_id stringlengths 64 64 | repository stringlengths 6 84 | name stringlengths 4 110 | content stringlengths 0 248k | license null | download_url stringlengths 89 454 | language stringclasses 7 values | comments stringlengths 0 74.6k | code stringlengths 0 248k |
|---|---|---|---|---|---|---|---|---|
2e9a986f5c44d891cc73cebd48b5a419d117c52cfd5d02c0b6bab1e3c9fbc471 | pflanze/chj-schemelib | usersyntax.scm |
;; --- |require| runtime macro ----
(##top-cte-add-macro!
##interaction-cte
'require
(##make-macro-descr
#t
-1
(lambda (stx)
;; do not eval at expansion time, because Gambit crashes when
;; doing nested compilation; instead usually require forms are
;; translated separately
(location-warn
(source-location stx)
"fall back to macro definition of require form, no compile-time definitions are supported")
(mod:require-expand stx))
#f))
;;; |RQ|
a require for user interaction that first clears what has been loaded
(##top-cte-add-macro!
##interaction-cte
'RQ
(##make-macro-descr
#t
-1
(lambda (stx)
(init-mod-loaded!)
(mod:require-expand stx))
#f))
| null | https://raw.githubusercontent.com/pflanze/chj-schemelib/59ff8476e39f207c2f1d807cfc9670581c8cedd3/mod/usersyntax.scm | scheme | --- |require| runtime macro ----
do not eval at expansion time, because Gambit crashes when
doing nested compilation; instead usually require forms are
translated separately
|RQ| |
(##top-cte-add-macro!
##interaction-cte
'require
(##make-macro-descr
#t
-1
(lambda (stx)
(location-warn
(source-location stx)
"fall back to macro definition of require form, no compile-time definitions are supported")
(mod:require-expand stx))
#f))
a require for user interaction that first clears what has been loaded
(##top-cte-add-macro!
##interaction-cte
'RQ
(##make-macro-descr
#t
-1
(lambda (stx)
(init-mod-loaded!)
(mod:require-expand stx))
#f))
|
1e2df78974bb816b216ea3fcf91ab195404139835c2c9ae45b109c78caea803f | NorfairKing/validity | Sequence.hs | # OPTIONS_GHC -fno - warn - orphans #
module Data.Validity.Sequence where
import Data.Foldable (toList)
import Data.Sequence (Seq)
import Data.Validity
-- | A 'Seq'uence of things is valid if all the elements are valid.
instance Validity v => Validity (Seq v) where
validate s = annotate (toList s) "Seq elements"
| null | https://raw.githubusercontent.com/NorfairKing/validity/1c3671a662673e21a1c5e8056eef5a7b0e8720ea/validity-containers/src/Data/Validity/Sequence.hs | haskell | | A 'Seq'uence of things is valid if all the elements are valid. | # OPTIONS_GHC -fno - warn - orphans #
module Data.Validity.Sequence where
import Data.Foldable (toList)
import Data.Sequence (Seq)
import Data.Validity
instance Validity v => Validity (Seq v) where
validate s = annotate (toList s) "Seq elements"
|
9fadd0fc0a3f1890305e427cac947389638f839f2e0ce57a6d74d768b4e392af | dgtized/shimmers | polygraph.cljc | (ns shimmers.model.polygraph
"a graph of points where each node is uniquely identified but also maps to an updatable position."
(:require
[loom.attr :as lga]
[loom.graph :as lg]
[thi.ng.geom.core :as g]
[thi.ng.geom.vector :as gv]))
(defn nodes->points [graph]
(->> graph
lg/nodes
(map (fn [node] [node (lga/attr graph node :pos)]))
(into {})))
FIXME : awful performance , makes creating a graph 2*N^2 , need spatial index or hashing
(defn point->node
[graph point]
(let [points (nodes->points graph)
tolerance 0.01]
(or (some (fn [[node pos]]
(when (< (g/dist-squared point pos) tolerance)
node))
points)
(count points))))
(defn add-edge [graph [p q]]
(let [a (point->node graph p)
b (point->node graph q)]
(-> graph
(lg/add-edges [a b (g/dist p q)])
(lga/add-attr a :pos p)
(lga/add-attr b :pos q))))
(defn edgegraph [edges]
(reduce add-edge (lg/weighted-graph) edges))
(comment
(edgegraph [[(gv/vec2 0 0) (gv/vec2 10 0)]
[(gv/vec2 10 0) (gv/vec2 0 10)]
[(gv/vec2 0 10) (gv/vec2 0 0)]])
(defn polygraph [_edges])
(defn pointgraph [_points]))
| null | https://raw.githubusercontent.com/dgtized/shimmers/822eeff9442365cb1731946f1bfa428c10269aea/src/shimmers/model/polygraph.cljc | clojure | (ns shimmers.model.polygraph
"a graph of points where each node is uniquely identified but also maps to an updatable position."
(:require
[loom.attr :as lga]
[loom.graph :as lg]
[thi.ng.geom.core :as g]
[thi.ng.geom.vector :as gv]))
(defn nodes->points [graph]
(->> graph
lg/nodes
(map (fn [node] [node (lga/attr graph node :pos)]))
(into {})))
FIXME : awful performance , makes creating a graph 2*N^2 , need spatial index or hashing
(defn point->node
[graph point]
(let [points (nodes->points graph)
tolerance 0.01]
(or (some (fn [[node pos]]
(when (< (g/dist-squared point pos) tolerance)
node))
points)
(count points))))
(defn add-edge [graph [p q]]
(let [a (point->node graph p)
b (point->node graph q)]
(-> graph
(lg/add-edges [a b (g/dist p q)])
(lga/add-attr a :pos p)
(lga/add-attr b :pos q))))
(defn edgegraph [edges]
(reduce add-edge (lg/weighted-graph) edges))
(comment
(edgegraph [[(gv/vec2 0 0) (gv/vec2 10 0)]
[(gv/vec2 10 0) (gv/vec2 0 10)]
[(gv/vec2 0 10) (gv/vec2 0 0)]])
(defn polygraph [_edges])
(defn pointgraph [_points]))
| |
e3ae6c99b0295724ce108d1fecc5297695d04024cd7f3514a10e1719eaff5ba1 | pirapira/bamboo | codegen_test.ml | open Syntax
open Codegen
The following two functions comes from
* -test
* which is under UNLICENSE
* -test
* which is under UNLICENSE
*)
let _ =
let dummy_cid_lookup (_ : string) = 3 in
let dummy_env = CodegenEnv.empty_env dummy_cid_lookup [] in
let dummy_l = LocationEnv.empty_env in
let _ = codegen_exp dummy_l dummy_env RightAligned (FalseExp, BoolType) in
let _ = codegen_exp dummy_l dummy_env RightAligned (TrueExp, BoolType) in
let _ = codegen_exp dummy_l dummy_env RightAligned (NotExp (TrueExp, BoolType), BoolType) in
let _ = codegen_exp dummy_l dummy_env RightAligned (NowExp, Uint256Type) in
Printf.printf "Finished codgen_test.\n"
| null | https://raw.githubusercontent.com/pirapira/bamboo/1cca98e0b6d2579fe32885e66aafd0f5e25d9eb5/src/codegen/codegen_test.ml | ocaml | open Syntax
open Codegen
The following two functions comes from
* -test
* which is under UNLICENSE
* -test
* which is under UNLICENSE
*)
let _ =
let dummy_cid_lookup (_ : string) = 3 in
let dummy_env = CodegenEnv.empty_env dummy_cid_lookup [] in
let dummy_l = LocationEnv.empty_env in
let _ = codegen_exp dummy_l dummy_env RightAligned (FalseExp, BoolType) in
let _ = codegen_exp dummy_l dummy_env RightAligned (TrueExp, BoolType) in
let _ = codegen_exp dummy_l dummy_env RightAligned (NotExp (TrueExp, BoolType), BoolType) in
let _ = codegen_exp dummy_l dummy_env RightAligned (NowExp, Uint256Type) in
Printf.printf "Finished codgen_test.\n"
| |
47cde3c63d148b92f4ea3ea811dfbc75a058c0dc799ce0b5b452dc054c2d9fc6 | r-willis/biten | peer_sup.erl | -module(peer_sup).
-behaviour(supervisor).
%% API
-export([start_link/0]).
%% Supervisor callbacks
-export([init/1]).
%% Helper macro for declaring children of supervisor
-define(CHILD(I, Type), {I, {I, start_link, []}, permanent, 5000, Type, [I]}).
-define(CHILD_T(I, Type), {I, {I, start_link, []}, temporary, 5000, Type, [I]}).
%% ===================================================================
%% API functions
%% ===================================================================
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
%% ===================================================================
%% Supervisor callbacks
%% ===================================================================
init([]) ->
{ok, {{simple_one_for_one, 0, 1}, % no restart, all childs are the same
[{peer, {peer, start_link, []},
temporary, brutal_kill, worker, [peer]}
] }}.
| null | https://raw.githubusercontent.com/r-willis/biten/75b13ea296992f8fa749646b9d7c15c5ef23d94d/apps/biten/src/peer_sup.erl | erlang | API
Supervisor callbacks
Helper macro for declaring children of supervisor
===================================================================
API functions
===================================================================
===================================================================
Supervisor callbacks
===================================================================
no restart, all childs are the same | -module(peer_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).
-define(CHILD(I, Type), {I, {I, start_link, []}, permanent, 5000, Type, [I]}).
-define(CHILD_T(I, Type), {I, {I, start_link, []}, temporary, 5000, Type, [I]}).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
init([]) ->
[{peer, {peer, start_link, []},
temporary, brutal_kill, worker, [peer]}
] }}.
|
c21d1196aecb417e819cae960cc9a254cc843a08fecaf9989625138cf0a905da | monstasat/chartjs-ocaml | chartjs.mli | open Js_of_ocaml
module Indexable : sig
type 'a t
* options also accept an array in which each item corresponds
to the element at the same index . Note that this method requires
to provide as many items as data , so , in most cases , using a function
is more appropriated if supported .
to the element at the same index. Note that this method requires
to provide as many items as data, so, in most cases, using a function
is more appropriated if supported. *)
val of_single : 'a -> 'a t Js.t
val of_js_array : 'a Js.js_array Js.t -> 'a t Js.t
val of_array : 'a array -> 'a t Js.t
val of_list : 'a list -> 'a t Js.t
val cast_single : 'a t Js.t -> 'a Js.opt
val cast_js_array : 'a t Js.t -> 'a Js.js_array Js.t Js.opt
end
module Scriptable : sig
type ('a, 'b) t
(** Scriptable options also accept a function which is called for each
of the underlying data values and that takes the unique argument
[context] representing contextual information. *)
val of_fun : ('a -> 'b) -> ('a, 'b) t Js.t
end
module Scriptable_indexable : sig
type ('a, 'b) t
val of_single : 'b -> ('a, 'b) t Js.t
val of_js_array : 'b Js.js_array Js.t -> ('a, 'b) t Js.t
val of_array : 'b array -> ('a, 'b) t Js.t
val of_list : 'b list -> ('a, 'b) t Js.t
val of_fun : ('a -> 'b) -> ('a, 'b) t Js.t
val cast_single : ('a, 'b) t Js.t -> 'b Js.opt
val cast_js_array : ('a, 'b) t Js.t -> 'b Js.js_array Js.t Js.opt
val cast_fun : ('a, 'b) t Js.t -> ('c, 'a -> 'b) Js.meth_callback Js.opt
end
module Line_cap : sig
type t
* @see < >
val butt : t Js.t
val round : t Js.t
val square : t Js.t
val of_string : string -> t Js.t
end
module Line_join : sig
type t
(** @see <-US/docs/Web/API/CanvasRenderingContext2D/lineJoin> *)
val round : t Js.t
val bevel : t Js.t
val miter : t Js.t
val of_string : string -> t Js.t
end
module Interaction_mode : sig
type t
(** When configuring interaction with the graph via hover or tooltips,
a number of different modes are available. *)
val point : t Js.t
(** Finds all of the items that intersect the point. *)
val nearest : t Js.t
(** Gets the items that are at the nearest distance to the point.
The nearest item is determined based on the distance to the center
of the chart item (point, bar). You can use the [axis] setting to define
which directions are used in distance calculation. If [intersect] is [true],
this is only triggered when the mouse position intersects an item
in the graph. This is very useful for combo charts where points are hidden
behind bars. *)
val index : t Js.t
* Finds item at the same index .
If the [ intersect ] setting is [ true ] , the first intersecting item is used
to determine the index in the data . If [ intersect ] is [ false ] ,
the nearest item in the x direction is used to determine the index .
To use index mode in a chart like the horizontal bar chart , where we search
along the y direction , you can use the [ axis ] setting introduced in v2.7.0 .
By setting this value to [ ' y ' ] on the y direction is used .
If the [intersect] setting is [true], the first intersecting item is used
to determine the index in the data. If [intersect] is [false],
the nearest item in the x direction is used to determine the index.
To use index mode in a chart like the horizontal bar chart, where we search
along the y direction, you can use the [axis] setting introduced in v2.7.0.
By setting this value to ['y'] on the y direction is used. *)
val dataset : t Js.t
* Finds items in the same dataset .
If the [ intersect ] setting is [ true ] , the first intersecting item is used
to determine the index in the data .
If [ intersect ] is [ false ] , the nearest item is used to determine the index .
If the [intersect] setting is [true], the first intersecting item is used
to determine the index in the data.
If [intersect] is [false], the nearest item is used to determine the index. *)
val x : t Js.t
(** Returns all items that would intersect based on the [X] coordinate
of the position only. Would be useful for a vertical cursor implementation.
Note that this only applies to cartesian charts. *)
val y : t Js.t
(** Returns all items that would intersect based on the [Y] coordinate
of the position. This would be useful for a horizontal cursor implementation.
Note that this only applies to cartesian charts. *)
val of_string : string -> t Js.t
end
module Point_style : sig
type t
val circle : t Js.t
val cross : t Js.t
val crossRot : t Js.t
val dash : t Js.t
val line : t Js.t
val rect : t Js.t
val rectRounded : t Js.t
val rectRot : t Js.t
val star : t Js.t
val triangle : t Js.t
val of_string : string -> t Js.t
val of_image : Dom_html.imageElement Js.t -> t Js.t
val of_video : Dom_html.videoElement Js.t -> t Js.t
val of_canvas : Dom_html.canvasElement Js.t -> t Js.t
val cast_string : t Js.t -> string Js.opt
val cast_image : t Js.t -> Dom_html.imageElement Js.t Js.opt
val cast_video : t Js.t -> Dom_html.videoElement Js.t Js.opt
val cast_canvas : t Js.t -> Dom_html.canvasElement Js.t Js.opt
end
module Easing : sig
type t
val linear : t Js.t
val easeInQuad : t Js.t
val easeOutQuad : t Js.t
val easeInOutQuad : t Js.t
val easeInCubic : t Js.t
val easeOutCubic : t Js.t
val easeInOutCubic : t Js.t
val easeInQuart : t Js.t
val easeOutQuart : t Js.t
val easeInOutQuart : t Js.t
val easeInQuint : t Js.t
val easeOutQuint : t Js.t
val easeInOutQuint : t Js.t
val easeInSine : t Js.t
val easeOutSine : t Js.t
val easeInOutSine : t Js.t
val easeInExpo : t Js.t
val easeOutExpo : t Js.t
val easeInOutExpo : t Js.t
val easeInCirc : t Js.t
val easeOutCirc : t Js.t
val easeInOutCirc : t Js.t
val easeInElastic : t Js.t
val easeOutElastic : t Js.t
val easeInOutElastic : t Js.t
val easeInBack : t Js.t
val easeOutBack : t Js.t
val easeInOutBack : t Js.t
val easeInBounce : t Js.t
val easeOutBounce : t Js.t
val easeInOutBounce : t Js.t
val of_string : string -> t Js.t
end
module Padding : sig
type t
(** If this value is a number, it is applied to all sides of the element
(left, top, right, bottom). If this value is an object, the [left]
property defines the left padding. Similarly the [right], [top] and
[bottom] properties can also be specified. *)
class type obj =
object
method top : int Js.optdef_prop
method right : int Js.optdef_prop
method bottom : int Js.optdef_prop
method left : int Js.optdef_prop
end
val make_object : ?top:int -> ?right:int -> ?bottom:int -> ?left:int -> unit -> t Js.t
val of_object : obj Js.t -> t Js.t
val of_int : int -> t Js.t
val cast_int : t Js.t -> int Js.opt
val cast_object : t Js.t -> obj Js.t Js.opt
end
module Color : sig
type t
* When supplying colors to Chart options , you can use a number of formats .
You can specify the color as a string in hexadecimal , RGB , or HSL notations .
If a color is needed , but not specified , Chart.js will use the global
default color . This color is stored at [ Chart.defaults.global.defaultColor ] .
It is initially set to [ ' rgba(0 , 0 , 0 , 0.1 ) ' ] .
You can also pass a [ CanvasGradient ] object .
You will need to create this before passing to the chart ,
but using it you can achieve some interesting effects .
You can specify the color as a string in hexadecimal, RGB, or HSL notations.
If a color is needed, but not specified, Chart.js will use the global
default color. This color is stored at [Chart.defaults.global.defaultColor].
It is initially set to ['rgba(0, 0, 0, 0.1)'].
You can also pass a [CanvasGradient] object.
You will need to create this before passing to the chart,
but using it you can achieve some interesting effects. *)
val of_string : string -> t Js.t
val of_canvas_gradient : Dom_html.canvasGradient Js.t -> t Js.t
val of_canvas_pattern : Dom_html.canvasPattern Js.t -> t Js.t
val cast_string : t Js.t -> string Js.opt
val cast_canvas_gradient : t Js.t -> Dom_html.canvasGradient Js.t Js.opt
val cast_canvas_pattern : t Js.t -> Dom_html.canvasPattern Js.t Js.opt
end
module Position : sig
type t
val left : t Js.t
val right : t Js.t
val top : t Js.t
val bottom : t Js.t
val of_string : string -> t Js.t
end
module Tooltip_position : sig
type t
val average : t
(** Will place the tooltip at the average position
of the items displayed in the tooltip. *)
val nearest : t
(** Will place the tooltip at the position of the element
closest to the event position. *)
val of_string : string -> t
end
module Line_height : sig
type t
(** @see <-US/docs/Web/CSS/line-height> *)
val of_string : string -> t Js.t
val of_float : float -> t Js.t
val cast_string : t Js.t -> string Js.opt
val cast_float : t Js.t -> float Js.opt
end
module Hover_axis : sig
type t
val x : t Js.t
val y : t Js.t
val xy : t Js.t
val of_string : string -> t Js.t
end
module Fill : sig
type t
val zero : t Js.t
val top : t Js.t
val bottom : t Js.t
val _true : t Js.t
val _false : t Js.t
val of_bool : bool -> t Js.t
val of_string : string -> t Js.t
val cast_bool : t Js.t -> bool Js.opt
val cast_string : t Js.t -> string Js.opt
end
module Time : sig
type t
val of_float_s : float -> t Js.t
val of_int_s : int -> t Js.t
val of_string : string -> t Js.t
val of_array : int array -> t Js.t
val of_js_array : int Js.js_array Js.t -> t Js.t
val of_date : Js.date Js.t -> t Js.t
val cast_float_s : t Js.t -> float Js.opt
val cast_string : t Js.t -> string Js.opt
val cast_js_array : t Js.t -> int Js.js_array Js.t Js.opt
val cast_date : t Js.t -> Js.date Js.t Js.opt
end
module Or_false : sig
type 'a t
val make : 'a -> 'a t Js.t
val _false : 'a t Js.t
end
type line_dash = float Js.js_array Js.t
(** @see <-US/docs/Web/API/CanvasRenderingContext2D/setLineDash> *)
type line_dash_offset = float
(** @see <-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset> *)
module Time_ticks_source : sig
type t
val auto : t Js.t
val data : t Js.t
val labels : t Js.t
val of_string : string -> t Js.t
end
module Time_distribution : sig
type t
val linear : t Js.t
(** Data points are spread according to their time (distances can vary). *)
val series : t Js.t
(** Data points are spread at the same distance from each other. *)
val of_string : string -> t Js.t
end
module Time_bounds : sig
type t
val data : t Js.t
(** Makes sure data are fully visible, labels outside are removed. *)
val ticks : t Js.t
(** Makes sure ticks are fully visible, data outside are truncated. *)
val of_string : string -> t Js.t
end
module Time_unit : sig
type t
val millisecond : t Js.t
val second : t Js.t
val minute : t Js.t
val hour : t Js.t
val day : t Js.t
val week : t Js.t
val month : t Js.t
val quarter : t Js.t
val year : t Js.t
val of_string : string -> t Js.t
end
module Interpolation_mode : sig
type t
val default : t Js.t
(** Default algorithm uses a custom weighted cubic interpolation,
which produces pleasant curves for all types of datasets. *)
val monotone : t Js.t
(** Monotone algorithm is more suited to [y = f(x)] datasets :
it preserves monotonicity (or piecewise monotonicity) of the dataset
being interpolated, and ensures local extremums (if any) stay at input
data points. *)
val of_string : string -> t Js.t
end
module Stepped_line : sig
type t
val _false : t Js.t
(** No Step Interpolation. *)
val _true : t Js.t
(** Step-before Interpolation (same as [before]). *)
val before : t Js.t
(** Step-before Interpolation. *)
val after : t Js.t
(** Step-after Interpolation. *)
val middle : t Js.t
(** Step-middle Interpolation. *)
val of_bool : bool -> t Js.t
val of_string : string -> t Js.t
end
module Line_fill : sig
type t
val relative : int -> t Js.t
val absolute : int -> t Js.t
val _false : t Js.t
val _true : t Js.t
(** Equivalent to [origin] *)
val start : t Js.t
val _end : t Js.t
val origin : t Js.t
val of_bool : bool -> t Js.t
val of_string : string -> t Js.t
end
module Pie_border_align : sig
type t
val center : t Js.t
(** The borders of arcs next to each other will overlap. *)
val inner : t Js.t
(** Guarantees that all the borders do not overlap. *)
end
module Axis_display : sig
type t
val auto : t Js.t
val cast_bool : t Js.t -> bool Js.opt
val is_auto : t Js.t -> bool
val of_bool : bool -> t Js.t
val of_string : string -> t Js.t
end
module Time_parser : sig
type t
val of_string : string -> t Js.t
(** A custom format to be used by Moment.js to parse the date. *)
val of_fun : ('a -> 'b Js.t) -> t Js.t
(** A function must return a Moment.js object given the appropriate data value. *)
val cast_string : t Js.t -> string Js.opt
val cast_fun : t Js.t -> ('a -> 'b Js.t) Js.callback Js.opt
end
module Bar_thickness : sig
type t
val flex : t Js.t
val of_int : int -> t Js.t
val of_float : float -> t Js.t
val is_flex : t Js.t -> bool
val cast_number : t Js.t -> Js.number Js.t Js.opt
end
type 'a tick_cb = ('a -> int -> 'a Js.js_array Js.t) Js.callback
type ('a, 'b, 'c) tooltip_cb =
('a, 'b -> 'c -> Js.js_string Js.t Indexable.t Js.t) Js.meth_callback Js.optdef
class type ['x, 'y] dataPoint =
object
method x : 'x Js.prop
method y : 'y Js.prop
end
class type ['t, 'y] dataPointT =
object
method t : 't Js.prop
method y : 'y Js.prop
end
class type ['x, 'y, 'r] dataPointR =
object
inherit ['x, 'y] dataPoint
method r : 'r Js.prop
end
val create_data_point : x:'a -> y:'b -> ('a, 'b) dataPoint Js.t
val create_data_point_t : t:'a -> y:'b -> ('a, 'b) dataPointT Js.t
val create_data_point_r : x:'a -> y:'b -> r:'c -> ('a, 'b, 'c) dataPointR Js.t
(** {1 Axes} *)
(** The minorTick configuration is nested under the ticks configuration
in the [minor] key. It defines options for the minor tick marks that are
generated by the axis. Omitted options are inherited from ticks
configuration. *)
class type minorTicks =
object
(** Returns the string representation of the tick value
as it should be displayed on the chart. *)
method callback : 'a tick_cb Js.prop
(** Font color for tick labels. *)
method fontColor : Color.t Js.t Js.optdef_prop
(** Font family for the tick labels, follows CSS font-family options. *)
method fontFamily : Js.js_string Js.t Js.optdef_prop
(** Font size for the tick labels. *)
method fontSize : int Js.optdef_prop
(** Font style for the tick labels, follows CSS font-style options
(i.e. normal, italic, oblique, initial, inherit). *)
method fontStyle : Js.js_string Js.t Js.optdef_prop
end
and majorTicks = minorTicks
(** The majorTick configuration is nested under the ticks configuration
in the [major] key. It defines options for the major tick marks that are
generated by the axis. Omitted options are inherited from ticks configuration.
These options are disabled by default. *)
(** The tick configuration is nested under the scale configuration
in the ticks key. It defines options for the tick marks that are
generated by the axis.*)
and ticks =
object
(** Returns the string representation of the tick value as
it should be displayed on the chart. *)
method callback : 'a tick_cb Js.prop
(** If [true], show tick marks. *)
method display : bool Js.t Js.prop
(** Font color for tick labels. *)
method fontColor : Color.t Js.t Js.optdef_prop
(** Font family for the tick labels, follows CSS font-family options. *)
method fontFamily : Js.js_string Js.t Js.optdef_prop
(** Font size for the tick labels. *)
method fontSize : int Js.optdef_prop
(** Font style for the tick labels, follows CSS font-style options
(i.e. normal, italic, oblique, initial, inherit). *)
method fontStyle : Js.js_string Js.t Js.optdef_prop
(** Reverses order of tick labels. *)
method reverse : bool Js.t Js.prop
(** Minor ticks configuration. Omitted options are inherited
from options above. *)
method minor : minorTicks Js.t
(** Major ticks configuration. Omitted options are inherited
from options above.*)
method major : majorTicks Js.t
end
and scaleLabel =
object
(** If true, display the axis title. *)
method display : bool Js.t Js.prop
(** The text for the title. (i.e. "# of People" or "Response Choices"). *)
method labelString : Js.js_string Js.t Js.prop
(** Height of an individual line of text. *)
method lineHeight : Line_height.t Js.t Js.prop
(** Font color for scale title. *)
method fontColor : Color.t Js.t Js.prop
(** Font family for the scale title, follows CSS font-family options. *)
method fontFamily : Js.js_string Js.t Js.prop
(** Font size for scale title. *)
method fontSize : int Js.prop
(** Font style for the scale title, follows CSS font-style options
(i.e. normal, italic, oblique, initial, inherit) *)
method fontStyle : Js.js_string Js.t Js.prop
(** Padding to apply around scale labels.
Only top and bottom are implemented. *)
method padding : Padding.t Js.t Js.prop
end
and gridLines =
object
(** If [false], do not display grid lines for this axis. *)
method display : bool Js.t Js.prop
(** If [true], gridlines are circular (on radar chart only). *)
method circular : bool Js.t Js.prop
* The color of the grid lines . If specified as an array ,
the first color applies to the first grid line , the second
to the second grid line and so on .
the first color applies to the first grid line, the second
to the second grid line and so on. *)
method color : Color.t Js.t Indexable.t Js.t Js.prop
(** Length and spacing of dashes on grid lines. *)
method borderDash : line_dash Js.prop
(** Offset for line dashes. *)
method borderDashOffset : line_dash_offset Js.prop
(** Stroke width of grid lines. *)
method lineWidth : int Indexable.t Js.t Js.prop
(** If true, draw border at the edge between the axis and the chart area. *)
method drawBorder : bool Js.t Js.prop
(** If true, draw lines on the chart area inside the axis lines.
This is useful when there are multiple axes and you need to
control which grid lines are drawn. *)
method drawOnChartArea : bool Js.t Js.prop
(** If true, draw lines beside the ticks in the axis area beside the chart. *)
method drawTicks : bool Js.t Js.prop
(** Length in pixels that the grid lines will draw into the axis area. *)
method tickMarkLength : int Js.prop
* Stroke width of the grid line for the first index ( index 0 ) .
method zeroLineWidth : int Js.prop
* Stroke color of the grid line for the first index ( index 0 ) .
method zeroLineColor : Color.t Js.t Js.prop
* Length and spacing of dashes of the grid line
for the first index ( index 0 ) .
for the first index (index 0). *)
method zeroLineBorderDash : line_dash Js.prop
* Offset for line dashes of the grid line for the first index ( index 0 ) .
method zeroLineBorderDashOffset : line_dash_offset Js.prop
(** If [true], grid lines will be shifted to be between labels.
This is set to true for a category scale in a bar chart by default. *)
method offsetGridLines : bool Js.t Js.prop
end
class type axis =
object
(** Type of scale being employed
Custom scales can be created and registered with a string key.
This allows changing the type of an axis for a chart. *)
method _type : Js.js_string Js.t Js.prop
* Controls the axis global visibility
( visible when [ true ] , hidden when [ false ] ) .
When display is [ ' auto ' ] , the axis is visible only
if at least one associated dataset is visible .
(visible when [true], hidden when [false]).
When display is ['auto'], the axis is visible only
if at least one associated dataset is visible. *)
method display : Axis_display.t Js.t Js.prop
(** The weight used to sort the axis.
Higher weights are further away from the chart area. *)
method weight : float Js.optdef_prop
(** Callback called before the update process starts. *)
method beforeUpdate : ('a Js.t -> unit) Js.callback Js.optdef_prop
(** Callback that runs before dimensions are set. *)
method beforeSetDimensions : ('a Js.t -> unit) Js.callback Js.optdef_prop
(** Callback that runs after dimensions are set. *)
method afterSetDimensions : ('a Js.t -> unit) Js.callback Js.optdef_prop
(** Callback that runs before data limits are determined. *)
method beforeDataLimits : ('a Js.t -> unit) Js.callback Js.optdef_prop
(** Callback that runs after data limits are determined. *)
method afterDataLimits : ('a Js.t -> unit) Js.callback Js.optdef_prop
(** Callback that runs before ticks are created. *)
method beforeBuildTicks : ('a Js.t -> unit) Js.callback Js.optdef_prop
(** Callback that runs after ticks are created. Useful for filtering ticks.
@return the filtered ticks. *)
method afterBuildTicks :
('a Js.t -> 'tick Js.js_array Js.t -> 'tick Js.js_array Js.t) Js.callback
Js.optdef_prop
(** Callback that runs before ticks are converted into strings. *)
method beforeTickToLabelConversion : ('a Js.t -> unit) Js.callback Js.optdef_prop
(** Callback that runs after ticks are converted into strings. *)
method afterTickToLabelConversion : ('a Js.t -> unit) Js.callback Js.optdef_prop
(** Callback that runs before tick rotation is determined. *)
method beforeCalculateTickRotation : ('a Js.t -> unit) Js.callback Js.optdef_prop
(** Callback that runs after tick rotation is determined. *)
method afterCalculateTickRotation : ('a Js.t -> unit) Js.callback Js.optdef_prop
(** Callback that runs before the scale fits to the canvas. *)
method beforeFit : ('a Js.t -> unit) Js.callback Js.optdef_prop
(** Callback that runs after the scale fits to the canvas. *)
method afterFit : ('a Js.t -> unit) Js.callback Js.optdef_prop
(** Callback that runs at the end of the update process. *)
method afterUpdate : ('a Js.t -> unit) Js.callback Js.optdef_prop
end
val empty_minor_ticks : unit -> minorTicks Js.t
val empty_major_ticks : unit -> majorTicks Js.t
val empty_ticks : unit -> ticks Js.t
val empty_scale_label : unit -> scaleLabel Js.t
val empty_grid_lines : unit -> gridLines Js.t
* { 2 Cartesian axes }
class type cartesianTicks =
object
inherit ticks
(** If [true], automatically calculates how many labels that
can be shown and hides labels accordingly. Turn it off to show all
labels no matter what. *)
method autoSkip : bool Js.t Js.prop
(** Padding between the ticks on the horizontal axis when autoSkip is
enabled. Note: Only applicable to horizontal scales. *)
method autoSkipPadding : int Js.prop
(** Distance in pixels to offset the label from the centre point of the
tick (in the y direction for the x axis, and the x direction for the
y axis). Note: this can cause labels at the edges to be cropped by the
edge of the canvas. *)
method labelOffset : int Js.prop
(** Maximum rotation for tick labels when rotating to condense labels.
Note: Rotation doesn't occur until necessary.
Note: Only applicable to horizontal scales. *)
method maxRotation : int Js.prop
(** Minimum rotation for tick labels.
Note: Only applicable to horizontal scales. *)
method minRotation : int Js.prop
(** Flips tick labels around axis, displaying the labels inside the chart
instead of outside. Note: Only applicable to vertical scales. *)
method mirror : bool Js.prop
(** Padding between the tick label and the axis. When set on a vertical axis,
this applies in the horizontal (X) direction. When set on a horizontal
axis, this applies in the vertical (Y) direction. *)
method padding : int Js.prop
end
class type cartesianAxis =
object
inherit axis
(** Position of the axis in the chart.
Possible values are: ['top'], ['left'], ['bottom'], ['right'] *)
method position : Position.t Js.t Js.prop
(** If [true], extra space is added to the both edges and the axis
is scaled to fit into the chart area. This is set to true for a
category scale in a bar chart by default. *)
method offset : bool Js.t Js.prop
(** The ID is used to link datasets and scale axes together. *)
method id : Js.js_string Js.t Js.prop
(** Grid line configuration. *)
method gridLines : gridLines Js.t Js.prop
(** Scale title configuration. *)
method scaleLabel : scaleLabel Js.t Js.prop
(** Ticks configuration. *)
method _ticks : cartesianTicks Js.t Js.prop
end
val coerce_cartesian_axis : #cartesianAxis Js.t -> cartesianAxis Js.t
val empty_cartesian_axis : unit -> cartesianAxis Js.t
* { 3 Category axis }
class type categoryTicks =
object
inherit cartesianTicks
(** An array of labels to display. *)
method labels : Js.js_string Js.t Js.optdef_prop
(** The minimum item to display. *)
method min : Js.js_string Js.t Js.optdef Js.prop
(** The maximum item to display. *)
method max : Js.js_string Js.t Js.optdef Js.prop
end
class type categoryAxis =
object
inherit cartesianAxis
method ticks : categoryTicks Js.t Js.prop
end
val empty_category_ticks : unit -> categoryTicks Js.t
val empty_category_axis : unit -> categoryAxis Js.t
* { 3 Linear axis }
class type linearTicks =
object
inherit cartesianTicks
(** If [true], scale will include 0 if it is not already included. *)
method beginAtZero : bool Js.t Js.optdef_prop
(** User defined minimum number for the scale,
overrides minimum value from data. *)
method min : float Js.optdef Js.prop
(** User defined maximum number for the scale,
overrides maximum value from data. *)
method max : float Js.optdef Js.prop
(** Maximum number of ticks and gridlines to show. *)
method maxTicksLimit : int Js.prop
(** If defined and stepSize is not specified,
the step size will be rounded to this many decimal places. *)
method precision : int Js.optdef_prop
(** User defined fixed step size for the scale. *)
method stepSize : int Js.optdef_prop
(** Adjustment used when calculating the maximum data value. *)
method suggestedMax : float Js.optdef Js.prop
(** Adjustment used when calculating the minimum data value. *)
method suggestedMin : float Js.optdef Js.prop
end
class type linearAxis =
object
inherit cartesianAxis
method ticks : linearTicks Js.t Js.prop
end
val empty_linear_ticks : unit -> linearTicks Js.t
val empty_linear_axis : unit -> linearAxis Js.t
* { 3 Logarithmic axis }
class type logarithmicTicks =
object
inherit cartesianTicks
(** User defined minimum number for the scale,
overrides minimum value from data. *)
method min : float Js.optdef Js.prop
(** User defined maximum number for the scale,
overrides maximum value from data. *)
method max : float Js.optdef Js.prop
end
class type logarithmicAxis =
object
inherit cartesianAxis
method ticks : logarithmicTicks Js.t Js.prop
end
val empty_logarithmic_ticks : unit -> logarithmicTicks Js.t
val empty_logarithmic_axis : unit -> logarithmicAxis Js.t
* { 3 Time axis }
(** The following display formats are used to configure
how different time units are formed into strings for
the axis tick marks. *)
class type timeDisplayFormats =
object
method millisecond : Js.js_string Js.t Js.prop
method second : Js.js_string Js.t Js.prop
method minute : Js.js_string Js.t Js.prop
method hour : Js.js_string Js.t Js.prop
method day : Js.js_string Js.t Js.prop
method week : Js.js_string Js.t Js.prop
method month : Js.js_string Js.t Js.prop
method quarter : Js.js_string Js.t Js.prop
method year : Js.js_string Js.t Js.prop
end
class type timeTicks =
object
inherit cartesianTicks
(** How ticks are generated.
[auto]: generates "optimal" ticks based on scale size and time options
[data]: generates ticks from data (including labels from data objects)
[labels]: generates ticks from user given data.labels values ONLY *)
method source : Time_ticks_source.t Js.t Js.prop
end
class type timeOptions =
object
(** Sets how different time units are displayed. *)
method displayFormats : timeDisplayFormats Js.t Js.optdef_prop
* If [ true ] and the unit is set to ' week ' , then the first day
of the week will be Monday . Otherwise , it will be Sunday .
of the week will be Monday. Otherwise, it will be Sunday. *)
method isoWeekday : bool Js.t Js.prop
(** If defined, this will override the data maximum *)
method max : Time.t Js.t Js.optdef_prop
(** If defined, this will override the data minimum *)
method min : Time.t Js.t Js.optdef_prop
(** Custom parser for dates. *)
method _parser : Time_parser.t Js.t Js.optdef_prop
(** If defined, dates will be rounded to the start of this unit. *)
method round : Time_unit.t Js.t Or_false.t Js.t Js.prop
(** The moment js format string to use for the tooltip. *)
method tooltipFormat : Js.js_string Js.t Js.optdef_prop
(** If defined, will force the unit to be a certain type. *)
method unit : Time_unit.t Js.t Or_false.t Js.t Js.prop
(** The number of units between grid lines. *)
method stepSize : int Js.prop
(** The minimum display format to be used for a time unit. *)
method minUnit : Time_unit.t Js.t Js.prop
end
class type timeAxis =
object
inherit cartesianAxis
method ticks : timeTicks Js.t Js.prop
method time : timeOptions Js.t Js.prop
(** The distribution property controls the data distribution along the scale:
[linear]: data are spread according to their time (distances can vary)
[series]: data are spread at the same distance from each other *)
method distribution : Time_distribution.t Js.t Js.prop
* The bounds property controls the scale boundary strategy
( bypassed by [ ] time options ) .
[ data ] : makes sure data are fully visible , labels outside are removed
[ ticks ] : makes sure ticks are fully visible , data outside are truncated
(bypassed by [min]/[max] time options).
[data]: makes sure data are fully visible, labels outside are removed
[ticks]: makes sure ticks are fully visible, data outside are truncated *)
method bounds : Time_bounds.t Js.t Js.prop
end
val empty_time_display_formats : unit -> timeDisplayFormats Js.t
val empty_time_ticks : unit -> timeTicks Js.t
val empty_time_options : unit -> timeOptions Js.t
val empty_time_axis : unit -> timeAxis Js.t
class type dataset =
object
method _type : Js.js_string Js.t Js.optdef_prop
method label : Js.js_string Js.t Js.prop
method hidden : bool Js.t Js.optdef_prop
end
val coerce_dataset : #dataset Js.t -> dataset Js.t
class type data =
object
method datasets : #dataset Js.t Js.js_array Js.t Js.prop
method labels : 'a Js.js_array Js.t Js.optdef_prop
method xLabels : 'a Js.js_array Js.t Js.optdef_prop
method yLabels : 'a Js.js_array Js.t Js.optdef_prop
end
val empty_data : unit -> data Js.t
(** {1 Chart configuration} *)
class type updateConfig =
object
method duration : int Js.optdef_prop
method _lazy : bool Js.t Js.optdef_prop
method easing : Easing.t Js.optdef_prop
end
(** {2 Animation} *)
class type animationItem =
object
(** Chart object. *)
method chart : chart Js.t Js.readonly_prop
(** Current Animation frame number. *)
method currentStep : float Js.readonly_prop
(** Number of animation frames. *)
method numSteps : float Js.readonly_prop
(** Function that renders the chart. *)
method render : chart Js.t -> animationItem Js.t -> unit Js.meth
(** User callback. *)
method onAnimationProgress : animationItem Js.t -> unit Js.meth
(** User callback. *)
method onAnimationComplete : animationItem Js.t -> unit Js.meth
end
and animation =
object
(** The number of milliseconds an animation takes. *)
method duration : int Js.prop
(** Easing function to use. *)
method easing : Easing.t Js.prop
(** Callback called on each step of an animation. *)
method onProgress : (animationItem Js.t -> unit) Js.callback Js.opt Js.prop
(** Callback called at the end of an animation. *)
method onComplete : (animationItem Js.t -> unit) Js.callback Js.opt Js.prop
end
* { 2 Layout }
and layout =
object
(** The padding to add inside the chart. *)
method padding : Padding.t Js.prop
FIXME this interface differs between and other chart types
(** {2 Legend} *)
and legendItem =
object
(** Label that will be displayed. *)
method text : Js.js_string Js.t Js.prop
FIXME seems it can be Indexable & Scriptable dependent on chart type
(** Fill style of the legend box. *)
method fillStyle : Color.t Js.t Js.prop
(** If [true], this item represents a hidden dataset.
Label will be rendered with a strike-through effect. *)
method hidden : bool Js.t Js.prop
(** For box border. *)
method lineCap : Line_cap.t Js.t Js.optdef_prop
(** For box border. *)
method lineDash : line_dash Js.optdef_prop
(** For box border. *)
method lineDashOffset : line_dash_offset Js.optdef_prop
(** For box border. *)
method lineJoin : Line_join.t Js.t Js.optdef_prop
(** Width of box border. *)
method lineWidth : int Js.prop
(** Stroke style of the legend box. *)
method strokeStyle : Color.t Js.t Js.prop
* Point style of the legend box ( only used if usePointStyle is true )
method pointStyle : Point_style.t Js.t Js.optdef_prop
method datasetIndex : int Js.prop
end
and legendLabels =
object ('self)
(** Width of coloured box. *)
method boxWidth : int Js.prop
(** Font size of text. *)
method fontSize : int Js.optdef_prop
(** Font style of text. *)
method fontStyle : Js.js_string Js.t Js.optdef_prop
(** Color of text. *)
method fontColor : Color.t Js.t Js.optdef_prop
(** Font family of legend text. *)
method fontFamily : Js.js_string Js.t Js.optdef_prop
(** Padding between rows of colored boxes. *)
method padding : int Js.prop
(** Generates legend items for each thing in the legend.
Default implementation returns the text + styling for the color box. *)
method generateLabels :
(chart Js.t -> legendItem Js.t Js.js_array Js.t) Js.callback Js.prop
* Filters legend items out of the legend . Receives 2 parameters ,
a Legend Item and the chart data .
a Legend Item and the chart data. *)
method filter :
('self, legendItem Js.t -> data Js.t -> bool Js.t) Js.meth_callback Js.optdef_prop
* Label style will match corresponding point style
( size is based on fontSize , boxWidth is not used in this case ) .
(size is based on fontSize, boxWidth is not used in this case). *)
method usePointStyle : bool Js.t Js.optdef_prop
end
and legend =
object
(** Is the legend shown. *)
method display : bool Js.t Js.prop
(** Position of the legend. *)
method position : Position.t Js.t Js.prop
* Marks that this box should take the full width of the canvas
( pushing down other boxes ) . This is unlikely to need to be changed
in day - to - day use .
(pushing down other boxes). This is unlikely to need to be changed
in day-to-day use. *)
method fullWidth : bool Js.t Js.prop
(** A callback that is called when a click event is
registered on a label item *)
method onClick :
(chart, Dom_html.event Js.t -> legendItem Js.t -> unit) Js.meth_callback
Js.optdef_prop
(** A callback that is called when a 'mousemove' event is
registered on top of a label item *)
method onHover :
(chart, Dom_html.event Js.t -> legendItem Js.t -> unit) Js.meth_callback
Js.optdef_prop
method onLeave :
(chart, Dom_html.event Js.t -> legendItem Js.t -> unit) Js.meth_callback
Js.optdef_prop
(** Legend will show datasets in reverse order. *)
method reverse : bool Js.t Js.prop
(** Legend label configuration. *)
method labels : legendLabels Js.t Js.prop
end
* { 2 Title }
and title =
object
(** Is the title shown. *)
method display : bool Js.t Js.prop
(** Position of title. *)
method position : Position.t Js.t Js.prop
(** Font size. *)
method fontSize : int Js.optdef_prop
(** Font family for the title text. *)
method fontFamily : Js.js_string Js.t Js.optdef_prop
(** Font color. *)
method fontColor : Js.js_string Js.t Js.optdef_prop
(** Font style. *)
method fontStyle : Js.js_string Js.t Js.optdef_prop
method fullWidth : bool Js.t Js.prop
(** Number of pixels to add above and below the title text. *)
method padding : int Js.prop
(** Height of an individual line of text. *)
method lineHeight : Line_height.t Js.t Js.optdef_prop
(** Title text to display. If specified as an array,
text is rendered on multiple lines. *)
method text : Js.js_string Js.t Indexable.t Js.t Js.prop
end
* { 2 Tooltip }
and tooltipItem =
object
(** Label for the tooltip. *)
method label : Js.js_string Js.t Js.readonly_prop
(** Value for the tooltip. *)
method value : Js.js_string Js.t Js.readonly_prop
(** Index of the dataset the item comes from. *)
method datasetIndex : int Js.readonly_prop
(** Index of this data item in the dataset. *)
method index : int Js.readonly_prop
(** X position of matching point. *)
method x : float Js.readonly_prop
(** Y position of matching point. *)
method y : float Js.readonly_prop
end
and tooltipBodyLines =
object
method before : Js.js_string Js.t Js.js_array Js.t Js.readonly_prop
method lines : Js.js_string Js.t Js.js_array Js.t Js.readonly_prop
method after : Js.js_string Js.t Js.js_array Js.t Js.readonly_prop
end
and tooltipModel =
object
(** The items that we are rendering in the tooltip. *)
method dataPoints : tooltipItem Js.t Js.js_array Js.t Js.readonly_prop
(** Positioning. *)
method xPadding : int Js.readonly_prop
method yPadding : int Js.readonly_prop
method xAlign : Js.js_string Js.t Js.readonly_prop
method yAlign : Js.js_string Js.t Js.readonly_prop
(** X and Y readonly_properties are the top left of the tooltip. *)
method x : float Js.readonly_prop
method y : float Js.readonly_prop
method width : float Js.readonly_prop
method height : float Js.readonly_prop
(** Where the tooltip points to. *)
method caretX : int Js.readonly_prop
method caretY : int Js.readonly_prop
* Body .
The body lines that need to be rendered .
Each object contains 3 parameters .
[ before ] - lines of text before the line with the color square
[ lines ] - lines of text to render as the main item with color square
[ after ] - lines of text to render after the main lines .
The body lines that need to be rendered.
Each object contains 3 parameters.
[before] - lines of text before the line with the color square
[lines] - lines of text to render as the main item with color square
[after] - lines of text to render after the main lines. *)
method body : tooltipBodyLines Js.t Js.readonly_prop
method beforeBody : Js.js_string Js.t Js.js_array Js.t Js.readonly_prop
method afterBody : Js.js_string Js.t Js.js_array Js.t Js.readonly_prop
method bodyFontColor : Color.t Js.t Js.readonly_prop
method __bodyFontFamily : Js.js_string Js.t Js.readonly_prop
method __bodyFontStyle : Js.js_string Js.t Js.readonly_prop
method __bodyAlign : Js.js_string Js.t Js.readonly_prop
method bodyFontSize : int Js.readonly_prop
method bodySpacing : int Js.readonly_prop
(** Title. Lines of text that form the title. *)
method title : Js.js_string Js.t Indexable.t Js.readonly_prop
method titleFontColor : Color.t Js.t Js.readonly_prop
method __titleFontFamily : Js.js_string Js.t Js.readonly_prop
method __titleFontStyle : Js.js_string Js.t Js.readonly_prop
method titleFontSize : int Js.readonly_prop
method __titleAlign : Js.js_string Js.t Js.readonly_prop
method titleSpacing : int Js.readonly_prop
method titleMarginBottom : int Js.readonly_prop
(** Footer. Lines of text that form the footer. *)
method footer : Js.js_string Js.t Indexable.t Js.readonly_prop
method footerFontColor : Color.t Js.t Js.readonly_prop
method __footerFontFamily : Js.js_string Js.t Js.readonly_prop
method __footerFontStyle : Js.js_string Js.t Js.readonly_prop
method footerFontSize : int Js.readonly_prop
method __footerAlign : Js.js_string Js.t Js.readonly_prop
method footerSpacing : int Js.readonly_prop
method footerMarginTop : int Js.readonly_prop
(** Appearance. *)
method caretSize : int Js.readonly_prop
method caretPadding : int Js.readonly_prop
method cornerRadius : int Js.readonly_prop
method backgroundColor : Color.t Js.t Js.readonly_prop
(** Colors to render for each item in body. This is the color of the
squares in the tooltip. *)
method labelColors : Color.t Js.t Js.js_array Js.t Js.readonly_prop
method labelTextColors : Color.t Js.t Js.js_array Js.t Js.readonly_prop
* Zero opacity is a hidden tooltip .
method opacity : float Js.readonly_prop
method legendColorBackground : Color.t Js.t Js.readonly_prop
method displayColors : bool Js.t Js.readonly_prop
method borderColor : Color.t Js.t Js.readonly_prop
method borderWidth : int Js.readonly_prop
end
and tooltipCallbacks =
object
(** Returns the text to render before the title. *)
method beforeTitle :
(tooltip Js.t, tooltipItem Js.js_array Js.t, data Js.t) tooltip_cb Js.prop
(** Returns the text to render as the title of the tooltip. *)
method title :
(tooltip Js.t, tooltipItem Js.js_array Js.t, data Js.t) tooltip_cb Js.prop
(** Returns the text to render after the title. *)
method afterTitle :
(tooltip Js.t, tooltipItem Js.js_array Js.t, data Js.t) tooltip_cb Js.prop
(** Returns the text to render before the body section. *)
method beforeBody :
(tooltip Js.t, tooltipItem Js.js_array Js.t, data Js.t) tooltip_cb Js.prop
(** Returns the text to render before an individual label.
This will be called for each item in the tooltip. *)
method beforeLabel : (tooltip Js.t, tooltipItem Js.t, data Js.t) tooltip_cb Js.prop
(** Returns the text to render for an individual item in the tooltip. *)
method label : (tooltip Js.t, tooltipItem Js.t, data Js.t) tooltip_cb Js.prop
(** Returns the colors to render for the tooltip item. *)
method labelColor : (tooltip Js.t, tooltipItem Js.t, chart Js.t) tooltip_cb Js.prop
(** Returns the colors for the text of the label for the tooltip item. *)
method labelTextColor :
(tooltip Js.t, tooltipItem Js.t, chart Js.t) tooltip_cb Js.prop
(** Returns text to render after an individual label. *)
method afterLabel : (tooltip Js.t, tooltipItem Js.t, data Js.t) tooltip_cb Js.prop
(** Returns text to render after the body section. *)
method afterBody :
(tooltip Js.t, tooltipItem Js.t Js.js_array Js.t, data Js.t) tooltip_cb Js.prop
(** Returns text to render before the footer section. *)
method beforeFooter :
(tooltip Js.t, tooltipItem Js.js_array Js.t, data Js.t) tooltip_cb Js.prop
(** Returns text to render as the footer of the tooltip. *)
method footer :
(tooltip Js.t, tooltipItem Js.js_array Js.t, data Js.t) tooltip_cb Js.prop
(** Text to render after the footer section. *)
method afterFooter :
(tooltip Js.t, tooltipItem Js.js_array Js.t, data Js.t) tooltip_cb Js.prop
end
and tooltip =
object ('self)
(** Are on-canvas tooltips enabled. *)
method enabled : bool Js.t Js.prop
(** Custom tooltip callback. *)
method custom : (tooltipModel Js.t -> unit) Js.callback Js.opt Js.prop
(** Sets which elements appear in the tooltip. *)
method mode : Interaction_mode.t Js.t Js.prop
(** If [true], the tooltip mode applies only when the mouse position
intersects with an element. If [false], the mode will be applied
at all times. *)
method intersect : bool Js.t Js.prop
(** Defines which directions are used in calculating distances.
Defaults to [x] for index mode and [xy] in [dataset] and [nearest]
modes. *)
method axis : Hover_axis.t Js.t Js.prop
(** The mode for positioning the tooltip. *)
method position : Tooltip_position.t Js.prop
(** Callbacks. *)
method callbacks : tooltipCallbacks Js.t Js.prop
(** Sort tooltip items. *)
method itemSort :
('self, tooltipItem Js.t -> tooltipItem Js.t -> data Js.t -> int) Js.meth_callback
Js.optdef_prop
(** Filter tooltip items. *)
method filter :
('self, tooltipItem Js.t -> data Js.t -> bool Js.t) Js.meth_callback Js.optdef_prop
(** Background color of the tooltip. *)
method backgroundColor : Color.t Js.t Js.prop
(** Title font. *)
method titleFontFamily : Js.js_string Js.t Js.optdef_prop
(** Title font size. *)
method titleFontSize : int Js.optdef_prop
(** Title font style *)
method titleFontStyle : Js.js_string Js.t Js.optdef_prop
(** Title font color *)
method titleFontColor : Color.t Js.t Js.optdef_prop
(** Spacing to add to top and bottom of each title line. *)
method titleSpacing : int Js.prop
(** Margin to add on bottom of title section. *)
method titleMarginBottom : int Js.prop
(** Body line font. *)
method bodyFontFamily : Js.js_string Js.t Js.optdef_prop
(** Body font size. *)
method bodyFontSize : int Js.optdef_prop
(** Body font style. *)
method bodyFontStyle : Js.js_string Js.t Js.optdef_prop
(** Body font color. *)
method bodyFontColor : Color.t Js.t Js.optdef_prop
(** Spacing to add to top and bottom of each tooltip item. *)
method bodySpacing : int Js.prop
(** Footer font. *)
method footerFontFamily : Js.js_string Js.t Js.optdef_prop
(** Footer font size. *)
method footerFontSize : int Js.optdef_prop
(** Footer font style. *)
method footerFontStyle : Js.js_string Js.t Js.optdef_prop
(** Footer font color. *)
method footerFontColor : Color.t Js.t Js.optdef_prop
(** Spacing to add to top and bottom of each footer line. *)
method footerSpacing : int Js.prop
(** Margin to add before drawing the footer. *)
method footerMarginTop : int Js.prop
(** Padding to add on left and right of tooltip. *)
method xPadding : int Js.prop
(** Padding to add on top and bottom of tooltip. *)
method yPadding : int Js.prop
(** Extra distance to move the end of the tooltip arrow
away from the tooltip point. *)
method caretPadding : int Js.prop
* Size , in px , of the tooltip arrow .
method caretSize : int Js.prop
(** Radius of tooltip corner curves. *)
method cornerRadius : int Js.prop
(** Color to draw behind the colored boxes when multiple
items are in the tooltip. *)
method multyKeyBackground : Color.t Js.t Js.prop
(** If [true], color boxes are shown in the tooltip. *)
method displayColors : bool Js.t Js.prop
(** Color of the border. *)
method borderColor : Color.t Js.t Js.prop
(** Size of the border. *)
method borderWidth : int Js.prop
end
* { 2 Interactions }
and hover =
object
(** Sets which elements appear in the tooltip. *)
method mode : Interaction_mode.t Js.t Js.prop
(** If true, the hover mode only applies when the mouse
position intersects an item on the chart. *)
method intersect : bool Js.t Js.prop
(** Defines which directions are used in calculating distances.
Defaults to [x] for index mode and [xy] in [dataset] and [nearest]
modes. *)
method axis : Hover_axis.t Js.t Js.prop
(** Duration in milliseconds it takes to animate hover style changes. *)
method animationDuration : int Js.prop
end
* { 2 Elements }
and pointElement =
object
(** Point radius. *)
method radius : int Js.prop
(** Point style. *)
method pointStyle : Point_style.t Js.t Js.prop
(** Point rotation (in degrees). *)
method rotation : int Js.optdef_prop
(** Point fill color. *)
method backgroundColor : Color.t Js.t Js.prop
(** Point stroke width. *)
method borderWidth : int Js.prop
(** Point stroke color. *)
method borderColor : Color.t Js.t Js.prop
(** Extra radius added to point radius for hit detection. *)
method hitRadius : int Js.prop
(** Point radius when hovered. *)
method hoverRadius : int Js.prop
(** Stroke width when hovered. *)
method hoverBorderWidth : int Js.prop
end
and lineElement =
object
* curve tension ( 0 for no curves ) .
method tension : float Js.prop
(** Line fill color. *)
method backgroundColor : Color.t Js.t Js.prop
(** Line stroke width. *)
method borderWidth : int Js.prop
(** Line stroke color. *)
method borderColor : Color.t Js.t Js.prop
(** Line cap style. *)
method borderCapStyle : Line_cap.t Js.t Js.prop
(** Line dash. *)
method borderDash : line_dash Js.prop
(** Line dash offset. *)
method borderDashOffset : line_dash_offset Js.prop
(** Line join style. *)
method borderJoinStyle : Line_join.t Js.t Js.prop
* [ true ] to keep control inside the chart ,
[ false ] for no restriction .
[false] for no restriction.*)
method capBezierPoints : bool Js.t Js.prop
(** Fill location. *)
method fill : Fill.t Js.t Js.prop
(** [true] to show the line as a stepped line (tension will be ignored). *)
method stepped : bool Js.t Js.optdef_prop
end
and rectangleElement =
object
(** Bar fill color. *)
method backgroundColor : Js.js_string Js.prop
(** Bar stroke width. *)
method borderWidth : int Js.prop
(** Bar stroke color. *)
method borderColor : Color.t Js.t Js.prop
(** Skipped (excluded) border: 'bottom', 'left', 'top' or 'right'. *)
method borderSkipped : Position.t Js.t Js.prop
end
and arcElement =
object
(** Arc fill color. *)
method backgroundColor : Color.t Js.t Js.prop
(** Arc stroke alignment. *)
method borderAlign : Js.js_string Js.t Js.prop
(** Arc stroke color. *)
method borderColor : Color.t Js.t Js.prop
(** Arc stroke width. *)
method borderWidth : int Js.prop
end
and elements =
object
(** Point elements are used to represent the points
in a line chart or a bubble chart. *)
method point : pointElement Js.t Js.prop
(** Line elements are used to represent the line in a line chart. *)
method line : lineElement Js.t Js.prop
(** Rectangle elements are used to represent the bars in a bar chart. *)
method rectangle : rectangleElement Js.t Js.prop
(** Arcs are used in the polar area, doughnut and pie charts. *)
method arc : arcElement Js.t Js.prop
end
* { 2 Options }
and chartSize =
object
method width : int Js.readonly_prop
method height : int Js.readonly_prop
end
* { 2 Chart }
(** The configuration is used to change how the chart behaves.
There are properties to control styling, fonts, the legend, etc. *)
and chartOptions =
object
* Chart.js animates charts out of the box .
A number of options are provided to configure how the animation
looks and how long it takes .
A number of options are provided to configure how the animation
looks and how long it takes. *)
method _animation : animation Js.t Js.prop
(** Layout configurations. *)
method layout : layout Js.t Js.prop
(** The chart legend displays data about the datasets
that are appearing on the chart. *)
method legend : legend Js.t Js.prop
(** The chart title defines text to draw at the top of the chart. *)
method title : title Js.t Js.prop
method hover : hover Js.t Js.prop
method tooltips : tooltip Js.t Js.prop
* While chart types provide settings to configure the styling
of each dataset , you sometimes want to style all datasets the same way .
A common example would be to stroke all of the bars in a bar chart with
the same colour but change the fill per dataset .
Options can be configured for four different types of elements : arc , lines ,
points , and rectangles . When set , these options apply to all objects
of that type unless specifically overridden by the configuration attached
to a dataset .
of each dataset, you sometimes want to style all datasets the same way.
A common example would be to stroke all of the bars in a bar chart with
the same colour but change the fill per dataset.
Options can be configured for four different types of elements: arc, lines,
points, and rectangles. When set, these options apply to all objects
of that type unless specifically overridden by the configuration attached
to a dataset. *)
method elements : elements Js.t Js.prop
(** Plugins are the most efficient way to customize or change the default
behavior of a chart. This option allows to define plugins directly in
the chart [plugins] config (a.k.a. inline plugins). *)
method plugins : 'a Js.t Js.prop
(** Sometimes you need a very complex legend. In these cases, it makes sense
to generate an HTML legend. Charts provide a generateLegend() method on their
prototype that returns an HTML string for the legend.
NOTE [legendCallback] is not called automatically and you must call
[generateLegend] yourself in code when creating a legend using this method. *)
method legendCallback : (chart Js.t -> Js.js_string Js.t) Js.callback Js.optdef_prop
(** Resizes the chart canvas when its container does. *)
method responsive : bool Js.t Js.prop
(** Duration in milliseconds it takes to animate
to new size after a resize event. *)
method responsiveAnimationDuration : int Js.prop
(** Maintain the original canvas aspect ratio (width / height) when resizing. *)
method maintainAspectRatio : bool Js.t Js.prop
* Canvas aspect ratio ( i.e. width / height , a value of 1
representing a square canvas ) . Note that this option is
ignored if the height is explicitly defined either as
attribute or via the style .
representing a square canvas). Note that this option is
ignored if the height is explicitly defined either as
attribute or via the style. *)
method aspectRatio : float Js.optdef_prop
* Called when a resize occurs . Gets passed two arguments :
the chart instance and the new size .
the chart instance and the new size. *)
method onResize :
(chart Js.t -> chartSize Js.t -> unit) Js.callback Js.opt Js.optdef_prop
(** Override the window's default devicePixelRatio. *)
method devicePixelRatio : float Js.optdef_prop
(** The events option defines the browser events that
the chart should listen to for tooltips and hovering. *)
method events : Js.js_string Js.t Js.js_array Js.t Js.prop
(** Called when any of the events fire.
Called in the context of the chart and passed the event
and an array of active elements (bars, points, etc). *)
method onHover :
( chart Js.t
, Dom_html.event Js.t -> 'a Js.t Js.js_array Js.t -> unit )
Js.meth_callback
Js.opt
Js.optdef_prop
(** Called if the event is of type 'mouseup' or 'click'.
Called in the context of the chart and passed the event
and an array of active elements. *)
method onClick :
( chart Js.t
, Dom_html.event Js.t -> 'a Js.t Js.js_array Js.t -> unit )
Js.meth_callback
Js.opt
Js.optdef_prop
end
and chartConfig =
object
method data : data Js.t Js.prop
method options : chartOptions Js.t Js.prop
method _type : Js.js_string Js.t Js.prop
end
and chart =
object ('self)
method id : int Js.readonly_prop
method height : int Js.readonly_prop
method width : int Js.readonly_prop
method offsetX : int Js.readonly_prop
method offsetY : int Js.readonly_prop
method borderWidth : int Js.readonly_prop
method animating : bool Js.t Js.readonly_prop
method aspectRatio : float Js.readonly_prop
method canvas : Dom_html.canvasElement Js.t Js.readonly_prop
method ctx : Dom_html.canvasRenderingContext2D Js.t Js.readonly_prop
method data : data Js.t Js.prop
method _options : chartOptions Js.t Js.prop
method _config : chartConfig Js.t Js.prop
(** {2 Chart API}*)
* Use this to destroy any chart instances that are created .
This will clean up any references stored to the chart object within Chart.js ,
along with any associated event listeners attached by Chart.js .
This must be called before the canvas is reused for a new chart .
This will clean up any references stored to the chart object within Chart.js,
along with any associated event listeners attached by Chart.js.
This must be called before the canvas is reused for a new chart. *)
method destroy : unit Js.meth
method update : unit Js.meth
(** Triggers an update of the chart.
This can be safely called after updating the data object.
This will update all scales, legends, and then re-render the chart.
A config object can be provided with additional configuration for
the update process. This is useful when update is manually called inside
an event handler and some different animation is desired.
The following properties are supported:
[duration]: Time for the animation of the redraw in milliseconds
[lazy]: If [true], the animation can be interrupted by other animations
[easing]: The animation easing function. *)
method update_withConfig : #updateConfig Js.t -> unit Js.meth
(** Reset the chart to it's state before the initial animation.
A new animation can then be triggered using [update]. *)
method reset : unit Js.meth
method render : unit Js.meth
(** Triggers a redraw of all chart elements.
Note, this does not update elements for new data.
Use [update] in that case.
See [update_withConfig] for more details on the config object. *)
method render_withConfig : #updateConfig Js.t -> unit Js.meth
(** Use this to stop any current animation loop.
This will pause the chart during any current animation frame.
Call [render] to re-animate. *)
method stop : 'self Js.t Js.meth
(** Use this to manually resize the canvas element.
This is run each time the canvas container is resized,
but you can call this method manually if you change the size
of the canvas nodes container element. *)
method resize : 'self Js.t Js.meth
(** Will clear the chart canvas. Used extensively internally between
animation frames, but you might find it useful. *)
method clear : 'self Js.t Js.meth
* This returns a base 64 encoded string of the chart in it 's current state .
method toBase64Image : Js.js_string Js.t Js.meth
(** Returns an HTML string of a legend for that chart.
The legend is generated from the legendCallback in the options. *)
method generateLegend : Js.js_string Js.t Js.meth
(** Looks for the dataset that matches the current index and returns that metadata.
This returned data has all of the metadata that is used to construct the chart.
The [data] property of the metadata will contain information about each point,
rectangle, etc. depending on the chart type. *)
method getDatasetMeta : int -> 'a Js.t Js.meth
end
val empty_animation : unit -> animation Js.t
val empty_layout : unit -> layout Js.t
val empty_legend_labels : unit -> legendLabels Js.t
val empty_legend : unit -> legend Js.t
val empty_title : unit -> title Js.t
val empty_tooltip_model : unit -> tooltipModel Js.t
val empty_tooltip_callbacks : unit -> tooltipCallbacks Js.t
val empty_tooltip : unit -> tooltip Js.t
val empty_hover : unit -> hover Js.t
val empty_point_element : unit -> pointElement Js.t
val empty_line_element : unit -> lineElement Js.t
val empty_rectangle_element : unit -> rectangleElement Js.t
val empty_arc_element : unit -> arcElement Js.t
val empty_elements : unit -> elements Js.t
val empty_update_config : unit -> updateConfig Js.t
(** {1 Charts} *)
(** {2 Line Chart} *)
class type ['a] lineOptionContext =
object
method chart : lineChart Js.t Js.readonly_prop
method dataIndex : int Js.readonly_prop
method dataset : 'a lineDataset Js.t Js.readonly_prop
method datasetIndex : int Js.readonly_prop
end
and lineScales =
object
method xAxes : #cartesianAxis Js.t Js.js_array Js.t Js.prop
method yAxes : #cartesianAxis Js.t Js.js_array Js.t Js.prop
end
and lineOptions =
object
inherit chartOptions
method animation : animation Js.t Js.prop
method scales : lineScales Js.t Js.prop
(** If [false], the lines between points are not drawn. *)
method showLines : bool Js.t Js.prop
* If [ false ] , NaN data causes a break in the line .
method spanGaps : bool Js.t Js.prop
end
and lineConfig =
object
method data : data Js.t Js.prop
method options : lineOptions Js.t Js.prop
method _type : Js.js_string Js.t Js.prop
end
and ['a] lineDataset =
object
inherit dataset
method data : 'a Js.js_array Js.t Js.prop
* { 2 General }
(** The ID of the x axis to plot this dataset on. *)
method xAxisID : Js.js_string Js.t Js.optdef_prop
(** The ID of the y axis to plot this dataset on. *)
method yAxisID : Js.js_string Js.t Js.optdef_prop
* { 2 Point styling }
(** The fill color for points. *)
method pointBackgroundColor :
('a lineOptionContext Js.t, Color.t Js.t) Scriptable_indexable.t Js.t
Js.optdef_prop
(** The border color for points. *)
method pointBorderColor :
('a lineOptionContext Js.t, Color.t Js.t) Scriptable_indexable.t Js.t
Js.optdef_prop
(** The width of the point border in pixels. *)
method pointBorderWidth :
('a lineOptionContext Js.t, int) Scriptable_indexable.t Js.t Js.optdef_prop
(** The pixel size of the non-displayed point that reacts to mouse events. *)
method pointHitRadius :
('a lineOptionContext Js.t, int) Scriptable_indexable.t Js.t Js.optdef_prop
(** The radius of the point shape. If set to 0, the point is not rendered. *)
method pointRadius :
('a lineOptionContext Js.t, int) Scriptable_indexable.t Js.t Js.optdef_prop
(** The rotation of the point in degrees. *)
method pointRotation :
('a lineOptionContext Js.t, int) Scriptable_indexable.t Js.t Js.optdef_prop
(** Style of the point. *)
method pointStyle : Point_style.t Js.t Js.optdef_prop
* { 2 Line styling }
(** The line fill color. *)
method backgroundColor : Color.t Js.t Js.optdef_prop
* style of the line .
method borderCapStyle : Line_cap.t Js.t Js.optdef_prop
(** The line color. *)
method borderColor : Color.t Js.t Js.optdef_prop
(** Length and spacing of dashes. *)
method borderDash : line_dash Js.optdef_prop
(** Offset for line dashes. *)
method borderDashOffset : line_dash_offset Js.optdef_prop
(** Line joint style. *)
method borderJoinStyle : Line_join.t Js.t Js.optdef_prop
(** The line width (in pixels). *)
method borderWidth : int Js.optdef_prop
(** How to fill the area under the line. *)
method fill : Line_fill.t Js.t Js.optdef_prop
* curve tension of the line . Set to 0 to draw straightlines .
This option is ignored if monotone cubic interpolation is used .
This option is ignored if monotone cubic interpolation is used. *)
method lineTension : float Js.optdef_prop
(** If [false], the line is not drawn for this dataset. *)
method showLine : bool Js.t Js.optdef_prop
* If [ true ] , lines will be drawn between points with no or null data .
If [ false ] , points with NaN data will create a break in the line .
If [false], points with NaN data will create a break in the line. *)
method spanGaps : bool Js.t Js.optdef_prop
* { 2 Interactions }
(** Point background color when hovered. *)
method pointHoverBackgroundColor :
('a lineOptionContext Js.t, Color.t Js.t) Scriptable_indexable.t Js.t
Js.optdef_prop
(** Point border color when hovered. *)
method pointHoverBorderColor :
('a lineOptionContext Js.t, Color.t Js.t) Scriptable_indexable.t Js.t
Js.optdef_prop
(** Border width of point when hovered. *)
method pointHoverBorderWidth :
('a lineOptionContext Js.t, int) Scriptable_indexable.t Js.t Js.optdef_prop
(** The radius of the point when hovered. *)
method pointHoverRadius :
('a lineOptionContext Js.t, int) Scriptable_indexable.t Js.t Js.optdef_prop
* { 2 Cubic Interpolation Mode }
(** The [default] and [monotone] interpolation modes are supported.
The [default] algorithm uses a custom weighted cubic interpolation,
which produces pleasant curves for all types of datasets.
The [monotone] algorithm is more suited to [y = f(x)] datasets : it preserves
monotonicity (or piecewise monotonicity) of the dataset being interpolated,
and ensures local extremums (if any) stay at input data points.
If left untouched (undefined), the global
[options.elements.line.cubicInterpolationMode] property is used. *)
method cubicInterpolationMode : Interpolation_mode.t Js.t Js.optdef_prop
* { 2 Stepped Line }
* The following values are supported for steppedLine .
[ false ] : No Step Interpolation ( default )
[ true ] : Step - before Interpolation ( eq . ' before ' )
[ ' before ' ] : Step - before Interpolation
[ ' after ' ] : Step - after Interpolation
[ ' middle ' ] : Step - middle Interpolation
If the [ steppedLine ] value is set to anything other than [ false ] ,
[ lineTension ] will be ignored .
[false]: No Step Interpolation (default)
[true]: Step-before Interpolation (eq. 'before')
['before']: Step-before Interpolation
['after']: Step-after Interpolation
['middle']: Step-middle Interpolation
If the [steppedLine] value is set to anything other than [false],
[lineTension] will be ignored.*)
method steppedLine : Stepped_line.t Js.t Js.optdef_prop
end
and lineChart =
object
inherit chart
method options : lineOptions Js.t Js.prop
method config : lineConfig Js.t Js.prop
end
val empty_line_scales : unit -> lineScales Js.t
val empty_line_options : unit -> lineOptions Js.t
val empty_line_dataset : unit -> 'a lineDataset Js.t
(** {2 Bar Chart} *)
class type barAxis =
object
* Percent ( 0 - 1 ) of the available width each bar should be within
the category width . 1.0 will take the whole category width and
put the bars right next to each other .
the category width. 1.0 will take the whole category width and
put the bars right next to each other. *)
method barPercentage : float Js.prop
(** Percent (0-1) of the available width each category should be within
the sample width. *)
method categoryPercentage : float Js.prop
(** Manually set width of each bar in pixels. If set to 'flex',
it computes "optimal" sample widths that globally arrange bars side by side.
If not set (default), bars are equally sized based on the smallest interval. *)
method barThickness : Bar_thickness.t Js.t Js.optdef_prop
(** Set this to ensure that bars are not sized thicker than this. *)
method maxBarThickness : float Js.optdef_prop
(** Set this to ensure that bars have a minimum length in pixels. *)
method minBarLength : float Js.optdef_prop
method stacked : bool Js.t Js.optdef_prop
end
class type cateroryBarAxis =
object
inherit categoryAxis
inherit barAxis
end
class type linearBarAxis =
object
inherit linearAxis
inherit barAxis
end
class type logarithmicBarAxis =
object
inherit logarithmicAxis
inherit barAxis
end
class type timeBarAxis =
object
inherit timeAxis
inherit barAxis
end
class type barScales =
object
method xAxes : #barAxis Js.t Js.js_array Js.t Js.prop
method yAxes : #barAxis Js.t Js.js_array Js.t Js.prop
end
class type ['a] barOptionContext =
object
method chart : barChart Js.t Js.readonly_prop
method dataIndex : int Js.readonly_prop
method dataset : 'a barDataset Js.t Js.readonly_prop
method datasetIndex : int Js.readonly_prop
end
and barOptions =
object
inherit chartOptions
method animation : animation Js.t Js.prop
method scales : barScales Js.t Js.prop
end
and barConfig =
object
method data : data Js.t Js.prop
method options : barOptions Js.t Js.prop
method _type : Js.js_string Js.t Js.prop
end
and ['a] barDataset =
object
inherit dataset
method data : 'a Js.js_array Js.t Js.prop
* { 2 General }
(** The ID of the x axis to plot this dataset on. *)
method xAxisID : Js.js_string Js.t Js.optdef_prop
(** The ID of the y axis to plot this dataset on. *)
method yAxisID : Js.js_string Js.t Js.optdef_prop
(** {2 Styling} *)
(** The bar background color. *)
method backgroundColor :
('a barOptionContext Js.t, Color.t Js.t) Scriptable_indexable.t Js.t Js.optdef_prop
(** The bar border color. *)
method borderColor :
('a barOptionContext Js.t, Color.t Js.t) Scriptable_indexable.t Js.t Js.optdef_prop
(** The edge to skip when drawing bar.
This setting is used to avoid drawing the bar stroke at the base of the fill.
In general, this does not need to be changed except when creating chart types
that derive from a bar chart.
Note: for negative bars in vertical chart, top and bottom are flipped.
Same goes for left and right in horizontal chart.
Options are:
['bottom'],
['left'],
['top'],
['right'],
[false] *)
method borderSkipped :
('a barOptionContext Js.t, Position.t Js.t Or_false.t Js.t) Scriptable_indexable.t
Js.t
Js.optdef_prop
* The bar border width ( in pixels ) .
If this value is a number , it is applied to all sides of the rectangle
( left , top , right , bottom ) , except [ ] . If this value is
an object , the [ left ] property defines the left border width . Similarly
the [ right ] , [ top ] and [ bottom ] properties can also be specified .
Omitted borders and [ borderSkipped ] are skipped .
If this value is a number, it is applied to all sides of the rectangle
(left, top, right, bottom), except [borderSkipped]. If this value is
an object, the [left] property defines the left border width. Similarly
the [right], [top] and [bottom] properties can also be specified.
Omitted borders and [borderSkipped] are skipped. *)
method borderWidth :
('a barOptionContext Js.t, Padding.t Js.t) Scriptable_indexable.t Js.t
Js.optdef_prop
* { 2 Interactions }
All these values , if undefined , fallback to the associated
[ elements.rectangle . * ] options .
All these values, if undefined, fallback to the associated
[elements.rectangle.*] options. *)
(** The bar background color when hovered. *)
method hoverBackgroundColor : Color.t Js.t Indexable.t Js.t Js.optdef_prop
(** The bar border color when hovered. *)
method hoverBorderColor : Color.t Js.t Indexable.t Js.t Js.optdef_prop
(** The bar border width when hovered (in pixels). *)
method hoverBorderWidth : Color.t Js.t Indexable.t Js.t Js.optdef_prop
(** The ID of the group to which this dataset belongs to
(when stacked, each group will be a separate stack). *)
method stack : Js.js_string Js.t Js.optdef_prop
end
and barChart =
object
inherit chart
method options : barOptions Js.t Js.prop
method config : barConfig Js.t Js.prop
end
val empty_bar_axis : unit -> cateroryBarAxis Js.t
val empty_linear_bar_axis : unit -> linearBarAxis Js.t
val empty_logarithmic_bar_axis : unit -> logarithmicBarAxis Js.t
val empty_time_bar_axis : unit -> timeBarAxis Js.t
val empty_bar_scales : unit -> barScales Js.t
val empty_bar_options : unit -> barOptions Js.t
val empty_bar_dataset : unit -> 'a barDataset Js.t
* { 2 Pie Chart }
class type ['a] pieOptionContext =
object
method chart : pieChart Js.t Js.readonly_prop
method dataIndex : int Js.readonly_prop
method dataset : 'a pieDataset Js.t Js.readonly_prop
method datasetIndex : int Js.readonly_prop
end
and pieAnimation =
object
inherit animation
(** If [true], the chart will animate in with a rotation animation. *)
method animateRotate : bool Js.t Js.prop
(** If true, will animate scaling the chart from the center outwards. *)
method animateScale : bool Js.t Js.prop
end
and pieOptions =
object
inherit chartOptions
method animation : pieAnimation Js.t Js.prop
(** The percentage of the chart that is cut out of the middle. *)
method cutoutPercentage : float Js.prop
(** Starting angle to draw arcs from. *)
method rotation : float Js.prop
(** Sweep to allow arcs to cover. *)
method circumference : float Js.prop
end
and pieConfig =
object
method data : data Js.t Js.prop
method options : pieOptions Js.t Js.prop
method _type : Js.js_string Js.t Js.prop
end
and ['a] pieDataset =
object
inherit dataset
method data : 'a Js.js_array Js.t Js.prop
(** {2 Styling} *)
(** Arc background color. *)
method backgroundColor :
('a pieOptionContext Js.t, Color.t Js.t) Scriptable_indexable.t Js.t Js.optdef_prop
(** Arc border color. *)
method borderColor :
('a pieOptionContext Js.t, Color.t Js.t) Scriptable_indexable.t Js.t Js.optdef_prop
(** Arc border width (in pixels). *)
method borderWidth :
('a pieOptionContext Js.t, int) Scriptable_indexable.t Js.t Js.optdef_prop
(** The relative thickness of the dataset.
Providing a value for weight will cause the pie or doughnut dataset
to be drawn with a thickness relative to the sum of all the dataset
weight values. *)
method weight : float Js.optdef_prop
* { 2 Interactions }
(** Arc background color when hovered. *)
method hoverBackgroundColor :
('a pieOptionContext Js.t, Color.t Js.t) Scriptable_indexable.t Js.t Js.optdef_prop
(** Arc border color when hovered. *)
method hoverBorderColor :
('a pieOptionContext Js.t, Color.t Js.t) Scriptable_indexable.t Js.t Js.optdef_prop
(** Arc border width when hovered (in pixels). *)
method hoverBorderWidth :
('a pieOptionContext Js.t, int) Scriptable_indexable.t Js.t Js.optdef_prop
(** {2 Border Alignment} *)
(** The following values are supported for [borderAlign]:
['center'] (default),
['inner'].
When ['center'] is set, the borders of arcs next to each other will overlap.
When ['inner'] is set, it is guaranteed that all the borders are not overlap. *)
method borderAlign : Pie_border_align.t Js.t Js.optdef_prop
end
and pieChart =
object
inherit chart
method options : pieOptions Js.t Js.prop
method config : pieConfig Js.t Js.prop
end
val empty_pie_animation : unit -> pieAnimation Js.t
val empty_pie_options : unit -> pieOptions Js.t
val empty_pie_dataset : unit -> 'a pieDataset Js.t
module Axis : sig
type 'a typ
val cartesian_category : categoryAxis typ
val cartesian_linear : linearAxis typ
val cartesian_logarithmic : logarithmicAxis typ
val cartesian_time : timeAxis typ
val of_string : string -> 'a typ
end
module Chart : sig
type 'a typ
val line : lineChart typ
val bar : barChart typ
val horizontal_bar : barChart typ
val pie : pieChart typ
val doughnut : pieChart typ
val of_string : string -> 'a typ
end
(** {1 Type Coercion} *)
module CoerceTo : sig
val line : #chart Js.t -> lineChart Js.t Js.opt
val bar : #chart Js.t -> barChart Js.t Js.opt
val horizontalBar : #chart Js.t -> barChart Js.t Js.opt
val pie : #chart Js.t -> pieChart Js.t Js.opt
val doughnut : #chart Js.t -> pieChart Js.t Js.opt
val cartesianCategory : #axis Js.t -> categoryAxis Js.t Js.opt
val cartesianLinear : #axis Js.t -> linearAxis Js.t Js.opt
val cartesianLogarithmic : #axis Js.t -> logarithmicAxis Js.t Js.opt
val cartesianTime : #axis Js.t -> timeAxis Js.t Js.opt
end
(** {1 Creating an Axis} *)
val create_axis : 'a Axis.typ -> 'a Js.t
(** {1 Creating a Chart} *)
val chart_from_canvas :
'a Chart.typ
-> data Js.t
-> #chartOptions Js.t
-> Dom_html.canvasElement Js.t
-> 'a Js.t
val chart_from_ctx :
'a Chart.typ
-> data Js.t
-> #chartOptions Js.t
-> Dom_html.canvasRenderingContext2D Js.t
-> 'a Js.t
val chart_from_id : 'a Chart.typ -> data Js.t -> #chartOptions Js.t -> string -> 'a Js.t
| null | https://raw.githubusercontent.com/monstasat/chartjs-ocaml/e6f25819bc18168811c63db72b615095ff082181/lib/chartjs.mli | ocaml | * Scriptable options also accept a function which is called for each
of the underlying data values and that takes the unique argument
[context] representing contextual information.
* @see <-US/docs/Web/API/CanvasRenderingContext2D/lineJoin>
* When configuring interaction with the graph via hover or tooltips,
a number of different modes are available.
* Finds all of the items that intersect the point.
* Gets the items that are at the nearest distance to the point.
The nearest item is determined based on the distance to the center
of the chart item (point, bar). You can use the [axis] setting to define
which directions are used in distance calculation. If [intersect] is [true],
this is only triggered when the mouse position intersects an item
in the graph. This is very useful for combo charts where points are hidden
behind bars.
* Returns all items that would intersect based on the [X] coordinate
of the position only. Would be useful for a vertical cursor implementation.
Note that this only applies to cartesian charts.
* Returns all items that would intersect based on the [Y] coordinate
of the position. This would be useful for a horizontal cursor implementation.
Note that this only applies to cartesian charts.
* If this value is a number, it is applied to all sides of the element
(left, top, right, bottom). If this value is an object, the [left]
property defines the left padding. Similarly the [right], [top] and
[bottom] properties can also be specified.
* Will place the tooltip at the average position
of the items displayed in the tooltip.
* Will place the tooltip at the position of the element
closest to the event position.
* @see <-US/docs/Web/CSS/line-height>
* @see <-US/docs/Web/API/CanvasRenderingContext2D/setLineDash>
* @see <-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset>
* Data points are spread according to their time (distances can vary).
* Data points are spread at the same distance from each other.
* Makes sure data are fully visible, labels outside are removed.
* Makes sure ticks are fully visible, data outside are truncated.
* Default algorithm uses a custom weighted cubic interpolation,
which produces pleasant curves for all types of datasets.
* Monotone algorithm is more suited to [y = f(x)] datasets :
it preserves monotonicity (or piecewise monotonicity) of the dataset
being interpolated, and ensures local extremums (if any) stay at input
data points.
* No Step Interpolation.
* Step-before Interpolation (same as [before]).
* Step-before Interpolation.
* Step-after Interpolation.
* Step-middle Interpolation.
* Equivalent to [origin]
* The borders of arcs next to each other will overlap.
* Guarantees that all the borders do not overlap.
* A custom format to be used by Moment.js to parse the date.
* A function must return a Moment.js object given the appropriate data value.
* {1 Axes}
* The minorTick configuration is nested under the ticks configuration
in the [minor] key. It defines options for the minor tick marks that are
generated by the axis. Omitted options are inherited from ticks
configuration.
* Returns the string representation of the tick value
as it should be displayed on the chart.
* Font color for tick labels.
* Font family for the tick labels, follows CSS font-family options.
* Font size for the tick labels.
* Font style for the tick labels, follows CSS font-style options
(i.e. normal, italic, oblique, initial, inherit).
* The majorTick configuration is nested under the ticks configuration
in the [major] key. It defines options for the major tick marks that are
generated by the axis. Omitted options are inherited from ticks configuration.
These options are disabled by default.
* The tick configuration is nested under the scale configuration
in the ticks key. It defines options for the tick marks that are
generated by the axis.
* Returns the string representation of the tick value as
it should be displayed on the chart.
* If [true], show tick marks.
* Font color for tick labels.
* Font family for the tick labels, follows CSS font-family options.
* Font size for the tick labels.
* Font style for the tick labels, follows CSS font-style options
(i.e. normal, italic, oblique, initial, inherit).
* Reverses order of tick labels.
* Minor ticks configuration. Omitted options are inherited
from options above.
* Major ticks configuration. Omitted options are inherited
from options above.
* If true, display the axis title.
* The text for the title. (i.e. "# of People" or "Response Choices").
* Height of an individual line of text.
* Font color for scale title.
* Font family for the scale title, follows CSS font-family options.
* Font size for scale title.
* Font style for the scale title, follows CSS font-style options
(i.e. normal, italic, oblique, initial, inherit)
* Padding to apply around scale labels.
Only top and bottom are implemented.
* If [false], do not display grid lines for this axis.
* If [true], gridlines are circular (on radar chart only).
* Length and spacing of dashes on grid lines.
* Offset for line dashes.
* Stroke width of grid lines.
* If true, draw border at the edge between the axis and the chart area.
* If true, draw lines on the chart area inside the axis lines.
This is useful when there are multiple axes and you need to
control which grid lines are drawn.
* If true, draw lines beside the ticks in the axis area beside the chart.
* Length in pixels that the grid lines will draw into the axis area.
* If [true], grid lines will be shifted to be between labels.
This is set to true for a category scale in a bar chart by default.
* Type of scale being employed
Custom scales can be created and registered with a string key.
This allows changing the type of an axis for a chart.
* The weight used to sort the axis.
Higher weights are further away from the chart area.
* Callback called before the update process starts.
* Callback that runs before dimensions are set.
* Callback that runs after dimensions are set.
* Callback that runs before data limits are determined.
* Callback that runs after data limits are determined.
* Callback that runs before ticks are created.
* Callback that runs after ticks are created. Useful for filtering ticks.
@return the filtered ticks.
* Callback that runs before ticks are converted into strings.
* Callback that runs after ticks are converted into strings.
* Callback that runs before tick rotation is determined.
* Callback that runs after tick rotation is determined.
* Callback that runs before the scale fits to the canvas.
* Callback that runs after the scale fits to the canvas.
* Callback that runs at the end of the update process.
* If [true], automatically calculates how many labels that
can be shown and hides labels accordingly. Turn it off to show all
labels no matter what.
* Padding between the ticks on the horizontal axis when autoSkip is
enabled. Note: Only applicable to horizontal scales.
* Distance in pixels to offset the label from the centre point of the
tick (in the y direction for the x axis, and the x direction for the
y axis). Note: this can cause labels at the edges to be cropped by the
edge of the canvas.
* Maximum rotation for tick labels when rotating to condense labels.
Note: Rotation doesn't occur until necessary.
Note: Only applicable to horizontal scales.
* Minimum rotation for tick labels.
Note: Only applicable to horizontal scales.
* Flips tick labels around axis, displaying the labels inside the chart
instead of outside. Note: Only applicable to vertical scales.
* Padding between the tick label and the axis. When set on a vertical axis,
this applies in the horizontal (X) direction. When set on a horizontal
axis, this applies in the vertical (Y) direction.
* Position of the axis in the chart.
Possible values are: ['top'], ['left'], ['bottom'], ['right']
* If [true], extra space is added to the both edges and the axis
is scaled to fit into the chart area. This is set to true for a
category scale in a bar chart by default.
* The ID is used to link datasets and scale axes together.
* Grid line configuration.
* Scale title configuration.
* Ticks configuration.
* An array of labels to display.
* The minimum item to display.
* The maximum item to display.
* If [true], scale will include 0 if it is not already included.
* User defined minimum number for the scale,
overrides minimum value from data.
* User defined maximum number for the scale,
overrides maximum value from data.
* Maximum number of ticks and gridlines to show.
* If defined and stepSize is not specified,
the step size will be rounded to this many decimal places.
* User defined fixed step size for the scale.
* Adjustment used when calculating the maximum data value.
* Adjustment used when calculating the minimum data value.
* User defined minimum number for the scale,
overrides minimum value from data.
* User defined maximum number for the scale,
overrides maximum value from data.
* The following display formats are used to configure
how different time units are formed into strings for
the axis tick marks.
* How ticks are generated.
[auto]: generates "optimal" ticks based on scale size and time options
[data]: generates ticks from data (including labels from data objects)
[labels]: generates ticks from user given data.labels values ONLY
* Sets how different time units are displayed.
* If defined, this will override the data maximum
* If defined, this will override the data minimum
* Custom parser for dates.
* If defined, dates will be rounded to the start of this unit.
* The moment js format string to use for the tooltip.
* If defined, will force the unit to be a certain type.
* The number of units between grid lines.
* The minimum display format to be used for a time unit.
* The distribution property controls the data distribution along the scale:
[linear]: data are spread according to their time (distances can vary)
[series]: data are spread at the same distance from each other
* {1 Chart configuration}
* {2 Animation}
* Chart object.
* Current Animation frame number.
* Number of animation frames.
* Function that renders the chart.
* User callback.
* User callback.
* The number of milliseconds an animation takes.
* Easing function to use.
* Callback called on each step of an animation.
* Callback called at the end of an animation.
* The padding to add inside the chart.
* {2 Legend}
* Label that will be displayed.
* Fill style of the legend box.
* If [true], this item represents a hidden dataset.
Label will be rendered with a strike-through effect.
* For box border.
* For box border.
* For box border.
* For box border.
* Width of box border.
* Stroke style of the legend box.
* Width of coloured box.
* Font size of text.
* Font style of text.
* Color of text.
* Font family of legend text.
* Padding between rows of colored boxes.
* Generates legend items for each thing in the legend.
Default implementation returns the text + styling for the color box.
* Is the legend shown.
* Position of the legend.
* A callback that is called when a click event is
registered on a label item
* A callback that is called when a 'mousemove' event is
registered on top of a label item
* Legend will show datasets in reverse order.
* Legend label configuration.
* Is the title shown.
* Position of title.
* Font size.
* Font family for the title text.
* Font color.
* Font style.
* Number of pixels to add above and below the title text.
* Height of an individual line of text.
* Title text to display. If specified as an array,
text is rendered on multiple lines.
* Label for the tooltip.
* Value for the tooltip.
* Index of the dataset the item comes from.
* Index of this data item in the dataset.
* X position of matching point.
* Y position of matching point.
* The items that we are rendering in the tooltip.
* Positioning.
* X and Y readonly_properties are the top left of the tooltip.
* Where the tooltip points to.
* Title. Lines of text that form the title.
* Footer. Lines of text that form the footer.
* Appearance.
* Colors to render for each item in body. This is the color of the
squares in the tooltip.
* Returns the text to render before the title.
* Returns the text to render as the title of the tooltip.
* Returns the text to render after the title.
* Returns the text to render before the body section.
* Returns the text to render before an individual label.
This will be called for each item in the tooltip.
* Returns the text to render for an individual item in the tooltip.
* Returns the colors to render for the tooltip item.
* Returns the colors for the text of the label for the tooltip item.
* Returns text to render after an individual label.
* Returns text to render after the body section.
* Returns text to render before the footer section.
* Returns text to render as the footer of the tooltip.
* Text to render after the footer section.
* Are on-canvas tooltips enabled.
* Custom tooltip callback.
* Sets which elements appear in the tooltip.
* If [true], the tooltip mode applies only when the mouse position
intersects with an element. If [false], the mode will be applied
at all times.
* Defines which directions are used in calculating distances.
Defaults to [x] for index mode and [xy] in [dataset] and [nearest]
modes.
* The mode for positioning the tooltip.
* Callbacks.
* Sort tooltip items.
* Filter tooltip items.
* Background color of the tooltip.
* Title font.
* Title font size.
* Title font style
* Title font color
* Spacing to add to top and bottom of each title line.
* Margin to add on bottom of title section.
* Body line font.
* Body font size.
* Body font style.
* Body font color.
* Spacing to add to top and bottom of each tooltip item.
* Footer font.
* Footer font size.
* Footer font style.
* Footer font color.
* Spacing to add to top and bottom of each footer line.
* Margin to add before drawing the footer.
* Padding to add on left and right of tooltip.
* Padding to add on top and bottom of tooltip.
* Extra distance to move the end of the tooltip arrow
away from the tooltip point.
* Radius of tooltip corner curves.
* Color to draw behind the colored boxes when multiple
items are in the tooltip.
* If [true], color boxes are shown in the tooltip.
* Color of the border.
* Size of the border.
* Sets which elements appear in the tooltip.
* If true, the hover mode only applies when the mouse
position intersects an item on the chart.
* Defines which directions are used in calculating distances.
Defaults to [x] for index mode and [xy] in [dataset] and [nearest]
modes.
* Duration in milliseconds it takes to animate hover style changes.
* Point radius.
* Point style.
* Point rotation (in degrees).
* Point fill color.
* Point stroke width.
* Point stroke color.
* Extra radius added to point radius for hit detection.
* Point radius when hovered.
* Stroke width when hovered.
* Line fill color.
* Line stroke width.
* Line stroke color.
* Line cap style.
* Line dash.
* Line dash offset.
* Line join style.
* Fill location.
* [true] to show the line as a stepped line (tension will be ignored).
* Bar fill color.
* Bar stroke width.
* Bar stroke color.
* Skipped (excluded) border: 'bottom', 'left', 'top' or 'right'.
* Arc fill color.
* Arc stroke alignment.
* Arc stroke color.
* Arc stroke width.
* Point elements are used to represent the points
in a line chart or a bubble chart.
* Line elements are used to represent the line in a line chart.
* Rectangle elements are used to represent the bars in a bar chart.
* Arcs are used in the polar area, doughnut and pie charts.
* The configuration is used to change how the chart behaves.
There are properties to control styling, fonts, the legend, etc.
* Layout configurations.
* The chart legend displays data about the datasets
that are appearing on the chart.
* The chart title defines text to draw at the top of the chart.
* Plugins are the most efficient way to customize or change the default
behavior of a chart. This option allows to define plugins directly in
the chart [plugins] config (a.k.a. inline plugins).
* Sometimes you need a very complex legend. In these cases, it makes sense
to generate an HTML legend. Charts provide a generateLegend() method on their
prototype that returns an HTML string for the legend.
NOTE [legendCallback] is not called automatically and you must call
[generateLegend] yourself in code when creating a legend using this method.
* Resizes the chart canvas when its container does.
* Duration in milliseconds it takes to animate
to new size after a resize event.
* Maintain the original canvas aspect ratio (width / height) when resizing.
* Override the window's default devicePixelRatio.
* The events option defines the browser events that
the chart should listen to for tooltips and hovering.
* Called when any of the events fire.
Called in the context of the chart and passed the event
and an array of active elements (bars, points, etc).
* Called if the event is of type 'mouseup' or 'click'.
Called in the context of the chart and passed the event
and an array of active elements.
* {2 Chart API}
* Triggers an update of the chart.
This can be safely called after updating the data object.
This will update all scales, legends, and then re-render the chart.
A config object can be provided with additional configuration for
the update process. This is useful when update is manually called inside
an event handler and some different animation is desired.
The following properties are supported:
[duration]: Time for the animation of the redraw in milliseconds
[lazy]: If [true], the animation can be interrupted by other animations
[easing]: The animation easing function.
* Reset the chart to it's state before the initial animation.
A new animation can then be triggered using [update].
* Triggers a redraw of all chart elements.
Note, this does not update elements for new data.
Use [update] in that case.
See [update_withConfig] for more details on the config object.
* Use this to stop any current animation loop.
This will pause the chart during any current animation frame.
Call [render] to re-animate.
* Use this to manually resize the canvas element.
This is run each time the canvas container is resized,
but you can call this method manually if you change the size
of the canvas nodes container element.
* Will clear the chart canvas. Used extensively internally between
animation frames, but you might find it useful.
* Returns an HTML string of a legend for that chart.
The legend is generated from the legendCallback in the options.
* Looks for the dataset that matches the current index and returns that metadata.
This returned data has all of the metadata that is used to construct the chart.
The [data] property of the metadata will contain information about each point,
rectangle, etc. depending on the chart type.
* {1 Charts}
* {2 Line Chart}
* If [false], the lines between points are not drawn.
* The ID of the x axis to plot this dataset on.
* The ID of the y axis to plot this dataset on.
* The fill color for points.
* The border color for points.
* The width of the point border in pixels.
* The pixel size of the non-displayed point that reacts to mouse events.
* The radius of the point shape. If set to 0, the point is not rendered.
* The rotation of the point in degrees.
* Style of the point.
* The line fill color.
* The line color.
* Length and spacing of dashes.
* Offset for line dashes.
* Line joint style.
* The line width (in pixels).
* How to fill the area under the line.
* If [false], the line is not drawn for this dataset.
* Point background color when hovered.
* Point border color when hovered.
* Border width of point when hovered.
* The radius of the point when hovered.
* The [default] and [monotone] interpolation modes are supported.
The [default] algorithm uses a custom weighted cubic interpolation,
which produces pleasant curves for all types of datasets.
The [monotone] algorithm is more suited to [y = f(x)] datasets : it preserves
monotonicity (or piecewise monotonicity) of the dataset being interpolated,
and ensures local extremums (if any) stay at input data points.
If left untouched (undefined), the global
[options.elements.line.cubicInterpolationMode] property is used.
* {2 Bar Chart}
* Percent (0-1) of the available width each category should be within
the sample width.
* Manually set width of each bar in pixels. If set to 'flex',
it computes "optimal" sample widths that globally arrange bars side by side.
If not set (default), bars are equally sized based on the smallest interval.
* Set this to ensure that bars are not sized thicker than this.
* Set this to ensure that bars have a minimum length in pixels.
* The ID of the x axis to plot this dataset on.
* The ID of the y axis to plot this dataset on.
* {2 Styling}
* The bar background color.
* The bar border color.
* The edge to skip when drawing bar.
This setting is used to avoid drawing the bar stroke at the base of the fill.
In general, this does not need to be changed except when creating chart types
that derive from a bar chart.
Note: for negative bars in vertical chart, top and bottom are flipped.
Same goes for left and right in horizontal chart.
Options are:
['bottom'],
['left'],
['top'],
['right'],
[false]
* The bar background color when hovered.
* The bar border color when hovered.
* The bar border width when hovered (in pixels).
* The ID of the group to which this dataset belongs to
(when stacked, each group will be a separate stack).
* If [true], the chart will animate in with a rotation animation.
* If true, will animate scaling the chart from the center outwards.
* The percentage of the chart that is cut out of the middle.
* Starting angle to draw arcs from.
* Sweep to allow arcs to cover.
* {2 Styling}
* Arc background color.
* Arc border color.
* Arc border width (in pixels).
* The relative thickness of the dataset.
Providing a value for weight will cause the pie or doughnut dataset
to be drawn with a thickness relative to the sum of all the dataset
weight values.
* Arc background color when hovered.
* Arc border color when hovered.
* Arc border width when hovered (in pixels).
* {2 Border Alignment}
* The following values are supported for [borderAlign]:
['center'] (default),
['inner'].
When ['center'] is set, the borders of arcs next to each other will overlap.
When ['inner'] is set, it is guaranteed that all the borders are not overlap.
* {1 Type Coercion}
* {1 Creating an Axis}
* {1 Creating a Chart} | open Js_of_ocaml
module Indexable : sig
type 'a t
* options also accept an array in which each item corresponds
to the element at the same index . Note that this method requires
to provide as many items as data , so , in most cases , using a function
is more appropriated if supported .
to the element at the same index. Note that this method requires
to provide as many items as data, so, in most cases, using a function
is more appropriated if supported. *)
val of_single : 'a -> 'a t Js.t
val of_js_array : 'a Js.js_array Js.t -> 'a t Js.t
val of_array : 'a array -> 'a t Js.t
val of_list : 'a list -> 'a t Js.t
val cast_single : 'a t Js.t -> 'a Js.opt
val cast_js_array : 'a t Js.t -> 'a Js.js_array Js.t Js.opt
end
module Scriptable : sig
type ('a, 'b) t
val of_fun : ('a -> 'b) -> ('a, 'b) t Js.t
end
module Scriptable_indexable : sig
type ('a, 'b) t
val of_single : 'b -> ('a, 'b) t Js.t
val of_js_array : 'b Js.js_array Js.t -> ('a, 'b) t Js.t
val of_array : 'b array -> ('a, 'b) t Js.t
val of_list : 'b list -> ('a, 'b) t Js.t
val of_fun : ('a -> 'b) -> ('a, 'b) t Js.t
val cast_single : ('a, 'b) t Js.t -> 'b Js.opt
val cast_js_array : ('a, 'b) t Js.t -> 'b Js.js_array Js.t Js.opt
val cast_fun : ('a, 'b) t Js.t -> ('c, 'a -> 'b) Js.meth_callback Js.opt
end
module Line_cap : sig
type t
* @see < >
val butt : t Js.t
val round : t Js.t
val square : t Js.t
val of_string : string -> t Js.t
end
module Line_join : sig
type t
val round : t Js.t
val bevel : t Js.t
val miter : t Js.t
val of_string : string -> t Js.t
end
module Interaction_mode : sig
type t
val point : t Js.t
val nearest : t Js.t
val index : t Js.t
* Finds item at the same index .
If the [ intersect ] setting is [ true ] , the first intersecting item is used
to determine the index in the data . If [ intersect ] is [ false ] ,
the nearest item in the x direction is used to determine the index .
To use index mode in a chart like the horizontal bar chart , where we search
along the y direction , you can use the [ axis ] setting introduced in v2.7.0 .
By setting this value to [ ' y ' ] on the y direction is used .
If the [intersect] setting is [true], the first intersecting item is used
to determine the index in the data. If [intersect] is [false],
the nearest item in the x direction is used to determine the index.
To use index mode in a chart like the horizontal bar chart, where we search
along the y direction, you can use the [axis] setting introduced in v2.7.0.
By setting this value to ['y'] on the y direction is used. *)
val dataset : t Js.t
* Finds items in the same dataset .
If the [ intersect ] setting is [ true ] , the first intersecting item is used
to determine the index in the data .
If [ intersect ] is [ false ] , the nearest item is used to determine the index .
If the [intersect] setting is [true], the first intersecting item is used
to determine the index in the data.
If [intersect] is [false], the nearest item is used to determine the index. *)
val x : t Js.t
val y : t Js.t
val of_string : string -> t Js.t
end
module Point_style : sig
type t
val circle : t Js.t
val cross : t Js.t
val crossRot : t Js.t
val dash : t Js.t
val line : t Js.t
val rect : t Js.t
val rectRounded : t Js.t
val rectRot : t Js.t
val star : t Js.t
val triangle : t Js.t
val of_string : string -> t Js.t
val of_image : Dom_html.imageElement Js.t -> t Js.t
val of_video : Dom_html.videoElement Js.t -> t Js.t
val of_canvas : Dom_html.canvasElement Js.t -> t Js.t
val cast_string : t Js.t -> string Js.opt
val cast_image : t Js.t -> Dom_html.imageElement Js.t Js.opt
val cast_video : t Js.t -> Dom_html.videoElement Js.t Js.opt
val cast_canvas : t Js.t -> Dom_html.canvasElement Js.t Js.opt
end
module Easing : sig
type t
val linear : t Js.t
val easeInQuad : t Js.t
val easeOutQuad : t Js.t
val easeInOutQuad : t Js.t
val easeInCubic : t Js.t
val easeOutCubic : t Js.t
val easeInOutCubic : t Js.t
val easeInQuart : t Js.t
val easeOutQuart : t Js.t
val easeInOutQuart : t Js.t
val easeInQuint : t Js.t
val easeOutQuint : t Js.t
val easeInOutQuint : t Js.t
val easeInSine : t Js.t
val easeOutSine : t Js.t
val easeInOutSine : t Js.t
val easeInExpo : t Js.t
val easeOutExpo : t Js.t
val easeInOutExpo : t Js.t
val easeInCirc : t Js.t
val easeOutCirc : t Js.t
val easeInOutCirc : t Js.t
val easeInElastic : t Js.t
val easeOutElastic : t Js.t
val easeInOutElastic : t Js.t
val easeInBack : t Js.t
val easeOutBack : t Js.t
val easeInOutBack : t Js.t
val easeInBounce : t Js.t
val easeOutBounce : t Js.t
val easeInOutBounce : t Js.t
val of_string : string -> t Js.t
end
module Padding : sig
type t
class type obj =
object
method top : int Js.optdef_prop
method right : int Js.optdef_prop
method bottom : int Js.optdef_prop
method left : int Js.optdef_prop
end
val make_object : ?top:int -> ?right:int -> ?bottom:int -> ?left:int -> unit -> t Js.t
val of_object : obj Js.t -> t Js.t
val of_int : int -> t Js.t
val cast_int : t Js.t -> int Js.opt
val cast_object : t Js.t -> obj Js.t Js.opt
end
module Color : sig
type t
* When supplying colors to Chart options , you can use a number of formats .
You can specify the color as a string in hexadecimal , RGB , or HSL notations .
If a color is needed , but not specified , Chart.js will use the global
default color . This color is stored at [ Chart.defaults.global.defaultColor ] .
It is initially set to [ ' rgba(0 , 0 , 0 , 0.1 ) ' ] .
You can also pass a [ CanvasGradient ] object .
You will need to create this before passing to the chart ,
but using it you can achieve some interesting effects .
You can specify the color as a string in hexadecimal, RGB, or HSL notations.
If a color is needed, but not specified, Chart.js will use the global
default color. This color is stored at [Chart.defaults.global.defaultColor].
It is initially set to ['rgba(0, 0, 0, 0.1)'].
You can also pass a [CanvasGradient] object.
You will need to create this before passing to the chart,
but using it you can achieve some interesting effects. *)
val of_string : string -> t Js.t
val of_canvas_gradient : Dom_html.canvasGradient Js.t -> t Js.t
val of_canvas_pattern : Dom_html.canvasPattern Js.t -> t Js.t
val cast_string : t Js.t -> string Js.opt
val cast_canvas_gradient : t Js.t -> Dom_html.canvasGradient Js.t Js.opt
val cast_canvas_pattern : t Js.t -> Dom_html.canvasPattern Js.t Js.opt
end
module Position : sig
type t
val left : t Js.t
val right : t Js.t
val top : t Js.t
val bottom : t Js.t
val of_string : string -> t Js.t
end
module Tooltip_position : sig
type t
val average : t
val nearest : t
val of_string : string -> t
end
module Line_height : sig
type t
val of_string : string -> t Js.t
val of_float : float -> t Js.t
val cast_string : t Js.t -> string Js.opt
val cast_float : t Js.t -> float Js.opt
end
module Hover_axis : sig
type t
val x : t Js.t
val y : t Js.t
val xy : t Js.t
val of_string : string -> t Js.t
end
module Fill : sig
type t
val zero : t Js.t
val top : t Js.t
val bottom : t Js.t
val _true : t Js.t
val _false : t Js.t
val of_bool : bool -> t Js.t
val of_string : string -> t Js.t
val cast_bool : t Js.t -> bool Js.opt
val cast_string : t Js.t -> string Js.opt
end
module Time : sig
type t
val of_float_s : float -> t Js.t
val of_int_s : int -> t Js.t
val of_string : string -> t Js.t
val of_array : int array -> t Js.t
val of_js_array : int Js.js_array Js.t -> t Js.t
val of_date : Js.date Js.t -> t Js.t
val cast_float_s : t Js.t -> float Js.opt
val cast_string : t Js.t -> string Js.opt
val cast_js_array : t Js.t -> int Js.js_array Js.t Js.opt
val cast_date : t Js.t -> Js.date Js.t Js.opt
end
module Or_false : sig
type 'a t
val make : 'a -> 'a t Js.t
val _false : 'a t Js.t
end
type line_dash = float Js.js_array Js.t
type line_dash_offset = float
module Time_ticks_source : sig
type t
val auto : t Js.t
val data : t Js.t
val labels : t Js.t
val of_string : string -> t Js.t
end
module Time_distribution : sig
type t
val linear : t Js.t
val series : t Js.t
val of_string : string -> t Js.t
end
module Time_bounds : sig
type t
val data : t Js.t
val ticks : t Js.t
val of_string : string -> t Js.t
end
module Time_unit : sig
type t
val millisecond : t Js.t
val second : t Js.t
val minute : t Js.t
val hour : t Js.t
val day : t Js.t
val week : t Js.t
val month : t Js.t
val quarter : t Js.t
val year : t Js.t
val of_string : string -> t Js.t
end
module Interpolation_mode : sig
type t
val default : t Js.t
val monotone : t Js.t
val of_string : string -> t Js.t
end
module Stepped_line : sig
type t
val _false : t Js.t
val _true : t Js.t
val before : t Js.t
val after : t Js.t
val middle : t Js.t
val of_bool : bool -> t Js.t
val of_string : string -> t Js.t
end
module Line_fill : sig
type t
val relative : int -> t Js.t
val absolute : int -> t Js.t
val _false : t Js.t
val _true : t Js.t
val start : t Js.t
val _end : t Js.t
val origin : t Js.t
val of_bool : bool -> t Js.t
val of_string : string -> t Js.t
end
module Pie_border_align : sig
type t
val center : t Js.t
val inner : t Js.t
end
module Axis_display : sig
type t
val auto : t Js.t
val cast_bool : t Js.t -> bool Js.opt
val is_auto : t Js.t -> bool
val of_bool : bool -> t Js.t
val of_string : string -> t Js.t
end
module Time_parser : sig
type t
val of_string : string -> t Js.t
val of_fun : ('a -> 'b Js.t) -> t Js.t
val cast_string : t Js.t -> string Js.opt
val cast_fun : t Js.t -> ('a -> 'b Js.t) Js.callback Js.opt
end
module Bar_thickness : sig
type t
val flex : t Js.t
val of_int : int -> t Js.t
val of_float : float -> t Js.t
val is_flex : t Js.t -> bool
val cast_number : t Js.t -> Js.number Js.t Js.opt
end
type 'a tick_cb = ('a -> int -> 'a Js.js_array Js.t) Js.callback
type ('a, 'b, 'c) tooltip_cb =
('a, 'b -> 'c -> Js.js_string Js.t Indexable.t Js.t) Js.meth_callback Js.optdef
class type ['x, 'y] dataPoint =
object
method x : 'x Js.prop
method y : 'y Js.prop
end
class type ['t, 'y] dataPointT =
object
method t : 't Js.prop
method y : 'y Js.prop
end
class type ['x, 'y, 'r] dataPointR =
object
inherit ['x, 'y] dataPoint
method r : 'r Js.prop
end
val create_data_point : x:'a -> y:'b -> ('a, 'b) dataPoint Js.t
val create_data_point_t : t:'a -> y:'b -> ('a, 'b) dataPointT Js.t
val create_data_point_r : x:'a -> y:'b -> r:'c -> ('a, 'b, 'c) dataPointR Js.t
class type minorTicks =
object
method callback : 'a tick_cb Js.prop
method fontColor : Color.t Js.t Js.optdef_prop
method fontFamily : Js.js_string Js.t Js.optdef_prop
method fontSize : int Js.optdef_prop
method fontStyle : Js.js_string Js.t Js.optdef_prop
end
and majorTicks = minorTicks
and ticks =
object
method callback : 'a tick_cb Js.prop
method display : bool Js.t Js.prop
method fontColor : Color.t Js.t Js.optdef_prop
method fontFamily : Js.js_string Js.t Js.optdef_prop
method fontSize : int Js.optdef_prop
method fontStyle : Js.js_string Js.t Js.optdef_prop
method reverse : bool Js.t Js.prop
method minor : minorTicks Js.t
method major : majorTicks Js.t
end
and scaleLabel =
object
method display : bool Js.t Js.prop
method labelString : Js.js_string Js.t Js.prop
method lineHeight : Line_height.t Js.t Js.prop
method fontColor : Color.t Js.t Js.prop
method fontFamily : Js.js_string Js.t Js.prop
method fontSize : int Js.prop
method fontStyle : Js.js_string Js.t Js.prop
method padding : Padding.t Js.t Js.prop
end
and gridLines =
object
method display : bool Js.t Js.prop
method circular : bool Js.t Js.prop
* The color of the grid lines . If specified as an array ,
the first color applies to the first grid line , the second
to the second grid line and so on .
the first color applies to the first grid line, the second
to the second grid line and so on. *)
method color : Color.t Js.t Indexable.t Js.t Js.prop
method borderDash : line_dash Js.prop
method borderDashOffset : line_dash_offset Js.prop
method lineWidth : int Indexable.t Js.t Js.prop
method drawBorder : bool Js.t Js.prop
method drawOnChartArea : bool Js.t Js.prop
method drawTicks : bool Js.t Js.prop
method tickMarkLength : int Js.prop
* Stroke width of the grid line for the first index ( index 0 ) .
method zeroLineWidth : int Js.prop
* Stroke color of the grid line for the first index ( index 0 ) .
method zeroLineColor : Color.t Js.t Js.prop
* Length and spacing of dashes of the grid line
for the first index ( index 0 ) .
for the first index (index 0). *)
method zeroLineBorderDash : line_dash Js.prop
* Offset for line dashes of the grid line for the first index ( index 0 ) .
method zeroLineBorderDashOffset : line_dash_offset Js.prop
method offsetGridLines : bool Js.t Js.prop
end
class type axis =
object
method _type : Js.js_string Js.t Js.prop
* Controls the axis global visibility
( visible when [ true ] , hidden when [ false ] ) .
When display is [ ' auto ' ] , the axis is visible only
if at least one associated dataset is visible .
(visible when [true], hidden when [false]).
When display is ['auto'], the axis is visible only
if at least one associated dataset is visible. *)
method display : Axis_display.t Js.t Js.prop
method weight : float Js.optdef_prop
method beforeUpdate : ('a Js.t -> unit) Js.callback Js.optdef_prop
method beforeSetDimensions : ('a Js.t -> unit) Js.callback Js.optdef_prop
method afterSetDimensions : ('a Js.t -> unit) Js.callback Js.optdef_prop
method beforeDataLimits : ('a Js.t -> unit) Js.callback Js.optdef_prop
method afterDataLimits : ('a Js.t -> unit) Js.callback Js.optdef_prop
method beforeBuildTicks : ('a Js.t -> unit) Js.callback Js.optdef_prop
method afterBuildTicks :
('a Js.t -> 'tick Js.js_array Js.t -> 'tick Js.js_array Js.t) Js.callback
Js.optdef_prop
method beforeTickToLabelConversion : ('a Js.t -> unit) Js.callback Js.optdef_prop
method afterTickToLabelConversion : ('a Js.t -> unit) Js.callback Js.optdef_prop
method beforeCalculateTickRotation : ('a Js.t -> unit) Js.callback Js.optdef_prop
method afterCalculateTickRotation : ('a Js.t -> unit) Js.callback Js.optdef_prop
method beforeFit : ('a Js.t -> unit) Js.callback Js.optdef_prop
method afterFit : ('a Js.t -> unit) Js.callback Js.optdef_prop
method afterUpdate : ('a Js.t -> unit) Js.callback Js.optdef_prop
end
val empty_minor_ticks : unit -> minorTicks Js.t
val empty_major_ticks : unit -> majorTicks Js.t
val empty_ticks : unit -> ticks Js.t
val empty_scale_label : unit -> scaleLabel Js.t
val empty_grid_lines : unit -> gridLines Js.t
* { 2 Cartesian axes }
class type cartesianTicks =
object
inherit ticks
method autoSkip : bool Js.t Js.prop
method autoSkipPadding : int Js.prop
method labelOffset : int Js.prop
method maxRotation : int Js.prop
method minRotation : int Js.prop
method mirror : bool Js.prop
method padding : int Js.prop
end
class type cartesianAxis =
object
inherit axis
method position : Position.t Js.t Js.prop
method offset : bool Js.t Js.prop
method id : Js.js_string Js.t Js.prop
method gridLines : gridLines Js.t Js.prop
method scaleLabel : scaleLabel Js.t Js.prop
method _ticks : cartesianTicks Js.t Js.prop
end
val coerce_cartesian_axis : #cartesianAxis Js.t -> cartesianAxis Js.t
val empty_cartesian_axis : unit -> cartesianAxis Js.t
* { 3 Category axis }
class type categoryTicks =
object
inherit cartesianTicks
method labels : Js.js_string Js.t Js.optdef_prop
method min : Js.js_string Js.t Js.optdef Js.prop
method max : Js.js_string Js.t Js.optdef Js.prop
end
class type categoryAxis =
object
inherit cartesianAxis
method ticks : categoryTicks Js.t Js.prop
end
val empty_category_ticks : unit -> categoryTicks Js.t
val empty_category_axis : unit -> categoryAxis Js.t
* { 3 Linear axis }
class type linearTicks =
object
inherit cartesianTicks
method beginAtZero : bool Js.t Js.optdef_prop
method min : float Js.optdef Js.prop
method max : float Js.optdef Js.prop
method maxTicksLimit : int Js.prop
method precision : int Js.optdef_prop
method stepSize : int Js.optdef_prop
method suggestedMax : float Js.optdef Js.prop
method suggestedMin : float Js.optdef Js.prop
end
class type linearAxis =
object
inherit cartesianAxis
method ticks : linearTicks Js.t Js.prop
end
val empty_linear_ticks : unit -> linearTicks Js.t
val empty_linear_axis : unit -> linearAxis Js.t
* { 3 Logarithmic axis }
class type logarithmicTicks =
object
inherit cartesianTicks
method min : float Js.optdef Js.prop
method max : float Js.optdef Js.prop
end
class type logarithmicAxis =
object
inherit cartesianAxis
method ticks : logarithmicTicks Js.t Js.prop
end
val empty_logarithmic_ticks : unit -> logarithmicTicks Js.t
val empty_logarithmic_axis : unit -> logarithmicAxis Js.t
* { 3 Time axis }
class type timeDisplayFormats =
object
method millisecond : Js.js_string Js.t Js.prop
method second : Js.js_string Js.t Js.prop
method minute : Js.js_string Js.t Js.prop
method hour : Js.js_string Js.t Js.prop
method day : Js.js_string Js.t Js.prop
method week : Js.js_string Js.t Js.prop
method month : Js.js_string Js.t Js.prop
method quarter : Js.js_string Js.t Js.prop
method year : Js.js_string Js.t Js.prop
end
class type timeTicks =
object
inherit cartesianTicks
method source : Time_ticks_source.t Js.t Js.prop
end
class type timeOptions =
object
method displayFormats : timeDisplayFormats Js.t Js.optdef_prop
* If [ true ] and the unit is set to ' week ' , then the first day
of the week will be Monday . Otherwise , it will be Sunday .
of the week will be Monday. Otherwise, it will be Sunday. *)
method isoWeekday : bool Js.t Js.prop
method max : Time.t Js.t Js.optdef_prop
method min : Time.t Js.t Js.optdef_prop
method _parser : Time_parser.t Js.t Js.optdef_prop
method round : Time_unit.t Js.t Or_false.t Js.t Js.prop
method tooltipFormat : Js.js_string Js.t Js.optdef_prop
method unit : Time_unit.t Js.t Or_false.t Js.t Js.prop
method stepSize : int Js.prop
method minUnit : Time_unit.t Js.t Js.prop
end
class type timeAxis =
object
inherit cartesianAxis
method ticks : timeTicks Js.t Js.prop
method time : timeOptions Js.t Js.prop
method distribution : Time_distribution.t Js.t Js.prop
* The bounds property controls the scale boundary strategy
( bypassed by [ ] time options ) .
[ data ] : makes sure data are fully visible , labels outside are removed
[ ticks ] : makes sure ticks are fully visible , data outside are truncated
(bypassed by [min]/[max] time options).
[data]: makes sure data are fully visible, labels outside are removed
[ticks]: makes sure ticks are fully visible, data outside are truncated *)
method bounds : Time_bounds.t Js.t Js.prop
end
val empty_time_display_formats : unit -> timeDisplayFormats Js.t
val empty_time_ticks : unit -> timeTicks Js.t
val empty_time_options : unit -> timeOptions Js.t
val empty_time_axis : unit -> timeAxis Js.t
class type dataset =
object
method _type : Js.js_string Js.t Js.optdef_prop
method label : Js.js_string Js.t Js.prop
method hidden : bool Js.t Js.optdef_prop
end
val coerce_dataset : #dataset Js.t -> dataset Js.t
class type data =
object
method datasets : #dataset Js.t Js.js_array Js.t Js.prop
method labels : 'a Js.js_array Js.t Js.optdef_prop
method xLabels : 'a Js.js_array Js.t Js.optdef_prop
method yLabels : 'a Js.js_array Js.t Js.optdef_prop
end
val empty_data : unit -> data Js.t
class type updateConfig =
object
method duration : int Js.optdef_prop
method _lazy : bool Js.t Js.optdef_prop
method easing : Easing.t Js.optdef_prop
end
class type animationItem =
object
method chart : chart Js.t Js.readonly_prop
method currentStep : float Js.readonly_prop
method numSteps : float Js.readonly_prop
method render : chart Js.t -> animationItem Js.t -> unit Js.meth
method onAnimationProgress : animationItem Js.t -> unit Js.meth
method onAnimationComplete : animationItem Js.t -> unit Js.meth
end
and animation =
object
method duration : int Js.prop
method easing : Easing.t Js.prop
method onProgress : (animationItem Js.t -> unit) Js.callback Js.opt Js.prop
method onComplete : (animationItem Js.t -> unit) Js.callback Js.opt Js.prop
end
* { 2 Layout }
and layout =
object
method padding : Padding.t Js.prop
FIXME this interface differs between and other chart types
and legendItem =
object
method text : Js.js_string Js.t Js.prop
FIXME seems it can be Indexable & Scriptable dependent on chart type
method fillStyle : Color.t Js.t Js.prop
method hidden : bool Js.t Js.prop
method lineCap : Line_cap.t Js.t Js.optdef_prop
method lineDash : line_dash Js.optdef_prop
method lineDashOffset : line_dash_offset Js.optdef_prop
method lineJoin : Line_join.t Js.t Js.optdef_prop
method lineWidth : int Js.prop
method strokeStyle : Color.t Js.t Js.prop
* Point style of the legend box ( only used if usePointStyle is true )
method pointStyle : Point_style.t Js.t Js.optdef_prop
method datasetIndex : int Js.prop
end
and legendLabels =
object ('self)
method boxWidth : int Js.prop
method fontSize : int Js.optdef_prop
method fontStyle : Js.js_string Js.t Js.optdef_prop
method fontColor : Color.t Js.t Js.optdef_prop
method fontFamily : Js.js_string Js.t Js.optdef_prop
method padding : int Js.prop
method generateLabels :
(chart Js.t -> legendItem Js.t Js.js_array Js.t) Js.callback Js.prop
* Filters legend items out of the legend . Receives 2 parameters ,
a Legend Item and the chart data .
a Legend Item and the chart data. *)
method filter :
('self, legendItem Js.t -> data Js.t -> bool Js.t) Js.meth_callback Js.optdef_prop
* Label style will match corresponding point style
( size is based on fontSize , boxWidth is not used in this case ) .
(size is based on fontSize, boxWidth is not used in this case). *)
method usePointStyle : bool Js.t Js.optdef_prop
end
and legend =
object
method display : bool Js.t Js.prop
method position : Position.t Js.t Js.prop
* Marks that this box should take the full width of the canvas
( pushing down other boxes ) . This is unlikely to need to be changed
in day - to - day use .
(pushing down other boxes). This is unlikely to need to be changed
in day-to-day use. *)
method fullWidth : bool Js.t Js.prop
method onClick :
(chart, Dom_html.event Js.t -> legendItem Js.t -> unit) Js.meth_callback
Js.optdef_prop
method onHover :
(chart, Dom_html.event Js.t -> legendItem Js.t -> unit) Js.meth_callback
Js.optdef_prop
method onLeave :
(chart, Dom_html.event Js.t -> legendItem Js.t -> unit) Js.meth_callback
Js.optdef_prop
method reverse : bool Js.t Js.prop
method labels : legendLabels Js.t Js.prop
end
* { 2 Title }
and title =
object
method display : bool Js.t Js.prop
method position : Position.t Js.t Js.prop
method fontSize : int Js.optdef_prop
method fontFamily : Js.js_string Js.t Js.optdef_prop
method fontColor : Js.js_string Js.t Js.optdef_prop
method fontStyle : Js.js_string Js.t Js.optdef_prop
method fullWidth : bool Js.t Js.prop
method padding : int Js.prop
method lineHeight : Line_height.t Js.t Js.optdef_prop
method text : Js.js_string Js.t Indexable.t Js.t Js.prop
end
* { 2 Tooltip }
and tooltipItem =
object
method label : Js.js_string Js.t Js.readonly_prop
method value : Js.js_string Js.t Js.readonly_prop
method datasetIndex : int Js.readonly_prop
method index : int Js.readonly_prop
method x : float Js.readonly_prop
method y : float Js.readonly_prop
end
and tooltipBodyLines =
object
method before : Js.js_string Js.t Js.js_array Js.t Js.readonly_prop
method lines : Js.js_string Js.t Js.js_array Js.t Js.readonly_prop
method after : Js.js_string Js.t Js.js_array Js.t Js.readonly_prop
end
and tooltipModel =
object
method dataPoints : tooltipItem Js.t Js.js_array Js.t Js.readonly_prop
method xPadding : int Js.readonly_prop
method yPadding : int Js.readonly_prop
method xAlign : Js.js_string Js.t Js.readonly_prop
method yAlign : Js.js_string Js.t Js.readonly_prop
method x : float Js.readonly_prop
method y : float Js.readonly_prop
method width : float Js.readonly_prop
method height : float Js.readonly_prop
method caretX : int Js.readonly_prop
method caretY : int Js.readonly_prop
* Body .
The body lines that need to be rendered .
Each object contains 3 parameters .
[ before ] - lines of text before the line with the color square
[ lines ] - lines of text to render as the main item with color square
[ after ] - lines of text to render after the main lines .
The body lines that need to be rendered.
Each object contains 3 parameters.
[before] - lines of text before the line with the color square
[lines] - lines of text to render as the main item with color square
[after] - lines of text to render after the main lines. *)
method body : tooltipBodyLines Js.t Js.readonly_prop
method beforeBody : Js.js_string Js.t Js.js_array Js.t Js.readonly_prop
method afterBody : Js.js_string Js.t Js.js_array Js.t Js.readonly_prop
method bodyFontColor : Color.t Js.t Js.readonly_prop
method __bodyFontFamily : Js.js_string Js.t Js.readonly_prop
method __bodyFontStyle : Js.js_string Js.t Js.readonly_prop
method __bodyAlign : Js.js_string Js.t Js.readonly_prop
method bodyFontSize : int Js.readonly_prop
method bodySpacing : int Js.readonly_prop
method title : Js.js_string Js.t Indexable.t Js.readonly_prop
method titleFontColor : Color.t Js.t Js.readonly_prop
method __titleFontFamily : Js.js_string Js.t Js.readonly_prop
method __titleFontStyle : Js.js_string Js.t Js.readonly_prop
method titleFontSize : int Js.readonly_prop
method __titleAlign : Js.js_string Js.t Js.readonly_prop
method titleSpacing : int Js.readonly_prop
method titleMarginBottom : int Js.readonly_prop
method footer : Js.js_string Js.t Indexable.t Js.readonly_prop
method footerFontColor : Color.t Js.t Js.readonly_prop
method __footerFontFamily : Js.js_string Js.t Js.readonly_prop
method __footerFontStyle : Js.js_string Js.t Js.readonly_prop
method footerFontSize : int Js.readonly_prop
method __footerAlign : Js.js_string Js.t Js.readonly_prop
method footerSpacing : int Js.readonly_prop
method footerMarginTop : int Js.readonly_prop
method caretSize : int Js.readonly_prop
method caretPadding : int Js.readonly_prop
method cornerRadius : int Js.readonly_prop
method backgroundColor : Color.t Js.t Js.readonly_prop
method labelColors : Color.t Js.t Js.js_array Js.t Js.readonly_prop
method labelTextColors : Color.t Js.t Js.js_array Js.t Js.readonly_prop
* Zero opacity is a hidden tooltip .
method opacity : float Js.readonly_prop
method legendColorBackground : Color.t Js.t Js.readonly_prop
method displayColors : bool Js.t Js.readonly_prop
method borderColor : Color.t Js.t Js.readonly_prop
method borderWidth : int Js.readonly_prop
end
and tooltipCallbacks =
object
method beforeTitle :
(tooltip Js.t, tooltipItem Js.js_array Js.t, data Js.t) tooltip_cb Js.prop
method title :
(tooltip Js.t, tooltipItem Js.js_array Js.t, data Js.t) tooltip_cb Js.prop
method afterTitle :
(tooltip Js.t, tooltipItem Js.js_array Js.t, data Js.t) tooltip_cb Js.prop
method beforeBody :
(tooltip Js.t, tooltipItem Js.js_array Js.t, data Js.t) tooltip_cb Js.prop
method beforeLabel : (tooltip Js.t, tooltipItem Js.t, data Js.t) tooltip_cb Js.prop
method label : (tooltip Js.t, tooltipItem Js.t, data Js.t) tooltip_cb Js.prop
method labelColor : (tooltip Js.t, tooltipItem Js.t, chart Js.t) tooltip_cb Js.prop
method labelTextColor :
(tooltip Js.t, tooltipItem Js.t, chart Js.t) tooltip_cb Js.prop
method afterLabel : (tooltip Js.t, tooltipItem Js.t, data Js.t) tooltip_cb Js.prop
method afterBody :
(tooltip Js.t, tooltipItem Js.t Js.js_array Js.t, data Js.t) tooltip_cb Js.prop
method beforeFooter :
(tooltip Js.t, tooltipItem Js.js_array Js.t, data Js.t) tooltip_cb Js.prop
method footer :
(tooltip Js.t, tooltipItem Js.js_array Js.t, data Js.t) tooltip_cb Js.prop
method afterFooter :
(tooltip Js.t, tooltipItem Js.js_array Js.t, data Js.t) tooltip_cb Js.prop
end
and tooltip =
object ('self)
method enabled : bool Js.t Js.prop
method custom : (tooltipModel Js.t -> unit) Js.callback Js.opt Js.prop
method mode : Interaction_mode.t Js.t Js.prop
method intersect : bool Js.t Js.prop
method axis : Hover_axis.t Js.t Js.prop
method position : Tooltip_position.t Js.prop
method callbacks : tooltipCallbacks Js.t Js.prop
method itemSort :
('self, tooltipItem Js.t -> tooltipItem Js.t -> data Js.t -> int) Js.meth_callback
Js.optdef_prop
method filter :
('self, tooltipItem Js.t -> data Js.t -> bool Js.t) Js.meth_callback Js.optdef_prop
method backgroundColor : Color.t Js.t Js.prop
method titleFontFamily : Js.js_string Js.t Js.optdef_prop
method titleFontSize : int Js.optdef_prop
method titleFontStyle : Js.js_string Js.t Js.optdef_prop
method titleFontColor : Color.t Js.t Js.optdef_prop
method titleSpacing : int Js.prop
method titleMarginBottom : int Js.prop
method bodyFontFamily : Js.js_string Js.t Js.optdef_prop
method bodyFontSize : int Js.optdef_prop
method bodyFontStyle : Js.js_string Js.t Js.optdef_prop
method bodyFontColor : Color.t Js.t Js.optdef_prop
method bodySpacing : int Js.prop
method footerFontFamily : Js.js_string Js.t Js.optdef_prop
method footerFontSize : int Js.optdef_prop
method footerFontStyle : Js.js_string Js.t Js.optdef_prop
method footerFontColor : Color.t Js.t Js.optdef_prop
method footerSpacing : int Js.prop
method footerMarginTop : int Js.prop
method xPadding : int Js.prop
method yPadding : int Js.prop
method caretPadding : int Js.prop
* Size , in px , of the tooltip arrow .
method caretSize : int Js.prop
method cornerRadius : int Js.prop
method multyKeyBackground : Color.t Js.t Js.prop
method displayColors : bool Js.t Js.prop
method borderColor : Color.t Js.t Js.prop
method borderWidth : int Js.prop
end
* { 2 Interactions }
and hover =
object
method mode : Interaction_mode.t Js.t Js.prop
method intersect : bool Js.t Js.prop
method axis : Hover_axis.t Js.t Js.prop
method animationDuration : int Js.prop
end
* { 2 Elements }
and pointElement =
object
method radius : int Js.prop
method pointStyle : Point_style.t Js.t Js.prop
method rotation : int Js.optdef_prop
method backgroundColor : Color.t Js.t Js.prop
method borderWidth : int Js.prop
method borderColor : Color.t Js.t Js.prop
method hitRadius : int Js.prop
method hoverRadius : int Js.prop
method hoverBorderWidth : int Js.prop
end
and lineElement =
object
* curve tension ( 0 for no curves ) .
method tension : float Js.prop
method backgroundColor : Color.t Js.t Js.prop
method borderWidth : int Js.prop
method borderColor : Color.t Js.t Js.prop
method borderCapStyle : Line_cap.t Js.t Js.prop
method borderDash : line_dash Js.prop
method borderDashOffset : line_dash_offset Js.prop
method borderJoinStyle : Line_join.t Js.t Js.prop
* [ true ] to keep control inside the chart ,
[ false ] for no restriction .
[false] for no restriction.*)
method capBezierPoints : bool Js.t Js.prop
method fill : Fill.t Js.t Js.prop
method stepped : bool Js.t Js.optdef_prop
end
and rectangleElement =
object
method backgroundColor : Js.js_string Js.prop
method borderWidth : int Js.prop
method borderColor : Color.t Js.t Js.prop
method borderSkipped : Position.t Js.t Js.prop
end
and arcElement =
object
method backgroundColor : Color.t Js.t Js.prop
method borderAlign : Js.js_string Js.t Js.prop
method borderColor : Color.t Js.t Js.prop
method borderWidth : int Js.prop
end
and elements =
object
method point : pointElement Js.t Js.prop
method line : lineElement Js.t Js.prop
method rectangle : rectangleElement Js.t Js.prop
method arc : arcElement Js.t Js.prop
end
* { 2 Options }
and chartSize =
object
method width : int Js.readonly_prop
method height : int Js.readonly_prop
end
* { 2 Chart }
and chartOptions =
object
* Chart.js animates charts out of the box .
A number of options are provided to configure how the animation
looks and how long it takes .
A number of options are provided to configure how the animation
looks and how long it takes. *)
method _animation : animation Js.t Js.prop
method layout : layout Js.t Js.prop
method legend : legend Js.t Js.prop
method title : title Js.t Js.prop
method hover : hover Js.t Js.prop
method tooltips : tooltip Js.t Js.prop
* While chart types provide settings to configure the styling
of each dataset , you sometimes want to style all datasets the same way .
A common example would be to stroke all of the bars in a bar chart with
the same colour but change the fill per dataset .
Options can be configured for four different types of elements : arc , lines ,
points , and rectangles . When set , these options apply to all objects
of that type unless specifically overridden by the configuration attached
to a dataset .
of each dataset, you sometimes want to style all datasets the same way.
A common example would be to stroke all of the bars in a bar chart with
the same colour but change the fill per dataset.
Options can be configured for four different types of elements: arc, lines,
points, and rectangles. When set, these options apply to all objects
of that type unless specifically overridden by the configuration attached
to a dataset. *)
method elements : elements Js.t Js.prop
method plugins : 'a Js.t Js.prop
method legendCallback : (chart Js.t -> Js.js_string Js.t) Js.callback Js.optdef_prop
method responsive : bool Js.t Js.prop
method responsiveAnimationDuration : int Js.prop
method maintainAspectRatio : bool Js.t Js.prop
* Canvas aspect ratio ( i.e. width / height , a value of 1
representing a square canvas ) . Note that this option is
ignored if the height is explicitly defined either as
attribute or via the style .
representing a square canvas). Note that this option is
ignored if the height is explicitly defined either as
attribute or via the style. *)
method aspectRatio : float Js.optdef_prop
* Called when a resize occurs . Gets passed two arguments :
the chart instance and the new size .
the chart instance and the new size. *)
method onResize :
(chart Js.t -> chartSize Js.t -> unit) Js.callback Js.opt Js.optdef_prop
method devicePixelRatio : float Js.optdef_prop
method events : Js.js_string Js.t Js.js_array Js.t Js.prop
method onHover :
( chart Js.t
, Dom_html.event Js.t -> 'a Js.t Js.js_array Js.t -> unit )
Js.meth_callback
Js.opt
Js.optdef_prop
method onClick :
( chart Js.t
, Dom_html.event Js.t -> 'a Js.t Js.js_array Js.t -> unit )
Js.meth_callback
Js.opt
Js.optdef_prop
end
and chartConfig =
object
method data : data Js.t Js.prop
method options : chartOptions Js.t Js.prop
method _type : Js.js_string Js.t Js.prop
end
and chart =
object ('self)
method id : int Js.readonly_prop
method height : int Js.readonly_prop
method width : int Js.readonly_prop
method offsetX : int Js.readonly_prop
method offsetY : int Js.readonly_prop
method borderWidth : int Js.readonly_prop
method animating : bool Js.t Js.readonly_prop
method aspectRatio : float Js.readonly_prop
method canvas : Dom_html.canvasElement Js.t Js.readonly_prop
method ctx : Dom_html.canvasRenderingContext2D Js.t Js.readonly_prop
method data : data Js.t Js.prop
method _options : chartOptions Js.t Js.prop
method _config : chartConfig Js.t Js.prop
* Use this to destroy any chart instances that are created .
This will clean up any references stored to the chart object within Chart.js ,
along with any associated event listeners attached by Chart.js .
This must be called before the canvas is reused for a new chart .
This will clean up any references stored to the chart object within Chart.js,
along with any associated event listeners attached by Chart.js.
This must be called before the canvas is reused for a new chart. *)
method destroy : unit Js.meth
method update : unit Js.meth
method update_withConfig : #updateConfig Js.t -> unit Js.meth
method reset : unit Js.meth
method render : unit Js.meth
method render_withConfig : #updateConfig Js.t -> unit Js.meth
method stop : 'self Js.t Js.meth
method resize : 'self Js.t Js.meth
method clear : 'self Js.t Js.meth
* This returns a base 64 encoded string of the chart in it 's current state .
method toBase64Image : Js.js_string Js.t Js.meth
method generateLegend : Js.js_string Js.t Js.meth
method getDatasetMeta : int -> 'a Js.t Js.meth
end
val empty_animation : unit -> animation Js.t
val empty_layout : unit -> layout Js.t
val empty_legend_labels : unit -> legendLabels Js.t
val empty_legend : unit -> legend Js.t
val empty_title : unit -> title Js.t
val empty_tooltip_model : unit -> tooltipModel Js.t
val empty_tooltip_callbacks : unit -> tooltipCallbacks Js.t
val empty_tooltip : unit -> tooltip Js.t
val empty_hover : unit -> hover Js.t
val empty_point_element : unit -> pointElement Js.t
val empty_line_element : unit -> lineElement Js.t
val empty_rectangle_element : unit -> rectangleElement Js.t
val empty_arc_element : unit -> arcElement Js.t
val empty_elements : unit -> elements Js.t
val empty_update_config : unit -> updateConfig Js.t
class type ['a] lineOptionContext =
object
method chart : lineChart Js.t Js.readonly_prop
method dataIndex : int Js.readonly_prop
method dataset : 'a lineDataset Js.t Js.readonly_prop
method datasetIndex : int Js.readonly_prop
end
and lineScales =
object
method xAxes : #cartesianAxis Js.t Js.js_array Js.t Js.prop
method yAxes : #cartesianAxis Js.t Js.js_array Js.t Js.prop
end
and lineOptions =
object
inherit chartOptions
method animation : animation Js.t Js.prop
method scales : lineScales Js.t Js.prop
method showLines : bool Js.t Js.prop
* If [ false ] , NaN data causes a break in the line .
method spanGaps : bool Js.t Js.prop
end
and lineConfig =
object
method data : data Js.t Js.prop
method options : lineOptions Js.t Js.prop
method _type : Js.js_string Js.t Js.prop
end
and ['a] lineDataset =
object
inherit dataset
method data : 'a Js.js_array Js.t Js.prop
* { 2 General }
method xAxisID : Js.js_string Js.t Js.optdef_prop
method yAxisID : Js.js_string Js.t Js.optdef_prop
* { 2 Point styling }
method pointBackgroundColor :
('a lineOptionContext Js.t, Color.t Js.t) Scriptable_indexable.t Js.t
Js.optdef_prop
method pointBorderColor :
('a lineOptionContext Js.t, Color.t Js.t) Scriptable_indexable.t Js.t
Js.optdef_prop
method pointBorderWidth :
('a lineOptionContext Js.t, int) Scriptable_indexable.t Js.t Js.optdef_prop
method pointHitRadius :
('a lineOptionContext Js.t, int) Scriptable_indexable.t Js.t Js.optdef_prop
method pointRadius :
('a lineOptionContext Js.t, int) Scriptable_indexable.t Js.t Js.optdef_prop
method pointRotation :
('a lineOptionContext Js.t, int) Scriptable_indexable.t Js.t Js.optdef_prop
method pointStyle : Point_style.t Js.t Js.optdef_prop
* { 2 Line styling }
method backgroundColor : Color.t Js.t Js.optdef_prop
* style of the line .
method borderCapStyle : Line_cap.t Js.t Js.optdef_prop
method borderColor : Color.t Js.t Js.optdef_prop
method borderDash : line_dash Js.optdef_prop
method borderDashOffset : line_dash_offset Js.optdef_prop
method borderJoinStyle : Line_join.t Js.t Js.optdef_prop
method borderWidth : int Js.optdef_prop
method fill : Line_fill.t Js.t Js.optdef_prop
* curve tension of the line . Set to 0 to draw straightlines .
This option is ignored if monotone cubic interpolation is used .
This option is ignored if monotone cubic interpolation is used. *)
method lineTension : float Js.optdef_prop
method showLine : bool Js.t Js.optdef_prop
* If [ true ] , lines will be drawn between points with no or null data .
If [ false ] , points with NaN data will create a break in the line .
If [false], points with NaN data will create a break in the line. *)
method spanGaps : bool Js.t Js.optdef_prop
* { 2 Interactions }
method pointHoverBackgroundColor :
('a lineOptionContext Js.t, Color.t Js.t) Scriptable_indexable.t Js.t
Js.optdef_prop
method pointHoverBorderColor :
('a lineOptionContext Js.t, Color.t Js.t) Scriptable_indexable.t Js.t
Js.optdef_prop
method pointHoverBorderWidth :
('a lineOptionContext Js.t, int) Scriptable_indexable.t Js.t Js.optdef_prop
method pointHoverRadius :
('a lineOptionContext Js.t, int) Scriptable_indexable.t Js.t Js.optdef_prop
* { 2 Cubic Interpolation Mode }
method cubicInterpolationMode : Interpolation_mode.t Js.t Js.optdef_prop
* { 2 Stepped Line }
* The following values are supported for steppedLine .
[ false ] : No Step Interpolation ( default )
[ true ] : Step - before Interpolation ( eq . ' before ' )
[ ' before ' ] : Step - before Interpolation
[ ' after ' ] : Step - after Interpolation
[ ' middle ' ] : Step - middle Interpolation
If the [ steppedLine ] value is set to anything other than [ false ] ,
[ lineTension ] will be ignored .
[false]: No Step Interpolation (default)
[true]: Step-before Interpolation (eq. 'before')
['before']: Step-before Interpolation
['after']: Step-after Interpolation
['middle']: Step-middle Interpolation
If the [steppedLine] value is set to anything other than [false],
[lineTension] will be ignored.*)
method steppedLine : Stepped_line.t Js.t Js.optdef_prop
end
and lineChart =
object
inherit chart
method options : lineOptions Js.t Js.prop
method config : lineConfig Js.t Js.prop
end
val empty_line_scales : unit -> lineScales Js.t
val empty_line_options : unit -> lineOptions Js.t
val empty_line_dataset : unit -> 'a lineDataset Js.t
class type barAxis =
object
* Percent ( 0 - 1 ) of the available width each bar should be within
the category width . 1.0 will take the whole category width and
put the bars right next to each other .
the category width. 1.0 will take the whole category width and
put the bars right next to each other. *)
method barPercentage : float Js.prop
method categoryPercentage : float Js.prop
method barThickness : Bar_thickness.t Js.t Js.optdef_prop
method maxBarThickness : float Js.optdef_prop
method minBarLength : float Js.optdef_prop
method stacked : bool Js.t Js.optdef_prop
end
class type cateroryBarAxis =
object
inherit categoryAxis
inherit barAxis
end
class type linearBarAxis =
object
inherit linearAxis
inherit barAxis
end
class type logarithmicBarAxis =
object
inherit logarithmicAxis
inherit barAxis
end
class type timeBarAxis =
object
inherit timeAxis
inherit barAxis
end
class type barScales =
object
method xAxes : #barAxis Js.t Js.js_array Js.t Js.prop
method yAxes : #barAxis Js.t Js.js_array Js.t Js.prop
end
class type ['a] barOptionContext =
object
method chart : barChart Js.t Js.readonly_prop
method dataIndex : int Js.readonly_prop
method dataset : 'a barDataset Js.t Js.readonly_prop
method datasetIndex : int Js.readonly_prop
end
and barOptions =
object
inherit chartOptions
method animation : animation Js.t Js.prop
method scales : barScales Js.t Js.prop
end
and barConfig =
object
method data : data Js.t Js.prop
method options : barOptions Js.t Js.prop
method _type : Js.js_string Js.t Js.prop
end
and ['a] barDataset =
object
inherit dataset
method data : 'a Js.js_array Js.t Js.prop
* { 2 General }
method xAxisID : Js.js_string Js.t Js.optdef_prop
method yAxisID : Js.js_string Js.t Js.optdef_prop
method backgroundColor :
('a barOptionContext Js.t, Color.t Js.t) Scriptable_indexable.t Js.t Js.optdef_prop
method borderColor :
('a barOptionContext Js.t, Color.t Js.t) Scriptable_indexable.t Js.t Js.optdef_prop
method borderSkipped :
('a barOptionContext Js.t, Position.t Js.t Or_false.t Js.t) Scriptable_indexable.t
Js.t
Js.optdef_prop
* The bar border width ( in pixels ) .
If this value is a number , it is applied to all sides of the rectangle
( left , top , right , bottom ) , except [ ] . If this value is
an object , the [ left ] property defines the left border width . Similarly
the [ right ] , [ top ] and [ bottom ] properties can also be specified .
Omitted borders and [ borderSkipped ] are skipped .
If this value is a number, it is applied to all sides of the rectangle
(left, top, right, bottom), except [borderSkipped]. If this value is
an object, the [left] property defines the left border width. Similarly
the [right], [top] and [bottom] properties can also be specified.
Omitted borders and [borderSkipped] are skipped. *)
method borderWidth :
('a barOptionContext Js.t, Padding.t Js.t) Scriptable_indexable.t Js.t
Js.optdef_prop
* { 2 Interactions }
All these values , if undefined , fallback to the associated
[ elements.rectangle . * ] options .
All these values, if undefined, fallback to the associated
[elements.rectangle.*] options. *)
method hoverBackgroundColor : Color.t Js.t Indexable.t Js.t Js.optdef_prop
method hoverBorderColor : Color.t Js.t Indexable.t Js.t Js.optdef_prop
method hoverBorderWidth : Color.t Js.t Indexable.t Js.t Js.optdef_prop
method stack : Js.js_string Js.t Js.optdef_prop
end
and barChart =
object
inherit chart
method options : barOptions Js.t Js.prop
method config : barConfig Js.t Js.prop
end
val empty_bar_axis : unit -> cateroryBarAxis Js.t
val empty_linear_bar_axis : unit -> linearBarAxis Js.t
val empty_logarithmic_bar_axis : unit -> logarithmicBarAxis Js.t
val empty_time_bar_axis : unit -> timeBarAxis Js.t
val empty_bar_scales : unit -> barScales Js.t
val empty_bar_options : unit -> barOptions Js.t
val empty_bar_dataset : unit -> 'a barDataset Js.t
* { 2 Pie Chart }
class type ['a] pieOptionContext =
object
method chart : pieChart Js.t Js.readonly_prop
method dataIndex : int Js.readonly_prop
method dataset : 'a pieDataset Js.t Js.readonly_prop
method datasetIndex : int Js.readonly_prop
end
and pieAnimation =
object
inherit animation
method animateRotate : bool Js.t Js.prop
method animateScale : bool Js.t Js.prop
end
and pieOptions =
object
inherit chartOptions
method animation : pieAnimation Js.t Js.prop
method cutoutPercentage : float Js.prop
method rotation : float Js.prop
method circumference : float Js.prop
end
and pieConfig =
object
method data : data Js.t Js.prop
method options : pieOptions Js.t Js.prop
method _type : Js.js_string Js.t Js.prop
end
and ['a] pieDataset =
object
inherit dataset
method data : 'a Js.js_array Js.t Js.prop
method backgroundColor :
('a pieOptionContext Js.t, Color.t Js.t) Scriptable_indexable.t Js.t Js.optdef_prop
method borderColor :
('a pieOptionContext Js.t, Color.t Js.t) Scriptable_indexable.t Js.t Js.optdef_prop
method borderWidth :
('a pieOptionContext Js.t, int) Scriptable_indexable.t Js.t Js.optdef_prop
method weight : float Js.optdef_prop
* { 2 Interactions }
method hoverBackgroundColor :
('a pieOptionContext Js.t, Color.t Js.t) Scriptable_indexable.t Js.t Js.optdef_prop
method hoverBorderColor :
('a pieOptionContext Js.t, Color.t Js.t) Scriptable_indexable.t Js.t Js.optdef_prop
method hoverBorderWidth :
('a pieOptionContext Js.t, int) Scriptable_indexable.t Js.t Js.optdef_prop
method borderAlign : Pie_border_align.t Js.t Js.optdef_prop
end
and pieChart =
object
inherit chart
method options : pieOptions Js.t Js.prop
method config : pieConfig Js.t Js.prop
end
val empty_pie_animation : unit -> pieAnimation Js.t
val empty_pie_options : unit -> pieOptions Js.t
val empty_pie_dataset : unit -> 'a pieDataset Js.t
module Axis : sig
type 'a typ
val cartesian_category : categoryAxis typ
val cartesian_linear : linearAxis typ
val cartesian_logarithmic : logarithmicAxis typ
val cartesian_time : timeAxis typ
val of_string : string -> 'a typ
end
module Chart : sig
type 'a typ
val line : lineChart typ
val bar : barChart typ
val horizontal_bar : barChart typ
val pie : pieChart typ
val doughnut : pieChart typ
val of_string : string -> 'a typ
end
module CoerceTo : sig
val line : #chart Js.t -> lineChart Js.t Js.opt
val bar : #chart Js.t -> barChart Js.t Js.opt
val horizontalBar : #chart Js.t -> barChart Js.t Js.opt
val pie : #chart Js.t -> pieChart Js.t Js.opt
val doughnut : #chart Js.t -> pieChart Js.t Js.opt
val cartesianCategory : #axis Js.t -> categoryAxis Js.t Js.opt
val cartesianLinear : #axis Js.t -> linearAxis Js.t Js.opt
val cartesianLogarithmic : #axis Js.t -> logarithmicAxis Js.t Js.opt
val cartesianTime : #axis Js.t -> timeAxis Js.t Js.opt
end
val create_axis : 'a Axis.typ -> 'a Js.t
val chart_from_canvas :
'a Chart.typ
-> data Js.t
-> #chartOptions Js.t
-> Dom_html.canvasElement Js.t
-> 'a Js.t
val chart_from_ctx :
'a Chart.typ
-> data Js.t
-> #chartOptions Js.t
-> Dom_html.canvasRenderingContext2D Js.t
-> 'a Js.t
val chart_from_id : 'a Chart.typ -> data Js.t -> #chartOptions Js.t -> string -> 'a Js.t
|
93539d7598e887d0e6b565e9fc301fa5139facc17e4b1b7a485b574e3d0ffac7 | haskell/haskell-ide-engine | FunctionalLiquidSpec.hs | {-# LANGUAGE OverloadedStrings #-}
module FunctionalLiquidSpec where
import Control.Lens hiding (List)
import Control.Monad.IO.Class
import Data.Aeson
import Data.Default
import qualified Data.Text as T
import Language.Haskell.LSP.Test hiding (message)
import Language.Haskell.LSP.Types as LSP
import Language.Haskell.LSP.Types.Lens as LSP hiding (contents, error )
import Haskell.Ide.Engine.Config
import Test.Hspec
import TestUtils
import Utils
-- ---------------------------------------------------------------------
spec :: Spec
spec = describe "liquid haskell diagnostics" $ do
it "runs diagnostics on save, no liquid" $
runSession hieCommandExamplePlugin codeActionSupportCaps "test/testdata" $ do
doc <- openDoc "liquid/Evens.hs" "haskell"
diags@(reduceDiag:_) <- waitForDiagnostics
liftIO $ do
length diags `shouldBe` 2
reduceDiag ^. range `shouldBe` Range (Position 5 18) (Position 5 22)
reduceDiag ^. severity `shouldBe` Just DsHint
reduceDiag ^. code `shouldBe` Just (StringValue "Use negate")
reduceDiag ^. source `shouldBe` Just "hlint"
diags2hlint <- waitForDiagnostics
liftIO $ length diags2hlint `shouldBe` 2
sendNotification TextDocumentDidSave (DidSaveTextDocumentParams doc)
diags3@(d:_) <- waitForDiagnosticsSource "eg2"
liftIO $ do
length diags3 `shouldBe` 1
d ^. LSP.range `shouldBe` Range (Position 0 0) (Position 1 0)
d ^. LSP.severity `shouldBe` Nothing
d ^. LSP.code `shouldBe` Nothing
d ^. LSP.message `shouldBe` T.pack "Example plugin diagnostic, triggered byDiagnosticOnSave"
-- ---------------------------------
it "runs diagnostics on save, with liquid haskell" $
runSession hieCommand codeActionSupportCaps "test/testdata" $ do
-- runSessionWithConfig logConfig hieCommand codeActionSupportCaps "test/testdata" $ do
doc <- openDoc "liquid/Evens.hs" "haskell"
diags@(reduceDiag:_) <- waitForDiagnostics
liftIO $ show " "
liftIO $ do
length diags `shouldBe` 2
reduceDiag ^. range `shouldBe` Range (Position 5 18) (Position 5 22)
reduceDiag ^. severity `shouldBe` Just DsHint
reduceDiag ^. code `shouldBe` Just (StringValue "Use negate")
reduceDiag ^. source `shouldBe` Just "hlint"
-- Enable liquid haskell plugin and disable hlint
let config = def { liquidOn = True, hlintOn = False }
sendNotification WorkspaceDidChangeConfiguration (DidChangeConfigurationParams (toJSON config))
-- docItem <- getDocItem file languageId
sendNotification TextDocumentDidSave (DidSaveTextDocumentParams doc)
-- TODO: what does that test?
-- TODO: whether hlint is really disbabled?
-- TODO: @fendor, document or remove
-- diags2hlint <- waitForDiagnostics
-- liftIO $ show diags2hlint ` shouldBe ` " "
-- -- We turned hlint diagnostics off
liftIO $ length diags2hlint ` shouldBe ` 0
-- diags2liquid <- waitForDiagnostics
liftIO $ length diags2liquid ` shouldBe ` 0
liftIO $ show diags2liquid ` shouldBe ` " "
diags3@(d:_) <- waitForDiagnosticsSource "liquid"
liftIO $ show ` shouldBe ` " "
liftIO $ do
length diags3 `shouldBe` 1
d ^. range `shouldBe` Range (Position 8 0) (Position 8 11)
d ^. severity `shouldBe` Just DsError
d ^. code `shouldBe` Nothing
d ^. source `shouldBe` Just "liquid"
d ^. message `shouldSatisfy` T.isPrefixOf ("Error: Liquid Type Mismatch\n" <>
" Inferred type\n" <>
" VV : {v : GHC.Types.Int | v == 7}\n" <>
" \n" <>
" not a subtype of Required type\n" <>
" VV : {VV : GHC.Types.Int | VV mod 2 == 0}\n ")
-- ---------------------------------------------------------------------
| null | https://raw.githubusercontent.com/haskell/haskell-ide-engine/d84b84322ccac81bf4963983d55cc4e6e98ad418/test/functional/FunctionalLiquidSpec.hs | haskell | # LANGUAGE OverloadedStrings #
---------------------------------------------------------------------
---------------------------------
runSessionWithConfig logConfig hieCommand codeActionSupportCaps "test/testdata" $ do
Enable liquid haskell plugin and disable hlint
docItem <- getDocItem file languageId
TODO: what does that test?
TODO: whether hlint is really disbabled?
TODO: @fendor, document or remove
diags2hlint <- waitForDiagnostics
liftIO $ show diags2hlint ` shouldBe ` " "
-- We turned hlint diagnostics off
diags2liquid <- waitForDiagnostics
--------------------------------------------------------------------- |
module FunctionalLiquidSpec where
import Control.Lens hiding (List)
import Control.Monad.IO.Class
import Data.Aeson
import Data.Default
import qualified Data.Text as T
import Language.Haskell.LSP.Test hiding (message)
import Language.Haskell.LSP.Types as LSP
import Language.Haskell.LSP.Types.Lens as LSP hiding (contents, error )
import Haskell.Ide.Engine.Config
import Test.Hspec
import TestUtils
import Utils
spec :: Spec
spec = describe "liquid haskell diagnostics" $ do
it "runs diagnostics on save, no liquid" $
runSession hieCommandExamplePlugin codeActionSupportCaps "test/testdata" $ do
doc <- openDoc "liquid/Evens.hs" "haskell"
diags@(reduceDiag:_) <- waitForDiagnostics
liftIO $ do
length diags `shouldBe` 2
reduceDiag ^. range `shouldBe` Range (Position 5 18) (Position 5 22)
reduceDiag ^. severity `shouldBe` Just DsHint
reduceDiag ^. code `shouldBe` Just (StringValue "Use negate")
reduceDiag ^. source `shouldBe` Just "hlint"
diags2hlint <- waitForDiagnostics
liftIO $ length diags2hlint `shouldBe` 2
sendNotification TextDocumentDidSave (DidSaveTextDocumentParams doc)
diags3@(d:_) <- waitForDiagnosticsSource "eg2"
liftIO $ do
length diags3 `shouldBe` 1
d ^. LSP.range `shouldBe` Range (Position 0 0) (Position 1 0)
d ^. LSP.severity `shouldBe` Nothing
d ^. LSP.code `shouldBe` Nothing
d ^. LSP.message `shouldBe` T.pack "Example plugin diagnostic, triggered byDiagnosticOnSave"
it "runs diagnostics on save, with liquid haskell" $
runSession hieCommand codeActionSupportCaps "test/testdata" $ do
doc <- openDoc "liquid/Evens.hs" "haskell"
diags@(reduceDiag:_) <- waitForDiagnostics
liftIO $ show " "
liftIO $ do
length diags `shouldBe` 2
reduceDiag ^. range `shouldBe` Range (Position 5 18) (Position 5 22)
reduceDiag ^. severity `shouldBe` Just DsHint
reduceDiag ^. code `shouldBe` Just (StringValue "Use negate")
reduceDiag ^. source `shouldBe` Just "hlint"
let config = def { liquidOn = True, hlintOn = False }
sendNotification WorkspaceDidChangeConfiguration (DidChangeConfigurationParams (toJSON config))
sendNotification TextDocumentDidSave (DidSaveTextDocumentParams doc)
liftIO $ length diags2hlint ` shouldBe ` 0
liftIO $ length diags2liquid ` shouldBe ` 0
liftIO $ show diags2liquid ` shouldBe ` " "
diags3@(d:_) <- waitForDiagnosticsSource "liquid"
liftIO $ show ` shouldBe ` " "
liftIO $ do
length diags3 `shouldBe` 1
d ^. range `shouldBe` Range (Position 8 0) (Position 8 11)
d ^. severity `shouldBe` Just DsError
d ^. code `shouldBe` Nothing
d ^. source `shouldBe` Just "liquid"
d ^. message `shouldSatisfy` T.isPrefixOf ("Error: Liquid Type Mismatch\n" <>
" Inferred type\n" <>
" VV : {v : GHC.Types.Int | v == 7}\n" <>
" \n" <>
" not a subtype of Required type\n" <>
" VV : {VV : GHC.Types.Int | VV mod 2 == 0}\n ")
|
5622395c02b214a20bc388449bbdf8f4da56353be2a77f033bf8abdd5273f1bf | wilkerlucio/pathom | index_oir_example.cljc | (ns com.wsscode.pathom.book.connect.index-oir-example
(:require [com.wsscode.pathom.connect :as pc]))
(def indexes
(-> {}
(pc/add 'thing-by-id {::pc/input #{:id}
::pc/output [:id :name :color]})
(pc/add 'thing-by-name {::pc/input #{:name}
::pc/output [:id :name :color]})))
; index-oir:
'{:name {#{:id} #{thing-by-id}}
:color {#{:id} #{thing-by-id}
#{:name} #{thing-by-name}}
:id {#{:name} #{thing-by-name}}}
| null | https://raw.githubusercontent.com/wilkerlucio/pathom/4ec25055d3d156241e9174d68ec438c93c971b9b/docs-src/modules/ROOT/examples/com/wsscode/pathom/book/connect/index_oir_example.cljc | clojure | index-oir: | (ns com.wsscode.pathom.book.connect.index-oir-example
(:require [com.wsscode.pathom.connect :as pc]))
(def indexes
(-> {}
(pc/add 'thing-by-id {::pc/input #{:id}
::pc/output [:id :name :color]})
(pc/add 'thing-by-name {::pc/input #{:name}
::pc/output [:id :name :color]})))
'{:name {#{:id} #{thing-by-id}}
:color {#{:id} #{thing-by-id}
#{:name} #{thing-by-name}}
:id {#{:name} #{thing-by-name}}}
|
684472d91ac167273332e68c37ecf6ac60639b65bc15344015ac4780a3cb8f4c | fukamachi/lev | bindings.lisp | (in-package :lev)
#+lev-ev-full
(eval-when (:compile-toplevel :load-toplevel :execute)
(pushnew :lev-ev-periodic *features*)
(pushnew :lev-ev-stat *features*)
(pushnew :lev-ev-prepare *features*)
(pushnew :lev-ev-check *features*)
(pushnew :lev-ev-idle *features*)
(pushnew :lev-ev-fork *features*)
(pushnew :lev-ev-cleanup *features*)
#-windows
(pushnew :lev-ev-child *features*)
(pushnew :lev-ev-async *features*)
(pushnew :lev-ev-embed *features*)
(pushnew :lev-ev-signal *features*)
#+lev-not-yet
(pushnew :lev-ev-walk *features*))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defconstant #.(lispify "EV_MINPRI" 'constant) -2)
(defconstant #.(lispify "EV_MAXPRI" 'constant) +2))
(defconstant #.(lispify "EV_VERSION_MAJOR" 'constant) 4)
(defconstant #.(lispify "EV_VERSION_MINOR" 'constant) 15)
(defanonenum
(#.(lispify "EV_UNDEF" 'enumvalue) #xFFFFFFFF) ;; guaranteed to be invalid
(#.(lispify "EV_NONE" 'enumvalue) #x00) ;; no events
(#.(lispify "EV_READ" 'enumvalue) #x01) ;; ev_io detected read will not block
(#.(lispify "EV_WRITE" 'enumvalue) #x02) ;; ev_io detected write will not block
(#.(lispify "EV__IOFDSET" 'enumvalue) #x80) ;; internal use only
(#.(lispify "EV_TIMER" 'enumvalue) #x00000100) ;; timer timed out
(#.(lispify "EV_PERIODIC" 'enumvalue) #x00000200) ;; periodic timer timed out
(#.(lispify "EV_SIGNAL" 'enumvalue) #x00000400) ;; signal was received
(#.(lispify "EV_CHILD" 'enumvalue) #x00000800) ;; child/pid has status change
(#.(lispify "EV_STAT" 'enumvalue) #x00001000) ;; stat data changed
(#.(lispify "EV_IDLE" 'enumvalue) #x00002000) ;; event loop is idling
(#.(lispify "EV_PREPARE" 'enumvalue) #x00004000) ;; event loop about to poll
(#.(lispify "EV_CHECK" 'enumvalue) #x00008000) ;; event loop finished poll
(#.(lispify "EV_EMBED" 'enumvalue) #x00010000) ;; embedded event loop needs sweep
(#.(lispify "EV_FORK" 'enumvalue) #x00020000) ;; event loop resumed in child
(#.(lispify "EV_CLEANUP" 'enumvalue) #x00040000) ;; event loop resumed in child
(#.(lispify "EV_ASYNC" 'enumvalue) #x00080000) ;; async intra-loop signal
(#.(lispify "EV_CUSTOM" 'enumvalue) #x01000000) ;; for use by user code
(#.(lispify "EV_ERROR" 'enumvalue) #x80000000)) ;; sent when an error occurs
;; alias for type-detection
(defconstant #.(lispify "EV_IO" 'enumvalue) #.(lispify "EV_READ" 'enumvalue))
#+lev-ev-compat3
pre 4.0 API compatibility
(defconstant #.(lispify "EV_TIMEOUT" 'enumvalue) #.(lispify "EV_TIMER" 'enumvalue))
(eval-when (:compile-toplevel :load-toplevel)
;; shared by all watchers
(defparameter *ev-watcher-slots*
'((#.(lispify "active" 'slotname) :int) ;; private
(#.(lispify "pending" 'slotname) :int) ;; private
(#.(lispify "priority" 'slotname) :int) ;; private
(#.(lispify "data" 'slotname) :pointer) ;; rw
(#.(lispify "cb" 'slotname) :pointer)))
(defparameter *ev-watcher-list-slots*
`(,@*ev-watcher-slots*
;; private
(#.(lispify "next" 'slotname) :pointer)))
(defparameter *ev-watcher-time-slots*
`(,@*ev-watcher-slots*
;; private
(#.(lispify "at" 'slotname) :double))))
#.`(cffi:defcstruct #.(lispify "ev_watcher" 'classname)
,@*ev-watcher-slots*)
#.`(cffi:defcstruct #.(lispify "ev_watcher_list" 'classname)
,@*ev-watcher-list-slots*)
#.`(cffi:defcstruct #.(lispify "ev_watcher_time" 'classname)
,@*ev-watcher-time-slots*)
;; invoked when fd is either EV_READable or EV_WRITEable
revent EV_READ , EV_WRITE
#.`(cffi:defcstruct #.(lispify "ev_io" 'classname)
,@*ev-watcher-list-slots*
(#.(lispify "fd" 'slotname) :int) ;; ro
(#.(lispify "events" 'slotname) :int)) ;; ro
;; invoked after a specific time, repeatable (based on monotonic clock)
revent EV_TIMEOUT
#.`(cffi:defcstruct #.(lispify "ev_timer" 'classname)
,@*ev-watcher-time-slots*
(#.(lispify "repeat" 'slotname) :double)) ;; rw
;; invoked at some specific time, possibly repeating at regular intervals (based on UTC)
revent EV_PERIODIC
#.`(cffi:defcstruct #.(lispify "ev_periodic" 'classname)
,@*ev-watcher-time-slots*
(#.(lispify "offset" 'slotname) :double) ;; rw
(#.(lispify "interval" 'slotname) :double) ;; rw
(#.(lispify "reschedule_cb" 'slotname) :pointer)) ;; rw
;; invoked when the given signal has been received
revent EV_SIGNAL
#.`(cffi:defcstruct #.(lispify "ev_signal" 'classname)
,@*ev-watcher-list-slots*
(#.(lispify "signum" 'slotname) :int)) ;; ro
invoked when sigchld is received and waitpid indicates the given pid
revent
#.`(cffi:defcstruct #.(lispify "ev_child" 'classname)
,@*ev-watcher-list-slots*
(#.(lispify "flags" 'slotname) :int) ;; private
(#.(lispify "pid" 'slotname) :int) ;; ro
(#.(lispify "rpid" 'slotname) :int) ;; rw, holds the received pid
rw , holds the exit status , use the macros from sys / wait.h
;; invoked each time the stat data changes for a given path
revent EV_STAT
#+lev-ev-stat
#.`(cffi:defcstruct #.(lispify "ev_stat" 'classname)
,@*ev-watcher-list-slots*
(#.(lispify "timer" 'slotname) (:struct #.(lispify "ev_timer" 'classname))) ;; private
(#.(lispify "interval" 'slotname) :double) ;; ro
(#.(lispify "path" 'slotname) :string) ;; ro
(#.(lispify "prev" 'slotname) :pointer) ;; ro
(#.(lispify "attr" 'slotname) :pointer) ;; ro
wd for inotify , fd for kqueue
(#.(lispify "wd" 'slotname) :int))
;; invoked when the nothing else needs to be done, keeps the process from blocking
revent
#+lev-ev-idle
#.`(cffi:defcstruct #.(lispify "ev_idle" 'classname)
,@*ev-watcher-slots*)
;; invoked for each run of the mainloop, just before the blocking call
;; you can still change events in any way you like
;; revent EV_PREPARE
#.`(cffi:defcstruct #.(lispify "ev_prepare" 'classname)
,@*ev-watcher-slots*)
;; invoked for each run of the mainloop, just after the blocking call
revent EV_CHECK
#.`(cffi:defcstruct #.(lispify "ev_check" 'classname)
,@*ev-watcher-slots*)
#+lev-ev-fork
;; the callback gets invoked before check in the child process when a fork was detected
;; revent EV_FORK
#.`(cffi:defcstruct #.(lispify "ev_fork" 'classname)
,@*ev-watcher-slots*)
#+lev-ev-cleanup
;; is invoked just before the loop gets destroyed
revent EV_CLEANUP
#.`(cffi:defcstruct #.(lispify "ev_cleanup" 'classname)
,@*ev-watcher-slots*)
#+lev-ev-embed
;; used to embed an event loop inside another
;; the callback gets invoked when the event loop has handled events, and can be 0
#.`(cffi:defcstruct #.(lispify "ev_embed" 'classname)
,@*ev-watcher-slots*
(#.(lispify "other" 'slotname) :pointer) ;; ro
(#.(lispify "io" 'slotname) (:struct #.(lispify "ev_io" 'classname))) ;; private
(#.(lispify "prepare" 'slotname) (:struct #.(lispify "ev_prepare" 'classname))) ;; private
(#.(lispify "check" 'slotname) (:struct #.(lispify "ev_check" 'classname))) ;; unused
(#.(lispify "timer" 'slotname) (:struct #.(lispify "ev_timer" 'classname))) ;; unused
(#.(lispify "periodic" 'slotname) (:struct #.(lispify "ev_periodic" 'classname))) ;; unused
(#.(lispify "idle" 'slotname) (:struct #.(lispify "ev_idle" 'classname))) ;; unused
(#.(lispify "fork" 'slotname) (:struct #.(lispify "ev_fork" 'classname))) ;; private
#+lev-ev-cleanup
(#.(lispify "cleanup" 'slotname) (:struct #.(lispify "ev_cleanup" 'classname)))) ;; unused
#+lev-ev-async
;; invoked when somebody calls ev_async_send on the watcher
;; revent EV_ASYNC
#.`(cffi:defcstruct #.(lispify "ev_async" 'classname)
,@*ev-watcher-slots*
(#.(lispify "sent" 'slotname) :pointer)) ;; private
;; the presence of this union forces similar struct layout
#.`(cffi:defcunion #.(lispify "ev_any_watcher" 'classname)
(#.(lispify "w" 'slotname) (:struct #.(lispify "ev_watcher" 'classname)))
(#.(lispify "wl" 'slotname) (:struct #.(lispify "ev_watcher_list" 'classname)))
(#.(lispify "io" 'slotname) (:struct #.(lispify "ev_io" 'classname)))
(#.(lispify "timer" 'slotname) (:struct #.(lispify "ev_timer" 'classname)))
(#.(lispify "periodic" 'slotname) (:struct #.(lispify "ev_periodic" 'classname)))
(#.(lispify "signal" 'slotname) (:struct #.(lispify "ev_signal" 'classname)))
(#.(lispify "child" 'slotname) (:struct #.(lispify "ev_child" 'classname)))
#+lev-ev-stat
(#.(lispify "stat" 'slotname) (:struct #.(lispify "ev_stat" 'classname)))
#+lev-ev-idle
(#.(lispify "idle" 'slotname) (:struct #.(lispify "ev_idle" 'classname)))
(#.(lispify "prepare" 'slotname) (:struct #.(lispify "ev_prepare" 'classname)))
(#.(lispify "check" 'slotname) (:struct #.(lispify "ev_check" 'classname)))
#+lev-ev-fork
(#.(lispify "fork" 'slotname) (:struct #.(lispify "ev_fork" 'classname)))
#+lev-ev-cleanup
(#.(lispify "cleanup" 'slotname) (:struct #.(lispify "ev_cleanup" 'classname)))
#+lev-ev-embed
(#.(lispify "embed" 'slotname) (:struct #.(lispify "ev_embed" 'classname)))
#+lev-ev-async
(#.(lispify "async" 'slotname) (:struct #.(lispify "ev_async" 'classname))))
;; flag bits for ev_default_loop and ev_loop_new
(defanonenum
;; the default
(#.(lispify "EVFLAG_AUTO" 'enumvalue) #x00000000) ;; not quite a mask
;; flag bits
(#.(lispify "EVFLAG_NOENV" 'enumvalue) #x01000000) ;; do NOT consult environment
(#.(lispify "EVFLAG_FORKCHECK" 'enumvalue) #x02000000) ;; check for a fork in each iteration
;; debugging/feature disable
(#.(lispify "EVFLAG_NOINOTIFY" 'enumvalue) #x00100000) ;; do not attempt to use inotify
#+lev-ev-compat3
(#.(lispify "EVFLAG_NOSIGFD" 'enumvalue) 0) ;; compatibility to pre-3.9
(#.(lispify "EVFLAG_SIGNALFD" 'enumvalue) #x00200000) ;; attempt to use signalfd
(#.(lispify "EVFLAG_NOSIGMASK" 'enumvalue) #x00400000)) ;; avoid modifying the signal mask
;; method bits to be ored together
(defanonenum
(#.(lispify "EVBACKEND_SELECT" 'enumvalue) #x00000001) ;; about anywhere
(#.(lispify "EVBACKEND_POLL" 'enumvalue) #x00000002) ;; !win
(#.(lispify "EVBACKEND_EPOLL" 'enumvalue) #x00000004) ;; linux
bsd
solaris 8 , NYI
solaris 10
(#.(lispify "EVBACKEND_ALL" 'enumvalue) #x0000003F) ;; all known backends
(#.(lispify "EVBACKEND_MASK" 'enumvalue) #x0000FFFF)) ;; all future backends
(cffi:defcfun ("ev_version_major" #.(lispify "ev_version_major" 'function)) :int)
(cffi:defcfun ("ev_version_minor" #.(lispify "ev_version_minor" 'function)) :int)
(cffi:defcfun ("ev_supported_backends" #.(lispify "ev_supported_backends" 'function)) :unsigned-int)
(cffi:defcfun ("ev_recommended_backends" #.(lispify "ev_recommended_backends" 'function)) :unsigned-int)
(cffi:defcfun ("ev_embeddable_backends" #.(lispify "ev_embeddable_backends" 'function)) :unsigned-int)
(cffi:defcfun ("ev_time" #.(lispify "ev_time" 'function)) :double)
;; sleep for a while
(cffi:defcfun ("ev_sleep" #.(lispify "ev_sleep" 'function)) :void
(delay :double))
;; Sets the allocation function to use, works like realloc.
;; It is used to allocate and free memory.
If it returns zero when memory needs to be allocated , the library might abort
;; or take some potentially destructive action.
;; The default is your system realloc function.
(cffi:defcfun ("ev_set_allocator" #.(lispify "ev_set_allocator" 'function)) :void
(cb :pointer))
;; set the callback function to call on a
;; retryable syscall error
;; (such as failed select, poll, epoll_wait)
(cffi:defcfun ("ev_set_syserr_cb" #.(lispify "ev_set_syserr_cb" 'function)) :void
(cb :pointer))
;; the default loop is the only one that handles signals and child watchers
;; you can call this as often as you like
(cffi:defcfun ("ev_default_loop" #.(lispify "ev_default_loop" 'function)) :pointer
(flags :unsigned-int))
(cffi:defcfun ("ev_default_loop_uc_" #.(lispify "ev_default_loop_uc_" 'function)) :pointer)
(cffi:defcfun ("ev_is_default_loop" #.(lispify "ev_is_default_loop" 'function)) :int
(loop :pointer))
;; create and destroy alternative loops that don't handle signals
(cffi:defcfun ("ev_loop_new" #.(lispify "ev_loop_new" 'function)) :pointer
(flags :unsigned-int))
(cffi:defcfun ("ev_now" #.(lispify "ev_now" 'function)) :double
(loop :pointer))
;; destroy event loops, also works for the default loop
(cffi:defcfun ("ev_loop_destroy" #.(lispify "ev_loop_destroy" 'function)) :void
(loop :pointer))
;; this needs to be called after fork, to duplicate the loop
;; when you want to re-use it in the child
;; you can call it in either the parent or the child
;; you can actually call it at any time, anywhere :)
(cffi:defcfun ("ev_loop_fork" #.(lispify "ev_loop_fork" 'function)) :void
(loop :pointer))
;; backend in use by loop
(cffi:defcfun ("ev_backend" #.(lispify "ev_backend" 'function)) :unsigned-int
(loop :pointer))
;; update event loop time
(cffi:defcfun ("ev_now_update" #.(lispify "ev_now_update" 'function)) :void
(loop :pointer))
#+lev-ev-walk
;; walk (almost) all watchers in the loop of a given type, invoking the
;; callback on every such watcher. The callback might stop the watcher,
;; but do nothing else with the loop
(cffi:defcfun ("ev_walk" #.(lispify "ev_walk" 'function)) :void
(types :int)
(cb :pointer))
;; ev_run flags values
(defanonenum
(#.(lispify "EVRUN_NOWAIT" 'enumvalue) 1) ;; do not block/wait
(#.(lispify "EVRUN_ONCE" 'enumvalue) 2)) ;; block *once* only
;; ev_break how values
(defanonenum
undo unloop
(#.(lispify "EVBREAK_ONE" 'enumvalue) 1) ;; unloop once
(#.(lispify "EVBREAK_ALL" 'enumvalue) 2)) ;; unloop all loops
(cffi:defcfun ("ev_run" #.(lispify "ev_run" 'function)) :int
(loop :pointer)
(flags :int))
;; break out of the loop
(cffi:defcfun ("ev_break" #.(lispify "ev_break" 'function)) :void
(loop :pointer)
(how :int))
;; ref/unref can be used to add or remove a refcount on the mainloop. every watcher
keeps one reference . if you have a long - running watcher you never unregister that
;; should not keep ev_loop from running, unref() after starting, and ref() before stopping.
(cffi:defcfun ("ev_ref" #.(lispify "ev_ref" 'function)) :void
(loop :pointer))
(cffi:defcfun ("ev_unref" #.(lispify "ev_unref" 'function)) :void
(loop :pointer))
;; convenience function, wait for a single event, without registering an event watcher
;; if timeout is < 0, do wait indefinitely
(cffi:defcfun ("ev_once" #.(lispify "ev_once" 'function)) :void
(loop :pointer)
(fd :int)
(events :int)
(timeout :double)
(cb :pointer)
(arg :pointer))
;; number of loop iterations
(cffi:defcfun ("ev_iteration" #.(lispify "ev_iteration" 'function)) :unsigned-int
(loop :pointer))
;; #ev_loop enters - #ev_loop leaves
(cffi:defcfun ("ev_depth" #.(lispify "ev_depth" 'function)) :unsigned-int
(loop :pointer))
;; about if loop data corrupted
(cffi:defcfun ("ev_verify" #.(lispify "ev_verify" 'function)) :void
(loop :pointer))
;; sleep at least this time, default 0
(cffi:defcfun ("ev_set_io_collect_interval" #.(lispify "ev_set_io_collect_interval" 'function)) :void
(loop :pointer)
(interval :double))
;; sleep at least this time, default 0
(cffi:defcfun ("ev_set_timeout_collect_interval" #.(lispify "ev_set_timeout_collect_interval" 'function)) :void
(loop :pointer)
(interval :double))
;; advanced stuff for threading etc. support, see docs
(cffi:defcfun ("ev_set_userdata" #.(lispify "ev_set_userdata" 'function)) :void
(loop :pointer)
(data :pointer))
(cffi:defcfun ("ev_userdata" #.(lispify "ev_userdata" 'function)) :pointer
(loop :pointer))
(cffi:defcfun ("ev_set_invoke_pending_cb" #.(lispify "ev_set_invoke_pending_cb" 'function)) :void
(loop :pointer)
(invoke_pending_cb :pointer))
(cffi:defcfun ("ev_set_loop_release_cb" #.(lispify "ev_set_loop_release_cb" 'function)) :void
(loop :pointer)
(release :pointer)
(acquire :pointer))
;; number of pending events, if any
(cffi:defcfun ("ev_pending_count" #.(lispify "ev_pending_count" 'function)) :unsigned-int
(loop :pointer))
;; invoke all pending watchers
(cffi:defcfun ("ev_invoke_pending" #.(lispify "ev_invoke_pending" 'function)) :void
(loop :pointer))
;; stop/start the timer handling.
(cffi:defcfun ("ev_suspend" #.(lispify "ev_suspend" 'function)) :void
(loop :pointer))
(cffi:defcfun ("ev_resume" #.(lispify "ev_resume" 'function)) :void
(loop :pointer))
(defun ev-init (ev cb_)
(cffi:with-foreign-slots ((active pending priority cb) ev (:struct ev-io))
(setf active 0
pending 0
priority 0
cb (cffi:get-callback cb_))))
(defun ev-io-set (ev fd_ events_)
(cffi:with-foreign-slots ((fd events) ev (:struct ev-io))
(setf fd fd_
events (logxor events_ +ev--iofdset+))))
(defun ev-timer-set (ev after_ repeat_)
(cffi:with-foreign-slots ((at repeat) ev (:struct ev-timer))
(setf at after_
repeat repeat_)))
(defun ev-periodic-set (ev offset_ interval_ reschedule-cb_)
(cffi:with-foreign-slots ((offset interval reschedule-cb) ev (:struct ev-periodic))
(setf offset offset_
interval interval_
reschedule-cb reschedule-cb_)))
(defun ev-signal-set (ev signum)
(setf (cffi:foreign-slot-value ev '(:struct ev-signal) 'signum) signum))
(defun ev-child-set (ev pid_ trace_)
(cffi:with-foreign-slots ((pid flags) ev (:struct ev-child))
(setf pid pid_
flags (if trace_ 1 0))))
(defun ev-stat-set (ev path_ interval_)
(cffi:with-foreign-slots ((path interval wd) ev (:struct ev-stat))
(setf path path_
interval interval_
wd -2)))
;; nop, yes, this is a serious in-joke
(defun ev-idle-set (ev) (declare (ignore ev)))
;; nop, yes, this is a serious in-joke
(defun ev-prepare-set (ev) (declare (ignore ev)))
;; nop, yes, this is a serious in-joke
(defun ev-check-set (ev) (declare (ignore ev)))
(defun ev-embed-set (ev other_)
(setf (cffi:foreign-slot-value ev '(:struct ev-embed) 'other) other_))
;; nop, yes, this is a serious in-joke
(defun ev-fork-set (ev) (declare (ignore ev)))
;; nop, yes, this is a serious in-joke
(defun ev-cleanup-set (ev) (declare (ignore ev)))
;; nop, yes, this is a serious in-joke
(defun ev-async-set (ev) (declare (ignore ev)))
(defun ev-io-init (ev cb fd events)
(ev-init ev cb)
(ev-io-set ev fd events))
(defun ev-timer-init (ev cb after repeat)
(ev-init ev cb)
(ev-timer-set ev after repeat))
(defun ev-periodic-init (ev cb offset interval reschedule-cb)
(ev-init ev cb)
(ev-periodic-set ev offset interval reschedule-cb))
(defun ev-signal-init (ev cb signum)
(ev-init ev cb)
(ev-signal-set ev signum))
(defun ev-child-init (ev cb pid trace)
(ev-init ev cb)
(ev-child-set ev pid trace))
(defun ev-stat-init (ev cb path interval)
(ev-init ev cb)
(ev-stat-set ev path interval))
(defun ev-idle-init (ev cb)
(ev-init ev cb)
(ev-idle-set ev))
(defun ev-prepare-init (ev cb)
(ev-init ev cb)
(ev-prepare-set ev))
(defun ev-check-init (ev cb)
(ev-init ev cb)
(ev-check-set ev))
(defun ev-embed-init (ev cb other)
(ev-init ev cb)
(ev-embed-set ev other))
(defun ev-fork-init (ev cb)
(ev-init ev cb)
(ev-fork-set ev))
(defun ev-cleanup-init (ev cb)
(ev-init ev cb)
(ev-cleanup-set ev))
(defun ev-async-init (ev cb)
(ev-init ev cb)
(ev-async-set ev))
(defun ev-is-pending (ev)
(cffi:foreign-slot-value ev '(:struct ev-watcher) 'pending))
(defun ev-is-active (ev)
(cffi:foreign-slot-value ev '(:struct ev-watcher) 'active))
(defun ev-cb (ev)
(cffi:foreign-slot-value ev '(:struct ev-watcher) 'cb))
(defun (setf ev-cb) (cb ev)
(setf (cffi:foreign-slot-value ev '(:struct ev-watcher) 'cb) cb))
(defun ev-set-cb (ev cb)
(setf (ev-cb ev) cb))
#.(if (= +ev-minpri+ +ev-maxpri+)
`(progn
(defun ev-priority (ev)
,ev-minpri)
(defun (setf ev-priority) (priority ev)
(declare (ignore ev))
priority)
(defun ev-set-priority (ev priority)
(setf (ev-priority ev) priority)))
`(progn
(defun ev-priority (ev)
(cffi:foreign-slot-value ev '(:struct ev-watcher) 'priority))
(defun (setf ev-priority) (priority ev)
(setf (cffi:foreign-slot-value ev '(:struct ev-watcher) 'priority) priority))
(defun ev-set-priority (ev priority)
(setf (ev-priority ev) priority))))
(defun ev-periodic-at (ev)
(cffi:foreign-slot-value ev '(:struct ev-watcher-time) 'at))
(cffi:defcfun ("ev_feed_event" #.(lispify "ev_feed_event" 'function)) :void
(loop :pointer)
(w :pointer)
(revents :int))
(cffi:defcfun ("ev_feed_fd_event" #.(lispify "ev_feed_fd_event" 'function)) :void
(loop :pointer)
(fd :int)
(revents :int))
(cffi:defcfun ("ev_feed_signal" #.(lispify "ev_feed_signal" 'function)) :void
(signum :int))
(cffi:defcfun ("ev_feed_signal_event" #.(lispify "ev_feed_signal_event" 'function)) :void
(loop :pointer)
(signum :int))
(cffi:defcfun ("ev_invoke" #.(lispify "ev_invoke" 'function)) :void
(loop :pointer)
(w :pointer)
(revents :int))
(cffi:defcfun ("ev_clear_pending" #.(lispify "ev_clear_pending" 'function)) :int
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_io_start" #.(lispify "ev_io_start" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_io_stop" #.(lispify "ev_io_stop" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_timer_start" #.(lispify "ev_timer_start" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_timer_stop" #.(lispify "ev_timer_stop" 'function)) :void
(loop :pointer)
(w :pointer))
;; stops if active and no repeat, restarts if active and repeating, starts if inactive and repeating
(cffi:defcfun ("ev_timer_again" #.(lispify "ev_timer_again" 'function)) :void
(loop :pointer)
(w :pointer))
;; return remaining time
(cffi:defcfun ("ev_timer_remaining" #.(lispify "ev_timer_remaining" 'function)) :double
(loop :pointer)
(w :pointer))
#+lev-ev-periodic
(progn
(cffi:defcfun ("ev_periodic_start" #.(lispify "ev_periodic_start" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_periodic_stop" #.(lispify "ev_periodic_stop" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_periodic_again" #.(lispify "ev_periodic_again" 'function)) :void
(loop :pointer)
(w :pointer)))
#+lev-ev-signal
(progn
;; only supported in the default loop
(cffi:defcfun ("ev_signal_start" #.(lispify "ev_signal_start" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_signal_stop" #.(lispify "ev_signal_stop" 'function)) :void
(loop :pointer)
(w :pointer)))
#+lev-ev-child
(progn
;; only supported in the default loop
(cffi:defcfun ("ev_child_start" #.(lispify "ev_child_start" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_child_stop" #.(lispify "ev_child_stop" 'function)) :void
(loop :pointer)
(w :pointer)))
#+lev-ev-stat
(progn
(cffi:defcfun ("ev_stat_start" #.(lispify "ev_stat_start" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_stat_stop" #.(lispify "ev_stat_stop" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_stat_stat" #.(lispify "ev_stat_stat" 'function)) :void
(loop :pointer)
(w :pointer)))
#+lev-ev-idle
(progn
(cffi:defcfun ("ev_idle_start" #.(lispify "ev_idle_start" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_idle_stop" #.(lispify "ev_idle_stop" 'function)) :void
(loop :pointer)
(w :pointer)))
#+lev-ev-prepare
(progn
(cffi:defcfun ("ev_prepare_start" #.(lispify "ev_prepare_start" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_prepare_stop" #.(lispify "ev_prepare_stop" 'function)) :void
(loop :pointer)
(w :pointer)))
#+lev-ev-check
(progn
(cffi:defcfun ("ev_check_start" #.(lispify "ev_check_start" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_check_stop" #.(lispify "ev_check_stop" 'function)) :void
(loop :pointer)
(w :pointer)))
#+lev-ev-fork
(progn
(cffi:defcfun ("ev_fork_start" #.(lispify "ev_fork_start" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_fork_stop" #.(lispify "ev_fork_stop" 'function)) :void
(loop :pointer)
(w :pointer)))
#+lev-ev-cleanup
(progn
(cffi:defcfun ("ev_cleanup_start" #.(lispify "ev_cleanup_start" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_cleanup_stop" #.(lispify "ev_cleanup_stop" 'function)) :void
(loop :pointer)
(w :pointer)))
#+lev-ev-embed
(progn
;; only supported when loop to be embedded is in fact embeddable
(cffi:defcfun ("ev_embed_start" #.(lispify "ev_embed_start" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_embed_stop" #.(lispify "ev_embed_stop" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_embed_sweep" #.(lispify "ev_embed_sweep" 'function)) :void
(loop :pointer)
(w :pointer)))
#+lev-ev-async
(progn
(cffi:defcfun ("ev_async_start" #.(lispify "ev_async_start" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_async_stop" #.(lispify "ev_async_stop" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_async_send" #.(lispify "ev_async_send" 'function)) :void
(loop :pointer)
(w :pointer)))
#+lev-ev-compat3
(progn
(defconstant #.(lispify "EVLOOP_NONBLOCK" 'contant) #.(lispify "EVRUN_NOWAIT" 'constant))
(defconstant #.(lispify "EVLOOP_ONESHOT" 'constant) #.(lispify "EVRUN_ONCE" 'constant))
(defconstant #.(lispify "EVUNLOOP_CANCEL" 'constant) #.(lispify "EVBREAK_CANCEL" 'constant))
(defconstant #.(lispify "EVUNLOOP_ONE" 'constant) #.(lispify "EVBREAK_ONE" 'constant))
(defconstant #.(lispify "EVUNLOOP_ALL" 'constant) #.(lispify "EVBREAK_ALL" 'constant)))
(cffi:defcfun ("ev_loop" #.(lispify "ev_loop" 'function)) :void
(loop :pointer)
(flags :int))
(cffi:defcfun ("ev_unloop" #.(lispify "ev_unloop" 'function)) :void
(loop :pointer)
(how :int))
(cffi:defcfun ("ev_default_destroy" #.(lispify "ev_default_destroy" 'function)) :void)
(cffi:defcfun ("ev_default_fork" #.(lispify "ev_default_fork" 'function)) :void)
(cffi:defcfun ("ev_loop_count" #.(lispify "ev_loop_count" 'function)) :unsigned-int
(loop :pointer))
(cffi:defcfun ("ev_loop_depth" #.(lispify "ev_loop_depth" 'function)) :unsigned-int
(loop :pointer))
(cffi:defcfun ("ev_loop_verify" #.(lispify "ev_loop_verify" 'function)) :void
(loop :pointer))
| null | https://raw.githubusercontent.com/fukamachi/lev/7d03c68dad44f1cc4ac2aeeab2d24eb525ad941a/src/bindings.lisp | lisp | guaranteed to be invalid
no events
ev_io detected read will not block
ev_io detected write will not block
internal use only
timer timed out
periodic timer timed out
signal was received
child/pid has status change
stat data changed
event loop is idling
event loop about to poll
event loop finished poll
embedded event loop needs sweep
event loop resumed in child
event loop resumed in child
async intra-loop signal
for use by user code
sent when an error occurs
alias for type-detection
shared by all watchers
private
private
private
rw
private
private
invoked when fd is either EV_READable or EV_WRITEable
ro
ro
invoked after a specific time, repeatable (based on monotonic clock)
rw
invoked at some specific time, possibly repeating at regular intervals (based on UTC)
rw
rw
rw
invoked when the given signal has been received
ro
private
ro
rw, holds the received pid
invoked each time the stat data changes for a given path
private
ro
ro
ro
ro
invoked when the nothing else needs to be done, keeps the process from blocking
invoked for each run of the mainloop, just before the blocking call
you can still change events in any way you like
revent EV_PREPARE
invoked for each run of the mainloop, just after the blocking call
the callback gets invoked before check in the child process when a fork was detected
revent EV_FORK
is invoked just before the loop gets destroyed
used to embed an event loop inside another
the callback gets invoked when the event loop has handled events, and can be 0
ro
private
private
unused
unused
unused
unused
private
unused
invoked when somebody calls ev_async_send on the watcher
revent EV_ASYNC
private
the presence of this union forces similar struct layout
flag bits for ev_default_loop and ev_loop_new
the default
not quite a mask
flag bits
do NOT consult environment
check for a fork in each iteration
debugging/feature disable
do not attempt to use inotify
compatibility to pre-3.9
attempt to use signalfd
avoid modifying the signal mask
method bits to be ored together
about anywhere
!win
linux
all known backends
all future backends
sleep for a while
Sets the allocation function to use, works like realloc.
It is used to allocate and free memory.
or take some potentially destructive action.
The default is your system realloc function.
set the callback function to call on a
retryable syscall error
(such as failed select, poll, epoll_wait)
the default loop is the only one that handles signals and child watchers
you can call this as often as you like
create and destroy alternative loops that don't handle signals
destroy event loops, also works for the default loop
this needs to be called after fork, to duplicate the loop
when you want to re-use it in the child
you can call it in either the parent or the child
you can actually call it at any time, anywhere :)
backend in use by loop
update event loop time
walk (almost) all watchers in the loop of a given type, invoking the
callback on every such watcher. The callback might stop the watcher,
but do nothing else with the loop
ev_run flags values
do not block/wait
block *once* only
ev_break how values
unloop once
unloop all loops
break out of the loop
ref/unref can be used to add or remove a refcount on the mainloop. every watcher
should not keep ev_loop from running, unref() after starting, and ref() before stopping.
convenience function, wait for a single event, without registering an event watcher
if timeout is < 0, do wait indefinitely
number of loop iterations
#ev_loop enters - #ev_loop leaves
about if loop data corrupted
sleep at least this time, default 0
sleep at least this time, default 0
advanced stuff for threading etc. support, see docs
number of pending events, if any
invoke all pending watchers
stop/start the timer handling.
nop, yes, this is a serious in-joke
nop, yes, this is a serious in-joke
nop, yes, this is a serious in-joke
nop, yes, this is a serious in-joke
nop, yes, this is a serious in-joke
nop, yes, this is a serious in-joke
stops if active and no repeat, restarts if active and repeating, starts if inactive and repeating
return remaining time
only supported in the default loop
only supported in the default loop
only supported when loop to be embedded is in fact embeddable | (in-package :lev)
#+lev-ev-full
(eval-when (:compile-toplevel :load-toplevel :execute)
(pushnew :lev-ev-periodic *features*)
(pushnew :lev-ev-stat *features*)
(pushnew :lev-ev-prepare *features*)
(pushnew :lev-ev-check *features*)
(pushnew :lev-ev-idle *features*)
(pushnew :lev-ev-fork *features*)
(pushnew :lev-ev-cleanup *features*)
#-windows
(pushnew :lev-ev-child *features*)
(pushnew :lev-ev-async *features*)
(pushnew :lev-ev-embed *features*)
(pushnew :lev-ev-signal *features*)
#+lev-not-yet
(pushnew :lev-ev-walk *features*))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defconstant #.(lispify "EV_MINPRI" 'constant) -2)
(defconstant #.(lispify "EV_MAXPRI" 'constant) +2))
(defconstant #.(lispify "EV_VERSION_MAJOR" 'constant) 4)
(defconstant #.(lispify "EV_VERSION_MINOR" 'constant) 15)
(defanonenum
(defconstant #.(lispify "EV_IO" 'enumvalue) #.(lispify "EV_READ" 'enumvalue))
#+lev-ev-compat3
pre 4.0 API compatibility
(defconstant #.(lispify "EV_TIMEOUT" 'enumvalue) #.(lispify "EV_TIMER" 'enumvalue))
(eval-when (:compile-toplevel :load-toplevel)
(defparameter *ev-watcher-slots*
(#.(lispify "cb" 'slotname) :pointer)))
(defparameter *ev-watcher-list-slots*
`(,@*ev-watcher-slots*
(#.(lispify "next" 'slotname) :pointer)))
(defparameter *ev-watcher-time-slots*
`(,@*ev-watcher-slots*
(#.(lispify "at" 'slotname) :double))))
#.`(cffi:defcstruct #.(lispify "ev_watcher" 'classname)
,@*ev-watcher-slots*)
#.`(cffi:defcstruct #.(lispify "ev_watcher_list" 'classname)
,@*ev-watcher-list-slots*)
#.`(cffi:defcstruct #.(lispify "ev_watcher_time" 'classname)
,@*ev-watcher-time-slots*)
revent EV_READ , EV_WRITE
#.`(cffi:defcstruct #.(lispify "ev_io" 'classname)
,@*ev-watcher-list-slots*
revent EV_TIMEOUT
#.`(cffi:defcstruct #.(lispify "ev_timer" 'classname)
,@*ev-watcher-time-slots*
revent EV_PERIODIC
#.`(cffi:defcstruct #.(lispify "ev_periodic" 'classname)
,@*ev-watcher-time-slots*
revent EV_SIGNAL
#.`(cffi:defcstruct #.(lispify "ev_signal" 'classname)
,@*ev-watcher-list-slots*
invoked when sigchld is received and waitpid indicates the given pid
revent
#.`(cffi:defcstruct #.(lispify "ev_child" 'classname)
,@*ev-watcher-list-slots*
rw , holds the exit status , use the macros from sys / wait.h
revent EV_STAT
#+lev-ev-stat
#.`(cffi:defcstruct #.(lispify "ev_stat" 'classname)
,@*ev-watcher-list-slots*
wd for inotify , fd for kqueue
(#.(lispify "wd" 'slotname) :int))
revent
#+lev-ev-idle
#.`(cffi:defcstruct #.(lispify "ev_idle" 'classname)
,@*ev-watcher-slots*)
#.`(cffi:defcstruct #.(lispify "ev_prepare" 'classname)
,@*ev-watcher-slots*)
revent EV_CHECK
#.`(cffi:defcstruct #.(lispify "ev_check" 'classname)
,@*ev-watcher-slots*)
#+lev-ev-fork
#.`(cffi:defcstruct #.(lispify "ev_fork" 'classname)
,@*ev-watcher-slots*)
#+lev-ev-cleanup
revent EV_CLEANUP
#.`(cffi:defcstruct #.(lispify "ev_cleanup" 'classname)
,@*ev-watcher-slots*)
#+lev-ev-embed
#.`(cffi:defcstruct #.(lispify "ev_embed" 'classname)
,@*ev-watcher-slots*
#+lev-ev-cleanup
#+lev-ev-async
#.`(cffi:defcstruct #.(lispify "ev_async" 'classname)
,@*ev-watcher-slots*
#.`(cffi:defcunion #.(lispify "ev_any_watcher" 'classname)
(#.(lispify "w" 'slotname) (:struct #.(lispify "ev_watcher" 'classname)))
(#.(lispify "wl" 'slotname) (:struct #.(lispify "ev_watcher_list" 'classname)))
(#.(lispify "io" 'slotname) (:struct #.(lispify "ev_io" 'classname)))
(#.(lispify "timer" 'slotname) (:struct #.(lispify "ev_timer" 'classname)))
(#.(lispify "periodic" 'slotname) (:struct #.(lispify "ev_periodic" 'classname)))
(#.(lispify "signal" 'slotname) (:struct #.(lispify "ev_signal" 'classname)))
(#.(lispify "child" 'slotname) (:struct #.(lispify "ev_child" 'classname)))
#+lev-ev-stat
(#.(lispify "stat" 'slotname) (:struct #.(lispify "ev_stat" 'classname)))
#+lev-ev-idle
(#.(lispify "idle" 'slotname) (:struct #.(lispify "ev_idle" 'classname)))
(#.(lispify "prepare" 'slotname) (:struct #.(lispify "ev_prepare" 'classname)))
(#.(lispify "check" 'slotname) (:struct #.(lispify "ev_check" 'classname)))
#+lev-ev-fork
(#.(lispify "fork" 'slotname) (:struct #.(lispify "ev_fork" 'classname)))
#+lev-ev-cleanup
(#.(lispify "cleanup" 'slotname) (:struct #.(lispify "ev_cleanup" 'classname)))
#+lev-ev-embed
(#.(lispify "embed" 'slotname) (:struct #.(lispify "ev_embed" 'classname)))
#+lev-ev-async
(#.(lispify "async" 'slotname) (:struct #.(lispify "ev_async" 'classname))))
(defanonenum
#+lev-ev-compat3
(defanonenum
bsd
solaris 8 , NYI
solaris 10
(cffi:defcfun ("ev_version_major" #.(lispify "ev_version_major" 'function)) :int)
(cffi:defcfun ("ev_version_minor" #.(lispify "ev_version_minor" 'function)) :int)
(cffi:defcfun ("ev_supported_backends" #.(lispify "ev_supported_backends" 'function)) :unsigned-int)
(cffi:defcfun ("ev_recommended_backends" #.(lispify "ev_recommended_backends" 'function)) :unsigned-int)
(cffi:defcfun ("ev_embeddable_backends" #.(lispify "ev_embeddable_backends" 'function)) :unsigned-int)
(cffi:defcfun ("ev_time" #.(lispify "ev_time" 'function)) :double)
(cffi:defcfun ("ev_sleep" #.(lispify "ev_sleep" 'function)) :void
(delay :double))
If it returns zero when memory needs to be allocated , the library might abort
(cffi:defcfun ("ev_set_allocator" #.(lispify "ev_set_allocator" 'function)) :void
(cb :pointer))
(cffi:defcfun ("ev_set_syserr_cb" #.(lispify "ev_set_syserr_cb" 'function)) :void
(cb :pointer))
(cffi:defcfun ("ev_default_loop" #.(lispify "ev_default_loop" 'function)) :pointer
(flags :unsigned-int))
(cffi:defcfun ("ev_default_loop_uc_" #.(lispify "ev_default_loop_uc_" 'function)) :pointer)
(cffi:defcfun ("ev_is_default_loop" #.(lispify "ev_is_default_loop" 'function)) :int
(loop :pointer))
(cffi:defcfun ("ev_loop_new" #.(lispify "ev_loop_new" 'function)) :pointer
(flags :unsigned-int))
(cffi:defcfun ("ev_now" #.(lispify "ev_now" 'function)) :double
(loop :pointer))
(cffi:defcfun ("ev_loop_destroy" #.(lispify "ev_loop_destroy" 'function)) :void
(loop :pointer))
(cffi:defcfun ("ev_loop_fork" #.(lispify "ev_loop_fork" 'function)) :void
(loop :pointer))
(cffi:defcfun ("ev_backend" #.(lispify "ev_backend" 'function)) :unsigned-int
(loop :pointer))
(cffi:defcfun ("ev_now_update" #.(lispify "ev_now_update" 'function)) :void
(loop :pointer))
#+lev-ev-walk
(cffi:defcfun ("ev_walk" #.(lispify "ev_walk" 'function)) :void
(types :int)
(cb :pointer))
(defanonenum
(defanonenum
undo unloop
(cffi:defcfun ("ev_run" #.(lispify "ev_run" 'function)) :int
(loop :pointer)
(flags :int))
(cffi:defcfun ("ev_break" #.(lispify "ev_break" 'function)) :void
(loop :pointer)
(how :int))
keeps one reference . if you have a long - running watcher you never unregister that
(cffi:defcfun ("ev_ref" #.(lispify "ev_ref" 'function)) :void
(loop :pointer))
(cffi:defcfun ("ev_unref" #.(lispify "ev_unref" 'function)) :void
(loop :pointer))
(cffi:defcfun ("ev_once" #.(lispify "ev_once" 'function)) :void
(loop :pointer)
(fd :int)
(events :int)
(timeout :double)
(cb :pointer)
(arg :pointer))
(cffi:defcfun ("ev_iteration" #.(lispify "ev_iteration" 'function)) :unsigned-int
(loop :pointer))
(cffi:defcfun ("ev_depth" #.(lispify "ev_depth" 'function)) :unsigned-int
(loop :pointer))
(cffi:defcfun ("ev_verify" #.(lispify "ev_verify" 'function)) :void
(loop :pointer))
(cffi:defcfun ("ev_set_io_collect_interval" #.(lispify "ev_set_io_collect_interval" 'function)) :void
(loop :pointer)
(interval :double))
(cffi:defcfun ("ev_set_timeout_collect_interval" #.(lispify "ev_set_timeout_collect_interval" 'function)) :void
(loop :pointer)
(interval :double))
(cffi:defcfun ("ev_set_userdata" #.(lispify "ev_set_userdata" 'function)) :void
(loop :pointer)
(data :pointer))
(cffi:defcfun ("ev_userdata" #.(lispify "ev_userdata" 'function)) :pointer
(loop :pointer))
(cffi:defcfun ("ev_set_invoke_pending_cb" #.(lispify "ev_set_invoke_pending_cb" 'function)) :void
(loop :pointer)
(invoke_pending_cb :pointer))
(cffi:defcfun ("ev_set_loop_release_cb" #.(lispify "ev_set_loop_release_cb" 'function)) :void
(loop :pointer)
(release :pointer)
(acquire :pointer))
(cffi:defcfun ("ev_pending_count" #.(lispify "ev_pending_count" 'function)) :unsigned-int
(loop :pointer))
(cffi:defcfun ("ev_invoke_pending" #.(lispify "ev_invoke_pending" 'function)) :void
(loop :pointer))
(cffi:defcfun ("ev_suspend" #.(lispify "ev_suspend" 'function)) :void
(loop :pointer))
(cffi:defcfun ("ev_resume" #.(lispify "ev_resume" 'function)) :void
(loop :pointer))
(defun ev-init (ev cb_)
(cffi:with-foreign-slots ((active pending priority cb) ev (:struct ev-io))
(setf active 0
pending 0
priority 0
cb (cffi:get-callback cb_))))
(defun ev-io-set (ev fd_ events_)
(cffi:with-foreign-slots ((fd events) ev (:struct ev-io))
(setf fd fd_
events (logxor events_ +ev--iofdset+))))
(defun ev-timer-set (ev after_ repeat_)
(cffi:with-foreign-slots ((at repeat) ev (:struct ev-timer))
(setf at after_
repeat repeat_)))
(defun ev-periodic-set (ev offset_ interval_ reschedule-cb_)
(cffi:with-foreign-slots ((offset interval reschedule-cb) ev (:struct ev-periodic))
(setf offset offset_
interval interval_
reschedule-cb reschedule-cb_)))
(defun ev-signal-set (ev signum)
(setf (cffi:foreign-slot-value ev '(:struct ev-signal) 'signum) signum))
(defun ev-child-set (ev pid_ trace_)
(cffi:with-foreign-slots ((pid flags) ev (:struct ev-child))
(setf pid pid_
flags (if trace_ 1 0))))
(defun ev-stat-set (ev path_ interval_)
(cffi:with-foreign-slots ((path interval wd) ev (:struct ev-stat))
(setf path path_
interval interval_
wd -2)))
(defun ev-idle-set (ev) (declare (ignore ev)))
(defun ev-prepare-set (ev) (declare (ignore ev)))
(defun ev-check-set (ev) (declare (ignore ev)))
(defun ev-embed-set (ev other_)
(setf (cffi:foreign-slot-value ev '(:struct ev-embed) 'other) other_))
(defun ev-fork-set (ev) (declare (ignore ev)))
(defun ev-cleanup-set (ev) (declare (ignore ev)))
(defun ev-async-set (ev) (declare (ignore ev)))
(defun ev-io-init (ev cb fd events)
(ev-init ev cb)
(ev-io-set ev fd events))
(defun ev-timer-init (ev cb after repeat)
(ev-init ev cb)
(ev-timer-set ev after repeat))
(defun ev-periodic-init (ev cb offset interval reschedule-cb)
(ev-init ev cb)
(ev-periodic-set ev offset interval reschedule-cb))
(defun ev-signal-init (ev cb signum)
(ev-init ev cb)
(ev-signal-set ev signum))
(defun ev-child-init (ev cb pid trace)
(ev-init ev cb)
(ev-child-set ev pid trace))
(defun ev-stat-init (ev cb path interval)
(ev-init ev cb)
(ev-stat-set ev path interval))
(defun ev-idle-init (ev cb)
(ev-init ev cb)
(ev-idle-set ev))
(defun ev-prepare-init (ev cb)
(ev-init ev cb)
(ev-prepare-set ev))
(defun ev-check-init (ev cb)
(ev-init ev cb)
(ev-check-set ev))
(defun ev-embed-init (ev cb other)
(ev-init ev cb)
(ev-embed-set ev other))
(defun ev-fork-init (ev cb)
(ev-init ev cb)
(ev-fork-set ev))
(defun ev-cleanup-init (ev cb)
(ev-init ev cb)
(ev-cleanup-set ev))
(defun ev-async-init (ev cb)
(ev-init ev cb)
(ev-async-set ev))
(defun ev-is-pending (ev)
(cffi:foreign-slot-value ev '(:struct ev-watcher) 'pending))
(defun ev-is-active (ev)
(cffi:foreign-slot-value ev '(:struct ev-watcher) 'active))
(defun ev-cb (ev)
(cffi:foreign-slot-value ev '(:struct ev-watcher) 'cb))
(defun (setf ev-cb) (cb ev)
(setf (cffi:foreign-slot-value ev '(:struct ev-watcher) 'cb) cb))
(defun ev-set-cb (ev cb)
(setf (ev-cb ev) cb))
#.(if (= +ev-minpri+ +ev-maxpri+)
`(progn
(defun ev-priority (ev)
,ev-minpri)
(defun (setf ev-priority) (priority ev)
(declare (ignore ev))
priority)
(defun ev-set-priority (ev priority)
(setf (ev-priority ev) priority)))
`(progn
(defun ev-priority (ev)
(cffi:foreign-slot-value ev '(:struct ev-watcher) 'priority))
(defun (setf ev-priority) (priority ev)
(setf (cffi:foreign-slot-value ev '(:struct ev-watcher) 'priority) priority))
(defun ev-set-priority (ev priority)
(setf (ev-priority ev) priority))))
(defun ev-periodic-at (ev)
(cffi:foreign-slot-value ev '(:struct ev-watcher-time) 'at))
(cffi:defcfun ("ev_feed_event" #.(lispify "ev_feed_event" 'function)) :void
(loop :pointer)
(w :pointer)
(revents :int))
(cffi:defcfun ("ev_feed_fd_event" #.(lispify "ev_feed_fd_event" 'function)) :void
(loop :pointer)
(fd :int)
(revents :int))
(cffi:defcfun ("ev_feed_signal" #.(lispify "ev_feed_signal" 'function)) :void
(signum :int))
(cffi:defcfun ("ev_feed_signal_event" #.(lispify "ev_feed_signal_event" 'function)) :void
(loop :pointer)
(signum :int))
(cffi:defcfun ("ev_invoke" #.(lispify "ev_invoke" 'function)) :void
(loop :pointer)
(w :pointer)
(revents :int))
(cffi:defcfun ("ev_clear_pending" #.(lispify "ev_clear_pending" 'function)) :int
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_io_start" #.(lispify "ev_io_start" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_io_stop" #.(lispify "ev_io_stop" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_timer_start" #.(lispify "ev_timer_start" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_timer_stop" #.(lispify "ev_timer_stop" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_timer_again" #.(lispify "ev_timer_again" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_timer_remaining" #.(lispify "ev_timer_remaining" 'function)) :double
(loop :pointer)
(w :pointer))
#+lev-ev-periodic
(progn
(cffi:defcfun ("ev_periodic_start" #.(lispify "ev_periodic_start" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_periodic_stop" #.(lispify "ev_periodic_stop" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_periodic_again" #.(lispify "ev_periodic_again" 'function)) :void
(loop :pointer)
(w :pointer)))
#+lev-ev-signal
(progn
(cffi:defcfun ("ev_signal_start" #.(lispify "ev_signal_start" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_signal_stop" #.(lispify "ev_signal_stop" 'function)) :void
(loop :pointer)
(w :pointer)))
#+lev-ev-child
(progn
(cffi:defcfun ("ev_child_start" #.(lispify "ev_child_start" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_child_stop" #.(lispify "ev_child_stop" 'function)) :void
(loop :pointer)
(w :pointer)))
#+lev-ev-stat
(progn
(cffi:defcfun ("ev_stat_start" #.(lispify "ev_stat_start" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_stat_stop" #.(lispify "ev_stat_stop" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_stat_stat" #.(lispify "ev_stat_stat" 'function)) :void
(loop :pointer)
(w :pointer)))
#+lev-ev-idle
(progn
(cffi:defcfun ("ev_idle_start" #.(lispify "ev_idle_start" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_idle_stop" #.(lispify "ev_idle_stop" 'function)) :void
(loop :pointer)
(w :pointer)))
#+lev-ev-prepare
(progn
(cffi:defcfun ("ev_prepare_start" #.(lispify "ev_prepare_start" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_prepare_stop" #.(lispify "ev_prepare_stop" 'function)) :void
(loop :pointer)
(w :pointer)))
#+lev-ev-check
(progn
(cffi:defcfun ("ev_check_start" #.(lispify "ev_check_start" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_check_stop" #.(lispify "ev_check_stop" 'function)) :void
(loop :pointer)
(w :pointer)))
#+lev-ev-fork
(progn
(cffi:defcfun ("ev_fork_start" #.(lispify "ev_fork_start" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_fork_stop" #.(lispify "ev_fork_stop" 'function)) :void
(loop :pointer)
(w :pointer)))
#+lev-ev-cleanup
(progn
(cffi:defcfun ("ev_cleanup_start" #.(lispify "ev_cleanup_start" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_cleanup_stop" #.(lispify "ev_cleanup_stop" 'function)) :void
(loop :pointer)
(w :pointer)))
#+lev-ev-embed
(progn
(cffi:defcfun ("ev_embed_start" #.(lispify "ev_embed_start" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_embed_stop" #.(lispify "ev_embed_stop" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_embed_sweep" #.(lispify "ev_embed_sweep" 'function)) :void
(loop :pointer)
(w :pointer)))
#+lev-ev-async
(progn
(cffi:defcfun ("ev_async_start" #.(lispify "ev_async_start" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_async_stop" #.(lispify "ev_async_stop" 'function)) :void
(loop :pointer)
(w :pointer))
(cffi:defcfun ("ev_async_send" #.(lispify "ev_async_send" 'function)) :void
(loop :pointer)
(w :pointer)))
#+lev-ev-compat3
(progn
(defconstant #.(lispify "EVLOOP_NONBLOCK" 'contant) #.(lispify "EVRUN_NOWAIT" 'constant))
(defconstant #.(lispify "EVLOOP_ONESHOT" 'constant) #.(lispify "EVRUN_ONCE" 'constant))
(defconstant #.(lispify "EVUNLOOP_CANCEL" 'constant) #.(lispify "EVBREAK_CANCEL" 'constant))
(defconstant #.(lispify "EVUNLOOP_ONE" 'constant) #.(lispify "EVBREAK_ONE" 'constant))
(defconstant #.(lispify "EVUNLOOP_ALL" 'constant) #.(lispify "EVBREAK_ALL" 'constant)))
(cffi:defcfun ("ev_loop" #.(lispify "ev_loop" 'function)) :void
(loop :pointer)
(flags :int))
(cffi:defcfun ("ev_unloop" #.(lispify "ev_unloop" 'function)) :void
(loop :pointer)
(how :int))
(cffi:defcfun ("ev_default_destroy" #.(lispify "ev_default_destroy" 'function)) :void)
(cffi:defcfun ("ev_default_fork" #.(lispify "ev_default_fork" 'function)) :void)
(cffi:defcfun ("ev_loop_count" #.(lispify "ev_loop_count" 'function)) :unsigned-int
(loop :pointer))
(cffi:defcfun ("ev_loop_depth" #.(lispify "ev_loop_depth" 'function)) :unsigned-int
(loop :pointer))
(cffi:defcfun ("ev_loop_verify" #.(lispify "ev_loop_verify" 'function)) :void
(loop :pointer))
|
62e659c85e47e26187cea13ea9daf033175dca2fdf2bfc4692e83bff2455c2b0 | cgrand/packed-printer | packed_printer.cljc | (ns net.cgrand.packed-printer
"Compact pretty printing."
(:require
[net.cgrand.packed-printer.core :as core]
; below requires have defmethods
[net.cgrand.packed-printer.text :as text]
[net.cgrand.packed-printer.text.edn]))
(defn pprint
"Packed prints x, core options are:
* :width the desired output width (in chars, defaults to 72),
* :strict, a number or boolean (defaults to true or 2), true when the desired width is a hard limit
(pprint may throw when no suitable layout is found), the strictness factor influences the layout
propension to write past the margin.
* :as a keyword denoting the nature of the input (defaults to :edn),
* :to a keyword denoting the expected output (defaults to :text).
More options may be available depending on :as and :to.
For [:text :edn], supported options are:
* kv-indent the amount of spaces by which to indent a value when it appears
at the start of a line (default 2),
* coll-indents a map of collection start delimiters (as strings) to the amount
by which to indent (default: length of the delimiter)."
[x & {:as opts :keys [strict width as to] :or {strict false width 72 as :edn to :text}}]
(if-some [layout (core/layout (core/spans x [to as] opts) width strict)]
(core/render layout to opts)
(throw (ex-info "Can't find a suitable layout. See ex-data."
{:dispatch [to as] :data x :opts opts})))) | null | https://raw.githubusercontent.com/cgrand/packed-printer/598d55d5b93790c3838e48ac8707d96d984ffea0/src/net/cgrand/packed_printer.cljc | clojure | below requires have defmethods | (ns net.cgrand.packed-printer
"Compact pretty printing."
(:require
[net.cgrand.packed-printer.core :as core]
[net.cgrand.packed-printer.text :as text]
[net.cgrand.packed-printer.text.edn]))
(defn pprint
"Packed prints x, core options are:
* :width the desired output width (in chars, defaults to 72),
* :strict, a number or boolean (defaults to true or 2), true when the desired width is a hard limit
(pprint may throw when no suitable layout is found), the strictness factor influences the layout
propension to write past the margin.
* :as a keyword denoting the nature of the input (defaults to :edn),
* :to a keyword denoting the expected output (defaults to :text).
More options may be available depending on :as and :to.
For [:text :edn], supported options are:
* kv-indent the amount of spaces by which to indent a value when it appears
at the start of a line (default 2),
* coll-indents a map of collection start delimiters (as strings) to the amount
by which to indent (default: length of the delimiter)."
[x & {:as opts :keys [strict width as to] :or {strict false width 72 as :edn to :text}}]
(if-some [layout (core/layout (core/spans x [to as] opts) width strict)]
(core/render layout to opts)
(throw (ex-info "Can't find a suitable layout. See ex-data."
{:dispatch [to as] :data x :opts opts})))) |
2b7af0ec3eb064adbc6730d8fb59b2dccddf3f96648ab303865f0fc09fe2f9e3 | fyquah/hardcaml_zprize | top_config_intf.ml | module type S = sig
include Hardcaml_ntt.Core_config.S
val memory_layout : Memory_layout.t
end
module type Top_config = sig
module type S = S
end
| null | https://raw.githubusercontent.com/fyquah/hardcaml_zprize/553b1be10ae9b977decbca850df6ee2d0595e7ff/zprize/ntt/hardcaml/src/top_config_intf.ml | ocaml | module type S = sig
include Hardcaml_ntt.Core_config.S
val memory_layout : Memory_layout.t
end
module type Top_config = sig
module type S = S
end
| |
8f069bfec7653d7cc039c9424e6b999d03a9b0573310ccc83ca74f33ee5c5857 | ghc/packages-Cabal | LogProgress.hs | # LANGUAGE GeneralizedNewtypeDeriving #
{-# LANGUAGE Rank2Types #-}
# LANGUAGE FlexibleContexts #
module Distribution.Utils.LogProgress (
LogProgress,
runLogProgress,
warnProgress,
infoProgress,
dieProgress,
addProgressCtx,
) where
import Prelude ()
import Distribution.Compat.Prelude
import Distribution.Utils.Progress
import Distribution.Verbosity
import Distribution.Simple.Utils
import Text.PrettyPrint
type CtxMsg = Doc
type LogMsg = Doc
type ErrMsg = Doc
data LogEnv = LogEnv {
le_verbosity :: Verbosity,
le_context :: [CtxMsg]
}
-- | The 'Progress' monad with specialized logging and
-- error messages.
newtype LogProgress a = LogProgress { unLogProgress :: LogEnv -> Progress LogMsg ErrMsg a }
instance Functor LogProgress where
fmap f (LogProgress m) = LogProgress (fmap (fmap f) m)
instance Applicative LogProgress where
pure x = LogProgress (pure (pure x))
LogProgress f <*> LogProgress x = LogProgress $ \r -> f r `ap` x r
instance Monad LogProgress where
return = pure
LogProgress m >>= f = LogProgress $ \r -> m r >>= \x -> unLogProgress (f x) r
| Run ' LogProgress ' , outputting traces according to ' Verbosity ' ,
-- 'die' if there is an error.
runLogProgress :: Verbosity -> LogProgress a -> IO a
runLogProgress verbosity (LogProgress m) =
foldProgress step_fn fail_fn return (m env)
where
env = LogEnv {
le_verbosity = verbosity,
le_context = []
}
step_fn :: LogMsg -> IO a -> IO a
step_fn doc go = do
putStrLn (render doc)
go
fail_fn :: Doc -> IO a
fail_fn doc = do
dieNoWrap verbosity (render doc)
| Output a warning trace message in ' LogProgress ' .
warnProgress :: Doc -> LogProgress ()
warnProgress s = LogProgress $ \env ->
when (le_verbosity env >= normal) $
stepProgress $
hang (text "Warning:") 4 (formatMsg (le_context env) s)
| Output an informational trace message in ' LogProgress ' .
infoProgress :: Doc -> LogProgress ()
infoProgress s = LogProgress $ \env ->
when (le_verbosity env >= verbose) $
stepProgress s
-- | Fail the computation with an error message.
dieProgress :: Doc -> LogProgress a
dieProgress s = LogProgress $ \env ->
failProgress $
hang (text "Error:") 4 (formatMsg (le_context env) s)
-- | Format a message with context. (Something simple for now.)
formatMsg :: [CtxMsg] -> Doc -> Doc
formatMsg ctx doc = doc $$ vcat ctx
-- | Add a message to the error/warning context.
addProgressCtx :: CtxMsg -> LogProgress a -> LogProgress a
addProgressCtx s (LogProgress m) = LogProgress $ \env ->
m env { le_context = s : le_context env }
| null | https://raw.githubusercontent.com/ghc/packages-Cabal/6f22f2a789fa23edb210a2591d74ea6a5f767872/Cabal/Distribution/Utils/LogProgress.hs | haskell | # LANGUAGE Rank2Types #
| The 'Progress' monad with specialized logging and
error messages.
'die' if there is an error.
| Fail the computation with an error message.
| Format a message with context. (Something simple for now.)
| Add a message to the error/warning context. | # LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE FlexibleContexts #
module Distribution.Utils.LogProgress (
LogProgress,
runLogProgress,
warnProgress,
infoProgress,
dieProgress,
addProgressCtx,
) where
import Prelude ()
import Distribution.Compat.Prelude
import Distribution.Utils.Progress
import Distribution.Verbosity
import Distribution.Simple.Utils
import Text.PrettyPrint
type CtxMsg = Doc
type LogMsg = Doc
type ErrMsg = Doc
data LogEnv = LogEnv {
le_verbosity :: Verbosity,
le_context :: [CtxMsg]
}
newtype LogProgress a = LogProgress { unLogProgress :: LogEnv -> Progress LogMsg ErrMsg a }
instance Functor LogProgress where
fmap f (LogProgress m) = LogProgress (fmap (fmap f) m)
instance Applicative LogProgress where
pure x = LogProgress (pure (pure x))
LogProgress f <*> LogProgress x = LogProgress $ \r -> f r `ap` x r
instance Monad LogProgress where
return = pure
LogProgress m >>= f = LogProgress $ \r -> m r >>= \x -> unLogProgress (f x) r
| Run ' LogProgress ' , outputting traces according to ' Verbosity ' ,
runLogProgress :: Verbosity -> LogProgress a -> IO a
runLogProgress verbosity (LogProgress m) =
foldProgress step_fn fail_fn return (m env)
where
env = LogEnv {
le_verbosity = verbosity,
le_context = []
}
step_fn :: LogMsg -> IO a -> IO a
step_fn doc go = do
putStrLn (render doc)
go
fail_fn :: Doc -> IO a
fail_fn doc = do
dieNoWrap verbosity (render doc)
| Output a warning trace message in ' LogProgress ' .
warnProgress :: Doc -> LogProgress ()
warnProgress s = LogProgress $ \env ->
when (le_verbosity env >= normal) $
stepProgress $
hang (text "Warning:") 4 (formatMsg (le_context env) s)
| Output an informational trace message in ' LogProgress ' .
infoProgress :: Doc -> LogProgress ()
infoProgress s = LogProgress $ \env ->
when (le_verbosity env >= verbose) $
stepProgress s
dieProgress :: Doc -> LogProgress a
dieProgress s = LogProgress $ \env ->
failProgress $
hang (text "Error:") 4 (formatMsg (le_context env) s)
formatMsg :: [CtxMsg] -> Doc -> Doc
formatMsg ctx doc = doc $$ vcat ctx
addProgressCtx :: CtxMsg -> LogProgress a -> LogProgress a
addProgressCtx s (LogProgress m) = LogProgress $ \env ->
m env { le_context = s : le_context env }
|
3f302f97f71d1eb6b5338e808353d4a5fea0298edc4479478dafe3d3dede0626 | erlyaws/yaws | mime_types_SUITE.erl | -module(mime_types_SUITE).
-include("testsuite.hrl").
-compile(export_all).
all() ->
[
generated_module,
default_type,
yaws_type,
erlang_type,
gzip_with_charset,
multiple_accept_headers,
charset_for_404
].
groups() ->
[
].
%%====================================================================
init_per_suite(Config) ->
Id = "testsuite-server",
YConf = filename:join(?tempdir(?MODULE), "yaws.conf"),
application:load(yaws),
application:set_env(yaws, id, Id),
application:set_env(yaws, conf, YConf),
ok = yaws:start(),
[{yaws_id, Id}, {yaws_config, YConf} | Config].
end_per_suite(_Config) ->
ok = application:stop(yaws),
ok = application:unload(yaws),
ok.
init_per_group(_Group, Config) ->
Config.
end_per_group(_Group, _Config) ->
ok.
-ifdef(DETERMINISTIC).
init_per_testcase(generated_module, _Config) ->
{skip, "generated_module test not supported for deterministic builds"};
init_per_testcase(default_type, _Config) ->
{skip, "default_type test not supported for deterministic builds"};
init_per_testcase(yaws_type, _Config) ->
{skip, "yaws_type test not supported for deterministic builds"};
init_per_testcase(erlang_type, _Config) ->
{skip, "erlang_type test not supported for deterministic builds"};
init_per_testcase(gzip_with_charset, _Config) ->
{skip, "gzip_with_charset test not supported for deterministic builds"};
init_per_testcase(charset_for_404, _Config) ->
{skip, "charset_for_404 test not supported for deterministic builds"};
init_per_testcase(_Test, Config) ->
Config.
-else.
init_per_testcase(_Test, Config) ->
Config.
-endif.
end_per_testcase(_Test, _Config) ->
ok.
%%====================================================================
generated_module(Config) ->
Port1 = testsuite:get_yaws_port(1, Config),
Port2 = testsuite:get_yaws_port(2, Config),
Vhost1 = {"localhost:"++integer_to_list(Port1), Port1},
Vhost2 = {"localhost:"++integer_to_list(Port2), Port2},
CInfo = mime_types:module_info(compile),
?assertEqual(yaws:id_dir(?config(yaws_id, Config)),
filename:dirname(proplists:get_value(source, CInfo))),
?assertEqual("text/html", mime_types:default_type()),
?assertEqual("text/html", mime_types:default_type(global)),
?assertEqual("text/html", mime_types:default_type(Vhost1)),
?assertEqual("text/plain; charset=UTF-8", mime_types:default_type(Vhost2)),
?assertEqual({yaws, "text/html"}, mime_types:t("yaws")),
?assertEqual({yaws, "text/html"}, mime_types:t(global,"yaws")),
?assertEqual({yaws, "text/html"}, mime_types:t(Vhost1,"yaws")),
?assertEqual({yaws, "text/xhtml; charset=ISO-8859-1"} ,mime_types:t(Vhost2,"yaws")),
?assertEqual({regular, "text/plain; charset=UTF-8"}, mime_types:t("tst")),
?assertEqual({regular, "text/plain; charset=UTF-8"}, mime_types:t(global,"tst")),
?assertEqual({regular, "text/plain; charset=UTF-8"}, mime_types:t(Vhost1,"tst")),
?assertEqual({regular, "application/x-test; charset=US-ASCII"}, mime_types:t(Vhost2,"tst")),
?assertEqual({regular, "text/html"}, mime_types:t("test")),
?assertEqual({regular, "text/html"}, mime_types:t(global,"test")),
?assertEqual({regular, "text/html"}, mime_types:t(Vhost1,"test")),
?assertEqual({regular, "application/x-test; charset=UTF-8"}, mime_types:t(Vhost2,"test")),
?assertEqual({php, "text/html"}, mime_types:t("php")),
?assertEqual({php, "text/html"}, mime_types:t(global, "php")),
?assertEqual({php, "text/html"}, mime_types:t(Vhost1, "php")),
?assertEqual({php, "application/x-httpd-php"}, mime_types:t(Vhost2,"php")),
?assertEqual({php, "application/x-httpd-php"}, mime_types:t(Vhost2,"PHP")),
?assertEqual({regular, "php5", "application/x-httpd-php5"}, mime_types:revt(Vhost2,"5php")),
?assertEqual({regular, "PHP5", "application/x-httpd-php5"}, mime_types:revt(Vhost2,"5PHP")),
?assertEqual({regular, "text/plain"}, mime_types:t("html")),
?assertEqual({regular, "text/plain"}, mime_types:t(global,"html")),
?assertEqual({regular, "text/plain"}, mime_types:t(Vhost1,"html")),
?assertEqual({regular, "text/plain; charset=UTF-8"}, mime_types:t(Vhost2,"html")),
ok.
default_type(Config) ->
Port1 = testsuite:get_yaws_port(1, Config),
Port2 = testsuite:get_yaws_port(2, Config),
Url1 = testsuite:make_url(http, "127.0.0.1", Port1, "/news"),
Url2 = testsuite:make_url(http, "127.0.0.1", Port2, "/news"),
{ok, {{_,200,_}, Hdrs1, _}} = testsuite:http_get(Url1),
?assertEqual("text/html", proplists:get_value("content-type", Hdrs1)),
{ok, {{_,200,_}, Hdrs2, _}} = testsuite:http_get(Url2),
?assertEqual("text/plain; charset=UTF-8", proplists:get_value("content-type", Hdrs2)),
ok.
yaws_type(Config) ->
Port1 = testsuite:get_yaws_port(1, Config),
Port2 = testsuite:get_yaws_port(2, Config),
Url1 = testsuite:make_url(http, "127.0.0.1", Port1, "/index.yaws"),
Url2 = testsuite:make_url(http, "127.0.0.1", Port2, "/index.yaws"),
{ok, {{_,200,_}, Hdrs1, _}} = testsuite:http_get(Url1),
?assertEqual("text/html", proplists:get_value("content-type", Hdrs1)),
{ok, {{_,200,_}, Hdrs2, _}} = testsuite:http_get(Url2),
?assertEqual("text/xhtml; charset=ISO-8859-1", proplists:get_value("content-type", Hdrs2)),
ok.
erlang_type(Config) ->
Port1 = testsuite:get_yaws_port(1, Config),
Port2 = testsuite:get_yaws_port(2, Config),
Url1 = testsuite:make_url(http, "127.0.0.1", Port1, "/code/myappmod.erl"),
Url2 = testsuite:make_url(http, "127.0.0.1", Port2, "/code/myappmod.erl"),
{ok, {{_,200,_}, Hdrs1, _}} = testsuite:http_get(Url1),
?assertEqual("text/html", proplists:get_value("content-type", Hdrs1)),
{ok, {{_,200,_}, Hdrs2, _}} = testsuite:http_get(Url2),
?assertEqual("text/x-erlang; charset=UTF-8", proplists:get_value("content-type", Hdrs2)),
ok.
gzip_with_charset(Config) ->
Port = testsuite:get_yaws_port(2, Config),
Url = testsuite:make_url(http, "127.0.0.1", Port, "/index.yaws"),
GzHdr = {"Accept-Encoding", "gzip, deflate"},
{ok, {{_,200,_}, Hdrs, _}} = testsuite:http_get(Url, [GzHdr]),
?assertEqual("text/xhtml; charset=ISO-8859-1", proplists:get_value("content-type", Hdrs)),
?assertEqual("gzip", proplists:get_value("content-encoding", Hdrs)),
ok.
multiple_accept_headers(Config) ->
Port1 = testsuite:get_yaws_port(1, Config),
Url1 = testsuite:make_url(http, "127.0.0.1", Port1, "/multiple_accept_headers.yaws"),
AcceptHdrs1 = [{"Accept", "text/html"}, {"Accept", "text/plain"}],
{ok, {{_,200,_}, Hdrs1, _}} = testsuite:http_get(Url1, AcceptHdrs1),
?assertEqual("text/html", proplists:get_value("content-type", Hdrs1)),
?assertEqual("text/html, text/plain",
proplists:get_value("x-test-request-accept", Hdrs1)),
AcceptHdrs2 = [{"Accept", "text/plain"}, {"Accept", "text/html"}],
{ok, {{_,200,_}, Hdrs2, _}} = testsuite:http_get(Url1, AcceptHdrs2),
?assertEqual("text/plain", proplists:get_value("content-type", Hdrs2)),
?assertEqual("text/plain, text/html",
proplists:get_value("x-test-request-accept", Hdrs2)),
AcceptHdrs3 = [{"Accept", "text/html, text/plain"}],
{ok, {{_,200,_}, Hdrs3, _}} = testsuite:http_get(Url1, AcceptHdrs3),
?assertEqual("text/html", proplists:get_value("content-type", Hdrs3)),
?assertEqual("text/html, text/plain",
proplists:get_value("x-test-request-accept", Hdrs3)),
AcceptHdrs4 = [{"Accept", "text/plain, text/html"}],
{ok, {{_,200,_}, Hdrs4, _}} = testsuite:http_get(Url1, AcceptHdrs4),
?assertEqual("text/plain", proplists:get_value("content-type", Hdrs4)),
?assertEqual("text/plain, text/html",
proplists:get_value("x-test-request-accept", Hdrs4)),
AcceptHdrs5 = [{"Accept", "text/plain, application/json"},
{"Accept", "text/html, text/*"}],
{ok, {{_,200,_}, Hdrs5, _}} = testsuite:http_get(Url1, AcceptHdrs5),
?assertEqual("text/plain", proplists:get_value("content-type", Hdrs5)),
?assertEqual("text/plain, application/json, text/html, text/*",
proplists:get_value("x-test-request-accept", Hdrs5)),
AcceptHdrs6 = [{"Accept", ",text/plain"}],
{ok, {{_,200,_}, Hdrs6, _}} = testsuite:http_get(Url1, AcceptHdrs6),
?assertEqual("text/plain", proplists:get_value("content-type", Hdrs6)),
?assertEqual("text/plain",
proplists:get_value("x-test-request-accept", Hdrs6)),
AcceptHdrs7 = [{"Accept", ",text/plain"}],
{ok, {{_,200,_}, Hdrs7, _}} = testsuite:http_get(Url1, AcceptHdrs7),
?assertEqual("text/plain", proplists:get_value("content-type", Hdrs7)),
?assertEqual("text/plain",
proplists:get_value("x-test-request-accept", Hdrs7)),
AcceptHdrs8 = [{"Accept", "text/plain, ,text/html"}],
{ok, {{_,200,_}, Hdrs8, _}} = testsuite:http_get(Url1, AcceptHdrs8),
?assertEqual("text/plain", proplists:get_value("content-type", Hdrs8)),
?assertEqual("text/plain, text/html",
proplists:get_value("x-test-request-accept", Hdrs8)),
AcceptHdrs9 = [{"Accept", ","}],
{ok, {{_,400,_}, _, _}} = testsuite:http_get(Url1, AcceptHdrs9),
ok.
charset_for_404(Config) ->
Port1 = testsuite:get_yaws_port(1, Config),
Port3 = testsuite:get_yaws_port(3, Config),
Url1 = testsuite:make_url(http, "127.0.0.1", Port1, "/404"),
Url3 = testsuite:make_url(http, "127.0.0.1", Port3, "/404"),
{ok, {{_,404,_}, Hdrs1, _}} = testsuite:http_get(Url1),
?assertEqual("text/plain", proplists:get_value("content-type", Hdrs1)),
{ok, {{_,404,_}, Hdrs3, _}} = testsuite:http_get(Url3),
?assertEqual("text/html; charset=UTF-8", proplists:get_value("content-type", Hdrs3)),
ok.
| null | https://raw.githubusercontent.com/erlyaws/yaws/50e86836fc629cd56a5673ac31b88058ebce2793/testsuite/mime_types_SUITE.erl | erlang | ====================================================================
==================================================================== | -module(mime_types_SUITE).
-include("testsuite.hrl").
-compile(export_all).
all() ->
[
generated_module,
default_type,
yaws_type,
erlang_type,
gzip_with_charset,
multiple_accept_headers,
charset_for_404
].
groups() ->
[
].
init_per_suite(Config) ->
Id = "testsuite-server",
YConf = filename:join(?tempdir(?MODULE), "yaws.conf"),
application:load(yaws),
application:set_env(yaws, id, Id),
application:set_env(yaws, conf, YConf),
ok = yaws:start(),
[{yaws_id, Id}, {yaws_config, YConf} | Config].
end_per_suite(_Config) ->
ok = application:stop(yaws),
ok = application:unload(yaws),
ok.
init_per_group(_Group, Config) ->
Config.
end_per_group(_Group, _Config) ->
ok.
-ifdef(DETERMINISTIC).
init_per_testcase(generated_module, _Config) ->
{skip, "generated_module test not supported for deterministic builds"};
init_per_testcase(default_type, _Config) ->
{skip, "default_type test not supported for deterministic builds"};
init_per_testcase(yaws_type, _Config) ->
{skip, "yaws_type test not supported for deterministic builds"};
init_per_testcase(erlang_type, _Config) ->
{skip, "erlang_type test not supported for deterministic builds"};
init_per_testcase(gzip_with_charset, _Config) ->
{skip, "gzip_with_charset test not supported for deterministic builds"};
init_per_testcase(charset_for_404, _Config) ->
{skip, "charset_for_404 test not supported for deterministic builds"};
init_per_testcase(_Test, Config) ->
Config.
-else.
init_per_testcase(_Test, Config) ->
Config.
-endif.
end_per_testcase(_Test, _Config) ->
ok.
generated_module(Config) ->
Port1 = testsuite:get_yaws_port(1, Config),
Port2 = testsuite:get_yaws_port(2, Config),
Vhost1 = {"localhost:"++integer_to_list(Port1), Port1},
Vhost2 = {"localhost:"++integer_to_list(Port2), Port2},
CInfo = mime_types:module_info(compile),
?assertEqual(yaws:id_dir(?config(yaws_id, Config)),
filename:dirname(proplists:get_value(source, CInfo))),
?assertEqual("text/html", mime_types:default_type()),
?assertEqual("text/html", mime_types:default_type(global)),
?assertEqual("text/html", mime_types:default_type(Vhost1)),
?assertEqual("text/plain; charset=UTF-8", mime_types:default_type(Vhost2)),
?assertEqual({yaws, "text/html"}, mime_types:t("yaws")),
?assertEqual({yaws, "text/html"}, mime_types:t(global,"yaws")),
?assertEqual({yaws, "text/html"}, mime_types:t(Vhost1,"yaws")),
?assertEqual({yaws, "text/xhtml; charset=ISO-8859-1"} ,mime_types:t(Vhost2,"yaws")),
?assertEqual({regular, "text/plain; charset=UTF-8"}, mime_types:t("tst")),
?assertEqual({regular, "text/plain; charset=UTF-8"}, mime_types:t(global,"tst")),
?assertEqual({regular, "text/plain; charset=UTF-8"}, mime_types:t(Vhost1,"tst")),
?assertEqual({regular, "application/x-test; charset=US-ASCII"}, mime_types:t(Vhost2,"tst")),
?assertEqual({regular, "text/html"}, mime_types:t("test")),
?assertEqual({regular, "text/html"}, mime_types:t(global,"test")),
?assertEqual({regular, "text/html"}, mime_types:t(Vhost1,"test")),
?assertEqual({regular, "application/x-test; charset=UTF-8"}, mime_types:t(Vhost2,"test")),
?assertEqual({php, "text/html"}, mime_types:t("php")),
?assertEqual({php, "text/html"}, mime_types:t(global, "php")),
?assertEqual({php, "text/html"}, mime_types:t(Vhost1, "php")),
?assertEqual({php, "application/x-httpd-php"}, mime_types:t(Vhost2,"php")),
?assertEqual({php, "application/x-httpd-php"}, mime_types:t(Vhost2,"PHP")),
?assertEqual({regular, "php5", "application/x-httpd-php5"}, mime_types:revt(Vhost2,"5php")),
?assertEqual({regular, "PHP5", "application/x-httpd-php5"}, mime_types:revt(Vhost2,"5PHP")),
?assertEqual({regular, "text/plain"}, mime_types:t("html")),
?assertEqual({regular, "text/plain"}, mime_types:t(global,"html")),
?assertEqual({regular, "text/plain"}, mime_types:t(Vhost1,"html")),
?assertEqual({regular, "text/plain; charset=UTF-8"}, mime_types:t(Vhost2,"html")),
ok.
default_type(Config) ->
Port1 = testsuite:get_yaws_port(1, Config),
Port2 = testsuite:get_yaws_port(2, Config),
Url1 = testsuite:make_url(http, "127.0.0.1", Port1, "/news"),
Url2 = testsuite:make_url(http, "127.0.0.1", Port2, "/news"),
{ok, {{_,200,_}, Hdrs1, _}} = testsuite:http_get(Url1),
?assertEqual("text/html", proplists:get_value("content-type", Hdrs1)),
{ok, {{_,200,_}, Hdrs2, _}} = testsuite:http_get(Url2),
?assertEqual("text/plain; charset=UTF-8", proplists:get_value("content-type", Hdrs2)),
ok.
yaws_type(Config) ->
Port1 = testsuite:get_yaws_port(1, Config),
Port2 = testsuite:get_yaws_port(2, Config),
Url1 = testsuite:make_url(http, "127.0.0.1", Port1, "/index.yaws"),
Url2 = testsuite:make_url(http, "127.0.0.1", Port2, "/index.yaws"),
{ok, {{_,200,_}, Hdrs1, _}} = testsuite:http_get(Url1),
?assertEqual("text/html", proplists:get_value("content-type", Hdrs1)),
{ok, {{_,200,_}, Hdrs2, _}} = testsuite:http_get(Url2),
?assertEqual("text/xhtml; charset=ISO-8859-1", proplists:get_value("content-type", Hdrs2)),
ok.
erlang_type(Config) ->
Port1 = testsuite:get_yaws_port(1, Config),
Port2 = testsuite:get_yaws_port(2, Config),
Url1 = testsuite:make_url(http, "127.0.0.1", Port1, "/code/myappmod.erl"),
Url2 = testsuite:make_url(http, "127.0.0.1", Port2, "/code/myappmod.erl"),
{ok, {{_,200,_}, Hdrs1, _}} = testsuite:http_get(Url1),
?assertEqual("text/html", proplists:get_value("content-type", Hdrs1)),
{ok, {{_,200,_}, Hdrs2, _}} = testsuite:http_get(Url2),
?assertEqual("text/x-erlang; charset=UTF-8", proplists:get_value("content-type", Hdrs2)),
ok.
gzip_with_charset(Config) ->
Port = testsuite:get_yaws_port(2, Config),
Url = testsuite:make_url(http, "127.0.0.1", Port, "/index.yaws"),
GzHdr = {"Accept-Encoding", "gzip, deflate"},
{ok, {{_,200,_}, Hdrs, _}} = testsuite:http_get(Url, [GzHdr]),
?assertEqual("text/xhtml; charset=ISO-8859-1", proplists:get_value("content-type", Hdrs)),
?assertEqual("gzip", proplists:get_value("content-encoding", Hdrs)),
ok.
multiple_accept_headers(Config) ->
Port1 = testsuite:get_yaws_port(1, Config),
Url1 = testsuite:make_url(http, "127.0.0.1", Port1, "/multiple_accept_headers.yaws"),
AcceptHdrs1 = [{"Accept", "text/html"}, {"Accept", "text/plain"}],
{ok, {{_,200,_}, Hdrs1, _}} = testsuite:http_get(Url1, AcceptHdrs1),
?assertEqual("text/html", proplists:get_value("content-type", Hdrs1)),
?assertEqual("text/html, text/plain",
proplists:get_value("x-test-request-accept", Hdrs1)),
AcceptHdrs2 = [{"Accept", "text/plain"}, {"Accept", "text/html"}],
{ok, {{_,200,_}, Hdrs2, _}} = testsuite:http_get(Url1, AcceptHdrs2),
?assertEqual("text/plain", proplists:get_value("content-type", Hdrs2)),
?assertEqual("text/plain, text/html",
proplists:get_value("x-test-request-accept", Hdrs2)),
AcceptHdrs3 = [{"Accept", "text/html, text/plain"}],
{ok, {{_,200,_}, Hdrs3, _}} = testsuite:http_get(Url1, AcceptHdrs3),
?assertEqual("text/html", proplists:get_value("content-type", Hdrs3)),
?assertEqual("text/html, text/plain",
proplists:get_value("x-test-request-accept", Hdrs3)),
AcceptHdrs4 = [{"Accept", "text/plain, text/html"}],
{ok, {{_,200,_}, Hdrs4, _}} = testsuite:http_get(Url1, AcceptHdrs4),
?assertEqual("text/plain", proplists:get_value("content-type", Hdrs4)),
?assertEqual("text/plain, text/html",
proplists:get_value("x-test-request-accept", Hdrs4)),
AcceptHdrs5 = [{"Accept", "text/plain, application/json"},
{"Accept", "text/html, text/*"}],
{ok, {{_,200,_}, Hdrs5, _}} = testsuite:http_get(Url1, AcceptHdrs5),
?assertEqual("text/plain", proplists:get_value("content-type", Hdrs5)),
?assertEqual("text/plain, application/json, text/html, text/*",
proplists:get_value("x-test-request-accept", Hdrs5)),
AcceptHdrs6 = [{"Accept", ",text/plain"}],
{ok, {{_,200,_}, Hdrs6, _}} = testsuite:http_get(Url1, AcceptHdrs6),
?assertEqual("text/plain", proplists:get_value("content-type", Hdrs6)),
?assertEqual("text/plain",
proplists:get_value("x-test-request-accept", Hdrs6)),
AcceptHdrs7 = [{"Accept", ",text/plain"}],
{ok, {{_,200,_}, Hdrs7, _}} = testsuite:http_get(Url1, AcceptHdrs7),
?assertEqual("text/plain", proplists:get_value("content-type", Hdrs7)),
?assertEqual("text/plain",
proplists:get_value("x-test-request-accept", Hdrs7)),
AcceptHdrs8 = [{"Accept", "text/plain, ,text/html"}],
{ok, {{_,200,_}, Hdrs8, _}} = testsuite:http_get(Url1, AcceptHdrs8),
?assertEqual("text/plain", proplists:get_value("content-type", Hdrs8)),
?assertEqual("text/plain, text/html",
proplists:get_value("x-test-request-accept", Hdrs8)),
AcceptHdrs9 = [{"Accept", ","}],
{ok, {{_,400,_}, _, _}} = testsuite:http_get(Url1, AcceptHdrs9),
ok.
charset_for_404(Config) ->
Port1 = testsuite:get_yaws_port(1, Config),
Port3 = testsuite:get_yaws_port(3, Config),
Url1 = testsuite:make_url(http, "127.0.0.1", Port1, "/404"),
Url3 = testsuite:make_url(http, "127.0.0.1", Port3, "/404"),
{ok, {{_,404,_}, Hdrs1, _}} = testsuite:http_get(Url1),
?assertEqual("text/plain", proplists:get_value("content-type", Hdrs1)),
{ok, {{_,404,_}, Hdrs3, _}} = testsuite:http_get(Url3),
?assertEqual("text/html; charset=UTF-8", proplists:get_value("content-type", Hdrs3)),
ok.
|
42f48ada12c3e39126e64f9feaa480d07fd0247422e902fed83d1c8c52f3608e | ahushh/monaba | Main.hs | {-# LANGUAGE OverloadedStrings #-}
import Control.Applicative ((<$>))
import Control.Arrow (second)
import Control.Monad (forM)
import Control.Monad.IO.Class (liftIO)
import Data.Text (pack, Text, concat)
import Data.Text.Encoding (encodeUtf8, decodeUtf8)
import Data.Char (toLower)
import Data.Monoid ((<>))
import Graphics.ImageMagick.MagickWand
import Prelude hiding (concat)
import System.Random (randomRIO)
import System.Environment (getArgs)
------------------------------------------------------------------------------------------------
-- | Takes a random element from list
pick :: [a] -> IO a
pick xs = (xs!!) <$> randomRIO (0, length xs - 1)
------------------------------------------------------------------------------------------------
colors = ["black","blue","brown","cyan","gray","green","magenta","orange","pink","red","violet","white","yellow"]
chars = filter (`notElem`("Il"::String)) $ ['a'..'x']++['A'..'X']++['1'..'9']
makeCaptcha :: String -> -- ^ Path to captcha
IO (Text, Text) -- ^ captcha value and hint
makeCaptcha path = withMagickWandGenesis $ localGenesis $ do
(_, w) <- magickWand
(_,dw) <- drawingWand
pw <- pixelWand
let len = 5
space = 12.0 :: Double -- space between characters in px
height = 30 -- image height
fSize = 25 -- font size
newImage w (truncate space*(len+2)) height pw
dw `setFontSize` fSize
w `addNoiseImage` randomNoise
blurImage w 0 1
text <- forM [1..len] $ \i -> do
x <- liftIO (randomRIO (-1.0,1.0) :: IO Double)
y <- liftIO (randomRIO (-2.0,2.0) :: IO Double)
char <- liftIO $ pick chars
color <- liftIO $ pick colors
pw `setColor` color
dw `setStrokeColor` pw
drawAnnotation dw (x+space*(fromIntegral i)) ((fSize :: Double)+y) (pack $ char:[])
return (decodeUtf8 $ color, pack $ (:[]) $ toLower $ char)
drawImage w dw
trimImage w 0
writeImage w $ Just $ pack path
color <- liftIO $ fst <$> pick text
let filteredText = concat $ map snd $ filter ((==color).fst) text
return (filteredText, "<div style='width:50px; height: 30px; display:inline-block; background-color:"<>color<>";'></div>")
------------------------------------------------------------------------------------------------
main = do
putStrLn . show =<< makeCaptcha . head =<< getArgs
| null | https://raw.githubusercontent.com/ahushh/monaba/9fbfffcc970da0ebaf2d5df716c3bb075b1c761a/monaba/captcha/Yoba/Main.hs | haskell | # LANGUAGE OverloadedStrings #
----------------------------------------------------------------------------------------------
| Takes a random element from list
----------------------------------------------------------------------------------------------
^ Path to captcha
^ captcha value and hint
space between characters in px
image height
font size
---------------------------------------------------------------------------------------------- | import Control.Applicative ((<$>))
import Control.Arrow (second)
import Control.Monad (forM)
import Control.Monad.IO.Class (liftIO)
import Data.Text (pack, Text, concat)
import Data.Text.Encoding (encodeUtf8, decodeUtf8)
import Data.Char (toLower)
import Data.Monoid ((<>))
import Graphics.ImageMagick.MagickWand
import Prelude hiding (concat)
import System.Random (randomRIO)
import System.Environment (getArgs)
pick :: [a] -> IO a
pick xs = (xs!!) <$> randomRIO (0, length xs - 1)
colors = ["black","blue","brown","cyan","gray","green","magenta","orange","pink","red","violet","white","yellow"]
chars = filter (`notElem`("Il"::String)) $ ['a'..'x']++['A'..'X']++['1'..'9']
makeCaptcha path = withMagickWandGenesis $ localGenesis $ do
(_, w) <- magickWand
(_,dw) <- drawingWand
pw <- pixelWand
let len = 5
newImage w (truncate space*(len+2)) height pw
dw `setFontSize` fSize
w `addNoiseImage` randomNoise
blurImage w 0 1
text <- forM [1..len] $ \i -> do
x <- liftIO (randomRIO (-1.0,1.0) :: IO Double)
y <- liftIO (randomRIO (-2.0,2.0) :: IO Double)
char <- liftIO $ pick chars
color <- liftIO $ pick colors
pw `setColor` color
dw `setStrokeColor` pw
drawAnnotation dw (x+space*(fromIntegral i)) ((fSize :: Double)+y) (pack $ char:[])
return (decodeUtf8 $ color, pack $ (:[]) $ toLower $ char)
drawImage w dw
trimImage w 0
writeImage w $ Just $ pack path
color <- liftIO $ fst <$> pick text
let filteredText = concat $ map snd $ filter ((==color).fst) text
return (filteredText, "<div style='width:50px; height: 30px; display:inline-block; background-color:"<>color<>";'></div>")
main = do
putStrLn . show =<< makeCaptcha . head =<< getArgs
|
c5909bed8d2cf80da573d7440a5df65d15ef8362c85b11f96a2ba040269bed3b | circleci/rollcage | ring_middleware.clj | (ns circleci.rollcage.ring-middleware
(:require [circleci.rollcage.core :as rollcage]))
(defn wrap-rollbar [handler rollcage-client]
(if-not rollcage-client
handler
(fn [req]
(try
(handler req)
(catch Exception e
(rollcage/error rollcage-client e {:url (:uri req)})
(throw e))))))
| null | https://raw.githubusercontent.com/circleci/rollcage/6cdf17c454978235efdde1643ee28f7d26f7488d/src/circleci/rollcage/ring_middleware.clj | clojure | (ns circleci.rollcage.ring-middleware
(:require [circleci.rollcage.core :as rollcage]))
(defn wrap-rollbar [handler rollcage-client]
(if-not rollcage-client
handler
(fn [req]
(try
(handler req)
(catch Exception e
(rollcage/error rollcage-client e {:url (:uri req)})
(throw e))))))
| |
d781326459bed3023772ecd1846669f8a3f51e65713d95a8abf78b62a4f1c991 | vyorkin/tiger | frame.mli | (** Holds information about formal parameters and
local variables allocated in this frame *)
type t [@@deriving show]
(** Abstract location of a formal parameter (function argument) or
a local variable that may be placed in a frame or in a register *)
type access [@@deriving show]
(** Makes a new frame for a function with the
given label and formal parameters *)
val mk : label:Temp.label -> formals:bool list -> t
(** Get a unique identifier of the given stack frame *)
val id : t -> int
(** Extracts a list of accesses denoting
the locations where the formal parameters will be
kept at runtime, as seen from inside the callee *)
val formals : t -> access list
(** Allocates a new local variable in the given frame or in a register.
The boolean argument specifies whether the new variable
escapes and needs to go in the frame.
Returns "in-memory" access with an offset from the frame pointer or
"in-register" access in case if it can be allocated in a register *)
val alloc_local : t -> escapes:bool -> access
module Printer : sig
val print_frame : t -> string
val print_access : access -> string
end
| null | https://raw.githubusercontent.com/vyorkin/tiger/54dd179c1cd291df42f7894abce3ee9064e18def/chapter6/lib/frame.mli | ocaml | * Holds information about formal parameters and
local variables allocated in this frame
* Abstract location of a formal parameter (function argument) or
a local variable that may be placed in a frame or in a register
* Makes a new frame for a function with the
given label and formal parameters
* Get a unique identifier of the given stack frame
* Extracts a list of accesses denoting
the locations where the formal parameters will be
kept at runtime, as seen from inside the callee
* Allocates a new local variable in the given frame or in a register.
The boolean argument specifies whether the new variable
escapes and needs to go in the frame.
Returns "in-memory" access with an offset from the frame pointer or
"in-register" access in case if it can be allocated in a register | type t [@@deriving show]
type access [@@deriving show]
val mk : label:Temp.label -> formals:bool list -> t
val id : t -> int
val formals : t -> access list
val alloc_local : t -> escapes:bool -> access
module Printer : sig
val print_frame : t -> string
val print_access : access -> string
end
|
b15aea87f593b280821fd1f741063d60462efd31c4dbf51f15c0f4838ee1f2f8 | sirherrbatka/statistical-learning | forest scratch.lisp | (cl:in-package #:statistical-learning.forest)
(defparameter *data*
(make-array (list 20 1) :element-type 'double-float
:initial-element 0.0d0))
(defparameter *target*
(make-array (list 20 1) :element-type 'double-float
:initial-element 0.0d0))
(iterate
(for i from 0 below 20)
(setf (aref *target* i 0) (if (oddp i) 1.0d0 0.0d0)))
(iterate
(for i from 0 below 20)
(setf (aref *data* i 0)
(if (oddp i)
(statistical-learning.algorithms::random-uniform 0.7d0 1.0d0)
(statistical-learning.algorithms::random-uniform 0.0d0 0.8d0))))
(defparameter *training-parameters*
(make 'statistical-learning.algorithms:information-gain-classification
:maximal-depth 3
:minimal-difference 0.001d0
:minimal-size 1
:trials-count 500
:parallel nil))
(defparameter *forest-parameters*
(make 'random-forest-parameters
:trees-count 3
:forest-class 'classification-random-forest
:parallel nil
:tree-attributes-count 1
:tree-sample-size 5
:tree-parameters *training-parameters*))
(defparameter *forest* (statistical-learning.mp:make-model *forest-parameters*
*data*
*target*))
(iterate
(with attribute-value = (statistical-learning.tp:attribute-value *tree*))
(with result = (make-array 20))
(for i from 0 below 20)
(setf (aref result i) (list (> (aref *data* i 0)
attribute-value)
(aref *target* i 0)))
(finally
(print result)))
| null | https://raw.githubusercontent.com/sirherrbatka/statistical-learning/491a9c749f0bb09194793bc26487a10fae69dae0/scratch/forest%20scratch.lisp | lisp | (cl:in-package #:statistical-learning.forest)
(defparameter *data*
(make-array (list 20 1) :element-type 'double-float
:initial-element 0.0d0))
(defparameter *target*
(make-array (list 20 1) :element-type 'double-float
:initial-element 0.0d0))
(iterate
(for i from 0 below 20)
(setf (aref *target* i 0) (if (oddp i) 1.0d0 0.0d0)))
(iterate
(for i from 0 below 20)
(setf (aref *data* i 0)
(if (oddp i)
(statistical-learning.algorithms::random-uniform 0.7d0 1.0d0)
(statistical-learning.algorithms::random-uniform 0.0d0 0.8d0))))
(defparameter *training-parameters*
(make 'statistical-learning.algorithms:information-gain-classification
:maximal-depth 3
:minimal-difference 0.001d0
:minimal-size 1
:trials-count 500
:parallel nil))
(defparameter *forest-parameters*
(make 'random-forest-parameters
:trees-count 3
:forest-class 'classification-random-forest
:parallel nil
:tree-attributes-count 1
:tree-sample-size 5
:tree-parameters *training-parameters*))
(defparameter *forest* (statistical-learning.mp:make-model *forest-parameters*
*data*
*target*))
(iterate
(with attribute-value = (statistical-learning.tp:attribute-value *tree*))
(with result = (make-array 20))
(for i from 0 below 20)
(setf (aref result i) (list (> (aref *data* i 0)
attribute-value)
(aref *target* i 0)))
(finally
(print result)))
| |
36959c748c07c572392c29ecba32f22408c5f0d5e219fa4b18b15f2d37bbc007 | drathier/elm-offline | Explorer.hs | # OPTIONS_GHC -Wall #
module Deps.Explorer
( Explorer
, Metadata
, Info(..)
, run
, exists
, getVersions
, getConstraints
)
where
| It is expensive to load ALL package metadata . You would need to :
1 . Know all the packages and all their versions .
2 . Download or read the elm.json file for each version .
The goal of this module is to only pay for ( 1 ) and pay for ( 2 ) as needed .
1. Know all the packages and all their versions.
2. Download or read the elm.json file for each version.
The goal of this module is to only pay for (1) and pay for (2) as needed.
-}
import Control.Monad.Except (liftIO, lift, throwError)
import Control.Monad.State (StateT, evalStateT, gets, modify)
import Data.Map (Map)
import qualified Data.Map as Map
import Elm.Package (Name, Version)
import qualified Deps.Cache as Cache
import qualified Elm.PerUserCache as PerUserCache
import qualified Elm.Project.Json as Project
import Elm.Project.Constraint (Constraint)
import qualified Reporting.Exit as Exit
import qualified Reporting.Exit.Deps as E
import qualified Reporting.Task as Task
-- EXPLORER
type Explorer =
StateT Metadata Task.Task
data Metadata =
Metadata
{ _registry :: Cache.PackageRegistry
, _info :: Map (Name, Version) Info
}
data Info =
Info
{ _elm :: Constraint
, _pkgs :: Map Name Constraint
}
run :: Cache.PackageRegistry -> Explorer a -> Task.Task a
run registry explorer =
evalStateT explorer (Metadata registry Map.empty)
-- EXISTS
exists :: Name -> Explorer ()
exists name =
do registry <- gets _registry
case Cache.getVersions name registry of
Right _ ->
return ()
Left suggestions ->
throwError (Exit.Deps (E.PackageNotFound name suggestions))
-- VERSIONS
getVersions :: Name -> Explorer [Version]
getVersions name =
do registry <- gets _registry
case Cache.getVersions name registry of
Right versions ->
return versions
Left _suggestions ->
do elmHome <- liftIO PerUserCache.getElmHome
throwError (Exit.Deps (E.CorruptVersionCache elmHome name))
-- CONSTRAINTS
getConstraints :: Name -> Version -> Explorer Info
getConstraints name version =
do allInfo <- gets _info
case Map.lookup (name, version) allInfo of
Just info ->
return info
Nothing ->
do pkgInfo <- lift $ Cache.getElmJson name version
let elm = Project._pkg_elm_version pkgInfo
let pkgs = Project._pkg_deps pkgInfo
let info = Info elm pkgs
modify $ \(Metadata vsns infos) ->
Metadata vsns $ Map.insert (name, version) info infos
return info
| null | https://raw.githubusercontent.com/drathier/elm-offline/f562198cac29f4cda15b69fde7e66edde89b34fa/builder/src/Deps/Explorer.hs | haskell | EXPLORER
EXISTS
VERSIONS
CONSTRAINTS | # OPTIONS_GHC -Wall #
module Deps.Explorer
( Explorer
, Metadata
, Info(..)
, run
, exists
, getVersions
, getConstraints
)
where
| It is expensive to load ALL package metadata . You would need to :
1 . Know all the packages and all their versions .
2 . Download or read the elm.json file for each version .
The goal of this module is to only pay for ( 1 ) and pay for ( 2 ) as needed .
1. Know all the packages and all their versions.
2. Download or read the elm.json file for each version.
The goal of this module is to only pay for (1) and pay for (2) as needed.
-}
import Control.Monad.Except (liftIO, lift, throwError)
import Control.Monad.State (StateT, evalStateT, gets, modify)
import Data.Map (Map)
import qualified Data.Map as Map
import Elm.Package (Name, Version)
import qualified Deps.Cache as Cache
import qualified Elm.PerUserCache as PerUserCache
import qualified Elm.Project.Json as Project
import Elm.Project.Constraint (Constraint)
import qualified Reporting.Exit as Exit
import qualified Reporting.Exit.Deps as E
import qualified Reporting.Task as Task
type Explorer =
StateT Metadata Task.Task
data Metadata =
Metadata
{ _registry :: Cache.PackageRegistry
, _info :: Map (Name, Version) Info
}
data Info =
Info
{ _elm :: Constraint
, _pkgs :: Map Name Constraint
}
run :: Cache.PackageRegistry -> Explorer a -> Task.Task a
run registry explorer =
evalStateT explorer (Metadata registry Map.empty)
exists :: Name -> Explorer ()
exists name =
do registry <- gets _registry
case Cache.getVersions name registry of
Right _ ->
return ()
Left suggestions ->
throwError (Exit.Deps (E.PackageNotFound name suggestions))
getVersions :: Name -> Explorer [Version]
getVersions name =
do registry <- gets _registry
case Cache.getVersions name registry of
Right versions ->
return versions
Left _suggestions ->
do elmHome <- liftIO PerUserCache.getElmHome
throwError (Exit.Deps (E.CorruptVersionCache elmHome name))
getConstraints :: Name -> Version -> Explorer Info
getConstraints name version =
do allInfo <- gets _info
case Map.lookup (name, version) allInfo of
Just info ->
return info
Nothing ->
do pkgInfo <- lift $ Cache.getElmJson name version
let elm = Project._pkg_elm_version pkgInfo
let pkgs = Project._pkg_deps pkgInfo
let info = Info elm pkgs
modify $ \(Metadata vsns infos) ->
Metadata vsns $ Map.insert (name, version) info infos
return info
|
68749c5b8869c97f3f9634a55159f890fa10434866059e9d44b6bd35ce05044a | AdaCore/why3 | infer_cfg.mli | (********************************************************************)
(* *)
The Why3 Verification Platform / The Why3 Development Team
Copyright 2010 - 2022 -- Inria - CNRS - Paris - Saclay University
(* *)
(* This software is distributed under the terms of the GNU Lesser *)
General Public License version 2.1 , with the special exception
(* on linking described in file LICENSE. *)
(* *)
(********************************************************************)
open Domain
open Infer_why3
open Term
open Expr
open Ity
val infer_print_cfg : Debug.flag
val infer_print_ai_result : Debug.flag
module type INFERCFG = sig
module QDom : Domain.TERM_DOMAIN
type control_point
type xcontrol_point = control_point * xsymbol
type control_points = control_point * control_point * xcontrol_point list
type domain
type cfg
type context = QDom.man
val empty_context : unit -> context
val start_cfg : unit -> cfg
val cfg_size : cfg -> int * int
(** (number of nodes, number of hyperedges) *)
val put_expr_in_cfg : cfg -> context -> ?ret:vsymbol option -> expr ->
control_points
val put_expr_with_pre : cfg -> context -> expr -> term list ->
control_points
val eval_fixpoints : cfg -> context -> (expr * domain) list
val domain_to_term : cfg -> context -> domain -> term
val add_variable : context -> pvsymbol -> unit
(* [add_variable ctx pv] adds the variable pv to the *)
end
module Make(S:sig
module Infer_why3 : INFERWHY3
val widening : int
end)(Domain : DOMAIN): INFERCFG
| null | https://raw.githubusercontent.com/AdaCore/why3/4441127004d53cf2cb0f722fed4a930ccf040ee4/src/infer/infer_cfg.mli | ocaml | ******************************************************************
This software is distributed under the terms of the GNU Lesser
on linking described in file LICENSE.
******************************************************************
* (number of nodes, number of hyperedges)
[add_variable ctx pv] adds the variable pv to the | The Why3 Verification Platform / The Why3 Development Team
Copyright 2010 - 2022 -- Inria - CNRS - Paris - Saclay University
General Public License version 2.1 , with the special exception
open Domain
open Infer_why3
open Term
open Expr
open Ity
val infer_print_cfg : Debug.flag
val infer_print_ai_result : Debug.flag
module type INFERCFG = sig
module QDom : Domain.TERM_DOMAIN
type control_point
type xcontrol_point = control_point * xsymbol
type control_points = control_point * control_point * xcontrol_point list
type domain
type cfg
type context = QDom.man
val empty_context : unit -> context
val start_cfg : unit -> cfg
val cfg_size : cfg -> int * int
val put_expr_in_cfg : cfg -> context -> ?ret:vsymbol option -> expr ->
control_points
val put_expr_with_pre : cfg -> context -> expr -> term list ->
control_points
val eval_fixpoints : cfg -> context -> (expr * domain) list
val domain_to_term : cfg -> context -> domain -> term
val add_variable : context -> pvsymbol -> unit
end
module Make(S:sig
module Infer_why3 : INFERWHY3
val widening : int
end)(Domain : DOMAIN): INFERCFG
|
4c1b6e63978368ca711c532aea9b031655c7530bfd1c3f0424a3cc7d28c412c6 | hamler-lang/hamler | IO.erl | %%---------------------------------------------------------------------------
%% |
%% Module : IO
Copyright : ( c ) 2020 - 2021 EMQ Technologies Co. , Ltd.
%% License : BSD-style (see the LICENSE file)
%%
Maintainer : ,
,
%% Stability : experimental
%% Portability : portable
%%
The IO FFI module .
%%
%%---------------------------------------------------------------------------
-module('IO').
-include("../Foreign.hrl").
-export([ readFile/1
, writeFile/2
, appendFile/2
, withFile/3
, consultFile/1
]).
-import('System.File', [open/2]).
readFile(FilePath) ->
?IO(return(file:read_file(FilePath))).
writeFile(FilePath, Data) ->
?IO(return(file:write_file(FilePath, Data, [write]))).
appendFile(FilePath, Data) ->
?IO(return(file:write_file(FilePath, Data, [append]))).
withFile(FilePath, Mode, Fun) ->
?IO(case ?RunIO(open(FilePath, Mode)) of
{ok, IoDevice} ->
try Fun(IoDevice) after file:close(IoDevice) end;
{error, Reason} -> error(Reason)
end).
consultFile(FilePath) ->
?IO(return(file:consult(FilePath))).
-compile({inline, [return/1]}).
return(ok) -> ok;
return({ok, Data}) -> Data;
return({error, Reason}) -> error(Reason).
| null | https://raw.githubusercontent.com/hamler-lang/hamler/3ba89dde3067076e112c60351b019eeed6c97dd7/lib/System/IO.erl | erlang | ---------------------------------------------------------------------------
|
Module : IO
License : BSD-style (see the LICENSE file)
Stability : experimental
Portability : portable
--------------------------------------------------------------------------- | Copyright : ( c ) 2020 - 2021 EMQ Technologies Co. , Ltd.
Maintainer : ,
,
The IO FFI module .
-module('IO').
-include("../Foreign.hrl").
-export([ readFile/1
, writeFile/2
, appendFile/2
, withFile/3
, consultFile/1
]).
-import('System.File', [open/2]).
readFile(FilePath) ->
?IO(return(file:read_file(FilePath))).
writeFile(FilePath, Data) ->
?IO(return(file:write_file(FilePath, Data, [write]))).
appendFile(FilePath, Data) ->
?IO(return(file:write_file(FilePath, Data, [append]))).
withFile(FilePath, Mode, Fun) ->
?IO(case ?RunIO(open(FilePath, Mode)) of
{ok, IoDevice} ->
try Fun(IoDevice) after file:close(IoDevice) end;
{error, Reason} -> error(Reason)
end).
consultFile(FilePath) ->
?IO(return(file:consult(FilePath))).
-compile({inline, [return/1]}).
return(ok) -> ok;
return({ok, Data}) -> Data;
return({error, Reason}) -> error(Reason).
|
393830227ec77b7b2b52b4a923e59d51f1eb6ac8ddfbb631fd2633a5bd91d81b | tolysz/prepare-ghcjs | Zip.hs | {-# LANGUAGE Safe #-}
# LANGUAGE TypeOperators #
-----------------------------------------------------------------------------
-- |
Module : Control . . Zip
Copyright : ( c ) 2011 ,
( c ) 2011
( c ) University Tuebingen 2011
-- License : BSD-style (see the file libraries/base/LICENSE)
-- Maintainer :
-- Stability : experimental
-- Portability : portable
--
Monadic zipping ( used for monad comprehensions )
--
-----------------------------------------------------------------------------
module Control.Monad.Zip where
import Control.Monad (liftM, liftM2)
import Data.Monoid
import Data.Proxy
import GHC.Generics
| ` MonadZip ` type class . Minimal definition : ` mzip ` or ` mzipWith `
--
-- Instances should satisfy the laws:
--
* Naturality :
--
> liftM ( f * * * g ) ( mzip ma mb ) = mzip ( liftM f ma ) ( liftM g mb )
--
-- * Information Preservation:
--
-- > liftM (const ()) ma = liftM (const ()) mb
-- > ==>
( mzip ma mb ) = ( ma , )
--
class Monad m => MonadZip m where
# MINIMAL mzip | mzipWith #
mzip :: m a -> m b -> m (a,b)
mzip = mzipWith (,)
mzipWith :: (a -> b -> c) -> m a -> m b -> m c
mzipWith f ma mb = liftM (uncurry f) (mzip ma mb)
munzip :: m (a,b) -> (m a, m b)
munzip mab = (liftM fst mab, liftM snd mab)
-- munzip is a member of the class because sometimes
-- you can implement it more efficiently than the
above default code . See Trac # 4370 comment by
instance MonadZip [] where
mzip = zip
mzipWith = zipWith
munzip = unzip
instance MonadZip Dual where
-- Cannot use coerce, it's unsafe
mzipWith = liftM2
instance MonadZip Sum where
mzipWith = liftM2
instance MonadZip Product where
mzipWith = liftM2
instance MonadZip Maybe where
mzipWith = liftM2
instance MonadZip First where
mzipWith = liftM2
instance MonadZip Last where
mzipWith = liftM2
instance MonadZip f => MonadZip (Alt f) where
mzipWith f (Alt ma) (Alt mb) = Alt (mzipWith f ma mb)
instance MonadZip Proxy where
mzipWith _ _ _ = Proxy
-- Instances for GHC.Generics
instance MonadZip U1 where
mzipWith _ _ _ = U1
instance MonadZip Par1 where
mzipWith = liftM2
instance MonadZip f => MonadZip (Rec1 f) where
mzipWith f (Rec1 fa) (Rec1 fb) = Rec1 (mzipWith f fa fb)
instance MonadZip f => MonadZip (M1 i c f) where
mzipWith f (M1 fa) (M1 fb) = M1 (mzipWith f fa fb)
instance (MonadZip f, MonadZip g) => MonadZip (f :*: g) where
mzipWith f (x1 :*: y1) (x2 :*: y2) = mzipWith f x1 x2 :*: mzipWith f y1 y2
| null | https://raw.githubusercontent.com/tolysz/prepare-ghcjs/8499e14e27854a366e98f89fab0af355056cf055/spec-lts8/base-pure/Control/Monad/Zip.hs | haskell | # LANGUAGE Safe #
---------------------------------------------------------------------------
|
License : BSD-style (see the file libraries/base/LICENSE)
Maintainer :
Stability : experimental
Portability : portable
---------------------------------------------------------------------------
Instances should satisfy the laws:
* Information Preservation:
> liftM (const ()) ma = liftM (const ()) mb
> ==>
munzip is a member of the class because sometimes
you can implement it more efficiently than the
Cannot use coerce, it's unsafe
Instances for GHC.Generics | # LANGUAGE TypeOperators #
Module : Control . . Zip
Copyright : ( c ) 2011 ,
( c ) 2011
( c ) University Tuebingen 2011
Monadic zipping ( used for monad comprehensions )
module Control.Monad.Zip where
import Control.Monad (liftM, liftM2)
import Data.Monoid
import Data.Proxy
import GHC.Generics
| ` MonadZip ` type class . Minimal definition : ` mzip ` or ` mzipWith `
* Naturality :
> liftM ( f * * * g ) ( mzip ma mb ) = mzip ( liftM f ma ) ( liftM g mb )
( mzip ma mb ) = ( ma , )
class Monad m => MonadZip m where
# MINIMAL mzip | mzipWith #
mzip :: m a -> m b -> m (a,b)
mzip = mzipWith (,)
mzipWith :: (a -> b -> c) -> m a -> m b -> m c
mzipWith f ma mb = liftM (uncurry f) (mzip ma mb)
munzip :: m (a,b) -> (m a, m b)
munzip mab = (liftM fst mab, liftM snd mab)
above default code . See Trac # 4370 comment by
instance MonadZip [] where
mzip = zip
mzipWith = zipWith
munzip = unzip
instance MonadZip Dual where
mzipWith = liftM2
instance MonadZip Sum where
mzipWith = liftM2
instance MonadZip Product where
mzipWith = liftM2
instance MonadZip Maybe where
mzipWith = liftM2
instance MonadZip First where
mzipWith = liftM2
instance MonadZip Last where
mzipWith = liftM2
instance MonadZip f => MonadZip (Alt f) where
mzipWith f (Alt ma) (Alt mb) = Alt (mzipWith f ma mb)
instance MonadZip Proxy where
mzipWith _ _ _ = Proxy
instance MonadZip U1 where
mzipWith _ _ _ = U1
instance MonadZip Par1 where
mzipWith = liftM2
instance MonadZip f => MonadZip (Rec1 f) where
mzipWith f (Rec1 fa) (Rec1 fb) = Rec1 (mzipWith f fa fb)
instance MonadZip f => MonadZip (M1 i c f) where
mzipWith f (M1 fa) (M1 fb) = M1 (mzipWith f fa fb)
instance (MonadZip f, MonadZip g) => MonadZip (f :*: g) where
mzipWith f (x1 :*: y1) (x2 :*: y2) = mzipWith f x1 x2 :*: mzipWith f y1 y2
|
5bec52a154817fa9ca6a3cee6985114de7af4c6461f985d30055d3d133424dc2 | dhammikamare/Learn-OCaml | replace.ml | Task : Write a function replace l x y which replaces every occurrence of
* item x with y in list l .
*
* Author : | -marasinghe
* item x with y in list l .
*
* Author : Dhammika Marasinghe | -marasinghe
*)
let rec replace l x y =
match l with
| [] -> []
| hd::tl -> if hd = x then y::replace tl x y
else hd::replace tl x y;;
(* test *)
let num = [1; 2 ; 3; 1];;
replace num 1 8;;
| null | https://raw.githubusercontent.com/dhammikamare/Learn-OCaml/2d4e3da38ee86cd7477964ffb8756a8483260322/lab07%20Lists/replace.ml | ocaml | test | Task : Write a function replace l x y which replaces every occurrence of
* item x with y in list l .
*
* Author : | -marasinghe
* item x with y in list l .
*
* Author : Dhammika Marasinghe | -marasinghe
*)
let rec replace l x y =
match l with
| [] -> []
| hd::tl -> if hd = x then y::replace tl x y
else hd::replace tl x y;;
let num = [1; 2 ; 3; 1];;
replace num 1 8;;
|
3615f8b87f243fc654401aef0fc52cb2fbf2cb380dd645576430b14411ddd9b9 | jfeser/castor | cozy.mli | (* open Ast *)
type binop = [ `Le | `Lt | `Ge | `Gt | `Add | `Sub | `Mul | `Div | `Eq | `And ]
[@@deriving sexp]
type expr =
[ `Binop of binop * expr * expr
| `Call of string * expr list
| `Cond of expr * expr * expr
| `Int of int
| `Len of query
| `Sum of query
| `The of query
| `Tuple of expr list
| `TupleGet of expr * int
| `Var of string
| `Let of string * expr * expr
| `String of string ]
[@@deriving sexp]
and 'a lambda = [ `Lambda of string * 'a ] [@@deriving sexp]
and query =
[ `Distinct of query
| `Filter of expr lambda * query
| `Flatmap of query lambda * query
| `Map of expr lambda * query
| `Table of string
| `Empty ]
[@@deriving sexp]
val cost : query - > Big_o.t
(* val to_string : string -> Name.t List.t -> t -> string *)
(* (\** Convert a layout to a cozy query. Takes the name for the benchmark, a list *)
(* of parameters, and a layout. *\) *)
| null | https://raw.githubusercontent.com/jfeser/castor/e9f394e9c0984300f71dc77b5a457ae4e4faa226/lib/cozy.mli | ocaml | open Ast
val to_string : string -> Name.t List.t -> t -> string
(\** Convert a layout to a cozy query. Takes the name for the benchmark, a list
of parameters, and a layout. *\) |
type binop = [ `Le | `Lt | `Ge | `Gt | `Add | `Sub | `Mul | `Div | `Eq | `And ]
[@@deriving sexp]
type expr =
[ `Binop of binop * expr * expr
| `Call of string * expr list
| `Cond of expr * expr * expr
| `Int of int
| `Len of query
| `Sum of query
| `The of query
| `Tuple of expr list
| `TupleGet of expr * int
| `Var of string
| `Let of string * expr * expr
| `String of string ]
[@@deriving sexp]
and 'a lambda = [ `Lambda of string * 'a ] [@@deriving sexp]
and query =
[ `Distinct of query
| `Filter of expr lambda * query
| `Flatmap of query lambda * query
| `Map of expr lambda * query
| `Table of string
| `Empty ]
[@@deriving sexp]
val cost : query - > Big_o.t
|
7c43d56215195dfd3b45efc8e101a71e4038efd9cb54ce0132942cb0e9f83a33 | swamp-agr/lambdabot-telegram-plugins | Main.hs | {-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Monad
import Control.Monad.Identity
import Data.Char
import Data.Version
import Lambdabot.Main
import System.Console.GetOpt
import System.Environment
import System.Exit
import System.IO
import Lambdabot.Config.Telegram
import Modules (modulesInfo)
import qualified Paths_lambdabot_telegram_plugins as P
flags :: [OptDescr (IO (DSum Config Identity))]
flags =
[ Option "h?" ["help"] (NoArg (usage [])) "Print this help message"
, Option "l" [] (arg "<level>" consoleLogLevel level) "Set the logging level"
, Option "t" ["trust"] (arg "<package>" trustedPackages strs) "Trust the specified packages when evaluating code"
, Option "V" ["version"] (NoArg version) "Print the version of lambdabot"
, Option "X" [] (arg "<extension>" languageExts strs) "Set a GHC language extension for @run"
, Option "n" ["name"] (arg "<name>" telegramBotName name) "Set telegram bot name"
]
where
arg :: String -> Config t -> (String -> IO t) -> ArgDescr (IO (DSum Config Identity))
arg descr key fn = ReqArg (fmap (key ==>) . fn) descr
strs = return . (:[])
name = return
level str = case reads (map toUpper str) of
(lv, []):_ -> return lv
_ -> usage
[ "Unknown log level."
, "Valid levels are: " ++ show [minBound .. maxBound :: Priority]
]
versionString :: String
versionString = ("lambdabot version " ++ showVersion P.version)
version :: IO a
version = do
putStrLn versionString
exitWith ExitSuccess
usage :: [String] -> IO a
usage errors = do
cmd <- getProgName
let isErr = not (null errors)
out = if isErr then stderr else stdout
mapM_ (hPutStrLn out) errors
when isErr (hPutStrLn out "")
hPutStrLn out versionString
hPutStr out (usageInfo (cmd ++ " [options]") flags)
exitWith (if isErr then ExitFailure 1 else ExitSuccess)
-- do argument handling
main :: IO ()
main = do
(config, nonOpts, errors) <- getOpt Permute flags <$> getArgs
when (not (null errors && null nonOpts)) (usage errors)
config' <- sequence config
dir <- P.getDataDir
exitWith <=< lambdabotMain modulesInfo $
[ dataDir ==> dir
, disabledCommands ==> ["quit"]
, telegramLambdabotVersion ==> P.version
, onStartupCmds ==> ["telegram"]
, enableInsults ==> False
] ++ config'
| null | https://raw.githubusercontent.com/swamp-agr/lambdabot-telegram-plugins/24420d751d1b667fe4c3dfc8916204b8eba002d6/app/Main.hs | haskell | # LANGUAGE OverloadedStrings #
do argument handling | module Main where
import Control.Monad
import Control.Monad.Identity
import Data.Char
import Data.Version
import Lambdabot.Main
import System.Console.GetOpt
import System.Environment
import System.Exit
import System.IO
import Lambdabot.Config.Telegram
import Modules (modulesInfo)
import qualified Paths_lambdabot_telegram_plugins as P
flags :: [OptDescr (IO (DSum Config Identity))]
flags =
[ Option "h?" ["help"] (NoArg (usage [])) "Print this help message"
, Option "l" [] (arg "<level>" consoleLogLevel level) "Set the logging level"
, Option "t" ["trust"] (arg "<package>" trustedPackages strs) "Trust the specified packages when evaluating code"
, Option "V" ["version"] (NoArg version) "Print the version of lambdabot"
, Option "X" [] (arg "<extension>" languageExts strs) "Set a GHC language extension for @run"
, Option "n" ["name"] (arg "<name>" telegramBotName name) "Set telegram bot name"
]
where
arg :: String -> Config t -> (String -> IO t) -> ArgDescr (IO (DSum Config Identity))
arg descr key fn = ReqArg (fmap (key ==>) . fn) descr
strs = return . (:[])
name = return
level str = case reads (map toUpper str) of
(lv, []):_ -> return lv
_ -> usage
[ "Unknown log level."
, "Valid levels are: " ++ show [minBound .. maxBound :: Priority]
]
versionString :: String
versionString = ("lambdabot version " ++ showVersion P.version)
version :: IO a
version = do
putStrLn versionString
exitWith ExitSuccess
usage :: [String] -> IO a
usage errors = do
cmd <- getProgName
let isErr = not (null errors)
out = if isErr then stderr else stdout
mapM_ (hPutStrLn out) errors
when isErr (hPutStrLn out "")
hPutStrLn out versionString
hPutStr out (usageInfo (cmd ++ " [options]") flags)
exitWith (if isErr then ExitFailure 1 else ExitSuccess)
main :: IO ()
main = do
(config, nonOpts, errors) <- getOpt Permute flags <$> getArgs
when (not (null errors && null nonOpts)) (usage errors)
config' <- sequence config
dir <- P.getDataDir
exitWith <=< lambdabotMain modulesInfo $
[ dataDir ==> dir
, disabledCommands ==> ["quit"]
, telegramLambdabotVersion ==> P.version
, onStartupCmds ==> ["telegram"]
, enableInsults ==> False
] ++ config'
|
47583cd5813fd9b28e52306f05a18f69387863ecfce8107d8b01cdbd14fa01fc | jasongilman/crdt-edit | logoot.clj | (ns crdt-edit.test.logoot
(:require [clojure.test :refer :all]
[clojure.test.check.properties :refer [for-all]]
[clojure.test.check.clojure-test :refer [defspec]]
[clojure.test.check :as tc]
[clojure.test.check.generators :as gen]
[crdt-edit.logoot :as l]
[clojure.pprint :refer [pprint]]))
(def site-gen
"Site generator."
(gen/elements [:a :b :c :d]))
(def position-identifier-gen
"Position identifier generator."
(gen/fmap (partial apply l/->PositionIdentifier)
(gen/tuple gen/pos-int site-gen)))
(def position-gen
"Position generator"
(gen/fmap l/->Position
(gen/vector position-identifier-gen 1 5)))
(def two-unique-positions-in-order
"Generator of two unique positions in sorted order."
(gen/fmap
sort
(gen/such-that
(partial apply not=)
(gen/vector position-gen 2))))
(defn mid
"Returns the middle integer between two ints"
[^long n1 ^long n2]
(int (/ (+ n1 n2) 2)))
Checks that between any two positions another position can be found and inserted correctly
(defspec intermediate-position-spec 1000
(for-all [positions two-unique-positions-in-order
site site-gen]
(let [[pos1 pos2] positions
middle-pos (l/intermediate-position site pos1 pos2)
expected-order [pos1 middle-pos pos2]]
(and
(= expected-order (sort expected-order))
(not= pos1 middle-pos)
(not= pos2 middle-pos)))))
(defn pos-builder
"Helps build positions. Takes a sequence a position int site pairs"
[& pairs]
(->> pairs
(partition 2)
(map (partial apply l/->PositionIdentifier))
l/->Position))
(def max-int Integer/MAX_VALUE)
(def min-int Integer/MIN_VALUE)
(deftest intermediate-position-examples
(are [site pos1-parts pos2-parts expected-parts]
(let [pos1 (apply pos-builder pos1-parts)
pos2 (apply pos-builder pos2-parts)
expected (apply pos-builder expected-parts)
actual (l/intermediate-position site pos1 pos2 mid)]
(if (= expected actual)
true
(do
(println "expected:")
(pprint expected)
(println "actual")
(pprint actual))))
:a [1 :a 5 :a 8 :a] [3 :a] [2 :a]
:a [4 :a 1 :a] [4 :a 3 :a] [4 :a 2 :a]
;; Use site to find position in between matching or separated by one.
:f [5 :a 1 :e] [5 :a 2 :a] [5 :a 1 :f]
:d [5 :a 1 :e] [5 :a 2 :a] [5 :a 1 :e (mid 0 max-int) :d]
:b [5 :a 1 :a] [5 :a 1 :c] [5 :a 1 :b]
:r [5 :a 1 :a 10 :a] [5 :a 1 :c] [5 :a 1 :a (mid 10 max-int) :r]
:a [0 :a] [0 :a 0 :a] [0 :a (mid min-int 0) :a]
:a [3 :a 1 :a] [4 :a 0 :a] [3 :a (mid 1 max-int) :a]
;; Best case but harder to implement
: a [ 3 : a 0 : a ] [ 4 : a 0 : a ] [ 3 : a ( mid 0 max - int ) : a ]
:a [3 :a 0 :a] [4 :a 0 :a] [3 :a 0 :a (mid 0 max-int) :a]
))
| null | https://raw.githubusercontent.com/jasongilman/crdt-edit/2b8126632bc7f204cb3979e9c51f7ab363704f29/test/crdt_edit/test/logoot.clj | clojure | Use site to find position in between matching or separated by one.
Best case but harder to implement | (ns crdt-edit.test.logoot
(:require [clojure.test :refer :all]
[clojure.test.check.properties :refer [for-all]]
[clojure.test.check.clojure-test :refer [defspec]]
[clojure.test.check :as tc]
[clojure.test.check.generators :as gen]
[crdt-edit.logoot :as l]
[clojure.pprint :refer [pprint]]))
(def site-gen
"Site generator."
(gen/elements [:a :b :c :d]))
(def position-identifier-gen
"Position identifier generator."
(gen/fmap (partial apply l/->PositionIdentifier)
(gen/tuple gen/pos-int site-gen)))
(def position-gen
"Position generator"
(gen/fmap l/->Position
(gen/vector position-identifier-gen 1 5)))
(def two-unique-positions-in-order
"Generator of two unique positions in sorted order."
(gen/fmap
sort
(gen/such-that
(partial apply not=)
(gen/vector position-gen 2))))
(defn mid
"Returns the middle integer between two ints"
[^long n1 ^long n2]
(int (/ (+ n1 n2) 2)))
Checks that between any two positions another position can be found and inserted correctly
(defspec intermediate-position-spec 1000
(for-all [positions two-unique-positions-in-order
site site-gen]
(let [[pos1 pos2] positions
middle-pos (l/intermediate-position site pos1 pos2)
expected-order [pos1 middle-pos pos2]]
(and
(= expected-order (sort expected-order))
(not= pos1 middle-pos)
(not= pos2 middle-pos)))))
(defn pos-builder
"Helps build positions. Takes a sequence a position int site pairs"
[& pairs]
(->> pairs
(partition 2)
(map (partial apply l/->PositionIdentifier))
l/->Position))
(def max-int Integer/MAX_VALUE)
(def min-int Integer/MIN_VALUE)
(deftest intermediate-position-examples
(are [site pos1-parts pos2-parts expected-parts]
(let [pos1 (apply pos-builder pos1-parts)
pos2 (apply pos-builder pos2-parts)
expected (apply pos-builder expected-parts)
actual (l/intermediate-position site pos1 pos2 mid)]
(if (= expected actual)
true
(do
(println "expected:")
(pprint expected)
(println "actual")
(pprint actual))))
:a [1 :a 5 :a 8 :a] [3 :a] [2 :a]
:a [4 :a 1 :a] [4 :a 3 :a] [4 :a 2 :a]
:f [5 :a 1 :e] [5 :a 2 :a] [5 :a 1 :f]
:d [5 :a 1 :e] [5 :a 2 :a] [5 :a 1 :e (mid 0 max-int) :d]
:b [5 :a 1 :a] [5 :a 1 :c] [5 :a 1 :b]
:r [5 :a 1 :a 10 :a] [5 :a 1 :c] [5 :a 1 :a (mid 10 max-int) :r]
:a [0 :a] [0 :a 0 :a] [0 :a (mid min-int 0) :a]
:a [3 :a 1 :a] [4 :a 0 :a] [3 :a (mid 1 max-int) :a]
: a [ 3 : a 0 : a ] [ 4 : a 0 : a ] [ 3 : a ( mid 0 max - int ) : a ]
:a [3 :a 0 :a] [4 :a 0 :a] [3 :a 0 :a (mid 0 max-int) :a]
))
|
90ee0253bce9d9d3e17e0dc577c091779c9fa35cf7e37a149521f1a3c4d66e3d | racket/typed-racket | with-type-typed-context-flag.rkt | #lang racket/load
(require (only-in typed/racket/shallow with-type)
syntax/macro-testing)
;; Test that the typed-context? flag is properly reset
(with-handlers ([exn:fail:syntax? void])
(convert-compile-time-error
(with-type [] (+ 1 "foo"))))
;; this should succeed instead of an error due to the typed-context?
;; flag being set to #t
(with-type [] (+ 1 3))
| null | https://raw.githubusercontent.com/racket/typed-racket/1dde78d165472d67ae682b68622d2b7ee3e15e1e/typed-racket-test/succeed/shallow/with-type-typed-context-flag.rkt | racket | Test that the typed-context? flag is properly reset
this should succeed instead of an error due to the typed-context?
flag being set to #t | #lang racket/load
(require (only-in typed/racket/shallow with-type)
syntax/macro-testing)
(with-handlers ([exn:fail:syntax? void])
(convert-compile-time-error
(with-type [] (+ 1 "foo"))))
(with-type [] (+ 1 3))
|
5591f6290ebe77898e21bc833270f9a878c0e54d49123797b48864289e1dbcc4 | yellowbean/clojucture | cn_test.clj | (ns clojucture.reader.cn_test
(:require
[clojucture.reader.cn :refer :all]
[clojucture.assumption :as assump]
[clojucture.pool :as p]
[clojucture.spv :as spv]
[clojure.test :refer :all]
[java-time :as jt]
[clojure.java.io :as io]
[clojucture.util :as u]))
(comment
(deftest testPy
(let [py-model (io/resource "china/Model.xlsx")
model (cn-load-model! (.getFile py-model))
;pool (get-in model [:status :pool])
;deal-accounts (get-in model [:info :accounts])
cpr-assump (assump/gen-pool-assump-df :cpr [0.1] [(jt/local-date 2017 1 1) (jt/local-date 2030 1 1)])
cdr-assump (assump/gen-pool-assump-df :cpr [0.1] [(jt/local-date 2017 1 1) (jt/local-date 2030 1 1)])
pool-assump {:prepayment cpr-assump :default cdr-assump}
;p-collect-int (get-in model [:info :p-collection-intervals])
;pool-cf-agg (.collect-cashflow pool pool-assump p-collect-int)
;rules {:principal :账户P :interest :账户I}
accs - with - deposit ( p / deposit - to - accs pool - cf - agg deal - accounts rules { : delay - days 10 } )
;waterfalls (get-in model [:info :waterfall])
]
( println (: 账户I - deposit ) )
;(.project-cashflow pool pool-assump)
;(println waterfalls)
;(println pool-cf-agg)
;(println (get-in model [:info :dates]))
;(println (assoc-in model [:status :b-rest-payment-dates]
; (filter #(jt/after? % update-date) (get-in deal-setup [:info :b-payment-dates]))))
;(let [ [b e a] (spv/run-bonds model pool-assump)]
; (println a)
; )
)
)
)
| null | https://raw.githubusercontent.com/yellowbean/clojucture/3ad99e06ecd9e5c478f653df4afbd69991cd4964/test/clojucture/reader/cn_test.clj | clojure | pool (get-in model [:status :pool])
deal-accounts (get-in model [:info :accounts])
p-collect-int (get-in model [:info :p-collection-intervals])
pool-cf-agg (.collect-cashflow pool pool-assump p-collect-int)
rules {:principal :账户P :interest :账户I}
waterfalls (get-in model [:info :waterfall])
(.project-cashflow pool pool-assump)
(println waterfalls)
(println pool-cf-agg)
(println (get-in model [:info :dates]))
(println (assoc-in model [:status :b-rest-payment-dates]
(filter #(jt/after? % update-date) (get-in deal-setup [:info :b-payment-dates]))))
(let [ [b e a] (spv/run-bonds model pool-assump)]
(println a)
) | (ns clojucture.reader.cn_test
(:require
[clojucture.reader.cn :refer :all]
[clojucture.assumption :as assump]
[clojucture.pool :as p]
[clojucture.spv :as spv]
[clojure.test :refer :all]
[java-time :as jt]
[clojure.java.io :as io]
[clojucture.util :as u]))
(comment
(deftest testPy
(let [py-model (io/resource "china/Model.xlsx")
model (cn-load-model! (.getFile py-model))
cpr-assump (assump/gen-pool-assump-df :cpr [0.1] [(jt/local-date 2017 1 1) (jt/local-date 2030 1 1)])
cdr-assump (assump/gen-pool-assump-df :cpr [0.1] [(jt/local-date 2017 1 1) (jt/local-date 2030 1 1)])
pool-assump {:prepayment cpr-assump :default cdr-assump}
accs - with - deposit ( p / deposit - to - accs pool - cf - agg deal - accounts rules { : delay - days 10 } )
]
( println (: 账户I - deposit ) )
)
)
)
|
d757cb9383142b5ba16a74572a0abfe34ba104c00e0b9164035913868b940341 | fbellomi/crossclj | emit_form.clj | Copyright ( c ) , Rich Hickey & contributors .
;; The use and distribution terms for this software are covered by the
;; Eclipse Public License 1.0 (-1.0.php)
;; which can be found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(ns cloned.clojure.tools.analyzer.passes.js.emit-form
(:require [cloned.clojure.tools.analyzer.passes
[emit-form :as default]
[uniquify :refer [uniquify-locals]]]
[clojure.string :as s]
[cljs.tagged-literals :refer [->JSValue]])
(:import cljs.tagged_literals.JSValue
java.io.Writer))
(defmulti -emit-form (fn [{:keys [op]} _] op))
(defn -emit-form*
[{:keys [form] :as ast} opts]
(let [expr (-emit-form ast opts)]
(if-let [m (and (instance? clojure.lang.IObj expr)
(meta form))]
(with-meta expr (merge m (meta expr)))
expr)))
(defn emit-form
"Return the form represented by the given AST
Opts is a set of options, valid options are:
* :hygienic
* :qualified-symbols"
{:pass-info {:walk :none :depends #{#'uniquify-locals} :compiler true}}
([ast] (emit-form ast #{}))
([ast opts]
(binding [default/-emit-form* -emit-form*]
(-emit-form* ast opts))))
(defn emit-hygienic-form
"Return an hygienic form represented by the given AST"
{:pass-info {:walk :none :depends #{#'uniquify-locals} :compiler true}}
[ast]
(binding [default/-emit-form* -emit-form*]
(-emit-form* ast #{:hygienic})))
(defmethod -emit-form :default
[ast opts]
(default/-emit-form ast opts))
(defmethod -emit-form :js
[{:keys [segs args]} opts]
(list* 'js* (s/join "~{}" segs) (mapv #(-emit-form* % opts) args)))
(defmethod -emit-form :js-object
[{:keys [keys vals]} opts]
(->JSValue (zipmap (map #(-emit-form* % opts) keys)
(map #(-emit-form* % opts) vals))))
(defmethod -emit-form :js-array
[{:keys [items]} opts]
(->JSValue (mapv #(-emit-form* % opts) items)))
(defmethod print-method JSValue [^JSValue o ^Writer w]
(.write w "#js ")
(.write w (str (.val o))))
(defmethod -emit-form :deftype
[{:keys [name fields pmask body]} opts]
(list 'deftype* name (map #(-emit-form* % opts) fields) pmask
(-emit-form* body opts)))
(defmethod -emit-form :defrecord
[{:keys [name fields pmask body]} opts]
(list 'defrecord* name (map #(-emit-form* % opts) fields) pmask
(-emit-form* body opts)))
(defmethod -emit-form :case-then
[{:keys [then]} opts]
(-emit-form* then opts))
(defmethod -emit-form :case-test
[{:keys [test]} opts]
(-emit-form* test opts))
(defmethod -emit-form :case
[{:keys [test nodes default]} opts]
`(case* ~(-emit-form* test opts)
~@(reduce (fn [acc {:keys [tests then]}]
(-> acc
(update-in [0] conj (mapv #(-emit-form* % opts) tests))
(update-in [1] conj (-emit-form* then opts))))
[[] []] nodes)
~(-emit-form* default opts)))
| null | https://raw.githubusercontent.com/fbellomi/crossclj/7630270ebe9ea3df89fe3d877b2571e6eae1062b/src/cloned/clojure/tools/analyzer/passes/js/emit_form.clj | clojure | The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software. | Copyright ( c ) , Rich Hickey & contributors .
(ns cloned.clojure.tools.analyzer.passes.js.emit-form
(:require [cloned.clojure.tools.analyzer.passes
[emit-form :as default]
[uniquify :refer [uniquify-locals]]]
[clojure.string :as s]
[cljs.tagged-literals :refer [->JSValue]])
(:import cljs.tagged_literals.JSValue
java.io.Writer))
(defmulti -emit-form (fn [{:keys [op]} _] op))
(defn -emit-form*
[{:keys [form] :as ast} opts]
(let [expr (-emit-form ast opts)]
(if-let [m (and (instance? clojure.lang.IObj expr)
(meta form))]
(with-meta expr (merge m (meta expr)))
expr)))
(defn emit-form
"Return the form represented by the given AST
Opts is a set of options, valid options are:
* :hygienic
* :qualified-symbols"
{:pass-info {:walk :none :depends #{#'uniquify-locals} :compiler true}}
([ast] (emit-form ast #{}))
([ast opts]
(binding [default/-emit-form* -emit-form*]
(-emit-form* ast opts))))
(defn emit-hygienic-form
"Return an hygienic form represented by the given AST"
{:pass-info {:walk :none :depends #{#'uniquify-locals} :compiler true}}
[ast]
(binding [default/-emit-form* -emit-form*]
(-emit-form* ast #{:hygienic})))
(defmethod -emit-form :default
[ast opts]
(default/-emit-form ast opts))
(defmethod -emit-form :js
[{:keys [segs args]} opts]
(list* 'js* (s/join "~{}" segs) (mapv #(-emit-form* % opts) args)))
(defmethod -emit-form :js-object
[{:keys [keys vals]} opts]
(->JSValue (zipmap (map #(-emit-form* % opts) keys)
(map #(-emit-form* % opts) vals))))
(defmethod -emit-form :js-array
[{:keys [items]} opts]
(->JSValue (mapv #(-emit-form* % opts) items)))
(defmethod print-method JSValue [^JSValue o ^Writer w]
(.write w "#js ")
(.write w (str (.val o))))
(defmethod -emit-form :deftype
[{:keys [name fields pmask body]} opts]
(list 'deftype* name (map #(-emit-form* % opts) fields) pmask
(-emit-form* body opts)))
(defmethod -emit-form :defrecord
[{:keys [name fields pmask body]} opts]
(list 'defrecord* name (map #(-emit-form* % opts) fields) pmask
(-emit-form* body opts)))
(defmethod -emit-form :case-then
[{:keys [then]} opts]
(-emit-form* then opts))
(defmethod -emit-form :case-test
[{:keys [test]} opts]
(-emit-form* test opts))
(defmethod -emit-form :case
[{:keys [test nodes default]} opts]
`(case* ~(-emit-form* test opts)
~@(reduce (fn [acc {:keys [tests then]}]
(-> acc
(update-in [0] conj (mapv #(-emit-form* % opts) tests))
(update-in [1] conj (-emit-form* then opts))))
[[] []] nodes)
~(-emit-form* default opts)))
|
7888373fd020258fb69ce952237e50b4c0a06738350e624720869f976c550386 | OCamlPro/OCamlPro-OCaml-Branch | ocamlprof.ml | (***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
and , INRIA Rocquencourt
Ported to Caml Special Light by
(* *)
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 .
(* *)
(***********************************************************************)
$ Id$
open Printf
open Clflags
open Config
open Location
open Misc
open Parsetree
(* User programs must not use identifiers that start with these prefixes. *)
let idprefix = "__ocaml_prof_";;
let modprefix = "OCAML__prof_";;
(* Errors specific to the profiler *)
exception Profiler of string
(* Modes *)
let instr_fun = ref false
and instr_match = ref false
and instr_if = ref false
and instr_loops = ref false
and instr_try = ref false
let cur_point = ref 0
and inchan = ref stdin
and outchan = ref stdout
(* To copy source fragments *)
let copy_buffer = String.create 256
let copy_chars_unix nchars =
let n = ref nchars in
while !n > 0 do
let m = input !inchan copy_buffer 0 (min !n 256) in
if m = 0 then raise End_of_file;
output !outchan copy_buffer 0 m;
n := !n - m
done
let copy_chars_win32 nchars =
for i = 1 to nchars do
let c = input_char !inchan in
if c <> '\r' then output_char !outchan c
done
let copy_chars =
match Sys.os_type with
"Win32" | "Cygwin" -> copy_chars_win32
| _ -> copy_chars_unix
let copy next =
assert (next >= !cur_point);
seek_in !inchan !cur_point;
copy_chars (next - !cur_point);
cur_point := next;
;;
let prof_counter = ref 0;;
let instr_mode = ref false
type insert = Open | Close;;
let to_insert = ref ([] : (insert * int) list);;
let insert_action st en =
to_insert := (Open, st) :: (Close, en) :: !to_insert
;;
(* Producing instrumented code *)
let add_incr_counter modul (kind,pos) =
copy pos;
match kind with
| Open ->
fprintf !outchan "(%sProfiling.incr %s%s_cnt %d; "
modprefix idprefix modul !prof_counter;
incr prof_counter;
| Close -> fprintf !outchan ")";
;;
let counters = ref (Array.create 0 0)
(* User defined marker *)
let special_id = ref ""
(* Producing results of profile run *)
let add_val_counter (kind,pos) =
if kind = Open then begin
copy pos;
fprintf !outchan "(* %s%d *) " !special_id !counters.(!prof_counter);
incr prof_counter;
end
;;
(* ************* rewrite ************* *)
let insert_profile rw_exp ex =
let st = ex.pexp_loc.loc_start.Lexing.pos_cnum
and en = ex.pexp_loc.loc_end.Lexing.pos_cnum
and gh = ex.pexp_loc.loc_ghost
in
if gh || st = en then
rw_exp true ex
else begin
insert_action st en;
rw_exp false ex;
end
;;
let pos_len = ref 0
let init_rewrite modes mod_name =
cur_point := 0;
if !instr_mode then begin
fprintf !outchan "module %sProfiling = Profiling;; " modprefix;
fprintf !outchan "let %s%s_cnt = Array.create 000000000" idprefix mod_name;
pos_len := pos_out !outchan;
fprintf !outchan
" 0;; Profiling.counters := \
(\"%s\", (\"%s\", %s%s_cnt)) :: !Profiling.counters;; "
mod_name modes idprefix mod_name;
end
let final_rewrite add_function =
to_insert := Sort.list (fun x y -> snd x < snd y) !to_insert;
prof_counter := 0;
List.iter add_function !to_insert;
copy (in_channel_length !inchan);
if !instr_mode then begin
let len = string_of_int !prof_counter in
if String.length len > 9 then raise (Profiler "too many counters");
seek_out !outchan (!pos_len - String.length len);
output_string !outchan len
end;
(* Cannot close because outchan is stdout and Format doesn't like
a closed stdout.
close_out !outchan;
*)
;;
let rec rewrite_patexp_list iflag l =
rewrite_exp_list iflag (List.map snd l)
and rewrite_patlexp_list iflag l =
rewrite_exp_list iflag (List.map snd l)
and rewrite_labelexp_list iflag l =
rewrite_exp_list iflag (List.map snd l)
and rewrite_exp_list iflag l =
List.iter (rewrite_exp iflag) l
and rewrite_exp iflag sexp =
if iflag then insert_profile rw_exp sexp
else rw_exp false sexp
and rw_exp iflag sexp =
match sexp.pexp_desc with
Pexp_ident lid -> ()
| Pexp_constant cst -> ()
| Pexp_let(_, spat_sexp_list, sbody) ->
rewrite_patexp_list iflag spat_sexp_list;
rewrite_exp iflag sbody
| Pexp_function (_, _, caselist) ->
if !instr_fun then
rewrite_function iflag caselist
else
rewrite_patlexp_list iflag caselist
| Pexp_match(sarg, caselist) ->
rewrite_exp iflag sarg;
if !instr_match && not sexp.pexp_loc.loc_ghost then
rewrite_funmatching caselist
else
rewrite_patlexp_list iflag caselist
| Pexp_try(sbody, caselist) ->
rewrite_exp iflag sbody;
if !instr_try && not sexp.pexp_loc.loc_ghost then
rewrite_trymatching caselist
else
rewrite_patexp_list iflag caselist
| Pexp_apply(sfunct, sargs) ->
rewrite_exp iflag sfunct;
rewrite_exp_list iflag (List.map snd sargs)
| Pexp_tuple sexpl ->
rewrite_exp_list iflag sexpl
| Pexp_construct(_, None, _) -> ()
| Pexp_construct(_, Some sarg, _) ->
rewrite_exp iflag sarg
| Pexp_variant(_, None) -> ()
| Pexp_variant(_, Some sarg) ->
rewrite_exp iflag sarg
| Pexp_record(lid_sexp_list, None) ->
rewrite_labelexp_list iflag lid_sexp_list
| Pexp_record(lid_sexp_list, Some sexp) ->
rewrite_exp iflag sexp;
rewrite_labelexp_list iflag lid_sexp_list
| Pexp_field(sarg, _) ->
rewrite_exp iflag sarg
| Pexp_setfield(srecord, _, snewval) ->
rewrite_exp iflag srecord;
rewrite_exp iflag snewval
| Pexp_array(sargl) ->
rewrite_exp_list iflag sargl
| Pexp_ifthenelse(scond, sifso, None) ->
rewrite_exp iflag scond;
rewrite_ifbody iflag sexp.pexp_loc.loc_ghost sifso
| Pexp_ifthenelse(scond, sifso, Some sifnot) ->
rewrite_exp iflag scond;
rewrite_ifbody iflag sexp.pexp_loc.loc_ghost sifso;
rewrite_ifbody iflag sexp.pexp_loc.loc_ghost sifnot
| Pexp_sequence(sexp1, sexp2) ->
rewrite_exp iflag sexp1;
rewrite_exp iflag sexp2
| Pexp_while(scond, sbody) ->
rewrite_exp iflag scond;
if !instr_loops && not sexp.pexp_loc.loc_ghost
then insert_profile rw_exp sbody
else rewrite_exp iflag sbody
| Pexp_for(_, slow, shigh, _, sbody) ->
rewrite_exp iflag slow;
rewrite_exp iflag shigh;
if !instr_loops && not sexp.pexp_loc.loc_ghost
then insert_profile rw_exp sbody
else rewrite_exp iflag sbody
| Pexp_constraint(sarg, _, _) ->
rewrite_exp iflag sarg
| Pexp_when(scond, sbody) ->
rewrite_exp iflag scond;
rewrite_exp iflag sbody
| Pexp_send (sobj, _) ->
rewrite_exp iflag sobj
| Pexp_new _ -> ()
| Pexp_setinstvar (_, sarg) ->
rewrite_exp iflag sarg
| Pexp_override l ->
List.iter (fun (_, sexp) -> rewrite_exp iflag sexp) l
| Pexp_letmodule (_, smod, sexp) ->
rewrite_mod iflag smod;
rewrite_exp iflag sexp
| Pexp_assert (cond) -> rewrite_exp iflag cond
| Pexp_assertfalse -> ()
| Pexp_lazy (expr) -> rewrite_exp iflag expr
| Pexp_poly (sexp, _) -> rewrite_exp iflag sexp
| Pexp_object (_, fieldl) ->
List.iter (rewrite_class_field iflag) fieldl
| Pexp_newtype (_, sexp) -> rewrite_exp iflag sexp
| Pexp_open (_, e) -> rewrite_exp iflag e
| Pexp_pack (smod) -> rewrite_mod iflag smod
and rewrite_ifbody iflag ghost sifbody =
if !instr_if && not ghost then
insert_profile rw_exp sifbody
else
rewrite_exp iflag sifbody
(* called only when !instr_fun *)
and rewrite_annotate_exp_list l =
List.iter
(function
| {pexp_desc = Pexp_when(scond, sbody)}
-> insert_profile rw_exp scond;
insert_profile rw_exp sbody;
| {pexp_desc = Pexp_constraint(sbody, _, _)} (* let f x : t = e *)
-> insert_profile rw_exp sbody
| sexp -> insert_profile rw_exp sexp)
l
and rewrite_function iflag = function
| [spat, ({pexp_desc = Pexp_function _} as sexp)] -> rewrite_exp iflag sexp
| l -> rewrite_funmatching l
and rewrite_funmatching l =
rewrite_annotate_exp_list (List.map snd l)
and rewrite_trymatching l =
rewrite_annotate_exp_list (List.map snd l)
(* Rewrite a class definition *)
and rewrite_class_field iflag =
function
Pcf_inher (_, cexpr, _) -> rewrite_class_expr iflag cexpr
| Pcf_val (_, _, _, sexp, _) -> rewrite_exp iflag sexp
| Pcf_meth (_, _, _, ({pexp_desc = Pexp_function _} as sexp), _) ->
rewrite_exp iflag sexp
| Pcf_meth (_, _, _, sexp, loc) ->
if !instr_fun && not loc.loc_ghost then insert_profile rw_exp sexp
else rewrite_exp iflag sexp
| Pcf_let(_, spat_sexp_list, _) ->
rewrite_patexp_list iflag spat_sexp_list
| Pcf_init sexp ->
rewrite_exp iflag sexp
| Pcf_valvirt _ | Pcf_virt _ | Pcf_cstr _ -> ()
and rewrite_class_expr iflag cexpr =
match cexpr.pcl_desc with
Pcl_constr _ -> ()
| Pcl_structure (_, fields) ->
List.iter (rewrite_class_field iflag) fields
| Pcl_fun (_, _, _, cexpr) ->
rewrite_class_expr iflag cexpr
| Pcl_apply (cexpr, exprs) ->
rewrite_class_expr iflag cexpr;
List.iter (rewrite_exp iflag) (List.map snd exprs)
| Pcl_let (_, spat_sexp_list, cexpr) ->
rewrite_patexp_list iflag spat_sexp_list;
rewrite_class_expr iflag cexpr
| Pcl_constraint (cexpr, _) ->
rewrite_class_expr iflag cexpr
and rewrite_class_declaration iflag cl =
rewrite_class_expr iflag cl.pci_expr
(* Rewrite a module expression or structure expression *)
and rewrite_mod iflag smod =
match smod.pmod_desc with
Pmod_ident lid -> ()
| Pmod_structure sstr -> List.iter (rewrite_str_item iflag) sstr
| Pmod_functor(param, smty, sbody) -> rewrite_mod iflag sbody
| Pmod_apply(smod1, smod2) -> rewrite_mod iflag smod1; rewrite_mod iflag smod2
| Pmod_constraint(smod, smty) -> rewrite_mod iflag smod
| Pmod_unpack(sexp) -> rewrite_exp iflag sexp
and rewrite_str_item iflag item =
match item.pstr_desc with
Pstr_eval exp -> rewrite_exp iflag exp
| Pstr_value(_, exps)
-> List.iter (function (_,exp) -> rewrite_exp iflag exp) exps
| Pstr_module(name, smod) -> rewrite_mod iflag smod
| Pstr_class classes -> List.iter (rewrite_class_declaration iflag) classes
| _ -> ()
Rewrite a .ml file
let rewrite_file srcfile add_function =
inchan := open_in_bin srcfile;
let lb = Lexing.from_channel !inchan in
Location.input_name := srcfile;
Location.init lb srcfile;
List.iter (rewrite_str_item false) (Parse.implementation lb);
final_rewrite add_function;
close_in !inchan
(* Copy a non-.ml file without change *)
let null_rewrite srcfile =
inchan := open_in_bin srcfile;
copy (in_channel_length !inchan);
close_in !inchan
;;
(* Setting flags from saved config *)
let set_flags s =
for i = 0 to String.length s - 1 do
match String.get s i with
'f' -> instr_fun := true
| 'm' -> instr_match := true
| 'i' -> instr_if := true
| 'l' -> instr_loops := true
| 't' -> instr_try := true
| 'a' -> instr_fun := true; instr_match := true;
instr_if := true; instr_loops := true;
instr_try := true
| _ -> ()
done
(* Command-line options *)
let modes = ref "fm"
let dumpfile = ref "ocamlprof.dump"
(* Process a file *)
let process_intf_file filename = null_rewrite filename;;
let process_impl_file filename =
let modname = Filename.basename(Filename.chop_extension filename) in
FIXME should let = String.capitalize modname
if !instr_mode then begin
(* Instrumentation mode *)
set_flags !modes;
init_rewrite !modes modname;
rewrite_file filename (add_incr_counter modname);
end else begin
(* Results mode *)
let ic = open_in_bin !dumpfile in
let allcounters =
(input_value ic : (string * (string * int array)) list) in
close_in ic;
let (modes, cv) =
try
List.assoc modname allcounters
with Not_found ->
raise(Profiler("Module " ^ modname ^ " not used in this profile."))
in
counters := cv;
set_flags modes;
init_rewrite modes modname;
rewrite_file filename add_val_counter;
end
;;
let process_anon_file filename =
if Filename.check_suffix filename ".ml" then
process_impl_file filename
else
process_intf_file filename
;;
(* Main function *)
open Format
let usage = "Usage: ocamlprof <options> <files>\noptions are:"
let print_version () =
printf "ocamlprof, version %s@." Sys.ocaml_version;
exit 0;
;;
let print_version_num () =
printf "%s@." Sys.ocaml_version;
exit 0;
;;
let main () =
try
Warnings.parse_options false "a";
Arg.parse [
"-f", Arg.String (fun s -> dumpfile := s),
"<file> Use <file> as dump file (default ocamlprof.dump)";
"-F", Arg.String (fun s -> special_id := s),
"<s> Insert string <s> with the counts";
"-impl", Arg.String process_impl_file,
"<file> Process <file> as a .ml file";
"-instrument", Arg.Set instr_mode, " (undocumented)";
"-intf", Arg.String process_intf_file,
"<file> Process <file> as a .mli file";
"-m", Arg.String (fun s -> modes := s), "<flags> (undocumented)";
"-version", Arg.Unit print_version,
" Print version and exit";
"-vnum", Arg.Unit print_version_num,
" Print version number and exit";
] process_anon_file usage;
exit 0
with x ->
let report_error ppf = function
| Lexer.Error(err, range) ->
fprintf ppf "@[%a%a@]@."
Location.print_error range Lexer.report_error err
| Syntaxerr.Error err ->
fprintf ppf "@[%a@]@."
Syntaxerr.report_error err
| Profiler msg ->
fprintf ppf "@[%s@]@." msg
| Sys_error msg ->
fprintf ppf "@[I/O error:@ %s@]@." msg
| x -> raise x in
report_error Format.err_formatter x;
exit 2
let _ = main ()
| null | https://raw.githubusercontent.com/OCamlPro/OCamlPro-OCaml-Branch/3a522985649389f89dac73e655d562c54f0456a5/inline-more/tools/ocamlprof.ml | ocaml | *********************************************************************
Objective Caml
*********************************************************************
User programs must not use identifiers that start with these prefixes.
Errors specific to the profiler
Modes
To copy source fragments
Producing instrumented code
User defined marker
Producing results of profile run
************* rewrite *************
Cannot close because outchan is stdout and Format doesn't like
a closed stdout.
close_out !outchan;
called only when !instr_fun
let f x : t = e
Rewrite a class definition
Rewrite a module expression or structure expression
Copy a non-.ml file without change
Setting flags from saved config
Command-line options
Process a file
Instrumentation mode
Results mode
Main function | and , INRIA Rocquencourt
Ported to Caml Special Light by
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 .
$ Id$
open Printf
open Clflags
open Config
open Location
open Misc
open Parsetree
let idprefix = "__ocaml_prof_";;
let modprefix = "OCAML__prof_";;
exception Profiler of string
let instr_fun = ref false
and instr_match = ref false
and instr_if = ref false
and instr_loops = ref false
and instr_try = ref false
let cur_point = ref 0
and inchan = ref stdin
and outchan = ref stdout
let copy_buffer = String.create 256
let copy_chars_unix nchars =
let n = ref nchars in
while !n > 0 do
let m = input !inchan copy_buffer 0 (min !n 256) in
if m = 0 then raise End_of_file;
output !outchan copy_buffer 0 m;
n := !n - m
done
let copy_chars_win32 nchars =
for i = 1 to nchars do
let c = input_char !inchan in
if c <> '\r' then output_char !outchan c
done
let copy_chars =
match Sys.os_type with
"Win32" | "Cygwin" -> copy_chars_win32
| _ -> copy_chars_unix
let copy next =
assert (next >= !cur_point);
seek_in !inchan !cur_point;
copy_chars (next - !cur_point);
cur_point := next;
;;
let prof_counter = ref 0;;
let instr_mode = ref false
type insert = Open | Close;;
let to_insert = ref ([] : (insert * int) list);;
let insert_action st en =
to_insert := (Open, st) :: (Close, en) :: !to_insert
;;
let add_incr_counter modul (kind,pos) =
copy pos;
match kind with
| Open ->
fprintf !outchan "(%sProfiling.incr %s%s_cnt %d; "
modprefix idprefix modul !prof_counter;
incr prof_counter;
| Close -> fprintf !outchan ")";
;;
let counters = ref (Array.create 0 0)
let special_id = ref ""
let add_val_counter (kind,pos) =
if kind = Open then begin
copy pos;
fprintf !outchan "(* %s%d *) " !special_id !counters.(!prof_counter);
incr prof_counter;
end
;;
let insert_profile rw_exp ex =
let st = ex.pexp_loc.loc_start.Lexing.pos_cnum
and en = ex.pexp_loc.loc_end.Lexing.pos_cnum
and gh = ex.pexp_loc.loc_ghost
in
if gh || st = en then
rw_exp true ex
else begin
insert_action st en;
rw_exp false ex;
end
;;
let pos_len = ref 0
let init_rewrite modes mod_name =
cur_point := 0;
if !instr_mode then begin
fprintf !outchan "module %sProfiling = Profiling;; " modprefix;
fprintf !outchan "let %s%s_cnt = Array.create 000000000" idprefix mod_name;
pos_len := pos_out !outchan;
fprintf !outchan
" 0;; Profiling.counters := \
(\"%s\", (\"%s\", %s%s_cnt)) :: !Profiling.counters;; "
mod_name modes idprefix mod_name;
end
let final_rewrite add_function =
to_insert := Sort.list (fun x y -> snd x < snd y) !to_insert;
prof_counter := 0;
List.iter add_function !to_insert;
copy (in_channel_length !inchan);
if !instr_mode then begin
let len = string_of_int !prof_counter in
if String.length len > 9 then raise (Profiler "too many counters");
seek_out !outchan (!pos_len - String.length len);
output_string !outchan len
end;
;;
let rec rewrite_patexp_list iflag l =
rewrite_exp_list iflag (List.map snd l)
and rewrite_patlexp_list iflag l =
rewrite_exp_list iflag (List.map snd l)
and rewrite_labelexp_list iflag l =
rewrite_exp_list iflag (List.map snd l)
and rewrite_exp_list iflag l =
List.iter (rewrite_exp iflag) l
and rewrite_exp iflag sexp =
if iflag then insert_profile rw_exp sexp
else rw_exp false sexp
and rw_exp iflag sexp =
match sexp.pexp_desc with
Pexp_ident lid -> ()
| Pexp_constant cst -> ()
| Pexp_let(_, spat_sexp_list, sbody) ->
rewrite_patexp_list iflag spat_sexp_list;
rewrite_exp iflag sbody
| Pexp_function (_, _, caselist) ->
if !instr_fun then
rewrite_function iflag caselist
else
rewrite_patlexp_list iflag caselist
| Pexp_match(sarg, caselist) ->
rewrite_exp iflag sarg;
if !instr_match && not sexp.pexp_loc.loc_ghost then
rewrite_funmatching caselist
else
rewrite_patlexp_list iflag caselist
| Pexp_try(sbody, caselist) ->
rewrite_exp iflag sbody;
if !instr_try && not sexp.pexp_loc.loc_ghost then
rewrite_trymatching caselist
else
rewrite_patexp_list iflag caselist
| Pexp_apply(sfunct, sargs) ->
rewrite_exp iflag sfunct;
rewrite_exp_list iflag (List.map snd sargs)
| Pexp_tuple sexpl ->
rewrite_exp_list iflag sexpl
| Pexp_construct(_, None, _) -> ()
| Pexp_construct(_, Some sarg, _) ->
rewrite_exp iflag sarg
| Pexp_variant(_, None) -> ()
| Pexp_variant(_, Some sarg) ->
rewrite_exp iflag sarg
| Pexp_record(lid_sexp_list, None) ->
rewrite_labelexp_list iflag lid_sexp_list
| Pexp_record(lid_sexp_list, Some sexp) ->
rewrite_exp iflag sexp;
rewrite_labelexp_list iflag lid_sexp_list
| Pexp_field(sarg, _) ->
rewrite_exp iflag sarg
| Pexp_setfield(srecord, _, snewval) ->
rewrite_exp iflag srecord;
rewrite_exp iflag snewval
| Pexp_array(sargl) ->
rewrite_exp_list iflag sargl
| Pexp_ifthenelse(scond, sifso, None) ->
rewrite_exp iflag scond;
rewrite_ifbody iflag sexp.pexp_loc.loc_ghost sifso
| Pexp_ifthenelse(scond, sifso, Some sifnot) ->
rewrite_exp iflag scond;
rewrite_ifbody iflag sexp.pexp_loc.loc_ghost sifso;
rewrite_ifbody iflag sexp.pexp_loc.loc_ghost sifnot
| Pexp_sequence(sexp1, sexp2) ->
rewrite_exp iflag sexp1;
rewrite_exp iflag sexp2
| Pexp_while(scond, sbody) ->
rewrite_exp iflag scond;
if !instr_loops && not sexp.pexp_loc.loc_ghost
then insert_profile rw_exp sbody
else rewrite_exp iflag sbody
| Pexp_for(_, slow, shigh, _, sbody) ->
rewrite_exp iflag slow;
rewrite_exp iflag shigh;
if !instr_loops && not sexp.pexp_loc.loc_ghost
then insert_profile rw_exp sbody
else rewrite_exp iflag sbody
| Pexp_constraint(sarg, _, _) ->
rewrite_exp iflag sarg
| Pexp_when(scond, sbody) ->
rewrite_exp iflag scond;
rewrite_exp iflag sbody
| Pexp_send (sobj, _) ->
rewrite_exp iflag sobj
| Pexp_new _ -> ()
| Pexp_setinstvar (_, sarg) ->
rewrite_exp iflag sarg
| Pexp_override l ->
List.iter (fun (_, sexp) -> rewrite_exp iflag sexp) l
| Pexp_letmodule (_, smod, sexp) ->
rewrite_mod iflag smod;
rewrite_exp iflag sexp
| Pexp_assert (cond) -> rewrite_exp iflag cond
| Pexp_assertfalse -> ()
| Pexp_lazy (expr) -> rewrite_exp iflag expr
| Pexp_poly (sexp, _) -> rewrite_exp iflag sexp
| Pexp_object (_, fieldl) ->
List.iter (rewrite_class_field iflag) fieldl
| Pexp_newtype (_, sexp) -> rewrite_exp iflag sexp
| Pexp_open (_, e) -> rewrite_exp iflag e
| Pexp_pack (smod) -> rewrite_mod iflag smod
and rewrite_ifbody iflag ghost sifbody =
if !instr_if && not ghost then
insert_profile rw_exp sifbody
else
rewrite_exp iflag sifbody
and rewrite_annotate_exp_list l =
List.iter
(function
| {pexp_desc = Pexp_when(scond, sbody)}
-> insert_profile rw_exp scond;
insert_profile rw_exp sbody;
-> insert_profile rw_exp sbody
| sexp -> insert_profile rw_exp sexp)
l
and rewrite_function iflag = function
| [spat, ({pexp_desc = Pexp_function _} as sexp)] -> rewrite_exp iflag sexp
| l -> rewrite_funmatching l
and rewrite_funmatching l =
rewrite_annotate_exp_list (List.map snd l)
and rewrite_trymatching l =
rewrite_annotate_exp_list (List.map snd l)
and rewrite_class_field iflag =
function
Pcf_inher (_, cexpr, _) -> rewrite_class_expr iflag cexpr
| Pcf_val (_, _, _, sexp, _) -> rewrite_exp iflag sexp
| Pcf_meth (_, _, _, ({pexp_desc = Pexp_function _} as sexp), _) ->
rewrite_exp iflag sexp
| Pcf_meth (_, _, _, sexp, loc) ->
if !instr_fun && not loc.loc_ghost then insert_profile rw_exp sexp
else rewrite_exp iflag sexp
| Pcf_let(_, spat_sexp_list, _) ->
rewrite_patexp_list iflag spat_sexp_list
| Pcf_init sexp ->
rewrite_exp iflag sexp
| Pcf_valvirt _ | Pcf_virt _ | Pcf_cstr _ -> ()
and rewrite_class_expr iflag cexpr =
match cexpr.pcl_desc with
Pcl_constr _ -> ()
| Pcl_structure (_, fields) ->
List.iter (rewrite_class_field iflag) fields
| Pcl_fun (_, _, _, cexpr) ->
rewrite_class_expr iflag cexpr
| Pcl_apply (cexpr, exprs) ->
rewrite_class_expr iflag cexpr;
List.iter (rewrite_exp iflag) (List.map snd exprs)
| Pcl_let (_, spat_sexp_list, cexpr) ->
rewrite_patexp_list iflag spat_sexp_list;
rewrite_class_expr iflag cexpr
| Pcl_constraint (cexpr, _) ->
rewrite_class_expr iflag cexpr
and rewrite_class_declaration iflag cl =
rewrite_class_expr iflag cl.pci_expr
and rewrite_mod iflag smod =
match smod.pmod_desc with
Pmod_ident lid -> ()
| Pmod_structure sstr -> List.iter (rewrite_str_item iflag) sstr
| Pmod_functor(param, smty, sbody) -> rewrite_mod iflag sbody
| Pmod_apply(smod1, smod2) -> rewrite_mod iflag smod1; rewrite_mod iflag smod2
| Pmod_constraint(smod, smty) -> rewrite_mod iflag smod
| Pmod_unpack(sexp) -> rewrite_exp iflag sexp
and rewrite_str_item iflag item =
match item.pstr_desc with
Pstr_eval exp -> rewrite_exp iflag exp
| Pstr_value(_, exps)
-> List.iter (function (_,exp) -> rewrite_exp iflag exp) exps
| Pstr_module(name, smod) -> rewrite_mod iflag smod
| Pstr_class classes -> List.iter (rewrite_class_declaration iflag) classes
| _ -> ()
Rewrite a .ml file
let rewrite_file srcfile add_function =
inchan := open_in_bin srcfile;
let lb = Lexing.from_channel !inchan in
Location.input_name := srcfile;
Location.init lb srcfile;
List.iter (rewrite_str_item false) (Parse.implementation lb);
final_rewrite add_function;
close_in !inchan
let null_rewrite srcfile =
inchan := open_in_bin srcfile;
copy (in_channel_length !inchan);
close_in !inchan
;;
let set_flags s =
for i = 0 to String.length s - 1 do
match String.get s i with
'f' -> instr_fun := true
| 'm' -> instr_match := true
| 'i' -> instr_if := true
| 'l' -> instr_loops := true
| 't' -> instr_try := true
| 'a' -> instr_fun := true; instr_match := true;
instr_if := true; instr_loops := true;
instr_try := true
| _ -> ()
done
let modes = ref "fm"
let dumpfile = ref "ocamlprof.dump"
let process_intf_file filename = null_rewrite filename;;
let process_impl_file filename =
let modname = Filename.basename(Filename.chop_extension filename) in
FIXME should let = String.capitalize modname
if !instr_mode then begin
set_flags !modes;
init_rewrite !modes modname;
rewrite_file filename (add_incr_counter modname);
end else begin
let ic = open_in_bin !dumpfile in
let allcounters =
(input_value ic : (string * (string * int array)) list) in
close_in ic;
let (modes, cv) =
try
List.assoc modname allcounters
with Not_found ->
raise(Profiler("Module " ^ modname ^ " not used in this profile."))
in
counters := cv;
set_flags modes;
init_rewrite modes modname;
rewrite_file filename add_val_counter;
end
;;
let process_anon_file filename =
if Filename.check_suffix filename ".ml" then
process_impl_file filename
else
process_intf_file filename
;;
open Format
let usage = "Usage: ocamlprof <options> <files>\noptions are:"
let print_version () =
printf "ocamlprof, version %s@." Sys.ocaml_version;
exit 0;
;;
let print_version_num () =
printf "%s@." Sys.ocaml_version;
exit 0;
;;
let main () =
try
Warnings.parse_options false "a";
Arg.parse [
"-f", Arg.String (fun s -> dumpfile := s),
"<file> Use <file> as dump file (default ocamlprof.dump)";
"-F", Arg.String (fun s -> special_id := s),
"<s> Insert string <s> with the counts";
"-impl", Arg.String process_impl_file,
"<file> Process <file> as a .ml file";
"-instrument", Arg.Set instr_mode, " (undocumented)";
"-intf", Arg.String process_intf_file,
"<file> Process <file> as a .mli file";
"-m", Arg.String (fun s -> modes := s), "<flags> (undocumented)";
"-version", Arg.Unit print_version,
" Print version and exit";
"-vnum", Arg.Unit print_version_num,
" Print version number and exit";
] process_anon_file usage;
exit 0
with x ->
let report_error ppf = function
| Lexer.Error(err, range) ->
fprintf ppf "@[%a%a@]@."
Location.print_error range Lexer.report_error err
| Syntaxerr.Error err ->
fprintf ppf "@[%a@]@."
Syntaxerr.report_error err
| Profiler msg ->
fprintf ppf "@[%s@]@." msg
| Sys_error msg ->
fprintf ppf "@[I/O error:@ %s@]@." msg
| x -> raise x in
report_error Format.err_formatter x;
exit 2
let _ = main ()
|
6a1f55c3131a846e3eaa149bfaf536c36acb354d1be4fa53cb46726c0ff00686 | kupl/FixML | sub3.ml | type nat = ZERO | SUCC of nat
let rec natadd : nat -> nat -> nat
=fun n1 n2 -> match n1 with
ZERO -> n2
|SUCC n1' -> SUCC(natadd n1' n2);;
let rec natmul : nat -> nat -> nat
=fun n1 n2 -> match n1 with
ZERO -> ZERO
|SUCC ZERO -> n2
|SUCC n1' -> SUCC(match n2 with
|ZERO -> ZERO
|SUCC ZERO -> SUCC ZERO
|SUCC n2' -> SUCC (natmul n1' (natmul n1 n2')));;
| null | https://raw.githubusercontent.com/kupl/FixML/0a032a733d68cd8ccc8b1034d2908cd43b241fce/benchmarks/nat/nat1/submissions/sub3.ml | ocaml | type nat = ZERO | SUCC of nat
let rec natadd : nat -> nat -> nat
=fun n1 n2 -> match n1 with
ZERO -> n2
|SUCC n1' -> SUCC(natadd n1' n2);;
let rec natmul : nat -> nat -> nat
=fun n1 n2 -> match n1 with
ZERO -> ZERO
|SUCC ZERO -> n2
|SUCC n1' -> SUCC(match n2 with
|ZERO -> ZERO
|SUCC ZERO -> SUCC ZERO
|SUCC n2' -> SUCC (natmul n1' (natmul n1 n2')));;
| |
f154f08711bc9c1e3e8b04f870f267ddd9942d31bb5dd68e46aee083b0e53fdd | expipiplus1/vulkan | TopTraverse.hs | module Data.Vector.TopTraverse
( traverseInTopOrder
) where
import Algebra.Graph.AdjacencyIntMap
hiding ( empty )
import Algebra.Graph.AdjacencyIntMap.Algorithm
import qualified Data.Foldable as F
import qualified Data.HashMap.Strict as Map
import Data.Maybe
import qualified Data.Text as T
import Data.Vector
import qualified Data.Vector as V
import Error ( HasErr
, throw
, traverseV
)
import Polysemy
import Prelude
import Relude ( Hashable )
traverseInTopOrder
:: (Eq k, Hashable k, HasErr r, Show k)
=> (a -> k)
-> (a -> [k])
-> (a -> Sem r b)
-> Vector a
-> Sem r (Vector b)
traverseInTopOrder getKey getPostSet f xs = do
perm <- topoSortedPermutation getKey getPostSet xs
traversed <- traverseV f (V.backpermute xs perm)
inv <- case inversePermutation perm of
Nothing -> throw "impossible: Unable to find inverse permutation"
Just i -> pure i
pure $ V.backpermute traversed inv
inversePermutation :: Vector Int -> Maybe (Vector Int)
inversePermutation indices = traverse
(\x -> V.findIndex (x ==) indices)
(V.fromList [0 .. V.length indices - 1])
topoSortedPermutation
:: forall a k r
. (Eq k, Hashable k, HasErr r, Show k)
=> (a -> k)
-> (a -> [k])
-> Vector a
-> Sem r (Vector Int)
topoSortedPermutation getKey getPostSet as = do
let keyed = getKey <$> as
keymap = Map.fromList (Prelude.zip (V.toList keyed) [0 ..])
lookupIndex :: k -> Maybe Int
lookupIndex = (`Map.lookup` keymap)
graph = stars
[ (i, ps)
| (a, i) <- Prelude.zip (V.toList as) [0 ..]
, let ks = getPostSet a
, -- TODO: error on Nothing here
let ps = Data.Maybe.catMaybes (lookupIndex <$> ks)
]
case topSort graph of
Left is ->
throw
$ "Cycle found in direct dependencies of structs: "
<> (T.pack . show) (V.backpermute keyed (V.fromList (F.toList is)))
Right is -> pure (V.reverse . V.fromList $ is)
| null | https://raw.githubusercontent.com/expipiplus1/vulkan/b1e33d1031779b4740c279c68879d05aee371659/generate-new/src/Data/Vector/TopTraverse.hs | haskell | TODO: error on Nothing here | module Data.Vector.TopTraverse
( traverseInTopOrder
) where
import Algebra.Graph.AdjacencyIntMap
hiding ( empty )
import Algebra.Graph.AdjacencyIntMap.Algorithm
import qualified Data.Foldable as F
import qualified Data.HashMap.Strict as Map
import Data.Maybe
import qualified Data.Text as T
import Data.Vector
import qualified Data.Vector as V
import Error ( HasErr
, throw
, traverseV
)
import Polysemy
import Prelude
import Relude ( Hashable )
traverseInTopOrder
:: (Eq k, Hashable k, HasErr r, Show k)
=> (a -> k)
-> (a -> [k])
-> (a -> Sem r b)
-> Vector a
-> Sem r (Vector b)
traverseInTopOrder getKey getPostSet f xs = do
perm <- topoSortedPermutation getKey getPostSet xs
traversed <- traverseV f (V.backpermute xs perm)
inv <- case inversePermutation perm of
Nothing -> throw "impossible: Unable to find inverse permutation"
Just i -> pure i
pure $ V.backpermute traversed inv
inversePermutation :: Vector Int -> Maybe (Vector Int)
inversePermutation indices = traverse
(\x -> V.findIndex (x ==) indices)
(V.fromList [0 .. V.length indices - 1])
topoSortedPermutation
:: forall a k r
. (Eq k, Hashable k, HasErr r, Show k)
=> (a -> k)
-> (a -> [k])
-> Vector a
-> Sem r (Vector Int)
topoSortedPermutation getKey getPostSet as = do
let keyed = getKey <$> as
keymap = Map.fromList (Prelude.zip (V.toList keyed) [0 ..])
lookupIndex :: k -> Maybe Int
lookupIndex = (`Map.lookup` keymap)
graph = stars
[ (i, ps)
| (a, i) <- Prelude.zip (V.toList as) [0 ..]
, let ks = getPostSet a
let ps = Data.Maybe.catMaybes (lookupIndex <$> ks)
]
case topSort graph of
Left is ->
throw
$ "Cycle found in direct dependencies of structs: "
<> (T.pack . show) (V.backpermute keyed (V.fromList (F.toList is)))
Right is -> pure (V.reverse . V.fromList $ is)
|
91a76e93e977cfdb03711ece77b16ff2a5350a99d56b8f3f419961af4cf939f1 | processone/ejabberd-contrib | mod_default_contacts.erl | %%%----------------------------------------------------------------------
%%% File : mod_default_contacts.erl
Author : < >
%%% Purpose : Auto-add contacts on registration
Created : 14 May 2019 by < >
%%%
%%%
ejabberd , Copyright ( C ) 2019 - 2020 ProcessOne
%%%
%%% This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
%%% License, or (at your option) any later version.
%%%
%%% This program is distributed in the hope that it will be useful,
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
%%% General Public License for more details.
%%%
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
%%%
%%%----------------------------------------------------------------------
-module(mod_default_contacts).
-author('').
-behavior(gen_mod).
%% gen_mod callbacks.
-export([start/2, stop/1, reload/3, mod_opt_type/1, depends/2, mod_options/1,
mod_doc/0]).
%% ejabberd_hooks callbacks.
-export([register_user/2]).
-include("logger.hrl").
-include_lib("xmpp/include/xmpp.hrl").
%%--------------------------------------------------------------------
%% gen_mod callbacks.
%%--------------------------------------------------------------------
-spec start(binary(), gen_mod:opts()) -> ok.
start(Host, _Opts) ->
ejabberd_hooks:add(register_user, Host, ?MODULE, register_user, 50).
-spec stop(binary()) -> ok.
stop(Host) ->
ejabberd_hooks:delete(register_user, Host, ?MODULE, register_user, 50).
-spec reload(binary(), gen_mod:opts(), gen_mod:opts()) -> ok.
reload(_Host, _NewOpts, _OldOpts) ->
ok.
-spec mod_opt_type(atom()) -> econf:validator().
mod_opt_type(contacts) ->
econf:list(
econf:and_then(
econf:options(
#{jid => econf:jid(),
name => econf:binary()},
[{required, [jid]}]),
fun(Opts) ->
Jid = proplists:get_value(jid, Opts),
Name = proplists:get_value(name, Opts, <<>>),
#roster_item{jid = Jid, name = Name}
end)).
-spec mod_options(binary()) -> [{atom(), any()}].
mod_options(_Host) ->
[{contacts, []}].
-spec depends(binary(), gen_mod:opts()) -> [{module(), hard | soft}].
depends(_Host, _Opts) ->
[{mod_roster, hard}].
mod_doc() ->
#{}.
%%--------------------------------------------------------------------
%% ejabberd_hooks callbacks.
%%--------------------------------------------------------------------
-spec register_user(binary(), binary()) -> any().
register_user(LUser, LServer) ->
?DEBUG("Auto-creating roster entries for ~s@~s", [LUser, LServer]),
Items = gen_mod:get_module_opt(LServer, ?MODULE, contacts),
mod_roster:set_items(LUser, LServer, #roster_query{items = Items}).
| null | https://raw.githubusercontent.com/processone/ejabberd-contrib/037c3749f331c8783666d45157e857ef5e7df42c/mod_default_contacts/src/mod_default_contacts.erl | erlang | ----------------------------------------------------------------------
File : mod_default_contacts.erl
Purpose : Auto-add contacts on registration
This program is free software; you can redistribute it and/or
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
----------------------------------------------------------------------
gen_mod callbacks.
ejabberd_hooks callbacks.
--------------------------------------------------------------------
gen_mod callbacks.
--------------------------------------------------------------------
--------------------------------------------------------------------
ejabberd_hooks callbacks.
-------------------------------------------------------------------- | Author : < >
Created : 14 May 2019 by < >
ejabberd , Copyright ( C ) 2019 - 2020 ProcessOne
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
-module(mod_default_contacts).
-author('').
-behavior(gen_mod).
-export([start/2, stop/1, reload/3, mod_opt_type/1, depends/2, mod_options/1,
mod_doc/0]).
-export([register_user/2]).
-include("logger.hrl").
-include_lib("xmpp/include/xmpp.hrl").
-spec start(binary(), gen_mod:opts()) -> ok.
start(Host, _Opts) ->
ejabberd_hooks:add(register_user, Host, ?MODULE, register_user, 50).
-spec stop(binary()) -> ok.
stop(Host) ->
ejabberd_hooks:delete(register_user, Host, ?MODULE, register_user, 50).
-spec reload(binary(), gen_mod:opts(), gen_mod:opts()) -> ok.
reload(_Host, _NewOpts, _OldOpts) ->
ok.
-spec mod_opt_type(atom()) -> econf:validator().
mod_opt_type(contacts) ->
econf:list(
econf:and_then(
econf:options(
#{jid => econf:jid(),
name => econf:binary()},
[{required, [jid]}]),
fun(Opts) ->
Jid = proplists:get_value(jid, Opts),
Name = proplists:get_value(name, Opts, <<>>),
#roster_item{jid = Jid, name = Name}
end)).
-spec mod_options(binary()) -> [{atom(), any()}].
mod_options(_Host) ->
[{contacts, []}].
-spec depends(binary(), gen_mod:opts()) -> [{module(), hard | soft}].
depends(_Host, _Opts) ->
[{mod_roster, hard}].
mod_doc() ->
#{}.
-spec register_user(binary(), binary()) -> any().
register_user(LUser, LServer) ->
?DEBUG("Auto-creating roster entries for ~s@~s", [LUser, LServer]),
Items = gen_mod:get_module_opt(LServer, ?MODULE, contacts),
mod_roster:set_items(LUser, LServer, #roster_query{items = Items}).
|
df4dd20717982b752fc5bf45303d5c11c23a2c091a117c255fafca37369065b5 | hugoduncan/oldmj | modules.clj | (ns makejack.invoke.modules
"Makejack tool to invoke targets on sub projects"
(:require [makejack.api.core :as makejack]
[makejack.impl.run :as run]
[makejack.impl.invokers :as invokers]))
(defn modules
"Execute target on sub-projects.
Sub-project directories are specified on the target's :modules key."
[args target-kw config options]
(let [target-config (get-in config [:mj :targets target-kw])
modules (:modules target-config)
args (into (:args target-config []) args)]
(when-not (sequential? modules)
(makejack/error
(str "ERROR: the :modules key of the "
target-kw
" target must specify a vector of subprojects")))
(doseq [module modules]
(when makejack/*verbose*
(println "Running" (first args) "in" module))
(run/run-command
(first args)
(rest args)
(assoc options :dir module)))
(when (:self target-config true)
(run/run-command
(first args)
(rest args)
options))))
(alter-var-root
#'invokers/invokers
assoc :modules #'modules)
| null | https://raw.githubusercontent.com/hugoduncan/oldmj/0a97488be7457baed01d2d9dd0ea6df4383832ab/cli/src/makejack/invoke/modules.clj | clojure | (ns makejack.invoke.modules
"Makejack tool to invoke targets on sub projects"
(:require [makejack.api.core :as makejack]
[makejack.impl.run :as run]
[makejack.impl.invokers :as invokers]))
(defn modules
"Execute target on sub-projects.
Sub-project directories are specified on the target's :modules key."
[args target-kw config options]
(let [target-config (get-in config [:mj :targets target-kw])
modules (:modules target-config)
args (into (:args target-config []) args)]
(when-not (sequential? modules)
(makejack/error
(str "ERROR: the :modules key of the "
target-kw
" target must specify a vector of subprojects")))
(doseq [module modules]
(when makejack/*verbose*
(println "Running" (first args) "in" module))
(run/run-command
(first args)
(rest args)
(assoc options :dir module)))
(when (:self target-config true)
(run/run-command
(first args)
(rest args)
options))))
(alter-var-root
#'invokers/invokers
assoc :modules #'modules)
| |
b8d09e994dfced5ac3b97f199c20cf0e0b35d426ba85c0d8523e67deb7204cc1 | ragkousism/Guix-on-Hurd | pumpio.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2015 < >
Copyright © 2016 < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU is free software ; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages pumpio)
#:use-module (guix licenses)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix git-download)
#:use-module (guix build-system gnu)
#:use-module (gnu packages aspell)
#:use-module (gnu packages qt)
#:use-module (gnu packages web))
(define-public pumpa
(package
(name "pumpa")
(version "0.9.2")
(source (origin
(method git-fetch) ; no source tarballs
(uri (git-reference
(url "git/")
(commit (string-append "v" version))))
(sha256
(base32
"09www29s4ldvd6apr73w7r4nmq93rcl2d182fylwgfcnncbvpy8s"))
(file-name (string-append name "-" version "-checkout"))))
(build-system gnu-build-system)
(arguments
'(#:phases (alist-replace
'configure
(lambda* (#:key inputs outputs #:allow-other-keys)
;; Fix dependency tests.
(substitute* "pumpa.pro"
(("/usr/include/tidy\\.h")
(string-append (assoc-ref inputs "tidy")
"/include/tidy.h"))
(("/usr/include/aspell.h")
(string-append (assoc-ref inputs "aspell")
"/include/aspell.h")))
;; Run qmake with proper installation prefix.
(let ((prefix (string-append "PREFIX="
(assoc-ref outputs "out"))))
(zero? (system* "qmake" prefix))))
%standard-phases)))
(inputs
`(("aspell" ,aspell)
("qtbase" ,qtbase)
("tidy" ,tidy)))
(synopsis "Qt-based pump.io client")
(description "Pumpa is a simple pump.io client written in C++ and Qt.")
(home-page "/")
(license gpl3+)))
| null | https://raw.githubusercontent.com/ragkousism/Guix-on-Hurd/e951bb2c0c4961dc6ac2bda8f331b9c4cee0da95/gnu/packages/pumpio.scm | scheme | GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
no source tarballs
Fix dependency tests.
Run qmake with proper installation prefix. | Copyright © 2015 < >
Copyright © 2016 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages pumpio)
#:use-module (guix licenses)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix git-download)
#:use-module (guix build-system gnu)
#:use-module (gnu packages aspell)
#:use-module (gnu packages qt)
#:use-module (gnu packages web))
(define-public pumpa
(package
(name "pumpa")
(version "0.9.2")
(source (origin
(uri (git-reference
(url "git/")
(commit (string-append "v" version))))
(sha256
(base32
"09www29s4ldvd6apr73w7r4nmq93rcl2d182fylwgfcnncbvpy8s"))
(file-name (string-append name "-" version "-checkout"))))
(build-system gnu-build-system)
(arguments
'(#:phases (alist-replace
'configure
(lambda* (#:key inputs outputs #:allow-other-keys)
(substitute* "pumpa.pro"
(("/usr/include/tidy\\.h")
(string-append (assoc-ref inputs "tidy")
"/include/tidy.h"))
(("/usr/include/aspell.h")
(string-append (assoc-ref inputs "aspell")
"/include/aspell.h")))
(let ((prefix (string-append "PREFIX="
(assoc-ref outputs "out"))))
(zero? (system* "qmake" prefix))))
%standard-phases)))
(inputs
`(("aspell" ,aspell)
("qtbase" ,qtbase)
("tidy" ,tidy)))
(synopsis "Qt-based pump.io client")
(description "Pumpa is a simple pump.io client written in C++ and Qt.")
(home-page "/")
(license gpl3+)))
|
80c64ce54453568575dd314bd61a81930da89f731215639bfbdb2a2c38b47404 | xapi-project/xen-api | xapi_pool_patch.ml |
* Copyright ( C ) 2006 - 2009 Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file 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 Lesser General Public License for more details .
* Copyright (C) 2006-2009 Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file 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 Lesser General Public License for more details.
*)
(**
* @group Pool Management
*)
open Client
module D = Debug.Make (struct let name = "xapi_pool_patch" end)
* Patches contain their own metadata in XML format . When the signature has been verified
the patch is executed with argument " info " and it emits XML like the following :
< info uuid="foo - bar - baz "
version="1.0 "
name - label="My First Patch(TM ) "
name - description="This is a simple executable patch file used for testing "
after - apply - guidance="restartHVM restartPV restartHost "
/ >
the patch is executed with argument "info" and it emits XML like the following:
<info uuid="foo-bar-baz"
version="1.0"
name-label="My First Patch(TM)"
name-description="This is a simple executable patch file used for testing"
after-apply-guidance="restartHVM restartPV restartHost"
/>
*)
open D
let pool_patch_of_update ~__context update_ref =
match
Db.Pool_patch.get_refs_where ~__context
~expr:
Db_filter_types.(
Eq (Field "pool_update", Literal (Ref.string_of update_ref))
)
with
| [patch] ->
patch
| patches ->
error
"Invalid state: Expected invariant - 1 pool_patch per pool_update. \
Found: [%s]"
(String.concat ";" (List.map (fun patch -> Ref.string_of patch) patches)) ;
raise Api_errors.(Server_error (internal_error, ["Invalid state"]))
let pool_patch_upload_handler (req : Http.Request.t) s _ =
debug "Patch Upload Handler - Entered..." ;
Xapi_http.with_context "Uploading update" req s (fun __context ->
Helpers.call_api_functions ~__context (fun rpc session_id ->
Strip out the task info here , we 'll use a new subtask . This
is to avoid our task being prematurely marked as completed by
the import_raw_vdi handler .
is to avoid our task being prematurely marked as completed by
the import_raw_vdi handler. *)
let strip = List.filter (fun (k, _) -> k <> "task_id") in
let add_sr query =
match Importexport.sr_of_req ~__context req with
| Some _ ->
query (* There was already an SR specified *)
| None ->
let pool = Db.Pool.get_all ~__context |> List.hd in
let default_SR = Db.Pool.get_default_SR ~__context ~self:pool in
("sr_id", Ref.string_of default_SR) :: query
in
let subtask =
Client.Task.create ~rpc ~session_id ~label:"VDI upload"
~description:""
in
Xapi_stdext_pervasives.Pervasiveext.finally
(fun () ->
let req =
Http.Request.
{
req with
cookie= strip req.cookie
; query=
("task_id", Ref.string_of subtask) :: strip req.query
|> add_sr
}
in
let vdi_opt =
Import_raw_vdi.localhost_handler rpc session_id
(Importexport.vdi_of_req ~__context req)
req s
in
match vdi_opt with
| Some vdi -> (
try
let update =
Client.Pool_update.introduce ~rpc ~session_id ~vdi
in
let patch = pool_patch_of_update ~__context update in
Db.Task.set_result ~__context
~self:(Context.get_task_id __context)
~value:(Ref.string_of patch) ;
TaskHelper.complete ~__context None
with e ->
Client.VDI.destroy ~rpc ~session_id ~self:vdi ;
TaskHelper.failed ~__context e
)
| None ->
(* Propagate the error from the subtask to the main task *)
let error_info =
Db.Task.get_error_info ~__context ~self:subtask
in
TaskHelper.failed ~__context
Api_errors.(
Server_error (List.hd error_info, List.tl error_info)
) ;
(* If we've got a None here, we'll already have replied with the error. Fail the task now too. *)
()
)
(fun () -> Client.Task.destroy ~rpc ~session_id ~self:subtask)
)
)
(* The [get_patch_applied_to] gives the patching status of a pool patch on the given host. It
returns [None] if the patch is not on the host, i.e. no corresponding host_patch;
returns [Some (ref, true)] if it's on the host and fully applied (as host_patch [ref]);
returns [Some (ref, false)] if it's on the host but isn't applied yet or the application is in progress. *)
let get_patch_applied_to ~__context ~patch ~host =
let expr =
Db_filter_types.(
And
( Eq (Field "pool_patch", Literal (Ref.string_of patch))
, Eq (Field "host", Literal (Ref.string_of host))
)
)
in
let result = Db.Host_patch.get_records_where ~__context ~expr in
match result with
| [] ->
None
| (rf, rc) :: _ ->
Some (rf, rc.API.host_patch_applied)
let write_patch_applied_db ~__context ?date ?(applied = true) ~self ~host () =
let date =
Xapi_stdext_date.Date.of_float
(match date with Some d -> d | None -> Unix.gettimeofday ())
in
match get_patch_applied_to ~__context ~patch:self ~host with
| Some (r, is_applied) ->
if not (is_applied = applied) then (
Db.Host_patch.set_timestamp_applied ~__context ~self:r ~value:date ;
Db.Host_patch.set_applied ~__context ~self:r ~value:applied
)
| None ->
let uuid = Uuidx.make () in
let r = Ref.make () in
Db.Host_patch.create ~__context ~ref:r ~uuid:(Uuidx.to_string uuid) ~host
~pool_patch:self ~timestamp_applied:date ~name_label:""
~name_description:"" ~version:"" ~filename:"" ~applied ~size:Int64.zero
~other_config:[]
(* Helper function. [forward __context self f] finds the update associated
with the pool_patch reference [self] and applies the function f to that
update *)
let forward ~__context ~self f =
let self = Db.Pool_patch.get_pool_update ~__context ~self in
Helpers.call_api_functions ~__context (fun rpc session_id ->
f ~rpc ~session_id ~self
)
(* precheck API call entrypoint *)
let precheck ~__context ~self ~host =
ignore (forward ~__context ~self (Client.Pool_update.precheck ~host)) ;
""
let apply ~__context ~self ~host =
forward ~__context ~self (Client.Pool_update.apply ~host) ;
""
let pool_apply ~__context ~self =
let hosts = Db.Host.get_all ~__context in
let (_ : string list) =
List.map
(fun host ->
Helpers.call_api_functions ~__context (fun rpc session_id ->
Client.Pool_patch.apply ~rpc ~session_id ~self ~host
)
)
hosts
in
let _ = Db.Pool_patch.set_pool_applied ~__context ~self ~value:true in
()
let clean ~__context ~self:_ = ()
let clean_on_host ~__context ~self:_ ~host:_ = ()
let pool_clean ~__context ~self =
forward ~__context ~self Client.Pool_update.pool_clean
let destroy ~__context ~self =
forward ~__context ~self Client.Pool_update.destroy
| null | https://raw.githubusercontent.com/xapi-project/xen-api/48cc1489fff0e344246ecf19fc1ebed6f09c7471/ocaml/xapi/xapi_pool_patch.ml | ocaml | *
* @group Pool Management
There was already an SR specified
Propagate the error from the subtask to the main task
If we've got a None here, we'll already have replied with the error. Fail the task now too.
The [get_patch_applied_to] gives the patching status of a pool patch on the given host. It
returns [None] if the patch is not on the host, i.e. no corresponding host_patch;
returns [Some (ref, true)] if it's on the host and fully applied (as host_patch [ref]);
returns [Some (ref, false)] if it's on the host but isn't applied yet or the application is in progress.
Helper function. [forward __context self f] finds the update associated
with the pool_patch reference [self] and applies the function f to that
update
precheck API call entrypoint |
* Copyright ( C ) 2006 - 2009 Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file 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 Lesser General Public License for more details .
* Copyright (C) 2006-2009 Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file 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 Lesser General Public License for more details.
*)
open Client
module D = Debug.Make (struct let name = "xapi_pool_patch" end)
* Patches contain their own metadata in XML format . When the signature has been verified
the patch is executed with argument " info " and it emits XML like the following :
< info uuid="foo - bar - baz "
version="1.0 "
name - label="My First Patch(TM ) "
name - description="This is a simple executable patch file used for testing "
after - apply - guidance="restartHVM restartPV restartHost "
/ >
the patch is executed with argument "info" and it emits XML like the following:
<info uuid="foo-bar-baz"
version="1.0"
name-label="My First Patch(TM)"
name-description="This is a simple executable patch file used for testing"
after-apply-guidance="restartHVM restartPV restartHost"
/>
*)
open D
let pool_patch_of_update ~__context update_ref =
match
Db.Pool_patch.get_refs_where ~__context
~expr:
Db_filter_types.(
Eq (Field "pool_update", Literal (Ref.string_of update_ref))
)
with
| [patch] ->
patch
| patches ->
error
"Invalid state: Expected invariant - 1 pool_patch per pool_update. \
Found: [%s]"
(String.concat ";" (List.map (fun patch -> Ref.string_of patch) patches)) ;
raise Api_errors.(Server_error (internal_error, ["Invalid state"]))
let pool_patch_upload_handler (req : Http.Request.t) s _ =
debug "Patch Upload Handler - Entered..." ;
Xapi_http.with_context "Uploading update" req s (fun __context ->
Helpers.call_api_functions ~__context (fun rpc session_id ->
Strip out the task info here , we 'll use a new subtask . This
is to avoid our task being prematurely marked as completed by
the import_raw_vdi handler .
is to avoid our task being prematurely marked as completed by
the import_raw_vdi handler. *)
let strip = List.filter (fun (k, _) -> k <> "task_id") in
let add_sr query =
match Importexport.sr_of_req ~__context req with
| Some _ ->
| None ->
let pool = Db.Pool.get_all ~__context |> List.hd in
let default_SR = Db.Pool.get_default_SR ~__context ~self:pool in
("sr_id", Ref.string_of default_SR) :: query
in
let subtask =
Client.Task.create ~rpc ~session_id ~label:"VDI upload"
~description:""
in
Xapi_stdext_pervasives.Pervasiveext.finally
(fun () ->
let req =
Http.Request.
{
req with
cookie= strip req.cookie
; query=
("task_id", Ref.string_of subtask) :: strip req.query
|> add_sr
}
in
let vdi_opt =
Import_raw_vdi.localhost_handler rpc session_id
(Importexport.vdi_of_req ~__context req)
req s
in
match vdi_opt with
| Some vdi -> (
try
let update =
Client.Pool_update.introduce ~rpc ~session_id ~vdi
in
let patch = pool_patch_of_update ~__context update in
Db.Task.set_result ~__context
~self:(Context.get_task_id __context)
~value:(Ref.string_of patch) ;
TaskHelper.complete ~__context None
with e ->
Client.VDI.destroy ~rpc ~session_id ~self:vdi ;
TaskHelper.failed ~__context e
)
| None ->
let error_info =
Db.Task.get_error_info ~__context ~self:subtask
in
TaskHelper.failed ~__context
Api_errors.(
Server_error (List.hd error_info, List.tl error_info)
) ;
()
)
(fun () -> Client.Task.destroy ~rpc ~session_id ~self:subtask)
)
)
let get_patch_applied_to ~__context ~patch ~host =
let expr =
Db_filter_types.(
And
( Eq (Field "pool_patch", Literal (Ref.string_of patch))
, Eq (Field "host", Literal (Ref.string_of host))
)
)
in
let result = Db.Host_patch.get_records_where ~__context ~expr in
match result with
| [] ->
None
| (rf, rc) :: _ ->
Some (rf, rc.API.host_patch_applied)
let write_patch_applied_db ~__context ?date ?(applied = true) ~self ~host () =
let date =
Xapi_stdext_date.Date.of_float
(match date with Some d -> d | None -> Unix.gettimeofday ())
in
match get_patch_applied_to ~__context ~patch:self ~host with
| Some (r, is_applied) ->
if not (is_applied = applied) then (
Db.Host_patch.set_timestamp_applied ~__context ~self:r ~value:date ;
Db.Host_patch.set_applied ~__context ~self:r ~value:applied
)
| None ->
let uuid = Uuidx.make () in
let r = Ref.make () in
Db.Host_patch.create ~__context ~ref:r ~uuid:(Uuidx.to_string uuid) ~host
~pool_patch:self ~timestamp_applied:date ~name_label:""
~name_description:"" ~version:"" ~filename:"" ~applied ~size:Int64.zero
~other_config:[]
let forward ~__context ~self f =
let self = Db.Pool_patch.get_pool_update ~__context ~self in
Helpers.call_api_functions ~__context (fun rpc session_id ->
f ~rpc ~session_id ~self
)
let precheck ~__context ~self ~host =
ignore (forward ~__context ~self (Client.Pool_update.precheck ~host)) ;
""
let apply ~__context ~self ~host =
forward ~__context ~self (Client.Pool_update.apply ~host) ;
""
let pool_apply ~__context ~self =
let hosts = Db.Host.get_all ~__context in
let (_ : string list) =
List.map
(fun host ->
Helpers.call_api_functions ~__context (fun rpc session_id ->
Client.Pool_patch.apply ~rpc ~session_id ~self ~host
)
)
hosts
in
let _ = Db.Pool_patch.set_pool_applied ~__context ~self ~value:true in
()
let clean ~__context ~self:_ = ()
let clean_on_host ~__context ~self:_ ~host:_ = ()
let pool_clean ~__context ~self =
forward ~__context ~self Client.Pool_update.pool_clean
let destroy ~__context ~self =
forward ~__context ~self Client.Pool_update.destroy
|
f299ba8cbb68e29ddde2316a07f1d5fc1f579c796e9f117a31d0d707d8a17cc5 | racket/scribble | manual-scheme.rkt | #lang racket/base
(require "../decode.rkt"
"../struct.rkt"
"../scheme.rkt"
"../search.rkt"
"../basic.rkt"
(only-in "../core.rkt" style style-properties)
"manual-style.rkt"
"manual-utils.rkt" ;; used via datum->syntax
"on-demand.rkt"
(for-syntax racket/base)
(for-label racket/base))
(provide racketblock RACKETBLOCK racketblock/form
racketblock0 RACKETBLOCK0 racketblock0/form
racketresultblock racketresultblock0
RACKETRESULTBLOCK RACKETRESULTBLOCK0
racketblockelem
racketinput RACKETINPUT
racketinput0 RACKETINPUT0
racketmod
racketmod0
racket RACKET racket/form racketresult racketid
racketmodname
racketmodlink indexed-racket
racketlink
(rename-out [racketblock schemeblock]
[RACKETBLOCK SCHEMEBLOCK]
[racketblock/form schemeblock/form]
[racketblock0 schemeblock0]
[RACKETBLOCK0 SCHEMEBLOCK0]
[racketblock0/form schemeblock0/form]
[racketblockelem schemeblockelem]
[racketinput schemeinput]
[racketmod schememod]
[racket scheme]
[RACKET SCHEME]
[racket/form scheme/form]
[racketresult schemeresult]
[racketid schemeid]
[racketmodname schememodname]
[racketmodlink schememodlink]
[indexed-racket indexed-scheme]
[racketlink schemelink]))
(define-code racketblock0 to-paragraph)
(define-code racketblock to-block-paragraph)
(define-code RACKETBLOCK to-block-paragraph UNSYNTAX)
(define-code RACKETBLOCK0 to-paragraph UNSYNTAX)
(define (to-block-paragraph v)
(code-inset (to-paragraph v)))
(define (to-result-paragraph v)
(to-paragraph v
#:color? #f
#:wrap-elem
(lambda (e) (make-element result-color e))))
(define (to-result-paragraph/prefix a b c)
(define to-paragraph (to-paragraph/prefix a b c))
(lambda (v)
(to-paragraph v
#:color? #f
#:wrap-elem
(lambda (e) (make-element result-color e)))))
(define-code racketresultblock0 to-result-paragraph)
(define-code racketresultblock (to-result-paragraph/prefix (hspace 2) (hspace 2) ""))
(define-code RACKETRESULTBLOCK (to-result-paragraph/prefix (hspace 2) (hspace 2) "")
UNSYNTAX)
(define-code RACKETRESULTBLOCK0 to-result-paragraph UNSYNTAX)
(define interaction-prompt (make-element 'tt (list "> " )))
(define-code racketinput to-input-paragraph/inset)
(define-code RACKETINPUT to-input-paragraph/inset)
(define-code racketinput0 to-input-paragraph)
(define-code RACKETINPUT0 to-input-paragraph)
(define to-input-paragraph
(to-paragraph/prefix
(make-element #f interaction-prompt)
(hspace 2)
""))
(define (to-input-paragraph/inset v)
(code-inset (to-input-paragraph v)))
(define-syntax (racketmod0 stx)
(syntax-case stx ()
[(_ #:file filename #:escape unsyntax-id lang rest ...)
(with-syntax ([modtag (datum->syntax
#'here
(list #'unsyntax-id
`(make-element
#f
(list (hash-lang)
spacer
,(if (identifier? #'lang)
`(as-modname-link
',#'lang
(to-element ',#'lang)
#f)
#'(racket lang)))))
#'lang)])
(if (syntax-e #'filename)
(quasisyntax/loc stx
(filebox
filename
#,(syntax/loc stx (racketblock0 #:escape unsyntax-id modtag rest ...))))
(syntax/loc stx (racketblock0 #:escape unsyntax-id modtag rest ...))))]
[(_ #:file filename lang rest ...)
(syntax/loc stx (racketmod0 #:file filename #:escape unsyntax lang rest ...))]
[(_ lang rest ...)
(syntax/loc stx (racketmod0 #:file #f lang rest ...))]))
(define-syntax-rule (racketmod rest ...)
(code-inset (racketmod0 rest ...)))
(define (to-element/result s)
(make-element result-color (list (to-element/no-color s))))
(define (to-element/id s)
(make-element symbol-color (list (to-element/no-color s))))
(define (to-element/no-escapes s)
(to-element s #:escapes? #f))
(define-syntax (keep-s-expr stx)
(syntax-case stx (quote)
[(_ ctx '#t #(src line col pos 5))
#'(make-long-boolean #t)]
[(_ ctx '#f #(src line col pos 6))
#'(make-long-boolean #f)]
[(_ ctx s srcloc)
(let ([sv (syntax-e
(syntax-case #'s (quote)
[(quote s) #'s]
[_ #'s]))])
(if (or (number? sv)
(boolean? sv)
(and (pair? sv)
(identifier? (car sv))
(or (free-identifier=? #'cons (car sv))
(free-identifier=? #'list (car sv)))))
;; We know that the context is irrelvant
#'s
;; Context may be relevant:
#'(*keep-s-expr s ctx)))]))
(define (*keep-s-expr s ctx)
(if (symbol? s)
(make-just-context s ctx)
s))
(define (add-sq-prop s name val)
(if (eq? name 'paren-shape)
(make-shaped-parens s val)
s))
(define-code racketblockelem to-element)
(define-code racket to-element unsyntax keep-s-expr add-sq-prop)
(define-code RACKET to-element UNSYNTAX keep-s-expr add-sq-prop)
(define-code racketresult to-element/result unsyntax keep-s-expr add-sq-prop)
(define-code racketid to-element/id unsyntax keep-s-expr add-sq-prop)
(define-code *racketmodname to-element/no-escapes unsyntax keep-s-expr add-sq-prop)
(define-syntax (**racketmodname stx)
(syntax-case stx ()
[(_ form)
(let ([stx #'form])
#`(*racketmodname
;; We want to remove lexical context from identifiers
;; that correspond to module names, but keep context
;; for `lib' or `planet' (which are rarely used)
#,(cond
[(identifier? stx) (datum->syntax #f (syntax-e stx) stx stx)]
[(and (pair? (syntax-e stx))
(memq (syntax-e (car (syntax-e stx))) '(lib planet file)))
(define s (car (syntax-e stx)))
(define rest
(let loop ([a (cdr (syntax-e stx))] [head? #f])
(cond
[(identifier? a) (datum->syntax #f (syntax-e a) a a)]
[(and head? (pair? a) (and (identifier? (car a))
(free-identifier=? #'unsyntax (car a))))
a]
[(pair? a) (cons (loop (car a) #t)
(loop (cdr a) #f))]
[(syntax? a) (datum->syntax a
(loop (syntax-e a) head?)
a
a)]
[else a])))
(datum->syntax stx (cons s rest) stx stx)]
[else stx])))]))
(define-syntax racketmodname
(syntax-rules (unsyntax)
[(racketmodname #,n)
(let ([sym n])
(as-modname-link sym (to-element sym) #f))]
[(racketmodname n)
(as-modname-link 'n (**racketmodname n) #f)]
[(racketmodname #,n #:indirect)
(let ([sym n])
(as-modname-link sym (to-element sym) #t))]
[(racketmodname n #:indirect)
(as-modname-link 'n (**racketmodname n) #t)]))
(define-syntax racketmodlink
(syntax-rules (unsyntax)
[(racketmodlink n content ...)
(*as-modname-link 'n (elem #:style #f content ...) #f)]))
(define (as-modname-link s e indirect?)
(if (symbol? s)
(*as-modname-link s e indirect?)
e))
(define-on-demand indirect-module-link-color
(struct-copy style module-link-color
[properties (cons 'indirect-link
(style-properties module-link-color))]))
(define (*as-modname-link s e indirect?)
(make-link-element (if indirect?
indirect-module-link-color
module-link-color)
(list e)
`(mod-path ,(datum-intern-literal (format "~s" s)))))
(define-syntax-rule (indexed-racket x)
(add-racket-index 'x (racket x)))
(define (add-racket-index s e)
(define k
(cond [(and (pair? s) (eq? (car s) 'quote)) (format "~s" (cadr s))]
[(string? s) s]
[else (format "~s" s)]))
(index* (list k) (list e) e))
(define-syntax-rule (define-/form id base)
(define-syntax (id stx)
(syntax-case stx ()
[(_ a)
;; Remove the context from any ellipsis in `a`:
(with-syntax ([a (strip-ellipsis-context #'a)])
#'(base a))])))
(define-for-syntax (strip-ellipsis-context a)
(define a-ellipsis (datum->syntax a '...))
(define a-ellipsis+ (datum->syntax a '...+))
(let loop ([a a])
(cond
[(identifier? a)
(cond
[(free-identifier=? a a-ellipsis #f)
(datum->syntax #f '... a a)]
[(free-identifier=? a a-ellipsis+ #f)
(datum->syntax #f '...+ a a)]
[else a])]
[(syntax? a)
(datum->syntax a (loop (syntax-e a)) a a)]
[(pair? a)
(cons (loop (car a))
(loop (cdr a)))]
[(vector? a)
(list->vector
(map loop (vector->list a)))]
[(box? a)
(box (loop (unbox a)))]
[(prefab-struct-key a)
=> (lambda (k)
(apply make-prefab-struct
k
(loop (cdr (vector->list (struct->vector a))))))]
[else a])))
(define-/form racketblock0/form racketblock0)
(define-/form racketblock/form racketblock)
(define-/form racket/form racket)
(define (*racketlink stx-id id style . s)
(define content (decode-content s))
(make-delayed-element
(lambda (r p ri)
(make-link-element
style
content
(or (find-racket-tag p ri stx-id #f)
`(undef ,(format "--UNDEFINED:~a--" (syntax-e stx-id))))))
(lambda () content)
(lambda () content)))
(define-syntax racketlink
(syntax-rules ()
[(_ id #:style style . content)
(*racketlink (quote-syntax id) 'id style . content)]
[(_ id . content)
(*racketlink (quote-syntax id) 'id #f . content)]))
| null | https://raw.githubusercontent.com/racket/scribble/d36a983e9d216e04ac1738fa3689c80731937f38/scribble-lib/scribble/private/manual-scheme.rkt | racket | used via datum->syntax
We know that the context is irrelvant
Context may be relevant:
We want to remove lexical context from identifiers
that correspond to module names, but keep context
for `lib' or `planet' (which are rarely used)
Remove the context from any ellipsis in `a`: | #lang racket/base
(require "../decode.rkt"
"../struct.rkt"
"../scheme.rkt"
"../search.rkt"
"../basic.rkt"
(only-in "../core.rkt" style style-properties)
"manual-style.rkt"
"on-demand.rkt"
(for-syntax racket/base)
(for-label racket/base))
(provide racketblock RACKETBLOCK racketblock/form
racketblock0 RACKETBLOCK0 racketblock0/form
racketresultblock racketresultblock0
RACKETRESULTBLOCK RACKETRESULTBLOCK0
racketblockelem
racketinput RACKETINPUT
racketinput0 RACKETINPUT0
racketmod
racketmod0
racket RACKET racket/form racketresult racketid
racketmodname
racketmodlink indexed-racket
racketlink
(rename-out [racketblock schemeblock]
[RACKETBLOCK SCHEMEBLOCK]
[racketblock/form schemeblock/form]
[racketblock0 schemeblock0]
[RACKETBLOCK0 SCHEMEBLOCK0]
[racketblock0/form schemeblock0/form]
[racketblockelem schemeblockelem]
[racketinput schemeinput]
[racketmod schememod]
[racket scheme]
[RACKET SCHEME]
[racket/form scheme/form]
[racketresult schemeresult]
[racketid schemeid]
[racketmodname schememodname]
[racketmodlink schememodlink]
[indexed-racket indexed-scheme]
[racketlink schemelink]))
(define-code racketblock0 to-paragraph)
(define-code racketblock to-block-paragraph)
(define-code RACKETBLOCK to-block-paragraph UNSYNTAX)
(define-code RACKETBLOCK0 to-paragraph UNSYNTAX)
(define (to-block-paragraph v)
(code-inset (to-paragraph v)))
(define (to-result-paragraph v)
(to-paragraph v
#:color? #f
#:wrap-elem
(lambda (e) (make-element result-color e))))
(define (to-result-paragraph/prefix a b c)
(define to-paragraph (to-paragraph/prefix a b c))
(lambda (v)
(to-paragraph v
#:color? #f
#:wrap-elem
(lambda (e) (make-element result-color e)))))
(define-code racketresultblock0 to-result-paragraph)
(define-code racketresultblock (to-result-paragraph/prefix (hspace 2) (hspace 2) ""))
(define-code RACKETRESULTBLOCK (to-result-paragraph/prefix (hspace 2) (hspace 2) "")
UNSYNTAX)
(define-code RACKETRESULTBLOCK0 to-result-paragraph UNSYNTAX)
(define interaction-prompt (make-element 'tt (list "> " )))
(define-code racketinput to-input-paragraph/inset)
(define-code RACKETINPUT to-input-paragraph/inset)
(define-code racketinput0 to-input-paragraph)
(define-code RACKETINPUT0 to-input-paragraph)
(define to-input-paragraph
(to-paragraph/prefix
(make-element #f interaction-prompt)
(hspace 2)
""))
(define (to-input-paragraph/inset v)
(code-inset (to-input-paragraph v)))
(define-syntax (racketmod0 stx)
(syntax-case stx ()
[(_ #:file filename #:escape unsyntax-id lang rest ...)
(with-syntax ([modtag (datum->syntax
#'here
(list #'unsyntax-id
`(make-element
#f
(list (hash-lang)
spacer
,(if (identifier? #'lang)
`(as-modname-link
',#'lang
(to-element ',#'lang)
#f)
#'(racket lang)))))
#'lang)])
(if (syntax-e #'filename)
(quasisyntax/loc stx
(filebox
filename
#,(syntax/loc stx (racketblock0 #:escape unsyntax-id modtag rest ...))))
(syntax/loc stx (racketblock0 #:escape unsyntax-id modtag rest ...))))]
[(_ #:file filename lang rest ...)
(syntax/loc stx (racketmod0 #:file filename #:escape unsyntax lang rest ...))]
[(_ lang rest ...)
(syntax/loc stx (racketmod0 #:file #f lang rest ...))]))
(define-syntax-rule (racketmod rest ...)
(code-inset (racketmod0 rest ...)))
(define (to-element/result s)
(make-element result-color (list (to-element/no-color s))))
(define (to-element/id s)
(make-element symbol-color (list (to-element/no-color s))))
(define (to-element/no-escapes s)
(to-element s #:escapes? #f))
(define-syntax (keep-s-expr stx)
(syntax-case stx (quote)
[(_ ctx '#t #(src line col pos 5))
#'(make-long-boolean #t)]
[(_ ctx '#f #(src line col pos 6))
#'(make-long-boolean #f)]
[(_ ctx s srcloc)
(let ([sv (syntax-e
(syntax-case #'s (quote)
[(quote s) #'s]
[_ #'s]))])
(if (or (number? sv)
(boolean? sv)
(and (pair? sv)
(identifier? (car sv))
(or (free-identifier=? #'cons (car sv))
(free-identifier=? #'list (car sv)))))
#'s
#'(*keep-s-expr s ctx)))]))
(define (*keep-s-expr s ctx)
(if (symbol? s)
(make-just-context s ctx)
s))
(define (add-sq-prop s name val)
(if (eq? name 'paren-shape)
(make-shaped-parens s val)
s))
(define-code racketblockelem to-element)
(define-code racket to-element unsyntax keep-s-expr add-sq-prop)
(define-code RACKET to-element UNSYNTAX keep-s-expr add-sq-prop)
(define-code racketresult to-element/result unsyntax keep-s-expr add-sq-prop)
(define-code racketid to-element/id unsyntax keep-s-expr add-sq-prop)
(define-code *racketmodname to-element/no-escapes unsyntax keep-s-expr add-sq-prop)
(define-syntax (**racketmodname stx)
(syntax-case stx ()
[(_ form)
(let ([stx #'form])
#`(*racketmodname
#,(cond
[(identifier? stx) (datum->syntax #f (syntax-e stx) stx stx)]
[(and (pair? (syntax-e stx))
(memq (syntax-e (car (syntax-e stx))) '(lib planet file)))
(define s (car (syntax-e stx)))
(define rest
(let loop ([a (cdr (syntax-e stx))] [head? #f])
(cond
[(identifier? a) (datum->syntax #f (syntax-e a) a a)]
[(and head? (pair? a) (and (identifier? (car a))
(free-identifier=? #'unsyntax (car a))))
a]
[(pair? a) (cons (loop (car a) #t)
(loop (cdr a) #f))]
[(syntax? a) (datum->syntax a
(loop (syntax-e a) head?)
a
a)]
[else a])))
(datum->syntax stx (cons s rest) stx stx)]
[else stx])))]))
(define-syntax racketmodname
(syntax-rules (unsyntax)
[(racketmodname #,n)
(let ([sym n])
(as-modname-link sym (to-element sym) #f))]
[(racketmodname n)
(as-modname-link 'n (**racketmodname n) #f)]
[(racketmodname #,n #:indirect)
(let ([sym n])
(as-modname-link sym (to-element sym) #t))]
[(racketmodname n #:indirect)
(as-modname-link 'n (**racketmodname n) #t)]))
(define-syntax racketmodlink
(syntax-rules (unsyntax)
[(racketmodlink n content ...)
(*as-modname-link 'n (elem #:style #f content ...) #f)]))
(define (as-modname-link s e indirect?)
(if (symbol? s)
(*as-modname-link s e indirect?)
e))
(define-on-demand indirect-module-link-color
(struct-copy style module-link-color
[properties (cons 'indirect-link
(style-properties module-link-color))]))
(define (*as-modname-link s e indirect?)
(make-link-element (if indirect?
indirect-module-link-color
module-link-color)
(list e)
`(mod-path ,(datum-intern-literal (format "~s" s)))))
(define-syntax-rule (indexed-racket x)
(add-racket-index 'x (racket x)))
(define (add-racket-index s e)
(define k
(cond [(and (pair? s) (eq? (car s) 'quote)) (format "~s" (cadr s))]
[(string? s) s]
[else (format "~s" s)]))
(index* (list k) (list e) e))
(define-syntax-rule (define-/form id base)
(define-syntax (id stx)
(syntax-case stx ()
[(_ a)
(with-syntax ([a (strip-ellipsis-context #'a)])
#'(base a))])))
(define-for-syntax (strip-ellipsis-context a)
(define a-ellipsis (datum->syntax a '...))
(define a-ellipsis+ (datum->syntax a '...+))
(let loop ([a a])
(cond
[(identifier? a)
(cond
[(free-identifier=? a a-ellipsis #f)
(datum->syntax #f '... a a)]
[(free-identifier=? a a-ellipsis+ #f)
(datum->syntax #f '...+ a a)]
[else a])]
[(syntax? a)
(datum->syntax a (loop (syntax-e a)) a a)]
[(pair? a)
(cons (loop (car a))
(loop (cdr a)))]
[(vector? a)
(list->vector
(map loop (vector->list a)))]
[(box? a)
(box (loop (unbox a)))]
[(prefab-struct-key a)
=> (lambda (k)
(apply make-prefab-struct
k
(loop (cdr (vector->list (struct->vector a))))))]
[else a])))
(define-/form racketblock0/form racketblock0)
(define-/form racketblock/form racketblock)
(define-/form racket/form racket)
(define (*racketlink stx-id id style . s)
(define content (decode-content s))
(make-delayed-element
(lambda (r p ri)
(make-link-element
style
content
(or (find-racket-tag p ri stx-id #f)
`(undef ,(format "--UNDEFINED:~a--" (syntax-e stx-id))))))
(lambda () content)
(lambda () content)))
(define-syntax racketlink
(syntax-rules ()
[(_ id #:style style . content)
(*racketlink (quote-syntax id) 'id style . content)]
[(_ id . content)
(*racketlink (quote-syntax id) 'id #f . content)]))
|
a2751fd121a1f8807c11a4c5ed4d9c60004a7e116aa84498848ceef963a50d31 | haskell-beam/beam | employee3common.hs | {-# LANGUAGE ImpredicativeTypes #-}
# LANGUAGE NoMonomorphismRestriction #
import Prelude hiding (lookup)
import Database.Beam hiding (withDatabaseDebug)
import qualified Database.Beam as Beam
import Database.Beam.Backend.SQL
import Database.Beam.Backend.Types
import Database.Beam.Sqlite hiding (runBeamSqliteDebug)
import qualified Database.Beam.Sqlite as Sqlite
import Database.SQLite.Simple
import Database.SQLite.Simple.FromField
import Text.Read
import Data.Time
import Lens.Micro
import Data.Text (Text)
import Data.Int
import Control.Monad
import Data.IORef
data UserT f
= User
{ _userEmail :: Columnar f Text
, _userFirstName :: Columnar f Text
, _userLastName :: Columnar f Text
, _userPassword :: Columnar f Text }
deriving Generic
type User = UserT Identity
type UserId = PrimaryKey UserT Identity
deriving instance Show User
deriving instance Eq User
instance Beamable UserT
instance Table UserT where
data PrimaryKey UserT f = UserId (Columnar f Text) deriving Generic
primaryKey = UserId . _userEmail
instance Beamable (PrimaryKey UserT)
data AddressT f = Address
{ _addressId :: C f Int32
, _addressLine1 :: C f Text
, _addressLine2 :: C f (Maybe Text)
, _addressCity :: C f Text
, _addressState :: C f Text
, _addressZip :: C f Text
, _addressForUser :: PrimaryKey UserT f }
deriving Generic
type Address = AddressT Identity
deriving instance Show (PrimaryKey UserT Identity)
deriving instance Show Address
instance Table AddressT where
data PrimaryKey AddressT f = AddressId (Columnar f Int32) deriving Generic
primaryKey = AddressId . _addressId
type AddressId = PrimaryKey AddressT Identity -- For convenience
instance Beamable AddressT
instance Beamable (PrimaryKey AddressT)
data ProductT f = Product
{ _productId :: C f Int32
, _productTitle :: C f Text
, _productDescription :: C f Text
, _productPrice :: C f Int32 {- Price in cents -} }
deriving Generic
type Product = ProductT Identity
deriving instance Show Product
instance Table ProductT where
data PrimaryKey ProductT f = ProductId (Columnar f Int32)
deriving Generic
primaryKey = ProductId . _productId
instance Beamable ProductT
instance Beamable (PrimaryKey ProductT)
deriving instance Show (PrimaryKey AddressT Identity)
data OrderT f = Order
{ _orderId :: Columnar f Int32
, _orderDate :: Columnar f LocalTime
, _orderForUser :: PrimaryKey UserT f
, _orderShipToAddress :: PrimaryKey AddressT f
, _orderShippingInfo :: PrimaryKey ShippingInfoT (Nullable f) }
deriving Generic
type Order = OrderT Identity
deriving instance Show Order
instance Table OrderT where
data PrimaryKey OrderT f = OrderId (Columnar f Int32)
deriving Generic
primaryKey = OrderId . _orderId
instance Beamable OrderT
instance Beamable (PrimaryKey OrderT)
data ShippingCarrier = USPS | FedEx | UPS | DHL
deriving (Show, Read, Eq, Ord, Enum)
instance HasSqlValueSyntax be String => HasSqlValueSyntax be ShippingCarrier where
sqlValueSyntax = autoSqlValueSyntax
instance FromField ShippingCarrier where
fromField f = do x <- readMaybe <$> fromField f
case x of
Nothing -> returnError ConversionFailed f "Could not 'read' value for 'ShippingCarrier'"
Just x -> pure x
instance (BeamBackend be, BackendFromField be ShippingCarrier) => FromBackendRow be ShippingCarrier
data ShippingInfoT f = ShippingInfo
{ _shippingInfoId :: Columnar f Int32
, _shippingInfoCarrier :: Columnar f ShippingCarrier
, _shippingInfoTrackingNumber :: Columnar f Text }
deriving Generic
type ShippingInfo = ShippingInfoT Identity
deriving instance Show ShippingInfo
instance Table ShippingInfoT where
data PrimaryKey ShippingInfoT f = ShippingInfoId (Columnar f Int32)
deriving Generic
primaryKey = ShippingInfoId . _shippingInfoId
instance Beamable ShippingInfoT
instance Beamable (PrimaryKey ShippingInfoT)
deriving instance Show (PrimaryKey ShippingInfoT (Nullable Identity))
deriving instance Show (PrimaryKey OrderT Identity)
deriving instance Show (PrimaryKey ProductT Identity)
data LineItemT f = LineItem
{ _lineItemInOrder :: PrimaryKey OrderT f
, _lineItemForProduct :: PrimaryKey ProductT f
, _lineItemQuantity :: Columnar f Int32 }
deriving Generic
type LineItem = LineItemT Identity
deriving instance Show LineItem
instance Table LineItemT where
data PrimaryKey LineItemT f = LineItemId (PrimaryKey OrderT f) (PrimaryKey ProductT f)
deriving Generic
primaryKey = LineItemId <$> _lineItemInOrder <*> _lineItemForProduct
instance Beamable LineItemT
instance Beamable (PrimaryKey LineItemT)
data ShoppingCartDb f = ShoppingCartDb
{ _shoppingCartUsers :: f (TableEntity UserT)
, _shoppingCartUserAddresses :: f (TableEntity AddressT)
, _shoppingCartProducts :: f (TableEntity ProductT)
, _shoppingCartOrders :: f (TableEntity OrderT)
, _shoppingCartShippingInfos :: f (TableEntity ShippingInfoT)
, _shoppingCartLineItems :: f (TableEntity LineItemT) }
deriving Generic
instance Database be ShoppingCartDb
ShoppingCartDb (TableLens shoppingCartUsers) (TableLens shoppingCartUserAddresses)
(TableLens shoppingCartProducts) (TableLens shoppingCartOrders)
(TableLens shoppingCartShippingInfos) (TableLens shoppingCartLineItems) = dbLenses
shoppingCartDb :: DatabaseSettings be ShoppingCartDb
shoppingCartDb = defaultDbSettings `withDbModification`
dbModification {
_shoppingCartUserAddresses =
modifyTable (\_ -> "addresses") $
tableModification {
_addressLine1 = fieldNamed "address1",
_addressLine2 = fieldNamed "address2"
},
_shoppingCartProducts = modifyTable (\_ -> "products") tableModification,
_shoppingCartOrders = modifyTable (\_ -> "orders") $
tableModification {
_orderShippingInfo = ShippingInfoId "shipping_info__id"
},
_shoppingCartShippingInfos = modifyTable (\_ -> "shipping_info") $
tableModification {
_shippingInfoId = "id",
_shippingInfoCarrier = "carrier",
_shippingInfoTrackingNumber = "tracking_number"
},
_shoppingCartLineItems = modifyTable (\_ -> "line_items") tableModification
}
Address (LensFor addressId) (LensFor addressLine1)
(LensFor addressLine2) (LensFor addressCity)
(LensFor addressState) (LensFor addressZip)
(UserId (LensFor addressForUserId)) =
tableLenses
User (LensFor userEmail) (LensFor userFirstName)
(LensFor userLastName) (LensFor userPassword) =
tableLenses
LineItem _ _ (LensFor lineItemQuantity) = tableLenses
Product (LensFor productId) (LensFor productTitle) (LensFor productDescription) (LensFor productPrice) = tableLenses
main :: IO ()
main =
do conn <- open ":memory:"
execute_ conn "CREATE TABLE cart_users (email VARCHAR NOT NULL, first_name VARCHAR NOT NULL, last_name VARCHAR NOT NULL, password VARCHAR NOT NULL, PRIMARY KEY( email ));"
execute_ conn "CREATE TABLE addresses ( id INTEGER PRIMARY KEY AUTOINCREMENT, address1 VARCHAR NOT NULL, address2 VARCHAR, city VARCHAR NOT NULL, state VARCHAR NOT NULL, zip VARCHAR NOT NULL, for_user__email VARCHAR NOT NULL );"
execute_ conn "CREATE TABLE products ( id INTEGER PRIMARY KEY AUTOINCREMENT, title VARCHAR NOT NULL, description VARCHAR NOT NULL, price INT NOT NULL );"
execute_ conn "CREATE TABLE orders ( id INTEGER PRIMARY KEY AUTOINCREMENT, date TIMESTAMP NOT NULL, for_user__email VARCHAR NOT NULL, ship_to_address__id INT NOT NULL, shipping_info__id INT);"
execute_ conn "CREATE TABLE shipping_info ( id INTEGER PRIMARY KEY AUTOINCREMENT, carrier VARCHAR NOT NULL, tracking_number VARCHAR NOT NULL);"
execute_ conn "CREATE TABLE line_items (item_in_order__id INTEGER NOT NULL, item_for_product__id INTEGER NOT NULL, item_quantity INTEGER NOT NULL)"
let users@[james, betty, sam] =
[ User "" "James" "Smith" "b4cc344d25a2efe540adbf2678e2304c" {- james -}
, User "" "Betty" "Jones" "82b054bd83ffad9b6cf8bdb98ce3cc2f" {- betty -}
, User "" "Sam" "Taylor" "332532dcfaa1cbf61e2a266bd723612c" {- sam -} ]
addresses = [ Address default_ (val_ "123 Little Street") (val_ Nothing) (val_ "Boston") (val_ "MA") (val_ "12345") (pk james)
, Address default_ (val_ "222 Main Street") (val_ (Just "Ste 1")) (val_ "Houston") (val_ "TX") (val_ "8888") (pk betty)
, Address default_ (val_ "9999 Residence Ave") (val_ Nothing) (val_ "Sugarland") (val_ "TX") (val_ "8989") (pk betty) ]
products = [ Product default_ (val_ "Red Ball") (val_ "A bright red, very spherical ball") (val_ 1000)
, Product default_ (val_ "Math Textbook") (val_ "Contains a lot of important math theorems and formulae") (val_ 2500)
, Product default_ (val_ "Intro to Haskell") (val_ "Learn the best programming language in the world") (val_ 3000)
, Product default_ (val_ "Suitcase") (val_ "A hard durable suitcase") (val_ 15000) ]
(jamesAddress1, bettyAddress1, bettyAddress2, redBall, mathTextbook, introToHaskell, suitcase) <-
runBeamSqlite conn $ do
runInsert $ insert (shoppingCartDb ^. shoppingCartUsers) $
insertValues users
[jamesAddress1, bettyAddress1, bettyAddress2] <-
runInsertReturningList $
insertReturning (shoppingCartDb ^. shoppingCartUserAddresses) $ insertExpressions addresses
[redBall, mathTextbook, introToHaskell, suitcase] <-
runInsertReturningList $
insertReturning (shoppingCartDb ^. shoppingCartProducts) $ insertExpressions products
pure ( jamesAddress1, bettyAddress1, bettyAddress2, redBall, mathTextbook, introToHaskell, suitcase )
bettyShippingInfo <-
runBeamSqlite conn $ do
[bettyShippingInfo] <-
runInsertReturningList $
insertReturning (shoppingCartDb ^. shoppingCartShippingInfos) $
insertExpressions [ ShippingInfo default_ (val_ USPS) (val_ "12345790ABCDEFGHI") ]
pure bettyShippingInfo
| null | https://raw.githubusercontent.com/haskell-beam/beam/596981a1ea6765b9f311d48a2ec4d8460ebc4b7e/docs/beam-templates/employee3common.hs | haskell | # LANGUAGE ImpredicativeTypes #
For convenience
Price in cents
james
betty
sam | # LANGUAGE NoMonomorphismRestriction #
import Prelude hiding (lookup)
import Database.Beam hiding (withDatabaseDebug)
import qualified Database.Beam as Beam
import Database.Beam.Backend.SQL
import Database.Beam.Backend.Types
import Database.Beam.Sqlite hiding (runBeamSqliteDebug)
import qualified Database.Beam.Sqlite as Sqlite
import Database.SQLite.Simple
import Database.SQLite.Simple.FromField
import Text.Read
import Data.Time
import Lens.Micro
import Data.Text (Text)
import Data.Int
import Control.Monad
import Data.IORef
data UserT f
= User
{ _userEmail :: Columnar f Text
, _userFirstName :: Columnar f Text
, _userLastName :: Columnar f Text
, _userPassword :: Columnar f Text }
deriving Generic
type User = UserT Identity
type UserId = PrimaryKey UserT Identity
deriving instance Show User
deriving instance Eq User
instance Beamable UserT
instance Table UserT where
data PrimaryKey UserT f = UserId (Columnar f Text) deriving Generic
primaryKey = UserId . _userEmail
instance Beamable (PrimaryKey UserT)
data AddressT f = Address
{ _addressId :: C f Int32
, _addressLine1 :: C f Text
, _addressLine2 :: C f (Maybe Text)
, _addressCity :: C f Text
, _addressState :: C f Text
, _addressZip :: C f Text
, _addressForUser :: PrimaryKey UserT f }
deriving Generic
type Address = AddressT Identity
deriving instance Show (PrimaryKey UserT Identity)
deriving instance Show Address
instance Table AddressT where
data PrimaryKey AddressT f = AddressId (Columnar f Int32) deriving Generic
primaryKey = AddressId . _addressId
instance Beamable AddressT
instance Beamable (PrimaryKey AddressT)
data ProductT f = Product
{ _productId :: C f Int32
, _productTitle :: C f Text
, _productDescription :: C f Text
deriving Generic
type Product = ProductT Identity
deriving instance Show Product
instance Table ProductT where
data PrimaryKey ProductT f = ProductId (Columnar f Int32)
deriving Generic
primaryKey = ProductId . _productId
instance Beamable ProductT
instance Beamable (PrimaryKey ProductT)
deriving instance Show (PrimaryKey AddressT Identity)
data OrderT f = Order
{ _orderId :: Columnar f Int32
, _orderDate :: Columnar f LocalTime
, _orderForUser :: PrimaryKey UserT f
, _orderShipToAddress :: PrimaryKey AddressT f
, _orderShippingInfo :: PrimaryKey ShippingInfoT (Nullable f) }
deriving Generic
type Order = OrderT Identity
deriving instance Show Order
instance Table OrderT where
data PrimaryKey OrderT f = OrderId (Columnar f Int32)
deriving Generic
primaryKey = OrderId . _orderId
instance Beamable OrderT
instance Beamable (PrimaryKey OrderT)
data ShippingCarrier = USPS | FedEx | UPS | DHL
deriving (Show, Read, Eq, Ord, Enum)
instance HasSqlValueSyntax be String => HasSqlValueSyntax be ShippingCarrier where
sqlValueSyntax = autoSqlValueSyntax
instance FromField ShippingCarrier where
fromField f = do x <- readMaybe <$> fromField f
case x of
Nothing -> returnError ConversionFailed f "Could not 'read' value for 'ShippingCarrier'"
Just x -> pure x
instance (BeamBackend be, BackendFromField be ShippingCarrier) => FromBackendRow be ShippingCarrier
data ShippingInfoT f = ShippingInfo
{ _shippingInfoId :: Columnar f Int32
, _shippingInfoCarrier :: Columnar f ShippingCarrier
, _shippingInfoTrackingNumber :: Columnar f Text }
deriving Generic
type ShippingInfo = ShippingInfoT Identity
deriving instance Show ShippingInfo
instance Table ShippingInfoT where
data PrimaryKey ShippingInfoT f = ShippingInfoId (Columnar f Int32)
deriving Generic
primaryKey = ShippingInfoId . _shippingInfoId
instance Beamable ShippingInfoT
instance Beamable (PrimaryKey ShippingInfoT)
deriving instance Show (PrimaryKey ShippingInfoT (Nullable Identity))
deriving instance Show (PrimaryKey OrderT Identity)
deriving instance Show (PrimaryKey ProductT Identity)
data LineItemT f = LineItem
{ _lineItemInOrder :: PrimaryKey OrderT f
, _lineItemForProduct :: PrimaryKey ProductT f
, _lineItemQuantity :: Columnar f Int32 }
deriving Generic
type LineItem = LineItemT Identity
deriving instance Show LineItem
instance Table LineItemT where
data PrimaryKey LineItemT f = LineItemId (PrimaryKey OrderT f) (PrimaryKey ProductT f)
deriving Generic
primaryKey = LineItemId <$> _lineItemInOrder <*> _lineItemForProduct
instance Beamable LineItemT
instance Beamable (PrimaryKey LineItemT)
data ShoppingCartDb f = ShoppingCartDb
{ _shoppingCartUsers :: f (TableEntity UserT)
, _shoppingCartUserAddresses :: f (TableEntity AddressT)
, _shoppingCartProducts :: f (TableEntity ProductT)
, _shoppingCartOrders :: f (TableEntity OrderT)
, _shoppingCartShippingInfos :: f (TableEntity ShippingInfoT)
, _shoppingCartLineItems :: f (TableEntity LineItemT) }
deriving Generic
instance Database be ShoppingCartDb
ShoppingCartDb (TableLens shoppingCartUsers) (TableLens shoppingCartUserAddresses)
(TableLens shoppingCartProducts) (TableLens shoppingCartOrders)
(TableLens shoppingCartShippingInfos) (TableLens shoppingCartLineItems) = dbLenses
shoppingCartDb :: DatabaseSettings be ShoppingCartDb
shoppingCartDb = defaultDbSettings `withDbModification`
dbModification {
_shoppingCartUserAddresses =
modifyTable (\_ -> "addresses") $
tableModification {
_addressLine1 = fieldNamed "address1",
_addressLine2 = fieldNamed "address2"
},
_shoppingCartProducts = modifyTable (\_ -> "products") tableModification,
_shoppingCartOrders = modifyTable (\_ -> "orders") $
tableModification {
_orderShippingInfo = ShippingInfoId "shipping_info__id"
},
_shoppingCartShippingInfos = modifyTable (\_ -> "shipping_info") $
tableModification {
_shippingInfoId = "id",
_shippingInfoCarrier = "carrier",
_shippingInfoTrackingNumber = "tracking_number"
},
_shoppingCartLineItems = modifyTable (\_ -> "line_items") tableModification
}
Address (LensFor addressId) (LensFor addressLine1)
(LensFor addressLine2) (LensFor addressCity)
(LensFor addressState) (LensFor addressZip)
(UserId (LensFor addressForUserId)) =
tableLenses
User (LensFor userEmail) (LensFor userFirstName)
(LensFor userLastName) (LensFor userPassword) =
tableLenses
LineItem _ _ (LensFor lineItemQuantity) = tableLenses
Product (LensFor productId) (LensFor productTitle) (LensFor productDescription) (LensFor productPrice) = tableLenses
main :: IO ()
main =
do conn <- open ":memory:"
execute_ conn "CREATE TABLE cart_users (email VARCHAR NOT NULL, first_name VARCHAR NOT NULL, last_name VARCHAR NOT NULL, password VARCHAR NOT NULL, PRIMARY KEY( email ));"
execute_ conn "CREATE TABLE addresses ( id INTEGER PRIMARY KEY AUTOINCREMENT, address1 VARCHAR NOT NULL, address2 VARCHAR, city VARCHAR NOT NULL, state VARCHAR NOT NULL, zip VARCHAR NOT NULL, for_user__email VARCHAR NOT NULL );"
execute_ conn "CREATE TABLE products ( id INTEGER PRIMARY KEY AUTOINCREMENT, title VARCHAR NOT NULL, description VARCHAR NOT NULL, price INT NOT NULL );"
execute_ conn "CREATE TABLE orders ( id INTEGER PRIMARY KEY AUTOINCREMENT, date TIMESTAMP NOT NULL, for_user__email VARCHAR NOT NULL, ship_to_address__id INT NOT NULL, shipping_info__id INT);"
execute_ conn "CREATE TABLE shipping_info ( id INTEGER PRIMARY KEY AUTOINCREMENT, carrier VARCHAR NOT NULL, tracking_number VARCHAR NOT NULL);"
execute_ conn "CREATE TABLE line_items (item_in_order__id INTEGER NOT NULL, item_for_product__id INTEGER NOT NULL, item_quantity INTEGER NOT NULL)"
let users@[james, betty, sam] =
addresses = [ Address default_ (val_ "123 Little Street") (val_ Nothing) (val_ "Boston") (val_ "MA") (val_ "12345") (pk james)
, Address default_ (val_ "222 Main Street") (val_ (Just "Ste 1")) (val_ "Houston") (val_ "TX") (val_ "8888") (pk betty)
, Address default_ (val_ "9999 Residence Ave") (val_ Nothing) (val_ "Sugarland") (val_ "TX") (val_ "8989") (pk betty) ]
products = [ Product default_ (val_ "Red Ball") (val_ "A bright red, very spherical ball") (val_ 1000)
, Product default_ (val_ "Math Textbook") (val_ "Contains a lot of important math theorems and formulae") (val_ 2500)
, Product default_ (val_ "Intro to Haskell") (val_ "Learn the best programming language in the world") (val_ 3000)
, Product default_ (val_ "Suitcase") (val_ "A hard durable suitcase") (val_ 15000) ]
(jamesAddress1, bettyAddress1, bettyAddress2, redBall, mathTextbook, introToHaskell, suitcase) <-
runBeamSqlite conn $ do
runInsert $ insert (shoppingCartDb ^. shoppingCartUsers) $
insertValues users
[jamesAddress1, bettyAddress1, bettyAddress2] <-
runInsertReturningList $
insertReturning (shoppingCartDb ^. shoppingCartUserAddresses) $ insertExpressions addresses
[redBall, mathTextbook, introToHaskell, suitcase] <-
runInsertReturningList $
insertReturning (shoppingCartDb ^. shoppingCartProducts) $ insertExpressions products
pure ( jamesAddress1, bettyAddress1, bettyAddress2, redBall, mathTextbook, introToHaskell, suitcase )
bettyShippingInfo <-
runBeamSqlite conn $ do
[bettyShippingInfo] <-
runInsertReturningList $
insertReturning (shoppingCartDb ^. shoppingCartShippingInfos) $
insertExpressions [ ShippingInfo default_ (val_ USPS) (val_ "12345790ABCDEFGHI") ]
pure bettyShippingInfo
|
6d9c7a126d573455e5e9cb444a417dda314fae390eed83717f1fa40ef5bb43fd | defndaines/meiro | triangle_test.clj | (ns meiro.triangle-test
(:require [clojure.test :refer [deftest testing is]]
[meiro.core :as m]
[meiro.triangle :as triangle]
[meiro.backtracker :as backtracker]))
(deftest neighbors-test
(testing "Top row behavior."
(is (= [[0 1] [1 0]]
(triangle/neighbors (m/init 3 3) [0 0])))
(is (= [[0 0] [0 2]]
(triangle/neighbors (m/init 3 3) [0 1])))
(is (= [[0 1] [1 2]]
(triangle/neighbors (m/init 3 3) [0 2])))
(is (= [[0 1] [0 3] [1 2]]
(triangle/neighbors (m/init 4 4) [0 2])))
(is (= [[0 2]]
(triangle/neighbors (m/init 4 4) [0 3]))))
(testing "Odd row behavior."
(is (= [[1 1] [0 0]]
(triangle/neighbors (m/init 3 3) [1 0])))
(is (= [[1 0] [1 2] [2 1]]
(triangle/neighbors (m/init 3 3) [1 1])))
(is (= [[1 1] [0 2]]
(triangle/neighbors (m/init 3 3) [1 2])))
(is (= [[1 1] [1 3] [0 2]]
(triangle/neighbors (m/init 4 4) [1 2])))
(is (= [[1 2] [2 3]]
(triangle/neighbors (m/init 4 4) [1 3]))))
(testing "Even row behavior."
(is (= [[2 1] [3 0]]
(triangle/neighbors (m/init 4 4) [2 0])))
(is (= [[2 0] [2 2] [1 1]]
(triangle/neighbors (m/init 4 4) [2 1])))
(is (= [[2 1] [3 2]]
(triangle/neighbors (m/init 4 3) [2 2])))
(is (= [[2 1] [2 3] [3 2]]
(triangle/neighbors (m/init 4 4) [2 2])))
(is (= [[2 2] [1 3]]
(triangle/neighbors (m/init 4 4) [2 3])))))
(deftest create-test
(testing "Ensure all cells are linked."
(is (every?
#(not-any? empty? %)
(backtracker/create (m/init 10 10)
[0 0]
triangle/neighbors
m/link)))))
| null | https://raw.githubusercontent.com/defndaines/meiro/f91d4dee2842c056a162c861baf8b71bb4fb140c/test/meiro/triangle_test.clj | clojure | (ns meiro.triangle-test
(:require [clojure.test :refer [deftest testing is]]
[meiro.core :as m]
[meiro.triangle :as triangle]
[meiro.backtracker :as backtracker]))
(deftest neighbors-test
(testing "Top row behavior."
(is (= [[0 1] [1 0]]
(triangle/neighbors (m/init 3 3) [0 0])))
(is (= [[0 0] [0 2]]
(triangle/neighbors (m/init 3 3) [0 1])))
(is (= [[0 1] [1 2]]
(triangle/neighbors (m/init 3 3) [0 2])))
(is (= [[0 1] [0 3] [1 2]]
(triangle/neighbors (m/init 4 4) [0 2])))
(is (= [[0 2]]
(triangle/neighbors (m/init 4 4) [0 3]))))
(testing "Odd row behavior."
(is (= [[1 1] [0 0]]
(triangle/neighbors (m/init 3 3) [1 0])))
(is (= [[1 0] [1 2] [2 1]]
(triangle/neighbors (m/init 3 3) [1 1])))
(is (= [[1 1] [0 2]]
(triangle/neighbors (m/init 3 3) [1 2])))
(is (= [[1 1] [1 3] [0 2]]
(triangle/neighbors (m/init 4 4) [1 2])))
(is (= [[1 2] [2 3]]
(triangle/neighbors (m/init 4 4) [1 3]))))
(testing "Even row behavior."
(is (= [[2 1] [3 0]]
(triangle/neighbors (m/init 4 4) [2 0])))
(is (= [[2 0] [2 2] [1 1]]
(triangle/neighbors (m/init 4 4) [2 1])))
(is (= [[2 1] [3 2]]
(triangle/neighbors (m/init 4 3) [2 2])))
(is (= [[2 1] [2 3] [3 2]]
(triangle/neighbors (m/init 4 4) [2 2])))
(is (= [[2 2] [1 3]]
(triangle/neighbors (m/init 4 4) [2 3])))))
(deftest create-test
(testing "Ensure all cells are linked."
(is (every?
#(not-any? empty? %)
(backtracker/create (m/init 10 10)
[0 0]
triangle/neighbors
m/link)))))
| |
67357ccc9e15712f913d39668efa0001e384f3a4e0c7eeb778a4fce3bd8dd843 | privet-kitty/cl-competitive | lca.lisp | (defpackage :cp/lca
(:use :cl)
(:export #:lca-table #:lca-table-p
#:make-lca-table #:lca-max-level #:lca-depths #:lca-parents
#:two-vertices-disconnected-error #:lca-get-lca #:lca-distance
#:lca-ascend #:lca-jump)
(:documentation
"Provides lowest common ancestor of tree (or forest) by binary lifting.
build: O(nlog(n))
query: O(log(n))"))
(in-package :cp/lca)
PAY ATTENTION TO THE STACK SIZE ! THE CONSTRUCTOR DOES DFS .
(deftype lca-int () '(signed-byte 32))
(deftype lca-uint () '(and lca-int (integer 0)))
(defstruct (lca-table
(:constructor %make-lca-table
(size
&aux
requires 1 + log_2{size-1 }
(max-level (+ 1 (integer-length (- size 2))))
(depths (make-array size
:element-type 'lca-int
:initial-element -1))
(parents (make-array (list size max-level)
:element-type 'lca-int))))
(:conc-name lca-)
(:copier nil))
(max-level nil :type (integer 0 #.most-positive-fixnum))
(depths nil :type (simple-array lca-int (*)))
(parents nil :type (simple-array lca-int (* *))))
(defun make-lca-table (graph &key root (key #'identity))
"GRAPH := vector of adjacency lists
ROOT := null | non-negative fixnum
If ROOT is null, this function traverses each connected component of GRAPH from
an arbitrarily picked vertex. Otherwise this function traverses GRAPH only from
GRAPH must be tree in the latter case . "
(declare (optimize (speed 3))
(vector graph)
(function key)
((or null (integer 0 #.most-positive-fixnum)) root))
(let* ((size (length graph))
(lca-table (%make-lca-table size))
(depths (lca-depths lca-table))
(parents (lca-parents lca-table))
(max-level (lca-max-level lca-table)))
(labels ((dfs (v parent depth)
(declare (lca-int v parent))
(setf (aref depths v) depth
(aref parents v 0) parent)
(dolist (edge (aref graph v))
(let ((dest (funcall key edge)))
(declare (lca-uint dest))
(unless (= dest parent)
(dfs dest v (+ 1 depth)))))))
(if root
(dfs root -1 0)
(dotimes (v size)
(when (= (aref depths v) -1)
(dfs v -1 0))))
(dotimes (k (- max-level 1))
(dotimes (v size)
(if (= -1 (aref parents v k))
(setf (aref parents v (+ k 1)) -1)
(setf (aref parents v (+ k 1))
(aref parents (aref parents v k) k)))))
lca-table)))
(define-condition two-vertices-disconnected-error (error)
((lca-table :initarg :lca-table :accessor two-vertices-disconnected-error-lca-table)
(vertex1 :initarg :vertex1 :accessor two-vertices-disconnected-error-vertex1)
(vertex2 :initarg :vertex2 :accessor two-vertices-disconnected-error-vertex2))
(:report
(lambda (c s)
(format s "~W and ~W are disconnected on lca-table ~W"
(two-vertices-disconnected-error-vertex1 c)
(two-vertices-disconnected-error-vertex2 c)
(two-vertices-disconnected-error-lca-table c)))))
(declaim (ftype (function * (values (integer 0 #.most-positive-fixnum) &optional))
lca-get-lca))
(defun lca-get-lca (lca-table vertex1 vertex2)
"Returns the lowest common ancestor of the vertices VERTEX1 and VERTEX2."
(declare (optimize (speed 3))
(lca-uint vertex1 vertex2))
(let* ((u vertex1)
(v vertex2)
(depths (lca-depths lca-table))
(parents (lca-parents lca-table))
(max-level (lca-max-level lca-table)))
(declare (lca-int u v))
Ensures depth[u ] < = ]
(when (> (aref depths u) (aref depths v))
(rotatef u v))
(dotimes (k max-level)
(when (logbitp k (- (aref depths v) (aref depths u)))
(setq v (aref parents v k))))
(if (= u v)
u
(loop for k from (- max-level 1) downto 0
unless (= (aref parents u k) (aref parents v k))
do (setq u (aref parents u k)
v (aref parents v k))
finally (if (= (aref parents u 0) -1)
(error 'two-vertices-disconnected-error
:lca-table lca-table
:vertex1 vertex1
:vertex2 vertex2)
(return (aref parents u 0)))))))
(declaim (ftype (function * (values lca-uint &optional)) lca-distance))
(defun lca-distance (lca-table vertex1 vertex2)
"Returns the distance between two vertices."
(declare (optimize (speed 3))
(lca-uint vertex1 vertex2))
(let ((depths (lca-depths lca-table))
(lca (lca-get-lca lca-table vertex1 vertex2)))
(+ (- (aref depths vertex1) (aref depths lca))
(- (aref depths vertex2) (aref depths lca)))))
(declaim (ftype (function * (values lca-uint &optional)) lca-ascend))
(defun lca-ascend (lca-table vertex delta)
"Returns the DELTA-th ancestor of VERTEX. (0-th ancestor is VERTEX itself.)"
(declare (optimize (speed 3))
(lca-uint vertex)
(integer delta))
(let ((depths (lca-depths lca-table))
(parents (lca-parents lca-table))
(max-level (lca-max-level lca-table)))
(unless (<= 0 delta (aref depths vertex))
(error "~D-th ancestor of vertex ~D doesn't exist, whose depth is ~D"
delta vertex (aref depths vertex)))
(dotimes (k max-level)
(when (logbitp k delta)
(setq vertex (aref parents vertex k))))
vertex))
(declaim (ftype (function * (values lca-uint &optional)) lca-jump))
(defun lca-jump (lca-table start end delta)
"Returns the vertex which is on the path between START and END and is located
at distance DELTA from START."
(declare (lca-uint start end delta))
(let ((lca (lca-get-lca lca-table start end))
(depths (lca-depths lca-table)))
(cond ((= lca end)
(lca-ascend lca-table start delta))
((= lca start)
(lca-ascend lca-table
end
(- (aref depths end)
(aref depths lca)
delta)))
((>= (- (aref depths start) (aref depths lca))
delta)
(lca-ascend lca-table start delta))
(t
(lca-ascend lca-table
end
(- (+ (aref depths end) (aref depths start))
(* 2 (aref depths lca))
delta))))))
| null | https://raw.githubusercontent.com/privet-kitty/cl-competitive/a29695366631170ef2aa293ddfef8e941f515ad0/module/lca.lisp | lisp | (defpackage :cp/lca
(:use :cl)
(:export #:lca-table #:lca-table-p
#:make-lca-table #:lca-max-level #:lca-depths #:lca-parents
#:two-vertices-disconnected-error #:lca-get-lca #:lca-distance
#:lca-ascend #:lca-jump)
(:documentation
"Provides lowest common ancestor of tree (or forest) by binary lifting.
build: O(nlog(n))
query: O(log(n))"))
(in-package :cp/lca)
PAY ATTENTION TO THE STACK SIZE ! THE CONSTRUCTOR DOES DFS .
(deftype lca-int () '(signed-byte 32))
(deftype lca-uint () '(and lca-int (integer 0)))
(defstruct (lca-table
(:constructor %make-lca-table
(size
&aux
requires 1 + log_2{size-1 }
(max-level (+ 1 (integer-length (- size 2))))
(depths (make-array size
:element-type 'lca-int
:initial-element -1))
(parents (make-array (list size max-level)
:element-type 'lca-int))))
(:conc-name lca-)
(:copier nil))
(max-level nil :type (integer 0 #.most-positive-fixnum))
(depths nil :type (simple-array lca-int (*)))
(parents nil :type (simple-array lca-int (* *))))
(defun make-lca-table (graph &key root (key #'identity))
"GRAPH := vector of adjacency lists
ROOT := null | non-negative fixnum
If ROOT is null, this function traverses each connected component of GRAPH from
an arbitrarily picked vertex. Otherwise this function traverses GRAPH only from
GRAPH must be tree in the latter case . "
(declare (optimize (speed 3))
(vector graph)
(function key)
((or null (integer 0 #.most-positive-fixnum)) root))
(let* ((size (length graph))
(lca-table (%make-lca-table size))
(depths (lca-depths lca-table))
(parents (lca-parents lca-table))
(max-level (lca-max-level lca-table)))
(labels ((dfs (v parent depth)
(declare (lca-int v parent))
(setf (aref depths v) depth
(aref parents v 0) parent)
(dolist (edge (aref graph v))
(let ((dest (funcall key edge)))
(declare (lca-uint dest))
(unless (= dest parent)
(dfs dest v (+ 1 depth)))))))
(if root
(dfs root -1 0)
(dotimes (v size)
(when (= (aref depths v) -1)
(dfs v -1 0))))
(dotimes (k (- max-level 1))
(dotimes (v size)
(if (= -1 (aref parents v k))
(setf (aref parents v (+ k 1)) -1)
(setf (aref parents v (+ k 1))
(aref parents (aref parents v k) k)))))
lca-table)))
(define-condition two-vertices-disconnected-error (error)
((lca-table :initarg :lca-table :accessor two-vertices-disconnected-error-lca-table)
(vertex1 :initarg :vertex1 :accessor two-vertices-disconnected-error-vertex1)
(vertex2 :initarg :vertex2 :accessor two-vertices-disconnected-error-vertex2))
(:report
(lambda (c s)
(format s "~W and ~W are disconnected on lca-table ~W"
(two-vertices-disconnected-error-vertex1 c)
(two-vertices-disconnected-error-vertex2 c)
(two-vertices-disconnected-error-lca-table c)))))
(declaim (ftype (function * (values (integer 0 #.most-positive-fixnum) &optional))
lca-get-lca))
(defun lca-get-lca (lca-table vertex1 vertex2)
"Returns the lowest common ancestor of the vertices VERTEX1 and VERTEX2."
(declare (optimize (speed 3))
(lca-uint vertex1 vertex2))
(let* ((u vertex1)
(v vertex2)
(depths (lca-depths lca-table))
(parents (lca-parents lca-table))
(max-level (lca-max-level lca-table)))
(declare (lca-int u v))
Ensures depth[u ] < = ]
(when (> (aref depths u) (aref depths v))
(rotatef u v))
(dotimes (k max-level)
(when (logbitp k (- (aref depths v) (aref depths u)))
(setq v (aref parents v k))))
(if (= u v)
u
(loop for k from (- max-level 1) downto 0
unless (= (aref parents u k) (aref parents v k))
do (setq u (aref parents u k)
v (aref parents v k))
finally (if (= (aref parents u 0) -1)
(error 'two-vertices-disconnected-error
:lca-table lca-table
:vertex1 vertex1
:vertex2 vertex2)
(return (aref parents u 0)))))))
(declaim (ftype (function * (values lca-uint &optional)) lca-distance))
(defun lca-distance (lca-table vertex1 vertex2)
"Returns the distance between two vertices."
(declare (optimize (speed 3))
(lca-uint vertex1 vertex2))
(let ((depths (lca-depths lca-table))
(lca (lca-get-lca lca-table vertex1 vertex2)))
(+ (- (aref depths vertex1) (aref depths lca))
(- (aref depths vertex2) (aref depths lca)))))
(declaim (ftype (function * (values lca-uint &optional)) lca-ascend))
(defun lca-ascend (lca-table vertex delta)
"Returns the DELTA-th ancestor of VERTEX. (0-th ancestor is VERTEX itself.)"
(declare (optimize (speed 3))
(lca-uint vertex)
(integer delta))
(let ((depths (lca-depths lca-table))
(parents (lca-parents lca-table))
(max-level (lca-max-level lca-table)))
(unless (<= 0 delta (aref depths vertex))
(error "~D-th ancestor of vertex ~D doesn't exist, whose depth is ~D"
delta vertex (aref depths vertex)))
(dotimes (k max-level)
(when (logbitp k delta)
(setq vertex (aref parents vertex k))))
vertex))
(declaim (ftype (function * (values lca-uint &optional)) lca-jump))
(defun lca-jump (lca-table start end delta)
"Returns the vertex which is on the path between START and END and is located
at distance DELTA from START."
(declare (lca-uint start end delta))
(let ((lca (lca-get-lca lca-table start end))
(depths (lca-depths lca-table)))
(cond ((= lca end)
(lca-ascend lca-table start delta))
((= lca start)
(lca-ascend lca-table
end
(- (aref depths end)
(aref depths lca)
delta)))
((>= (- (aref depths start) (aref depths lca))
delta)
(lca-ascend lca-table start delta))
(t
(lca-ascend lca-table
end
(- (+ (aref depths end) (aref depths start))
(* 2 (aref depths lca))
delta))))))
| |
f9a05e9125e67d6b74e96b82fd2a382c164736f19c372390fd8c90288daa2423 | deadtrickster/prometheus.cl | errors.lisp | (in-package #:prometheus.test)
(plan 1)
(subtest "Errors"
(subtest "Base Error"
(error-class-exists prom:base-error error))
(subtest "Invalid Value Error"
(error-class-exists prom:invalid-value-error)
(error-report-test prom:invalid-value-error ((:value -1 :reason "counters can only be incremented by non-negative amounts")
"Value -1 is invalid. Reason: counters can only be incremented by non-negative amounts")))
(subtest "Invalid Label Name Error"
(error-class-exists prom:invalid-label-name-error)
(error-report-test prom:invalid-label-name-error ((:name 123 :reason "label name is not a string")
"Label name 123 is invalid. Reason: label name is not a string")))
(subtest "Invalid Label Value Error"
(error-class-exists prom:invalid-label-value-error prom:invalid-value-error)
(error-report-test prom:invalid-label-value-error ((:value 123 :reason "label value is not a string")
"Label value 123 is invalid. Reason: label value is not a string")))
(subtest "Invalid Label Count Error"
(error-class-exists prom:invalid-label-count-error)
(error-report-test prom:invalid-label-count-error ((:actual 123 :expected 12)
"Invalid label count. Got 123, expected 12")))
(subtest "Invalid Labels Error"
(error-class-exists prom:invalid-labels-error)
(error-report-test prom:invalid-labels-error ((:actual #(1 2 3) :expected 'list)
"Invalid labels. Got #(1 2 3) (type: (SIMPLE-VECTOR 3)), expected LIST")))
(subtest "Invalid Metric Name Error"
(error-class-exists prom:invalid-metric-name-error)
(error-report-test prom:invalid-metric-name-error ((:name 123 :reason "metric name is not a string")
"Metric name 123 is invalid. Reason: metric name is not a string")))
(subtest "Invalid Buckets Error"
(error-class-exists prom:invalid-buckets-error)
(error-report-test prom:invalid-buckets-error ((:value #(1 2 3) :reason "expected LIST")
"Invalid buckets. Got #(1 2 3) (type: (SIMPLE-VECTOR 3)), reason: expected LIST")))
(subtest "Invalid Bucket Bound Error"
(error-class-exists prom:invalid-bucket-bound-error prom:invalid-value-error)
(error-report-test prom:invalid-bucket-bound-error ((:value "QWE" :reason "bucket bound is not an integer/float")
"Bucket bound \"QWE\" is invalid. Reason: bucket bound is not an integer/float")))
(subtest "Collectable Already Registered Error"
(error-class-exists prom:collectable-already-registered-error)
(error-report-test prom:collectable-already-registered-error ((:collectable 1 :registry 2 :rname 3)
"Collectable 1 already registered in registry 2 with name 3"))))
(finalize)
| null | https://raw.githubusercontent.com/deadtrickster/prometheus.cl/60572b793135e8ab5a857d47cc1a5fe0af3a2d53/t/prometheus/errors.lisp | lisp | (in-package #:prometheus.test)
(plan 1)
(subtest "Errors"
(subtest "Base Error"
(error-class-exists prom:base-error error))
(subtest "Invalid Value Error"
(error-class-exists prom:invalid-value-error)
(error-report-test prom:invalid-value-error ((:value -1 :reason "counters can only be incremented by non-negative amounts")
"Value -1 is invalid. Reason: counters can only be incremented by non-negative amounts")))
(subtest "Invalid Label Name Error"
(error-class-exists prom:invalid-label-name-error)
(error-report-test prom:invalid-label-name-error ((:name 123 :reason "label name is not a string")
"Label name 123 is invalid. Reason: label name is not a string")))
(subtest "Invalid Label Value Error"
(error-class-exists prom:invalid-label-value-error prom:invalid-value-error)
(error-report-test prom:invalid-label-value-error ((:value 123 :reason "label value is not a string")
"Label value 123 is invalid. Reason: label value is not a string")))
(subtest "Invalid Label Count Error"
(error-class-exists prom:invalid-label-count-error)
(error-report-test prom:invalid-label-count-error ((:actual 123 :expected 12)
"Invalid label count. Got 123, expected 12")))
(subtest "Invalid Labels Error"
(error-class-exists prom:invalid-labels-error)
(error-report-test prom:invalid-labels-error ((:actual #(1 2 3) :expected 'list)
"Invalid labels. Got #(1 2 3) (type: (SIMPLE-VECTOR 3)), expected LIST")))
(subtest "Invalid Metric Name Error"
(error-class-exists prom:invalid-metric-name-error)
(error-report-test prom:invalid-metric-name-error ((:name 123 :reason "metric name is not a string")
"Metric name 123 is invalid. Reason: metric name is not a string")))
(subtest "Invalid Buckets Error"
(error-class-exists prom:invalid-buckets-error)
(error-report-test prom:invalid-buckets-error ((:value #(1 2 3) :reason "expected LIST")
"Invalid buckets. Got #(1 2 3) (type: (SIMPLE-VECTOR 3)), reason: expected LIST")))
(subtest "Invalid Bucket Bound Error"
(error-class-exists prom:invalid-bucket-bound-error prom:invalid-value-error)
(error-report-test prom:invalid-bucket-bound-error ((:value "QWE" :reason "bucket bound is not an integer/float")
"Bucket bound \"QWE\" is invalid. Reason: bucket bound is not an integer/float")))
(subtest "Collectable Already Registered Error"
(error-class-exists prom:collectable-already-registered-error)
(error-report-test prom:collectable-already-registered-error ((:collectable 1 :registry 2 :rname 3)
"Collectable 1 already registered in registry 2 with name 3"))))
(finalize)
| |
3e09755389a8d3281039e064ebe1793e568f2a95ce4b9ab96f05f9f2777005c3 | tsloughter/kuberl | kuberl_v1beta1_daemon_set.erl | -module(kuberl_v1beta1_daemon_set).
-export([encode/1]).
-export_type([kuberl_v1beta1_daemon_set/0]).
-type kuberl_v1beta1_daemon_set() ::
#{ 'apiVersion' => binary(),
'kind' => binary(),
'metadata' => kuberl_v1_object_meta:kuberl_v1_object_meta(),
'spec' => kuberl_v1beta1_daemon_set_spec:kuberl_v1beta1_daemon_set_spec(),
'status' => kuberl_v1beta1_daemon_set_status:kuberl_v1beta1_daemon_set_status()
}.
encode(#{ 'apiVersion' := ApiVersion,
'kind' := Kind,
'metadata' := Metadata,
'spec' := Spec,
'status' := Status
}) ->
#{ 'apiVersion' => ApiVersion,
'kind' => Kind,
'metadata' => Metadata,
'spec' => Spec,
'status' => Status
}.
| null | https://raw.githubusercontent.com/tsloughter/kuberl/f02ae6680d6ea5db6e8b6c7acbee8c4f9df482e2/gen/kuberl_v1beta1_daemon_set.erl | erlang | -module(kuberl_v1beta1_daemon_set).
-export([encode/1]).
-export_type([kuberl_v1beta1_daemon_set/0]).
-type kuberl_v1beta1_daemon_set() ::
#{ 'apiVersion' => binary(),
'kind' => binary(),
'metadata' => kuberl_v1_object_meta:kuberl_v1_object_meta(),
'spec' => kuberl_v1beta1_daemon_set_spec:kuberl_v1beta1_daemon_set_spec(),
'status' => kuberl_v1beta1_daemon_set_status:kuberl_v1beta1_daemon_set_status()
}.
encode(#{ 'apiVersion' := ApiVersion,
'kind' := Kind,
'metadata' := Metadata,
'spec' := Spec,
'status' := Status
}) ->
#{ 'apiVersion' => ApiVersion,
'kind' => Kind,
'metadata' => Metadata,
'spec' => Spec,
'status' => Status
}.
| |
99b77258a8062a2230a7284bedcb249254f02606d0e1d2c03c5bc4771b51b4d2 | anuragsoni/poll | poll.mli | module Event = Event
module Backend = Backend
module Timeout = Timeout
module Poll_intf = Poll_intf
include Poll_intf.S
(** [create'] accepts a user-supplied polling implementation and uses it to create a new
poller instance. *)
val create' : ?num_events:int -> (module Poll_intf.S) -> t
* [ backend ] returns the io event notification backend ( ex : kqueue , epoll , etc ) used by
the poller instance .
the poller instance. *)
val backend : t -> Backend.t
| null | https://raw.githubusercontent.com/anuragsoni/poll/fc5a98eed478f59c507cabefe072b73fdb633fe8/src/poll.mli | ocaml | * [create'] accepts a user-supplied polling implementation and uses it to create a new
poller instance. | module Event = Event
module Backend = Backend
module Timeout = Timeout
module Poll_intf = Poll_intf
include Poll_intf.S
val create' : ?num_events:int -> (module Poll_intf.S) -> t
* [ backend ] returns the io event notification backend ( ex : kqueue , epoll , etc ) used by
the poller instance .
the poller instance. *)
val backend : t -> Backend.t
|
f731f7f7c9c5758c5f79ac4c0bb00e994805336a3e6bc09e4b0bca9a315d188f | simon-brooke/dog-and-duck | constants.clj | (ns dog-and-duck.quack.picky.constants
"Constants supporting the picky validator.")
Copyright ( C ) , 2022
;;; This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation ; either version 2
;;; of the License, or (at your option) any later version.
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
You should have received a copy of the GNU General Public License
;;; along with this program; if not, write to the Free Software
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 , USA .
(def ^:const activitystreams-context-uri
"The URI of the context of an ActivityStreams object is expected to be this
literal string.
**NOTE THAT** the URI actually used in the published suite of
activitystreams-test-documents use this URI with 'http' rather than
'https' as the property part, but the spec itself specifies 'https'."
"")
(def ^:const actor-types
"The set of types we will accept as actors.
There's an [explicit set of allowed actor types]
(-vocabulary/#actor-types)."
#{"Application"
"Group"
"Organization"
"Person"
"Service"})
(def ^:const context-key
"The Clojure reader barfs on `:@context`, although it is in principle a valid
keyword. So we'll make it once, here, to make the code more performant and
easier to read."
(keyword "@context"))
(def ^:const re-rfc5646
"A regex which tests conformity to RFC 5646. Cribbed from
-to-detect-locales"
#"^[a-z]{2,4}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$")
(def ^:const severity
"Severity of faults found, as follows:
0. `:info` not actually a fault, but an issue noted during validation;
1. `:minor` things which I consider to be faults, but which
don't actually breach the spec;
2. `:should` instances where the spec says something SHOULD
be done, which isn't;
3. `:must` instances where the spec says something MUST
be done, which isn't;
4. `:critical` instances where I believe the fault means that
the object cannot be meaningfully processed."
#{:info :minor :should :must :critical})
(def ^:const severity-filters
"Hack for implementing a severity hierarchy"
{:all #{}
:info #{}
:minor #{:info}
:should #{:info :minor}
:must #{:info :minor :should}
:critical #{:info :minor :should :must}})
(def ^:const validation-fault-context-uri
"The URI of the context of a validation fault report object shall be this
literal string."
"-brooke.github.io/dog-and-duck/codox/Validation_Faults.html")
(def ^:const activity-types
"The set of types we will accept as activities.
There's an [explicit set of allowed activity types]
(-vocabulary/#activity-types)."
#{"Accept" "Add" "Announce" "Arrive" "Block" "Create" "Delete" "Dislike"
"Flag" "Follow" "Ignore" "Invite" "Join" "Leave" "Like" "Listen" "Move"
"Offer" "Question" "Reject" "Read" "Remove" "TentativeAccept"
"TentativeReject" "Travel" "Undo" "Update" "View"})
(def ^:const noun-types
"The set of object types we will accept as nouns.
There's an [explicit set of allowed 'object types']
(-vocabulary/#object-types), but by
implication it is not exhaustive."
#{"Article"
"Audio"
"Document"
"Event"
"Image"
"Link"
"Mention"
"Note"
"Object"
"Page"
"Place"
"Profile"
"Relationsip"
"Tombstone"
"Video"})
(def ^:const implicit-noun-types
"These types are not explicitly listed in [Section 3.3 of the spec]
(-vocabulary/#object-types), but are
mentioned in narrative"
#{"Link"})
| null | https://raw.githubusercontent.com/simon-brooke/dog-and-duck/21a4c23c8f9eda4764ed6a0e3282fd736f6fc3a8/src/dog_and_duck/quack/picky/constants.clj | clojure | This program is free software; you can redistribute it and/or
either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program; if not, write to the Free Software
| (ns dog-and-duck.quack.picky.constants
"Constants supporting the picky validator.")
Copyright ( C ) , 2022
modify it under the terms of the GNU General Public License
You should have received a copy of the GNU General Public License
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 , USA .
(def ^:const activitystreams-context-uri
"The URI of the context of an ActivityStreams object is expected to be this
literal string.
**NOTE THAT** the URI actually used in the published suite of
activitystreams-test-documents use this URI with 'http' rather than
'https' as the property part, but the spec itself specifies 'https'."
"")
(def ^:const actor-types
"The set of types we will accept as actors.
There's an [explicit set of allowed actor types]
(-vocabulary/#actor-types)."
#{"Application"
"Group"
"Organization"
"Person"
"Service"})
(def ^:const context-key
"The Clojure reader barfs on `:@context`, although it is in principle a valid
keyword. So we'll make it once, here, to make the code more performant and
easier to read."
(keyword "@context"))
(def ^:const re-rfc5646
"A regex which tests conformity to RFC 5646. Cribbed from
-to-detect-locales"
#"^[a-z]{2,4}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$")
(def ^:const severity
"Severity of faults found, as follows:
1. `:minor` things which I consider to be faults, but which
2. `:should` instances where the spec says something SHOULD
3. `:must` instances where the spec says something MUST
4. `:critical` instances where I believe the fault means that
the object cannot be meaningfully processed."
#{:info :minor :should :must :critical})
(def ^:const severity-filters
"Hack for implementing a severity hierarchy"
{:all #{}
:info #{}
:minor #{:info}
:should #{:info :minor}
:must #{:info :minor :should}
:critical #{:info :minor :should :must}})
(def ^:const validation-fault-context-uri
"The URI of the context of a validation fault report object shall be this
literal string."
"-brooke.github.io/dog-and-duck/codox/Validation_Faults.html")
(def ^:const activity-types
"The set of types we will accept as activities.
There's an [explicit set of allowed activity types]
(-vocabulary/#activity-types)."
#{"Accept" "Add" "Announce" "Arrive" "Block" "Create" "Delete" "Dislike"
"Flag" "Follow" "Ignore" "Invite" "Join" "Leave" "Like" "Listen" "Move"
"Offer" "Question" "Reject" "Read" "Remove" "TentativeAccept"
"TentativeReject" "Travel" "Undo" "Update" "View"})
(def ^:const noun-types
"The set of object types we will accept as nouns.
There's an [explicit set of allowed 'object types']
(-vocabulary/#object-types), but by
implication it is not exhaustive."
#{"Article"
"Audio"
"Document"
"Event"
"Image"
"Link"
"Mention"
"Note"
"Object"
"Page"
"Place"
"Profile"
"Relationsip"
"Tombstone"
"Video"})
(def ^:const implicit-noun-types
"These types are not explicitly listed in [Section 3.3 of the spec]
(-vocabulary/#object-types), but are
mentioned in narrative"
#{"Link"})
|
26dc53ff21712efe4757b6d0010e2f775a18533b5edaaef71c1213202f7f83ae | haskus/haskus-system | Size.hs | # LANGUAGE LambdaCase #
-- | Sizes
module Haskus.Arch.X86_64.ISA.Size
( Size(..)
, sizeInBits
, AddressSize(..)
, SizedValue(..)
, toSizedValue
, fromSizedValue
, OperandSize(..)
, opSizeInBits
, getSize
, getSize64
, getOpSize64
) where
import Haskus.Binary.Get
import Haskus.Number.Word
-- | Size
data Size
= Size8
| Size16
| Size32
| Size64
| Size128
| Size256
| Size512
deriving (Show,Eq,Ord)
-- | Get a size in bits
sizeInBits :: Size -> Word
sizeInBits = \case
Size8 -> 8
Size16 -> 16
Size32 -> 32
Size64 -> 64
Size128 -> 128
Size256 -> 256
Size512 -> 512
-- | Address size
data AddressSize
= AddrSize16
| AddrSize32
| AddrSize64
deriving (Show,Eq,Ord)
-- | Sized value
data SizedValue
= SizedValue8 !Word8
| SizedValue16 !Word16
| SizedValue32 !Word32
| SizedValue64 !Word64
deriving (Show,Eq,Ord)
| Convert a value into a SizedValue
toSizedValue :: Size -> Word64 -> SizedValue
toSizedValue s v = case s of
Size8 -> SizedValue8 (fromIntegral v)
Size16 -> SizedValue16 (fromIntegral v)
Size32 -> SizedValue32 (fromIntegral v)
Size64 -> SizedValue64 (fromIntegral v)
_ -> error ("toSizedValue: invalid size (" ++ show s ++ ")")
| Convert a value from a SizedValue
fromSizedValue :: SizedValue -> Word64
fromSizedValue = \case
SizedValue8 v -> fromIntegral v
SizedValue16 v -> fromIntegral v
SizedValue32 v -> fromIntegral v
SizedValue64 v -> v
-- | Operand size
data OperandSize
= OpSize8
| OpSize16
| OpSize32
| OpSize64
deriving (Show,Eq,Ord)
-- | Operand size in bits
opSizeInBits :: OperandSize -> Word
opSizeInBits = \case
OpSize8 -> 8
OpSize16 -> 16
OpSize32 -> 32
OpSize64 -> 64
| Read a SizedValue
getSize :: Size -> Get SizedValue
getSize Size8 = SizedValue8 <$> getWord8
getSize Size16 = SizedValue16 <$> getWord16le
getSize Size32 = SizedValue32 <$> getWord32le
getSize Size64 = SizedValue64 <$> getWord64le
getSize s = error ("getSize: unsupported size: " ++ show s)
-- | Read a value in a Word64
getSize64 :: Size -> Get Word64
getSize64 Size8 = fromIntegral <$> getWord8
getSize64 Size16 = fromIntegral <$> getWord16le
getSize64 Size32 = fromIntegral <$> getWord32le
getSize64 Size64 = getWord64le
getSize64 s = error ("getSize: unsupported size: " ++ show s)
-- | Read a value in a Word64
getOpSize64 :: OperandSize -> Get Word64
getOpSize64 OpSize8 = fromIntegral <$> getWord8
getOpSize64 OpSize16 = fromIntegral <$> getWord16le
getOpSize64 OpSize32 = fromIntegral <$> getWord32le
getOpSize64 OpSize64 = getWord64le
| null | https://raw.githubusercontent.com/haskus/haskus-system/38b3a363c26bc4d82e3493d8638d46bc35678616/haskus-system/src/lib/Haskus/Arch/X86_64/ISA/Size.hs | haskell | | Sizes
| Size
| Get a size in bits
| Address size
| Sized value
| Operand size
| Operand size in bits
| Read a value in a Word64
| Read a value in a Word64 | # LANGUAGE LambdaCase #
module Haskus.Arch.X86_64.ISA.Size
( Size(..)
, sizeInBits
, AddressSize(..)
, SizedValue(..)
, toSizedValue
, fromSizedValue
, OperandSize(..)
, opSizeInBits
, getSize
, getSize64
, getOpSize64
) where
import Haskus.Binary.Get
import Haskus.Number.Word
data Size
= Size8
| Size16
| Size32
| Size64
| Size128
| Size256
| Size512
deriving (Show,Eq,Ord)
sizeInBits :: Size -> Word
sizeInBits = \case
Size8 -> 8
Size16 -> 16
Size32 -> 32
Size64 -> 64
Size128 -> 128
Size256 -> 256
Size512 -> 512
data AddressSize
= AddrSize16
| AddrSize32
| AddrSize64
deriving (Show,Eq,Ord)
data SizedValue
= SizedValue8 !Word8
| SizedValue16 !Word16
| SizedValue32 !Word32
| SizedValue64 !Word64
deriving (Show,Eq,Ord)
| Convert a value into a SizedValue
toSizedValue :: Size -> Word64 -> SizedValue
toSizedValue s v = case s of
Size8 -> SizedValue8 (fromIntegral v)
Size16 -> SizedValue16 (fromIntegral v)
Size32 -> SizedValue32 (fromIntegral v)
Size64 -> SizedValue64 (fromIntegral v)
_ -> error ("toSizedValue: invalid size (" ++ show s ++ ")")
| Convert a value from a SizedValue
fromSizedValue :: SizedValue -> Word64
fromSizedValue = \case
SizedValue8 v -> fromIntegral v
SizedValue16 v -> fromIntegral v
SizedValue32 v -> fromIntegral v
SizedValue64 v -> v
data OperandSize
= OpSize8
| OpSize16
| OpSize32
| OpSize64
deriving (Show,Eq,Ord)
opSizeInBits :: OperandSize -> Word
opSizeInBits = \case
OpSize8 -> 8
OpSize16 -> 16
OpSize32 -> 32
OpSize64 -> 64
| Read a SizedValue
getSize :: Size -> Get SizedValue
getSize Size8 = SizedValue8 <$> getWord8
getSize Size16 = SizedValue16 <$> getWord16le
getSize Size32 = SizedValue32 <$> getWord32le
getSize Size64 = SizedValue64 <$> getWord64le
getSize s = error ("getSize: unsupported size: " ++ show s)
getSize64 :: Size -> Get Word64
getSize64 Size8 = fromIntegral <$> getWord8
getSize64 Size16 = fromIntegral <$> getWord16le
getSize64 Size32 = fromIntegral <$> getWord32le
getSize64 Size64 = getWord64le
getSize64 s = error ("getSize: unsupported size: " ++ show s)
getOpSize64 :: OperandSize -> Get Word64
getOpSize64 OpSize8 = fromIntegral <$> getWord8
getOpSize64 OpSize16 = fromIntegral <$> getWord16le
getOpSize64 OpSize32 = fromIntegral <$> getWord32le
getOpSize64 OpSize64 = getWord64le
|
2f3e21793e9f0ffc382365b8141f80acfcb1962172059710f2f6738578faaa71 | robert-strandh/Cluster | add.lisp | (in-package #:cluster)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Mnemonic ADD
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
To the contents of GPR A ( destination ) , add an 8 - bit immediate
;;; value (source) and store the result in the destination.
;;;
Opcodes : 04
(define-instruction "ADD"
:modes (32 64)
:operands ((gpr-a 8) (imm 8))
:opcodes (#x04)
:encoding (- imm))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; To the contents of GPR A (16/32/64) (destination), add an
immediate value ( 16/32 ) ( source ) , and store the result in the
;;; destination.
;;;
Opcodes : 05
To the contents of GPR AX ( destination ) , add an immediate 16 - bit
;;; value (source), and store the result in the destination.
(define-instruction "ADD"
:modes (32 64)
:operands ((gpr-a 16) (imm 16))
:opcodes (#x05)
:encoding (- imm)
:operand-size-override t)
To the contents of ( destination ) , add an immediate 32 - bit
;;; value (source), and store the result in the destination.
(define-instruction "ADD"
:modes (32 64)
:operands ((gpr-a 32) (imm 32))
:opcodes (#x05)
:encoding (- imm))
;;; To the contents of GPR RAX (destination), add an immediate
sign - extended 32 - bit value ( source ) , and store the result in the
;;; destination.
(define-instruction "ADD"
:modes (64)
:operands ((gpr-a 64) (simm 32))
:opcodes (#x05)
:encoding (- imm)
:rex.w t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
To an 8 - bit GPR or memory location ( destination ) , add an immediate
8 - bit value ( source ) , and store the result in the destination .
;;;
Opcodes : 80
Opcode extension : 0
To an 8 - bit GPR ( destination ) , add an immediate 8 - bit value
;;; (source), and store the result in the destination.
(define-instruction "ADD"
:modes (32 64)
:operands ((gpr 8) (imm 8))
:opcodes (#x80)
:opcode-extension 0
:encoding (modrm imm))
To an 8 - bit memory location ( destination ) , add an immediate 8 - bit
;;; value (source), and store the result in the destination.
(define-instruction "ADD"
:modes (32 64)
:operands ((memory 8) (imm 8))
:opcodes (#x80)
:opcode-extension 0
:encoding (modrm imm))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; To a GPR or memory location (16/32/64) (destination), add an
immediate value ( 16/32 ) ( source ) , and store the result in the
;;; destination.
;;;
Opcodes : 81
Opcode extension 0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
To a 16 - bit GPR or memory location ( destination ) , add an immediate
16 - bit value ( source ) , and store the result in the destination .
To a 16 - bit GPR ( destination ) , add an immediate 16 - bit value
;;; (source), and store the result in the destination.
(define-instruction "ADD"
:modes (32 64)
:operands ((gpr 16) (imm 16))
:opcodes (#x81)
:opcode-extension 0
:encoding (modrm imm)
:operand-size-override t)
To a 16 - bit memory location ( destination ) , add an immediate 16 - bit
;;; value (source), and store the result in the destination.
(define-instruction "ADD"
:modes (32 64)
:operands ((memory 16) (imm 16))
:opcodes (#x81)
:opcode-extension 0
:encoding (modrm imm)
:operand-size-override t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
To a 32 - bit GPR or memory location ( destination ) , add an immediate
32 - bit value ( source ) , and store the result in the destination .
To a 32 - bit GPR ( destination ) , add an immediate 32 - bit value
;;; (source), and store the result in the destination.
(define-instruction "ADD"
:modes (32 64)
:operands ((gpr 32) (imm 32))
:opcodes (#x81)
:opcode-extension 0
:encoding (modrm imm))
To a 32 - bit memory location ( destination ) , add an immediate 32 - bit
;;; value (source), and store the result in the destination.
(define-instruction "ADD"
:modes (32 64)
:operands ((memory 32) (imm 32))
:opcodes (#x81)
:opcode-extension 0
:encoding (modrm imm))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
To a 32 - bit GPR or memory location ( destination ) , add an immediate
32 - bit sign - extended value ( source ) , and store the result in the
;;; destination.
To a 32 - bit GPR ( destination ) , add an immediate 32 - bit
;;; sign-extended value (source), and store the result in the
;;; destination.
(define-instruction "ADD"
:modes (64)
:operands ((gpr 64) (simm 32))
:opcodes (#x81)
:opcode-extension 0
:encoding (modrm imm)
:rex.w t)
To a 32 - bit memory location ( destination ) , add an immediate 32 - bit
;;; sign-extended value (source), and store the result in the
;;; destination.
(define-instruction "ADD"
:modes (64)
:operands ((memory 64) (simm 32))
:opcodes (#x81)
:opcode-extension 0
:encoding (modrm imm)
:rex.w t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; To a GPR or memory location (16/32/64) (destination), add an
immediate 8 - bit sign - extended value ( source ) , and store the result
;;; in the destination.
;;;
Opcodes : 83
Opcode extension : 0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
To a 16 - bit GPR or memory location ( destination ) , add an immediate
8 - bit sign - extended value ( source ) , and store the result in the
;;; destination.
To a 16 - bit GPR ( destination ) , add an immediate 8 - bit
;;; sign-extended value (source), and store the result in the
;;; destination.
(define-instruction "ADD"
:modes (32 64)
:operands ((gpr 16) (simm 8))
:opcodes (#x83)
:opcode-extension 0
:encoding (modrm imm)
:operand-size-override t)
To a 16 - bit memory location ( destination ) , add an immediate 8 - bit
;;; sign-extended value (source), and store the result in the
;;; destination.
(define-instruction "ADD"
:modes (32 64)
:operands ((memory 16) (simm 8))
:opcodes (#x83)
:opcode-extension 0
:encoding (modrm imm)
:operand-size-override t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
To a 32 - bit GPR or memory location ( destination ) , add an immediate
8 - bit sign - extended value ( source ) , and store the result in the
;;; destination.
To a 32 - bit GPR ( destination ) , add an immediate 8 - bit
;;; sign-extended value (source), and store the result in the
;;; destination.
(define-instruction "ADD"
:modes (32 64)
:operands ((gpr 32) (simm 8))
:opcodes (#x83)
:opcode-extension 0
:encoding (modrm imm))
To a 32 - bit memory location ( destination ) , add an immediate 8 - bit
;;; sign-extended value (source), and store the result in the
;;; destination.
(define-instruction "ADD"
:modes (32 64)
:operands ((memory 32) (simm 8))
:opcodes (#x83)
:opcode-extension 0
:encoding (modrm imm))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
To a 64 - bit GPR or memory location ( destination ) , add an immediate
8 - bit sign - extended value ( source ) , and store the result in the
;;; destination.
To a 64 - bit GPR ( destination ) , add an immediate 8 - bit
;;; sign-extended value (source), and store the result in the
;;; destination.
(define-instruction "ADD"
:modes (64)
:operands ((gpr 64) (simm 8))
:opcodes (#x83)
:opcode-extension 0
:encoding (modrm imm)
:rex.w t)
To a 64 - bit memory location ( destination ) , add an immediate 8 - bit
;;; sign-extended value (source), and store the result in the
;;; destination.
(define-instruction "ADD"
:modes (64)
:operands ((memory 64) (simm 8))
:opcodes (#x83)
:opcode-extension 0
:encoding (modrm imm)
:rex.w t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
To an 8 - bit GPR or memory location ( destination ) , add an immediate
8 - bit value ( source ) , and store the result in the destination .
;;;
Opcodes : 00
To an 8 - bit GPR ( destination ) , add an immediate 8 - bit value
;;; (source), and store the result in the destination.
(define-instruction "ADD"
:modes (32 64)
:operands ((gpr 8) (gpr 8))
:opcodes (#x00)
:encoding (modrm reg))
To an 8 - bit memory location ( destination ) , add an immediate 8 - bit
;;; value (source), and store the result in the destination.
(define-instruction "ADD"
:modes (32 64)
:operands ((memory 8) (gpr 8))
:opcodes (#x00)
:encoding (modrm reg)
:lock t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; To a GPR or memory location (16/32/64) (destination), add the
;;; contents of a GPR (16/32/64) (source), and store the result in the
;;; destination.
;;;
Opcodes : 01
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
To a 16 - bit GPR or memory location ( destination ) , add the contents
of a 16 - bit GPR ( source ) , and store the result in the destination .
To a 16 - bit GPR ( destination ) , add the contents of a 16 - bit GPR
;;; (source), and store the result in the destination.
(define-instruction "ADD"
:modes (32 64)
:operands ((gpr 16) (gpr 16))
:opcodes (#x01)
:encoding (modrm reg)
:operand-size-override t)
To a 16 - bit memory location ( destination ) , add the contents of a
16 - bit GPR ( source ) , and store the result in the destination .
(define-instruction "ADD"
:modes (32 64)
:operands ((memory 16) (gpr 16))
:opcodes (#x01)
:encoding (modrm reg)
:lock t
:operand-size-override t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
To a 32 - bit GPR or memory location ( destination ) , add the contents
of a 32 - bit GPR ( source ) , and store the result in the destination .
To a 32 - bit GPR ( destination ) , add the contents of a 32 - bit GPR
;;; (source), and store the result in the destination.
(define-instruction "ADD"
:modes (32 64)
:operands ((gpr 32) (gpr 32))
:opcodes (#x01)
:encoding (modrm reg))
To a 32 - bit memory location ( destination ) , add the contents of a
32 - bit GPR ( source ) , and store the result in the destination .
(define-instruction "ADD"
:modes (32 64)
:operands ((memory 32) (gpr 32))
:opcodes (#x01)
:encoding (modrm reg)
:lock t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
To a 64 - bit GPR or memory location ( destination ) , add the contents
of a 64 - bit GPR ( source ) , and store the result in the destination .
To a 64 - bit GPR ( destination ) , add the contents of a 64 - bit GPR
;;; (source), and store the result in the destination.
(define-instruction "ADD"
:modes (64)
:operands ((gpr 64) (gpr 64))
:opcodes (#x01)
:encoding (modrm reg)
:rex.w t)
To a 64 - bit memory location ( destination ) , add the contents of a
64 - bit GPR ( source ) , and store the result in the destination .
(define-instruction "ADD"
:modes (64)
:operands ((memory 64) (gpr 64))
:opcodes (#x01)
:encoding (modrm reg)
:lock t
:rex.w t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
To an 8 - bit GPR ( destination ) , add the contents of an 8 - bit GPR or
;;; memory location (source), and store the result in the destination.
;;;
Opcodes : 02
To an 8 - bit GPR ( destination ) , add the contents of an 8 - bit GPR
;;; (source), and store the result in the destination.
(define-instruction "ADD"
:modes (32 64)
:operands ((gpr 8) (gpr 8))
:opcodes (#x02)
:encoding (reg modrm))
To an 8 - bit GPR ( destination ) , add the contents of an 8 - bit memory
;;; location (source), and store the result in the destination.
(define-instruction "ADD"
:modes (32 64)
:operands ((gpr 8) (memory 8))
:opcodes (#x02)
:encoding (reg modrm))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; To a GPR (16/32/64) (destination), add the contents of a GPR or
;;; memory location (16/32/64) (source), and store the result in the
;;; destination.
;;;
Opcodes : 03
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
To a 16 - bit GPR ( destination ) , add the contents of a 16 - bit GPR or
;;; memory location (source), and store the result in the destination.
To a 16 - bit GPR ( destination ) , add the contents of a 16 - bit GPR
;;; (source), and store the result in the destination.
(define-instruction "ADD"
:modes (32 64)
:operands ((gpr 16) (gpr 16))
:opcodes (#x03)
:encoding (reg modrm)
:operand-size-override t)
To a 16 - bit GPR ( destination ) , add the contents of a 16 - bit memory
;;; location (source), and store the result in the destination.
(define-instruction "ADD"
:modes (32 64)
:operands ((gpr 16) (memory 16))
:opcodes (#x03)
:encoding (reg modrm)
:operand-size-override t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
To a 32 - bit GPR ( destination ) , add the contents of a 32 - bit GPR or
;;; memory location (source), and store the result in the destination.
To a 32 - bit GPR ( destination ) , add the contents of a 32 - bit GPR
;;; (source), and store the result in the destination.
(define-instruction "ADD"
:modes (32 64)
:operands ((gpr 32) (gpr 32))
:opcodes (#x03)
:encoding (reg modrm))
To a 32 - bit GPR ( destination ) , add the contents of a 32 - bit memory
;;; location (source), and store the result in the destination.
(define-instruction "ADD"
:modes (32 64)
:operands ((gpr 32) (memory 32))
:opcodes (#x03)
:encoding (reg modrm))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
To a 64 - bit GPR ( destination ) , add the contents of a 64 - bit GPR or
;;; memory location (source), and store the result in the destination.
To a 64 - bit GPR ( destination ) , add the contents of a 64 - bit GPR
;;; (source), and store the result in the destination.
(define-instruction "ADD"
:modes (64)
:operands ((gpr 64) (gpr 64))
:opcodes (#x03)
:encoding (reg modrm)
:rex.w t)
To a 64 - bit GPR ( destination ) , add the contents of a 64 - bit memory
;;; location (source), and store the result in the destination.
(define-instruction "ADD"
:modes (64)
:operands ((gpr 64) (memory 64))
:opcodes (#x03)
:encoding (reg modrm)
:rex.w t)
| null | https://raw.githubusercontent.com/robert-strandh/Cluster/9010412a2d2109d3eb6e607bd62cc0c482adac81/x86-instruction-database/add.lisp | lisp |
Mnemonic ADD
value (source) and store the result in the destination.
To the contents of GPR A (16/32/64) (destination), add an
destination.
value (source), and store the result in the destination.
value (source), and store the result in the destination.
To the contents of GPR RAX (destination), add an immediate
destination.
(source), and store the result in the destination.
value (source), and store the result in the destination.
To a GPR or memory location (16/32/64) (destination), add an
destination.
(source), and store the result in the destination.
value (source), and store the result in the destination.
(source), and store the result in the destination.
value (source), and store the result in the destination.
destination.
sign-extended value (source), and store the result in the
destination.
sign-extended value (source), and store the result in the
destination.
To a GPR or memory location (16/32/64) (destination), add an
in the destination.
destination.
sign-extended value (source), and store the result in the
destination.
sign-extended value (source), and store the result in the
destination.
destination.
sign-extended value (source), and store the result in the
destination.
sign-extended value (source), and store the result in the
destination.
destination.
sign-extended value (source), and store the result in the
destination.
sign-extended value (source), and store the result in the
destination.
(source), and store the result in the destination.
value (source), and store the result in the destination.
To a GPR or memory location (16/32/64) (destination), add the
contents of a GPR (16/32/64) (source), and store the result in the
destination.
(source), and store the result in the destination.
(source), and store the result in the destination.
(source), and store the result in the destination.
memory location (source), and store the result in the destination.
(source), and store the result in the destination.
location (source), and store the result in the destination.
To a GPR (16/32/64) (destination), add the contents of a GPR or
memory location (16/32/64) (source), and store the result in the
destination.
memory location (source), and store the result in the destination.
(source), and store the result in the destination.
location (source), and store the result in the destination.
memory location (source), and store the result in the destination.
(source), and store the result in the destination.
location (source), and store the result in the destination.
memory location (source), and store the result in the destination.
(source), and store the result in the destination.
location (source), and store the result in the destination. | (in-package #:cluster)
To the contents of GPR A ( destination ) , add an 8 - bit immediate
Opcodes : 04
(define-instruction "ADD"
:modes (32 64)
:operands ((gpr-a 8) (imm 8))
:opcodes (#x04)
:encoding (- imm))
immediate value ( 16/32 ) ( source ) , and store the result in the
Opcodes : 05
To the contents of GPR AX ( destination ) , add an immediate 16 - bit
(define-instruction "ADD"
:modes (32 64)
:operands ((gpr-a 16) (imm 16))
:opcodes (#x05)
:encoding (- imm)
:operand-size-override t)
To the contents of ( destination ) , add an immediate 32 - bit
(define-instruction "ADD"
:modes (32 64)
:operands ((gpr-a 32) (imm 32))
:opcodes (#x05)
:encoding (- imm))
sign - extended 32 - bit value ( source ) , and store the result in the
(define-instruction "ADD"
:modes (64)
:operands ((gpr-a 64) (simm 32))
:opcodes (#x05)
:encoding (- imm)
:rex.w t)
To an 8 - bit GPR or memory location ( destination ) , add an immediate
8 - bit value ( source ) , and store the result in the destination .
Opcodes : 80
Opcode extension : 0
To an 8 - bit GPR ( destination ) , add an immediate 8 - bit value
(define-instruction "ADD"
:modes (32 64)
:operands ((gpr 8) (imm 8))
:opcodes (#x80)
:opcode-extension 0
:encoding (modrm imm))
To an 8 - bit memory location ( destination ) , add an immediate 8 - bit
(define-instruction "ADD"
:modes (32 64)
:operands ((memory 8) (imm 8))
:opcodes (#x80)
:opcode-extension 0
:encoding (modrm imm))
immediate value ( 16/32 ) ( source ) , and store the result in the
Opcodes : 81
Opcode extension 0
To a 16 - bit GPR or memory location ( destination ) , add an immediate
16 - bit value ( source ) , and store the result in the destination .
To a 16 - bit GPR ( destination ) , add an immediate 16 - bit value
(define-instruction "ADD"
:modes (32 64)
:operands ((gpr 16) (imm 16))
:opcodes (#x81)
:opcode-extension 0
:encoding (modrm imm)
:operand-size-override t)
To a 16 - bit memory location ( destination ) , add an immediate 16 - bit
(define-instruction "ADD"
:modes (32 64)
:operands ((memory 16) (imm 16))
:opcodes (#x81)
:opcode-extension 0
:encoding (modrm imm)
:operand-size-override t)
To a 32 - bit GPR or memory location ( destination ) , add an immediate
32 - bit value ( source ) , and store the result in the destination .
To a 32 - bit GPR ( destination ) , add an immediate 32 - bit value
(define-instruction "ADD"
:modes (32 64)
:operands ((gpr 32) (imm 32))
:opcodes (#x81)
:opcode-extension 0
:encoding (modrm imm))
To a 32 - bit memory location ( destination ) , add an immediate 32 - bit
(define-instruction "ADD"
:modes (32 64)
:operands ((memory 32) (imm 32))
:opcodes (#x81)
:opcode-extension 0
:encoding (modrm imm))
To a 32 - bit GPR or memory location ( destination ) , add an immediate
32 - bit sign - extended value ( source ) , and store the result in the
To a 32 - bit GPR ( destination ) , add an immediate 32 - bit
(define-instruction "ADD"
:modes (64)
:operands ((gpr 64) (simm 32))
:opcodes (#x81)
:opcode-extension 0
:encoding (modrm imm)
:rex.w t)
To a 32 - bit memory location ( destination ) , add an immediate 32 - bit
(define-instruction "ADD"
:modes (64)
:operands ((memory 64) (simm 32))
:opcodes (#x81)
:opcode-extension 0
:encoding (modrm imm)
:rex.w t)
immediate 8 - bit sign - extended value ( source ) , and store the result
Opcodes : 83
Opcode extension : 0
To a 16 - bit GPR or memory location ( destination ) , add an immediate
8 - bit sign - extended value ( source ) , and store the result in the
To a 16 - bit GPR ( destination ) , add an immediate 8 - bit
(define-instruction "ADD"
:modes (32 64)
:operands ((gpr 16) (simm 8))
:opcodes (#x83)
:opcode-extension 0
:encoding (modrm imm)
:operand-size-override t)
To a 16 - bit memory location ( destination ) , add an immediate 8 - bit
(define-instruction "ADD"
:modes (32 64)
:operands ((memory 16) (simm 8))
:opcodes (#x83)
:opcode-extension 0
:encoding (modrm imm)
:operand-size-override t)
To a 32 - bit GPR or memory location ( destination ) , add an immediate
8 - bit sign - extended value ( source ) , and store the result in the
To a 32 - bit GPR ( destination ) , add an immediate 8 - bit
(define-instruction "ADD"
:modes (32 64)
:operands ((gpr 32) (simm 8))
:opcodes (#x83)
:opcode-extension 0
:encoding (modrm imm))
To a 32 - bit memory location ( destination ) , add an immediate 8 - bit
(define-instruction "ADD"
:modes (32 64)
:operands ((memory 32) (simm 8))
:opcodes (#x83)
:opcode-extension 0
:encoding (modrm imm))
To a 64 - bit GPR or memory location ( destination ) , add an immediate
8 - bit sign - extended value ( source ) , and store the result in the
To a 64 - bit GPR ( destination ) , add an immediate 8 - bit
(define-instruction "ADD"
:modes (64)
:operands ((gpr 64) (simm 8))
:opcodes (#x83)
:opcode-extension 0
:encoding (modrm imm)
:rex.w t)
To a 64 - bit memory location ( destination ) , add an immediate 8 - bit
(define-instruction "ADD"
:modes (64)
:operands ((memory 64) (simm 8))
:opcodes (#x83)
:opcode-extension 0
:encoding (modrm imm)
:rex.w t)
To an 8 - bit GPR or memory location ( destination ) , add an immediate
8 - bit value ( source ) , and store the result in the destination .
Opcodes : 00
To an 8 - bit GPR ( destination ) , add an immediate 8 - bit value
(define-instruction "ADD"
:modes (32 64)
:operands ((gpr 8) (gpr 8))
:opcodes (#x00)
:encoding (modrm reg))
To an 8 - bit memory location ( destination ) , add an immediate 8 - bit
(define-instruction "ADD"
:modes (32 64)
:operands ((memory 8) (gpr 8))
:opcodes (#x00)
:encoding (modrm reg)
:lock t)
Opcodes : 01
To a 16 - bit GPR or memory location ( destination ) , add the contents
of a 16 - bit GPR ( source ) , and store the result in the destination .
To a 16 - bit GPR ( destination ) , add the contents of a 16 - bit GPR
(define-instruction "ADD"
:modes (32 64)
:operands ((gpr 16) (gpr 16))
:opcodes (#x01)
:encoding (modrm reg)
:operand-size-override t)
To a 16 - bit memory location ( destination ) , add the contents of a
16 - bit GPR ( source ) , and store the result in the destination .
(define-instruction "ADD"
:modes (32 64)
:operands ((memory 16) (gpr 16))
:opcodes (#x01)
:encoding (modrm reg)
:lock t
:operand-size-override t)
To a 32 - bit GPR or memory location ( destination ) , add the contents
of a 32 - bit GPR ( source ) , and store the result in the destination .
To a 32 - bit GPR ( destination ) , add the contents of a 32 - bit GPR
(define-instruction "ADD"
:modes (32 64)
:operands ((gpr 32) (gpr 32))
:opcodes (#x01)
:encoding (modrm reg))
To a 32 - bit memory location ( destination ) , add the contents of a
32 - bit GPR ( source ) , and store the result in the destination .
(define-instruction "ADD"
:modes (32 64)
:operands ((memory 32) (gpr 32))
:opcodes (#x01)
:encoding (modrm reg)
:lock t)
To a 64 - bit GPR or memory location ( destination ) , add the contents
of a 64 - bit GPR ( source ) , and store the result in the destination .
To a 64 - bit GPR ( destination ) , add the contents of a 64 - bit GPR
(define-instruction "ADD"
:modes (64)
:operands ((gpr 64) (gpr 64))
:opcodes (#x01)
:encoding (modrm reg)
:rex.w t)
To a 64 - bit memory location ( destination ) , add the contents of a
64 - bit GPR ( source ) , and store the result in the destination .
(define-instruction "ADD"
:modes (64)
:operands ((memory 64) (gpr 64))
:opcodes (#x01)
:encoding (modrm reg)
:lock t
:rex.w t)
To an 8 - bit GPR ( destination ) , add the contents of an 8 - bit GPR or
Opcodes : 02
To an 8 - bit GPR ( destination ) , add the contents of an 8 - bit GPR
(define-instruction "ADD"
:modes (32 64)
:operands ((gpr 8) (gpr 8))
:opcodes (#x02)
:encoding (reg modrm))
To an 8 - bit GPR ( destination ) , add the contents of an 8 - bit memory
(define-instruction "ADD"
:modes (32 64)
:operands ((gpr 8) (memory 8))
:opcodes (#x02)
:encoding (reg modrm))
Opcodes : 03
To a 16 - bit GPR ( destination ) , add the contents of a 16 - bit GPR or
To a 16 - bit GPR ( destination ) , add the contents of a 16 - bit GPR
(define-instruction "ADD"
:modes (32 64)
:operands ((gpr 16) (gpr 16))
:opcodes (#x03)
:encoding (reg modrm)
:operand-size-override t)
To a 16 - bit GPR ( destination ) , add the contents of a 16 - bit memory
(define-instruction "ADD"
:modes (32 64)
:operands ((gpr 16) (memory 16))
:opcodes (#x03)
:encoding (reg modrm)
:operand-size-override t)
To a 32 - bit GPR ( destination ) , add the contents of a 32 - bit GPR or
To a 32 - bit GPR ( destination ) , add the contents of a 32 - bit GPR
(define-instruction "ADD"
:modes (32 64)
:operands ((gpr 32) (gpr 32))
:opcodes (#x03)
:encoding (reg modrm))
To a 32 - bit GPR ( destination ) , add the contents of a 32 - bit memory
(define-instruction "ADD"
:modes (32 64)
:operands ((gpr 32) (memory 32))
:opcodes (#x03)
:encoding (reg modrm))
To a 64 - bit GPR ( destination ) , add the contents of a 64 - bit GPR or
To a 64 - bit GPR ( destination ) , add the contents of a 64 - bit GPR
(define-instruction "ADD"
:modes (64)
:operands ((gpr 64) (gpr 64))
:opcodes (#x03)
:encoding (reg modrm)
:rex.w t)
To a 64 - bit GPR ( destination ) , add the contents of a 64 - bit memory
(define-instruction "ADD"
:modes (64)
:operands ((gpr 64) (memory 64))
:opcodes (#x03)
:encoding (reg modrm)
:rex.w t)
|
7d4e690a0343c07539247679be6d3ea242dc8fdd85bfc888d5fec67104f9b6a2 | discus-lang/ddc | Module.hs | {-# OPTIONS_HADDOCK hide #-}
module DDC.Core.Codec.Text.Parser.Module
(pModule)
where
import DDC.Core.Codec.Text.Parser.Type
import DDC.Core.Codec.Text.Parser.Exp
import DDC.Core.Codec.Text.Parser.Context
import DDC.Core.Codec.Text.Parser.Base
import DDC.Core.Codec.Text.Parser.ExportSpec
import DDC.Core.Codec.Text.Parser.ImportSpec
import DDC.Core.Codec.Text.Parser.DataDef
import DDC.Core.Codec.Text.Lexer.Tokens
import DDC.Core.Module
import DDC.Core.Exp.Annot
import DDC.Data.Pretty
import Data.Char
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.Text as T
import qualified DDC.Control.Parser as P
-- | Parse a core module.
pModule :: (Ord n, Pretty n)
=> Context n
-> Parser n (Module P.SourcePos n)
pModule c
= do sp <- pTokSP (KKeyword EModule)
modName <- pModuleName
Parse header declarations
heads <- P.many (pHeadDecl c modName)
let importSpecs_noArity = concat $ [specs | HeadImportSpecs specs <- heads ]
let exportSpecs = concat $ [specs | HeadExportSpecs specs <- heads ]
let dataDefsLocal = [(n, def) | HeadDataDef n def <- heads ]
let typeDefsLocal = [(n, (k, t)) | HeadTypeDef n k t <- heads ]
-- Attach arity information to import specs.
The aritity information itself comes in the ARITY pragmas ,
-- which are parsed as separate top level things.
let importArities
= Map.fromList [ (n, (iTypes, iValues, iBoxes ))
| HeadPragmaArity n iTypes iValues iBoxes <- heads ]
let attachAritySpec (ImportForeignValue n (ImportValueModule mn v t _))
= ImportForeignValue n (ImportValueModule mn v t (Map.lookup n importArities))
attachAritySpec spec = spec
let importSpecs
= map attachAritySpec importSpecs_noArity
Parse function definitions .
-- If there is a 'with' keyword then this is a standard module with bindings.
-- If not, then it is a module header, which doesn't need bindings.
(lts, isHeader)
<- P.choice
[ do pTok (KKeyword EWith)
LET;+
lts <- P.sepBy1 (pLetsSP c) (pTok (KKeyword EIn))
let lts' = concat [map (\l -> (l, sp')) ls | (ls, sp') <- lts]
return (lts', False)
, do return ([], True) ]
-- The body of the module consists of the top-level bindings wrapped
-- around a unit constructor place-holder.
let body = xLetsAnnot lts (xUnit sp)
return $ ModuleCore
{ moduleName = modName
, moduleIsHeader = isHeader
, moduleTransitiveDeps = Set.empty
, moduleExportTypes = []
, moduleExportValues = [(n, s) | ExportValue n s <- exportSpecs]
, moduleImportModules = [mn | ImportModule mn <- importSpecs]
, moduleImportTypes = [(n, s) | ImportForeignType n s <- importSpecs]
, moduleImportCaps = [(n, s) | ImportForeignCap n s <- importSpecs]
, moduleImportValues = [(n, s) | ImportForeignValue n s <- importSpecs]
, moduleImportTypeDefs = [(n, (k, t)) | ImportType n k t <- importSpecs]
, moduleImportDataDefs = [(dataDefTypeName def, def)
| ImportData def <- importSpecs]
, moduleLocalDataDefs = dataDefsLocal
, moduleLocalTypeDefs = typeDefsLocal
, moduleBody = body }
---------------------------------------------------------------------------------------------------
-- | Wrapper for a declaration that can appear in the module header.
data HeadDecl n
-- | Import specifications.
= HeadImportSpecs [ImportSpec n]
-- | Export specifications.
| HeadExportSpecs [ExportSpec n]
-- | Data type definitions.
| HeadDataDef n (DataDef n)
-- | Type equations.
| HeadTypeDef n (Kind n) (Type n)
-- | Arity pragmas.
-- Number of type parameters, value parameters, and boxes for some super.
| HeadPragmaArity n Int Int Int
-- | Parse one of the declarations that can appear in a module header.
pHeadDecl :: (Ord n, Pretty n)
=> Context n -> ModuleName -> Parser n (HeadDecl n)
pHeadDecl ctx modName
= P.choice
[ do imports <- pImportSpecs ctx modName
return $ HeadImportSpecs imports
, do exports <- pExportSpecs ctx modName
return $ HeadExportSpecs exports
, do def <- pDataDef ctx (Just modName)
return $ HeadDataDef (dataDefTypeName def) def
, do (n, k, t) <- pTypeDef ctx
return $ HeadTypeDef n k t
, do pHeadPragma ctx
]
-- | Parse a type equation.
pTypeDef :: (Ord n, Pretty n)
=> Context n -> Parser n (n, Kind n, Type n)
pTypeDef c
= do pKey EType
n <- pName
pTokSP (KOp ":")
k <- pType c
pSym SEquals
t <- pType c
pSym SSemiColon
return (n, k, t)
-- | Parse one of the pragmas that can appear in the module header.
pHeadPragma :: Context n -> Parser n (HeadDecl n)
pHeadPragma ctx
= do (txt, sp) <- pPragmaSP
case words $ T.unpack txt of
-- The type and value arity of a super.
["ARITY", name, strTypes, strValues, strBoxes]
| all isDigit strTypes
, all isDigit strValues
, all isDigit strBoxes
, Just makeLitName <- contextMakeLiteralName ctx
, Just n <- makeLitName sp (LString (T.pack name)) True
-> return $ HeadPragmaArity n
(read strTypes) (read strValues) (read strBoxes)
_ -> P.unexpected $ "pragma " ++ "{-# " ++ T.unpack txt ++ "#-}"
| null | https://raw.githubusercontent.com/discus-lang/ddc/2baa1b4e2d43b6b02135257677671a83cb7384ac/src/s1/ddc-core/DDC/Core/Codec/Text/Parser/Module.hs | haskell | # OPTIONS_HADDOCK hide #
| Parse a core module.
Attach arity information to import specs.
which are parsed as separate top level things.
If there is a 'with' keyword then this is a standard module with bindings.
If not, then it is a module header, which doesn't need bindings.
The body of the module consists of the top-level bindings wrapped
around a unit constructor place-holder.
-------------------------------------------------------------------------------------------------
| Wrapper for a declaration that can appear in the module header.
| Import specifications.
| Export specifications.
| Data type definitions.
| Type equations.
| Arity pragmas.
Number of type parameters, value parameters, and boxes for some super.
| Parse one of the declarations that can appear in a module header.
| Parse a type equation.
| Parse one of the pragmas that can appear in the module header.
The type and value arity of a super. |
module DDC.Core.Codec.Text.Parser.Module
(pModule)
where
import DDC.Core.Codec.Text.Parser.Type
import DDC.Core.Codec.Text.Parser.Exp
import DDC.Core.Codec.Text.Parser.Context
import DDC.Core.Codec.Text.Parser.Base
import DDC.Core.Codec.Text.Parser.ExportSpec
import DDC.Core.Codec.Text.Parser.ImportSpec
import DDC.Core.Codec.Text.Parser.DataDef
import DDC.Core.Codec.Text.Lexer.Tokens
import DDC.Core.Module
import DDC.Core.Exp.Annot
import DDC.Data.Pretty
import Data.Char
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.Text as T
import qualified DDC.Control.Parser as P
pModule :: (Ord n, Pretty n)
=> Context n
-> Parser n (Module P.SourcePos n)
pModule c
= do sp <- pTokSP (KKeyword EModule)
modName <- pModuleName
Parse header declarations
heads <- P.many (pHeadDecl c modName)
let importSpecs_noArity = concat $ [specs | HeadImportSpecs specs <- heads ]
let exportSpecs = concat $ [specs | HeadExportSpecs specs <- heads ]
let dataDefsLocal = [(n, def) | HeadDataDef n def <- heads ]
let typeDefsLocal = [(n, (k, t)) | HeadTypeDef n k t <- heads ]
The aritity information itself comes in the ARITY pragmas ,
let importArities
= Map.fromList [ (n, (iTypes, iValues, iBoxes ))
| HeadPragmaArity n iTypes iValues iBoxes <- heads ]
let attachAritySpec (ImportForeignValue n (ImportValueModule mn v t _))
= ImportForeignValue n (ImportValueModule mn v t (Map.lookup n importArities))
attachAritySpec spec = spec
let importSpecs
= map attachAritySpec importSpecs_noArity
Parse function definitions .
(lts, isHeader)
<- P.choice
[ do pTok (KKeyword EWith)
LET;+
lts <- P.sepBy1 (pLetsSP c) (pTok (KKeyword EIn))
let lts' = concat [map (\l -> (l, sp')) ls | (ls, sp') <- lts]
return (lts', False)
, do return ([], True) ]
let body = xLetsAnnot lts (xUnit sp)
return $ ModuleCore
{ moduleName = modName
, moduleIsHeader = isHeader
, moduleTransitiveDeps = Set.empty
, moduleExportTypes = []
, moduleExportValues = [(n, s) | ExportValue n s <- exportSpecs]
, moduleImportModules = [mn | ImportModule mn <- importSpecs]
, moduleImportTypes = [(n, s) | ImportForeignType n s <- importSpecs]
, moduleImportCaps = [(n, s) | ImportForeignCap n s <- importSpecs]
, moduleImportValues = [(n, s) | ImportForeignValue n s <- importSpecs]
, moduleImportTypeDefs = [(n, (k, t)) | ImportType n k t <- importSpecs]
, moduleImportDataDefs = [(dataDefTypeName def, def)
| ImportData def <- importSpecs]
, moduleLocalDataDefs = dataDefsLocal
, moduleLocalTypeDefs = typeDefsLocal
, moduleBody = body }
data HeadDecl n
= HeadImportSpecs [ImportSpec n]
| HeadExportSpecs [ExportSpec n]
| HeadDataDef n (DataDef n)
| HeadTypeDef n (Kind n) (Type n)
| HeadPragmaArity n Int Int Int
pHeadDecl :: (Ord n, Pretty n)
=> Context n -> ModuleName -> Parser n (HeadDecl n)
pHeadDecl ctx modName
= P.choice
[ do imports <- pImportSpecs ctx modName
return $ HeadImportSpecs imports
, do exports <- pExportSpecs ctx modName
return $ HeadExportSpecs exports
, do def <- pDataDef ctx (Just modName)
return $ HeadDataDef (dataDefTypeName def) def
, do (n, k, t) <- pTypeDef ctx
return $ HeadTypeDef n k t
, do pHeadPragma ctx
]
pTypeDef :: (Ord n, Pretty n)
=> Context n -> Parser n (n, Kind n, Type n)
pTypeDef c
= do pKey EType
n <- pName
pTokSP (KOp ":")
k <- pType c
pSym SEquals
t <- pType c
pSym SSemiColon
return (n, k, t)
pHeadPragma :: Context n -> Parser n (HeadDecl n)
pHeadPragma ctx
= do (txt, sp) <- pPragmaSP
case words $ T.unpack txt of
["ARITY", name, strTypes, strValues, strBoxes]
| all isDigit strTypes
, all isDigit strValues
, all isDigit strBoxes
, Just makeLitName <- contextMakeLiteralName ctx
, Just n <- makeLitName sp (LString (T.pack name)) True
-> return $ HeadPragmaArity n
(read strTypes) (read strValues) (read strBoxes)
_ -> P.unexpected $ "pragma " ++ "{-# " ++ T.unpack txt ++ "#-}"
|
d8b9b712b340a15079541bc16005d21383d7a6875a85b7cba31c19a3263e82f5 | PEZ/rich4clojure | problem_147.clj | (ns rich4clojure.easy.problem-147
(:require [hyperfiddle.rcf :refer [tests]]))
= 's Trapezoid =
By 4Clojure user : narvius
;; Difficulty: Easy
;; Tags: [seqs]
;;
;; Write a function that, for any given input vector of
;; numbers, returns an infinite lazy sequence of vectors,
;; where each next one is constructed from the previous
following the rules used in 's Triangle . For
example , for [ 3 1 2 ] , the next row is [ 3 4 3 2 ] .
;;
;; Beware of arithmetic overflow! In clojure (since
version 1.3 in 2011 ) , if you use an arithmetic operator
like + and the result is too large to fit into a 64 - bit
;; integer, an exception is thrown. You can use +' to
indicate that you would rather overflow into Clojure 's
;; slower, arbitrary-precision bigint.
(def __ :tests-will-fail)
(comment
)
(tests
(second (__ [2 3 2])) := [2 5 5 2]
(take 5 (__ [1])) := [[1] [1 1] [1 2 1] [1 3 3 1] [1 4 6 4 1]]
(take 2 (__ [3 1 2])) := [[3 1 2] [3 4 3 2]]
(take 100 (__ [2 4 2])) := (rest (take 101 (__ [2 2]))))
;; Share your solution, and/or check how others did it:
;; | null | https://raw.githubusercontent.com/PEZ/rich4clojure/2ccfac041840e9b1550f0a69b9becbdb03f9525b/src/rich4clojure/easy/problem_147.clj | clojure | Difficulty: Easy
Tags: [seqs]
Write a function that, for any given input vector of
numbers, returns an infinite lazy sequence of vectors,
where each next one is constructed from the previous
Beware of arithmetic overflow! In clojure (since
integer, an exception is thrown. You can use +' to
slower, arbitrary-precision bigint.
Share your solution, and/or check how others did it:
| (ns rich4clojure.easy.problem-147
(:require [hyperfiddle.rcf :refer [tests]]))
= 's Trapezoid =
By 4Clojure user : narvius
following the rules used in 's Triangle . For
example , for [ 3 1 2 ] , the next row is [ 3 4 3 2 ] .
version 1.3 in 2011 ) , if you use an arithmetic operator
like + and the result is too large to fit into a 64 - bit
indicate that you would rather overflow into Clojure 's
(def __ :tests-will-fail)
(comment
)
(tests
(second (__ [2 3 2])) := [2 5 5 2]
(take 5 (__ [1])) := [[1] [1 1] [1 2 1] [1 3 3 1] [1 4 6 4 1]]
(take 2 (__ [3 1 2])) := [[3 1 2] [3 4 3 2]]
(take 100 (__ [2 4 2])) := (rest (take 101 (__ [2 2]))))
|
ff5e48f0a0c9095569f55f307541cce692a2687d5fa3f853add174c0b4ba69a9 | tisnik/clojure-examples | core_test.clj | (ns matrix2.core-test
(:require [clojure.test :refer :all]
[matrix2.core :refer :all]))
(deftest a-test
(testing "FIXME, I fail."
(is (= 0 1))))
| null | https://raw.githubusercontent.com/tisnik/clojure-examples/984af4a3e20d994b4f4989678ee1330e409fdae3/matrix2/test/matrix2/core_test.clj | clojure | (ns matrix2.core-test
(:require [clojure.test :refer :all]
[matrix2.core :refer :all]))
(deftest a-test
(testing "FIXME, I fail."
(is (= 0 1))))
| |
a21b97ff46af879009e4aac2a9ad97acffcafc457b5ee37afb447ca17c556351 | stylewarning/formulador | canvas.lisp | ;;;; canvas.lisp
;;;;
Copyright ( c ) 2013 - 2018
;;;;
;;;; A simple notion of a "canvas" on which we can draw formulas.
(in-package #:formulador)
(defstruct (canvas (:constructor %make-canvas)
(:predicate canvasp)
(:print-function (lambda (canvas stream depth)
(declare (ignore depth))
(print-canvas canvas stream))))
data
region-associations)
(defun make-canvas (width height)
"Make a new canvas of width WIDTH and height HEIGHT."
(%make-canvas :data (make-array (list height width)
:element-type 'character
:initial-element #\Space)))
(defun canvas-dimensions (canvas)
"Return the dimensions of the canvas (WIDTH HEIGHT)."
(reverse (array-dimensions (canvas-data canvas))))
(defun canvas-ref (canvas x y)
"Obtain the character (X, Y) in the canvas CANVAS."
(aref (canvas-data canvas) y x))
(defvar *error-on-out-of-bounds-write* nil
"Error when attempting to write out of bounds on a canvas.")
(defvar *warn-on-out-of-bounds-write* t
"Warn when attempting to write out of bounds on a canvas.")
(defun canvas-set (canvas x y new-data)
"Set the character at (X, Y) in the canvas CANVAS to the value NEW-DATA."
(cond
((array-in-bounds-p (canvas-data canvas) y x)
(setf (aref (canvas-data canvas) y x)
new-data))
(t
(cond
(*error-on-out-of-bounds-write*
(cerror "Ignore write."
"Attempting to write ~S out of bounds at ~
position (~D, ~D) for canvas ~A."
new-data
x
y
canvas))
(*warn-on-out-of-bounds-write*
(warn "Attempted to write ~S out of bounds at ~
position (~D, ~D) for canvas ~A."
new-data
x
y
canvas))))))
(defsetf canvas-ref canvas-set)
(defun add-association (canvas region &optional object)
"Add the region REGION to the canvas CANVAS, associating it with the object OBJECT."
(push (cons region object)
(canvas-region-associations canvas)))
(defun find-associations (canvas x y)
"Find the regions which contain the point (X, Y) along with their associated objects."
(loop :for ra :in (canvas-region-associations canvas)
:when (in-region-p (car ra) x y)
:collect ra))
(defun objects-at-point (canvas x y)
"Compute all of the objects at the point (X, Y) in the canvas CANVAS."
(mapcar #'cdr (find-associations canvas x y)))
(defun print-canvas (canvas &optional (stream *standard-output*))
(print-unreadable-object (canvas stream :type t)
(terpri stream)
(destructuring-bind (width height)
(canvas-dimensions canvas)
(loop :initially (write-char #\+ stream)
:repeat width
:do (write-char #\- stream)
:finally (progn
(write-char #\+ stream)
(terpri stream)))
(dotimes (y height)
(write-char #\| stream)
(dotimes (x width)
(write-char (canvas-ref canvas x y) stream))
(write-char #\| stream)
(terpri stream))
(loop :initially (write-char #\+ stream)
:repeat width
:do (write-char #\- stream)
:finally (progn
(write-char #\+ stream)
(terpri stream))))
(format stream "with ~D defined region~:p"
(length (canvas-region-associations canvas)))))
| null | https://raw.githubusercontent.com/stylewarning/formulador/7f3528da88adf8e3debdc5db564077ccd06ef2c5/canvas.lisp | lisp | canvas.lisp
A simple notion of a "canvas" on which we can draw formulas. | Copyright ( c ) 2013 - 2018
(in-package #:formulador)
(defstruct (canvas (:constructor %make-canvas)
(:predicate canvasp)
(:print-function (lambda (canvas stream depth)
(declare (ignore depth))
(print-canvas canvas stream))))
data
region-associations)
(defun make-canvas (width height)
"Make a new canvas of width WIDTH and height HEIGHT."
(%make-canvas :data (make-array (list height width)
:element-type 'character
:initial-element #\Space)))
(defun canvas-dimensions (canvas)
"Return the dimensions of the canvas (WIDTH HEIGHT)."
(reverse (array-dimensions (canvas-data canvas))))
(defun canvas-ref (canvas x y)
"Obtain the character (X, Y) in the canvas CANVAS."
(aref (canvas-data canvas) y x))
(defvar *error-on-out-of-bounds-write* nil
"Error when attempting to write out of bounds on a canvas.")
(defvar *warn-on-out-of-bounds-write* t
"Warn when attempting to write out of bounds on a canvas.")
(defun canvas-set (canvas x y new-data)
"Set the character at (X, Y) in the canvas CANVAS to the value NEW-DATA."
(cond
((array-in-bounds-p (canvas-data canvas) y x)
(setf (aref (canvas-data canvas) y x)
new-data))
(t
(cond
(*error-on-out-of-bounds-write*
(cerror "Ignore write."
"Attempting to write ~S out of bounds at ~
position (~D, ~D) for canvas ~A."
new-data
x
y
canvas))
(*warn-on-out-of-bounds-write*
(warn "Attempted to write ~S out of bounds at ~
position (~D, ~D) for canvas ~A."
new-data
x
y
canvas))))))
(defsetf canvas-ref canvas-set)
(defun add-association (canvas region &optional object)
"Add the region REGION to the canvas CANVAS, associating it with the object OBJECT."
(push (cons region object)
(canvas-region-associations canvas)))
(defun find-associations (canvas x y)
"Find the regions which contain the point (X, Y) along with their associated objects."
(loop :for ra :in (canvas-region-associations canvas)
:when (in-region-p (car ra) x y)
:collect ra))
(defun objects-at-point (canvas x y)
"Compute all of the objects at the point (X, Y) in the canvas CANVAS."
(mapcar #'cdr (find-associations canvas x y)))
(defun print-canvas (canvas &optional (stream *standard-output*))
(print-unreadable-object (canvas stream :type t)
(terpri stream)
(destructuring-bind (width height)
(canvas-dimensions canvas)
(loop :initially (write-char #\+ stream)
:repeat width
:do (write-char #\- stream)
:finally (progn
(write-char #\+ stream)
(terpri stream)))
(dotimes (y height)
(write-char #\| stream)
(dotimes (x width)
(write-char (canvas-ref canvas x y) stream))
(write-char #\| stream)
(terpri stream))
(loop :initially (write-char #\+ stream)
:repeat width
:do (write-char #\- stream)
:finally (progn
(write-char #\+ stream)
(terpri stream))))
(format stream "with ~D defined region~:p"
(length (canvas-region-associations canvas)))))
|
4793db606cbf50e133d5fcab7eb329f5db881fd2e8c99c8c7f74e596f03a06aa | dparis/gen-phzr | revolute_constraint.cljs | (ns phzr.physics.p2.revolute-constraint
(:require [phzr.impl.utils.core :refer [clj->phaser phaser->clj]]
[phzr.impl.extend :as ex]
[cljsjs.phaser]))
(defn ->RevoluteConstraint
"Connects two bodies at given offset points, letting them rotate relative to each other around this point.
The pivot points are given in world (pixel) coordinates.
Parameters:
* world (Phaser.Physics.P2) - A reference to the P2 World.
* body-a (p2.Body) - First connected body.
* pivot-a (Float32Array) - The point relative to the center of mass of bodyA which bodyA is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32].
* body-b (p2.Body) - Second connected body.
* pivot-b (Float32Array) - The point relative to the center of mass of bodyB which bodyB is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32].
* max-force (number) {optional} - The maximum force that should be applied to constrain the bodies.
* world-pivot (Float32Array) {optional} - A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value."
([world body-a pivot-a body-b pivot-b]
(js/Phaser.Physics.P2.RevoluteConstraint. (clj->phaser world)
(clj->phaser body-a)
(clj->phaser pivot-a)
(clj->phaser body-b)
(clj->phaser pivot-b)))
([world body-a pivot-a body-b pivot-b max-force]
(js/Phaser.Physics.P2.RevoluteConstraint. (clj->phaser world)
(clj->phaser body-a)
(clj->phaser pivot-a)
(clj->phaser body-b)
(clj->phaser pivot-b)
(clj->phaser max-force)))
([world body-a pivot-a body-b pivot-b max-force world-pivot]
(js/Phaser.Physics.P2.RevoluteConstraint. (clj->phaser world)
(clj->phaser body-a)
(clj->phaser pivot-a)
(clj->phaser body-b)
(clj->phaser pivot-b)
(clj->phaser max-force)
(clj->phaser world-pivot))))
| null | https://raw.githubusercontent.com/dparis/gen-phzr/e4c7b272e225ac343718dc15fc84f5f0dce68023/out/physics/p2/revolute_constraint.cljs | clojure | (ns phzr.physics.p2.revolute-constraint
(:require [phzr.impl.utils.core :refer [clj->phaser phaser->clj]]
[phzr.impl.extend :as ex]
[cljsjs.phaser]))
(defn ->RevoluteConstraint
"Connects two bodies at given offset points, letting them rotate relative to each other around this point.
The pivot points are given in world (pixel) coordinates.
Parameters:
* world (Phaser.Physics.P2) - A reference to the P2 World.
* body-a (p2.Body) - First connected body.
* pivot-a (Float32Array) - The point relative to the center of mass of bodyA which bodyA is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32].
* body-b (p2.Body) - Second connected body.
* pivot-b (Float32Array) - The point relative to the center of mass of bodyB which bodyB is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32].
* max-force (number) {optional} - The maximum force that should be applied to constrain the bodies.
* world-pivot (Float32Array) {optional} - A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value."
([world body-a pivot-a body-b pivot-b]
(js/Phaser.Physics.P2.RevoluteConstraint. (clj->phaser world)
(clj->phaser body-a)
(clj->phaser pivot-a)
(clj->phaser body-b)
(clj->phaser pivot-b)))
([world body-a pivot-a body-b pivot-b max-force]
(js/Phaser.Physics.P2.RevoluteConstraint. (clj->phaser world)
(clj->phaser body-a)
(clj->phaser pivot-a)
(clj->phaser body-b)
(clj->phaser pivot-b)
(clj->phaser max-force)))
([world body-a pivot-a body-b pivot-b max-force world-pivot]
(js/Phaser.Physics.P2.RevoluteConstraint. (clj->phaser world)
(clj->phaser body-a)
(clj->phaser pivot-a)
(clj->phaser body-b)
(clj->phaser pivot-b)
(clj->phaser max-force)
(clj->phaser world-pivot))))
| |
29a3bee9b0a14f6821cba6150d12ee9cdb7f4e1de047c1488d3714bbc7175495 | composewell/streamly | Common.hs | # OPTIONS_GHC -Wno - deprecations #
-- |
Module : Streamly . Test . Prelude . Common
Copyright : ( c ) 2020 Composewell Technologies
--
-- License : BSD-3-Clause
-- Maintainer :
-- Stability : experimental
Portability : GHC
module Streamly.Test.Prelude.Common
(
-- * Construction operations
constructWithRepeat
, constructWithRepeatM
, constructWithReplicate
, constructWithReplicateM
, constructWithIntFromThenTo
, constructWithDoubleFromThenTo
, constructWithIterate
, constructWithIterateM
, constructWithEnumerate
, constructWithEnumerateTo
, constructWithFromIndices
, constructWithFromIndicesM
, constructWithFromList
, constructWithFromListM
, constructWithUnfoldr
, constructWithCons
, constructWithConsM
, constructWithFromPure
, constructWithFromEffect
, simpleOps
-- * Applicative operations
, applicativeOps
, applicativeOps1
-- * Elimination operations
, eliminationOpsOrdered
, eliminationOpsWord8
, eliminationOps
-- * Functor operations
, functorOps
-- * Monoid operations
, monoidOps
, loops
, bindAndComposeSimpleOps
, bindAndComposeHierarchyOps
, nestTwoStreams
, nestTwoStreamsApp
, composeAndComposeSimpleSerially
, composeAndComposeSimpleAheadly
, composeAndComposeSimpleWSerially
-- * Semigroup operations
, semigroupOps
, parallelCheck
-- * Transformation operations
, transformCombineOpsOrdered
, transformCombineOpsCommon
, toListFL
* Monad operations
, monadBind
, monadThen
-- * Zip operations
, zipApplicative
, zipMonadic
, zipAsyncApplicative
, zipAsyncMonadic
-- * Exception operations
, exceptionOps
* MonadThrow operations
, composeWithMonadThrow
-- * Cleanup tests
, checkCleanup
-- * Adhoc tests
, takeCombined
-- * Default values
, maxTestCount
, maxStreamLen
-- * Helper operations
, folded
, makeCommonOps
, makeOps
, mapOps
, sortEq
) where
import Control.Applicative (ZipList(..), liftA2)
import Control.Exception (Exception, try)
import Control.Concurrent (threadDelay)
import Control.Monad (replicateM)
#ifdef DEVBUILD
import Control.Monad (when)
#endif
import Control.Monad.Catch (throwM, MonadThrow)
import Data.IORef ( IORef, atomicModifyIORef', modifyIORef', newIORef
, readIORef, writeIORef)
import Data.List
( delete
, deleteBy
, elemIndex
, elemIndices
, find
, findIndex
, findIndices
, foldl'
, foldl1'
, insert
, intersperse
, isPrefixOf
, isSubsequenceOf
, maximumBy
, minimumBy
, scanl'
, sort
, stripPrefix
, unfoldr
)
import Data.Maybe (mapMaybe)
import GHC.Word (Word8)
import System.Mem (performMajorGC)
import Test.Hspec.QuickCheck
import Test.Hspec
import Test.QuickCheck (Property, choose, forAll, listOf, withMaxSuccess)
import Test.QuickCheck.Monadic (assert, monadicIO, run)
import Streamly.Prelude (SerialT, IsStream, (.:), nil, (|&), fromSerial)
#ifndef COVERAGE_BUILD
import Streamly.Prelude (avgRate, rate, maxBuffer, maxThreads)
#endif
import qualified Streamly.Prelude as S
import qualified Streamly.Data.Fold as FL
import qualified Streamly.Internal.Data.Stream.IsStream as S
import qualified Streamly.Internal.Data.Stream.IsStream.Common as IS
import qualified Streamly.Internal.Data.Unfold as UF
import qualified Data.Map.Strict as Map
import Streamly.Test.Common
maxStreamLen :: Int
maxStreamLen = 1000
-- Coverage build takes too long with default number of tests
maxTestCount :: Int
#ifdef DEVBUILD
maxTestCount = 100
#else
maxTestCount = 10
#endif
singleton :: IsStream t => a -> t m a
singleton a = a .: nil
sortEq :: Ord a => [a] -> [a] -> Bool
sortEq a b = sort a == sort b
-------------------------------------------------------------------------------
-- Construction operations
-------------------------------------------------------------------------------
constructWithLen
:: (Show a, Eq a)
=> (Int -> t IO a)
-> (Int -> [a])
-> (t IO a -> SerialT IO a)
-> Word8
-> Property
constructWithLen mkStream mkList op len = withMaxSuccess maxTestCount $
monadicIO $ do
stream <- run $ (S.toList . op) (mkStream (fromIntegral len))
let list = mkList (fromIntegral len)
listEquals (==) stream list
constructWithLenM
:: (Int -> t IO Int)
-> (Int -> IO [Int])
-> (t IO Int -> SerialT IO Int)
-> Word8
-> Property
constructWithLenM mkStream mkList op len = withMaxSuccess maxTestCount $
monadicIO $ do
stream <- run $ (S.toList . op) (mkStream (fromIntegral len))
list <- run $ mkList (fromIntegral len)
listEquals (==) stream list
constructWithReplicate, constructWithReplicateM, constructWithIntFromThenTo
:: IsStream t
=> (t IO Int -> SerialT IO Int)
-> Word8
-> Property
constructWithReplicateM = constructWithLenM stream list
where list = flip replicateM (return 1 :: IO Int)
stream = flip S.replicateM (return 1 :: IO Int)
constructWithReplicate = constructWithLen stream list
where list = flip replicate (1 :: Int)
stream = flip S.replicate (1 :: Int)
constructWithIntFromThenTo op l =
forAll (choose (minBound, maxBound)) $ \from ->
forAll (choose (minBound, maxBound)) $ \next ->
forAll (choose (minBound, maxBound)) $ \to ->
let list len = take len [from,next..to]
stream len = S.take len $ S.enumerateFromThenTo from next to
in constructWithLen stream list op l
constructWithRepeat, constructWithRepeatM
:: IsStream t
=> (t IO Int -> SerialT IO Int)
-> Word8
-> Property
constructWithRepeat = constructWithLenM stream list
where
stream n = S.take n $ S.repeat 1
list n = return $ replicate n 1
constructWithRepeatM = constructWithLenM stream list
where
stream n = S.take n $ S.repeatM (return 1)
list n = return $ replicate n 1
-- XXX try very small steps close to 0
constructWithDoubleFromThenTo
:: IsStream t
=> (t IO Double -> SerialT IO Double)
-> Word8
-> Property
constructWithDoubleFromThenTo op l =
forAll (choose (-9007199254740999,9007199254740999)) $ \from ->
forAll (choose (-9007199254740999,9007199254740999)) $ \next ->
forAll (choose (-9007199254740999,9007199254740999)) $ \to ->
let list len = take len [from,next..to]
stream len = S.take len $ S.enumerateFromThenTo from next to
in constructWithLen stream list op l
constructWithIterate ::
IsStream t => (t IO Int -> SerialT IO Int) -> Word8 -> Property
constructWithIterate op len =
withMaxSuccess maxTestCount $
monadicIO $ do
stream <-
run $
(S.toList . op . S.take (fromIntegral len))
(S.iterate (+ 1) (0 :: Int))
let list = take (fromIntegral len) (iterate (+ 1) 0)
listEquals (==) stream list
constructWithIterateM ::
IsStream t => (t IO Int -> SerialT IO Int) -> Word8 -> Property
constructWithIterateM op len =
withMaxSuccess maxTestCount $
monadicIO $ do
mvl <- run (newIORef [] :: IO (IORef [Int]))
let addM mv x y = modifyIORef' mv (++ [y + x]) >> return (y + x)
list = take (fromIntegral len) (iterate (+ 1) 0)
run $
S.drain . op $
S.take (fromIntegral len) $
S.iterateM (addM mvl 1) (addM mvl 0 0 :: IO Int)
streamEffect <- run $ readIORef mvl
listEquals (==) streamEffect list
constructWithFromIndices ::
IsStream t => (t IO Int -> SerialT IO Int) -> Word8 -> Property
constructWithFromIndices op len =
withMaxSuccess maxTestCount $
monadicIO $ do
stream <-
run $ (S.toList . op . S.take (fromIntegral len)) (S.fromIndices id)
let list = take (fromIntegral len) (iterate (+ 1) 0)
listEquals (==) stream list
constructWithFromIndicesM ::
IsStream t => (t IO Int -> SerialT IO Int) -> Word8 -> Property
constructWithFromIndicesM op len =
withMaxSuccess maxTestCount $
monadicIO $ do
mvl <- run (newIORef [] :: IO (IORef [Int]))
let addIndex mv i = modifyIORef' mv (++ [i]) >> return i
list = take (fromIntegral len) (iterate (+ 1) 0)
run $
S.drain . op $
S.take (fromIntegral len) $ S.fromIndicesM (addIndex mvl)
streamEffect <- run $ readIORef mvl
listEquals (==) streamEffect list
constructWithCons ::
IsStream t
=> (Int -> t IO Int -> t IO Int)
-> (t IO Int -> SerialT IO Int)
-> Word8
-> Property
constructWithCons cons op len =
withMaxSuccess maxTestCount $
monadicIO $ do
strm <-
run
$ S.toList . op . S.take (fromIntegral len)
$ foldr cons S.nil (repeat 0)
let list = replicate (fromIntegral len) 0
listEquals (==) strm list
constructWithConsM ::
IsStream t
=> (IO Int -> t IO Int -> t IO Int)
-> ([Int] -> [Int])
-> (t IO Int -> SerialT IO Int)
-> Word8
-> Property
constructWithConsM consM listT op len =
withMaxSuccess maxTestCount $
monadicIO $ do
strm <-
run $
S.toList . op . S.take (fromIntegral len) $
foldr consM S.nil (repeat (return 0))
let list = replicate (fromIntegral len) 0
listEquals (==) (listT strm) list
constructWithEnumerate ::
IsStream t
=> ([Int] -> [Int])
-> (t IO Int -> SerialT IO Int)
-> Word8
-> Property
constructWithEnumerate listT op len =
withMaxSuccess maxTestCount $
monadicIO $ do
strm <- run $ S.toList . op . S.take (fromIntegral len) $ S.enumerate
let list = take (fromIntegral len) (enumFrom minBound)
listEquals (==) (listT strm) list
constructWithEnumerateTo ::
IsStream t
=> ([Int] -> [Int])
-> (t IO Int -> SerialT IO Int)
-> Word8
-> Property
constructWithEnumerateTo listT op len =
withMaxSuccess maxTestCount $
monadicIO $ do
It takes forever to enumerate from to len , so
-- instead we just do till len elements
strm <- run $ S.toList . op $ S.enumerateTo (minBound + fromIntegral len)
let list = enumFromTo minBound (minBound + fromIntegral len)
listEquals (==) (listT strm) list
constructWithFromList ::
IsStream t
=> ([Int] -> [Int])
-> (t IO Int -> SerialT IO Int)
-> Word8
-> Property
constructWithFromList listT op len =
withMaxSuccess maxTestCount $
monadicIO $ do
strm <- run $ S.toList . op . S.fromList $ [0 .. fromIntegral len]
let list = [0 .. fromIntegral len]
listEquals (==) (listT strm) list
constructWithFromListM ::
IsStream t
=> ([Int] -> [Int])
-> (t IO Int -> SerialT IO Int)
-> Word8
-> Property
constructWithFromListM listT op len =
withMaxSuccess maxTestCount $
monadicIO $ do
strm <-
run $
S.toList . op . S.fromListM . fmap pure $ [0 .. fromIntegral len]
let list = [0 .. fromIntegral len]
listEquals (==) (listT strm) list
constructWithUnfoldr ::
IsStream t
=> ([Int] -> [Int])
-> (t IO Int -> SerialT IO Int)
-> Word8
-> Property
constructWithUnfoldr listT op len =
withMaxSuccess maxTestCount $
monadicIO $ do
strm <- run $ S.toList . op $ S.unfoldr unfoldStep 0
let list = unfoldr unfoldStep 0
listEquals (==) (listT strm) list
where
unfoldStep seed =
if seed > fromIntegral len
then Nothing
else Just (seed, seed + 1)
constructWithFromPure ::
(IsStream t, Monoid (t IO Int))
=> ([Int] -> [Int])
-> (t IO Int -> SerialT IO Int)
-> Word8
-> Property
constructWithFromPure listT op len =
withMaxSuccess maxTestCount $
monadicIO $ do
strm <-
run
$ S.toList . op . S.take (fromIntegral len)
$ foldMap S.fromPure (repeat 0)
let list = replicate (fromIntegral len) 0
listEquals (==) (listT strm) list
constructWithFromEffect ::
(IsStream t, Monoid (t IO Int))
=> ([Int] -> [Int])
-> (t IO Int -> SerialT IO Int)
-> Word8
-> Property
constructWithFromEffect listT op len =
withMaxSuccess maxTestCount $
monadicIO $ do
strm <-
run
$ S.toList . op . S.take (fromIntegral len)
$ foldMap S.fromEffect (repeat (return 0))
let list = replicate (fromIntegral len) 0
listEquals (==) (listT strm) list
simpleProps ::
(Int -> t IO Int)
-> (t IO Int -> SerialT IO Int)
-> Int
-> Property
simpleProps constr op a = monadicIO $ do
strm <- run $ S.toList . op . constr $ a
listEquals (==) strm [a]
simpleOps :: IsStream t => (t IO Int -> SerialT IO Int) -> Spec
simpleOps op = do
prop "fromPure a = a" $ simpleProps S.fromPure op
prop "fromEffect a = a" $ simpleProps (S.fromEffect . return) op
-------------------------------------------------------------------------------
-- Applicative operations
-------------------------------------------------------------------------------
applicativeOps
:: (Applicative (t IO), Semigroup (t IO Int))
=> ([Int] -> t IO Int)
-> String
-> ([(Int, Int)] -> [(Int, Int)] -> Bool)
-> (t IO (Int, Int) -> SerialT IO (Int, Int))
-> Spec
applicativeOps constr desc eq t = do
prop (desc <> " <*>") $
transformFromList2
constr
eq
(\a b -> (,) <$> a <*> b)
(\a b -> t ((,) <$> a <*> b))
prop (desc <> " liftA2") $
transformFromList2 constr eq (liftA2 (,)) (\a b -> t $ liftA2 (,) a b)
prop (desc <> " Apply - composed first argument") $
sort <$>
(S.toList . t) ((,) <$> (pure 1 <> pure 2) <*> pure 3) `shouldReturn`
[(1, 3), (2, 3)]
prop (desc <> " Apply - composed second argument") $
sort <$>
(S.toList . t) (pure ((,) 1) <*> (pure 2 <> pure 3)) `shouldReturn`
[(1, 2), (1, 3)]
XXX we can combine this with applicativeOps by making the type sufficiently
-- polymorphic.
applicativeOps1
:: Applicative (t IO)
=> ([Int] -> t IO Int)
-> String
-> ([Int] -> [Int] -> Bool)
-> (t IO Int -> SerialT IO Int)
-> Spec
applicativeOps1 constr desc eq t = do
prop (desc <> " *>") $
transformFromList2 constr eq (*>) (\a b -> t (a *> b))
prop (desc <> " <*") $
transformFromList2 constr eq (<*) (\a b -> t (a <* b))
transformFromList2
:: (Eq c, Show c)
=> ([a] -> t IO a)
-> ([c] -> [c] -> Bool)
-> ([a] -> [a] -> [c])
-> (t IO a -> t IO a -> SerialT IO c)
-> ([a], [a])
-> Property
transformFromList2 constr eq listOp op (a, b) =
withMaxSuccess maxTestCount $
monadicIO $ do
stream <- run (S.toList $ op (constr a) (constr b))
let list = listOp a b
listEquals eq stream list
-------------------------------------------------------------------------------
-- Elimination operations
-------------------------------------------------------------------------------
eliminateOp
:: (Show a, Eq a)
=> ([s] -> t IO s)
-> ([s] -> a)
-> (t IO s -> IO a)
-> [s]
-> Property
eliminateOp constr listOp op a =
monadicIO $ do
stream <- run $ op (constr a)
let list = listOp a
equals (==) stream list
wrapMaybe :: ([a1] -> a2) -> [a1] -> Maybe a2
wrapMaybe f x = if null x then Nothing else Just (f x)
wrapOutOfBounds :: ([a1] -> Int -> a2) -> Int -> [a1] -> Maybe a2
wrapOutOfBounds f i x | null x = Nothing
| i >= length x = Nothing
| otherwise = Just (f x i)
wrapThe :: Eq a => [a] -> Maybe a
wrapThe (x:xs)
| all (x ==) xs = Just x
| otherwise = Nothing
wrapThe [] = Nothing
-- This is the reference uniq implementation to compare uniq against,
-- we can use uniq from vector package, but for now this should
-- suffice.
referenceUniq :: Eq a => [a] -> [a]
referenceUniq = go
where
go [] = []
go (x:[]) = [x]
go (x:y:xs)
| x == y = go (x : xs)
| otherwise = x : go (y : xs)
eliminationOps
:: ([Int] -> t IO Int)
-> String
-> (t IO Int -> SerialT IO Int)
-> Spec
eliminationOps constr desc t = do
-- Elimination
prop (desc <> " null") $ eliminateOp constr null $ S.null . t
prop (desc <> " foldl'") $
eliminateOp constr (foldl' (+) 0) $ S.foldl' (+) 0 . t
prop (desc <> " foldl1'") $
eliminateOp constr (wrapMaybe $ foldl1' (+)) $ S.foldl1' (+) . t
#ifdef DEVBUILD
prop (desc <> " foldr1") $
eliminateOp constr (wrapMaybe $ foldr1 (+)) $ S.foldr1 (+) . t
#endif
prop (desc <> " all") $ eliminateOp constr (all even) $ S.all even . t
prop (desc <> " any") $ eliminateOp constr (any even) $ S.any even . t
prop (desc <> " and") $ eliminateOp constr (and . fmap (> 0)) $
(S.and . S.map (> 0)) . t
prop (desc <> " or") $ eliminateOp constr (or . fmap (> 0)) $
(S.or . S.map (> 0)) . t
prop (desc <> " length") $ eliminateOp constr length $ S.length . t
prop (desc <> " sum") $ eliminateOp constr sum $ S.sum . t
prop (desc <> " product") $ eliminateOp constr product $ S.product . t
prop (desc <> " mapM_ sumIORef") $
eliminateOp constr sum $
(\strm -> do
ioRef <- newIORef 0
let sumInRef a = modifyIORef' ioRef (a +)
S.mapM_ sumInRef strm
readIORef ioRef) .
t
prop (desc <> "trace sumIORef") $
eliminateOp constr sum $
(\strm -> do
ioRef <- newIORef 0
let sumInRef a = modifyIORef' ioRef (a +)
S.drain $ S.trace sumInRef strm
readIORef ioRef) .
t
prop (desc <> " maximum") $
eliminateOp constr (wrapMaybe maximum) $ S.maximum . t
prop (desc <> " minimum") $
eliminateOp constr (wrapMaybe minimum) $ S.minimum . t
prop (desc <> " maximumBy compare") $
eliminateOp constr (wrapMaybe maximum) $
S.maximumBy compare . t
prop (desc <> " maximumBy flip compare") $
eliminateOp constr (wrapMaybe $ maximumBy $ flip compare) $
S.maximumBy (flip compare) . t
prop (desc <> " minimumBy compare") $
eliminateOp constr (wrapMaybe minimum) $
S.minimumBy compare . t
prop (desc <> " minimumBy flip compare") $
eliminateOp constr (wrapMaybe $ minimumBy $ flip compare) $
S.minimumBy (flip compare) . t
prop (desc <> " findIndex") $
eliminateOp constr (findIndex odd) $ S.findIndex odd . t
prop (desc <> " elemIndex") $
eliminateOp constr (elemIndex 3) $ S.elemIndex 3 . t
prop (desc <> " !! 5") $
eliminateOp constr (wrapOutOfBounds (!!) 5) $ (S.!! 5) . t
prop (desc <> " !! 4") $
eliminateOp constr (wrapOutOfBounds (!!) 0) $ (S.!! 0) . t
prop (desc <> " find") $ eliminateOp constr (find even) $ S.find even . t
prop (desc <> " findM") $ eliminateOp constr (find even) $ S.findM (return . even) . t
prop (desc <> " lookup") $
eliminateOp constr (lookup 3 . flip zip [1..]) $
S.lookup 3 . S.zipWith (\a b -> (b, a)) (S.fromList [(1::Int)..]) . t
prop (desc <> " the") $ eliminateOp constr wrapThe $ S.the . t
-- Multi-stream eliminations
-- XXX Write better tests for substreams.
prop (desc <> " eqBy (==) t t") $
eliminateOp constr (\s -> s == s) $ (\s -> S.eqBy (==) s s) . t
prop (desc <> " cmpBy (==) t t") $
eliminateOp constr (\s -> compare s s) $ (\s -> S.cmpBy compare s s) . t
prop (desc <> " isPrefixOf 10") $ eliminateOp constr (isPrefixOf [1..10]) $
S.isPrefixOf (S.fromList [(1::Int)..10]) . t
prop (desc <> " isSubsequenceOf 10") $
eliminateOp constr (isSubsequenceOf $ filter even [1..10]) $
S.isSubsequenceOf (S.fromList $ filter even [(1::Int)..10]) . t
prop (desc <> " stripPrefix 10") $ eliminateOp constr (stripPrefix [1..10]) $
(\s -> s >>= maybe (return Nothing) (fmap Just . S.toList)) .
S.stripPrefix (S.fromList [(1::Int)..10]) . t
-- head/tail/last may depend on the order in case of parallel streams
-- so we test these only for serial streams.
eliminationOpsOrdered
:: ([Int] -> t IO Int)
-> String
-> (t IO Int -> SerialT IO Int)
-> Spec
eliminationOpsOrdered constr desc t = do
prop (desc <> " head") $ eliminateOp constr (wrapMaybe head) $ S.head . t
prop (desc <> " tail") $ eliminateOp constr (wrapMaybe tail) $ \x -> do
r <- S.tail (t x)
case r of
Nothing -> return Nothing
Just s -> Just <$> S.toList s
prop (desc <> " last") $ eliminateOp constr (wrapMaybe last) $ S.last . t
prop (desc <> " init") $ eliminateOp constr (wrapMaybe init) $ \x -> do
r <- S.init (t x)
case r of
Nothing -> return Nothing
Just s -> Just <$> S.toList s
elemOp
:: ([Word8] -> t IO Word8)
-> (t IO Word8 -> SerialT IO Word8)
-> (Word8 -> SerialT IO Word8 -> IO Bool)
-> (Word8 -> [Word8] -> Bool)
-> (Word8, [Word8])
-> Property
elemOp constr op streamOp listOp (x, xs) =
monadicIO $ do
stream <- run $ (streamOp x . op) (constr xs)
let list = listOp x xs
equals (==) stream list
eliminationOpsWord8
:: ([Word8] -> t IO Word8)
-> String
-> (t IO Word8 -> SerialT IO Word8)
-> Spec
eliminationOpsWord8 constr desc t = do
prop (desc <> " elem") $ elemOp constr t S.elem elem
prop (desc <> " notElem") $ elemOp constr t S.notElem notElem
-------------------------------------------------------------------------------
-- Functor operations
-------------------------------------------------------------------------------
functorOps
:: (Functor (t IO), Semigroup (t IO Int))
=> ([Int] -> t IO Int)
-> String
-> ([Int] -> [Int] -> Bool)
-> (t IO Int -> SerialT IO Int)
-> Spec
functorOps constr desc eq t = do
prop (desc <> " id") $ transformFromList constr eq id t
prop (desc <> " fmap (+1)") $
transformFromList constr eq (fmap (+ 1)) $ t . fmap (+ 1)
prop (desc <> " fmap on composed (<>)") $
sort <$>
(S.toList . t) (fmap (+ 1) (constr [1] <> constr [2])) `shouldReturn`
([2, 3] :: [Int])
transformFromList
:: (Eq b, Show b) =>
([a] -> t IO a)
-> ([b] -> [b] -> Bool)
-> ([a] -> [b])
-> (t IO a -> SerialT IO b)
-> [a]
-> Property
transformFromList constr eq listOp op a =
monadicIO $ do
stream <- run ((S.toList . op) (constr a))
let list = listOp a
listEquals eq stream list
------------------------------------------------------------------------------
-- Monoid operations
------------------------------------------------------------------------------
monoidOps
:: (IsStream t, Semigroup (t IO Int))
=> String
-> t IO Int
-> ([Int] -> [Int] -> Bool)
-> (t IO Int -> SerialT IO Int)
-> Spec
monoidOps desc z eq t = do
-- XXX these should get covered by the property tests
prop (desc <> " Compose mempty, mempty") $ spec (z <> z) []
prop (desc <> " Compose empty at the beginning") $ spec (z <> singleton 1) [1]
prop (desc <> " Compose empty at the end") $ spec (singleton 1 <> z) [1]
prop (desc <> " Compose two") $ spec (singleton 0 <> singleton 1) [0, 1]
prop (desc <> " Compose many") $
spec (S.concatForFoldableWith (<>) [1 .. 100] singleton) [1 .. 100]
-- These are not covered by the property tests
prop (desc <> " Compose three - empty in the middle") $
spec (singleton 0 <> z <> singleton 1) [0, 1]
prop (desc <> " Compose left associated") $
spec
(((singleton 0 <> singleton 1) <> singleton 2) <> singleton 3)
[0, 1, 2, 3]
prop (desc <> " Compose right associated") $
spec
(singleton 0 <> (singleton 1 <> (singleton 2 <> singleton 3)))
[0, 1, 2, 3]
prop (desc <> " Compose hierarchical (multiple levels)") $
spec
(((singleton 0 <> singleton 1) <> (singleton 2 <> singleton 3)) <>
((singleton 4 <> singleton 5) <> (singleton 6 <> singleton 7)))
[0 .. 7]
where
tl = S.toList . t
spec s list =
monadicIO $ do
stream <- run $ tl s
listEquals eq stream list
---------------------------------------------------------------------------
-- Monoidal composition recursion loops
---------------------------------------------------------------------------
loops
:: (IsStream t, Semigroup (t IO Int), Monad (t IO))
=> (t IO Int -> t IO Int)
-> ([Int] -> [Int])
-> ([Int] -> [Int])
-> Spec
loops t tsrt hsrt = do
it "Tail recursive loop" $ (tsrt <$> (S.toList . S.adapt) (loopTail 0))
`shouldReturn` [0..3]
it "Head recursive loop" $ (hsrt <$> (S.toList . S.adapt) (loopHead 0))
`shouldReturn` [0..3]
where
loopHead x = do
-- this print line is important for the test (causes a bind)
S.fromEffect $ putStrLn "LoopHead..."
t $ (if x < 3 then loopHead (x + 1) else nil) <> return x
loopTail x = do
-- this print line is important for the test (causes a bind)
S.fromEffect $ putStrLn "LoopTail..."
t $ return x <> (if x < 3 then loopTail (x + 1) else nil)
---------------------------------------------------------------------------
-- Bind and monoidal composition combinations
---------------------------------------------------------------------------
bindAndComposeSimpleOps
:: IsStream t
=> String
-> ([Int] -> [Int] -> Bool)
-> (t IO Int -> SerialT IO Int)
-> Spec
bindAndComposeSimpleOps desc eq t = do
bindAndComposeSimple
("Bind and compose " <> desc <> " Stream serially/")
S.fromSerial
bindAndComposeSimple
("Bind and compose " <> desc <> " Stream wSerially/")
S.fromWSerial
bindAndComposeSimple
("Bind and compose " <> desc <> " Stream aheadly/")
S.fromAhead
bindAndComposeSimple
("Bind and compose " <> desc <> " Stream asyncly/")
S.fromAsync
bindAndComposeSimple
("Bind and compose " <> desc <> " Stream wAsyncly/")
S.fromWAsync
bindAndComposeSimple
("Bind and compose " <> desc <> " Stream parallely/")
S.fromParallel
where
bindAndComposeSimple
:: (IsStream t2, Semigroup (t2 IO Int), Monad (t2 IO))
=> String
-> (t2 IO Int -> t2 IO Int)
-> Spec
bindAndComposeSimple idesc t2 = do
-- XXX need a bind in the body of forEachWith instead of a simple return
prop (idesc <> " Compose many (right fold) with bind") $ \list ->
monadicIO $ do
stream <-
run $
(S.toList . t)
(S.adapt . t2 $ S.concatForFoldableWith (<>) list return)
listEquals eq stream list
prop (idesc <> " Compose many (left fold) with bind") $ \list ->
monadicIO $ do
let forL xs k = foldl (<>) nil $ fmap k xs
stream <-
run $ (S.toList . t) (S.adapt . t2 $ forL list return)
listEquals eq stream list
---------------------------------------------------------------------------
-- Bind and monoidal composition combinations
---------------------------------------------------------------------------
bindAndComposeHierarchyOps ::
(IsStream t, Monad (t IO))
=> String
-> (t IO Int -> SerialT IO Int)
-> Spec
bindAndComposeHierarchyOps desc t1 = do
let fldldesc = "Bind and compose foldl, " <> desc <> " Stream "
fldrdesc = "Bind and compose foldr, " <> desc <> " Stream "
bindAndComposeHierarchy
(fldldesc <> "serially") S.fromSerial fldl
bindAndComposeHierarchy
(fldrdesc <> "serially") S.fromSerial fldr
bindAndComposeHierarchy
(fldldesc <> "wSerially") S.fromWSerial fldl
bindAndComposeHierarchy
(fldrdesc <> "wSerially") S.fromWSerial fldr
bindAndComposeHierarchy
(fldldesc <> "aheadly") S.fromAhead fldl
bindAndComposeHierarchy
(fldrdesc <> "aheadly") S.fromAhead fldr
bindAndComposeHierarchy
(fldldesc <> "asyncly") S.fromAsync fldl
bindAndComposeHierarchy
(fldrdesc <> "asyncly") S.fromAsync fldr
bindAndComposeHierarchy
(fldldesc <> "wAsyncly") S.fromWAsync fldl
bindAndComposeHierarchy
(fldrdesc <> "wAsyncly") S.fromWAsync fldr
bindAndComposeHierarchy
(fldldesc <> "parallely") S.fromParallel fldl
bindAndComposeHierarchy
(fldrdesc <> "parallely") S.fromParallel fldr
where
bindAndComposeHierarchy
:: (IsStream t2, Monad (t2 IO))
=> String
-> (t2 IO Int -> t2 IO Int)
-> ([t2 IO Int] -> t2 IO Int)
-> Spec
bindAndComposeHierarchy specdesc t2 g =
describe specdesc $
it "Bind and compose nested" $
(sort <$> (S.toList . t1) bindComposeNested)
`shouldReturn` (sort (
[12, 18]
<> replicate 3 13
<> replicate 3 17
<> replicate 6 14
<> replicate 6 16
<> replicate 7 15) :: [Int])
where
-- bindComposeNested :: WAsyncT IO Int
bindComposeNested =
let c1 = tripleCompose (return 1) (return 2) (return 3)
c2 = tripleCompose (return 4) (return 5) (return 6)
c3 = tripleCompose (return 7) (return 8) (return 9)
b = tripleBind c1 c2 c3
it seems to be causing a huge space leak in hspec so disabling this for now
-- c = tripleCompose b b b
-- m = tripleBind c c c
-- in m
in b
tripleCompose a b c = S.adapt . t2 $ g [a, b, c]
tripleBind mx my mz =
mx >>= \x -> my
>>= \y -> mz
>>= \z -> return (x + y + z)
fldr, fldl :: (IsStream t, Semigroup (t IO Int))
=> [t IO Int] -> t IO Int
fldr = foldr (<>) nil
fldl = foldl (<>) nil
Nest two lists using different styles of product compositions
nestTwoStreams
:: (IsStream t, Semigroup (t IO Int), Monad (t IO))
=> String
-> ([Int] -> [Int])
-> ([Int] -> [Int])
-> (t IO Int -> SerialT IO Int)
-> Spec
nestTwoStreams desc streamListT listT t =
it ("Nests two streams using monadic " <> desc <> " composition") $ do
let s1 = S.concatMapFoldableWith (<>) return [1..4]
s2 = S.concatMapFoldableWith (<>) return [5..8]
r <- (S.toList . t) $ do
x <- s1
y <- s2
return $ x + y
streamListT r `shouldBe` listT [6,7,8,9,7,8,9,10,8,9,10,11,9,10,11,12]
nestTwoStreamsApp
:: (IsStream t, Semigroup (t IO Int), Monad (t IO))
=> String
-> ([Int] -> [Int])
-> ([Int] -> [Int])
-> (t IO Int -> SerialT IO Int)
-> Spec
nestTwoStreamsApp desc streamListT listT t =
it ("Nests two streams using applicative " <> desc <> " composition") $ do
let s1 = S.concatMapFoldableWith (<>) return [1..4]
s2 = S.concatMapFoldableWith (<>) return [5..8]
r = (S.toList . t) ((+) <$> s1 <*> s2)
streamListT <$> r
`shouldReturn` listT [6,7,8,9,7,8,9,10,8,9,10,11,9,10,11,12]
-- TBD need more such combinations to be tested.
composeAndComposeSimple
:: ( IsStream t1, Semigroup (t1 IO Int)
, IsStream t2, Monoid (t2 IO Int), Monad (t2 IO)
)
=> (t1 IO Int -> SerialT IO Int)
-> (t2 IO Int -> t2 IO Int)
-> [[Int]] -> Spec
composeAndComposeSimple t1 t2 answer = do
let rfold = S.adapt . t2 . S.concatMapFoldableWith (<>) return
it "Compose right associated outer expr, right folded inner" $
(S.toList . t1) (rfold [1,2,3] <> (rfold [4,5,6] <> rfold [7,8,9]))
`shouldReturn` head answer
it "Compose left associated outer expr, right folded inner" $
(S.toList . t1) ((rfold [1,2,3] <> rfold [4,5,6]) <> rfold [7,8,9])
`shouldReturn` (answer !! 1)
let lfold xs = S.adapt $ t2 $ foldl (<>) mempty $ fmap return xs
it "Compose right associated outer expr, left folded inner" $
(S.toList . t1) (lfold [1,2,3] <> (lfold [4,5,6] <> lfold [7,8,9]))
`shouldReturn` (answer !! 2)
it "Compose left associated outer expr, left folded inner" $
(S.toList . t1) ((lfold [1,2,3] <> lfold [4,5,6]) <> lfold [7,8,9])
`shouldReturn` (answer !! 3)
composeAndComposeSimpleSerially
:: (IsStream t, Semigroup (t IO Int))
=> String
-> [[Int]]
-> (t IO Int -> SerialT IO Int)
-> Spec
composeAndComposeSimpleSerially desc answer t = do
describe (desc <> " and Serial <>") $ composeAndComposeSimple t S.fromSerial answer
composeAndComposeSimpleAheadly
:: (IsStream t, Semigroup (t IO Int))
=> String
-> [[Int]]
-> (t IO Int -> SerialT IO Int)
-> Spec
composeAndComposeSimpleAheadly desc answer t = do
describe (desc <> " and Ahead <>") $ composeAndComposeSimple t S.fromAhead answer
composeAndComposeSimpleWSerially
:: (IsStream t, Semigroup (t IO Int))
=> String
-> [[Int]]
-> (t IO Int -> SerialT IO Int)
-> Spec
composeAndComposeSimpleWSerially desc answer t = do
describe (desc <> " and WSerial <>") $ composeAndComposeSimple t S.fromWSerial answer
-------------------------------------------------------------------------------
-- Semigroup operations
-------------------------------------------------------------------------------
foldFromList
:: ([Int] -> t IO Int)
-> (t IO Int -> SerialT IO Int)
-> ([Int] -> [Int] -> Bool)
-> [Int]
-> Property
foldFromList constr op eq = transformFromList constr eq id op
-- XXX concatenate streams of multiple elements rather than single elements
semigroupOps
:: (IsStream t, Monoid (t IO Int))
=> String
-> ([Int] -> [Int] -> Bool)
-> (t IO Int -> SerialT IO Int)
-> Spec
semigroupOps desc eq t = do
prop (desc <> " <>") $ foldFromList (S.concatMapFoldableWith (<>) singleton) t eq
prop (desc <> " mappend") $ foldFromList (S.concatMapFoldableWith mappend singleton) t eq
-------------------------------------------------------------------------------
-- Transformation operations
-------------------------------------------------------------------------------
transformCombineFromList
:: Semigroup (t IO Int)
=> ([Int] -> t IO Int)
-> ([Int] -> [Int] -> Bool)
-> ([Int] -> [Int])
-> (t IO Int -> SerialT IO Int)
-> (t IO Int -> t IO Int)
-> [Int]
-> [Int]
-> [Int]
-> Property
transformCombineFromList constr eq listOp t op a b c =
withMaxSuccess maxTestCount $
monadicIO $ do
stream <- run ((S.toList . t) $
constr a <> op (constr b <> constr c))
let list = a <> listOp (b <> c)
listEquals eq stream list
takeEndBy :: Property
takeEndBy = forAll (listOf (chooseInt (0, maxStreamLen))) $ \lst -> monadicIO $ do
let (s1, s3) = span (<= 200) lst
let s4 = [head s3 | not (null s3)]
s2 <- run $ S.toList $ IS.takeEndBy (> 200) $ S.fromList lst
assert $ s1 ++ s4 == s2
XXX add tests for MonadReader and MonadError etc . In case an SVar is
-- accidentally passed through them.
--
This tests transform ops along with detecting illegal sharing of SVar across
-- conurrent streams. These tests work for all stream types whereas
-- transformCombineOpsOrdered work only for ordered stream types i.e. excluding
-- the Async type.
transformCombineOpsCommon
:: (IsStream t, Semigroup (t IO Int) , Functor (t IO))
=> ([Int] -> t IO Int)
-> String
-> ([Int] -> [Int] -> Bool)
-> (t IO Int -> SerialT IO Int)
-> Spec
transformCombineOpsCommon constr desc eq t = do
let transform = transformCombineFromList constr eq
-- Filtering
prop (desc <> " filter False") $
transform (filter (const False)) t (S.filter (const False))
prop (desc <> " filter True") $
transform (filter (const True)) t (S.filter (const True))
prop (desc <> " filter even") $
transform (filter even) t (S.filter even)
prop (desc <> " filterM False") $
transform (filter (const False)) t (S.filterM (const $ return False))
prop (desc <> " filterM True") $
transform (filter (const True)) t (S.filterM (const $ return True))
prop (desc <> " filterM even") $
transform (filter even) t (S.filterM (return . even))
prop (desc <> " take maxBound") $
transform (take maxBound) t (S.take maxBound)
prop (desc <> " take 0") $ transform (take 0) t (S.take 0)
prop (desc <> " takeWhile True") $
transform (takeWhile (const True)) t (S.takeWhile (const True))
prop (desc <> " takeWhile False") $
transform (takeWhile (const False)) t (S.takeWhile (const False))
prop (desc <> " takeWhileM True") $
transform (takeWhile (const True)) t (S.takeWhileM (const $ return True))
prop (desc <> " takeWhileM False") $
transform (takeWhile (const False)) t (S.takeWhileM (const $ return False))
prop "takeEndBy" takeEndBy
prop (desc <> " drop maxBound") $
transform (drop maxBound) t (S.drop maxBound)
prop (desc <> " drop 0") $ transform (drop 0) t (S.drop 0)
prop (desc <> " dropWhile True") $
transform (dropWhile (const True)) t (S.dropWhile (const True))
prop (desc <> " dropWhile False") $
transform (dropWhile (const False)) t (S.dropWhile (const False))
prop (desc <> " dropWhileM True") $
transform (dropWhile (const True)) t (S.dropWhileM (const $ return True))
prop (desc <> " dropWhileM False") $
transform (dropWhile (const False)) t (S.dropWhileM (const $ return False))
prop (desc <> " deleteBy (<=) maxBound") $
transform (deleteBy (<=) maxBound) t (S.deleteBy (<=) maxBound)
prop (desc <> " deleteBy (==) 4") $
transform (delete 4) t (S.deleteBy (==) 4)
-- transformation
prop (desc <> " mapM (+1)") $
transform (fmap (+1)) t (S.mapM (\x -> return (x + 1)))
prop (desc <> " scanl'") $ transform (scanl' (const id) 0) t
(S.scanl' (const id) 0)
prop (desc <> " postscanl'") $ transform (tail . scanl' (const id) 0) t
(S.postscanl' (const id) 0)
prop (desc <> " scanlM'") $ transform (scanl' (const id) 0) t
(S.scanlM' (\_ a -> return a) (return 0))
prop (desc <> " postscanlM'") $ transform (tail . scanl' (const id) 0) t
(S.postscanlM' (\_ a -> return a) (return 0))
prop (desc <> " scanl1'") $ transform (scanl1 (const id)) t
(S.scanl1' (const id))
prop (desc <> " scanl1M'") $ transform (scanl1 (const id)) t
(S.scanl1M' (\_ a -> return a))
let f x = if odd x then Just (x + 100) else Nothing
prop (desc <> " mapMaybe") $ transform (mapMaybe f) t (S.mapMaybe f)
prop (desc <> " mapMaybeM") $
transform (mapMaybe f) t (S.mapMaybeM (return . f))
-- tap
prop (desc <> " tap FL.sum . map (+1)") $ \a b ->
withMaxSuccess maxTestCount $
monadicIO $ do
cref <- run $ newIORef 0
let fldstp _ e = modifyIORef' cref (e +)
sumfoldinref = FL.foldlM' fldstp (return ())
op = S.tap sumfoldinref . S.mapM (\x -> return (x+1))
listOp = fmap (+1)
stream <- run ((S.toList . t) $ op (constr a <> constr b))
let list = listOp (a <> b)
ssum <- run $ readIORef cref
assert (sum list == ssum)
listEquals eq stream list
-- reordering
prop (desc <> " reverse") $ transform reverse t S.reverse
prop (desc <> " reverse'") $ transform reverse t S.reverse'
-- inserting
prop (desc <> " intersperseM") $
forAll (choose (minBound, maxBound)) $ \n ->
transform (intersperse n) t (S.intersperseM $ return n)
prop (desc <> " intersperse") $
forAll (choose (minBound, maxBound)) $ \n ->
transform (intersperse n) t (S.intersperse n)
prop (desc <> " insertBy 0") $
forAll (choose (minBound, maxBound)) $ \n ->
transform (insert n) t (S.insertBy compare n)
-- multi-stream
prop (desc <> " concatMap") $
forAll (choose (0, 100)) $ \n ->
transform (concatMap (const [1..n]))
t (S.concatMap (const (S.fromList [1..n])))
prop (desc <> " concatMapM") $
forAll (choose (0, 100)) $ \n ->
transform (concatMap (const [1..n]))
t (S.concatMapM (const (return $ S.fromList [1..n])))
prop (desc <> " unfoldMany") $
forAll (choose (0, 100)) $ \n ->
transform (concatMap (const [1..n]))
t (S.unfoldMany (UF.lmap (const undefined)
$ UF.both [1..n] UF.fromList))
toListFL :: Monad m => FL.Fold m a [a]
toListFL = FL.toList
-- transformation tests that can only work reliably for ordered streams i.e.
Serial , Ahead and Zip . For example if we use " take 1 " on an async stream , it
-- might yield a different result every time.
transformCombineOpsOrdered
:: (IsStream t, Semigroup (t IO Int))
=> ([Int] -> t IO Int)
-> String
-> ([Int] -> [Int] -> Bool)
-> (t IO Int -> SerialT IO Int)
-> Spec
transformCombineOpsOrdered constr desc eq t = do
let transform = transformCombineFromList constr eq
-- Filtering
prop (desc <> " take 1") $ transform (take 1) t (S.take 1)
#ifdef DEVBUILD
prop (desc <> " take 2") $ transform (take 2) t (S.take 2)
prop (desc <> " take 3") $ transform (take 3) t (S.take 3)
prop (desc <> " take 4") $ transform (take 4) t (S.take 4)
prop (desc <> " take 5") $ transform (take 5) t (S.take 5)
#endif
prop (desc <> " take 10") $ transform (take 10) t (S.take 10)
prop (desc <> " takeWhile > 0") $
transform (takeWhile (> 0)) t (S.takeWhile (> 0))
prop (desc <> " takeWhileM > 0") $
transform (takeWhile (> 0)) t (S.takeWhileM (return . (> 0)))
prop (desc <> " drop 1") $ transform (drop 1) t (S.drop 1)
prop (desc <> " drop 10") $ transform (drop 10) t (S.drop 10)
prop (desc <> " dropWhile > 0") $
transform (dropWhile (> 0)) t (S.dropWhile (> 0))
prop (desc <> " dropWhileM > 0") $
transform (dropWhile (> 0)) t (S.dropWhileM (return . (> 0)))
prop (desc <> " scan") $ transform (scanl' (+) 0) t (S.scanl' (+) 0)
prop (desc <> " uniq") $ transform referenceUniq t S.uniq
prop (desc <> " deleteBy (<=) 0") $
transform (deleteBy (<=) 0) t (S.deleteBy (<=) 0)
prop (desc <> " findIndices") $
transform (findIndices odd) t (S.findIndices odd)
prop (desc <> " findIndices . filter") $
transform (findIndices odd . filter odd)
t
(S.findIndices odd . S.filter odd)
prop (desc <> " elemIndices") $
transform (elemIndices 0) t (S.elemIndices 0)
XXX this does not fail when the SVar is shared , need to fix .
prop (desc <> " concurrent application") $
transform (fmap (+1)) t (|& S.map (+1))
-------------------------------------------------------------------------------
Monad operations
-------------------------------------------------------------------------------
monadThen
:: Monad (t IO)
=> ([Int] -> t IO Int)
-> ([Int] -> [Int] -> Bool)
-> (t IO Int -> SerialT IO Int)
-> ([Int], [Int])
-> Property
monadThen constr eq t (a, b) = withMaxSuccess maxTestCount $ monadicIO $ do
stream <- run ((S.toList . t) (constr a >> constr b))
let list = a >> b
listEquals eq stream list
monadBind
:: Monad (t IO)
=> ([Int] -> t IO Int)
-> ([Int] -> [Int] -> Bool)
-> (t IO Int -> SerialT IO Int)
-> ([Int], [Int])
-> Property
monadBind constr eq t (a, b) = withMaxSuccess maxTestCount $
monadicIO $ do
stream <-
run
((S.toList . t)
(constr a >>= \x -> (+ x) <$> constr b))
let list = a >>= \x -> (+ x) <$> b
listEquals eq stream list
-------------------------------------------------------------------------------
-- Zip operations
-------------------------------------------------------------------------------
zipApplicative
:: (IsStream t, Applicative (t IO))
=> ([Int] -> t IO Int)
-> ([(Int, Int)] -> [(Int, Int)] -> Bool)
-> (t IO (Int, Int) -> SerialT IO (Int, Int))
-> ([Int], [Int])
-> Property
zipApplicative constr eq t (a, b) = withMaxSuccess maxTestCount $
monadicIO $ do
stream1 <- run ((S.toList . t) ((,) <$> constr a <*> constr b))
stream2 <- run ((S.toList . t) (pure (,) <*> constr a <*> constr b))
stream3 <- run ((S.toList . t) (S.zipWith (,) (constr a) (constr b)))
let list = getZipList $ (,) <$> ZipList a <*> ZipList b
listEquals eq stream1 list
listEquals eq stream2 list
listEquals eq stream3 list
zipMonadic
:: IsStream t
=> ([Int] -> t IO Int)
-> ([(Int, Int)] -> [(Int, Int)] -> Bool)
-> (t IO (Int, Int) -> SerialT IO (Int, Int))
-> ([Int], [Int])
-> Property
zipMonadic constr eq t (a, b) = withMaxSuccess maxTestCount $
monadicIO $ do
stream1 <-
run
((S.toList . t)
(S.zipWithM (curry return) (constr a) (constr b)))
let list = getZipList $ (,) <$> ZipList a <*> ZipList b
listEquals eq stream1 list
zipAsyncMonadic
:: IsStream t
=> ([Int] -> t IO Int)
-> ([(Int, Int)] -> [(Int, Int)] -> Bool)
-> (t IO (Int, Int) -> SerialT IO (Int, Int))
-> ([Int], [Int])
-> Property
zipAsyncMonadic constr eq t (a, b) = withMaxSuccess maxTestCount $
monadicIO $ do
stream1 <-
run
((S.toList . t)
(S.zipWithM (curry return) (constr a) (constr b)))
stream2 <-
run
((S.toList . t)
(S.zipAsyncWithM (curry return) (constr a) (constr b)))
let list = getZipList $ (,) <$> ZipList a <*> ZipList b
listEquals eq stream1 list
listEquals eq stream2 list
zipAsyncApplicative
:: IsStream t
=> ([Int] -> t IO Int)
-> ([(Int, Int)] -> [(Int, Int)] -> Bool)
-> (t IO (Int, Int) -> SerialT IO (Int, Int))
-> ([Int], [Int])
-> Property
zipAsyncApplicative constr eq t (a, b) = withMaxSuccess maxTestCount $
monadicIO $ do
stream <-
run
((S.toList . t)
(S.zipAsyncWith (,) (constr a) (constr b)))
let list = getZipList $ (,) <$> ZipList a <*> ZipList b
listEquals eq stream list
---------------------------------------------------------------------------
-- Semigroup/Monoidal Composition strict ordering checks
---------------------------------------------------------------------------
parallelCheck :: (IsStream t, Monad (t IO))
=> (t IO Int -> SerialT IO Int)
-> (t IO Int -> t IO Int -> t IO Int)
-> Spec
parallelCheck t f = do
it "Parallel ordering left associated" $
(S.toList . t) (((event 4 `f` event 3) `f` event 2) `f` event 1)
`shouldReturn` [1..4]
it "Parallel ordering right associated" $
(S.toList . t) (event 4 `f` (event 3 `f` (event 2 `f` event 1)))
`shouldReturn` [1..4]
where event n = S.fromEffect (threadDelay (n * 200000)) >> return n
-------------------------------------------------------------------------------
Exception ops
-------------------------------------------------------------------------------
beforeProp :: IsStream t => (t IO Int -> SerialT IO Int) -> [Int] -> Property
beforeProp t vec =
withMaxSuccess maxTestCount $
monadicIO $ do
ioRef <- run $ newIORef []
run
$ S.drain . t
$ S.before (writeIORef ioRef [0])
$ S.mapM (\a -> do atomicModifyIORef' ioRef (\xs -> (xs ++ [a], ()))
return a)
$ S.fromList vec
refValue <- run $ readIORef ioRef
listEquals (==) (head refValue : sort (tail refValue)) (0:sort vec)
afterProp :: IsStream t => (t IO Int -> SerialT IO Int) -> [Int] -> Property
afterProp t vec =
withMaxSuccess maxTestCount $
monadicIO $ do
ioRef <- run $ newIORef []
run
$ S.drain . t
$ S.after (modifyIORef' ioRef (0:))
$ S.mapM (\a -> do atomicModifyIORef' ioRef (\xs -> (a:xs, ()))
return a)
$ S.fromList vec
refValue <- run $ readIORef ioRef
listEquals (==) (head refValue : sort (tail refValue)) (0:sort vec)
bracketProp :: IsStream t => (t IO Int -> SerialT IO Int) -> [Int] -> Property
bracketProp t vec =
withMaxSuccess maxTestCount $
monadicIO $ do
ioRef <- run $ newIORef (0 :: Int)
run $
S.drain . t $
S.bracket
(return ioRef)
(`writeIORef` 1)
(\ioref ->
S.mapM
(\a -> writeIORef ioref 2 >> return a)
(S.fromList vec))
refValue <- run $ readIORef ioRef
assert $ refValue == 1
#ifdef DEVBUILD
bracketPartialStreamProp ::
(IsStream t) => (t IO Int -> SerialT IO Int) -> [Int] -> Property
bracketPartialStreamProp t vec =
forAll (choose (0, length vec)) $ \len -> do
withMaxSuccess maxTestCount $
monadicIO $ do
ioRef <- run $ newIORef (0 :: Int)
run $
S.drain . t $
S.take len $
S.bracket
(writeIORef ioRef 1 >> return ioRef)
(`writeIORef` 3)
(\ioref ->
S.mapM
(\a -> writeIORef ioref 2 >> return a)
(S.fromList vec))
run $ do
performMajorGC
threadDelay 1000000
refValue <- run $ readIORef ioRef
when (refValue /= 0 && refValue /= 3) $
error $ "refValue == " ++ show refValue
#endif
bracketExceptionProp ::
(IsStream t, MonadThrow (t IO), Semigroup (t IO Int))
=> (t IO Int -> SerialT IO Int)
-> Property
bracketExceptionProp t =
withMaxSuccess maxTestCount $
monadicIO $ do
ioRef <- run $ newIORef (0 :: Int)
res <-
run $
try . S.drain . t $
S.bracket
(return ioRef)
(`writeIORef` 1)
(const $ throwM (ExampleException "E") <> S.nil)
assert $ res == Left (ExampleException "E")
refValue <- run $ readIORef ioRef
assert $ refValue == 1
finallyProp :: (IsStream t) => (t IO Int -> SerialT IO Int) -> [Int] -> Property
finallyProp t vec =
withMaxSuccess maxTestCount $
monadicIO $ do
ioRef <- run $ newIORef (0 :: Int)
run $
S.drain . t $
S.finally
(writeIORef ioRef 1)
(S.mapM (\a -> writeIORef ioRef 2 >> return a) (S.fromList vec))
refValue <- run $ readIORef ioRef
assert $ refValue == 1
retry :: Spec
retry = do
ref <- runIO $ newIORef (0 :: Int)
res <- runIO $ S.toList (S.retry emap handler (stream1 ref))
refVal <- runIO $ readIORef ref
spec res refVal
where
emap = Map.singleton (ExampleException "E") 10
stream1 ref =
S.fromListM
[ return 1
, return 2
, atomicModifyIORef' ref (\a -> (a + 1, ()))
>> throwM (ExampleException "E")
>> return 3
, return 4
]
stream2 = S.fromList [5, 6, 7 :: Int]
handler = const stream2
expectedRes = [1, 2, 5, 6, 7]
expectedRefVal = 11
spec res refVal = do
it "Runs the exception handler properly" $ res `shouldBe` expectedRes
it "Runs retires the exception correctly"
$ refVal `shouldBe` expectedRefVal
#ifdef DEVBUILD
finallyPartialStreamProp ::
(IsStream t) => (t IO Int -> SerialT IO Int) -> [Int] -> Property
finallyPartialStreamProp t vec =
forAll (choose (0, length vec)) $ \len -> do
withMaxSuccess maxTestCount $
monadicIO $ do
ioRef <- run $ newIORef (0 :: Int)
run $
S.drain . t $
S.take len $
S.finally
(writeIORef ioRef 2)
(S.mapM
(\a -> writeIORef ioRef 1 >> return a)
(S.fromList vec))
run $ do
performMajorGC
threadDelay 100000
refValue <- run $ readIORef ioRef
when (refValue /= 0 && refValue /= 2) $
error $ "refValue == " ++ show refValue
#endif
finallyExceptionProp ::
(IsStream t, MonadThrow (t IO), Semigroup (t IO Int))
=> (t IO Int -> SerialT IO Int)
-> Property
finallyExceptionProp t =
withMaxSuccess maxTestCount $
monadicIO $ do
ioRef <- run $ newIORef (0 :: Int)
res <-
run $
try . S.drain . t $
S.finally
(writeIORef ioRef 1)
(throwM (ExampleException "E") <> S.nil)
assert $ res == Left (ExampleException "E")
refValue <- run $ readIORef ioRef
assert $ refValue == 1
onExceptionProp ::
(IsStream t, MonadThrow (t IO), Semigroup (t IO Int))
=> (t IO Int -> SerialT IO Int)
-> Property
onExceptionProp t =
withMaxSuccess maxTestCount $
monadicIO $ do
ioRef <- run $ newIORef (0 :: Int)
res <-
run $
try . S.drain . t $
S.onException
(writeIORef ioRef 1)
(throwM (ExampleException "E") <> S.nil)
assert $ res == Left (ExampleException "E")
refValue <- run $ readIORef ioRef
assert $ refValue == 1
handleProp ::
IsStream t
=> (t IO Int -> SerialT IO Int)
-> [Int]
-> Property
handleProp t vec =
withMaxSuccess maxTestCount $
monadicIO $ do
res <-
run $
S.toList . t $
S.handle
(\(ExampleException i) -> read i `S.cons` S.fromList vec)
(S.fromSerial $ S.fromList vec <> throwM (ExampleException "0"))
assert $ res == vec ++ [0] ++ vec
exceptionOps ::
(IsStream t, MonadThrow (t IO), Semigroup (t IO Int))
=> String
-> (t IO Int -> SerialT IO Int)
-> Spec
exceptionOps desc t = do
prop (desc <> " before") $ beforeProp t
prop (desc <> " after") $ afterProp t
prop (desc <> " bracket end of stream") $ bracketProp t
#ifdef INCLUDE_FLAKY_TESTS
prop (desc <> " bracket partial stream") $ bracketPartialStreamProp t
#endif
prop (desc <> " bracket exception in stream") $ bracketExceptionProp t
prop (desc <> " onException") $ onExceptionProp t
prop (desc <> " finally end of stream") $ finallyProp t
#ifdef INCLUDE_FLAKY_TESTS
prop (desc <> " finally partial stream") $ finallyPartialStreamProp t
#endif
prop (desc <> " finally exception in stream") $ finallyExceptionProp t
prop (desc <> " handle") $ handleProp t
retry
-------------------------------------------------------------------------------
-- Compose with MonadThrow
-------------------------------------------------------------------------------
newtype ExampleException = ExampleException String deriving (Eq, Show, Ord)
instance Exception ExampleException
composeWithMonadThrow
:: ( IsStream t
, Semigroup (t IO Int)
, MonadThrow (t IO)
)
=> (t IO Int -> SerialT IO Int)
-> Spec
composeWithMonadThrow t = do
it "Compose throwM, nil" $
try (tl (throwM (ExampleException "E") <> S.nil))
`shouldReturn` (Left (ExampleException "E") :: Either ExampleException [Int])
it "Compose nil, throwM" $
try (tl (S.nil <> throwM (ExampleException "E")))
`shouldReturn` (Left (ExampleException "E") :: Either ExampleException [Int])
oneLevelNestedSum "serially" S.fromSerial
oneLevelNestedSum "wSerially" S.fromWSerial
oneLevelNestedSum "asyncly" S.fromAsync
oneLevelNestedSum "wAsyncly" S.fromWAsync
XXX add two level nesting
oneLevelNestedProduct "serially" S.fromSerial
oneLevelNestedProduct "wSerially" S.fromWSerial
oneLevelNestedProduct "asyncly" S.fromAsync
oneLevelNestedProduct "wAsyncly" S.fromWAsync
where
tl = S.toList . t
oneLevelNestedSum desc t1 =
it ("One level nested sum " <> desc) $ do
let nested = S.fromFoldable [1..10] <> throwM (ExampleException "E")
<> S.fromFoldable [1..10]
try (tl (S.nil <> t1 nested <> S.fromFoldable [1..10]))
`shouldReturn` (Left (ExampleException "E") :: Either ExampleException [Int])
oneLevelNestedProduct desc t1 =
it ("One level nested product" <> desc) $ do
let s1 = t $ S.concatMapFoldableWith (<>) return [1..4]
s2 = t1 $ S.concatMapFoldableWith (<>) return [5..8]
try $ tl (do
x <- S.adapt s1
y <- s2
if x + y > 10
then throwM (ExampleException "E")
else return (x + y)
)
`shouldReturn` (Left (ExampleException "E") :: Either ExampleException [Int])
-------------------------------------------------------------------------------
-- Cleanup tests
-------------------------------------------------------------------------------
checkCleanup :: IsStream t
=> Int
-> (t IO Int -> SerialT IO Int)
-> (t IO Int -> t IO Int)
-> IO ()
checkCleanup d t op = do
r <- newIORef (-1 :: Int)
S.drain . fromSerial $ do
_ <- t $ op $ delay r 0 S.|: delay r 1 S.|: delay r 2 S.|: S.nil
return ()
performMajorGC
threadDelay 500000
res <- readIORef r
res `shouldBe` 0
where
delay ref i = threadDelay (i*d*100000) >> writeIORef ref i >> return i
-------------------------------------------------------------------------------
-- Some ad-hoc tests that failed at times
-------------------------------------------------------------------------------
takeCombined :: (Monad m, Semigroup (t m Int), Show a, Eq a, IsStream t)
=> Int -> (t m Int -> SerialT IO a) -> IO ()
takeCombined n t = do
let constr = S.fromFoldable
r <- (S.toList . t) $
S.take n (constr ([] :: [Int]) <> constr ([] :: [Int]))
r `shouldBe` []
-------------------------------------------------------------------------------
-- Helper operations
-------------------------------------------------------------------------------
folded :: IsStream t => [a] -> t IO a
folded =
fromSerial .
(\xs ->
case xs of
[x] -> return x -- singleton stream case
_ -> S.concatMapFoldableWith (<>) return xs)
#ifndef COVERAGE_BUILD
makeCommonOps :: IsStream t => (t m a -> c) -> [(String, t m a -> c)]
#else
makeCommonOps :: b -> [(String, b)]
#endif
makeCommonOps t =
[ ("default", t)
#ifndef COVERAGE_BUILD
, ("rate AvgRate 10000", t . avgRate 10000)
, ("rate Nothing", t . rate Nothing)
, ("maxBuffer 0", t . maxBuffer 0)
, ("maxThreads 0", t . maxThreads 0)
, ("maxThreads 1", t . maxThreads 1)
#ifdef USE_LARGE_MEMORY
, ("maxThreads -1", t . maxThreads (-1))
#endif
#endif
]
#ifndef COVERAGE_BUILD
makeOps :: IsStream t => (t m a -> c) -> [(String, t m a -> c)]
#else
makeOps :: b -> [(String, b)]
#endif
makeOps t = makeCommonOps t ++
[
#ifndef COVERAGE_BUILD
("maxBuffer 1", t . maxBuffer 1)
#endif
]
mapOps :: (a -> Spec) -> [(String, a)] -> Spec
mapOps spec = mapM_ (\(desc, f) -> describe desc $ spec f)
| null | https://raw.githubusercontent.com/composewell/streamly/5327f181db2cf956461b74ed50720eebf119f25a/test/lib/Streamly/Test/Prelude/Common.hs | haskell | |
License : BSD-3-Clause
Maintainer :
Stability : experimental
* Construction operations
* Applicative operations
* Elimination operations
* Functor operations
* Monoid operations
* Semigroup operations
* Transformation operations
* Zip operations
* Exception operations
* Cleanup tests
* Adhoc tests
* Default values
* Helper operations
Coverage build takes too long with default number of tests
-----------------------------------------------------------------------------
Construction operations
-----------------------------------------------------------------------------
XXX try very small steps close to 0
instead we just do till len elements
-----------------------------------------------------------------------------
Applicative operations
-----------------------------------------------------------------------------
polymorphic.
-----------------------------------------------------------------------------
Elimination operations
-----------------------------------------------------------------------------
This is the reference uniq implementation to compare uniq against,
we can use uniq from vector package, but for now this should
suffice.
Elimination
Multi-stream eliminations
XXX Write better tests for substreams.
head/tail/last may depend on the order in case of parallel streams
so we test these only for serial streams.
-----------------------------------------------------------------------------
Functor operations
-----------------------------------------------------------------------------
----------------------------------------------------------------------------
Monoid operations
----------------------------------------------------------------------------
XXX these should get covered by the property tests
These are not covered by the property tests
-------------------------------------------------------------------------
Monoidal composition recursion loops
-------------------------------------------------------------------------
this print line is important for the test (causes a bind)
this print line is important for the test (causes a bind)
-------------------------------------------------------------------------
Bind and monoidal composition combinations
-------------------------------------------------------------------------
XXX need a bind in the body of forEachWith instead of a simple return
-------------------------------------------------------------------------
Bind and monoidal composition combinations
-------------------------------------------------------------------------
bindComposeNested :: WAsyncT IO Int
c = tripleCompose b b b
m = tripleBind c c c
in m
TBD need more such combinations to be tested.
-----------------------------------------------------------------------------
Semigroup operations
-----------------------------------------------------------------------------
XXX concatenate streams of multiple elements rather than single elements
-----------------------------------------------------------------------------
Transformation operations
-----------------------------------------------------------------------------
accidentally passed through them.
conurrent streams. These tests work for all stream types whereas
transformCombineOpsOrdered work only for ordered stream types i.e. excluding
the Async type.
Filtering
transformation
tap
reordering
inserting
multi-stream
transformation tests that can only work reliably for ordered streams i.e.
might yield a different result every time.
Filtering
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
Zip operations
-----------------------------------------------------------------------------
-------------------------------------------------------------------------
Semigroup/Monoidal Composition strict ordering checks
-------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
Compose with MonadThrow
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
Cleanup tests
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
Some ad-hoc tests that failed at times
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
Helper operations
-----------------------------------------------------------------------------
singleton stream case | # OPTIONS_GHC -Wno - deprecations #
Module : Streamly . Test . Prelude . Common
Copyright : ( c ) 2020 Composewell Technologies
Portability : GHC
module Streamly.Test.Prelude.Common
(
constructWithRepeat
, constructWithRepeatM
, constructWithReplicate
, constructWithReplicateM
, constructWithIntFromThenTo
, constructWithDoubleFromThenTo
, constructWithIterate
, constructWithIterateM
, constructWithEnumerate
, constructWithEnumerateTo
, constructWithFromIndices
, constructWithFromIndicesM
, constructWithFromList
, constructWithFromListM
, constructWithUnfoldr
, constructWithCons
, constructWithConsM
, constructWithFromPure
, constructWithFromEffect
, simpleOps
, applicativeOps
, applicativeOps1
, eliminationOpsOrdered
, eliminationOpsWord8
, eliminationOps
, functorOps
, monoidOps
, loops
, bindAndComposeSimpleOps
, bindAndComposeHierarchyOps
, nestTwoStreams
, nestTwoStreamsApp
, composeAndComposeSimpleSerially
, composeAndComposeSimpleAheadly
, composeAndComposeSimpleWSerially
, semigroupOps
, parallelCheck
, transformCombineOpsOrdered
, transformCombineOpsCommon
, toListFL
* Monad operations
, monadBind
, monadThen
, zipApplicative
, zipMonadic
, zipAsyncApplicative
, zipAsyncMonadic
, exceptionOps
* MonadThrow operations
, composeWithMonadThrow
, checkCleanup
, takeCombined
, maxTestCount
, maxStreamLen
, folded
, makeCommonOps
, makeOps
, mapOps
, sortEq
) where
import Control.Applicative (ZipList(..), liftA2)
import Control.Exception (Exception, try)
import Control.Concurrent (threadDelay)
import Control.Monad (replicateM)
#ifdef DEVBUILD
import Control.Monad (when)
#endif
import Control.Monad.Catch (throwM, MonadThrow)
import Data.IORef ( IORef, atomicModifyIORef', modifyIORef', newIORef
, readIORef, writeIORef)
import Data.List
( delete
, deleteBy
, elemIndex
, elemIndices
, find
, findIndex
, findIndices
, foldl'
, foldl1'
, insert
, intersperse
, isPrefixOf
, isSubsequenceOf
, maximumBy
, minimumBy
, scanl'
, sort
, stripPrefix
, unfoldr
)
import Data.Maybe (mapMaybe)
import GHC.Word (Word8)
import System.Mem (performMajorGC)
import Test.Hspec.QuickCheck
import Test.Hspec
import Test.QuickCheck (Property, choose, forAll, listOf, withMaxSuccess)
import Test.QuickCheck.Monadic (assert, monadicIO, run)
import Streamly.Prelude (SerialT, IsStream, (.:), nil, (|&), fromSerial)
#ifndef COVERAGE_BUILD
import Streamly.Prelude (avgRate, rate, maxBuffer, maxThreads)
#endif
import qualified Streamly.Prelude as S
import qualified Streamly.Data.Fold as FL
import qualified Streamly.Internal.Data.Stream.IsStream as S
import qualified Streamly.Internal.Data.Stream.IsStream.Common as IS
import qualified Streamly.Internal.Data.Unfold as UF
import qualified Data.Map.Strict as Map
import Streamly.Test.Common
maxStreamLen :: Int
maxStreamLen = 1000
maxTestCount :: Int
#ifdef DEVBUILD
maxTestCount = 100
#else
maxTestCount = 10
#endif
singleton :: IsStream t => a -> t m a
singleton a = a .: nil
sortEq :: Ord a => [a] -> [a] -> Bool
sortEq a b = sort a == sort b
constructWithLen
:: (Show a, Eq a)
=> (Int -> t IO a)
-> (Int -> [a])
-> (t IO a -> SerialT IO a)
-> Word8
-> Property
constructWithLen mkStream mkList op len = withMaxSuccess maxTestCount $
monadicIO $ do
stream <- run $ (S.toList . op) (mkStream (fromIntegral len))
let list = mkList (fromIntegral len)
listEquals (==) stream list
constructWithLenM
:: (Int -> t IO Int)
-> (Int -> IO [Int])
-> (t IO Int -> SerialT IO Int)
-> Word8
-> Property
constructWithLenM mkStream mkList op len = withMaxSuccess maxTestCount $
monadicIO $ do
stream <- run $ (S.toList . op) (mkStream (fromIntegral len))
list <- run $ mkList (fromIntegral len)
listEquals (==) stream list
constructWithReplicate, constructWithReplicateM, constructWithIntFromThenTo
:: IsStream t
=> (t IO Int -> SerialT IO Int)
-> Word8
-> Property
constructWithReplicateM = constructWithLenM stream list
where list = flip replicateM (return 1 :: IO Int)
stream = flip S.replicateM (return 1 :: IO Int)
constructWithReplicate = constructWithLen stream list
where list = flip replicate (1 :: Int)
stream = flip S.replicate (1 :: Int)
constructWithIntFromThenTo op l =
forAll (choose (minBound, maxBound)) $ \from ->
forAll (choose (minBound, maxBound)) $ \next ->
forAll (choose (minBound, maxBound)) $ \to ->
let list len = take len [from,next..to]
stream len = S.take len $ S.enumerateFromThenTo from next to
in constructWithLen stream list op l
constructWithRepeat, constructWithRepeatM
:: IsStream t
=> (t IO Int -> SerialT IO Int)
-> Word8
-> Property
constructWithRepeat = constructWithLenM stream list
where
stream n = S.take n $ S.repeat 1
list n = return $ replicate n 1
constructWithRepeatM = constructWithLenM stream list
where
stream n = S.take n $ S.repeatM (return 1)
list n = return $ replicate n 1
constructWithDoubleFromThenTo
:: IsStream t
=> (t IO Double -> SerialT IO Double)
-> Word8
-> Property
constructWithDoubleFromThenTo op l =
forAll (choose (-9007199254740999,9007199254740999)) $ \from ->
forAll (choose (-9007199254740999,9007199254740999)) $ \next ->
forAll (choose (-9007199254740999,9007199254740999)) $ \to ->
let list len = take len [from,next..to]
stream len = S.take len $ S.enumerateFromThenTo from next to
in constructWithLen stream list op l
constructWithIterate ::
IsStream t => (t IO Int -> SerialT IO Int) -> Word8 -> Property
constructWithIterate op len =
withMaxSuccess maxTestCount $
monadicIO $ do
stream <-
run $
(S.toList . op . S.take (fromIntegral len))
(S.iterate (+ 1) (0 :: Int))
let list = take (fromIntegral len) (iterate (+ 1) 0)
listEquals (==) stream list
constructWithIterateM ::
IsStream t => (t IO Int -> SerialT IO Int) -> Word8 -> Property
constructWithIterateM op len =
withMaxSuccess maxTestCount $
monadicIO $ do
mvl <- run (newIORef [] :: IO (IORef [Int]))
let addM mv x y = modifyIORef' mv (++ [y + x]) >> return (y + x)
list = take (fromIntegral len) (iterate (+ 1) 0)
run $
S.drain . op $
S.take (fromIntegral len) $
S.iterateM (addM mvl 1) (addM mvl 0 0 :: IO Int)
streamEffect <- run $ readIORef mvl
listEquals (==) streamEffect list
constructWithFromIndices ::
IsStream t => (t IO Int -> SerialT IO Int) -> Word8 -> Property
constructWithFromIndices op len =
withMaxSuccess maxTestCount $
monadicIO $ do
stream <-
run $ (S.toList . op . S.take (fromIntegral len)) (S.fromIndices id)
let list = take (fromIntegral len) (iterate (+ 1) 0)
listEquals (==) stream list
constructWithFromIndicesM ::
IsStream t => (t IO Int -> SerialT IO Int) -> Word8 -> Property
constructWithFromIndicesM op len =
withMaxSuccess maxTestCount $
monadicIO $ do
mvl <- run (newIORef [] :: IO (IORef [Int]))
let addIndex mv i = modifyIORef' mv (++ [i]) >> return i
list = take (fromIntegral len) (iterate (+ 1) 0)
run $
S.drain . op $
S.take (fromIntegral len) $ S.fromIndicesM (addIndex mvl)
streamEffect <- run $ readIORef mvl
listEquals (==) streamEffect list
constructWithCons ::
IsStream t
=> (Int -> t IO Int -> t IO Int)
-> (t IO Int -> SerialT IO Int)
-> Word8
-> Property
constructWithCons cons op len =
withMaxSuccess maxTestCount $
monadicIO $ do
strm <-
run
$ S.toList . op . S.take (fromIntegral len)
$ foldr cons S.nil (repeat 0)
let list = replicate (fromIntegral len) 0
listEquals (==) strm list
constructWithConsM ::
IsStream t
=> (IO Int -> t IO Int -> t IO Int)
-> ([Int] -> [Int])
-> (t IO Int -> SerialT IO Int)
-> Word8
-> Property
constructWithConsM consM listT op len =
withMaxSuccess maxTestCount $
monadicIO $ do
strm <-
run $
S.toList . op . S.take (fromIntegral len) $
foldr consM S.nil (repeat (return 0))
let list = replicate (fromIntegral len) 0
listEquals (==) (listT strm) list
constructWithEnumerate ::
IsStream t
=> ([Int] -> [Int])
-> (t IO Int -> SerialT IO Int)
-> Word8
-> Property
constructWithEnumerate listT op len =
withMaxSuccess maxTestCount $
monadicIO $ do
strm <- run $ S.toList . op . S.take (fromIntegral len) $ S.enumerate
let list = take (fromIntegral len) (enumFrom minBound)
listEquals (==) (listT strm) list
constructWithEnumerateTo ::
IsStream t
=> ([Int] -> [Int])
-> (t IO Int -> SerialT IO Int)
-> Word8
-> Property
constructWithEnumerateTo listT op len =
withMaxSuccess maxTestCount $
monadicIO $ do
It takes forever to enumerate from to len , so
strm <- run $ S.toList . op $ S.enumerateTo (minBound + fromIntegral len)
let list = enumFromTo minBound (minBound + fromIntegral len)
listEquals (==) (listT strm) list
constructWithFromList ::
IsStream t
=> ([Int] -> [Int])
-> (t IO Int -> SerialT IO Int)
-> Word8
-> Property
constructWithFromList listT op len =
withMaxSuccess maxTestCount $
monadicIO $ do
strm <- run $ S.toList . op . S.fromList $ [0 .. fromIntegral len]
let list = [0 .. fromIntegral len]
listEquals (==) (listT strm) list
constructWithFromListM ::
IsStream t
=> ([Int] -> [Int])
-> (t IO Int -> SerialT IO Int)
-> Word8
-> Property
constructWithFromListM listT op len =
withMaxSuccess maxTestCount $
monadicIO $ do
strm <-
run $
S.toList . op . S.fromListM . fmap pure $ [0 .. fromIntegral len]
let list = [0 .. fromIntegral len]
listEquals (==) (listT strm) list
constructWithUnfoldr ::
IsStream t
=> ([Int] -> [Int])
-> (t IO Int -> SerialT IO Int)
-> Word8
-> Property
constructWithUnfoldr listT op len =
withMaxSuccess maxTestCount $
monadicIO $ do
strm <- run $ S.toList . op $ S.unfoldr unfoldStep 0
let list = unfoldr unfoldStep 0
listEquals (==) (listT strm) list
where
unfoldStep seed =
if seed > fromIntegral len
then Nothing
else Just (seed, seed + 1)
constructWithFromPure ::
(IsStream t, Monoid (t IO Int))
=> ([Int] -> [Int])
-> (t IO Int -> SerialT IO Int)
-> Word8
-> Property
constructWithFromPure listT op len =
withMaxSuccess maxTestCount $
monadicIO $ do
strm <-
run
$ S.toList . op . S.take (fromIntegral len)
$ foldMap S.fromPure (repeat 0)
let list = replicate (fromIntegral len) 0
listEquals (==) (listT strm) list
constructWithFromEffect ::
(IsStream t, Monoid (t IO Int))
=> ([Int] -> [Int])
-> (t IO Int -> SerialT IO Int)
-> Word8
-> Property
constructWithFromEffect listT op len =
withMaxSuccess maxTestCount $
monadicIO $ do
strm <-
run
$ S.toList . op . S.take (fromIntegral len)
$ foldMap S.fromEffect (repeat (return 0))
let list = replicate (fromIntegral len) 0
listEquals (==) (listT strm) list
simpleProps ::
(Int -> t IO Int)
-> (t IO Int -> SerialT IO Int)
-> Int
-> Property
simpleProps constr op a = monadicIO $ do
strm <- run $ S.toList . op . constr $ a
listEquals (==) strm [a]
simpleOps :: IsStream t => (t IO Int -> SerialT IO Int) -> Spec
simpleOps op = do
prop "fromPure a = a" $ simpleProps S.fromPure op
prop "fromEffect a = a" $ simpleProps (S.fromEffect . return) op
applicativeOps
:: (Applicative (t IO), Semigroup (t IO Int))
=> ([Int] -> t IO Int)
-> String
-> ([(Int, Int)] -> [(Int, Int)] -> Bool)
-> (t IO (Int, Int) -> SerialT IO (Int, Int))
-> Spec
applicativeOps constr desc eq t = do
prop (desc <> " <*>") $
transformFromList2
constr
eq
(\a b -> (,) <$> a <*> b)
(\a b -> t ((,) <$> a <*> b))
prop (desc <> " liftA2") $
transformFromList2 constr eq (liftA2 (,)) (\a b -> t $ liftA2 (,) a b)
prop (desc <> " Apply - composed first argument") $
sort <$>
(S.toList . t) ((,) <$> (pure 1 <> pure 2) <*> pure 3) `shouldReturn`
[(1, 3), (2, 3)]
prop (desc <> " Apply - composed second argument") $
sort <$>
(S.toList . t) (pure ((,) 1) <*> (pure 2 <> pure 3)) `shouldReturn`
[(1, 2), (1, 3)]
XXX we can combine this with applicativeOps by making the type sufficiently
applicativeOps1
:: Applicative (t IO)
=> ([Int] -> t IO Int)
-> String
-> ([Int] -> [Int] -> Bool)
-> (t IO Int -> SerialT IO Int)
-> Spec
applicativeOps1 constr desc eq t = do
prop (desc <> " *>") $
transformFromList2 constr eq (*>) (\a b -> t (a *> b))
prop (desc <> " <*") $
transformFromList2 constr eq (<*) (\a b -> t (a <* b))
transformFromList2
:: (Eq c, Show c)
=> ([a] -> t IO a)
-> ([c] -> [c] -> Bool)
-> ([a] -> [a] -> [c])
-> (t IO a -> t IO a -> SerialT IO c)
-> ([a], [a])
-> Property
transformFromList2 constr eq listOp op (a, b) =
withMaxSuccess maxTestCount $
monadicIO $ do
stream <- run (S.toList $ op (constr a) (constr b))
let list = listOp a b
listEquals eq stream list
eliminateOp
:: (Show a, Eq a)
=> ([s] -> t IO s)
-> ([s] -> a)
-> (t IO s -> IO a)
-> [s]
-> Property
eliminateOp constr listOp op a =
monadicIO $ do
stream <- run $ op (constr a)
let list = listOp a
equals (==) stream list
wrapMaybe :: ([a1] -> a2) -> [a1] -> Maybe a2
wrapMaybe f x = if null x then Nothing else Just (f x)
wrapOutOfBounds :: ([a1] -> Int -> a2) -> Int -> [a1] -> Maybe a2
wrapOutOfBounds f i x | null x = Nothing
| i >= length x = Nothing
| otherwise = Just (f x i)
wrapThe :: Eq a => [a] -> Maybe a
wrapThe (x:xs)
| all (x ==) xs = Just x
| otherwise = Nothing
wrapThe [] = Nothing
referenceUniq :: Eq a => [a] -> [a]
referenceUniq = go
where
go [] = []
go (x:[]) = [x]
go (x:y:xs)
| x == y = go (x : xs)
| otherwise = x : go (y : xs)
eliminationOps
:: ([Int] -> t IO Int)
-> String
-> (t IO Int -> SerialT IO Int)
-> Spec
eliminationOps constr desc t = do
prop (desc <> " null") $ eliminateOp constr null $ S.null . t
prop (desc <> " foldl'") $
eliminateOp constr (foldl' (+) 0) $ S.foldl' (+) 0 . t
prop (desc <> " foldl1'") $
eliminateOp constr (wrapMaybe $ foldl1' (+)) $ S.foldl1' (+) . t
#ifdef DEVBUILD
prop (desc <> " foldr1") $
eliminateOp constr (wrapMaybe $ foldr1 (+)) $ S.foldr1 (+) . t
#endif
prop (desc <> " all") $ eliminateOp constr (all even) $ S.all even . t
prop (desc <> " any") $ eliminateOp constr (any even) $ S.any even . t
prop (desc <> " and") $ eliminateOp constr (and . fmap (> 0)) $
(S.and . S.map (> 0)) . t
prop (desc <> " or") $ eliminateOp constr (or . fmap (> 0)) $
(S.or . S.map (> 0)) . t
prop (desc <> " length") $ eliminateOp constr length $ S.length . t
prop (desc <> " sum") $ eliminateOp constr sum $ S.sum . t
prop (desc <> " product") $ eliminateOp constr product $ S.product . t
prop (desc <> " mapM_ sumIORef") $
eliminateOp constr sum $
(\strm -> do
ioRef <- newIORef 0
let sumInRef a = modifyIORef' ioRef (a +)
S.mapM_ sumInRef strm
readIORef ioRef) .
t
prop (desc <> "trace sumIORef") $
eliminateOp constr sum $
(\strm -> do
ioRef <- newIORef 0
let sumInRef a = modifyIORef' ioRef (a +)
S.drain $ S.trace sumInRef strm
readIORef ioRef) .
t
prop (desc <> " maximum") $
eliminateOp constr (wrapMaybe maximum) $ S.maximum . t
prop (desc <> " minimum") $
eliminateOp constr (wrapMaybe minimum) $ S.minimum . t
prop (desc <> " maximumBy compare") $
eliminateOp constr (wrapMaybe maximum) $
S.maximumBy compare . t
prop (desc <> " maximumBy flip compare") $
eliminateOp constr (wrapMaybe $ maximumBy $ flip compare) $
S.maximumBy (flip compare) . t
prop (desc <> " minimumBy compare") $
eliminateOp constr (wrapMaybe minimum) $
S.minimumBy compare . t
prop (desc <> " minimumBy flip compare") $
eliminateOp constr (wrapMaybe $ minimumBy $ flip compare) $
S.minimumBy (flip compare) . t
prop (desc <> " findIndex") $
eliminateOp constr (findIndex odd) $ S.findIndex odd . t
prop (desc <> " elemIndex") $
eliminateOp constr (elemIndex 3) $ S.elemIndex 3 . t
prop (desc <> " !! 5") $
eliminateOp constr (wrapOutOfBounds (!!) 5) $ (S.!! 5) . t
prop (desc <> " !! 4") $
eliminateOp constr (wrapOutOfBounds (!!) 0) $ (S.!! 0) . t
prop (desc <> " find") $ eliminateOp constr (find even) $ S.find even . t
prop (desc <> " findM") $ eliminateOp constr (find even) $ S.findM (return . even) . t
prop (desc <> " lookup") $
eliminateOp constr (lookup 3 . flip zip [1..]) $
S.lookup 3 . S.zipWith (\a b -> (b, a)) (S.fromList [(1::Int)..]) . t
prop (desc <> " the") $ eliminateOp constr wrapThe $ S.the . t
prop (desc <> " eqBy (==) t t") $
eliminateOp constr (\s -> s == s) $ (\s -> S.eqBy (==) s s) . t
prop (desc <> " cmpBy (==) t t") $
eliminateOp constr (\s -> compare s s) $ (\s -> S.cmpBy compare s s) . t
prop (desc <> " isPrefixOf 10") $ eliminateOp constr (isPrefixOf [1..10]) $
S.isPrefixOf (S.fromList [(1::Int)..10]) . t
prop (desc <> " isSubsequenceOf 10") $
eliminateOp constr (isSubsequenceOf $ filter even [1..10]) $
S.isSubsequenceOf (S.fromList $ filter even [(1::Int)..10]) . t
prop (desc <> " stripPrefix 10") $ eliminateOp constr (stripPrefix [1..10]) $
(\s -> s >>= maybe (return Nothing) (fmap Just . S.toList)) .
S.stripPrefix (S.fromList [(1::Int)..10]) . t
eliminationOpsOrdered
:: ([Int] -> t IO Int)
-> String
-> (t IO Int -> SerialT IO Int)
-> Spec
eliminationOpsOrdered constr desc t = do
prop (desc <> " head") $ eliminateOp constr (wrapMaybe head) $ S.head . t
prop (desc <> " tail") $ eliminateOp constr (wrapMaybe tail) $ \x -> do
r <- S.tail (t x)
case r of
Nothing -> return Nothing
Just s -> Just <$> S.toList s
prop (desc <> " last") $ eliminateOp constr (wrapMaybe last) $ S.last . t
prop (desc <> " init") $ eliminateOp constr (wrapMaybe init) $ \x -> do
r <- S.init (t x)
case r of
Nothing -> return Nothing
Just s -> Just <$> S.toList s
elemOp
:: ([Word8] -> t IO Word8)
-> (t IO Word8 -> SerialT IO Word8)
-> (Word8 -> SerialT IO Word8 -> IO Bool)
-> (Word8 -> [Word8] -> Bool)
-> (Word8, [Word8])
-> Property
elemOp constr op streamOp listOp (x, xs) =
monadicIO $ do
stream <- run $ (streamOp x . op) (constr xs)
let list = listOp x xs
equals (==) stream list
eliminationOpsWord8
:: ([Word8] -> t IO Word8)
-> String
-> (t IO Word8 -> SerialT IO Word8)
-> Spec
eliminationOpsWord8 constr desc t = do
prop (desc <> " elem") $ elemOp constr t S.elem elem
prop (desc <> " notElem") $ elemOp constr t S.notElem notElem
functorOps
:: (Functor (t IO), Semigroup (t IO Int))
=> ([Int] -> t IO Int)
-> String
-> ([Int] -> [Int] -> Bool)
-> (t IO Int -> SerialT IO Int)
-> Spec
functorOps constr desc eq t = do
prop (desc <> " id") $ transformFromList constr eq id t
prop (desc <> " fmap (+1)") $
transformFromList constr eq (fmap (+ 1)) $ t . fmap (+ 1)
prop (desc <> " fmap on composed (<>)") $
sort <$>
(S.toList . t) (fmap (+ 1) (constr [1] <> constr [2])) `shouldReturn`
([2, 3] :: [Int])
transformFromList
:: (Eq b, Show b) =>
([a] -> t IO a)
-> ([b] -> [b] -> Bool)
-> ([a] -> [b])
-> (t IO a -> SerialT IO b)
-> [a]
-> Property
transformFromList constr eq listOp op a =
monadicIO $ do
stream <- run ((S.toList . op) (constr a))
let list = listOp a
listEquals eq stream list
monoidOps
:: (IsStream t, Semigroup (t IO Int))
=> String
-> t IO Int
-> ([Int] -> [Int] -> Bool)
-> (t IO Int -> SerialT IO Int)
-> Spec
monoidOps desc z eq t = do
prop (desc <> " Compose mempty, mempty") $ spec (z <> z) []
prop (desc <> " Compose empty at the beginning") $ spec (z <> singleton 1) [1]
prop (desc <> " Compose empty at the end") $ spec (singleton 1 <> z) [1]
prop (desc <> " Compose two") $ spec (singleton 0 <> singleton 1) [0, 1]
prop (desc <> " Compose many") $
spec (S.concatForFoldableWith (<>) [1 .. 100] singleton) [1 .. 100]
prop (desc <> " Compose three - empty in the middle") $
spec (singleton 0 <> z <> singleton 1) [0, 1]
prop (desc <> " Compose left associated") $
spec
(((singleton 0 <> singleton 1) <> singleton 2) <> singleton 3)
[0, 1, 2, 3]
prop (desc <> " Compose right associated") $
spec
(singleton 0 <> (singleton 1 <> (singleton 2 <> singleton 3)))
[0, 1, 2, 3]
prop (desc <> " Compose hierarchical (multiple levels)") $
spec
(((singleton 0 <> singleton 1) <> (singleton 2 <> singleton 3)) <>
((singleton 4 <> singleton 5) <> (singleton 6 <> singleton 7)))
[0 .. 7]
where
tl = S.toList . t
spec s list =
monadicIO $ do
stream <- run $ tl s
listEquals eq stream list
loops
:: (IsStream t, Semigroup (t IO Int), Monad (t IO))
=> (t IO Int -> t IO Int)
-> ([Int] -> [Int])
-> ([Int] -> [Int])
-> Spec
loops t tsrt hsrt = do
it "Tail recursive loop" $ (tsrt <$> (S.toList . S.adapt) (loopTail 0))
`shouldReturn` [0..3]
it "Head recursive loop" $ (hsrt <$> (S.toList . S.adapt) (loopHead 0))
`shouldReturn` [0..3]
where
loopHead x = do
S.fromEffect $ putStrLn "LoopHead..."
t $ (if x < 3 then loopHead (x + 1) else nil) <> return x
loopTail x = do
S.fromEffect $ putStrLn "LoopTail..."
t $ return x <> (if x < 3 then loopTail (x + 1) else nil)
bindAndComposeSimpleOps
:: IsStream t
=> String
-> ([Int] -> [Int] -> Bool)
-> (t IO Int -> SerialT IO Int)
-> Spec
bindAndComposeSimpleOps desc eq t = do
bindAndComposeSimple
("Bind and compose " <> desc <> " Stream serially/")
S.fromSerial
bindAndComposeSimple
("Bind and compose " <> desc <> " Stream wSerially/")
S.fromWSerial
bindAndComposeSimple
("Bind and compose " <> desc <> " Stream aheadly/")
S.fromAhead
bindAndComposeSimple
("Bind and compose " <> desc <> " Stream asyncly/")
S.fromAsync
bindAndComposeSimple
("Bind and compose " <> desc <> " Stream wAsyncly/")
S.fromWAsync
bindAndComposeSimple
("Bind and compose " <> desc <> " Stream parallely/")
S.fromParallel
where
bindAndComposeSimple
:: (IsStream t2, Semigroup (t2 IO Int), Monad (t2 IO))
=> String
-> (t2 IO Int -> t2 IO Int)
-> Spec
bindAndComposeSimple idesc t2 = do
prop (idesc <> " Compose many (right fold) with bind") $ \list ->
monadicIO $ do
stream <-
run $
(S.toList . t)
(S.adapt . t2 $ S.concatForFoldableWith (<>) list return)
listEquals eq stream list
prop (idesc <> " Compose many (left fold) with bind") $ \list ->
monadicIO $ do
let forL xs k = foldl (<>) nil $ fmap k xs
stream <-
run $ (S.toList . t) (S.adapt . t2 $ forL list return)
listEquals eq stream list
bindAndComposeHierarchyOps ::
(IsStream t, Monad (t IO))
=> String
-> (t IO Int -> SerialT IO Int)
-> Spec
bindAndComposeHierarchyOps desc t1 = do
let fldldesc = "Bind and compose foldl, " <> desc <> " Stream "
fldrdesc = "Bind and compose foldr, " <> desc <> " Stream "
bindAndComposeHierarchy
(fldldesc <> "serially") S.fromSerial fldl
bindAndComposeHierarchy
(fldrdesc <> "serially") S.fromSerial fldr
bindAndComposeHierarchy
(fldldesc <> "wSerially") S.fromWSerial fldl
bindAndComposeHierarchy
(fldrdesc <> "wSerially") S.fromWSerial fldr
bindAndComposeHierarchy
(fldldesc <> "aheadly") S.fromAhead fldl
bindAndComposeHierarchy
(fldrdesc <> "aheadly") S.fromAhead fldr
bindAndComposeHierarchy
(fldldesc <> "asyncly") S.fromAsync fldl
bindAndComposeHierarchy
(fldrdesc <> "asyncly") S.fromAsync fldr
bindAndComposeHierarchy
(fldldesc <> "wAsyncly") S.fromWAsync fldl
bindAndComposeHierarchy
(fldrdesc <> "wAsyncly") S.fromWAsync fldr
bindAndComposeHierarchy
(fldldesc <> "parallely") S.fromParallel fldl
bindAndComposeHierarchy
(fldrdesc <> "parallely") S.fromParallel fldr
where
bindAndComposeHierarchy
:: (IsStream t2, Monad (t2 IO))
=> String
-> (t2 IO Int -> t2 IO Int)
-> ([t2 IO Int] -> t2 IO Int)
-> Spec
bindAndComposeHierarchy specdesc t2 g =
describe specdesc $
it "Bind and compose nested" $
(sort <$> (S.toList . t1) bindComposeNested)
`shouldReturn` (sort (
[12, 18]
<> replicate 3 13
<> replicate 3 17
<> replicate 6 14
<> replicate 6 16
<> replicate 7 15) :: [Int])
where
bindComposeNested =
let c1 = tripleCompose (return 1) (return 2) (return 3)
c2 = tripleCompose (return 4) (return 5) (return 6)
c3 = tripleCompose (return 7) (return 8) (return 9)
b = tripleBind c1 c2 c3
it seems to be causing a huge space leak in hspec so disabling this for now
in b
tripleCompose a b c = S.adapt . t2 $ g [a, b, c]
tripleBind mx my mz =
mx >>= \x -> my
>>= \y -> mz
>>= \z -> return (x + y + z)
fldr, fldl :: (IsStream t, Semigroup (t IO Int))
=> [t IO Int] -> t IO Int
fldr = foldr (<>) nil
fldl = foldl (<>) nil
Nest two lists using different styles of product compositions
nestTwoStreams
:: (IsStream t, Semigroup (t IO Int), Monad (t IO))
=> String
-> ([Int] -> [Int])
-> ([Int] -> [Int])
-> (t IO Int -> SerialT IO Int)
-> Spec
nestTwoStreams desc streamListT listT t =
it ("Nests two streams using monadic " <> desc <> " composition") $ do
let s1 = S.concatMapFoldableWith (<>) return [1..4]
s2 = S.concatMapFoldableWith (<>) return [5..8]
r <- (S.toList . t) $ do
x <- s1
y <- s2
return $ x + y
streamListT r `shouldBe` listT [6,7,8,9,7,8,9,10,8,9,10,11,9,10,11,12]
nestTwoStreamsApp
:: (IsStream t, Semigroup (t IO Int), Monad (t IO))
=> String
-> ([Int] -> [Int])
-> ([Int] -> [Int])
-> (t IO Int -> SerialT IO Int)
-> Spec
nestTwoStreamsApp desc streamListT listT t =
it ("Nests two streams using applicative " <> desc <> " composition") $ do
let s1 = S.concatMapFoldableWith (<>) return [1..4]
s2 = S.concatMapFoldableWith (<>) return [5..8]
r = (S.toList . t) ((+) <$> s1 <*> s2)
streamListT <$> r
`shouldReturn` listT [6,7,8,9,7,8,9,10,8,9,10,11,9,10,11,12]
composeAndComposeSimple
:: ( IsStream t1, Semigroup (t1 IO Int)
, IsStream t2, Monoid (t2 IO Int), Monad (t2 IO)
)
=> (t1 IO Int -> SerialT IO Int)
-> (t2 IO Int -> t2 IO Int)
-> [[Int]] -> Spec
composeAndComposeSimple t1 t2 answer = do
let rfold = S.adapt . t2 . S.concatMapFoldableWith (<>) return
it "Compose right associated outer expr, right folded inner" $
(S.toList . t1) (rfold [1,2,3] <> (rfold [4,5,6] <> rfold [7,8,9]))
`shouldReturn` head answer
it "Compose left associated outer expr, right folded inner" $
(S.toList . t1) ((rfold [1,2,3] <> rfold [4,5,6]) <> rfold [7,8,9])
`shouldReturn` (answer !! 1)
let lfold xs = S.adapt $ t2 $ foldl (<>) mempty $ fmap return xs
it "Compose right associated outer expr, left folded inner" $
(S.toList . t1) (lfold [1,2,3] <> (lfold [4,5,6] <> lfold [7,8,9]))
`shouldReturn` (answer !! 2)
it "Compose left associated outer expr, left folded inner" $
(S.toList . t1) ((lfold [1,2,3] <> lfold [4,5,6]) <> lfold [7,8,9])
`shouldReturn` (answer !! 3)
composeAndComposeSimpleSerially
:: (IsStream t, Semigroup (t IO Int))
=> String
-> [[Int]]
-> (t IO Int -> SerialT IO Int)
-> Spec
composeAndComposeSimpleSerially desc answer t = do
describe (desc <> " and Serial <>") $ composeAndComposeSimple t S.fromSerial answer
composeAndComposeSimpleAheadly
:: (IsStream t, Semigroup (t IO Int))
=> String
-> [[Int]]
-> (t IO Int -> SerialT IO Int)
-> Spec
composeAndComposeSimpleAheadly desc answer t = do
describe (desc <> " and Ahead <>") $ composeAndComposeSimple t S.fromAhead answer
composeAndComposeSimpleWSerially
:: (IsStream t, Semigroup (t IO Int))
=> String
-> [[Int]]
-> (t IO Int -> SerialT IO Int)
-> Spec
composeAndComposeSimpleWSerially desc answer t = do
describe (desc <> " and WSerial <>") $ composeAndComposeSimple t S.fromWSerial answer
foldFromList
:: ([Int] -> t IO Int)
-> (t IO Int -> SerialT IO Int)
-> ([Int] -> [Int] -> Bool)
-> [Int]
-> Property
foldFromList constr op eq = transformFromList constr eq id op
semigroupOps
:: (IsStream t, Monoid (t IO Int))
=> String
-> ([Int] -> [Int] -> Bool)
-> (t IO Int -> SerialT IO Int)
-> Spec
semigroupOps desc eq t = do
prop (desc <> " <>") $ foldFromList (S.concatMapFoldableWith (<>) singleton) t eq
prop (desc <> " mappend") $ foldFromList (S.concatMapFoldableWith mappend singleton) t eq
transformCombineFromList
:: Semigroup (t IO Int)
=> ([Int] -> t IO Int)
-> ([Int] -> [Int] -> Bool)
-> ([Int] -> [Int])
-> (t IO Int -> SerialT IO Int)
-> (t IO Int -> t IO Int)
-> [Int]
-> [Int]
-> [Int]
-> Property
transformCombineFromList constr eq listOp t op a b c =
withMaxSuccess maxTestCount $
monadicIO $ do
stream <- run ((S.toList . t) $
constr a <> op (constr b <> constr c))
let list = a <> listOp (b <> c)
listEquals eq stream list
takeEndBy :: Property
takeEndBy = forAll (listOf (chooseInt (0, maxStreamLen))) $ \lst -> monadicIO $ do
let (s1, s3) = span (<= 200) lst
let s4 = [head s3 | not (null s3)]
s2 <- run $ S.toList $ IS.takeEndBy (> 200) $ S.fromList lst
assert $ s1 ++ s4 == s2
XXX add tests for MonadReader and MonadError etc . In case an SVar is
This tests transform ops along with detecting illegal sharing of SVar across
transformCombineOpsCommon
:: (IsStream t, Semigroup (t IO Int) , Functor (t IO))
=> ([Int] -> t IO Int)
-> String
-> ([Int] -> [Int] -> Bool)
-> (t IO Int -> SerialT IO Int)
-> Spec
transformCombineOpsCommon constr desc eq t = do
let transform = transformCombineFromList constr eq
prop (desc <> " filter False") $
transform (filter (const False)) t (S.filter (const False))
prop (desc <> " filter True") $
transform (filter (const True)) t (S.filter (const True))
prop (desc <> " filter even") $
transform (filter even) t (S.filter even)
prop (desc <> " filterM False") $
transform (filter (const False)) t (S.filterM (const $ return False))
prop (desc <> " filterM True") $
transform (filter (const True)) t (S.filterM (const $ return True))
prop (desc <> " filterM even") $
transform (filter even) t (S.filterM (return . even))
prop (desc <> " take maxBound") $
transform (take maxBound) t (S.take maxBound)
prop (desc <> " take 0") $ transform (take 0) t (S.take 0)
prop (desc <> " takeWhile True") $
transform (takeWhile (const True)) t (S.takeWhile (const True))
prop (desc <> " takeWhile False") $
transform (takeWhile (const False)) t (S.takeWhile (const False))
prop (desc <> " takeWhileM True") $
transform (takeWhile (const True)) t (S.takeWhileM (const $ return True))
prop (desc <> " takeWhileM False") $
transform (takeWhile (const False)) t (S.takeWhileM (const $ return False))
prop "takeEndBy" takeEndBy
prop (desc <> " drop maxBound") $
transform (drop maxBound) t (S.drop maxBound)
prop (desc <> " drop 0") $ transform (drop 0) t (S.drop 0)
prop (desc <> " dropWhile True") $
transform (dropWhile (const True)) t (S.dropWhile (const True))
prop (desc <> " dropWhile False") $
transform (dropWhile (const False)) t (S.dropWhile (const False))
prop (desc <> " dropWhileM True") $
transform (dropWhile (const True)) t (S.dropWhileM (const $ return True))
prop (desc <> " dropWhileM False") $
transform (dropWhile (const False)) t (S.dropWhileM (const $ return False))
prop (desc <> " deleteBy (<=) maxBound") $
transform (deleteBy (<=) maxBound) t (S.deleteBy (<=) maxBound)
prop (desc <> " deleteBy (==) 4") $
transform (delete 4) t (S.deleteBy (==) 4)
prop (desc <> " mapM (+1)") $
transform (fmap (+1)) t (S.mapM (\x -> return (x + 1)))
prop (desc <> " scanl'") $ transform (scanl' (const id) 0) t
(S.scanl' (const id) 0)
prop (desc <> " postscanl'") $ transform (tail . scanl' (const id) 0) t
(S.postscanl' (const id) 0)
prop (desc <> " scanlM'") $ transform (scanl' (const id) 0) t
(S.scanlM' (\_ a -> return a) (return 0))
prop (desc <> " postscanlM'") $ transform (tail . scanl' (const id) 0) t
(S.postscanlM' (\_ a -> return a) (return 0))
prop (desc <> " scanl1'") $ transform (scanl1 (const id)) t
(S.scanl1' (const id))
prop (desc <> " scanl1M'") $ transform (scanl1 (const id)) t
(S.scanl1M' (\_ a -> return a))
let f x = if odd x then Just (x + 100) else Nothing
prop (desc <> " mapMaybe") $ transform (mapMaybe f) t (S.mapMaybe f)
prop (desc <> " mapMaybeM") $
transform (mapMaybe f) t (S.mapMaybeM (return . f))
prop (desc <> " tap FL.sum . map (+1)") $ \a b ->
withMaxSuccess maxTestCount $
monadicIO $ do
cref <- run $ newIORef 0
let fldstp _ e = modifyIORef' cref (e +)
sumfoldinref = FL.foldlM' fldstp (return ())
op = S.tap sumfoldinref . S.mapM (\x -> return (x+1))
listOp = fmap (+1)
stream <- run ((S.toList . t) $ op (constr a <> constr b))
let list = listOp (a <> b)
ssum <- run $ readIORef cref
assert (sum list == ssum)
listEquals eq stream list
prop (desc <> " reverse") $ transform reverse t S.reverse
prop (desc <> " reverse'") $ transform reverse t S.reverse'
prop (desc <> " intersperseM") $
forAll (choose (minBound, maxBound)) $ \n ->
transform (intersperse n) t (S.intersperseM $ return n)
prop (desc <> " intersperse") $
forAll (choose (minBound, maxBound)) $ \n ->
transform (intersperse n) t (S.intersperse n)
prop (desc <> " insertBy 0") $
forAll (choose (minBound, maxBound)) $ \n ->
transform (insert n) t (S.insertBy compare n)
prop (desc <> " concatMap") $
forAll (choose (0, 100)) $ \n ->
transform (concatMap (const [1..n]))
t (S.concatMap (const (S.fromList [1..n])))
prop (desc <> " concatMapM") $
forAll (choose (0, 100)) $ \n ->
transform (concatMap (const [1..n]))
t (S.concatMapM (const (return $ S.fromList [1..n])))
prop (desc <> " unfoldMany") $
forAll (choose (0, 100)) $ \n ->
transform (concatMap (const [1..n]))
t (S.unfoldMany (UF.lmap (const undefined)
$ UF.both [1..n] UF.fromList))
toListFL :: Monad m => FL.Fold m a [a]
toListFL = FL.toList
Serial , Ahead and Zip . For example if we use " take 1 " on an async stream , it
transformCombineOpsOrdered
:: (IsStream t, Semigroup (t IO Int))
=> ([Int] -> t IO Int)
-> String
-> ([Int] -> [Int] -> Bool)
-> (t IO Int -> SerialT IO Int)
-> Spec
transformCombineOpsOrdered constr desc eq t = do
let transform = transformCombineFromList constr eq
prop (desc <> " take 1") $ transform (take 1) t (S.take 1)
#ifdef DEVBUILD
prop (desc <> " take 2") $ transform (take 2) t (S.take 2)
prop (desc <> " take 3") $ transform (take 3) t (S.take 3)
prop (desc <> " take 4") $ transform (take 4) t (S.take 4)
prop (desc <> " take 5") $ transform (take 5) t (S.take 5)
#endif
prop (desc <> " take 10") $ transform (take 10) t (S.take 10)
prop (desc <> " takeWhile > 0") $
transform (takeWhile (> 0)) t (S.takeWhile (> 0))
prop (desc <> " takeWhileM > 0") $
transform (takeWhile (> 0)) t (S.takeWhileM (return . (> 0)))
prop (desc <> " drop 1") $ transform (drop 1) t (S.drop 1)
prop (desc <> " drop 10") $ transform (drop 10) t (S.drop 10)
prop (desc <> " dropWhile > 0") $
transform (dropWhile (> 0)) t (S.dropWhile (> 0))
prop (desc <> " dropWhileM > 0") $
transform (dropWhile (> 0)) t (S.dropWhileM (return . (> 0)))
prop (desc <> " scan") $ transform (scanl' (+) 0) t (S.scanl' (+) 0)
prop (desc <> " uniq") $ transform referenceUniq t S.uniq
prop (desc <> " deleteBy (<=) 0") $
transform (deleteBy (<=) 0) t (S.deleteBy (<=) 0)
prop (desc <> " findIndices") $
transform (findIndices odd) t (S.findIndices odd)
prop (desc <> " findIndices . filter") $
transform (findIndices odd . filter odd)
t
(S.findIndices odd . S.filter odd)
prop (desc <> " elemIndices") $
transform (elemIndices 0) t (S.elemIndices 0)
XXX this does not fail when the SVar is shared , need to fix .
prop (desc <> " concurrent application") $
transform (fmap (+1)) t (|& S.map (+1))
Monad operations
monadThen
:: Monad (t IO)
=> ([Int] -> t IO Int)
-> ([Int] -> [Int] -> Bool)
-> (t IO Int -> SerialT IO Int)
-> ([Int], [Int])
-> Property
monadThen constr eq t (a, b) = withMaxSuccess maxTestCount $ monadicIO $ do
stream <- run ((S.toList . t) (constr a >> constr b))
let list = a >> b
listEquals eq stream list
monadBind
:: Monad (t IO)
=> ([Int] -> t IO Int)
-> ([Int] -> [Int] -> Bool)
-> (t IO Int -> SerialT IO Int)
-> ([Int], [Int])
-> Property
monadBind constr eq t (a, b) = withMaxSuccess maxTestCount $
monadicIO $ do
stream <-
run
((S.toList . t)
(constr a >>= \x -> (+ x) <$> constr b))
let list = a >>= \x -> (+ x) <$> b
listEquals eq stream list
zipApplicative
:: (IsStream t, Applicative (t IO))
=> ([Int] -> t IO Int)
-> ([(Int, Int)] -> [(Int, Int)] -> Bool)
-> (t IO (Int, Int) -> SerialT IO (Int, Int))
-> ([Int], [Int])
-> Property
zipApplicative constr eq t (a, b) = withMaxSuccess maxTestCount $
monadicIO $ do
stream1 <- run ((S.toList . t) ((,) <$> constr a <*> constr b))
stream2 <- run ((S.toList . t) (pure (,) <*> constr a <*> constr b))
stream3 <- run ((S.toList . t) (S.zipWith (,) (constr a) (constr b)))
let list = getZipList $ (,) <$> ZipList a <*> ZipList b
listEquals eq stream1 list
listEquals eq stream2 list
listEquals eq stream3 list
zipMonadic
:: IsStream t
=> ([Int] -> t IO Int)
-> ([(Int, Int)] -> [(Int, Int)] -> Bool)
-> (t IO (Int, Int) -> SerialT IO (Int, Int))
-> ([Int], [Int])
-> Property
zipMonadic constr eq t (a, b) = withMaxSuccess maxTestCount $
monadicIO $ do
stream1 <-
run
((S.toList . t)
(S.zipWithM (curry return) (constr a) (constr b)))
let list = getZipList $ (,) <$> ZipList a <*> ZipList b
listEquals eq stream1 list
zipAsyncMonadic
:: IsStream t
=> ([Int] -> t IO Int)
-> ([(Int, Int)] -> [(Int, Int)] -> Bool)
-> (t IO (Int, Int) -> SerialT IO (Int, Int))
-> ([Int], [Int])
-> Property
zipAsyncMonadic constr eq t (a, b) = withMaxSuccess maxTestCount $
monadicIO $ do
stream1 <-
run
((S.toList . t)
(S.zipWithM (curry return) (constr a) (constr b)))
stream2 <-
run
((S.toList . t)
(S.zipAsyncWithM (curry return) (constr a) (constr b)))
let list = getZipList $ (,) <$> ZipList a <*> ZipList b
listEquals eq stream1 list
listEquals eq stream2 list
zipAsyncApplicative
:: IsStream t
=> ([Int] -> t IO Int)
-> ([(Int, Int)] -> [(Int, Int)] -> Bool)
-> (t IO (Int, Int) -> SerialT IO (Int, Int))
-> ([Int], [Int])
-> Property
zipAsyncApplicative constr eq t (a, b) = withMaxSuccess maxTestCount $
monadicIO $ do
stream <-
run
((S.toList . t)
(S.zipAsyncWith (,) (constr a) (constr b)))
let list = getZipList $ (,) <$> ZipList a <*> ZipList b
listEquals eq stream list
parallelCheck :: (IsStream t, Monad (t IO))
=> (t IO Int -> SerialT IO Int)
-> (t IO Int -> t IO Int -> t IO Int)
-> Spec
parallelCheck t f = do
it "Parallel ordering left associated" $
(S.toList . t) (((event 4 `f` event 3) `f` event 2) `f` event 1)
`shouldReturn` [1..4]
it "Parallel ordering right associated" $
(S.toList . t) (event 4 `f` (event 3 `f` (event 2 `f` event 1)))
`shouldReturn` [1..4]
where event n = S.fromEffect (threadDelay (n * 200000)) >> return n
Exception ops
beforeProp :: IsStream t => (t IO Int -> SerialT IO Int) -> [Int] -> Property
beforeProp t vec =
withMaxSuccess maxTestCount $
monadicIO $ do
ioRef <- run $ newIORef []
run
$ S.drain . t
$ S.before (writeIORef ioRef [0])
$ S.mapM (\a -> do atomicModifyIORef' ioRef (\xs -> (xs ++ [a], ()))
return a)
$ S.fromList vec
refValue <- run $ readIORef ioRef
listEquals (==) (head refValue : sort (tail refValue)) (0:sort vec)
afterProp :: IsStream t => (t IO Int -> SerialT IO Int) -> [Int] -> Property
afterProp t vec =
withMaxSuccess maxTestCount $
monadicIO $ do
ioRef <- run $ newIORef []
run
$ S.drain . t
$ S.after (modifyIORef' ioRef (0:))
$ S.mapM (\a -> do atomicModifyIORef' ioRef (\xs -> (a:xs, ()))
return a)
$ S.fromList vec
refValue <- run $ readIORef ioRef
listEquals (==) (head refValue : sort (tail refValue)) (0:sort vec)
bracketProp :: IsStream t => (t IO Int -> SerialT IO Int) -> [Int] -> Property
bracketProp t vec =
withMaxSuccess maxTestCount $
monadicIO $ do
ioRef <- run $ newIORef (0 :: Int)
run $
S.drain . t $
S.bracket
(return ioRef)
(`writeIORef` 1)
(\ioref ->
S.mapM
(\a -> writeIORef ioref 2 >> return a)
(S.fromList vec))
refValue <- run $ readIORef ioRef
assert $ refValue == 1
#ifdef DEVBUILD
bracketPartialStreamProp ::
(IsStream t) => (t IO Int -> SerialT IO Int) -> [Int] -> Property
bracketPartialStreamProp t vec =
forAll (choose (0, length vec)) $ \len -> do
withMaxSuccess maxTestCount $
monadicIO $ do
ioRef <- run $ newIORef (0 :: Int)
run $
S.drain . t $
S.take len $
S.bracket
(writeIORef ioRef 1 >> return ioRef)
(`writeIORef` 3)
(\ioref ->
S.mapM
(\a -> writeIORef ioref 2 >> return a)
(S.fromList vec))
run $ do
performMajorGC
threadDelay 1000000
refValue <- run $ readIORef ioRef
when (refValue /= 0 && refValue /= 3) $
error $ "refValue == " ++ show refValue
#endif
bracketExceptionProp ::
(IsStream t, MonadThrow (t IO), Semigroup (t IO Int))
=> (t IO Int -> SerialT IO Int)
-> Property
bracketExceptionProp t =
withMaxSuccess maxTestCount $
monadicIO $ do
ioRef <- run $ newIORef (0 :: Int)
res <-
run $
try . S.drain . t $
S.bracket
(return ioRef)
(`writeIORef` 1)
(const $ throwM (ExampleException "E") <> S.nil)
assert $ res == Left (ExampleException "E")
refValue <- run $ readIORef ioRef
assert $ refValue == 1
finallyProp :: (IsStream t) => (t IO Int -> SerialT IO Int) -> [Int] -> Property
finallyProp t vec =
withMaxSuccess maxTestCount $
monadicIO $ do
ioRef <- run $ newIORef (0 :: Int)
run $
S.drain . t $
S.finally
(writeIORef ioRef 1)
(S.mapM (\a -> writeIORef ioRef 2 >> return a) (S.fromList vec))
refValue <- run $ readIORef ioRef
assert $ refValue == 1
retry :: Spec
retry = do
ref <- runIO $ newIORef (0 :: Int)
res <- runIO $ S.toList (S.retry emap handler (stream1 ref))
refVal <- runIO $ readIORef ref
spec res refVal
where
emap = Map.singleton (ExampleException "E") 10
stream1 ref =
S.fromListM
[ return 1
, return 2
, atomicModifyIORef' ref (\a -> (a + 1, ()))
>> throwM (ExampleException "E")
>> return 3
, return 4
]
stream2 = S.fromList [5, 6, 7 :: Int]
handler = const stream2
expectedRes = [1, 2, 5, 6, 7]
expectedRefVal = 11
spec res refVal = do
it "Runs the exception handler properly" $ res `shouldBe` expectedRes
it "Runs retires the exception correctly"
$ refVal `shouldBe` expectedRefVal
#ifdef DEVBUILD
finallyPartialStreamProp ::
(IsStream t) => (t IO Int -> SerialT IO Int) -> [Int] -> Property
finallyPartialStreamProp t vec =
forAll (choose (0, length vec)) $ \len -> do
withMaxSuccess maxTestCount $
monadicIO $ do
ioRef <- run $ newIORef (0 :: Int)
run $
S.drain . t $
S.take len $
S.finally
(writeIORef ioRef 2)
(S.mapM
(\a -> writeIORef ioRef 1 >> return a)
(S.fromList vec))
run $ do
performMajorGC
threadDelay 100000
refValue <- run $ readIORef ioRef
when (refValue /= 0 && refValue /= 2) $
error $ "refValue == " ++ show refValue
#endif
finallyExceptionProp ::
(IsStream t, MonadThrow (t IO), Semigroup (t IO Int))
=> (t IO Int -> SerialT IO Int)
-> Property
finallyExceptionProp t =
withMaxSuccess maxTestCount $
monadicIO $ do
ioRef <- run $ newIORef (0 :: Int)
res <-
run $
try . S.drain . t $
S.finally
(writeIORef ioRef 1)
(throwM (ExampleException "E") <> S.nil)
assert $ res == Left (ExampleException "E")
refValue <- run $ readIORef ioRef
assert $ refValue == 1
onExceptionProp ::
(IsStream t, MonadThrow (t IO), Semigroup (t IO Int))
=> (t IO Int -> SerialT IO Int)
-> Property
onExceptionProp t =
withMaxSuccess maxTestCount $
monadicIO $ do
ioRef <- run $ newIORef (0 :: Int)
res <-
run $
try . S.drain . t $
S.onException
(writeIORef ioRef 1)
(throwM (ExampleException "E") <> S.nil)
assert $ res == Left (ExampleException "E")
refValue <- run $ readIORef ioRef
assert $ refValue == 1
handleProp ::
IsStream t
=> (t IO Int -> SerialT IO Int)
-> [Int]
-> Property
handleProp t vec =
withMaxSuccess maxTestCount $
monadicIO $ do
res <-
run $
S.toList . t $
S.handle
(\(ExampleException i) -> read i `S.cons` S.fromList vec)
(S.fromSerial $ S.fromList vec <> throwM (ExampleException "0"))
assert $ res == vec ++ [0] ++ vec
exceptionOps ::
(IsStream t, MonadThrow (t IO), Semigroup (t IO Int))
=> String
-> (t IO Int -> SerialT IO Int)
-> Spec
exceptionOps desc t = do
prop (desc <> " before") $ beforeProp t
prop (desc <> " after") $ afterProp t
prop (desc <> " bracket end of stream") $ bracketProp t
#ifdef INCLUDE_FLAKY_TESTS
prop (desc <> " bracket partial stream") $ bracketPartialStreamProp t
#endif
prop (desc <> " bracket exception in stream") $ bracketExceptionProp t
prop (desc <> " onException") $ onExceptionProp t
prop (desc <> " finally end of stream") $ finallyProp t
#ifdef INCLUDE_FLAKY_TESTS
prop (desc <> " finally partial stream") $ finallyPartialStreamProp t
#endif
prop (desc <> " finally exception in stream") $ finallyExceptionProp t
prop (desc <> " handle") $ handleProp t
retry
newtype ExampleException = ExampleException String deriving (Eq, Show, Ord)
instance Exception ExampleException
composeWithMonadThrow
:: ( IsStream t
, Semigroup (t IO Int)
, MonadThrow (t IO)
)
=> (t IO Int -> SerialT IO Int)
-> Spec
composeWithMonadThrow t = do
it "Compose throwM, nil" $
try (tl (throwM (ExampleException "E") <> S.nil))
`shouldReturn` (Left (ExampleException "E") :: Either ExampleException [Int])
it "Compose nil, throwM" $
try (tl (S.nil <> throwM (ExampleException "E")))
`shouldReturn` (Left (ExampleException "E") :: Either ExampleException [Int])
oneLevelNestedSum "serially" S.fromSerial
oneLevelNestedSum "wSerially" S.fromWSerial
oneLevelNestedSum "asyncly" S.fromAsync
oneLevelNestedSum "wAsyncly" S.fromWAsync
XXX add two level nesting
oneLevelNestedProduct "serially" S.fromSerial
oneLevelNestedProduct "wSerially" S.fromWSerial
oneLevelNestedProduct "asyncly" S.fromAsync
oneLevelNestedProduct "wAsyncly" S.fromWAsync
where
tl = S.toList . t
oneLevelNestedSum desc t1 =
it ("One level nested sum " <> desc) $ do
let nested = S.fromFoldable [1..10] <> throwM (ExampleException "E")
<> S.fromFoldable [1..10]
try (tl (S.nil <> t1 nested <> S.fromFoldable [1..10]))
`shouldReturn` (Left (ExampleException "E") :: Either ExampleException [Int])
oneLevelNestedProduct desc t1 =
it ("One level nested product" <> desc) $ do
let s1 = t $ S.concatMapFoldableWith (<>) return [1..4]
s2 = t1 $ S.concatMapFoldableWith (<>) return [5..8]
try $ tl (do
x <- S.adapt s1
y <- s2
if x + y > 10
then throwM (ExampleException "E")
else return (x + y)
)
`shouldReturn` (Left (ExampleException "E") :: Either ExampleException [Int])
checkCleanup :: IsStream t
=> Int
-> (t IO Int -> SerialT IO Int)
-> (t IO Int -> t IO Int)
-> IO ()
checkCleanup d t op = do
r <- newIORef (-1 :: Int)
S.drain . fromSerial $ do
_ <- t $ op $ delay r 0 S.|: delay r 1 S.|: delay r 2 S.|: S.nil
return ()
performMajorGC
threadDelay 500000
res <- readIORef r
res `shouldBe` 0
where
delay ref i = threadDelay (i*d*100000) >> writeIORef ref i >> return i
takeCombined :: (Monad m, Semigroup (t m Int), Show a, Eq a, IsStream t)
=> Int -> (t m Int -> SerialT IO a) -> IO ()
takeCombined n t = do
let constr = S.fromFoldable
r <- (S.toList . t) $
S.take n (constr ([] :: [Int]) <> constr ([] :: [Int]))
r `shouldBe` []
folded :: IsStream t => [a] -> t IO a
folded =
fromSerial .
(\xs ->
case xs of
_ -> S.concatMapFoldableWith (<>) return xs)
#ifndef COVERAGE_BUILD
makeCommonOps :: IsStream t => (t m a -> c) -> [(String, t m a -> c)]
#else
makeCommonOps :: b -> [(String, b)]
#endif
makeCommonOps t =
[ ("default", t)
#ifndef COVERAGE_BUILD
, ("rate AvgRate 10000", t . avgRate 10000)
, ("rate Nothing", t . rate Nothing)
, ("maxBuffer 0", t . maxBuffer 0)
, ("maxThreads 0", t . maxThreads 0)
, ("maxThreads 1", t . maxThreads 1)
#ifdef USE_LARGE_MEMORY
, ("maxThreads -1", t . maxThreads (-1))
#endif
#endif
]
#ifndef COVERAGE_BUILD
makeOps :: IsStream t => (t m a -> c) -> [(String, t m a -> c)]
#else
makeOps :: b -> [(String, b)]
#endif
makeOps t = makeCommonOps t ++
[
#ifndef COVERAGE_BUILD
("maxBuffer 1", t . maxBuffer 1)
#endif
]
mapOps :: (a -> Spec) -> [(String, a)] -> Spec
mapOps spec = mapM_ (\(desc, f) -> describe desc $ spec f)
|
ea3e845775e16c94bfce6313606b1e6be4bc6dfad2b2c8a1d69bd1efbcda459f | technoblogy/ulisp-builder | build.lisp | ;;;-*- Mode: Lisp; Package: cl-user -*-
(in-package :cl-user)
;; Generate *********************************************************************************************
(defun write-no-comments (stream string comments)
(cond
(comments
(write-string string stream)
(terpri stream))
(t
(let ((start 0))
(loop
(let* ((com (search "/*" string :start2 start))
(ment (when com (search "*/" string :start2 com))))
(cond
32
Swallow return too
(t (write-string string stream :start start)
(terpri stream)
(return)))))))))
(defun definition-p (string)
(cond
((null string) nil)
((stringp string)
(let* ((com (search "/*" string :start2 0))
(ment (when com (search "*/" string :start2 com))))
(not (and com ment (= com 1) (= ment (- (length string) 2))))))
(t t)))
(defun mappend (fn &rest lsts)
"maps elements in list and finally appends all resulted lists."
(apply #'append (apply #'mapcar fn lsts)))
( wildcards ( if wildcard ( reduce # ' + ( map ' list # ' ( lambda ( x ) ( 1- ( length x ) ) ) ( cadar keywords ) ) ) 0 ) )
(defun do-keyword-enums (str keywords)
(let* ((wildcard (null (caar keywords)))
(only-wildcard (and wildcard (null (cdr keywords)))))
(dotimes (n (length keywords))
(destructuring-bind (cpu lists) (nth n keywords)
(let ((klist (mappend #'(lambda (x) (map 'list #'(lambda (y) (if (listp y) (car y) y)) (cdr x))) lists)))
(unless (and wildcard (zerop n)) (format str "#~[~:;el~]if defined(~a)~%" (if wildcard (1- n) n) cpu))
(format str "~{~a~%~}" (split-into-lines (format nil "~{K_~a,~^ ~}" klist))))))
(unless only-wildcard (format str "#endif~%"))))
(defun do-keyword-progmems (str keywords i)
(let* ((wildcard (null (caar keywords)))
(only-wildcard (and wildcard (null (cdr keywords))))
(j i))
(dotimes (n (length keywords))
(destructuring-bind (cpu lists) (nth n keywords)
(let ((klist (mappend #'(lambda (x) (cdr x)) lists)))
(when cpu
(setq j i)
(format str "#~[~:;el~]if defined(~a)~%" (if wildcard (1- n) n) cpu))
(dolist (k klist)
(format str "const char string~a[] PROGMEM = \":~a\";~%" j
(substitute #\- #\_ (string-downcase (if (consp k) (car k) k))))
(incf j))
(when cpu (format str "const char string~a[] PROGMEM = \"\";~%" j)))
(unless cpu (setq i j))))
(if only-wildcard (format str "const char string~a[] PROGMEM = \"\";~%" j)
(format str "#endif~%"))))
(defun needs-&-prefix (a b)
(or
(and (eq a 'register) (listp b) (stringp (second b)) (char/= (char (second b) 0) #\())
(and (eq a 'register) (atom b))))
(defun docstring (definition enum string)
(cond
((null definition) nil)
((stringp definition)
(let* ((com (search "/*" definition :start2 0))
(ment (when com (search "*/" definition :start2 com))))
(when (and com ment) (subseq definition (+ com 3) (- ment 1)))))
((keywordp definition) nil)
((symbolp definition)
(let* ((definition (with-output-to-string (str) (funcall definition str enum string t)))
(com (search "/*" definition :start2 0))
(ment (when com (search "*/" definition :start2 com))))
(when (and com ment) (subseq definition (+ com 3) (- ment 1)))))
(t nil)))
(defun replace-linebreaks (string)
(let ((result "")
(start 0))
(loop
(let ((cr (position #\newline string :start start)))
(when (not cr) (return (concatenate 'string result (string-trim '(#\space) (subseq string start)))))
(setq result
(concatenate 'string result (string-trim '(#\space) (subseq string start cr)) "\\n\"" (string #\newline) "\""))
(setq start (+ 1 cr))))))
(defun do-keyword-table (str keywords i documentation)
(let* ((wildcard (null (caar keywords)))
(only-wildcard (and wildcard (null (cdr keywords))))
(docstring nil)
(j i))
(dotimes (n (length keywords))
(destructuring-bind (cpu lists) (nth n keywords)
(let ((klist (mappend #'(lambda (x) (mapcar #'(lambda (y) (cons (car x) y)) (cdr x))) lists)))
(when cpu
(setq j i)
(format str "#~[~:;el~]if defined(~a)~%" (if wildcard (1- n) n) cpu))
(dolist (k klist)
(destructuring-bind (a . b) k
(if documentation
(format str " { string~a, (fn_ptr_type)~:[~;&~]~a, ~a, ~:[NULL~;doc~a~] },~%"
j (needs-&-prefix a b) (if (listp b) (second b) b) (or a 0) docstring j)
(format str " { string~a, (fn_ptr_type)~:[~;&~]~a, ~a },~%"
j (needs-&-prefix a b) (if (listp b) (second b) b) (or a 0)))
(incf j)))
(when cpu
(if documentation
(format str " { string~a, NULL, 0x00, ~:[NULL~;doc~a~] },~%" j docstring j)
(format str " { string~a, NULL, 0x00 },~%" j))))
(unless cpu (setq i j))))
(if only-wildcard
(if documentation
(format str " { string~a, NULL, 0x00, ~:[NULL~;doc~a~] },~%" j docstring j)
(format str " { string~a, NULL, 0x00 },~%" j))
(format str "#endif~%"))))
(defun build (&optional (platform :avr) (comments nil) (documentation t))
(let* ((maxsymbol 0)
(definitions *definitions*)
(keywords (eval (intern (format nil "*KEYWORDS-~a*" platform) :cl-user))))
(flet ((include (section str)
(let ((special (intern (format nil "*~a-~a*" section platform) :cl-user))
(default (intern (format nil "*~a*" section) :cl-user)))
(cond
((boundp special)
(let ((inc (eval special)))
(cond
((listp inc) (map nil #'(lambda (x) (write-no-comments str x comments)) inc))
(t (write-no-comments str inc comments)))))
((boundp default)
(let ((inc (eval default)))
(cond
((listp inc) (map nil #'(lambda (x) (write-no-comments str x comments)) inc))
(t (write-no-comments str inc comments)))))
(t nil)))))
;;
(with-open-file (str (capi:prompt-for-file "Output File" :operation :save :pathname "/Users/david/Desktop/") :direction :output)
;; Write preamble
; (include :header str)
(write-no-comments str (eval (intern (format nil "*~a-~a*" :header platform) :cl-user)) t)
(include :workspace str)
(include :macros str)
(include :constants str)
(include :typedefs str)
;; Write enum declarations
(let ((enums
(split-into-lines (format nil "~{~a, ~}" (map 'list #'car (apply #'append (mapcar #'cadr definitions)))) 16)))
(format str "~%enum builtin_t { ~{~a~%~}" enums)
; Do keywords
(do-keyword-enums str keywords)
(format str "USERFUNCTIONS, ENDFUNCTIONS, SET_SIZE = INT_MAX };~%"))
;;
(include :global-variables str)
(include :error-handling str)
(include :setup-workspace str)
(include :make-objects str)
;; Write utilities
(include :garbage-collection str)
(include :compactimage str)
(include :make-filename str)
(include :saveimage str)
(include :tracing str)
(include :helper-functions str)
(include :association-lists str)
(include :array-utilities str)
(include :string-utilities str)
(include :closures str)
(include :in-place str)
(include :i2c-interface str)
(include :stream-interface str)
( include : watchdog )
(include :check-pins str)
(include :note str)
(include :sleep str)
(include :prettyprint str)
(include :assembler str)
#+interrupts
(include :interrupts str)
;; Write function definitions
(dolist (section definitions)
(destructuring-bind (comment defs &optional prefix) section
(declare (ignore prefix))
(when comment (format str "~%// ~a~%" comment))
(dolist (item defs)
(destructuring-bind (enum string min max definition) item
(declare (ignore min max))
(cond
((null (definition-p definition)) nil)
((stringp definition)
(write-no-comments str definition comments))
((keywordp definition) nil)
((symbolp definition)
(funcall definition str enum string comments)
(format str "~%"))
(t nil))))))
(format str "~%// Insert your own function definitions here~%")
;; Write PROGMEM strings
(format str "~%// Built-in symbol names~%")
(let ((i 0))
(dolist (section definitions)
(destructuring-bind (comment defs &optional prefix) section
(declare (ignore comment prefix))
(dolist (item defs)
(destructuring-bind (enum string min max definition) item
(declare (ignore definition min max))
(let ((lower (string-downcase enum)))
(format str "const char string~a[] PROGMEM = \"~a\";~%" i (or string lower))
(setq maxsymbol (max maxsymbol (length (or string lower))))
(incf i))))))
; Do keywords
(do-keyword-progmems str keywords i))
(format str "~%// Insert your own function names here~%")
;; Write documentation strings
(when documentation
(format str "~%// Documentation strings~%")
(let ((i 0))
(dolist (section definitions)
(destructuring-bind (comment defs &optional prefix) section
(declare (ignore comment prefix))
(dolist (item defs)
(destructuring-bind (enum string min max definition) item
(declare (ignore min max))
(let ((docstring (docstring definition enum string)))
(when docstring
(format str "const char doc~a[] PROGMEM = \"~a\";~%"
i (replace-linebreaks docstring)))
(incf i)))))))
(format str "~%// Insert your own function documentation here~%"))
;; Write table
(format str "~%// Built-in symbol lookup table~%")
(let ((i 0))
(format str "const tbl_entry_t lookup_table[] PROGMEM = {~%")
(dolist (section definitions)
(destructuring-bind (comment defs &optional (prefix "fn")) section
(declare (ignore comment))
(dolist (item defs)
(destructuring-bind (enum string min max definition) item
(let ((docstring (docstring definition enum string))
(lower (cond
((consp definition) (string-downcase (car definition)))
((keywordp definition) definition)
(t (string-downcase enum)))))
(if documentation
(format str " { string~a, ~:[NULL~2*~;~a_~a~], 0x~2,'0x, ~:[NULL~;doc~a~] },~%"
i (definition-p definition) prefix lower (+ (ash min 4) (min max 15)) docstring i)
(format str " { string~a, ~:[NULL~2*~;~a_~a~], 0x~2,'0x },~%"
i (definition-p definition) prefix lower (+ (ash min 4) (min max 15))))
(incf i))))))
; Do keywords
(do-keyword-table str keywords i documentation)
(format str "~%~a~%~%};~%" "// Insert your own table entries here"))
;; Write rest
(include :table str)
(include :eval str)
(include :print-functions str)
(include :read-functions str)
(when (eq platform :badge) (write-string *lisp-badge* str))
(include :setup str)
(include :repl str)
(include :loop str)
maxsymbol))))
| null | https://raw.githubusercontent.com/technoblogy/ulisp-builder/fbab6e2331f2d43bfb75b1a6d01fc893144b35b1/build.lisp | lisp | -*- Mode: Lisp; Package: cl-user -*-
Generate *********************************************************************************************
Write preamble
(include :header str)
Write enum declarations
Do keywords
Write utilities
Write function definitions
Write PROGMEM strings
Do keywords
Write documentation strings
Write table
Do keywords
Write rest |
(in-package :cl-user)
(defun write-no-comments (stream string comments)
(cond
(comments
(write-string string stream)
(terpri stream))
(t
(let ((start 0))
(loop
(let* ((com (search "/*" string :start2 start))
(ment (when com (search "*/" string :start2 com))))
(cond
32
Swallow return too
(t (write-string string stream :start start)
(terpri stream)
(return)))))))))
(defun definition-p (string)
(cond
((null string) nil)
((stringp string)
(let* ((com (search "/*" string :start2 0))
(ment (when com (search "*/" string :start2 com))))
(not (and com ment (= com 1) (= ment (- (length string) 2))))))
(t t)))
(defun mappend (fn &rest lsts)
"maps elements in list and finally appends all resulted lists."
(apply #'append (apply #'mapcar fn lsts)))
( wildcards ( if wildcard ( reduce # ' + ( map ' list # ' ( lambda ( x ) ( 1- ( length x ) ) ) ( cadar keywords ) ) ) 0 ) )
(defun do-keyword-enums (str keywords)
(let* ((wildcard (null (caar keywords)))
(only-wildcard (and wildcard (null (cdr keywords)))))
(dotimes (n (length keywords))
(destructuring-bind (cpu lists) (nth n keywords)
(let ((klist (mappend #'(lambda (x) (map 'list #'(lambda (y) (if (listp y) (car y) y)) (cdr x))) lists)))
(unless (and wildcard (zerop n)) (format str "#~[~:;el~]if defined(~a)~%" (if wildcard (1- n) n) cpu))
(format str "~{~a~%~}" (split-into-lines (format nil "~{K_~a,~^ ~}" klist))))))
(unless only-wildcard (format str "#endif~%"))))
(defun do-keyword-progmems (str keywords i)
(let* ((wildcard (null (caar keywords)))
(only-wildcard (and wildcard (null (cdr keywords))))
(j i))
(dotimes (n (length keywords))
(destructuring-bind (cpu lists) (nth n keywords)
(let ((klist (mappend #'(lambda (x) (cdr x)) lists)))
(when cpu
(setq j i)
(format str "#~[~:;el~]if defined(~a)~%" (if wildcard (1- n) n) cpu))
(dolist (k klist)
(format str "const char string~a[] PROGMEM = \":~a\";~%" j
(substitute #\- #\_ (string-downcase (if (consp k) (car k) k))))
(incf j))
(when cpu (format str "const char string~a[] PROGMEM = \"\";~%" j)))
(unless cpu (setq i j))))
(if only-wildcard (format str "const char string~a[] PROGMEM = \"\";~%" j)
(format str "#endif~%"))))
(defun needs-&-prefix (a b)
(or
(and (eq a 'register) (listp b) (stringp (second b)) (char/= (char (second b) 0) #\())
(and (eq a 'register) (atom b))))
(defun docstring (definition enum string)
(cond
((null definition) nil)
((stringp definition)
(let* ((com (search "/*" definition :start2 0))
(ment (when com (search "*/" definition :start2 com))))
(when (and com ment) (subseq definition (+ com 3) (- ment 1)))))
((keywordp definition) nil)
((symbolp definition)
(let* ((definition (with-output-to-string (str) (funcall definition str enum string t)))
(com (search "/*" definition :start2 0))
(ment (when com (search "*/" definition :start2 com))))
(when (and com ment) (subseq definition (+ com 3) (- ment 1)))))
(t nil)))
(defun replace-linebreaks (string)
(let ((result "")
(start 0))
(loop
(let ((cr (position #\newline string :start start)))
(when (not cr) (return (concatenate 'string result (string-trim '(#\space) (subseq string start)))))
(setq result
(concatenate 'string result (string-trim '(#\space) (subseq string start cr)) "\\n\"" (string #\newline) "\""))
(setq start (+ 1 cr))))))
(defun do-keyword-table (str keywords i documentation)
(let* ((wildcard (null (caar keywords)))
(only-wildcard (and wildcard (null (cdr keywords))))
(docstring nil)
(j i))
(dotimes (n (length keywords))
(destructuring-bind (cpu lists) (nth n keywords)
(let ((klist (mappend #'(lambda (x) (mapcar #'(lambda (y) (cons (car x) y)) (cdr x))) lists)))
(when cpu
(setq j i)
(format str "#~[~:;el~]if defined(~a)~%" (if wildcard (1- n) n) cpu))
(dolist (k klist)
(destructuring-bind (a . b) k
(if documentation
(format str " { string~a, (fn_ptr_type)~:[~;&~]~a, ~a, ~:[NULL~;doc~a~] },~%"
j (needs-&-prefix a b) (if (listp b) (second b) b) (or a 0) docstring j)
(format str " { string~a, (fn_ptr_type)~:[~;&~]~a, ~a },~%"
j (needs-&-prefix a b) (if (listp b) (second b) b) (or a 0)))
(incf j)))
(when cpu
(if documentation
(format str " { string~a, NULL, 0x00, ~:[NULL~;doc~a~] },~%" j docstring j)
(format str " { string~a, NULL, 0x00 },~%" j))))
(unless cpu (setq i j))))
(if only-wildcard
(if documentation
(format str " { string~a, NULL, 0x00, ~:[NULL~;doc~a~] },~%" j docstring j)
(format str " { string~a, NULL, 0x00 },~%" j))
(format str "#endif~%"))))
(defun build (&optional (platform :avr) (comments nil) (documentation t))
(let* ((maxsymbol 0)
(definitions *definitions*)
(keywords (eval (intern (format nil "*KEYWORDS-~a*" platform) :cl-user))))
(flet ((include (section str)
(let ((special (intern (format nil "*~a-~a*" section platform) :cl-user))
(default (intern (format nil "*~a*" section) :cl-user)))
(cond
((boundp special)
(let ((inc (eval special)))
(cond
((listp inc) (map nil #'(lambda (x) (write-no-comments str x comments)) inc))
(t (write-no-comments str inc comments)))))
((boundp default)
(let ((inc (eval default)))
(cond
((listp inc) (map nil #'(lambda (x) (write-no-comments str x comments)) inc))
(t (write-no-comments str inc comments)))))
(t nil)))))
(with-open-file (str (capi:prompt-for-file "Output File" :operation :save :pathname "/Users/david/Desktop/") :direction :output)
(write-no-comments str (eval (intern (format nil "*~a-~a*" :header platform) :cl-user)) t)
(include :workspace str)
(include :macros str)
(include :constants str)
(include :typedefs str)
(let ((enums
(split-into-lines (format nil "~{~a, ~}" (map 'list #'car (apply #'append (mapcar #'cadr definitions)))) 16)))
(format str "~%enum builtin_t { ~{~a~%~}" enums)
(do-keyword-enums str keywords)
(format str "USERFUNCTIONS, ENDFUNCTIONS, SET_SIZE = INT_MAX };~%"))
(include :global-variables str)
(include :error-handling str)
(include :setup-workspace str)
(include :make-objects str)
(include :garbage-collection str)
(include :compactimage str)
(include :make-filename str)
(include :saveimage str)
(include :tracing str)
(include :helper-functions str)
(include :association-lists str)
(include :array-utilities str)
(include :string-utilities str)
(include :closures str)
(include :in-place str)
(include :i2c-interface str)
(include :stream-interface str)
( include : watchdog )
(include :check-pins str)
(include :note str)
(include :sleep str)
(include :prettyprint str)
(include :assembler str)
#+interrupts
(include :interrupts str)
(dolist (section definitions)
(destructuring-bind (comment defs &optional prefix) section
(declare (ignore prefix))
(when comment (format str "~%// ~a~%" comment))
(dolist (item defs)
(destructuring-bind (enum string min max definition) item
(declare (ignore min max))
(cond
((null (definition-p definition)) nil)
((stringp definition)
(write-no-comments str definition comments))
((keywordp definition) nil)
((symbolp definition)
(funcall definition str enum string comments)
(format str "~%"))
(t nil))))))
(format str "~%// Insert your own function definitions here~%")
(format str "~%// Built-in symbol names~%")
(let ((i 0))
(dolist (section definitions)
(destructuring-bind (comment defs &optional prefix) section
(declare (ignore comment prefix))
(dolist (item defs)
(destructuring-bind (enum string min max definition) item
(declare (ignore definition min max))
(let ((lower (string-downcase enum)))
(format str "const char string~a[] PROGMEM = \"~a\";~%" i (or string lower))
(setq maxsymbol (max maxsymbol (length (or string lower))))
(incf i))))))
(do-keyword-progmems str keywords i))
(format str "~%// Insert your own function names here~%")
(when documentation
(format str "~%// Documentation strings~%")
(let ((i 0))
(dolist (section definitions)
(destructuring-bind (comment defs &optional prefix) section
(declare (ignore comment prefix))
(dolist (item defs)
(destructuring-bind (enum string min max definition) item
(declare (ignore min max))
(let ((docstring (docstring definition enum string)))
(when docstring
(format str "const char doc~a[] PROGMEM = \"~a\";~%"
i (replace-linebreaks docstring)))
(incf i)))))))
(format str "~%// Insert your own function documentation here~%"))
(format str "~%// Built-in symbol lookup table~%")
(let ((i 0))
(format str "const tbl_entry_t lookup_table[] PROGMEM = {~%")
(dolist (section definitions)
(destructuring-bind (comment defs &optional (prefix "fn")) section
(declare (ignore comment))
(dolist (item defs)
(destructuring-bind (enum string min max definition) item
(let ((docstring (docstring definition enum string))
(lower (cond
((consp definition) (string-downcase (car definition)))
((keywordp definition) definition)
(t (string-downcase enum)))))
(if documentation
(format str " { string~a, ~:[NULL~2*~;~a_~a~], 0x~2,'0x, ~:[NULL~;doc~a~] },~%"
i (definition-p definition) prefix lower (+ (ash min 4) (min max 15)) docstring i)
(format str " { string~a, ~:[NULL~2*~;~a_~a~], 0x~2,'0x },~%"
i (definition-p definition) prefix lower (+ (ash min 4) (min max 15))))
(incf i))))))
(do-keyword-table str keywords i documentation)
(format str "~%~a~%~%};~%" "// Insert your own table entries here"))
(include :table str)
(include :eval str)
(include :print-functions str)
(include :read-functions str)
(when (eq platform :badge) (write-string *lisp-badge* str))
(include :setup str)
(include :repl str)
(include :loop str)
maxsymbol))))
|
f0c1138597a65797d5a3e3cb327c18dd2bc4f8792d191efb7ced33af316f54bc | LPCIC/matita | stats.ml |
||M|| This file is part of HELM , an Hypertextual , Electronic
||A|| Library of Mathematics , developed at the Computer Science
||T|| Department , University of Bologna , Italy .
||I||
||T|| HELM is free software ; you can redistribute it and/or
||A|| modify it under the terms of the GNU General Public License
\ / version 2 or ( at your option ) any later version .
\ / This software is distributed as is , NO WARRANTY .
V _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
||M|| This file is part of HELM, an Hypertextual, Electronic
||A|| Library of Mathematics, developed at the Computer Science
||T|| Department, University of Bologna, Italy.
||I||
||T|| HELM is free software; you can redistribute it and/or
||A|| modify it under the terms of the GNU General Public License
\ / version 2 or (at your option) any later version.
\ / This software is distributed as is, NO WARRANTY.
V_______________________________________________________________ *)
$ I d : stats.ml 9822 2009 - 06 - 03 15:37:06Z denes $
module Stats (B : Terms.Blob) =
struct
module SymbMap = Map.Make(B)
let rec occ_nbr t acc = function
| Terms.Leaf u when B.eq t u -> 1+acc
| Terms.Node l -> List.fold_left (occ_nbr t) acc l
| _ -> acc
;;
let occ_nbr t = occ_nbr t 0;;
let goal_occ_nbr t = function
| (_,Terms.Equation (l,r,_,_),_,_) ->
occ_nbr t l + occ_nbr t r
| _ -> assert false
;;
let rec parse_symbols acc l =
let rec aux acc = function
| Terms.Leaf t ->
(try
let (occ,ar) = SymbMap.find t acc in
SymbMap.add t (occ+1,ar) acc
with Not_found -> SymbMap.add t (1,0) acc)
| Terms.Var _ -> acc
| Terms.Node (Terms.Leaf hd::tl) ->
let acc =
try let (occ,ar) = SymbMap.find hd acc in
SymbMap.add hd (occ+1,ar) acc
with Not_found -> SymbMap.add hd (1,List.length tl) acc
in List.fold_left aux acc tl
| _ -> assert false
in
match l with
| [] -> acc
| (_,hd,_,_)::tl ->
match hd with
| Terms.Equation (l,r,_,_) ->
parse_symbols (aux (aux acc l) r) tl
| Terms.Predicate _ -> assert false;
;;
let goal_pos t goal =
let rec aux path = function
| Terms.Var _ -> []
| Terms.Leaf x ->
if B.eq t x then path else []
| Terms.Node l ->
match
HExtlib.list_findopt
(fun x i ->
let p = aux (i::path) x in
if p = [] then None else Some p)
l
with
| None -> []
| Some p -> p
in
aux []
(match goal with
| _,Terms.Equation (l,r,ty,_),_,_ -> Terms.Node [ Terms.Leaf B.eqP; ty; l; r ]
| _,Terms.Predicate p,_,_ -> p)
;;
let parse_symbols l goal =
let res = parse_symbols (parse_symbols SymbMap.empty [goal]) l in
SymbMap.fold (fun t (occ,ar) acc ->
(t,occ,ar,goal_occ_nbr t goal,goal_pos t goal)::acc) res []
;;
let rec leaf_count = function
| Terms.Node l -> List.fold_left (fun acc x -> acc + (leaf_count x)) 0 l
| Terms.Leaf _ -> 1
| _ -> 0
;;
let rec dependencies op clauses acc =
match clauses with
| [] -> acc
| (_,lit,_,_)::tl ->
match lit with
| Terms.Predicate _ -> assert false
| Terms.Equation (l,r,_,_) ->
match l,r with
| (Terms.Node (Terms.Leaf op1::_),Terms.Node
(Terms.Leaf op2::_)) ->
if (B.eq op1 op) && not (B.eq op2 op) then
let already = List.exists (B.eq op2) acc in
let occ_l = occ_nbr op l in
let occ_r = occ_nbr op r in
if not already && occ_r > occ_l then
dependencies op tl (op2::acc)
else dependencies op tl acc
else if not (B.eq op1 op) && (B.eq op2 op) then
let already = List.exists (B.eq op1) acc in
let occ_l = occ_nbr op l in
let occ_r = occ_nbr op r in
if not already && occ_l > occ_r then
dependencies op tl (op1::acc)
else
dependencies op tl acc
else dependencies op tl acc
| ((Terms.Node (Terms.Leaf op1::t) as x),y)
| (y,(Terms.Node (Terms.Leaf op1::t) as x)) when leaf_count x > leaf_count y ->
let rec term_leaves = function
| Terms.Node l -> List.fold_left (fun acc x -> acc @ (term_leaves x)) [] l
| Terms.Leaf x -> [x]
| _ -> []
in
if List.mem op (List.filter (fun z -> not (B.eq op1 z)) (term_leaves x)) then
dependencies op tl (op1::acc)
else
dependencies op tl acc
| _ -> dependencies op tl acc
;;
let dependencies op clauses = HExtlib.list_uniq (List.sort Pervasives.compare (dependencies op clauses []));;
let =
end
| null | https://raw.githubusercontent.com/LPCIC/matita/794ed25e6e608b2136ce7fa2963bca4115c7e175/matita/components/ng_paramodulation/stats.ml | ocaml |
||M|| This file is part of HELM , an Hypertextual , Electronic
||A|| Library of Mathematics , developed at the Computer Science
||T|| Department , University of Bologna , Italy .
||I||
||T|| HELM is free software ; you can redistribute it and/or
||A|| modify it under the terms of the GNU General Public License
\ / version 2 or ( at your option ) any later version .
\ / This software is distributed as is , NO WARRANTY .
V _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
||M|| This file is part of HELM, an Hypertextual, Electronic
||A|| Library of Mathematics, developed at the Computer Science
||T|| Department, University of Bologna, Italy.
||I||
||T|| HELM is free software; you can redistribute it and/or
||A|| modify it under the terms of the GNU General Public License
\ / version 2 or (at your option) any later version.
\ / This software is distributed as is, NO WARRANTY.
V_______________________________________________________________ *)
$ I d : stats.ml 9822 2009 - 06 - 03 15:37:06Z denes $
module Stats (B : Terms.Blob) =
struct
module SymbMap = Map.Make(B)
let rec occ_nbr t acc = function
| Terms.Leaf u when B.eq t u -> 1+acc
| Terms.Node l -> List.fold_left (occ_nbr t) acc l
| _ -> acc
;;
let occ_nbr t = occ_nbr t 0;;
let goal_occ_nbr t = function
| (_,Terms.Equation (l,r,_,_),_,_) ->
occ_nbr t l + occ_nbr t r
| _ -> assert false
;;
let rec parse_symbols acc l =
let rec aux acc = function
| Terms.Leaf t ->
(try
let (occ,ar) = SymbMap.find t acc in
SymbMap.add t (occ+1,ar) acc
with Not_found -> SymbMap.add t (1,0) acc)
| Terms.Var _ -> acc
| Terms.Node (Terms.Leaf hd::tl) ->
let acc =
try let (occ,ar) = SymbMap.find hd acc in
SymbMap.add hd (occ+1,ar) acc
with Not_found -> SymbMap.add hd (1,List.length tl) acc
in List.fold_left aux acc tl
| _ -> assert false
in
match l with
| [] -> acc
| (_,hd,_,_)::tl ->
match hd with
| Terms.Equation (l,r,_,_) ->
parse_symbols (aux (aux acc l) r) tl
| Terms.Predicate _ -> assert false;
;;
let goal_pos t goal =
let rec aux path = function
| Terms.Var _ -> []
| Terms.Leaf x ->
if B.eq t x then path else []
| Terms.Node l ->
match
HExtlib.list_findopt
(fun x i ->
let p = aux (i::path) x in
if p = [] then None else Some p)
l
with
| None -> []
| Some p -> p
in
aux []
(match goal with
| _,Terms.Equation (l,r,ty,_),_,_ -> Terms.Node [ Terms.Leaf B.eqP; ty; l; r ]
| _,Terms.Predicate p,_,_ -> p)
;;
let parse_symbols l goal =
let res = parse_symbols (parse_symbols SymbMap.empty [goal]) l in
SymbMap.fold (fun t (occ,ar) acc ->
(t,occ,ar,goal_occ_nbr t goal,goal_pos t goal)::acc) res []
;;
let rec leaf_count = function
| Terms.Node l -> List.fold_left (fun acc x -> acc + (leaf_count x)) 0 l
| Terms.Leaf _ -> 1
| _ -> 0
;;
let rec dependencies op clauses acc =
match clauses with
| [] -> acc
| (_,lit,_,_)::tl ->
match lit with
| Terms.Predicate _ -> assert false
| Terms.Equation (l,r,_,_) ->
match l,r with
| (Terms.Node (Terms.Leaf op1::_),Terms.Node
(Terms.Leaf op2::_)) ->
if (B.eq op1 op) && not (B.eq op2 op) then
let already = List.exists (B.eq op2) acc in
let occ_l = occ_nbr op l in
let occ_r = occ_nbr op r in
if not already && occ_r > occ_l then
dependencies op tl (op2::acc)
else dependencies op tl acc
else if not (B.eq op1 op) && (B.eq op2 op) then
let already = List.exists (B.eq op1) acc in
let occ_l = occ_nbr op l in
let occ_r = occ_nbr op r in
if not already && occ_l > occ_r then
dependencies op tl (op1::acc)
else
dependencies op tl acc
else dependencies op tl acc
| ((Terms.Node (Terms.Leaf op1::t) as x),y)
| (y,(Terms.Node (Terms.Leaf op1::t) as x)) when leaf_count x > leaf_count y ->
let rec term_leaves = function
| Terms.Node l -> List.fold_left (fun acc x -> acc @ (term_leaves x)) [] l
| Terms.Leaf x -> [x]
| _ -> []
in
if List.mem op (List.filter (fun z -> not (B.eq op1 z)) (term_leaves x)) then
dependencies op tl (op1::acc)
else
dependencies op tl acc
| _ -> dependencies op tl acc
;;
let dependencies op clauses = HExtlib.list_uniq (List.sort Pervasives.compare (dependencies op clauses []));;
let =
end
| |
e2e2dd5506d0a37c1639ea8dd5e786e007b7f488a50a77007ab4b5313d218ef1 | gebi/jungerl | lines.erl | The contents of this file are subject to the Erlang Public License ,
Version 1.0 , ( the " License " ) ; you may not use this file except in
%%% compliance with the License. You may obtain a copy of the License at
%%%
%%%
Software distributed under the License is distributed on an " AS IS "
%%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%%% the License for the specific language governing rights and limitations
%%% under the License.
%%%
The Original Code is lines-1.0 .
%%%
The Initial Developer of the Original Code is Ericsson Telecom
AB . Portions created by Ericsson are Copyright ( C ) , 1998 , Ericsson
Telecom AB . All Rights Reserved .
%%%
%%% Contributor(s): ______________________________________.
%%%----------------------------------------------------------------------
# 0 . BASIC INFORMATION
%%%----------------------------------------------------------------------
%%% File: lines.erl
Author : < >
%%% Description : Efficient array of lines (e.g. for text editor)
Fixes : : fixed bug in replace
%%% Modules used : lists
%%%
%%%----------------------------------------------------------------------
%%% Efficient array of lines (e.g. for text editor)
%%% allows for append, as well as insert, replace, delete in any position
%%% with reasonable access times.
Rough benchmarking indicates ( on a 440MHz Ultra ):
%%%
NoOfLines Append ( uSec ) Read ( uSec ) Delete ( uSec )
100 9 7 7
1,000 14 10 11
10,000 22 13 15
100,000 30 16 18
%%%
%%% Comment on the benchmark: The times for Append and Delete are mean
%%% times for "growing file" and "shrinking file", that is, starting from
an empty array and inserting 100,000 lines took ca 3 seconds ; deleting
them took ca 1.8 seconds . The Read test involved accessing all lines
%%% in the full array and calculating the mean time.
%%%
%%% The array doesn't care what goes into each position. In other words,
%%% it can be used for any datatype -- not just lines of text.
%%%----------------------------------------------------------------------
-module(lines).
-vsn('1.0').
-date('00-03-13').
-author('').
-export([new/0, new/1, new/2,
count/1,
nth/2,
append/2,
replace/3,
insert/3,
insert_after/3,
delete/2,
convert_to_list/1,
convert_from_list/1]).
-define(BREAK, 10). % how many lines to store in each leaf
-define(dbg(Fmt, Args), ok=io:format("~p: " ++ Fmt, [?LINE|Args])).
%% new() -> line_array()
%%
%% Creates a new line array.
%%
new() ->
{0, []}.
%% see make_array(N, []).
%%
new(N) ->
new(N, []).
make an array of N lines . Each line will be initialized to DefaultLine .
%% This is _much_ faster and more space efficient than growing an
%% array line by line.
%%
new(N, DefaultLine) when N =< ?BREAK ->
{N, lists:duplicate(N, DefaultLine)};
new(N, DefaultLine) when N =< 2*?BREAK ->
Left = {?BREAK, lists:duplicate(?BREAK,DefaultLine)},
RightN = N - ?BREAK,
Right = {RightN, lists:duplicate(RightN, DefaultLine)},
{N, {Left, Right}};
new(N, DefaultLine) ->
{FullBuckets, RestLeaf, Height} = size_array(N),
FullBucket =
case FullBuckets > 0 of
true ->
{?BREAK, lists:duplicate(?BREAK, DefaultLine)};
false ->
[]
end,
RestBucket = {RestLeaf, lists:duplicate(RestLeaf, DefaultLine)},
{Tree,_,_} = grow_tree(1, Height, FullBuckets, FullBucket, RestBucket),
Tree.
grow_tree(H, Height, TotB, FullB, RestB) when H < Height ->
NextH = H+1,
{{LSz,_}=Left, TotB1, RestB1} =
grow_tree(NextH, Height, TotB, FullB, RestB),
{{RSz,_}=Right, TotB2, RestB2} =
grow_tree(NextH, Height, TotB1, FullB, RestB1),
{{LSz+RSz, {Left,Right}},TotB2,RestB2};
grow_tree(H, H, 0, _, {0,_}=Empty=_RestB) ->
{Empty,0,Empty};
grow_tree(H,H,0,FullB,RestB) ->
{RestB,0,{0,[]}};
grow_tree(H,H,1,FullB,{RestSz,_}=RestB) ->
{{?BREAK+RestSz, {FullB, RestB}}, 0, {0,[]}};
grow_tree(H,H,TotB,FullB,RestB) when TotB > 1 ->
{{2*?BREAK, {FullB,FullB}},TotB-2,RestB}.
size_array(N) ->
FullBuckets = N div ?BREAK,
case N rem ?BREAK of
0 ->
{BMax, Height} = calc_sz(FullBuckets),
{FullBuckets, 0, Height};
RestLeaf ->
{BMax, Height} = calc_sz(FullBuckets+1),
{FullBuckets, RestLeaf, Height}
end.
calc_sz(Buckets) ->
calc_sz(Buckets, Initial=2, Height=1).
calc_sz(N, Sz, Height) when N =< Sz ->
{Sz, Height};
calc_sz(N, Sz, Height) ->
calc_sz(N, Sz + (2 bsl Height), Height+1).
%% line_count(line_array()) -> integer()
%%
%% Returns the number of lines stored in the array
%%
count({N, _}) ->
N.
%% nth(LineNo : integer(), Array : line_array()) -> line()
%%
%% Returns the line in position LineNo
%%
nth(L, _) when L < 1 ->
exit({out_of_range, L});
nth(L, {LMax, _}) when L > LMax ->
exit({out_of_range, L});
nth(L, {LMax, List}) when list(List) ->
lists:nth(L, List);
nth(L, {LMax, {Left = {LL, _}, Right}}) when L > LL ->
nth(L-LL, Right);
nth(L, {_, {Left, _}}) ->
nth(L, Left).
%% append(Line : line(), Array : line_array()) -> line_array().
%%
%% Appends Line to the end of Array.
%% e.g. append(x, [1,2,3,4]) -> [1,2,3,4,x].
%% Returns the modified array.
%%
append(Line, {L, List}) when list(List), L < ?BREAK ->
{L+1, List ++ [Line]};
append(Line, {L, List}) when list(List) ->
{L+1, {{L, List}, {1, [Line]}}};
append(Line, {L, {Left = {LL1, L1}, Right}}) ->
NewRight = append(Line, Right),
balance_left(L+1, Left, NewRight).
replace(LineNo : integer ( ) , Array : line_array ( ) , NewLine : line ( ) ) - >
%% line_array().
%%
Replaces the line in position LineNo with NewLine .
e.g. replace(3 , [ 1,2,3,4 ] , x ) - > [ 1,2,x,4 ] .
%% Returns the modified array.
%%
replace(Lno, _, _) when Lno < 1 ->
exit({out_of_range, Lno});
replace(Lno, {L, _}, NewLine) when Lno > L ->
exit({out_of_range, Lno});
replace(Lno, {L, List}, NewLine) when list(List) ->
{L, replace_nth(Lno, List, NewLine)};
replace(Lno, {L, {Left={LL1, L1}, Right={LL2, L2}}}, NewLine) when Lno > LL1 ->
NewRight = replace(Lno-LL1, Right, NewLine),
{L, {Left, NewRight}};
replace(Lno, {L, {Left={LL1,L1}, Right={LL2,L2}}}, NewLine) ->
NewLeft = replace(Lno, Left, NewLine),
{L, {NewLeft, Right}}.
insert(LineNo : integer ( ) , Array : line_array ( ) , NewLine ) - > line_array ( ) .
%%
%% Inserts NewLine *before* the line in position LineNo.
e.g. insert(3 , [ 1,2,3,4 ] , x ) - > [ 1,2,x,3,4 ] .
%% Returns the modified array.
%%
insert(Lno, _, _) when Lno < 1 ->
exit({out_of_range, Lno});
insert(Lno, {L, _}, NewLine) when Lno > L ->
exit({out_of_range, Lno});
insert(Lno, {L, List}, NewLine) when list(List) ->
if L < ?BREAK ->
{L+1, insert_nth(Lno, List, NewLine)};
true ->
NewList = insert_nth(Lno, List, NewLine),
{L1, L2} = split_at(?BREAK, NewList),
NewL = L+1,
{NewL, {{?BREAK, L1}, {NewL-?BREAK, L2}}}
end;
insert(Lno, {L, {Left={LL,_}, Right}}, NewLine) when Lno > LL ->
NewRight = insert(Lno-LL, Right, NewLine),
balance_left(L+1, Left, NewRight);
insert(Lno, {L, {Left, Right}}, NewLine) ->
NewLeft = insert(Lno, Left, NewLine),
balance_right(L+1, NewLeft, Right).
insert_after(LineNo : integer ( ) , Array : line_array ( ) , NewLine ) - >
%% line_array().
%%
%% Inserts NewLine *after* the line in position LineNo.
%% e.g. insert(3, [1,2,3,4], x) -> [1,2,3,x,4].
%% Returns the modified array.
%%
insert_after(Lno, _, _) when Lno < 0 ->
exit({out_of_range, Lno});
insert_after(Lno, {L, _}, NewLine) when Lno > L ->
exit({out_of_range, Lno});
insert_after(L, {L,_}=Array, NewLine) ->
append(NewLine, Array);
insert_after(Lno, {L, List}, NewLine) when list(List) ->
if L < ?BREAK ->
{L+1, insert_after_nth(Lno, List, NewLine)};
true ->
NewList = insert_after_nth(Lno, List, NewLine),
{L1, L2} = split_at(?BREAK, NewList),
NewL = L+1,
{NewL, {{?BREAK, L1}, {NewL-?BREAK, L2}}}
end;
insert_after(Lno, {L, {Left={LL,_}, Right}}, NewLine) when Lno > LL ->
NewRight = insert_after(Lno-LL, Right, NewLine),
balance_left(L+1, Left, NewRight);
insert_after(Lno, {L, {Left, Right}}, NewLine) ->
NewLeft = insert_after(Lno, Left, NewLine),
balance_right(L+1, NewLeft, Right).
%% delete(LineNo : integer(), Array : line_array()) -> line_array().
%%
%% Deletes the line in position LineNo.
%% e.g. delete(3, [1,2,3,4]) -> [1,2,4].
%% Returns the modified array.
%%
delete(Lno, _) when Lno < 1 ->
exit({out_of_range, Lno});
delete(Lno, {N_Tot, _}) when Lno > N_Tot ->
exit({out_of_range, Lno});
delete(Lno, {N, List}) when list(List) ->
{N-1, delete_nth(Lno, List)};
delete(Lno, {N, {Left = {N_Left, _}, Right}}) when Lno > N_Left ->
case delete(Lno-N_Left, Right) of
{0, _} ->
case N-1 of N_Left -> ok end, % Assert
Left;
NewRight ->
balance_right(N-1, Left, NewRight)
end;
delete(Lno, {N, {Left, Right = {N_Right,_}}}) ->
case delete(Lno, Left) of
{0, _} ->
case N-1 of N_Right -> ok end, % Assert
Right;
NewLeft ->
balance_left(N-1, NewLeft, Right)
end.
convert_to_list({_, List}) when list(List) ->
List;
convert_to_list({L, {Left, Right}}) ->
convert_to_list(Left) ++ convert_to_list(Right).
convert_from_list(L) when list(L) ->
lists:foldl(fun(Ln, Lsx) ->
append(Ln, Lsx)
end, new(), L).
%%% ===========================================================
%%% internal functions
%%% ===========================================================
replace_nth(1, [H|T], X) ->
[X|T];
replace_nth(N, [H|T], X) ->
[H|replace_nth(N-1, T, X)].
insert_nth(1, L, X) ->
[X|L];
insert_nth(N, [H|T], X) ->
[H|insert_nth(N-1, T, X)].
insert_after_nth(1, [H|T], X) ->
[H,X|T];
insert_after_nth(N, [H|T], X) ->
[H|insert_after_nth(N-1, T, X)].
delete_nth(1, [H|T]) ->
T;
delete_nth(N, [H|T]) ->
[H|delete_nth(N-1, T)].
split_at(Pos , List ) - > { List1 , List2 }
split List into two after position Pos ( List1 includes List[Pos ] )
%%
split_at(Pos, L) ->
split_at(Pos, L, []).
split_at(0, L, Acc) ->
{lists:reverse(Acc), L};
split_at(Pos, [H|T], Acc) ->
split_at(Pos-1, T, [H|Acc]).
%% Balancing functions
%% Since we know whether we inserted/deleted in the right or left subtree,
%% we have explicit balancing functions for each case.
We rebalance if the number of elements in one sub - subtree exceeds the
%% sum of elements in the others.
balance_left(N_Tot,
Left = {N_Left, _},
Right = {N_Right, {RLeft = {N_RLeft, _},
RRight = {N_RRight, _}}}) ->
NewN_Left = N_Left + N_RLeft,
if N_RRight > NewN_Left ->
NewLeft = {NewN_Left, {Left, RLeft}},
NewRight = RRight,
{N_Tot, {NewLeft, NewRight}};
true ->
{N_Tot, {Left, Right}}
end;
balance_left(N_Tot, Left, Right) ->
{N_Tot, {Left, Right}}.
balance_right(N_Tot,
Left = {N_Left, {LLeft = {N_LLeft, _},
LRight = {N_LRight, _}}},
Right = {N_Right, _}) ->
NewN_Right = N_Right + N_LRight,
if N_LLeft > NewN_Right ->
NewLeft = LLeft,
NewRight = {NewN_Right, {LRight, Right}},
{N_Tot, {NewLeft, NewRight}};
true ->
{N_Tot, {Left, Right}}
end;
balance_right(N_Tot, Left, Right) ->
{N_Tot, {Left, Right}}.
| null | https://raw.githubusercontent.com/gebi/jungerl/8f5c102295dbe903f47d79fd64714b7de17026ec/lib/lines/src/lines.erl | erlang | compliance with the License. You may obtain a copy of the License at
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
Contributor(s): ______________________________________.
----------------------------------------------------------------------
----------------------------------------------------------------------
File: lines.erl
Description : Efficient array of lines (e.g. for text editor)
Modules used : lists
----------------------------------------------------------------------
Efficient array of lines (e.g. for text editor)
allows for append, as well as insert, replace, delete in any position
with reasonable access times.
Comment on the benchmark: The times for Append and Delete are mean
times for "growing file" and "shrinking file", that is, starting from
in the full array and calculating the mean time.
The array doesn't care what goes into each position. In other words,
it can be used for any datatype -- not just lines of text.
----------------------------------------------------------------------
how many lines to store in each leaf
new() -> line_array()
Creates a new line array.
see make_array(N, []).
This is _much_ faster and more space efficient than growing an
array line by line.
line_count(line_array()) -> integer()
Returns the number of lines stored in the array
nth(LineNo : integer(), Array : line_array()) -> line()
Returns the line in position LineNo
append(Line : line(), Array : line_array()) -> line_array().
Appends Line to the end of Array.
e.g. append(x, [1,2,3,4]) -> [1,2,3,4,x].
Returns the modified array.
line_array().
Returns the modified array.
Inserts NewLine *before* the line in position LineNo.
Returns the modified array.
line_array().
Inserts NewLine *after* the line in position LineNo.
e.g. insert(3, [1,2,3,4], x) -> [1,2,3,x,4].
Returns the modified array.
delete(LineNo : integer(), Array : line_array()) -> line_array().
Deletes the line in position LineNo.
e.g. delete(3, [1,2,3,4]) -> [1,2,4].
Returns the modified array.
Assert
Assert
===========================================================
internal functions
===========================================================
Balancing functions
Since we know whether we inserted/deleted in the right or left subtree,
we have explicit balancing functions for each case.
sum of elements in the others.
| The contents of this file are subject to the Erlang Public License ,
Version 1.0 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
The Original Code is lines-1.0 .
The Initial Developer of the Original Code is Ericsson Telecom
AB . Portions created by Ericsson are Copyright ( C ) , 1998 , Ericsson
Telecom AB . All Rights Reserved .
# 0 . BASIC INFORMATION
Author : < >
Fixes : : fixed bug in replace
Rough benchmarking indicates ( on a 440MHz Ultra ):
NoOfLines Append ( uSec ) Read ( uSec ) Delete ( uSec )
100 9 7 7
1,000 14 10 11
10,000 22 13 15
100,000 30 16 18
an empty array and inserting 100,000 lines took ca 3 seconds ; deleting
them took ca 1.8 seconds . The Read test involved accessing all lines
-module(lines).
-vsn('1.0').
-date('00-03-13').
-author('').
-export([new/0, new/1, new/2,
count/1,
nth/2,
append/2,
replace/3,
insert/3,
insert_after/3,
delete/2,
convert_to_list/1,
convert_from_list/1]).
-define(dbg(Fmt, Args), ok=io:format("~p: " ++ Fmt, [?LINE|Args])).
new() ->
{0, []}.
new(N) ->
new(N, []).
make an array of N lines . Each line will be initialized to DefaultLine .
new(N, DefaultLine) when N =< ?BREAK ->
{N, lists:duplicate(N, DefaultLine)};
new(N, DefaultLine) when N =< 2*?BREAK ->
Left = {?BREAK, lists:duplicate(?BREAK,DefaultLine)},
RightN = N - ?BREAK,
Right = {RightN, lists:duplicate(RightN, DefaultLine)},
{N, {Left, Right}};
new(N, DefaultLine) ->
{FullBuckets, RestLeaf, Height} = size_array(N),
FullBucket =
case FullBuckets > 0 of
true ->
{?BREAK, lists:duplicate(?BREAK, DefaultLine)};
false ->
[]
end,
RestBucket = {RestLeaf, lists:duplicate(RestLeaf, DefaultLine)},
{Tree,_,_} = grow_tree(1, Height, FullBuckets, FullBucket, RestBucket),
Tree.
grow_tree(H, Height, TotB, FullB, RestB) when H < Height ->
NextH = H+1,
{{LSz,_}=Left, TotB1, RestB1} =
grow_tree(NextH, Height, TotB, FullB, RestB),
{{RSz,_}=Right, TotB2, RestB2} =
grow_tree(NextH, Height, TotB1, FullB, RestB1),
{{LSz+RSz, {Left,Right}},TotB2,RestB2};
grow_tree(H, H, 0, _, {0,_}=Empty=_RestB) ->
{Empty,0,Empty};
grow_tree(H,H,0,FullB,RestB) ->
{RestB,0,{0,[]}};
grow_tree(H,H,1,FullB,{RestSz,_}=RestB) ->
{{?BREAK+RestSz, {FullB, RestB}}, 0, {0,[]}};
grow_tree(H,H,TotB,FullB,RestB) when TotB > 1 ->
{{2*?BREAK, {FullB,FullB}},TotB-2,RestB}.
size_array(N) ->
FullBuckets = N div ?BREAK,
case N rem ?BREAK of
0 ->
{BMax, Height} = calc_sz(FullBuckets),
{FullBuckets, 0, Height};
RestLeaf ->
{BMax, Height} = calc_sz(FullBuckets+1),
{FullBuckets, RestLeaf, Height}
end.
calc_sz(Buckets) ->
calc_sz(Buckets, Initial=2, Height=1).
calc_sz(N, Sz, Height) when N =< Sz ->
{Sz, Height};
calc_sz(N, Sz, Height) ->
calc_sz(N, Sz + (2 bsl Height), Height+1).
count({N, _}) ->
N.
nth(L, _) when L < 1 ->
exit({out_of_range, L});
nth(L, {LMax, _}) when L > LMax ->
exit({out_of_range, L});
nth(L, {LMax, List}) when list(List) ->
lists:nth(L, List);
nth(L, {LMax, {Left = {LL, _}, Right}}) when L > LL ->
nth(L-LL, Right);
nth(L, {_, {Left, _}}) ->
nth(L, Left).
append(Line, {L, List}) when list(List), L < ?BREAK ->
{L+1, List ++ [Line]};
append(Line, {L, List}) when list(List) ->
{L+1, {{L, List}, {1, [Line]}}};
append(Line, {L, {Left = {LL1, L1}, Right}}) ->
NewRight = append(Line, Right),
balance_left(L+1, Left, NewRight).
replace(LineNo : integer ( ) , Array : line_array ( ) , NewLine : line ( ) ) - >
Replaces the line in position LineNo with NewLine .
e.g. replace(3 , [ 1,2,3,4 ] , x ) - > [ 1,2,x,4 ] .
replace(Lno, _, _) when Lno < 1 ->
exit({out_of_range, Lno});
replace(Lno, {L, _}, NewLine) when Lno > L ->
exit({out_of_range, Lno});
replace(Lno, {L, List}, NewLine) when list(List) ->
{L, replace_nth(Lno, List, NewLine)};
replace(Lno, {L, {Left={LL1, L1}, Right={LL2, L2}}}, NewLine) when Lno > LL1 ->
NewRight = replace(Lno-LL1, Right, NewLine),
{L, {Left, NewRight}};
replace(Lno, {L, {Left={LL1,L1}, Right={LL2,L2}}}, NewLine) ->
NewLeft = replace(Lno, Left, NewLine),
{L, {NewLeft, Right}}.
insert(LineNo : integer ( ) , Array : line_array ( ) , NewLine ) - > line_array ( ) .
e.g. insert(3 , [ 1,2,3,4 ] , x ) - > [ 1,2,x,3,4 ] .
insert(Lno, _, _) when Lno < 1 ->
exit({out_of_range, Lno});
insert(Lno, {L, _}, NewLine) when Lno > L ->
exit({out_of_range, Lno});
insert(Lno, {L, List}, NewLine) when list(List) ->
if L < ?BREAK ->
{L+1, insert_nth(Lno, List, NewLine)};
true ->
NewList = insert_nth(Lno, List, NewLine),
{L1, L2} = split_at(?BREAK, NewList),
NewL = L+1,
{NewL, {{?BREAK, L1}, {NewL-?BREAK, L2}}}
end;
insert(Lno, {L, {Left={LL,_}, Right}}, NewLine) when Lno > LL ->
NewRight = insert(Lno-LL, Right, NewLine),
balance_left(L+1, Left, NewRight);
insert(Lno, {L, {Left, Right}}, NewLine) ->
NewLeft = insert(Lno, Left, NewLine),
balance_right(L+1, NewLeft, Right).
insert_after(LineNo : integer ( ) , Array : line_array ( ) , NewLine ) - >
insert_after(Lno, _, _) when Lno < 0 ->
exit({out_of_range, Lno});
insert_after(Lno, {L, _}, NewLine) when Lno > L ->
exit({out_of_range, Lno});
insert_after(L, {L,_}=Array, NewLine) ->
append(NewLine, Array);
insert_after(Lno, {L, List}, NewLine) when list(List) ->
if L < ?BREAK ->
{L+1, insert_after_nth(Lno, List, NewLine)};
true ->
NewList = insert_after_nth(Lno, List, NewLine),
{L1, L2} = split_at(?BREAK, NewList),
NewL = L+1,
{NewL, {{?BREAK, L1}, {NewL-?BREAK, L2}}}
end;
insert_after(Lno, {L, {Left={LL,_}, Right}}, NewLine) when Lno > LL ->
NewRight = insert_after(Lno-LL, Right, NewLine),
balance_left(L+1, Left, NewRight);
insert_after(Lno, {L, {Left, Right}}, NewLine) ->
NewLeft = insert_after(Lno, Left, NewLine),
balance_right(L+1, NewLeft, Right).
delete(Lno, _) when Lno < 1 ->
exit({out_of_range, Lno});
delete(Lno, {N_Tot, _}) when Lno > N_Tot ->
exit({out_of_range, Lno});
delete(Lno, {N, List}) when list(List) ->
{N-1, delete_nth(Lno, List)};
delete(Lno, {N, {Left = {N_Left, _}, Right}}) when Lno > N_Left ->
case delete(Lno-N_Left, Right) of
{0, _} ->
Left;
NewRight ->
balance_right(N-1, Left, NewRight)
end;
delete(Lno, {N, {Left, Right = {N_Right,_}}}) ->
case delete(Lno, Left) of
{0, _} ->
Right;
NewLeft ->
balance_left(N-1, NewLeft, Right)
end.
convert_to_list({_, List}) when list(List) ->
List;
convert_to_list({L, {Left, Right}}) ->
convert_to_list(Left) ++ convert_to_list(Right).
convert_from_list(L) when list(L) ->
lists:foldl(fun(Ln, Lsx) ->
append(Ln, Lsx)
end, new(), L).
replace_nth(1, [H|T], X) ->
[X|T];
replace_nth(N, [H|T], X) ->
[H|replace_nth(N-1, T, X)].
insert_nth(1, L, X) ->
[X|L];
insert_nth(N, [H|T], X) ->
[H|insert_nth(N-1, T, X)].
insert_after_nth(1, [H|T], X) ->
[H,X|T];
insert_after_nth(N, [H|T], X) ->
[H|insert_after_nth(N-1, T, X)].
delete_nth(1, [H|T]) ->
T;
delete_nth(N, [H|T]) ->
[H|delete_nth(N-1, T)].
split_at(Pos , List ) - > { List1 , List2 }
split List into two after position Pos ( List1 includes List[Pos ] )
split_at(Pos, L) ->
split_at(Pos, L, []).
split_at(0, L, Acc) ->
{lists:reverse(Acc), L};
split_at(Pos, [H|T], Acc) ->
split_at(Pos-1, T, [H|Acc]).
We rebalance if the number of elements in one sub - subtree exceeds the
balance_left(N_Tot,
Left = {N_Left, _},
Right = {N_Right, {RLeft = {N_RLeft, _},
RRight = {N_RRight, _}}}) ->
NewN_Left = N_Left + N_RLeft,
if N_RRight > NewN_Left ->
NewLeft = {NewN_Left, {Left, RLeft}},
NewRight = RRight,
{N_Tot, {NewLeft, NewRight}};
true ->
{N_Tot, {Left, Right}}
end;
balance_left(N_Tot, Left, Right) ->
{N_Tot, {Left, Right}}.
balance_right(N_Tot,
Left = {N_Left, {LLeft = {N_LLeft, _},
LRight = {N_LRight, _}}},
Right = {N_Right, _}) ->
NewN_Right = N_Right + N_LRight,
if N_LLeft > NewN_Right ->
NewLeft = LLeft,
NewRight = {NewN_Right, {LRight, Right}},
{N_Tot, {NewLeft, NewRight}};
true ->
{N_Tot, {Left, Right}}
end;
balance_right(N_Tot, Left, Right) ->
{N_Tot, {Left, Right}}.
|
4983fd420a91af57e4098b35fc2ccaaf6ba18a92296b3de2cc3a68cbf1cf1870 | libre-man/cl-transmission | cl-transmission.lisp | (in-package :cl-user)
(defpackage cl-transmission-test
(:use :cl
:cl-transmission
:prove))
(in-package :cl-transmission-test)
;; NOTE: To run this test file, execute `(asdf:test-system :cl-transmission)' in your Lisp.
(plan nil)
;; blah blah blah.
(finalize)
| null | https://raw.githubusercontent.com/libre-man/cl-transmission/4bbf1d2761bfa5dfa79b7bc12c3238089b994d95/t/cl-transmission.lisp | lisp | NOTE: To run this test file, execute `(asdf:test-system :cl-transmission)' in your Lisp.
blah blah blah. | (in-package :cl-user)
(defpackage cl-transmission-test
(:use :cl
:cl-transmission
:prove))
(in-package :cl-transmission-test)
(plan nil)
(finalize)
|
abe7bfffe2c4c63f8a68d211a29e02079b3c059e7b4e1b89d1fda601f4b2e48d | dgtized/shimmers | wave.cljc | (ns shimmers.math.wave)
;;
;; Consider implementing cycloid and pulse-wave as well
(defn square
"Square wave function from -1 to 1 with frequency `f`"
[f t]
(+ (* 2 (- (* 2 (Math/floor (* f t)))
(Math/floor (* 2 f t)))) 1))
(defn sawtooth
"Sawtooth wave function from -1 to 1 over period `p`."
[p t]
(let [f (/ t p)]
(* 2 (- f (Math/floor (+ 0.5 f))))))
(defn triangle
"Linear wave function from -1 to 1 over period `p`."
[p t]
(let [f (Math/floor (+ (/ (* 2 t) p) 0.5))]
(* (/ 4 p) (- t (* (/ p 2) f)) (Math/pow -1 f))))
(defn triangle01 [p t]
(* 2 (abs (- (/ t p) (Math/floor (+ (/ t p) (/ 1 2)))))))
(comment
(map (fn [t] [t (triangle01 1 t)]) (range -1 1 0.1)))
| null | https://raw.githubusercontent.com/dgtized/shimmers/15d64c103f66496663b7698a50b974aedeee286f/src/shimmers/math/wave.cljc | clojure |
Consider implementing cycloid and pulse-wave as well | (ns shimmers.math.wave)
(defn square
"Square wave function from -1 to 1 with frequency `f`"
[f t]
(+ (* 2 (- (* 2 (Math/floor (* f t)))
(Math/floor (* 2 f t)))) 1))
(defn sawtooth
"Sawtooth wave function from -1 to 1 over period `p`."
[p t]
(let [f (/ t p)]
(* 2 (- f (Math/floor (+ 0.5 f))))))
(defn triangle
"Linear wave function from -1 to 1 over period `p`."
[p t]
(let [f (Math/floor (+ (/ (* 2 t) p) 0.5))]
(* (/ 4 p) (- t (* (/ p 2) f)) (Math/pow -1 f))))
(defn triangle01 [p t]
(* 2 (abs (- (/ t p) (Math/floor (+ (/ t p) (/ 1 2)))))))
(comment
(map (fn [t] [t (triangle01 1 t)]) (range -1 1 0.1)))
|
f5d18d9011e3b40ea7ef5273e9e1d079f89f6df71e7eb2ed0b0d5254d8c2849c | norm2782/NanoProlog | ParserUUTC.hs | module Language.Prolog.NanoProlog.ParserUUTC (
pFun
, pRule
, pTerm
, pCons
, pTerms
, startParse
) where
import Control.Applicative ((<**>))
import Language.Prolog.NanoProlog.NanoProlog
import ParseLib.Abstract hiding ( token, symbol )
import qualified ParseLib.Abstract as PL ( token, symbol )
spaces :: Parser Char String
spaces = many (choice [PL.symbol ' ', PL.symbol '\r', PL.symbol '\n', PL.symbol '\t'])
token :: String -> Parser Char String
token t = PL.token t <* spaces
symbol :: Char -> Parser Char Char
symbol c = PL.symbol c <* spaces
lexeme :: Parser Char a -> Parser Char a
lexeme p = p <* spaces
pDot :: Parser Char Char
pDot = symbol '.'
pSepDot :: Parser Char String -> Parser Char [String]
pSepDot p = (:) <$> p <*> many ((:) <$> pDot <*> p)
pChainr :: Parser s (a -> a -> a) -> Parser s a -> Parser s a
pChainr op x = r
where r = x <??> (flip <$> op <*> r)
(<??>) :: Parser s b -> Parser s (b -> b) -> Parser s b
p <??> q = p <**> (q `opt` id)
pTerm, pFactor, pCons, pVar, pFun :: Parser Char Term
pTerm = pChainr ((\f a -> Fun "->" [f, a]) <$ token "->") pCons
pCons = pChainr ((\h t -> Fun "cons" [h, t]) <$ symbol ':') pFactor
pFactor = pVar
<|> pFun
<|> parenthesised pTerm
pFun = Fun <$> pLowerCase <*> (parenthesised pTerms `opt` [])
<|> Fun "[]" <$> bracketed ((:[]) <$> pTerm)
pVar = Var <$> lexeme ((++) <$> many1 pUpper <*> (concat <$> pSepDot (many1 pDigit) `opt` []))
pRange :: (Enum a, Eq a) => (a, a) -> Parser a a
pRange (b, e) = choice (map PL.symbol [b..e])
pUpper, pLower, pLetter, pDigit :: Parser Char Char
pUpper = pRange ('A', 'Z')
pLower = pRange ('a', 'z')
pLetter = pUpper <|> pLower
pDigit = pRange ('0', '9')
pLowerCase :: Parser Char String
pLowerCase = lexeme ((:) <$> pLower <*> many (pLetter <|> pDigit))
pTerms :: Parser Char [Term]
pTerms = listOf pTerm (symbol ',')
pRule :: Parser Char Rule
pRule = (:<-:) <$> pFun <*> ((token ":-" *> pTerms) `opt` []) <* pDot
startParse :: Parser s a -> [s] -> [(a,[s])]
startParse p = parse (p <* eof)
opt :: Parser s a -> a -> Parser s a
opt p v = p <<|> pure v
| null | https://raw.githubusercontent.com/norm2782/NanoProlog/30b3165fe462252ba6d8aafce9a4ce783aa3e066/src/Language/Prolog/NanoProlog/ParserUUTC.hs | haskell | module Language.Prolog.NanoProlog.ParserUUTC (
pFun
, pRule
, pTerm
, pCons
, pTerms
, startParse
) where
import Control.Applicative ((<**>))
import Language.Prolog.NanoProlog.NanoProlog
import ParseLib.Abstract hiding ( token, symbol )
import qualified ParseLib.Abstract as PL ( token, symbol )
spaces :: Parser Char String
spaces = many (choice [PL.symbol ' ', PL.symbol '\r', PL.symbol '\n', PL.symbol '\t'])
token :: String -> Parser Char String
token t = PL.token t <* spaces
symbol :: Char -> Parser Char Char
symbol c = PL.symbol c <* spaces
lexeme :: Parser Char a -> Parser Char a
lexeme p = p <* spaces
pDot :: Parser Char Char
pDot = symbol '.'
pSepDot :: Parser Char String -> Parser Char [String]
pSepDot p = (:) <$> p <*> many ((:) <$> pDot <*> p)
pChainr :: Parser s (a -> a -> a) -> Parser s a -> Parser s a
pChainr op x = r
where r = x <??> (flip <$> op <*> r)
(<??>) :: Parser s b -> Parser s (b -> b) -> Parser s b
p <??> q = p <**> (q `opt` id)
pTerm, pFactor, pCons, pVar, pFun :: Parser Char Term
pTerm = pChainr ((\f a -> Fun "->" [f, a]) <$ token "->") pCons
pCons = pChainr ((\h t -> Fun "cons" [h, t]) <$ symbol ':') pFactor
pFactor = pVar
<|> pFun
<|> parenthesised pTerm
pFun = Fun <$> pLowerCase <*> (parenthesised pTerms `opt` [])
<|> Fun "[]" <$> bracketed ((:[]) <$> pTerm)
pVar = Var <$> lexeme ((++) <$> many1 pUpper <*> (concat <$> pSepDot (many1 pDigit) `opt` []))
pRange :: (Enum a, Eq a) => (a, a) -> Parser a a
pRange (b, e) = choice (map PL.symbol [b..e])
pUpper, pLower, pLetter, pDigit :: Parser Char Char
pUpper = pRange ('A', 'Z')
pLower = pRange ('a', 'z')
pLetter = pUpper <|> pLower
pDigit = pRange ('0', '9')
pLowerCase :: Parser Char String
pLowerCase = lexeme ((:) <$> pLower <*> many (pLetter <|> pDigit))
pTerms :: Parser Char [Term]
pTerms = listOf pTerm (symbol ',')
pRule :: Parser Char Rule
pRule = (:<-:) <$> pFun <*> ((token ":-" *> pTerms) `opt` []) <* pDot
startParse :: Parser s a -> [s] -> [(a,[s])]
startParse p = parse (p <* eof)
opt :: Parser s a -> a -> Parser s a
opt p v = p <<|> pure v
| |
7a0248cf1f6490c2da8351fb3936179cdee956cc0db032bcdb1fd788621d1d10 | xh4/web-toolkit | run.lisp | ;;;; -*- Mode: Lisp; indent-tabs-mode: nil -*-
(in-package :it.bese.fiveam)
;;;; * Running Tests
;;;; Once the programmer has defined what the tests are these need to
;;;; be run and the expected effects should be compared with the
;;;; actual effects. FiveAM provides the function RUN for this
;;;; purpose, RUN executes a number of tests and collects the results
;;;; of each individual check into a list which is then
returned . There are three types of test results : passed , failed
;;;; and skipped, these are represented by TEST-RESULT objects.
Generally running a test will return normally , but there are two
;;;; exceptional situations which can occur:
;;;; - An exception is signaled while running the test. If the
;;;; variable *on-error* is :DEBUG than FiveAM will enter the
;;;; debugger, otherwise a test failure (of type
;;;; unexpected-test-failure) is returned. When entering the
debugger two restarts are made available , one simply reruns the
;;;; current test and another signals a test-failure and continues
;;;; with the remaining tests.
;;;; - A circular dependency is detected. An error is signaled and a
;;;; restart is made available which signals a test-skipped and
;;;; continues with the remaining tests. This restart also sets the
;;;; dependency status of the test to nil, so any tests which depend
;;;; on this one (even if the dependency is not circular) will be
;;;; skipped.
;;;; The functions RUN!, !, !! and !!! are convenient wrappers around
;;;; RUN and EXPLAIN.
(deftype on-problem-action ()
'(member :debug :backtrace nil))
(declaim (type on-problem-action *on-error* *on-failure*))
(defvar *on-error* nil
"The action to perform on error:
- :DEBUG if we should drop into the debugger
- :BACKTRACE to print a backtrace
- NIL to simply continue")
(defvar *on-failure* nil
"The action to perform on check failure:
- :DEBUG if we should drop into the debugger
- :BACKTRACE to print a backtrace
- NIL to simply continue")
(defvar *debug-on-error* nil
"T if we should drop into the debugger on error, NIL otherwise.
OBSOLETE: superseded by *ON-ERROR*")
(defvar *debug-on-failure* nil
"T if we should drop into the debugger on a failing check, NIL otherwise.
OBSOLETE: superseded by *ON-FAILURE*")
(defparameter *print-names* t
"T if we should print test running progress, NIL otherwise.")
(defparameter *test-dribble-indent* (make-array 0
:element-type 'character
:fill-pointer 0
:adjustable t)
"Used to indent tests and test suites in their parent suite")
(defun import-testing-symbols (package-designator)
(import '(5am::is 5am::is-true 5am::is-false 5am::signals 5am::finishes)
package-designator))
(defparameter *run-queue* '()
"List of test waiting to be run.")
(define-condition circular-dependency (error)
((test-case :initarg :test-case))
(:report (lambda (cd stream)
(format stream "A circular dependency wes detected in ~S." (slot-value cd 'test-case))))
(:documentation "Condition signaled when a circular dependency
between test-cases has been detected."))
(defgeneric run-resolving-dependencies (test)
(:documentation "Given a dependency spec determine if the spec
is satisfied or not, this will generally involve running other
tests. If the dependency spec can be satisfied the test is also
run."))
(defmethod run-resolving-dependencies ((test test-case))
"Return true if this test, and its dependencies, are satisfied,
NIL otherwise."
(case (status test)
(:unknown
(setf (status test) :resolving)
(if (or (not (depends-on test))
(eql t (resolve-dependencies (depends-on test))))
(progn
(run-test-lambda test)
(status test))
(with-run-state (result-list)
(unless (eql :circular (status test))
(push (make-instance 'test-skipped
:test-case test
:reason "Dependencies not satisfied")
result-list)
(setf (status test) :depends-not-satisfied)))))
(:resolving
(restart-case
(error 'circular-dependency :test-case test)
(skip ()
:report (lambda (s)
(format s "Skip the test ~S and all its dependencies." (name test)))
(with-run-state (result-list)
(push (make-instance 'test-skipped :reason "Circular dependencies" :test-case test)
result-list))
(setf (status test) :circular))))
(t (status test))))
(defgeneric resolve-dependencies (depends-on))
(defmethod resolve-dependencies ((depends-on symbol))
"A test which depends on a symbol is interpreted as `(AND
,DEPENDS-ON)."
(run-resolving-dependencies (get-test depends-on)))
(defmethod resolve-dependencies ((depends-on list))
"Return true if the dependency spec DEPENDS-ON is satisfied,
nil otherwise."
(if (null depends-on)
t
(flet ((satisfies-depends-p (test)
(funcall test (lambda (dep)
(eql t (resolve-dependencies dep)))
(cdr depends-on))))
(ecase (car depends-on)
(and (satisfies-depends-p #'every))
(or (satisfies-depends-p #'some))
(not (satisfies-depends-p #'notany))
(:before (every #'(lambda (dep)
(let ((status (status (get-test dep))))
(if (eql :unknown status)
(run-resolving-dependencies (get-test dep))
status)))
(cdr depends-on)))))))
(defun results-status (result-list)
"Given a list of test results (generated while running a test)
return true if no results are of type TEST-FAILURE. Returns second
and third values, which are the set of failed tests and skipped
tests respectively."
(let ((failed-tests
(remove-if-not #'test-failure-p result-list))
(skipped-tests
(remove-if-not #'test-skipped-p result-list)))
(values (null failed-tests)
failed-tests
skipped-tests)))
(defun return-result-list (test-lambda)
"Run the test function TEST-LAMBDA and return a list of all
test results generated, does not modify the special environment
variable RESULT-LIST."
(bind-run-state ((result-list '()))
(funcall test-lambda)
result-list))
(defgeneric run-test-lambda (test))
(defmethod run-test-lambda ((test test-case))
(with-run-state (result-list)
(bind-run-state ((current-test test))
(labels ((abort-test (e &optional (reason (format nil "Unexpected Error: ~S~%~A." e e)))
(add-result 'unexpected-test-failure
:test-expr nil
:test-case test
:reason reason
:condition e))
(run-it ()
(let ((result-list '()))
(declare (special result-list))
(handler-bind ((check-failure (lambda (e)
(declare (ignore e))
(cond
((eql *on-failure* :debug)
nil)
(t
(when (eql *on-failure* :backtrace)
(trivial-backtrace:print-backtrace-to-stream
*test-dribble*))
(invoke-restart
(find-restart 'ignore-failure))))))
(error (lambda (e)
(unless (or (eql *on-error* :debug)
(typep e 'check-failure))
(when (eql *on-error* :backtrace)
(trivial-backtrace:print-backtrace-to-stream
*test-dribble*))
(abort-test e)
(return-from run-it result-list)))))
(restart-case
(handler-case
(let ((*readtable* (copy-readtable))
(*package* (runtime-package test)))
(when *print-names*
(format *test-dribble* "~%~ARunning test ~A " *test-dribble-indent* (name test)))
(if (collect-profiling-info test)
Timing info does n't get collected ATM , we need a portable library
( setf ( profiling - info test ) ( collect - timing ( test - lambda test ) ) )
(funcall (test-lambda test))
(funcall (test-lambda test))))
(storage-condition (e)
;; heap-exhausted/constrol-stack-exhausted
;; handler-case unwinds the stack (unlike handler-bind)
(abort-test e (format nil "STORAGE-CONDITION: aborted for safety. ~S~%~A." e e))
(return-from run-it result-list)))
(retest ()
:report (lambda (stream)
(format stream "~@<Rerun the test ~S~@:>" test))
(return-from run-it (run-it)))
(ignore ()
:report (lambda (stream)
(format stream "~@<Signal an exceptional test failure and abort the test ~S.~@:>" test))
(abort-test (make-instance 'test-failure :test-case test
:reason "Failure restart."))))
result-list))))
(let ((results (run-it)))
(setf (status test) (results-status results)
result-list (nconc result-list results)))))))
(defgeneric %run (test-spec)
(:documentation "Internal method for running a test. Does not
update the status of the tests nor the special variables !,
!!, !!!"))
(defmethod %run ((test test-case))
(run-resolving-dependencies test))
(defmethod %run ((tests list))
(mapc #'%run tests))
(defmethod %run ((suite test-suite))
(when *print-names*
(format *test-dribble* "~%~ARunning test suite ~A" *test-dribble-indent* (name suite)))
(let ((suite-results '()))
(flet ((run-tests ()
(loop
for test being the hash-values of (tests suite)
do (%run test))))
(vector-push-extend #\space *test-dribble-indent*)
(unwind-protect
(bind-run-state ((result-list '()))
(unwind-protect
(if (collect-profiling-info suite)
Timing info does n't get collected ATM , we need a portable library
( setf ( profiling - info suite ) ( collect - timing # ' run - tests ) )
(run-tests)
(run-tests)))
(setf suite-results result-list
(status suite) (every #'test-passed-p suite-results)))
(vector-pop *test-dribble-indent*)
(with-run-state (result-list)
(setf result-list (nconc result-list suite-results)))))))
(defmethod %run ((test-name symbol))
(when-let (test (get-test test-name))
(%run test)))
(defvar *initial-!* (lambda () (format t "Haven't run that many tests yet.~%")))
(defvar *!* *initial-!*)
(defvar *!!* *initial-!*)
(defvar *!!!* *initial-!*)
;;;; ** Public entry points
(defun run! (&optional (test-spec *suite*)
&key ((:print-names *print-names*) *print-names*))
"Equivalent to (explain! (run TEST-SPEC))."
(explain! (run test-spec)))
(defun explain! (result-list)
"Explain the results of RESULT-LIST using a
detailed-text-explainer with output going to *test-dribble*.
Return a boolean indicating whether no tests failed."
(explain (make-instance 'detailed-text-explainer) result-list *test-dribble*)
(results-status result-list))
(defun debug! (&optional (test-spec *suite*))
"Calls (run! test-spec) but enters the debugger if any kind of error happens."
(let ((*on-error* :debug)
(*on-failure* :debug))
(run! test-spec)))
(defun run (test-spec &key ((:print-names *print-names*) *print-names*))
"Run the test specified by TEST-SPEC.
TEST-SPEC can be either a symbol naming a test or test suite, or
a testable-object object. This function changes the operations
performed by the !, !! and !!! functions."
(psetf *!* (lambda ()
(loop :for test :being :the :hash-keys :of *test*
:do (setf (status (get-test test)) :unknown))
(bind-run-state ((result-list '()))
(with-simple-restart (explain "Ignore the rest of the tests and explain current results")
(%run test-spec))
result-list))
*!!* *!*
*!!!* *!!*)
(let ((*on-error*
(or *on-error* (cond
(*debug-on-error*
(format *test-dribble* "*DEBUG-ON-ERROR* is obsolete. Use *ON-ERROR*.")
:debug)
(t nil))))
(*on-failure*
(or *on-failure* (cond
(*debug-on-failure*
(format *test-dribble* "*DEBUG-ON-FAILURE* is obsolete. Use *ON-FAILURE*.")
:debug)
(t nil)))))
(funcall *!*)))
(defun ! ()
"Rerun the most recently run test and explain the results."
(explain! (funcall *!*)))
(defun !! ()
"Rerun the second most recently run test and explain the results."
(explain! (funcall *!!*)))
(defun !!! ()
"Rerun the third most recently run test and explain the results."
(explain! (funcall *!!!*)))
(defun run-all-tests (&key (summary :end))
"Runs all defined test suites, T if all tests passed and NIL otherwise.
SUMMARY can be :END to print a summary at the end, :SUITE to print it
after each suite or NIL to skip explanations."
(check-type summary (member nil :suite :end))
(loop :for suite :in (cons 'nil (sort (copy-list *toplevel-suites*) #'string<=))
:for results := (if (suite-emptyp suite) nil (run suite))
:when (consp results)
:collect results :into all-results
:do (cond
((not (eql summary :suite))
nil)
(results
(explain! results))
(suite
(format *test-dribble* "Suite ~A is empty~%" suite)))
:finally (progn
(when (eql summary :end)
(explain! (alexandria:flatten all-results)))
(return (every #'results-status all-results)))))
Copyright ( c ) 2002 - 2003 ,
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions are
;; met:
;;
;; - Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;;
;; - Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in the
;; documentation and/or other materials provided with the distribution.
;;
- Neither the name of , nor , nor the names
;; of its contributors may be used to endorse or promote products
;; derived from this software without specific prior written permission.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE ,
;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
| null | https://raw.githubusercontent.com/xh4/web-toolkit/e510d44a25b36ca8acd66734ed1ee9f5fe6ecd09/vendor/fiveam-v1.4.1/src/run.lisp | lisp | -*- Mode: Lisp; indent-tabs-mode: nil -*-
* Running Tests
Once the programmer has defined what the tests are these need to
be run and the expected effects should be compared with the
actual effects. FiveAM provides the function RUN for this
purpose, RUN executes a number of tests and collects the results
of each individual check into a list which is then
and skipped, these are represented by TEST-RESULT objects.
exceptional situations which can occur:
- An exception is signaled while running the test. If the
variable *on-error* is :DEBUG than FiveAM will enter the
debugger, otherwise a test failure (of type
unexpected-test-failure) is returned. When entering the
current test and another signals a test-failure and continues
with the remaining tests.
- A circular dependency is detected. An error is signaled and a
restart is made available which signals a test-skipped and
continues with the remaining tests. This restart also sets the
dependency status of the test to nil, so any tests which depend
on this one (even if the dependency is not circular) will be
skipped.
The functions RUN!, !, !! and !!! are convenient wrappers around
RUN and EXPLAIN.
heap-exhausted/constrol-stack-exhausted
handler-case unwinds the stack (unlike handler-bind)
** Public entry points
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
LOSS OF USE ,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
(in-package :it.bese.fiveam)
returned . There are three types of test results : passed , failed
Generally running a test will return normally , but there are two
debugger two restarts are made available , one simply reruns the
(deftype on-problem-action ()
'(member :debug :backtrace nil))
(declaim (type on-problem-action *on-error* *on-failure*))
(defvar *on-error* nil
"The action to perform on error:
- :DEBUG if we should drop into the debugger
- :BACKTRACE to print a backtrace
- NIL to simply continue")
(defvar *on-failure* nil
"The action to perform on check failure:
- :DEBUG if we should drop into the debugger
- :BACKTRACE to print a backtrace
- NIL to simply continue")
(defvar *debug-on-error* nil
"T if we should drop into the debugger on error, NIL otherwise.
OBSOLETE: superseded by *ON-ERROR*")
(defvar *debug-on-failure* nil
"T if we should drop into the debugger on a failing check, NIL otherwise.
OBSOLETE: superseded by *ON-FAILURE*")
(defparameter *print-names* t
"T if we should print test running progress, NIL otherwise.")
(defparameter *test-dribble-indent* (make-array 0
:element-type 'character
:fill-pointer 0
:adjustable t)
"Used to indent tests and test suites in their parent suite")
(defun import-testing-symbols (package-designator)
(import '(5am::is 5am::is-true 5am::is-false 5am::signals 5am::finishes)
package-designator))
(defparameter *run-queue* '()
"List of test waiting to be run.")
(define-condition circular-dependency (error)
((test-case :initarg :test-case))
(:report (lambda (cd stream)
(format stream "A circular dependency wes detected in ~S." (slot-value cd 'test-case))))
(:documentation "Condition signaled when a circular dependency
between test-cases has been detected."))
(defgeneric run-resolving-dependencies (test)
(:documentation "Given a dependency spec determine if the spec
is satisfied or not, this will generally involve running other
tests. If the dependency spec can be satisfied the test is also
run."))
(defmethod run-resolving-dependencies ((test test-case))
"Return true if this test, and its dependencies, are satisfied,
NIL otherwise."
(case (status test)
(:unknown
(setf (status test) :resolving)
(if (or (not (depends-on test))
(eql t (resolve-dependencies (depends-on test))))
(progn
(run-test-lambda test)
(status test))
(with-run-state (result-list)
(unless (eql :circular (status test))
(push (make-instance 'test-skipped
:test-case test
:reason "Dependencies not satisfied")
result-list)
(setf (status test) :depends-not-satisfied)))))
(:resolving
(restart-case
(error 'circular-dependency :test-case test)
(skip ()
:report (lambda (s)
(format s "Skip the test ~S and all its dependencies." (name test)))
(with-run-state (result-list)
(push (make-instance 'test-skipped :reason "Circular dependencies" :test-case test)
result-list))
(setf (status test) :circular))))
(t (status test))))
(defgeneric resolve-dependencies (depends-on))
(defmethod resolve-dependencies ((depends-on symbol))
"A test which depends on a symbol is interpreted as `(AND
,DEPENDS-ON)."
(run-resolving-dependencies (get-test depends-on)))
(defmethod resolve-dependencies ((depends-on list))
"Return true if the dependency spec DEPENDS-ON is satisfied,
nil otherwise."
(if (null depends-on)
t
(flet ((satisfies-depends-p (test)
(funcall test (lambda (dep)
(eql t (resolve-dependencies dep)))
(cdr depends-on))))
(ecase (car depends-on)
(and (satisfies-depends-p #'every))
(or (satisfies-depends-p #'some))
(not (satisfies-depends-p #'notany))
(:before (every #'(lambda (dep)
(let ((status (status (get-test dep))))
(if (eql :unknown status)
(run-resolving-dependencies (get-test dep))
status)))
(cdr depends-on)))))))
(defun results-status (result-list)
"Given a list of test results (generated while running a test)
return true if no results are of type TEST-FAILURE. Returns second
and third values, which are the set of failed tests and skipped
tests respectively."
(let ((failed-tests
(remove-if-not #'test-failure-p result-list))
(skipped-tests
(remove-if-not #'test-skipped-p result-list)))
(values (null failed-tests)
failed-tests
skipped-tests)))
(defun return-result-list (test-lambda)
"Run the test function TEST-LAMBDA and return a list of all
test results generated, does not modify the special environment
variable RESULT-LIST."
(bind-run-state ((result-list '()))
(funcall test-lambda)
result-list))
(defgeneric run-test-lambda (test))
(defmethod run-test-lambda ((test test-case))
(with-run-state (result-list)
(bind-run-state ((current-test test))
(labels ((abort-test (e &optional (reason (format nil "Unexpected Error: ~S~%~A." e e)))
(add-result 'unexpected-test-failure
:test-expr nil
:test-case test
:reason reason
:condition e))
(run-it ()
(let ((result-list '()))
(declare (special result-list))
(handler-bind ((check-failure (lambda (e)
(declare (ignore e))
(cond
((eql *on-failure* :debug)
nil)
(t
(when (eql *on-failure* :backtrace)
(trivial-backtrace:print-backtrace-to-stream
*test-dribble*))
(invoke-restart
(find-restart 'ignore-failure))))))
(error (lambda (e)
(unless (or (eql *on-error* :debug)
(typep e 'check-failure))
(when (eql *on-error* :backtrace)
(trivial-backtrace:print-backtrace-to-stream
*test-dribble*))
(abort-test e)
(return-from run-it result-list)))))
(restart-case
(handler-case
(let ((*readtable* (copy-readtable))
(*package* (runtime-package test)))
(when *print-names*
(format *test-dribble* "~%~ARunning test ~A " *test-dribble-indent* (name test)))
(if (collect-profiling-info test)
Timing info does n't get collected ATM , we need a portable library
( setf ( profiling - info test ) ( collect - timing ( test - lambda test ) ) )
(funcall (test-lambda test))
(funcall (test-lambda test))))
(storage-condition (e)
(abort-test e (format nil "STORAGE-CONDITION: aborted for safety. ~S~%~A." e e))
(return-from run-it result-list)))
(retest ()
:report (lambda (stream)
(format stream "~@<Rerun the test ~S~@:>" test))
(return-from run-it (run-it)))
(ignore ()
:report (lambda (stream)
(format stream "~@<Signal an exceptional test failure and abort the test ~S.~@:>" test))
(abort-test (make-instance 'test-failure :test-case test
:reason "Failure restart."))))
result-list))))
(let ((results (run-it)))
(setf (status test) (results-status results)
result-list (nconc result-list results)))))))
(defgeneric %run (test-spec)
(:documentation "Internal method for running a test. Does not
update the status of the tests nor the special variables !,
!!, !!!"))
(defmethod %run ((test test-case))
(run-resolving-dependencies test))
(defmethod %run ((tests list))
(mapc #'%run tests))
(defmethod %run ((suite test-suite))
(when *print-names*
(format *test-dribble* "~%~ARunning test suite ~A" *test-dribble-indent* (name suite)))
(let ((suite-results '()))
(flet ((run-tests ()
(loop
for test being the hash-values of (tests suite)
do (%run test))))
(vector-push-extend #\space *test-dribble-indent*)
(unwind-protect
(bind-run-state ((result-list '()))
(unwind-protect
(if (collect-profiling-info suite)
Timing info does n't get collected ATM , we need a portable library
( setf ( profiling - info suite ) ( collect - timing # ' run - tests ) )
(run-tests)
(run-tests)))
(setf suite-results result-list
(status suite) (every #'test-passed-p suite-results)))
(vector-pop *test-dribble-indent*)
(with-run-state (result-list)
(setf result-list (nconc result-list suite-results)))))))
(defmethod %run ((test-name symbol))
(when-let (test (get-test test-name))
(%run test)))
(defvar *initial-!* (lambda () (format t "Haven't run that many tests yet.~%")))
(defvar *!* *initial-!*)
(defvar *!!* *initial-!*)
(defvar *!!!* *initial-!*)
(defun run! (&optional (test-spec *suite*)
&key ((:print-names *print-names*) *print-names*))
"Equivalent to (explain! (run TEST-SPEC))."
(explain! (run test-spec)))
(defun explain! (result-list)
"Explain the results of RESULT-LIST using a
detailed-text-explainer with output going to *test-dribble*.
Return a boolean indicating whether no tests failed."
(explain (make-instance 'detailed-text-explainer) result-list *test-dribble*)
(results-status result-list))
(defun debug! (&optional (test-spec *suite*))
"Calls (run! test-spec) but enters the debugger if any kind of error happens."
(let ((*on-error* :debug)
(*on-failure* :debug))
(run! test-spec)))
(defun run (test-spec &key ((:print-names *print-names*) *print-names*))
"Run the test specified by TEST-SPEC.
TEST-SPEC can be either a symbol naming a test or test suite, or
a testable-object object. This function changes the operations
performed by the !, !! and !!! functions."
(psetf *!* (lambda ()
(loop :for test :being :the :hash-keys :of *test*
:do (setf (status (get-test test)) :unknown))
(bind-run-state ((result-list '()))
(with-simple-restart (explain "Ignore the rest of the tests and explain current results")
(%run test-spec))
result-list))
*!!* *!*
*!!!* *!!*)
(let ((*on-error*
(or *on-error* (cond
(*debug-on-error*
(format *test-dribble* "*DEBUG-ON-ERROR* is obsolete. Use *ON-ERROR*.")
:debug)
(t nil))))
(*on-failure*
(or *on-failure* (cond
(*debug-on-failure*
(format *test-dribble* "*DEBUG-ON-FAILURE* is obsolete. Use *ON-FAILURE*.")
:debug)
(t nil)))))
(funcall *!*)))
(defun ! ()
"Rerun the most recently run test and explain the results."
(explain! (funcall *!*)))
(defun !! ()
"Rerun the second most recently run test and explain the results."
(explain! (funcall *!!*)))
(defun !!! ()
"Rerun the third most recently run test and explain the results."
(explain! (funcall *!!!*)))
(defun run-all-tests (&key (summary :end))
"Runs all defined test suites, T if all tests passed and NIL otherwise.
SUMMARY can be :END to print a summary at the end, :SUITE to print it
after each suite or NIL to skip explanations."
(check-type summary (member nil :suite :end))
(loop :for suite :in (cons 'nil (sort (copy-list *toplevel-suites*) #'string<=))
:for results := (if (suite-emptyp suite) nil (run suite))
:when (consp results)
:collect results :into all-results
:do (cond
((not (eql summary :suite))
nil)
(results
(explain! results))
(suite
(format *test-dribble* "Suite ~A is empty~%" suite)))
:finally (progn
(when (eql summary :end)
(explain! (alexandria:flatten all-results)))
(return (every #'results-status all-results)))))
Copyright ( c ) 2002 - 2003 ,
- Neither the name of , nor , nor the names
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
|
30b0dbf4dcb25fe8011ab4825afb47db684c71361f5d49bbe828fe98842d9a52 | pirapira/coq2rust | globnames.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
open Util
open Names
open Term
open Mod_subst
* { 6 Global reference is a kernel side type for all references together }
type global_reference =
| VarRef of variable
| ConstRef of constant
| IndRef of inductive
| ConstructRef of constructor
val isVarRef : global_reference -> bool
val isConstRef : global_reference -> bool
val isIndRef : global_reference -> bool
val isConstructRef : global_reference -> bool
val eq_gr : global_reference -> global_reference -> bool
val canonical_gr : global_reference -> global_reference
val destVarRef : global_reference -> variable
val destConstRef : global_reference -> constant
val destIndRef : global_reference -> inductive
val destConstructRef : global_reference -> constructor
val is_global : global_reference -> constr -> bool
val subst_constructor : substitution -> constructor -> constructor * constr
val subst_global : substitution -> global_reference -> global_reference * constr
val subst_global_reference : substitution -> global_reference -> global_reference
(** This constr is not safe to be typechecked, universe polymorphism is not
handled here: just use for printing *)
val printable_constr_of_global : global_reference -> constr
(** Turn a construction denoting a global reference into a global reference;
raise [Not_found] if not a global reference *)
val global_of_constr : constr -> global_reference
* Obsolete synonyms for constr_of_global and global_of_constr
val reference_of_constr : constr -> global_reference
module RefOrdered : sig
type t = global_reference
val compare : t -> t -> int
val equal : t -> t -> bool
val hash : t -> int
end
module RefOrdered_env : sig
type t = global_reference
val compare : t -> t -> int
val equal : t -> t -> bool
val hash : t -> int
end
module Refset : CSig.SetS with type elt = global_reference
module Refmap : Map.ExtS
with type key = global_reference and module Set := Refset
module Refset_env : CSig.SetS with type elt = global_reference
module Refmap_env : Map.ExtS
with type key = global_reference and module Set := Refset_env
* { 6 Extended global references }
type syndef_name = kernel_name
type extended_global_reference =
| TrueGlobal of global_reference
| SynDef of syndef_name
module ExtRefOrdered : sig
type t = extended_global_reference
val compare : t -> t -> int
val equal : t -> t -> bool
val hash : t -> int
end
type global_reference_or_constr =
| IsGlobal of global_reference
| IsConstr of constr
* { 6 Temporary function to brutally form kernel names from section paths }
val encode_mind : DirPath.t -> Id.t -> mutual_inductive
val decode_mind : mutual_inductive -> DirPath.t * Id.t
val encode_con : DirPath.t -> Id.t -> constant
val decode_con : constant -> DirPath.t * Id.t
* { 6 Popping one level of section in global names }
val pop_con : constant -> constant
val pop_kn : mutual_inductive-> mutual_inductive
val pop_global_reference : global_reference -> global_reference
| null | https://raw.githubusercontent.com/pirapira/coq2rust/22e8aaefc723bfb324ca2001b2b8e51fcc923543/library/globnames.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
* This constr is not safe to be typechecked, universe polymorphism is not
handled here: just use for printing
* Turn a construction denoting a global reference into a global reference;
raise [Not_found] if not a global reference | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Util
open Names
open Term
open Mod_subst
* { 6 Global reference is a kernel side type for all references together }
type global_reference =
| VarRef of variable
| ConstRef of constant
| IndRef of inductive
| ConstructRef of constructor
val isVarRef : global_reference -> bool
val isConstRef : global_reference -> bool
val isIndRef : global_reference -> bool
val isConstructRef : global_reference -> bool
val eq_gr : global_reference -> global_reference -> bool
val canonical_gr : global_reference -> global_reference
val destVarRef : global_reference -> variable
val destConstRef : global_reference -> constant
val destIndRef : global_reference -> inductive
val destConstructRef : global_reference -> constructor
val is_global : global_reference -> constr -> bool
val subst_constructor : substitution -> constructor -> constructor * constr
val subst_global : substitution -> global_reference -> global_reference * constr
val subst_global_reference : substitution -> global_reference -> global_reference
val printable_constr_of_global : global_reference -> constr
val global_of_constr : constr -> global_reference
* Obsolete synonyms for constr_of_global and global_of_constr
val reference_of_constr : constr -> global_reference
module RefOrdered : sig
type t = global_reference
val compare : t -> t -> int
val equal : t -> t -> bool
val hash : t -> int
end
module RefOrdered_env : sig
type t = global_reference
val compare : t -> t -> int
val equal : t -> t -> bool
val hash : t -> int
end
module Refset : CSig.SetS with type elt = global_reference
module Refmap : Map.ExtS
with type key = global_reference and module Set := Refset
module Refset_env : CSig.SetS with type elt = global_reference
module Refmap_env : Map.ExtS
with type key = global_reference and module Set := Refset_env
* { 6 Extended global references }
type syndef_name = kernel_name
type extended_global_reference =
| TrueGlobal of global_reference
| SynDef of syndef_name
module ExtRefOrdered : sig
type t = extended_global_reference
val compare : t -> t -> int
val equal : t -> t -> bool
val hash : t -> int
end
type global_reference_or_constr =
| IsGlobal of global_reference
| IsConstr of constr
* { 6 Temporary function to brutally form kernel names from section paths }
val encode_mind : DirPath.t -> Id.t -> mutual_inductive
val decode_mind : mutual_inductive -> DirPath.t * Id.t
val encode_con : DirPath.t -> Id.t -> constant
val decode_con : constant -> DirPath.t * Id.t
* { 6 Popping one level of section in global names }
val pop_con : constant -> constant
val pop_kn : mutual_inductive-> mutual_inductive
val pop_global_reference : global_reference -> global_reference
|
c59625ac1a5490185335783f1fa6c0bf2eefcb37bc0f01a8777922493b191237 | ConsenSysMesh/Fae | VersionsTX2.hs | body :: Transaction (Versioned String, String) String
body = return . snd
| null | https://raw.githubusercontent.com/ConsenSysMesh/Fae/3ff023f70fa403e9cef80045907e415ccd88d7e8/txs/VersionsTX2.hs | haskell | body :: Transaction (Versioned String, String) String
body = return . snd
| |
c202f247019580d8dd9b6fbd580e62fd647639a190e06fabd83ac02e516c1c9f | tonymorris/geo-gpx | Email.hs | -- | Complex Type: @emailType@ </#type_emailType>
module Data.Geo.GPX.Type.Email(
Email
, email
) where
import Data.Geo.GPX.Lens.IdL
import Data.Geo.GPX.Lens.DomainL
import Data.Lens.Common
import Control.Comonad.Trans.Store
import Text.XML.HXT.Arrow.Pickle
data Email = Email String String
deriving (Eq, Ord)
email ::
String -- ^ The id.
-> String -- ^ The domain.
-> Email
email =
Email
instance IdL Email where
idL =
Lens $ \(Email id domain) -> store (\id -> Email id domain) id
instance DomainL Email where
domainL =
Lens $ \(Email id domain) -> store (\domain -> Email id domain) domain
instance XmlPickler Email where
xpickle =
xpWrap (uncurry email, \(Email id' domain') -> (id', domain'))
(xpPair (xpAttr "id" xpText) (xpAttr "domain" xpText))
| null | https://raw.githubusercontent.com/tonymorris/geo-gpx/526b59ec403293c810c2ba08d2c006dc526e8bf9/src/Data/Geo/GPX/Type/Email.hs | haskell | | Complex Type: @emailType@ </#type_emailType>
^ The id.
^ The domain. | module Data.Geo.GPX.Type.Email(
Email
, email
) where
import Data.Geo.GPX.Lens.IdL
import Data.Geo.GPX.Lens.DomainL
import Data.Lens.Common
import Control.Comonad.Trans.Store
import Text.XML.HXT.Arrow.Pickle
data Email = Email String String
deriving (Eq, Ord)
email ::
-> Email
email =
Email
instance IdL Email where
idL =
Lens $ \(Email id domain) -> store (\id -> Email id domain) id
instance DomainL Email where
domainL =
Lens $ \(Email id domain) -> store (\domain -> Email id domain) domain
instance XmlPickler Email where
xpickle =
xpWrap (uncurry email, \(Email id' domain') -> (id', domain'))
(xpPair (xpAttr "id" xpText) (xpAttr "domain" xpText))
|
a1d86c764fd75b3bbfe5712c5208ecc98f17bddeebf1c3fc9c2a93be532bb19a | BranchTaken/Hemlock | test_hash_fold_empty.ml | open! Basis.Rudiments
open! Basis
open String
let test () =
let hash_empty state = begin
state
|> hash_fold ""
end in
let e1 =
Hash.State.empty
|> hash_empty
in
let e2 =
Hash.State.empty
|> hash_empty
|> hash_empty
in
assert U128.((Hash.t_of_state e1) <> (Hash.t_of_state e2))
let _ = test ()
| null | https://raw.githubusercontent.com/BranchTaken/Hemlock/a518d85876a620f65da2497ac9e34323e205fbc0/bootstrap/test/basis/string/test_hash_fold_empty.ml | ocaml | open! Basis.Rudiments
open! Basis
open String
let test () =
let hash_empty state = begin
state
|> hash_fold ""
end in
let e1 =
Hash.State.empty
|> hash_empty
in
let e2 =
Hash.State.empty
|> hash_empty
|> hash_empty
in
assert U128.((Hash.t_of_state e1) <> (Hash.t_of_state e2))
let _ = test ()
| |
bcb9663698bddb0cda91184a8a85f4487d13ff922eb28ccd1d8e59c182773d91 | xapi-project/xen-api | extauth_plugin_ADpbis.ml |
* Copyright ( C ) 2006 - 2009 Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file 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 Lesser General Public License for more details .
* Copyright (C) 2006-2009 Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file 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 Lesser General Public License for more details.
*)
(**
* @group Access Control
*)
module D = Debug.Make (struct let name = "extauth_plugin_ADpbis" end)
open D
open Xapi_stdext_std.Xstringext
let finally = Xapi_stdext_pervasives.Pervasiveext.finally
let with_lock = Xapi_stdext_threads.Threadext.Mutex.execute
let lwsmd_service = "lwsmd"
module Lwsmd = struct
This can be refined by Mtime.Span.hour when is updated to 1.4.0
let restart_interval = Int64.mul 3600L 1000000000L |> Mtime.Span.of_uint64_ns
let next_check_point =
Mtime.add_span (Mtime_clock.now ()) restart_interval |> ref
let is_ad_enabled ~__context =
( Helpers.get_localhost ~__context |> fun self ->
Db.Host.get_external_auth_type ~__context ~self
)
|> fun x -> x = Xapi_globs.auth_type_AD
let enable_nsswitch () =
try
ignore
(Forkhelpers.execute_command_get_output
!Xapi_globs.domain_join_cli_cmd
["configure"; "--enable"; "nsswitch"]
)
with e ->
error "Fail to run %s with error %s"
!Xapi_globs.domain_join_cli_cmd
(ExnHelper.string_of_exn e)
let stop ~timeout ~wait_until_success =
Xapi_systemctl.stop ~timeout ~wait_until_success lwsmd_service
let start ~timeout ~wait_until_success =
Xapi_systemctl.start ~timeout ~wait_until_success lwsmd_service
let restart ~timeout ~wait_until_success =
Xapi_systemctl.restart ~timeout ~wait_until_success lwsmd_service
let restart_on_error () =
(* Only restart once within restart_interval *)
let now = Mtime_clock.now () in
match !next_check_point with
| Some check_point ->
if Mtime.is_later now ~than:check_point then (
debug "Restart %s due to local server error" lwsmd_service ;
next_check_point := Mtime.add_span now restart_interval ;
restart ~timeout:0. ~wait_until_success:false
)
| None ->
debug "next_check_point overflow"
let init_service ~__context =
This function is called during start
(* it will start lwsmd service if the host is authed with AD *)
does not wait lwsmd service to boot up success as following reasons
* 1 . The waiting will slow down
* 2 . still needs to boot up even lwsmd bootup fail
* 3 . does not need to use lwsmd functionality during its bootup
* 1. The waiting will slow down xapi bootup
* 2. Xapi still needs to boot up even lwsmd bootup fail
* 3. Xapi does not need to use lwsmd functionality during its bootup *)
if is_ad_enabled ~__context then (
restart ~wait_until_success:false ~timeout:5. ;
help to enable nsswitch during bootup if it find the host is authed with AD
* nsswitch will be automatically enabled with command
* but this enabling is necessary when the host authed with AD upgrade
* As it will not run the - cli command again
* nsswitch will be automatically enabled with command domainjoin-cli
* but this enabling is necessary when the host authed with AD upgrade
* As it will not run the domainjoin-cli command again *)
enable_nsswitch ()
)
end
let match_error_tag (lines : string list) =
let err_catch_list =
[
("DNS_ERROR_BAD_PACKET", Auth_signature.E_LOOKUP)
; ("LW_ERROR_PASSWORD_MISMATCH", Auth_signature.E_CREDENTIALS)
; ("LW_ERROR_INVALID_ACCOUNT", Auth_signature.E_INVALID_ACCOUNT)
; ("LW_ERROR_ACCESS_DENIED", Auth_signature.E_DENIED)
; ("LW_ERROR_DOMAIN_IS_OFFLINE", Auth_signature.E_UNAVAILABLE)
; ("LW_ERROR_INVALID_OU", Auth_signature.E_INVALID_OU)
(* More errors to be caught here *)
]
in
let split_to_words str =
let seps = ['('; ')'; ' '; '\t'; '.'] in
String.split_f (fun s -> List.exists (fun sep -> sep = s) seps) str
in
let rec has_err lines err_pattern =
match lines with
| [] ->
false
| line :: rest -> (
try
ignore (List.find (fun w -> w = err_pattern) (split_to_words line)) ;
true
with Not_found -> has_err rest err_pattern
)
in
try
let _, errtag =
List.find
(fun (err_pattern, _) -> has_err lines err_pattern)
err_catch_list
in
errtag
with Not_found -> Auth_signature.E_GENERIC
let extract_sid_from_group_list group_list =
List.map
(fun (_, v) ->
let v = String.replace ")" "" v in
let v = String.replace "sid =" "|" v in
let vs = String.split_f (fun c -> c = '|') v in
let sid = String.trim (List.nth vs 1) in
debug "extract_sid_from_group_list get sid=[%s]" sid ;
sid
)
(List.filter (fun (n, _) -> n = "") group_list)
let start_damon () =
try Lwsmd.start ~timeout:5. ~wait_until_success:true
with _ ->
raise
(Auth_signature.Auth_service_error
( Auth_signature.E_GENERIC
, Printf.sprintf "Failed to start %s" lwsmd_service
)
)
module AuthADlw : Auth_signature.AUTH_MODULE = struct
* External Authentication Plugin component
* using AD / Pbis as a backend
* v1 14Nov14
*
* External Authentication Plugin component
* using AD/Pbis as a backend
* v1 14Nov14
*
*)
let user_friendly_error_msg =
"The Active Directory Plug-in could not complete the command. Additional \
information in the logs."
let mutex_check_availability =
Locking_helpers.Named_mutex.create "IS_SERVER_AVAILABLE"
let splitlines s =
String.split_f (fun c -> c = '\n') (String.replace "#012" "\n" s)
let pbis_common_with_password (password : string) (pbis_cmd : string)
(pbis_args : string list) =
let debug_cmd =
pbis_cmd ^ " " ^ List.fold_left (fun p pp -> p ^ " " ^ pp) " " pbis_args
in
try
debug "execute %s" debug_cmd ;
let env = [|"PASSWORD=" ^ password|] in
let _ = Forkhelpers.execute_command_get_output ~env pbis_cmd pbis_args in
[]
with
| Forkhelpers.Spawn_internal_error (stderr, stdout, Unix.WEXITED n) ->
error "execute %s exited with code %d [stdout = '%s'; stderr = '%s']"
debug_cmd n stdout stderr ;
let lines =
List.filter
(fun l -> String.length l > 0)
(splitlines (stdout ^ stderr))
in
let errmsg = List.hd (List.rev lines) in
let errtag = match_error_tag lines in
raise (Auth_signature.Auth_service_error (errtag, errmsg))
| e ->
error "execute %s exited: %s" debug_cmd (ExnHelper.string_of_exn e) ;
raise
(Auth_signature.Auth_service_error
(Auth_signature.E_GENERIC, user_friendly_error_msg)
)
let pbis_config (name : string) (value : string) =
let pbis_cmd = "/opt/pbis/bin/config" in
let pbis_args = [name; value] in
let debug_cmd = pbis_cmd ^ " " ^ name ^ " " ^ value in
try
debug "execute %s" debug_cmd ;
let _ = Forkhelpers.execute_command_get_output pbis_cmd pbis_args in
()
with
| Forkhelpers.Spawn_internal_error (stderr, stdout, Unix.WEXITED n) ->
error "execute %s exited with code %d [stdout = '%s'; stderr = '%s']"
debug_cmd n stdout stderr ;
let lines =
List.filter
(fun l -> String.length l > 0)
(splitlines (stdout ^ stderr))
in
let errmsg = List.hd (List.rev lines) in
raise
(Auth_signature.Auth_service_error (Auth_signature.E_GENERIC, errmsg))
| e ->
error "execute %s exited: %s" debug_cmd (ExnHelper.string_of_exn e) ;
raise
(Auth_signature.Auth_service_error
(Auth_signature.E_GENERIC, user_friendly_error_msg)
)
let ensure_pbis_configured () =
pbis_config "SpaceReplacement" "+" ;
pbis_config "CreateHomeDir" "false" ;
pbis_config "SyncSystemTime" "false" ;
pbis_config "LdapSignAndSeal" "true" ;
pbis_config "CacheEntryExpiry" "300" ;
()
let pbis_common ?(stdin_string = "") (pbis_cmd : string)
(pbis_args : string list) =
let debug_cmd =
pbis_cmd ^ " " ^ List.fold_left (fun p pp -> p ^ " " ^ pp) " " pbis_args
in
let debug_cmd =
if String.has_substr debug_cmd "--password" then
"(omitted for security)"
else
debug_cmd
in
(* stuff to clean up on the way out of the function: *)
let fds_to_close = ref [] in
let files_to_unlink = ref [] in
(* take care to close an fd only once *)
let close_fd fd =
if List.mem fd !fds_to_close then (
Unix.close fd ;
fds_to_close := List.filter (fun x -> x <> fd) !fds_to_close
)
in
(* take care to unlink a file only once *)
let unlink_file filename =
if List.mem filename !files_to_unlink then (
Unix.unlink filename ;
files_to_unlink := List.filter (fun x -> x <> filename) !files_to_unlink
)
in
(* guarantee to release all resources (files, fds) *)
let finalize () =
List.iter close_fd !fds_to_close ;
List.iter unlink_file !files_to_unlink
in
let finally_finalize f = finally f finalize in
let exited_code = ref 0 in
let output = ref "" in
finally_finalize (fun () ->
let _ =
try
debug "execute %s" debug_cmd ;
creates pipes between and pbis process
let in_readme, in_writeme = Unix.pipe () in
fds_to_close := in_readme :: in_writeme :: !fds_to_close ;
let out_tmpfile = Filename.temp_file "pbis" ".out" in
files_to_unlink := out_tmpfile :: !files_to_unlink ;
let err_tmpfile = Filename.temp_file "pbis" ".err" in
files_to_unlink := err_tmpfile :: !files_to_unlink ;
let out_writeme = Unix.openfile out_tmpfile [Unix.O_WRONLY] 0o0 in
fds_to_close := out_writeme :: !fds_to_close ;
let err_writeme = Unix.openfile err_tmpfile [Unix.O_WRONLY] 0o0 in
fds_to_close := err_writeme :: !fds_to_close ;
let pid =
Forkhelpers.safe_close_and_exec (Some in_readme)
(Some out_writeme) (Some err_writeme) [] pbis_cmd pbis_args
in
finally
(fun () ->
debug "Created process pid %s for cmd %s"
(Forkhelpers.string_of_pidty pid)
debug_cmd ;
Insert this delay to reproduce the can not write to stdin bug :
Thread.delay 5 . ;
Thread.delay 5.; *)
WARNING : we do n't close the in_readme because otherwise in the case where the pbis
binary does n't expect any input there is a race between it finishing ( and closing the last
reference to the in_readme ) and us attempting to write to in_writeme . If pbis wins the
race then our write will fail with EPIPE ( Unix.error 31 in ocamlese ) . If we keep a reference
to in_readme then our write of " \n " will succeed .
An alternative fix would be to not write anything when stdin_string = " "
binary doesn't expect any input there is a race between it finishing (and closing the last
reference to the in_readme) and us attempting to write to in_writeme. If pbis wins the
race then our write will fail with EPIPE (Unix.error 31 in ocamlese). If we keep a reference
to in_readme then our write of "\n" will succeed.
An alternative fix would be to not write anything when stdin_string = "" *)
push stdin_string to recently created process ' STDIN
try
usually , STDIN contains some sensitive data such as passwords that we do not want showing up in ps
or in the debug log via debug_cmd
let stdin_string = stdin_string ^ "\n" in
HACK : without , the pbis scripts do n't return !
let (_ : int) =
Unix.write_substring in_writeme stdin_string 0
(String.length stdin_string)
in
close_fd in_writeme
we need to close stdin , otherwise the unix cmd waits forever
with e ->
(* in_string is usually the password or other sensitive param, so never write it to debug or exn *)
debug "Error writing to stdin for cmd %s: %s" debug_cmd
(ExnHelper.string_of_exn e) ;
raise
(Auth_signature.Auth_service_error
(Auth_signature.E_GENERIC, ExnHelper.string_of_exn e)
)
)
(fun () ->
match Forkhelpers.waitpid pid with
| _, Unix.WEXITED n ->
exited_code := n ;
output :=
Xapi_stdext_unix.Unixext.string_of_file out_tmpfile
^ Xapi_stdext_unix.Unixext.string_of_file err_tmpfile
| _ ->
error "PBIS %s exit with WSTOPPED or WSIGNALED" debug_cmd ;
raise
(Auth_signature.Auth_service_error
(Auth_signature.E_GENERIC, user_friendly_error_msg)
)
)
with e ->
error "execute %s exited: %s" debug_cmd (ExnHelper.string_of_exn e) ;
raise
(Auth_signature.Auth_service_error
(Auth_signature.E_GENERIC, user_friendly_error_msg)
)
in
if !exited_code <> 0 then (
error "execute '%s': exit_code=[%d] output=[%s]" debug_cmd
!exited_code
(String.replace "\n" ";" !output) ;
let split_to_words s =
String.split_f (fun c -> c = '(' || c = ')' || c = '.' || c = ' ') s
in
let revlines =
List.rev
(List.filter (fun l -> String.length l > 0) (splitlines !output))
in
let errmsg = List.hd revlines in
let errcodeline =
if List.length revlines > 1 then List.nth revlines 1 else errmsg
in
let errcode =
List.hd
(List.filter
(fun w -> String.startswith "LW_ERROR_" w)
(split_to_words errcodeline)
)
in
debug "Pbis raised an error for cmd %s: (%s) %s" debug_cmd errcode
errmsg ;
match errcode with
| "LW_ERROR_INVALID_GROUP_INFO_LEVEL" ->
raise
(Auth_signature.Auth_service_error
(Auth_signature.E_GENERIC, errcode)
)
(* For pbis_get_all_byid *)
| "LW_ERROR_NO_SUCH_USER"
| "LW_ERROR_NO_SUCH_GROUP"
| "LW_ERROR_NO_SUCH_OBJECT" ->
raise Not_found (* Subject_cannot_be_resolved *)
| "LW_ERROR_KRB5_CALL_FAILED"
| "LW_ERROR_PASSWORD_MISMATCH"
| "LW_ERROR_ACCOUNT_DISABLED"
| "LW_ERROR_NOT_HANDLED" ->
raise (Auth_signature.Auth_failure errmsg)
| "LW_ERROR_INVALID_OU" ->
raise
(Auth_signature.Auth_service_error
(Auth_signature.E_INVALID_OU, errmsg)
)
| "LW_ERROR_INVALID_DOMAIN" ->
raise
(Auth_signature.Auth_service_error
(Auth_signature.E_GENERIC, errmsg)
)
| "LW_ERROR_ERRNO_ECONNREFUSED" ->
CA-368806 : Restart service to workaround pbis wedged
Lwsmd.restart_on_error () ;
raise
(Auth_signature.Auth_service_error
(Auth_signature.E_GENERIC, errmsg)
)
| "LW_ERROR_LSA_SERVER_UNREACHABLE" | _ ->
raise
(Auth_signature.Auth_service_error
( Auth_signature.E_GENERIC
, Printf.sprintf "(%s) %s" errcode errmsg
)
)
) else
debug "execute %s: output length=[%d]" debug_cmd
(String.length !output) ;
let lines =
List.filter (fun l -> String.length l > 0) (splitlines !output)
in
let parse_line (acc, currkey) line =
let slices = String.split ~limit:2 ':' line in
debug "parse %s: currkey=[%s] line=[%s]" debug_cmd currkey line ;
if List.length slices > 1 then (
let key = String.trim (List.hd slices) in
let value = String.trim (List.nth slices 1) in
debug "parse %s: key=[%s] value=[%s] currkey=[%s]" debug_cmd key
value currkey ;
if String.length value > 0 then
(acc @ [(key, value)], "")
else
(acc, key)
) else
let key = currkey in
let value = String.trim line in
debug "parse %s: key=[%s] value=[%s] currkey=[%s]" debug_cmd key
value currkey ;
(acc @ [(key, value)], currkey)
in
let attrs, _ = List.fold_left parse_line ([], "") lines in
attrs
)
assoc list for caching pbis_common results ,
item value is ( ( stdin_string , pbis_cmd , ) , ( unix_time , pbis_common_result ) )
item value is ((stdin_string, pbis_cmd, pbis_args), (unix_time, pbis_common_result))
*)
let cache_of_pbis_common :
((string * string * string list) * (float * (string * string) list)) list
ref =
ref []
let cache_of_pbis_common_m = Mutex.create ()
let pbis_common_with_cache ?(stdin_string = "") (pbis_cmd : string)
(pbis_args : string list) =
let expired = 120.0 in
let now = Unix.time () in
let cache_key = (stdin_string, pbis_cmd, pbis_args) in
let f () =
cache_of_pbis_common :=
List.filter
(fun (_, (ts, _)) -> now -. ts < expired)
!cache_of_pbis_common ;
try
let _, result = List.assoc cache_key !cache_of_pbis_common in
debug "pbis_common_with_cache hit \"%s\" cache." pbis_cmd ;
result
with Not_found ->
let result = pbis_common ~stdin_string pbis_cmd pbis_args in
cache_of_pbis_common :=
!cache_of_pbis_common @ [(cache_key, (Unix.time (), result))] ;
result
in
with_lock cache_of_pbis_common_m f
let get_joined_domain_name () =
Server_helpers.exec_with_new_task "obtaining joined-domain name"
(fun __context ->
let host = Helpers.get_localhost ~__context in
(* the service_name always contains the domain name provided during domain-join *)
Db.Host.get_external_auth_service_name ~__context ~self:host
)
(* CP-842: when resolving AD usernames, make joined-domain prefix optional *)
let get_full_subject_name ?(use_nt_format = true) subject_name =
(* CA-27744: always use NT-style names by default *)
try
tests if the UPN account name separator @ is present in subject name
ignore (String.index subject_name '@') ;
(* we only reach this point if the separator @ is present in subject_name *)
(* nothing to do, we assume that subject_name already contains the domain name after @ *)
subject_name
with Not_found -> (
try
if no UPN username separator @ was found
(* tests if the NT account name separator \ is present in subject name *)
ignore (String.index subject_name '\\') ;
(* we only reach this point if the separator \ is present in subject_name *)
(* nothing to do, we assume that subject_name already contains the domain name before \ *)
subject_name
with Not_found ->
if
if neither the UPN separator @ nor the NT username separator \ was found
use_nt_format
then
the default : NT names is unique , whereas UPN ones are not ( CA-27744 )
(* we prepend the joined-domain name to the subjectname as an NT name: <domain.com>\<subjectname> *)
get_joined_domain_name () ^ "\\" ^ subject_name
obs : ( 1 ) pbis accepts a fully qualified domain name < domain.com > with both formats and
( 2 ) some pbis commands accept only the NT - format , such as find - group - by - name
else
UPN format not the default format ( CA-27744 )
we append the joined - domain name to the subjectname as a UPN name : < subjectname>@<domain.com >
subject_name ^ "@" ^ get_joined_domain_name ()
)
Converts from UPN format ( ) to legacy NT format ( )
(* This function is a workaround to use find-group-by-name, which requires nt-format names) *)
For anything else , use the original UPN name
let convert_upn_to_nt_username subject_name =
try
test if the UPN account name separator @ is present in subject name
let i = String.index subject_name '@' in
(* we only reach this point if the separator @ is present in subject_name *)
when @ is present , we need to convert the UPN name to NT format
let user = String.sub subject_name 0 i in
let domain =
String.sub subject_name (i + 1) (String.length subject_name - i - 1)
in
domain ^ "\\" ^ user
with Not_found ->
if no UPN username separator @ was found
(* nothing to do in this case *)
subject_name
let pbis_get_all_byid subject_id =
try
pbis_common_with_cache "/opt/pbis/bin/find-by-sid"
["--level"; "2"; subject_id]
with
| Auth_signature.Auth_service_error
(Auth_signature.E_GENERIC, "LW_ERROR_INVALID_GROUP_INFO_LEVEL")
->
pbis_common_with_cache "/opt/pbis/bin/find-by-sid"
["--level"; "1"; subject_id]
let pbis_get_group_sids_byname _subject_name =
let subject_name = get_full_subject_name _subject_name in
(* append domain if necessary *)
let subject_attrs =
pbis_common_with_cache "/opt/pbis/bin/list-groups-for-user"
["--show-sid"; subject_name]
in
PBIS list - groups - for - user raw output like
Number of groups found for user ' test@testdomain ' : 2
Group[1 of 2 ] name = testdomain\dnsadmins ( gid = 580912206 , = S-1 - 5 - 21 - 791009147 - 1041474540 - 2433379237 - 1102 )
Group[2 of 2 ] name = testdomain\domain+users ( gid = 580911617 , sid = S-1 - 5 - 21 - 791009147 - 1041474540 - 2433379237 - 513 )
And pbis_common will return subject_attrs as
[ ( " Number of groups found for user ' test@testdomain ' " , " 2 " ) , ( " " , ) , ( " " , line2 ) ... ( " " , lineN ) ]
Number of groups found for user 'test@testdomain' : 2
Group[1 of 2] name = testdomain\dnsadmins (gid = 580912206, sid = S-1-5-21-791009147-1041474540-2433379237-1102)
Group[2 of 2] name = testdomain\domain+users (gid = 580911617, sid = S-1-5-21-791009147-1041474540-2433379237-513)
And pbis_common will return subject_attrs as
[("Number of groups found for user 'test@testdomain'", "2"), ("", line1), ("", line2) ... ("", lineN)]
*)
extract_sid_from_group_list subject_attrs
general Pbis error
let pbis_get_sid_byname _subject_name cmd =
let subject_name = get_full_subject_name _subject_name in
(* append domain if necessary *)
let subject_attrs = pbis_common cmd ["--level"; "1"; subject_name] in
find - user - by - name returns several lines . We ony need the SID
if List.mem_assoc "SID" subject_attrs then
OK , return SID
else
no SID value returned
this should not have happend , pbis did n't return an SID field ! !
let msg =
Printf.sprintf "Pbis didn't return an SID field for user %s"
subject_name
in
debug "Error pbis_get_sid_byname for subject name %s: %s" subject_name msg ;
raise (Auth_signature.Auth_service_error (Auth_signature.E_GENERIC, msg))
general Pbis error
subject_id get_subject_identifier(string subject_name )
Takes a subject_name ( as may be entered into the XenCenter UI when defining subjects --
see Access Control wiki page ) ; and resolves it to a subject_id against the external
auth / directory service .
Raises Not_found ( * Subject_cannot_be_resolved
Takes a subject_name (as may be entered into the XenCenter UI when defining subjects --
see Access Control wiki page); and resolves it to a subject_id against the external
auth/directory service.
Raises Not_found (*Subject_cannot_be_resolved*) if authentication is not succesful.
*)
let get_subject_identifier _subject_name =
try
(* looks up list of users*)
let subject_name = get_full_subject_name _subject_name in
(* append domain if necessary *)
pbis_get_sid_byname subject_name "/opt/pbis/bin/find-user-by-name"
with _ ->
(* append domain if necessary, find-group-by-name only accepts nt-format names *)
let subject_name =
get_full_subject_name ~use_nt_format:true
(convert_upn_to_nt_username _subject_name)
in
(* looks up list of groups*)
pbis_get_sid_byname subject_name "/opt/pbis/bin/find-group-by-name"
subject_id Authenticate_username_password(string username , string password )
Takes a username and password , and tries to authenticate against an already configured
auth service ( see XenAPI requirements Wiki page for details of how auth service configuration
takes place and the appropriate values are stored within the XenServer Metadata ) .
If authentication is successful then a subject_id is returned representing the account
corresponding to the supplied credentials ( where the subject_id is in a namespace managed by
the auth module / service itself -- e.g. maybe a SID or something in the AD case ) .
Raises auth_failure if authentication is not successful
Takes a username and password, and tries to authenticate against an already configured
auth service (see XenAPI requirements Wiki page for details of how auth service configuration
takes place and the appropriate values are stored within the XenServer Metadata).
If authentication is successful then a subject_id is returned representing the account
corresponding to the supplied credentials (where the subject_id is in a namespace managed by
the auth module/service itself -- e.g. maybe a SID or something in the AD case).
Raises auth_failure if authentication is not successful
*)
let authenticate_username_password username password =
(* first, we try to authenticated user against our external user database *)
(* pbis_common will raise an Auth_failure if external authentication fails *)
let domain, user =
match String.split_f (fun c -> c = '\\') username with
| [domain; user] ->
(domain, user)
| [user] ->
(get_joined_domain_name (), user)
| _ ->
raise
(Auth_signature.Auth_service_error
(Auth_signature.E_GENERIC, "Invalid username " ^ username)
)
in
let (_ : (string * string) list) =
pbis_common "/opt/pbis/bin/lsa"
[
"authenticate-user"
; "--user"
; user
; "--domain"
; domain
; "--password"
; password
]
in
(* no exception raised, then authentication succeeded, *)
(* now we return the authenticated user's id *)
get_subject_identifier (get_full_subject_name username)
(* subject_id Authenticate_ticket(string ticket)
As above but uses a ticket as credentials (i.e. for single sign-on)
*)
(* not implemented now, not needed for our tests, only for a *)
(* future single sign-on feature *)
let authenticate_ticket _tgt =
failwith "extauth_plugin authenticate_ticket not implemented"
( ( string*string ) list ) )
Takes a subject_identifier and returns the user record from the directory service as
key / value pairs . In the returned string*string map , there _ must _ be a key called
subject_name that refers to the name of the account ( e.g. the user or group name as may
be displayed in ) . There is no other requirements to include fields from the user
record -- initially qI'd imagine that we would n't bother adding anything else here , but
it 's a string*string list anyway for possible future expansion .
Raises Not_found ( * Subject_cannot_be_resolved
Takes a subject_identifier and returns the user record from the directory service as
key/value pairs. In the returned string*string map, there _must_ be a key called
subject_name that refers to the name of the account (e.g. the user or group name as may
be displayed in XenCenter). There is no other requirements to include fields from the user
record -- initially qI'd imagine that we wouldn't bother adding anything else here, but
it's a string*string list anyway for possible future expansion.
Raises Not_found (*Subject_cannot_be_resolved*) if subject_id cannot be resolved by external auth service
*)
let query_subject_information subject_identifier =
let unmap_lw_space_chars lwname =
let defensive_copy = Bytes.of_string lwname in
(* CA-29006: map chars in names back to original space chars in windows-names *)
(* we use + as the pbis space-replacement because it's an invalid NT-username char in windows *)
the space - replacement char used by pbis is defined at /etc / pbis / lsassd.conf
let current_lw_space_replacement = '+' in
String.iteri
(fun i c ->
if c = current_lw_space_replacement then
Bytes.set defensive_copy i ' '
else
()
)
lwname ;
Bytes.unsafe_to_string defensive_copy
in
let get_value name ls =
if List.mem_assoc name ls then List.assoc name ls else ""
in
let infolist = pbis_get_all_byid subject_identifier in
let subject_is_group = get_value "Uid" infolist = "" in
if subject_is_group then
(* subject is group *)
in this case , a few info fields are not available : UPN , Uid , Gecos , Account { disabled , expired , locked } , Password expired
[
("subject-name", unmap_lw_space_chars (get_value "Name" infolist))
; ("subject-gid", get_value "Gid" infolist)
; ("subject-sid", get_value "SID" infolist)
; ("subject-is-group", "true")
(*(* comma-separated list of subjects that are contained in this subject *)
("contains-byname", List.fold_left (fun (n,v) m ->m^","^v) "" (List.filter (fun (n,v)->n="Members") infolist));*)
]
else (* subject is user *)
let subject_name = unmap_lw_space_chars (get_value "Name" infolist) in
let subject_gecos = get_value "Gecos" infolist in
[
("subject-name", subject_name)
; ("subject-upn", get_value "UPN" infolist)
; ("subject-uid", get_value "Uid" infolist)
; ("subject-gid", get_value "Gid" infolist)
; ("subject-sid", get_value "SID" infolist)
; ("subject-gecos", subject_gecos)
; ( "subject-displayname"
, if subject_gecos = "" || subject_gecos = "<null>" then
subject_name
else
subject_gecos
)
( " subject - homedir " , get_value " Home dir " infolist ) ;
( " subject - shell " , get_value " Shell " infolist ) ;
("subject-is-group", "false")
; ( "subject-account-disabled"
, get_value "Account disabled (or locked)" infolist
)
; ("subject-account-expired", get_value "Account Expired" infolist)
; ( "subject-account-locked"
, get_value "Account disabled (or locked)" infolist
)
; ("subject-password-expired", get_value "Password Expired" infolist)
]
( string list ) query_group_membership(string subject_identifier )
Takes a subject_identifier and returns its group membership ( i.e. a list of subject
identifiers of the groups that the subject passed in belongs to ) . The set of groups returned
_ must _ be transitively closed wrt the is_member_of relation if the external directory service
supports nested groups ( as does for example )
Takes a subject_identifier and returns its group membership (i.e. a list of subject
identifiers of the groups that the subject passed in belongs to). The set of groups returned
_must_ be transitively closed wrt the is_member_of relation if the external directory service
supports nested groups (as AD does for example)
*)
let query_group_membership subject_identifier =
let subject_info = query_subject_information subject_identifier in
if
List.assoc "subject-is-group" subject_info = "true"
(* this field is always present *)
then
subject is a group , so get_group_sids_byname will not work because pbis 's list - groups
(* doesnt work if a group name is given as input *)
FIXME : default action for groups until workaround is found : return an empty list of membership groups
[]
else
(* subject is a user, list-groups and therefore get_group_sids_byname work fine *)
let subject_name = List.assoc "subject-name" subject_info in
(* CA-27744: always use NT-style names *)
let subject_sid_membership_list =
pbis_get_group_sids_byname subject_name
in
debug "Resolved %i group sids for subject %s (%s): %s"
(List.length subject_sid_membership_list)
subject_name subject_identifier
(List.fold_left
(fun p pp -> if p = "" then pp else p ^ "," ^ pp)
"" subject_sid_membership_list
) ;
subject_sid_membership_list
(*
In addition, there are some event hooks that auth modules implement as follows:
*)
let _is_pbis_server_available max_tries =
we _ need _ to use a username contained in our domain , otherwise the following tests wo n't work .
Microsoft KB / Q243330 article provides the KRBTGT account as a well - known built - in SID in AD
Microsoft KB / Q229909 article says that KRBTGT account can not be renamed or enabled , making
it the perfect target for such a test using a username ( Administrator account can be renamed )
Microsoft KB/Q243330 article provides the KRBTGT account as a well-known built-in SID in AD
Microsoft KB/Q229909 article says that KRBTGT account cannot be renamed or enabled, making
it the perfect target for such a test using a username (Administrator account can be renamed) *)
let krbtgt = "KRBTGT" in
let try_clear_cache () =
the primary purpose of this function is to clear the cache so that
[ try_fetch_sid ] is forced to perform an end to end query to the
AD server . as such , we do n't care if krbtgt was not originally in
the cache
[ try_fetch_sid ] is forced to perform an end to end query to the
AD server. as such, we don't care if krbtgt was not originally in
the cache *)
match get_full_subject_name krbtgt with
| exception _ ->
info
"_is_pbis_server_available: failed to get full subject name for %s"
krbtgt ;
Error ()
| full_username -> (
match
ignore
(pbis_common "/opt/pbis/bin/ad-cache"
["--delete-user"; "--name"; full_username]
)
with
| () | (exception Not_found) ->
Ok ()
| exception e ->
debug "Failed to remove user %s from cache: %s" full_username
(ExnHelper.string_of_exn e) ;
Error ()
)
in
let try_fetch_sid () =
try
let sid = get_subject_identifier krbtgt in
debug
"Request to external authentication server successful: user %s was \
found"
krbtgt ;
let (_ : (string * string) list) = query_subject_information sid in
debug
"Request to external authentication server successful: sid %s was \
found"
sid ;
Ok ()
with
| Not_found ->
that means that pbis is responding to at least cached subject queries .
in this case , was n't found in the AD domain . this usually indicates that the
AD domain is offline / inaccessible to pbis , which will cause problems , specially
to the ssh python hook - script , so we need to try again until KRBTGT is found , indicating
that the domain is online and accessible to pbis queries
in this case, KRBTGT wasn't found in the AD domain. this usually indicates that the
AD domain is offline/inaccessible to pbis, which will cause problems, specially
to the ssh python hook-script, so we need to try again until KRBTGT is found, indicating
that the domain is online and accessible to pbis queries *)
debug
"Request to external authentication server returned KRBTGT \
Not_found" ;
Error ()
| e ->
debug
"Request to external authentication server failed for reason: %s"
(ExnHelper.string_of_exn e) ;
Error ()
in
let rec go i =
if i > max_tries then (
info
"Testing external authentication server failed after %i tries, \
giving up!"
max_tries ;
false
) else (
debug
"Testing if external authentication server is accepting requests... \
attempt %i of %i"
i max_tries ;
let ( >>= ) = Rresult.( >>= ) in
if we do n't remove krbtgt from the cache before
query subject information about krbtgt , then
[ try_fetch_sid ] would erroneously return success
in the case that PBIS is running locally , but the
AD domain is offline
query subject information about krbtgt, then
[ try_fetch_sid ] would erroneously return success
in the case that PBIS is running locally, but the
AD domain is offline *)
match try_clear_cache () >>= try_fetch_sid with
| Error () ->
Thread.delay 5.0 ;
(go [@tailcall]) (i + 1)
| Ok () ->
true
)
in
go 0
let is_pbis_server_available max =
Locking_helpers.Named_mutex.execute mutex_check_availability (fun () ->
_is_pbis_server_available max
)
converts from domain.com\user to , in case domain.com is present in the subject_name
let convert_nt_to_upn_username subject_name =
try
(* test if the NT account name separator \ is present in subject name *)
let i = String.index subject_name '\\' in
(* we only reach this point if the separator \ is present in subject_name *)
when \ is present , we need to convert the NT name to UPN format
let domain = String.sub subject_name 0 i in
let user =
String.sub subject_name (i + 1) (String.length subject_name - i - 1)
in
user ^ "@" ^ domain
with Not_found ->
(* if no NT username separator \ was found *)
(* nothing to do in this case *)
subject_name
unit on_enable(((string*string ) list ) config_params )
Called internally by _ on each host _ when a client enables an external auth service for the
pool via the XenAPI [ see AD integration wiki page ] . The config_params here are the ones passed
by the client as part of the corresponding XenAPI call .
On receiving this hook , the auth module should :
( i ) do whatever it needs to do ( if anything ) to register with the external auth / directory
service [ using the config params supplied to get access ]
( ii ) Write the config_params that it needs to store persistently in the XenServer metadata
into the Pool.external_auth_configuration field . [ Note - the rationale for making the plugin
write the config params it needs long - term into the XenServer metadata itself is so it can
explicitly filter any one - time credentials [ like username / password for example ] that it
does not need long - term . ]
Called internally by xapi _on each host_ when a client enables an external auth service for the
pool via the XenAPI [see AD integration wiki page]. The config_params here are the ones passed
by the client as part of the corresponding XenAPI call.
On receiving this hook, the auth module should:
(i) do whatever it needs to do (if anything) to register with the external auth/directory
service [using the config params supplied to get access]
(ii) Write the config_params that it needs to store persistently in the XenServer metadata
into the Pool.external_auth_configuration field. [Note - the rationale for making the plugin
write the config params it needs long-term into the XenServer metadata itself is so it can
explicitly filter any one-time credentials [like AD username/password for example] that it
does not need long-term.]
*)
let on_enable config_params =
but in the ldap plugin , we should ' join the AD / domain ' , i.e. we should
basically : ( 1 ) create a machine account in the realm ,
( 2 ) store the machine account password somewhere locally ( in a keytab )
start_damon () ;
if
not
(List.mem_assoc "user" config_params
&& List.mem_assoc "pass" config_params
)
then
raise
(Auth_signature.Auth_service_error
( Auth_signature.E_GENERIC
, "enable requires two config params: user and pass."
)
)
else (* we have all the required parameters *)
let hostname =
Server_helpers.exec_with_new_task "retrieving hostname"
(fun __context ->
let host = Helpers.get_localhost ~__context in
Db.Host.get_hostname ~__context ~self:host
)
in
if
String.fold_left (fun b ch -> b && ch >= '0' && ch <= '9') true hostname
then
raise
(Auth_signature.Auth_service_error
( Auth_signature.E_GENERIC
, Printf.sprintf "hostname '%s' cannot contain only digits."
hostname
)
)
else
let domain =
let service_name =
Server_helpers.exec_with_new_task
"retrieving external_auth_service_name" (fun __context ->
let host = Helpers.get_localhost ~__context in
Db.Host.get_external_auth_service_name ~__context ~self:host
)
in
if
List.mem_assoc "domain" config_params
(* legacy test: do we have domain name in config? *)
then (* then config:domain must match service-name *)
let _domain = List.assoc "domain" config_params in
if service_name <> _domain then
raise
(Auth_signature.Auth_service_error
( Auth_signature.E_GENERIC
, "if present, config:domain must match service-name."
)
)
else
service_name
else
(* if no config:domain provided, we simply use the string in service_name for the domain name *)
service_name
in
let _user = List.assoc "user" config_params in
let pass = List.assoc "pass" config_params in
let ou_conf, ou_params =
if List.mem_assoc "ou" config_params then
let ou = List.assoc "ou" config_params in
([("ou", ou)], ["--ou"; ou])
else
([], [])
in
Adding the config parameter " config : , Y , Z "
* will disable the modules X , Y and Z in .
* will disable the modules X, Y and Z in domainjoin-cli. *)
let disabled_modules =
try
match List.assoc "disable_modules" config_params with
| "" ->
[]
| disabled_modules_string ->
String.split_f (fun c -> c = ',') disabled_modules_string
with Not_found -> []
in
let disabled_module_params =
List.concat
(List.map
(fun disabled_module -> ["--disable"; disabled_module])
disabled_modules
)
in
we need to make sure that the user passed to domaijoin - cli command is in the UPN syntax ( )
let user = convert_nt_to_upn_username _user in
execute the pbis domain join cmd
try
let (_ : (string * string) list) =
[
["join"]
; ou_params
; disabled_module_params
; ["--ignore-pam"; "--notimesync"; domain; user]
]
|> List.concat
|> pbis_common_with_password pass !Xapi_globs.domain_join_cli_cmd
in
let max_tries = 60 in
tests 60 x 5.0 seconds = 300 seconds = 5minutes trying
if not (is_pbis_server_available max_tries) then (
let errmsg =
Printf.sprintf
"External authentication server not available after %i query \
tests"
max_tries
in
debug "%s" errmsg ;
raise
(Auth_signature.Auth_service_error
(Auth_signature.E_UNAVAILABLE, errmsg)
)
) ;
OK SUCCESS , pbis has joined the AD domain successfully
(* write persistently the relevant config_params in the host.external_auth_configuration field *)
(* we should not store the user's (admin's) password !! *)
let extauthconf = [("domain", domain); ("user", user)] @ ou_conf in
Server_helpers.exec_with_new_task
"storing external_auth_configuration" (fun __context ->
let host = Helpers.get_localhost ~__context in
Db.Host.set_external_auth_configuration ~__context ~self:host
~value:extauthconf ;
debug "added external_auth_configuration for host %s"
(Db.Host.get_name_label ~__context ~self:host)
) ;
with_lock cache_of_pbis_common_m (fun _ -> cache_of_pbis_common := []) ;
ensure_pbis_configured ()
with e ->
(*ERROR, we didn't join the AD domain*)
debug
"Error enabling external authentication for domain %s and user %s: \
%s"
domain user
(ExnHelper.string_of_exn e) ;
raise e
unit on_disable ( )
Called internally by _ on each host _ when a client disables an auth service via the XenAPI .
The hook will be called _ before _ the Pool configuration fields relating to the external - auth
service are cleared ( i.e. so you can access the config params you need from the pool metadata
within the body of the on_disable method )
Called internally by xapi _on each host_ when a client disables an auth service via the XenAPI.
The hook will be called _before_ the Pool configuration fields relating to the external-auth
service are cleared (i.e. so you can access the config params you need from the pool metadata
within the body of the on_disable method)
*)
let on_disable config_params =
but in the ldap plugin , we should ' leave the AD / domain ' , i.e. we should
( 1 ) remove the machine account from the realm , ( 2 ) remove the keytab locally
let pbis_failure =
try
( if
not
(List.mem_assoc "user" config_params
&& List.mem_assoc "pass" config_params
)
then
no windows admin+pass have been provided : leave the pbis host in the AD database
execute the pbis domain - leave cmd
(* this function will raise an exception if something goes wrong *)
let (_ : (string * string) list) =
pbis_common !Xapi_globs.domain_join_cli_cmd ["leave"]
in
()
else
windows admin+pass have been provided : ask pbis to remove host from AD database
let _user = List.assoc "user" config_params in
let pass = List.assoc "pass" config_params in
we need to make sure that the user passed to domaijoin - cli command is in the UPN syntax ( )
let user =
convert_nt_to_upn_username
(get_full_subject_name ~use_nt_format:false _user)
in
execute the pbis domain - leave cmd
(* this function will raise an exception if something goes wrong *)
let (_ : (string * string) list) =
pbis_common_with_password pass
!Xapi_globs.domain_join_cli_cmd
["leave"; user]
in
()
) ;
no failure observed in pbis
with e ->
unexpected error disabling pbis
debug "Internal Pbis error when disabling external authentication: %s"
(ExnHelper.string_of_exn e) ;
(* CA-27627: we should NOT re-raise the exception e here, because otherwise we might get stuck, *)
without being able to disable an external authentication configuration , since the Pbis
behavior is outside our control . For instance , Pbis raises an exception during domain - leave
(* when the domain controller is offline, so it would be impossible to leave a domain that *)
(* has already been deleted. *)
Not re - raising an exception here is not too bad , because both ssh and to the AD / Pbis
(* commands will be disabled anyway by host.disable_external_auth. So, even though access to the external *)
(* authentication service might still be possible from Dom0 shell, it will not be possible *)
to login as an external user via ssh or to call external - authentication services via xapi / xe .
Some e
CA-28942 : stores exception returned by pbis for later
in
We always do a manual clean - up of pbis , in order to restore to its pre - pbis state
It does n't matter if pbis succeeded or not
This disables Pbis even from Dom0 shell
debug "Doing a manual Pbis domain-leave cleanup..." ;
When pbis raises an exception during domain - leave , we try again , using
some of the command - line workarounds that describes in CA-27627 :
let pbis_force_domain_leave_script =
"/opt/xensource/libexec/pbis-force-domain-leave"
in
( try
let output, stderr =
Forkhelpers.execute_command_get_output pbis_force_domain_leave_script
[]
in
debug "execute %s: stdout=[%s],stderr=[%s]"
pbis_force_domain_leave_script
(String.replace "\n" ";" output)
(String.replace "\n" ";" stderr)
with e ->
debug "exception executing %s: %s" pbis_force_domain_leave_script
(ExnHelper.string_of_exn e)
) ;
OK SUCCESS , pbis has left the AD domain successfully
(* remove persistently the relevant config_params in the host.external_auth_configuration field *)
Server_helpers.exec_with_new_task "removing external_auth_configuration"
(fun __context ->
let host = Helpers.get_localhost ~__context in
Db.Host.set_external_auth_configuration ~__context ~self:host ~value:[] ;
debug "removed external_auth_configuration for host %s"
(Db.Host.get_name_label ~__context ~self:host)
) ;
match pbis_failure with
| None ->
() (* OK, return unit*)
| Some e ->
raise e
bubble up pbis failure
unit on_xapi_initialize(bool system_boot )
Called internally by whenever it starts up . The system_boot flag is true iff is
starting for the first time after a host boot
Called internally by xapi whenever it starts up. The system_boot flag is true iff xapi is
starting for the first time after a host boot
*)
let on_xapi_initialize _system_boot =
the AD server is initialized outside , by init.d scripts
this function is called during initialization in xapi.ml
(* make sure that the AD/LSASS server is responding before returning *)
let max_tries = 12 in
tests 12 x 5.0 seconds = 60 seconds = up to 1 minute trying
if not (is_pbis_server_available max_tries) then (
let errmsg =
Printf.sprintf
"External authentication server not available after %i query tests"
max_tries
in
debug "%s" errmsg ;
raise
(Auth_signature.Auth_service_error (Auth_signature.E_GENERIC, errmsg))
) ;
()
unit on_xapi_exit ( )
Called internally when is doing a clean exit .
Called internally when xapi is doing a clean exit.
*)
let on_xapi_exit () =
(* nothing to do here in this unix plugin *)
(* in the ldap plugin, we should remove the tgt ticket in /tmp/krb5cc_0 *)
()
(* Implement the single value required for the module signature *)
let methods =
{
Auth_signature.authenticate_username_password
; Auth_signature.authenticate_ticket
; Auth_signature.get_subject_identifier
; Auth_signature.query_subject_information
; Auth_signature.query_group_membership
; Auth_signature.on_enable
; Auth_signature.on_disable
; Auth_signature.on_xapi_initialize
; Auth_signature.on_xapi_exit
}
end
| null | https://raw.githubusercontent.com/xapi-project/xen-api/1b7ef7ca5b33fea6e933bb39a661a7fb1f56ed02/ocaml/xapi/extauth_plugin_ADpbis.ml | ocaml | *
* @group Access Control
Only restart once within restart_interval
it will start lwsmd service if the host is authed with AD
More errors to be caught here
stuff to clean up on the way out of the function:
take care to close an fd only once
take care to unlink a file only once
guarantee to release all resources (files, fds)
in_string is usually the password or other sensitive param, so never write it to debug or exn
For pbis_get_all_byid
Subject_cannot_be_resolved
the service_name always contains the domain name provided during domain-join
CP-842: when resolving AD usernames, make joined-domain prefix optional
CA-27744: always use NT-style names by default
we only reach this point if the separator @ is present in subject_name
nothing to do, we assume that subject_name already contains the domain name after @
tests if the NT account name separator \ is present in subject name
we only reach this point if the separator \ is present in subject_name
nothing to do, we assume that subject_name already contains the domain name before \
we prepend the joined-domain name to the subjectname as an NT name: <domain.com>\<subjectname>
This function is a workaround to use find-group-by-name, which requires nt-format names)
we only reach this point if the separator @ is present in subject_name
nothing to do in this case
append domain if necessary
append domain if necessary
Subject_cannot_be_resolved
looks up list of users
append domain if necessary
append domain if necessary, find-group-by-name only accepts nt-format names
looks up list of groups
first, we try to authenticated user against our external user database
pbis_common will raise an Auth_failure if external authentication fails
no exception raised, then authentication succeeded,
now we return the authenticated user's id
subject_id Authenticate_ticket(string ticket)
As above but uses a ticket as credentials (i.e. for single sign-on)
not implemented now, not needed for our tests, only for a
future single sign-on feature
Subject_cannot_be_resolved
CA-29006: map chars in names back to original space chars in windows-names
we use + as the pbis space-replacement because it's an invalid NT-username char in windows
subject is group
(* comma-separated list of subjects that are contained in this subject
subject is user
this field is always present
doesnt work if a group name is given as input
subject is a user, list-groups and therefore get_group_sids_byname work fine
CA-27744: always use NT-style names
In addition, there are some event hooks that auth modules implement as follows:
test if the NT account name separator \ is present in subject name
we only reach this point if the separator \ is present in subject_name
if no NT username separator \ was found
nothing to do in this case
we have all the required parameters
legacy test: do we have domain name in config?
then config:domain must match service-name
if no config:domain provided, we simply use the string in service_name for the domain name
write persistently the relevant config_params in the host.external_auth_configuration field
we should not store the user's (admin's) password !!
ERROR, we didn't join the AD domain
this function will raise an exception if something goes wrong
this function will raise an exception if something goes wrong
CA-27627: we should NOT re-raise the exception e here, because otherwise we might get stuck,
when the domain controller is offline, so it would be impossible to leave a domain that
has already been deleted.
commands will be disabled anyway by host.disable_external_auth. So, even though access to the external
authentication service might still be possible from Dom0 shell, it will not be possible
remove persistently the relevant config_params in the host.external_auth_configuration field
OK, return unit
make sure that the AD/LSASS server is responding before returning
nothing to do here in this unix plugin
in the ldap plugin, we should remove the tgt ticket in /tmp/krb5cc_0
Implement the single value required for the module signature |
* Copyright ( C ) 2006 - 2009 Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file 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 Lesser General Public License for more details .
* Copyright (C) 2006-2009 Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file 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 Lesser General Public License for more details.
*)
module D = Debug.Make (struct let name = "extauth_plugin_ADpbis" end)
open D
open Xapi_stdext_std.Xstringext
let finally = Xapi_stdext_pervasives.Pervasiveext.finally
let with_lock = Xapi_stdext_threads.Threadext.Mutex.execute
let lwsmd_service = "lwsmd"
module Lwsmd = struct
This can be refined by Mtime.Span.hour when is updated to 1.4.0
let restart_interval = Int64.mul 3600L 1000000000L |> Mtime.Span.of_uint64_ns
let next_check_point =
Mtime.add_span (Mtime_clock.now ()) restart_interval |> ref
let is_ad_enabled ~__context =
( Helpers.get_localhost ~__context |> fun self ->
Db.Host.get_external_auth_type ~__context ~self
)
|> fun x -> x = Xapi_globs.auth_type_AD
let enable_nsswitch () =
try
ignore
(Forkhelpers.execute_command_get_output
!Xapi_globs.domain_join_cli_cmd
["configure"; "--enable"; "nsswitch"]
)
with e ->
error "Fail to run %s with error %s"
!Xapi_globs.domain_join_cli_cmd
(ExnHelper.string_of_exn e)
let stop ~timeout ~wait_until_success =
Xapi_systemctl.stop ~timeout ~wait_until_success lwsmd_service
let start ~timeout ~wait_until_success =
Xapi_systemctl.start ~timeout ~wait_until_success lwsmd_service
let restart ~timeout ~wait_until_success =
Xapi_systemctl.restart ~timeout ~wait_until_success lwsmd_service
let restart_on_error () =
let now = Mtime_clock.now () in
match !next_check_point with
| Some check_point ->
if Mtime.is_later now ~than:check_point then (
debug "Restart %s due to local server error" lwsmd_service ;
next_check_point := Mtime.add_span now restart_interval ;
restart ~timeout:0. ~wait_until_success:false
)
| None ->
debug "next_check_point overflow"
let init_service ~__context =
This function is called during start
does not wait lwsmd service to boot up success as following reasons
* 1 . The waiting will slow down
* 2 . still needs to boot up even lwsmd bootup fail
* 3 . does not need to use lwsmd functionality during its bootup
* 1. The waiting will slow down xapi bootup
* 2. Xapi still needs to boot up even lwsmd bootup fail
* 3. Xapi does not need to use lwsmd functionality during its bootup *)
if is_ad_enabled ~__context then (
restart ~wait_until_success:false ~timeout:5. ;
help to enable nsswitch during bootup if it find the host is authed with AD
* nsswitch will be automatically enabled with command
* but this enabling is necessary when the host authed with AD upgrade
* As it will not run the - cli command again
* nsswitch will be automatically enabled with command domainjoin-cli
* but this enabling is necessary when the host authed with AD upgrade
* As it will not run the domainjoin-cli command again *)
enable_nsswitch ()
)
end
let match_error_tag (lines : string list) =
let err_catch_list =
[
("DNS_ERROR_BAD_PACKET", Auth_signature.E_LOOKUP)
; ("LW_ERROR_PASSWORD_MISMATCH", Auth_signature.E_CREDENTIALS)
; ("LW_ERROR_INVALID_ACCOUNT", Auth_signature.E_INVALID_ACCOUNT)
; ("LW_ERROR_ACCESS_DENIED", Auth_signature.E_DENIED)
; ("LW_ERROR_DOMAIN_IS_OFFLINE", Auth_signature.E_UNAVAILABLE)
; ("LW_ERROR_INVALID_OU", Auth_signature.E_INVALID_OU)
]
in
let split_to_words str =
let seps = ['('; ')'; ' '; '\t'; '.'] in
String.split_f (fun s -> List.exists (fun sep -> sep = s) seps) str
in
let rec has_err lines err_pattern =
match lines with
| [] ->
false
| line :: rest -> (
try
ignore (List.find (fun w -> w = err_pattern) (split_to_words line)) ;
true
with Not_found -> has_err rest err_pattern
)
in
try
let _, errtag =
List.find
(fun (err_pattern, _) -> has_err lines err_pattern)
err_catch_list
in
errtag
with Not_found -> Auth_signature.E_GENERIC
let extract_sid_from_group_list group_list =
List.map
(fun (_, v) ->
let v = String.replace ")" "" v in
let v = String.replace "sid =" "|" v in
let vs = String.split_f (fun c -> c = '|') v in
let sid = String.trim (List.nth vs 1) in
debug "extract_sid_from_group_list get sid=[%s]" sid ;
sid
)
(List.filter (fun (n, _) -> n = "") group_list)
let start_damon () =
try Lwsmd.start ~timeout:5. ~wait_until_success:true
with _ ->
raise
(Auth_signature.Auth_service_error
( Auth_signature.E_GENERIC
, Printf.sprintf "Failed to start %s" lwsmd_service
)
)
module AuthADlw : Auth_signature.AUTH_MODULE = struct
* External Authentication Plugin component
* using AD / Pbis as a backend
* v1 14Nov14
*
* External Authentication Plugin component
* using AD/Pbis as a backend
* v1 14Nov14
*
*)
let user_friendly_error_msg =
"The Active Directory Plug-in could not complete the command. Additional \
information in the logs."
let mutex_check_availability =
Locking_helpers.Named_mutex.create "IS_SERVER_AVAILABLE"
let splitlines s =
String.split_f (fun c -> c = '\n') (String.replace "#012" "\n" s)
let pbis_common_with_password (password : string) (pbis_cmd : string)
(pbis_args : string list) =
let debug_cmd =
pbis_cmd ^ " " ^ List.fold_left (fun p pp -> p ^ " " ^ pp) " " pbis_args
in
try
debug "execute %s" debug_cmd ;
let env = [|"PASSWORD=" ^ password|] in
let _ = Forkhelpers.execute_command_get_output ~env pbis_cmd pbis_args in
[]
with
| Forkhelpers.Spawn_internal_error (stderr, stdout, Unix.WEXITED n) ->
error "execute %s exited with code %d [stdout = '%s'; stderr = '%s']"
debug_cmd n stdout stderr ;
let lines =
List.filter
(fun l -> String.length l > 0)
(splitlines (stdout ^ stderr))
in
let errmsg = List.hd (List.rev lines) in
let errtag = match_error_tag lines in
raise (Auth_signature.Auth_service_error (errtag, errmsg))
| e ->
error "execute %s exited: %s" debug_cmd (ExnHelper.string_of_exn e) ;
raise
(Auth_signature.Auth_service_error
(Auth_signature.E_GENERIC, user_friendly_error_msg)
)
let pbis_config (name : string) (value : string) =
let pbis_cmd = "/opt/pbis/bin/config" in
let pbis_args = [name; value] in
let debug_cmd = pbis_cmd ^ " " ^ name ^ " " ^ value in
try
debug "execute %s" debug_cmd ;
let _ = Forkhelpers.execute_command_get_output pbis_cmd pbis_args in
()
with
| Forkhelpers.Spawn_internal_error (stderr, stdout, Unix.WEXITED n) ->
error "execute %s exited with code %d [stdout = '%s'; stderr = '%s']"
debug_cmd n stdout stderr ;
let lines =
List.filter
(fun l -> String.length l > 0)
(splitlines (stdout ^ stderr))
in
let errmsg = List.hd (List.rev lines) in
raise
(Auth_signature.Auth_service_error (Auth_signature.E_GENERIC, errmsg))
| e ->
error "execute %s exited: %s" debug_cmd (ExnHelper.string_of_exn e) ;
raise
(Auth_signature.Auth_service_error
(Auth_signature.E_GENERIC, user_friendly_error_msg)
)
let ensure_pbis_configured () =
pbis_config "SpaceReplacement" "+" ;
pbis_config "CreateHomeDir" "false" ;
pbis_config "SyncSystemTime" "false" ;
pbis_config "LdapSignAndSeal" "true" ;
pbis_config "CacheEntryExpiry" "300" ;
()
let pbis_common ?(stdin_string = "") (pbis_cmd : string)
(pbis_args : string list) =
let debug_cmd =
pbis_cmd ^ " " ^ List.fold_left (fun p pp -> p ^ " " ^ pp) " " pbis_args
in
let debug_cmd =
if String.has_substr debug_cmd "--password" then
"(omitted for security)"
else
debug_cmd
in
let fds_to_close = ref [] in
let files_to_unlink = ref [] in
let close_fd fd =
if List.mem fd !fds_to_close then (
Unix.close fd ;
fds_to_close := List.filter (fun x -> x <> fd) !fds_to_close
)
in
let unlink_file filename =
if List.mem filename !files_to_unlink then (
Unix.unlink filename ;
files_to_unlink := List.filter (fun x -> x <> filename) !files_to_unlink
)
in
let finalize () =
List.iter close_fd !fds_to_close ;
List.iter unlink_file !files_to_unlink
in
let finally_finalize f = finally f finalize in
let exited_code = ref 0 in
let output = ref "" in
finally_finalize (fun () ->
let _ =
try
debug "execute %s" debug_cmd ;
creates pipes between and pbis process
let in_readme, in_writeme = Unix.pipe () in
fds_to_close := in_readme :: in_writeme :: !fds_to_close ;
let out_tmpfile = Filename.temp_file "pbis" ".out" in
files_to_unlink := out_tmpfile :: !files_to_unlink ;
let err_tmpfile = Filename.temp_file "pbis" ".err" in
files_to_unlink := err_tmpfile :: !files_to_unlink ;
let out_writeme = Unix.openfile out_tmpfile [Unix.O_WRONLY] 0o0 in
fds_to_close := out_writeme :: !fds_to_close ;
let err_writeme = Unix.openfile err_tmpfile [Unix.O_WRONLY] 0o0 in
fds_to_close := err_writeme :: !fds_to_close ;
let pid =
Forkhelpers.safe_close_and_exec (Some in_readme)
(Some out_writeme) (Some err_writeme) [] pbis_cmd pbis_args
in
finally
(fun () ->
debug "Created process pid %s for cmd %s"
(Forkhelpers.string_of_pidty pid)
debug_cmd ;
Insert this delay to reproduce the can not write to stdin bug :
Thread.delay 5 . ;
Thread.delay 5.; *)
WARNING : we do n't close the in_readme because otherwise in the case where the pbis
binary does n't expect any input there is a race between it finishing ( and closing the last
reference to the in_readme ) and us attempting to write to in_writeme . If pbis wins the
race then our write will fail with EPIPE ( Unix.error 31 in ocamlese ) . If we keep a reference
to in_readme then our write of " \n " will succeed .
An alternative fix would be to not write anything when stdin_string = " "
binary doesn't expect any input there is a race between it finishing (and closing the last
reference to the in_readme) and us attempting to write to in_writeme. If pbis wins the
race then our write will fail with EPIPE (Unix.error 31 in ocamlese). If we keep a reference
to in_readme then our write of "\n" will succeed.
An alternative fix would be to not write anything when stdin_string = "" *)
push stdin_string to recently created process ' STDIN
try
usually , STDIN contains some sensitive data such as passwords that we do not want showing up in ps
or in the debug log via debug_cmd
let stdin_string = stdin_string ^ "\n" in
HACK : without , the pbis scripts do n't return !
let (_ : int) =
Unix.write_substring in_writeme stdin_string 0
(String.length stdin_string)
in
close_fd in_writeme
we need to close stdin , otherwise the unix cmd waits forever
with e ->
debug "Error writing to stdin for cmd %s: %s" debug_cmd
(ExnHelper.string_of_exn e) ;
raise
(Auth_signature.Auth_service_error
(Auth_signature.E_GENERIC, ExnHelper.string_of_exn e)
)
)
(fun () ->
match Forkhelpers.waitpid pid with
| _, Unix.WEXITED n ->
exited_code := n ;
output :=
Xapi_stdext_unix.Unixext.string_of_file out_tmpfile
^ Xapi_stdext_unix.Unixext.string_of_file err_tmpfile
| _ ->
error "PBIS %s exit with WSTOPPED or WSIGNALED" debug_cmd ;
raise
(Auth_signature.Auth_service_error
(Auth_signature.E_GENERIC, user_friendly_error_msg)
)
)
with e ->
error "execute %s exited: %s" debug_cmd (ExnHelper.string_of_exn e) ;
raise
(Auth_signature.Auth_service_error
(Auth_signature.E_GENERIC, user_friendly_error_msg)
)
in
if !exited_code <> 0 then (
error "execute '%s': exit_code=[%d] output=[%s]" debug_cmd
!exited_code
(String.replace "\n" ";" !output) ;
let split_to_words s =
String.split_f (fun c -> c = '(' || c = ')' || c = '.' || c = ' ') s
in
let revlines =
List.rev
(List.filter (fun l -> String.length l > 0) (splitlines !output))
in
let errmsg = List.hd revlines in
let errcodeline =
if List.length revlines > 1 then List.nth revlines 1 else errmsg
in
let errcode =
List.hd
(List.filter
(fun w -> String.startswith "LW_ERROR_" w)
(split_to_words errcodeline)
)
in
debug "Pbis raised an error for cmd %s: (%s) %s" debug_cmd errcode
errmsg ;
match errcode with
| "LW_ERROR_INVALID_GROUP_INFO_LEVEL" ->
raise
(Auth_signature.Auth_service_error
(Auth_signature.E_GENERIC, errcode)
)
| "LW_ERROR_NO_SUCH_USER"
| "LW_ERROR_NO_SUCH_GROUP"
| "LW_ERROR_NO_SUCH_OBJECT" ->
| "LW_ERROR_KRB5_CALL_FAILED"
| "LW_ERROR_PASSWORD_MISMATCH"
| "LW_ERROR_ACCOUNT_DISABLED"
| "LW_ERROR_NOT_HANDLED" ->
raise (Auth_signature.Auth_failure errmsg)
| "LW_ERROR_INVALID_OU" ->
raise
(Auth_signature.Auth_service_error
(Auth_signature.E_INVALID_OU, errmsg)
)
| "LW_ERROR_INVALID_DOMAIN" ->
raise
(Auth_signature.Auth_service_error
(Auth_signature.E_GENERIC, errmsg)
)
| "LW_ERROR_ERRNO_ECONNREFUSED" ->
CA-368806 : Restart service to workaround pbis wedged
Lwsmd.restart_on_error () ;
raise
(Auth_signature.Auth_service_error
(Auth_signature.E_GENERIC, errmsg)
)
| "LW_ERROR_LSA_SERVER_UNREACHABLE" | _ ->
raise
(Auth_signature.Auth_service_error
( Auth_signature.E_GENERIC
, Printf.sprintf "(%s) %s" errcode errmsg
)
)
) else
debug "execute %s: output length=[%d]" debug_cmd
(String.length !output) ;
let lines =
List.filter (fun l -> String.length l > 0) (splitlines !output)
in
let parse_line (acc, currkey) line =
let slices = String.split ~limit:2 ':' line in
debug "parse %s: currkey=[%s] line=[%s]" debug_cmd currkey line ;
if List.length slices > 1 then (
let key = String.trim (List.hd slices) in
let value = String.trim (List.nth slices 1) in
debug "parse %s: key=[%s] value=[%s] currkey=[%s]" debug_cmd key
value currkey ;
if String.length value > 0 then
(acc @ [(key, value)], "")
else
(acc, key)
) else
let key = currkey in
let value = String.trim line in
debug "parse %s: key=[%s] value=[%s] currkey=[%s]" debug_cmd key
value currkey ;
(acc @ [(key, value)], currkey)
in
let attrs, _ = List.fold_left parse_line ([], "") lines in
attrs
)
assoc list for caching pbis_common results ,
item value is ( ( stdin_string , pbis_cmd , ) , ( unix_time , pbis_common_result ) )
item value is ((stdin_string, pbis_cmd, pbis_args), (unix_time, pbis_common_result))
*)
let cache_of_pbis_common :
((string * string * string list) * (float * (string * string) list)) list
ref =
ref []
let cache_of_pbis_common_m = Mutex.create ()
let pbis_common_with_cache ?(stdin_string = "") (pbis_cmd : string)
(pbis_args : string list) =
let expired = 120.0 in
let now = Unix.time () in
let cache_key = (stdin_string, pbis_cmd, pbis_args) in
let f () =
cache_of_pbis_common :=
List.filter
(fun (_, (ts, _)) -> now -. ts < expired)
!cache_of_pbis_common ;
try
let _, result = List.assoc cache_key !cache_of_pbis_common in
debug "pbis_common_with_cache hit \"%s\" cache." pbis_cmd ;
result
with Not_found ->
let result = pbis_common ~stdin_string pbis_cmd pbis_args in
cache_of_pbis_common :=
!cache_of_pbis_common @ [(cache_key, (Unix.time (), result))] ;
result
in
with_lock cache_of_pbis_common_m f
let get_joined_domain_name () =
Server_helpers.exec_with_new_task "obtaining joined-domain name"
(fun __context ->
let host = Helpers.get_localhost ~__context in
Db.Host.get_external_auth_service_name ~__context ~self:host
)
let get_full_subject_name ?(use_nt_format = true) subject_name =
try
tests if the UPN account name separator @ is present in subject name
ignore (String.index subject_name '@') ;
subject_name
with Not_found -> (
try
if no UPN username separator @ was found
ignore (String.index subject_name '\\') ;
subject_name
with Not_found ->
if
if neither the UPN separator @ nor the NT username separator \ was found
use_nt_format
then
the default : NT names is unique , whereas UPN ones are not ( CA-27744 )
get_joined_domain_name () ^ "\\" ^ subject_name
obs : ( 1 ) pbis accepts a fully qualified domain name < domain.com > with both formats and
( 2 ) some pbis commands accept only the NT - format , such as find - group - by - name
else
UPN format not the default format ( CA-27744 )
we append the joined - domain name to the subjectname as a UPN name : < subjectname>@<domain.com >
subject_name ^ "@" ^ get_joined_domain_name ()
)
Converts from UPN format ( ) to legacy NT format ( )
For anything else , use the original UPN name
let convert_upn_to_nt_username subject_name =
try
test if the UPN account name separator @ is present in subject name
let i = String.index subject_name '@' in
when @ is present , we need to convert the UPN name to NT format
let user = String.sub subject_name 0 i in
let domain =
String.sub subject_name (i + 1) (String.length subject_name - i - 1)
in
domain ^ "\\" ^ user
with Not_found ->
if no UPN username separator @ was found
subject_name
let pbis_get_all_byid subject_id =
try
pbis_common_with_cache "/opt/pbis/bin/find-by-sid"
["--level"; "2"; subject_id]
with
| Auth_signature.Auth_service_error
(Auth_signature.E_GENERIC, "LW_ERROR_INVALID_GROUP_INFO_LEVEL")
->
pbis_common_with_cache "/opt/pbis/bin/find-by-sid"
["--level"; "1"; subject_id]
let pbis_get_group_sids_byname _subject_name =
let subject_name = get_full_subject_name _subject_name in
let subject_attrs =
pbis_common_with_cache "/opt/pbis/bin/list-groups-for-user"
["--show-sid"; subject_name]
in
PBIS list - groups - for - user raw output like
Number of groups found for user ' test@testdomain ' : 2
Group[1 of 2 ] name = testdomain\dnsadmins ( gid = 580912206 , = S-1 - 5 - 21 - 791009147 - 1041474540 - 2433379237 - 1102 )
Group[2 of 2 ] name = testdomain\domain+users ( gid = 580911617 , sid = S-1 - 5 - 21 - 791009147 - 1041474540 - 2433379237 - 513 )
And pbis_common will return subject_attrs as
[ ( " Number of groups found for user ' test@testdomain ' " , " 2 " ) , ( " " , ) , ( " " , line2 ) ... ( " " , lineN ) ]
Number of groups found for user 'test@testdomain' : 2
Group[1 of 2] name = testdomain\dnsadmins (gid = 580912206, sid = S-1-5-21-791009147-1041474540-2433379237-1102)
Group[2 of 2] name = testdomain\domain+users (gid = 580911617, sid = S-1-5-21-791009147-1041474540-2433379237-513)
And pbis_common will return subject_attrs as
[("Number of groups found for user 'test@testdomain'", "2"), ("", line1), ("", line2) ... ("", lineN)]
*)
extract_sid_from_group_list subject_attrs
general Pbis error
let pbis_get_sid_byname _subject_name cmd =
let subject_name = get_full_subject_name _subject_name in
let subject_attrs = pbis_common cmd ["--level"; "1"; subject_name] in
find - user - by - name returns several lines . We ony need the SID
if List.mem_assoc "SID" subject_attrs then
OK , return SID
else
no SID value returned
this should not have happend , pbis did n't return an SID field ! !
let msg =
Printf.sprintf "Pbis didn't return an SID field for user %s"
subject_name
in
debug "Error pbis_get_sid_byname for subject name %s: %s" subject_name msg ;
raise (Auth_signature.Auth_service_error (Auth_signature.E_GENERIC, msg))
general Pbis error
subject_id get_subject_identifier(string subject_name )
Takes a subject_name ( as may be entered into the XenCenter UI when defining subjects --
see Access Control wiki page ) ; and resolves it to a subject_id against the external
auth / directory service .
Raises Not_found ( * Subject_cannot_be_resolved
Takes a subject_name (as may be entered into the XenCenter UI when defining subjects --
see Access Control wiki page); and resolves it to a subject_id against the external
auth/directory service.
*)
let get_subject_identifier _subject_name =
try
let subject_name = get_full_subject_name _subject_name in
pbis_get_sid_byname subject_name "/opt/pbis/bin/find-user-by-name"
with _ ->
let subject_name =
get_full_subject_name ~use_nt_format:true
(convert_upn_to_nt_username _subject_name)
in
pbis_get_sid_byname subject_name "/opt/pbis/bin/find-group-by-name"
subject_id Authenticate_username_password(string username , string password )
Takes a username and password , and tries to authenticate against an already configured
auth service ( see XenAPI requirements Wiki page for details of how auth service configuration
takes place and the appropriate values are stored within the XenServer Metadata ) .
If authentication is successful then a subject_id is returned representing the account
corresponding to the supplied credentials ( where the subject_id is in a namespace managed by
the auth module / service itself -- e.g. maybe a SID or something in the AD case ) .
Raises auth_failure if authentication is not successful
Takes a username and password, and tries to authenticate against an already configured
auth service (see XenAPI requirements Wiki page for details of how auth service configuration
takes place and the appropriate values are stored within the XenServer Metadata).
If authentication is successful then a subject_id is returned representing the account
corresponding to the supplied credentials (where the subject_id is in a namespace managed by
the auth module/service itself -- e.g. maybe a SID or something in the AD case).
Raises auth_failure if authentication is not successful
*)
let authenticate_username_password username password =
let domain, user =
match String.split_f (fun c -> c = '\\') username with
| [domain; user] ->
(domain, user)
| [user] ->
(get_joined_domain_name (), user)
| _ ->
raise
(Auth_signature.Auth_service_error
(Auth_signature.E_GENERIC, "Invalid username " ^ username)
)
in
let (_ : (string * string) list) =
pbis_common "/opt/pbis/bin/lsa"
[
"authenticate-user"
; "--user"
; user
; "--domain"
; domain
; "--password"
; password
]
in
get_subject_identifier (get_full_subject_name username)
let authenticate_ticket _tgt =
failwith "extauth_plugin authenticate_ticket not implemented"
( ( string*string ) list ) )
Takes a subject_identifier and returns the user record from the directory service as
key / value pairs . In the returned string*string map , there _ must _ be a key called
subject_name that refers to the name of the account ( e.g. the user or group name as may
be displayed in ) . There is no other requirements to include fields from the user
record -- initially qI'd imagine that we would n't bother adding anything else here , but
it 's a string*string list anyway for possible future expansion .
Raises Not_found ( * Subject_cannot_be_resolved
Takes a subject_identifier and returns the user record from the directory service as
key/value pairs. In the returned string*string map, there _must_ be a key called
subject_name that refers to the name of the account (e.g. the user or group name as may
be displayed in XenCenter). There is no other requirements to include fields from the user
record -- initially qI'd imagine that we wouldn't bother adding anything else here, but
it's a string*string list anyway for possible future expansion.
*)
let query_subject_information subject_identifier =
let unmap_lw_space_chars lwname =
let defensive_copy = Bytes.of_string lwname in
the space - replacement char used by pbis is defined at /etc / pbis / lsassd.conf
let current_lw_space_replacement = '+' in
String.iteri
(fun i c ->
if c = current_lw_space_replacement then
Bytes.set defensive_copy i ' '
else
()
)
lwname ;
Bytes.unsafe_to_string defensive_copy
in
let get_value name ls =
if List.mem_assoc name ls then List.assoc name ls else ""
in
let infolist = pbis_get_all_byid subject_identifier in
let subject_is_group = get_value "Uid" infolist = "" in
if subject_is_group then
in this case , a few info fields are not available : UPN , Uid , Gecos , Account { disabled , expired , locked } , Password expired
[
("subject-name", unmap_lw_space_chars (get_value "Name" infolist))
; ("subject-gid", get_value "Gid" infolist)
; ("subject-sid", get_value "SID" infolist)
; ("subject-is-group", "true")
("contains-byname", List.fold_left (fun (n,v) m ->m^","^v) "" (List.filter (fun (n,v)->n="Members") infolist));*)
]
let subject_name = unmap_lw_space_chars (get_value "Name" infolist) in
let subject_gecos = get_value "Gecos" infolist in
[
("subject-name", subject_name)
; ("subject-upn", get_value "UPN" infolist)
; ("subject-uid", get_value "Uid" infolist)
; ("subject-gid", get_value "Gid" infolist)
; ("subject-sid", get_value "SID" infolist)
; ("subject-gecos", subject_gecos)
; ( "subject-displayname"
, if subject_gecos = "" || subject_gecos = "<null>" then
subject_name
else
subject_gecos
)
( " subject - homedir " , get_value " Home dir " infolist ) ;
( " subject - shell " , get_value " Shell " infolist ) ;
("subject-is-group", "false")
; ( "subject-account-disabled"
, get_value "Account disabled (or locked)" infolist
)
; ("subject-account-expired", get_value "Account Expired" infolist)
; ( "subject-account-locked"
, get_value "Account disabled (or locked)" infolist
)
; ("subject-password-expired", get_value "Password Expired" infolist)
]
( string list ) query_group_membership(string subject_identifier )
Takes a subject_identifier and returns its group membership ( i.e. a list of subject
identifiers of the groups that the subject passed in belongs to ) . The set of groups returned
_ must _ be transitively closed wrt the is_member_of relation if the external directory service
supports nested groups ( as does for example )
Takes a subject_identifier and returns its group membership (i.e. a list of subject
identifiers of the groups that the subject passed in belongs to). The set of groups returned
_must_ be transitively closed wrt the is_member_of relation if the external directory service
supports nested groups (as AD does for example)
*)
let query_group_membership subject_identifier =
let subject_info = query_subject_information subject_identifier in
if
List.assoc "subject-is-group" subject_info = "true"
then
subject is a group , so get_group_sids_byname will not work because pbis 's list - groups
FIXME : default action for groups until workaround is found : return an empty list of membership groups
[]
else
let subject_name = List.assoc "subject-name" subject_info in
let subject_sid_membership_list =
pbis_get_group_sids_byname subject_name
in
debug "Resolved %i group sids for subject %s (%s): %s"
(List.length subject_sid_membership_list)
subject_name subject_identifier
(List.fold_left
(fun p pp -> if p = "" then pp else p ^ "," ^ pp)
"" subject_sid_membership_list
) ;
subject_sid_membership_list
let _is_pbis_server_available max_tries =
we _ need _ to use a username contained in our domain , otherwise the following tests wo n't work .
Microsoft KB / Q243330 article provides the KRBTGT account as a well - known built - in SID in AD
Microsoft KB / Q229909 article says that KRBTGT account can not be renamed or enabled , making
it the perfect target for such a test using a username ( Administrator account can be renamed )
Microsoft KB/Q243330 article provides the KRBTGT account as a well-known built-in SID in AD
Microsoft KB/Q229909 article says that KRBTGT account cannot be renamed or enabled, making
it the perfect target for such a test using a username (Administrator account can be renamed) *)
let krbtgt = "KRBTGT" in
let try_clear_cache () =
the primary purpose of this function is to clear the cache so that
[ try_fetch_sid ] is forced to perform an end to end query to the
AD server . as such , we do n't care if krbtgt was not originally in
the cache
[ try_fetch_sid ] is forced to perform an end to end query to the
AD server. as such, we don't care if krbtgt was not originally in
the cache *)
match get_full_subject_name krbtgt with
| exception _ ->
info
"_is_pbis_server_available: failed to get full subject name for %s"
krbtgt ;
Error ()
| full_username -> (
match
ignore
(pbis_common "/opt/pbis/bin/ad-cache"
["--delete-user"; "--name"; full_username]
)
with
| () | (exception Not_found) ->
Ok ()
| exception e ->
debug "Failed to remove user %s from cache: %s" full_username
(ExnHelper.string_of_exn e) ;
Error ()
)
in
let try_fetch_sid () =
try
let sid = get_subject_identifier krbtgt in
debug
"Request to external authentication server successful: user %s was \
found"
krbtgt ;
let (_ : (string * string) list) = query_subject_information sid in
debug
"Request to external authentication server successful: sid %s was \
found"
sid ;
Ok ()
with
| Not_found ->
that means that pbis is responding to at least cached subject queries .
in this case , was n't found in the AD domain . this usually indicates that the
AD domain is offline / inaccessible to pbis , which will cause problems , specially
to the ssh python hook - script , so we need to try again until KRBTGT is found , indicating
that the domain is online and accessible to pbis queries
in this case, KRBTGT wasn't found in the AD domain. this usually indicates that the
AD domain is offline/inaccessible to pbis, which will cause problems, specially
to the ssh python hook-script, so we need to try again until KRBTGT is found, indicating
that the domain is online and accessible to pbis queries *)
debug
"Request to external authentication server returned KRBTGT \
Not_found" ;
Error ()
| e ->
debug
"Request to external authentication server failed for reason: %s"
(ExnHelper.string_of_exn e) ;
Error ()
in
let rec go i =
if i > max_tries then (
info
"Testing external authentication server failed after %i tries, \
giving up!"
max_tries ;
false
) else (
debug
"Testing if external authentication server is accepting requests... \
attempt %i of %i"
i max_tries ;
let ( >>= ) = Rresult.( >>= ) in
if we do n't remove krbtgt from the cache before
query subject information about krbtgt , then
[ try_fetch_sid ] would erroneously return success
in the case that PBIS is running locally , but the
AD domain is offline
query subject information about krbtgt, then
[ try_fetch_sid ] would erroneously return success
in the case that PBIS is running locally, but the
AD domain is offline *)
match try_clear_cache () >>= try_fetch_sid with
| Error () ->
Thread.delay 5.0 ;
(go [@tailcall]) (i + 1)
| Ok () ->
true
)
in
go 0
let is_pbis_server_available max =
Locking_helpers.Named_mutex.execute mutex_check_availability (fun () ->
_is_pbis_server_available max
)
converts from domain.com\user to , in case domain.com is present in the subject_name
let convert_nt_to_upn_username subject_name =
try
let i = String.index subject_name '\\' in
when \ is present , we need to convert the NT name to UPN format
let domain = String.sub subject_name 0 i in
let user =
String.sub subject_name (i + 1) (String.length subject_name - i - 1)
in
user ^ "@" ^ domain
with Not_found ->
subject_name
unit on_enable(((string*string ) list ) config_params )
Called internally by _ on each host _ when a client enables an external auth service for the
pool via the XenAPI [ see AD integration wiki page ] . The config_params here are the ones passed
by the client as part of the corresponding XenAPI call .
On receiving this hook , the auth module should :
( i ) do whatever it needs to do ( if anything ) to register with the external auth / directory
service [ using the config params supplied to get access ]
( ii ) Write the config_params that it needs to store persistently in the XenServer metadata
into the Pool.external_auth_configuration field . [ Note - the rationale for making the plugin
write the config params it needs long - term into the XenServer metadata itself is so it can
explicitly filter any one - time credentials [ like username / password for example ] that it
does not need long - term . ]
Called internally by xapi _on each host_ when a client enables an external auth service for the
pool via the XenAPI [see AD integration wiki page]. The config_params here are the ones passed
by the client as part of the corresponding XenAPI call.
On receiving this hook, the auth module should:
(i) do whatever it needs to do (if anything) to register with the external auth/directory
service [using the config params supplied to get access]
(ii) Write the config_params that it needs to store persistently in the XenServer metadata
into the Pool.external_auth_configuration field. [Note - the rationale for making the plugin
write the config params it needs long-term into the XenServer metadata itself is so it can
explicitly filter any one-time credentials [like AD username/password for example] that it
does not need long-term.]
*)
let on_enable config_params =
but in the ldap plugin , we should ' join the AD / domain ' , i.e. we should
basically : ( 1 ) create a machine account in the realm ,
( 2 ) store the machine account password somewhere locally ( in a keytab )
start_damon () ;
if
not
(List.mem_assoc "user" config_params
&& List.mem_assoc "pass" config_params
)
then
raise
(Auth_signature.Auth_service_error
( Auth_signature.E_GENERIC
, "enable requires two config params: user and pass."
)
)
let hostname =
Server_helpers.exec_with_new_task "retrieving hostname"
(fun __context ->
let host = Helpers.get_localhost ~__context in
Db.Host.get_hostname ~__context ~self:host
)
in
if
String.fold_left (fun b ch -> b && ch >= '0' && ch <= '9') true hostname
then
raise
(Auth_signature.Auth_service_error
( Auth_signature.E_GENERIC
, Printf.sprintf "hostname '%s' cannot contain only digits."
hostname
)
)
else
let domain =
let service_name =
Server_helpers.exec_with_new_task
"retrieving external_auth_service_name" (fun __context ->
let host = Helpers.get_localhost ~__context in
Db.Host.get_external_auth_service_name ~__context ~self:host
)
in
if
List.mem_assoc "domain" config_params
let _domain = List.assoc "domain" config_params in
if service_name <> _domain then
raise
(Auth_signature.Auth_service_error
( Auth_signature.E_GENERIC
, "if present, config:domain must match service-name."
)
)
else
service_name
else
service_name
in
let _user = List.assoc "user" config_params in
let pass = List.assoc "pass" config_params in
let ou_conf, ou_params =
if List.mem_assoc "ou" config_params then
let ou = List.assoc "ou" config_params in
([("ou", ou)], ["--ou"; ou])
else
([], [])
in
Adding the config parameter " config : , Y , Z "
* will disable the modules X , Y and Z in .
* will disable the modules X, Y and Z in domainjoin-cli. *)
let disabled_modules =
try
match List.assoc "disable_modules" config_params with
| "" ->
[]
| disabled_modules_string ->
String.split_f (fun c -> c = ',') disabled_modules_string
with Not_found -> []
in
let disabled_module_params =
List.concat
(List.map
(fun disabled_module -> ["--disable"; disabled_module])
disabled_modules
)
in
we need to make sure that the user passed to domaijoin - cli command is in the UPN syntax ( )
let user = convert_nt_to_upn_username _user in
execute the pbis domain join cmd
try
let (_ : (string * string) list) =
[
["join"]
; ou_params
; disabled_module_params
; ["--ignore-pam"; "--notimesync"; domain; user]
]
|> List.concat
|> pbis_common_with_password pass !Xapi_globs.domain_join_cli_cmd
in
let max_tries = 60 in
tests 60 x 5.0 seconds = 300 seconds = 5minutes trying
if not (is_pbis_server_available max_tries) then (
let errmsg =
Printf.sprintf
"External authentication server not available after %i query \
tests"
max_tries
in
debug "%s" errmsg ;
raise
(Auth_signature.Auth_service_error
(Auth_signature.E_UNAVAILABLE, errmsg)
)
) ;
OK SUCCESS , pbis has joined the AD domain successfully
let extauthconf = [("domain", domain); ("user", user)] @ ou_conf in
Server_helpers.exec_with_new_task
"storing external_auth_configuration" (fun __context ->
let host = Helpers.get_localhost ~__context in
Db.Host.set_external_auth_configuration ~__context ~self:host
~value:extauthconf ;
debug "added external_auth_configuration for host %s"
(Db.Host.get_name_label ~__context ~self:host)
) ;
with_lock cache_of_pbis_common_m (fun _ -> cache_of_pbis_common := []) ;
ensure_pbis_configured ()
with e ->
debug
"Error enabling external authentication for domain %s and user %s: \
%s"
domain user
(ExnHelper.string_of_exn e) ;
raise e
unit on_disable ( )
Called internally by _ on each host _ when a client disables an auth service via the XenAPI .
The hook will be called _ before _ the Pool configuration fields relating to the external - auth
service are cleared ( i.e. so you can access the config params you need from the pool metadata
within the body of the on_disable method )
Called internally by xapi _on each host_ when a client disables an auth service via the XenAPI.
The hook will be called _before_ the Pool configuration fields relating to the external-auth
service are cleared (i.e. so you can access the config params you need from the pool metadata
within the body of the on_disable method)
*)
let on_disable config_params =
but in the ldap plugin , we should ' leave the AD / domain ' , i.e. we should
( 1 ) remove the machine account from the realm , ( 2 ) remove the keytab locally
let pbis_failure =
try
( if
not
(List.mem_assoc "user" config_params
&& List.mem_assoc "pass" config_params
)
then
no windows admin+pass have been provided : leave the pbis host in the AD database
execute the pbis domain - leave cmd
let (_ : (string * string) list) =
pbis_common !Xapi_globs.domain_join_cli_cmd ["leave"]
in
()
else
windows admin+pass have been provided : ask pbis to remove host from AD database
let _user = List.assoc "user" config_params in
let pass = List.assoc "pass" config_params in
we need to make sure that the user passed to domaijoin - cli command is in the UPN syntax ( )
let user =
convert_nt_to_upn_username
(get_full_subject_name ~use_nt_format:false _user)
in
execute the pbis domain - leave cmd
let (_ : (string * string) list) =
pbis_common_with_password pass
!Xapi_globs.domain_join_cli_cmd
["leave"; user]
in
()
) ;
no failure observed in pbis
with e ->
unexpected error disabling pbis
debug "Internal Pbis error when disabling external authentication: %s"
(ExnHelper.string_of_exn e) ;
without being able to disable an external authentication configuration , since the Pbis
behavior is outside our control . For instance , Pbis raises an exception during domain - leave
Not re - raising an exception here is not too bad , because both ssh and to the AD / Pbis
to login as an external user via ssh or to call external - authentication services via xapi / xe .
Some e
CA-28942 : stores exception returned by pbis for later
in
We always do a manual clean - up of pbis , in order to restore to its pre - pbis state
It does n't matter if pbis succeeded or not
This disables Pbis even from Dom0 shell
debug "Doing a manual Pbis domain-leave cleanup..." ;
When pbis raises an exception during domain - leave , we try again , using
some of the command - line workarounds that describes in CA-27627 :
let pbis_force_domain_leave_script =
"/opt/xensource/libexec/pbis-force-domain-leave"
in
( try
let output, stderr =
Forkhelpers.execute_command_get_output pbis_force_domain_leave_script
[]
in
debug "execute %s: stdout=[%s],stderr=[%s]"
pbis_force_domain_leave_script
(String.replace "\n" ";" output)
(String.replace "\n" ";" stderr)
with e ->
debug "exception executing %s: %s" pbis_force_domain_leave_script
(ExnHelper.string_of_exn e)
) ;
OK SUCCESS , pbis has left the AD domain successfully
Server_helpers.exec_with_new_task "removing external_auth_configuration"
(fun __context ->
let host = Helpers.get_localhost ~__context in
Db.Host.set_external_auth_configuration ~__context ~self:host ~value:[] ;
debug "removed external_auth_configuration for host %s"
(Db.Host.get_name_label ~__context ~self:host)
) ;
match pbis_failure with
| None ->
| Some e ->
raise e
bubble up pbis failure
unit on_xapi_initialize(bool system_boot )
Called internally by whenever it starts up . The system_boot flag is true iff is
starting for the first time after a host boot
Called internally by xapi whenever it starts up. The system_boot flag is true iff xapi is
starting for the first time after a host boot
*)
let on_xapi_initialize _system_boot =
the AD server is initialized outside , by init.d scripts
this function is called during initialization in xapi.ml
let max_tries = 12 in
tests 12 x 5.0 seconds = 60 seconds = up to 1 minute trying
if not (is_pbis_server_available max_tries) then (
let errmsg =
Printf.sprintf
"External authentication server not available after %i query tests"
max_tries
in
debug "%s" errmsg ;
raise
(Auth_signature.Auth_service_error (Auth_signature.E_GENERIC, errmsg))
) ;
()
unit on_xapi_exit ( )
Called internally when is doing a clean exit .
Called internally when xapi is doing a clean exit.
*)
let on_xapi_exit () =
()
let methods =
{
Auth_signature.authenticate_username_password
; Auth_signature.authenticate_ticket
; Auth_signature.get_subject_identifier
; Auth_signature.query_subject_information
; Auth_signature.query_group_membership
; Auth_signature.on_enable
; Auth_signature.on_disable
; Auth_signature.on_xapi_initialize
; Auth_signature.on_xapi_exit
}
end
|
61b3534f55d1fa9c0115102322c4b66b2de914d227f7ab985eae43dcc17a6ea6 | arachne-framework/factui | test_runner.cljc | (ns factui.test-runner
(:require [factui.impl.session-test]
[factui.api-test]
[factui.api-reactive-test]
#?(:clj [clojure.test :refer [deftest is are run-tests]]
:cljs [cljs.test :refer-macros [deftest is are run-tests]])))
#?(:cljs (enable-console-print!))
#?(:cljs
(defmethod cljs.test/report [:cljs.test/default :end-run-tests] [m]
(if (cljs.test/successful? m)
(.exit js/phantom 0)
(.exit js/phantom 1))))
(defn -main
"Entry point for running tests (until *.cljc tools catch up)"
[]
(run-tests
'factui.impl.session-test
'factui.api-reactive-test
'factui.api-test))
;; Run tests at the root level, in CLJS
#?(:cljs (-main))
| null | https://raw.githubusercontent.com/arachne-framework/factui/818ea79d7f84dfe80ad23ade0b6b2ed5bb1c6287/test/factui/test_runner.cljc | clojure | Run tests at the root level, in CLJS | (ns factui.test-runner
(:require [factui.impl.session-test]
[factui.api-test]
[factui.api-reactive-test]
#?(:clj [clojure.test :refer [deftest is are run-tests]]
:cljs [cljs.test :refer-macros [deftest is are run-tests]])))
#?(:cljs (enable-console-print!))
#?(:cljs
(defmethod cljs.test/report [:cljs.test/default :end-run-tests] [m]
(if (cljs.test/successful? m)
(.exit js/phantom 0)
(.exit js/phantom 1))))
(defn -main
"Entry point for running tests (until *.cljc tools catch up)"
[]
(run-tests
'factui.impl.session-test
'factui.api-reactive-test
'factui.api-test))
#?(:cljs (-main))
|
52642e94a218567c128387d2fb208ae8c7f7b50547be6cbde814c435f34e8042 | rbonichon/smtpp | do_parse.ml | (*********************************************************************************)
Copyright ( c ) 2015 , INRIA , Universite de Nancy 2 and Universidade Federal
do Rio Grande do Norte .
(* *)
(* 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. *)
(*********************************************************************************)
open Lexing;;
let report_error l =
let pos = lexeme_start_p l in
let o = pos.pos_cnum - pos.pos_bol in
Format.eprintf
"Error in file %s, line %d, column %d %s@."
pos.pos_fname pos.pos_lnum o
l.lex_buffer
;
;;
let lex_file fname =
try
let chan =
match fname with
| "-" -> stdin
| file -> open_in file
in
let lexbuf = Lexing.from_channel chan in
lexbuf.Lexing.lex_curr_p <- {
Lexing.pos_fname = fname;
Lexing.pos_lnum = 1;
Lexing.pos_bol = 0;
Lexing.pos_cnum = 0;
};
(lexbuf, fun () -> close_in chan)
with
| Not_found -> exit 2;
;;
let apply () =
let (lexbuf, close) = lex_file (List.hd (Config.get_files ())) in
try
let script = Parser.script Lexer.token lexbuf in
let ext_script = Extended_ast.load_theories script in
Io.debug "Parsing and elaboration done@.";
if Config.get_unused () then Undef_unused.apply_and_pp ext_script;
let ext_script =
if Config.get_detect () then
Extended_ast.set_logic
(Inferlogic.detect_and_print script)
ext_script
else ext_script
in
if Config.get_pushpop () then Pushpop.apply script;
if Config.get_obfuscate () then Obfuscator.apply ext_script;
if Config.get_reprint () then Pp.pp Format.std_formatter script;
if Config.get_preLA () then Pre_LA.pre_LA Format.std_formatter script;
(* if Config.get_preprocessor () then Preprocessor.apply script; *)
close ();
with
| Lexer.LexError msg ->
Format.eprintf "Parse error: %s@." msg;
report_error lexbuf
| Parser.Error ->
Format.eprintf "Parse error:@.";
report_error lexbuf
;;
| null | https://raw.githubusercontent.com/rbonichon/smtpp/57eb74bccbb0f30293ee058ded4b01baa1067756/src/do_parse.ml | ocaml | *******************************************************************************
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.
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
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*******************************************************************************
if Config.get_preprocessor () then Preprocessor.apply script; | Copyright ( c ) 2015 , INRIA , Universite de Nancy 2 and Universidade Federal
do Rio Grande do Norte .
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
open Lexing;;
let report_error l =
let pos = lexeme_start_p l in
let o = pos.pos_cnum - pos.pos_bol in
Format.eprintf
"Error in file %s, line %d, column %d %s@."
pos.pos_fname pos.pos_lnum o
l.lex_buffer
;
;;
let lex_file fname =
try
let chan =
match fname with
| "-" -> stdin
| file -> open_in file
in
let lexbuf = Lexing.from_channel chan in
lexbuf.Lexing.lex_curr_p <- {
Lexing.pos_fname = fname;
Lexing.pos_lnum = 1;
Lexing.pos_bol = 0;
Lexing.pos_cnum = 0;
};
(lexbuf, fun () -> close_in chan)
with
| Not_found -> exit 2;
;;
let apply () =
let (lexbuf, close) = lex_file (List.hd (Config.get_files ())) in
try
let script = Parser.script Lexer.token lexbuf in
let ext_script = Extended_ast.load_theories script in
Io.debug "Parsing and elaboration done@.";
if Config.get_unused () then Undef_unused.apply_and_pp ext_script;
let ext_script =
if Config.get_detect () then
Extended_ast.set_logic
(Inferlogic.detect_and_print script)
ext_script
else ext_script
in
if Config.get_pushpop () then Pushpop.apply script;
if Config.get_obfuscate () then Obfuscator.apply ext_script;
if Config.get_reprint () then Pp.pp Format.std_formatter script;
if Config.get_preLA () then Pre_LA.pre_LA Format.std_formatter script;
close ();
with
| Lexer.LexError msg ->
Format.eprintf "Parse error: %s@." msg;
report_error lexbuf
| Parser.Error ->
Format.eprintf "Parse error:@.";
report_error lexbuf
;;
|
044a14ecadd2d998c83bdd6ecbd4c60d786daf1cedf21b47e6aabf056988ed0e | UberPyro/prowl | ast.ml | open Format
open Lexing
type 'a loc = 'a * (position * position)
let span_flag = ref false
let span_of_pos p = p.pos_lnum, p.pos_cnum - p.pos_bol
let multispan_of_pos (p1, p2) =
let x1, y1 = span_of_pos p1 in
let x2, y2 = span_of_pos p2 in
x1, y1, x2, y2
let pp_loc c f (a, loc) =
c f a;
let x1, y1, x2, y2 = multispan_of_pos loc in
begin
if !span_flag
then Printf.sprintf " [%d:%d => %d:%d]" x1 y1 x2 y2
else ""
end |> pp_print_string f
type access_mod = Priv | Opaq | Pub [@@deriving show]
and sp = sp_t loc [@@deriving show]
and sp_t =
| SDef of string * ty
| STy of string * string list * ty option
| SData of string * string list * data
[@@deriving show]
and ty = ty_t loc [@@deriving show]
and ty_t = ty_term * ty_term [@@deriving show]
and ty_term = ty_term_t loc [@@deriving show]
and ty_term_t =
| TId of string
| TGen of string
| TAccess of ty_term * string
| TCat of ty_term list
| TCapture of ty
| TList of ty
| TMap of ty_term * ty
| TUnit
| TVoid
| TBin of ty list list
| TSig of sp list
| TMod of sp list
| TImpl of string * ty
[@@deriving show]
and data = data_t loc [@@deriving show]
and data_t = (ty_term list * string) list list [@@deriving show]
and s = s_t loc [@@deriving show]
and s_t =
| Def of access_mod * implicit * p * e * ty option
| Open of implicit * e
| Mix of e
| Ty of access_mod * string * string list * ty option
| Data of access_mod * string * string list * data
[@@deriving show]
and implicit = bool
and greed = Gre | Rel | Cut [@@deriving show]
and quant =
| Opt
| Plus
| Star
| Num of e
| Min of e
| Max of e
| Range of e * e
[@@deriving show]
and stack_comb = stack_comb_t loc [@@deriving show]
and stack_comb_t =
| Dup of int
| Zap of int
| Rot of int
| Run of int
[@@deriving show]
and det_control = {
d_try: bool;
d_parallel: bool;
det: det_control_core;
} [@@deriving show]
and det_control_core =
| DNone
| DOne
| DCut
| DScore
| DMany
[@@deriving show]
and e = e_t loc [@@deriving show]
and e_t =
| Id of string
| Access of e * string
| Get of e * e
(* Todo: Data & Tuple access *)
| Int of int
| Flo of float
| Char of char
| Str of string
| Unit
| List of e list
| Map of (e * e) list
| Pair of e * e
| Left of e
| Right of e
| EData of string
| Prod of e list
| Mod of s list
| Impl of e
| Capture of e
| Sect of string
| SectLeft of string * e
| SectRight of e * string
| Cat of e list
| Bop of e * string * e
| StackComb of stack_comb list
| Det of det_control
| Let of (string * implicit * p * e) list * e
| As of string * p * e
| Quant of e * quant * greed
| Case of (greed * e) list
| Inv of e list
| Span of e * e
| Noncap of e
| Cap of e
| Atomic of e
[@@deriving show]
and p = p_t loc [@@deriving show]
and p_t =
| PId of string
| PAccess of p * string
| PBlank
| PCat of p list
| PAsc of p * ty
| PImpl of p * ty
| POpen of implicit
| PUse
| PInt of int
| PFlo of float
| PStr of string
| PChar of char
| PUnit
| PList of p list
| PMap of (e * p) list
| PPair of p * p
| PLeft of p
| PRight of p
| PData of string
| PProd of p list
| PCapture of p
| PBop of p * string * p
[@@deriving show]
and program = access_mod * e [@@deriving show]
| null | https://raw.githubusercontent.com/UberPyro/prowl/8b59cf8870bfe0fab9b8b61f3f6662895b8c0f51/src/parse/ast.ml | ocaml | Todo: Data & Tuple access | open Format
open Lexing
type 'a loc = 'a * (position * position)
let span_flag = ref false
let span_of_pos p = p.pos_lnum, p.pos_cnum - p.pos_bol
let multispan_of_pos (p1, p2) =
let x1, y1 = span_of_pos p1 in
let x2, y2 = span_of_pos p2 in
x1, y1, x2, y2
let pp_loc c f (a, loc) =
c f a;
let x1, y1, x2, y2 = multispan_of_pos loc in
begin
if !span_flag
then Printf.sprintf " [%d:%d => %d:%d]" x1 y1 x2 y2
else ""
end |> pp_print_string f
type access_mod = Priv | Opaq | Pub [@@deriving show]
and sp = sp_t loc [@@deriving show]
and sp_t =
| SDef of string * ty
| STy of string * string list * ty option
| SData of string * string list * data
[@@deriving show]
and ty = ty_t loc [@@deriving show]
and ty_t = ty_term * ty_term [@@deriving show]
and ty_term = ty_term_t loc [@@deriving show]
and ty_term_t =
| TId of string
| TGen of string
| TAccess of ty_term * string
| TCat of ty_term list
| TCapture of ty
| TList of ty
| TMap of ty_term * ty
| TUnit
| TVoid
| TBin of ty list list
| TSig of sp list
| TMod of sp list
| TImpl of string * ty
[@@deriving show]
and data = data_t loc [@@deriving show]
and data_t = (ty_term list * string) list list [@@deriving show]
and s = s_t loc [@@deriving show]
and s_t =
| Def of access_mod * implicit * p * e * ty option
| Open of implicit * e
| Mix of e
| Ty of access_mod * string * string list * ty option
| Data of access_mod * string * string list * data
[@@deriving show]
and implicit = bool
and greed = Gre | Rel | Cut [@@deriving show]
and quant =
| Opt
| Plus
| Star
| Num of e
| Min of e
| Max of e
| Range of e * e
[@@deriving show]
and stack_comb = stack_comb_t loc [@@deriving show]
and stack_comb_t =
| Dup of int
| Zap of int
| Rot of int
| Run of int
[@@deriving show]
and det_control = {
d_try: bool;
d_parallel: bool;
det: det_control_core;
} [@@deriving show]
and det_control_core =
| DNone
| DOne
| DCut
| DScore
| DMany
[@@deriving show]
and e = e_t loc [@@deriving show]
and e_t =
| Id of string
| Access of e * string
| Get of e * e
| Int of int
| Flo of float
| Char of char
| Str of string
| Unit
| List of e list
| Map of (e * e) list
| Pair of e * e
| Left of e
| Right of e
| EData of string
| Prod of e list
| Mod of s list
| Impl of e
| Capture of e
| Sect of string
| SectLeft of string * e
| SectRight of e * string
| Cat of e list
| Bop of e * string * e
| StackComb of stack_comb list
| Det of det_control
| Let of (string * implicit * p * e) list * e
| As of string * p * e
| Quant of e * quant * greed
| Case of (greed * e) list
| Inv of e list
| Span of e * e
| Noncap of e
| Cap of e
| Atomic of e
[@@deriving show]
and p = p_t loc [@@deriving show]
and p_t =
| PId of string
| PAccess of p * string
| PBlank
| PCat of p list
| PAsc of p * ty
| PImpl of p * ty
| POpen of implicit
| PUse
| PInt of int
| PFlo of float
| PStr of string
| PChar of char
| PUnit
| PList of p list
| PMap of (e * p) list
| PPair of p * p
| PLeft of p
| PRight of p
| PData of string
| PProd of p list
| PCapture of p
| PBop of p * string * p
[@@deriving show]
and program = access_mod * e [@@deriving show]
|
1be85cfcb7f7565b3340d7c682bc07fa408ffd4b4e35f52a86855b85b6da9422 | juxt/vext | header_names.clj | Copyright © 2020 , JUXT LTD .
(ns juxt.vext.header-names
(:require
[clojure.string :as str]
[clojure.set :as set]))
(def header-canonical-case
{"a-im" "A-IM",
"accept" "Accept",
"accept-additions" "Accept-Additions",
"accept-charset" "Accept-Charset",
"accept-datetime" "Accept-Datetime",
"accept-encoding" "Accept-Encoding",
"accept-features" "Accept-Features",
"accept-language" "Accept-Language",
"accept-patch" "Accept-Patch",
"accept-post" "Accept-Post",
"accept-ranges" "Accept-Ranges",
"age" "Age",
"allow" "Allow",
"alpn" "ALPN",
"alt-svc" "Alt-Svc",
"alt-used" "Alt-Used",
"alternates" "Alternates",
"apply-to-redirect-ref" "Apply-To-Redirect-Ref",
"authentication-control" "Authentication-Control",
"authentication-info" "Authentication-Info",
"authorization" "Authorization",
"c-ext" "C-Ext",
"c-man" "C-Man",
"c-opt" "C-Opt",
"c-pep" "C-PEP",
"c-pep-info" "C-PEP-Info",
"cache-control" "Cache-Control",
"cal-managed-id" "Cal-Managed-ID",
"caldav-timezones" "CalDAV-Timezones",
"cdn-loop" "CDN-Loop",
"cert-not-after" "Cert-Not-After",
"cert-not-before" "Cert-Not-Before",
"close" "Close",
"connection" "Connection",
"content-base" "Content-Base",
"content-disposition" "Content-Disposition",
"content-encoding" "Content-Encoding",
"content-id" "Content-ID",
"content-language" "Content-Language",
"content-length" "Content-Length",
"content-location" "Content-Location",
"content-md5" "Content-MD5",
"content-range" "Content-Range",
"content-script-type" "Content-Script-Type",
"content-style-type" "Content-Style-Type",
"content-type" "Content-Type",
"content-version" "Content-Version",
"cookie" "Cookie",
"cookie2" "Cookie2",
"dasl" "DASL",
"date" "Date",
"dav" "DAV",
"default-style" "Default-Style",
"delta-base" "Delta-Base",
"depth" "Depth",
"derived-from" "Derived-From",
"destination" "Destination",
"differential-id" "Differential-ID",
"digest" "Digest",
"early-data" "Early-Data",
"etag" "ETag",
"expect" "Expect",
"expect-ct" "Expect-CT",
"expires" "Expires",
"ext" "Ext",
"forwarded" "Forwarded",
"from" "From",
"getprofile" "GetProfile",
"hobareg" "Hobareg",
"host" "Host",
"http2-settings" "HTTP2-Settings",
"if" "If",
"if-match" "If-Match",
"if-modified-since" "If-Modified-Since",
"if-none-match" "If-None-Match",
"if-range" "If-Range",
"if-schedule-tag-match" "If-Schedule-Tag-Match",
"if-unmodified-since" "If-Unmodified-Since",
"im" "IM",
"include-referred-token-binding-id"
"Include-Referred-Token-Binding-ID",
"keep-alive" "Keep-Alive",
"label" "Label",
"last-modified" "Last-Modified",
"link" "Link",
"location" "Location",
"lock-token" "Lock-Token",
"man" "Man",
"max-forwards" "Max-Forwards",
"memento-datetime" "Memento-Datetime",
"meter" "Meter",
"mime-version" "MIME-Version",
"negotiate" "Negotiate",
"odata-entityid" "OData-EntityId",
"odata-isolation" "OData-Isolation",
"odata-maxversion" "OData-MaxVersion",
"odata-version" "OData-Version",
"opt" "Opt",
"optional-www-authenticate" "Optional-WWW-Authenticate",
"ordering-type" "Ordering-Type",
"origin" "Origin",
"oscore" "OSCORE",
"overwrite" "Overwrite",
"p3p" "P3P",
"pep" "PEP",
"pep-info" "Pep-Info",
"pics-label" "PICS-Label",
"position" "Position",
"pragma" "Pragma",
"prefer" "Prefer",
"preference-applied" "Preference-Applied",
"profileobject" "ProfileObject",
"protocol" "Protocol",
"protocol-info" "Protocol-Info",
"protocol-query" "Protocol-Query",
"protocol-request" "Protocol-Request",
"proxy-authenticate" "Proxy-Authenticate",
"proxy-authentication-info" "Proxy-Authentication-Info",
"proxy-authorization" "Proxy-Authorization",
"proxy-features" "Proxy-Features",
"proxy-instruction" "Proxy-Instruction",
"public" "Public",
"public-key-pins" "Public-Key-Pins",
"public-key-pins-report-only" "Public-Key-Pins-Report-Only",
"range" "Range",
"redirect-ref" "Redirect-Ref",
"referer" "Referer",
"replay-nonce" "Replay-Nonce",
"retry-after" "Retry-After",
"safe" "Safe",
"schedule-reply" "Schedule-Reply",
"schedule-tag" "Schedule-Tag",
"sec-token-binding" "Sec-Token-Binding",
"sec-websocket-accept" "Sec-WebSocket-Accept",
"sec-websocket-extensions" "Sec-WebSocket-Extensions",
"sec-websocket-key" "Sec-WebSocket-Key",
"sec-websocket-protocol" "Sec-WebSocket-Protocol",
"sec-websocket-version" "Sec-WebSocket-Version",
"security-scheme" "Security-Scheme",
"server" "Server",
"set-cookie" "Set-Cookie",
"set-cookie2" "Set-Cookie2",
"setprofile" "SetProfile",
"slug" "SLUG",
"soapaction" "SoapAction",
"status-uri" "Status-URI",
"strict-transport-security" "Strict-Transport-Security",
"sunset" "Sunset",
"surrogate-capability" "Surrogate-Capability",
"surrogate-control" "Surrogate-Control",
"tcn" "TCN",
"te" "TE",
"timeout" "Timeout",
"topic" "Topic",
"trailer" "Trailer",
"transfer-encoding" "Transfer-Encoding",
"ttl" "TTL",
"upgrade" "Upgrade",
"urgency" "Urgency",
"uri" "URI",
"user-agent" "User-Agent",
"variant-vary" "Variant-Vary",
"vary" "Vary",
"via" "Via",
"want-digest" "Want-Digest",
"warning" "Warning",
"www-authenticate" "WWW-Authenticate",
"x-content-type-options" "X-Content-Type-Options",
"x-frame-options" "X-Frame-Options"})
(defn create-header-map []
(->>
(str/split (slurp "-headers/perm-headers.csv") #"\n")
(map (fn [line] (str/split line #",")) )
(filter (fn [[_ _ protocol]] (= protocol "http")))
(map first)
(sort)
(map (juxt str/lower-case identity))
(into (sorted-map))))
(defn- wrap-headers-normalize-case-response [response]
(update response :headers set/rename-keys header-canonical-case))
(defn wrap-headers-normalize-case
"Turn headers into their normalized case. Eg. user-agent becomes User-Agent."
[h]
(fn
([req]
(wrap-headers-normalize-case-response (h req)))
([req respond raise]
(h
req
(fn [response]
(respond (wrap-headers-normalize-case-response response)))
raise))))
| null | https://raw.githubusercontent.com/juxt/vext/9e109bb43b0cb2c31ec439e7438c7bfb298ff16d/src/juxt/vext/header_names.clj | clojure | Copyright © 2020 , JUXT LTD .
(ns juxt.vext.header-names
(:require
[clojure.string :as str]
[clojure.set :as set]))
(def header-canonical-case
{"a-im" "A-IM",
"accept" "Accept",
"accept-additions" "Accept-Additions",
"accept-charset" "Accept-Charset",
"accept-datetime" "Accept-Datetime",
"accept-encoding" "Accept-Encoding",
"accept-features" "Accept-Features",
"accept-language" "Accept-Language",
"accept-patch" "Accept-Patch",
"accept-post" "Accept-Post",
"accept-ranges" "Accept-Ranges",
"age" "Age",
"allow" "Allow",
"alpn" "ALPN",
"alt-svc" "Alt-Svc",
"alt-used" "Alt-Used",
"alternates" "Alternates",
"apply-to-redirect-ref" "Apply-To-Redirect-Ref",
"authentication-control" "Authentication-Control",
"authentication-info" "Authentication-Info",
"authorization" "Authorization",
"c-ext" "C-Ext",
"c-man" "C-Man",
"c-opt" "C-Opt",
"c-pep" "C-PEP",
"c-pep-info" "C-PEP-Info",
"cache-control" "Cache-Control",
"cal-managed-id" "Cal-Managed-ID",
"caldav-timezones" "CalDAV-Timezones",
"cdn-loop" "CDN-Loop",
"cert-not-after" "Cert-Not-After",
"cert-not-before" "Cert-Not-Before",
"close" "Close",
"connection" "Connection",
"content-base" "Content-Base",
"content-disposition" "Content-Disposition",
"content-encoding" "Content-Encoding",
"content-id" "Content-ID",
"content-language" "Content-Language",
"content-length" "Content-Length",
"content-location" "Content-Location",
"content-md5" "Content-MD5",
"content-range" "Content-Range",
"content-script-type" "Content-Script-Type",
"content-style-type" "Content-Style-Type",
"content-type" "Content-Type",
"content-version" "Content-Version",
"cookie" "Cookie",
"cookie2" "Cookie2",
"dasl" "DASL",
"date" "Date",
"dav" "DAV",
"default-style" "Default-Style",
"delta-base" "Delta-Base",
"depth" "Depth",
"derived-from" "Derived-From",
"destination" "Destination",
"differential-id" "Differential-ID",
"digest" "Digest",
"early-data" "Early-Data",
"etag" "ETag",
"expect" "Expect",
"expect-ct" "Expect-CT",
"expires" "Expires",
"ext" "Ext",
"forwarded" "Forwarded",
"from" "From",
"getprofile" "GetProfile",
"hobareg" "Hobareg",
"host" "Host",
"http2-settings" "HTTP2-Settings",
"if" "If",
"if-match" "If-Match",
"if-modified-since" "If-Modified-Since",
"if-none-match" "If-None-Match",
"if-range" "If-Range",
"if-schedule-tag-match" "If-Schedule-Tag-Match",
"if-unmodified-since" "If-Unmodified-Since",
"im" "IM",
"include-referred-token-binding-id"
"Include-Referred-Token-Binding-ID",
"keep-alive" "Keep-Alive",
"label" "Label",
"last-modified" "Last-Modified",
"link" "Link",
"location" "Location",
"lock-token" "Lock-Token",
"man" "Man",
"max-forwards" "Max-Forwards",
"memento-datetime" "Memento-Datetime",
"meter" "Meter",
"mime-version" "MIME-Version",
"negotiate" "Negotiate",
"odata-entityid" "OData-EntityId",
"odata-isolation" "OData-Isolation",
"odata-maxversion" "OData-MaxVersion",
"odata-version" "OData-Version",
"opt" "Opt",
"optional-www-authenticate" "Optional-WWW-Authenticate",
"ordering-type" "Ordering-Type",
"origin" "Origin",
"oscore" "OSCORE",
"overwrite" "Overwrite",
"p3p" "P3P",
"pep" "PEP",
"pep-info" "Pep-Info",
"pics-label" "PICS-Label",
"position" "Position",
"pragma" "Pragma",
"prefer" "Prefer",
"preference-applied" "Preference-Applied",
"profileobject" "ProfileObject",
"protocol" "Protocol",
"protocol-info" "Protocol-Info",
"protocol-query" "Protocol-Query",
"protocol-request" "Protocol-Request",
"proxy-authenticate" "Proxy-Authenticate",
"proxy-authentication-info" "Proxy-Authentication-Info",
"proxy-authorization" "Proxy-Authorization",
"proxy-features" "Proxy-Features",
"proxy-instruction" "Proxy-Instruction",
"public" "Public",
"public-key-pins" "Public-Key-Pins",
"public-key-pins-report-only" "Public-Key-Pins-Report-Only",
"range" "Range",
"redirect-ref" "Redirect-Ref",
"referer" "Referer",
"replay-nonce" "Replay-Nonce",
"retry-after" "Retry-After",
"safe" "Safe",
"schedule-reply" "Schedule-Reply",
"schedule-tag" "Schedule-Tag",
"sec-token-binding" "Sec-Token-Binding",
"sec-websocket-accept" "Sec-WebSocket-Accept",
"sec-websocket-extensions" "Sec-WebSocket-Extensions",
"sec-websocket-key" "Sec-WebSocket-Key",
"sec-websocket-protocol" "Sec-WebSocket-Protocol",
"sec-websocket-version" "Sec-WebSocket-Version",
"security-scheme" "Security-Scheme",
"server" "Server",
"set-cookie" "Set-Cookie",
"set-cookie2" "Set-Cookie2",
"setprofile" "SetProfile",
"slug" "SLUG",
"soapaction" "SoapAction",
"status-uri" "Status-URI",
"strict-transport-security" "Strict-Transport-Security",
"sunset" "Sunset",
"surrogate-capability" "Surrogate-Capability",
"surrogate-control" "Surrogate-Control",
"tcn" "TCN",
"te" "TE",
"timeout" "Timeout",
"topic" "Topic",
"trailer" "Trailer",
"transfer-encoding" "Transfer-Encoding",
"ttl" "TTL",
"upgrade" "Upgrade",
"urgency" "Urgency",
"uri" "URI",
"user-agent" "User-Agent",
"variant-vary" "Variant-Vary",
"vary" "Vary",
"via" "Via",
"want-digest" "Want-Digest",
"warning" "Warning",
"www-authenticate" "WWW-Authenticate",
"x-content-type-options" "X-Content-Type-Options",
"x-frame-options" "X-Frame-Options"})
(defn create-header-map []
(->>
(str/split (slurp "-headers/perm-headers.csv") #"\n")
(map (fn [line] (str/split line #",")) )
(filter (fn [[_ _ protocol]] (= protocol "http")))
(map first)
(sort)
(map (juxt str/lower-case identity))
(into (sorted-map))))
(defn- wrap-headers-normalize-case-response [response]
(update response :headers set/rename-keys header-canonical-case))
(defn wrap-headers-normalize-case
"Turn headers into their normalized case. Eg. user-agent becomes User-Agent."
[h]
(fn
([req]
(wrap-headers-normalize-case-response (h req)))
([req respond raise]
(h
req
(fn [response]
(respond (wrap-headers-normalize-case-response response)))
raise))))
| |
a65e5a7f5614f4a3d02bfc314d52ff3d9c5985ab773e988ea2d9e0208b730ec1 | satos---jp/mincaml_self_hosting | string.ml |
let rec concat s vs =
match vs with
| [] -> ""
| [x] -> x
| x :: xs -> x ^ s ^ (concat s xs)
let make n c =
let cs = Char.escaped c in
let rec f x =
if x <= 0 then "" else cs ^ (f (x-1))
in
f n
let rec sub s a b =
if b <= 0 then "" else
(make 1 (String.get s a)) ^ (sub s (a+1) (b-1))
| null | https://raw.githubusercontent.com/satos---jp/mincaml_self_hosting/5fdf8b5083437d7607a924142eea52d9b1de0439/lib/ml/string.ml | ocaml |
let rec concat s vs =
match vs with
| [] -> ""
| [x] -> x
| x :: xs -> x ^ s ^ (concat s xs)
let make n c =
let cs = Char.escaped c in
let rec f x =
if x <= 0 then "" else cs ^ (f (x-1))
in
f n
let rec sub s a b =
if b <= 0 then "" else
(make 1 (String.get s a)) ^ (sub s (a+1) (b-1))
| |
bbdacb017b9fe6ea3cbb3afd5e7ce787216f2d430593256d54b09a721b054428 | mariari/Misc-Lisp-Scripts | tester.lisp | (in-package "YOUR-PACKAGE")
(defparameter *hash-table* '#.*my-db-album*)
| null | https://raw.githubusercontent.com/mariari/Misc-Lisp-Scripts/acecadc75fcbe15e6b97e084d179aacdbbde06a8/Books/PracticalCommonLisp/Chapter1/tester.lisp | lisp | (in-package "YOUR-PACKAGE")
(defparameter *hash-table* '#.*my-db-album*)
| |
a68a9e60b0a30f1199bffeaeba1435e18d0a549c5161edf14509d47252770e57 | nuprl/gradual-typing-performance | quick-sample.rkt | #lang racket/base
(provide quick-sample)
;; -----------------------------------------------------------------------------
(require
benchmark-util
racket/file
(only-in racket/include include)
(only-in "quads.rkt"
page-break
column-break
word
box
block
block-break))
;; =============================================================================
(define (quick-sample)
(block '(measure 240.0 font "Times New Roman" leading 16.0 vmeasure 300.0 size 13.5 x-align justify x-align-last-line left)
(box '(width 15.0))
(block '()
(block '(weight bold) "Hot " (word '(size 22.0) "D") "ang, My Fellow Americans.")
" This "
(block '(no-break #t) "is some truly")
" nonsense generated from my typesetting system, which is called Quad. I’m writing this in a source file in DrRacket. When I click [Run], a PDF pops out. Not bad\u200a—\u200aand no LaTeX needed. Quad, however, does use the fancy linebreaking algorithm developed for TeX. (It also includes a faster linebreaking algorithm for when speed is more important than quality.) Of course, it can also handle "
(block '(font "Courier") "different fonts,")
(block '(style italic) " styles, ")
(word '(size 14.0 weight bold) "and sizes-")
" within the same line. As you can see, it can also justify paragraphs."
(block-break '())
(box '(width 15.0))
(block '() "“Each horizontal row represents " (box '(color "Red" background "Yellow") "an OS-level thread,") " and the colored dots represent important events in the execution of the program (they are color-coded to distinguish one event type from another). The upper-left blue dot in the timeline represents the future’s creation. The future executes for a brief period (represented by a green bar in the second line) on thread 1, and then pauses to allow the runtime thread to perform a future-unsafe operation.")
(column-break)
(box '(width 15.0))
(block '() "In the Racket implementation, future-unsafe operations fall into one of two categories. A blocking operation halts the evaluation of the future, and will not allow it to continue until it is touched. After the operation completes within touch, the remainder of the future’s work will be evaluated sequentially by the runtime thread. A synchronized operation also halts the future, but the runtime thread may perform the operation at any time and, once completed, the future may continue running in parallel. Memory allocation and JIT compilation are two common examples of synchronized operations." (page-break) "another page"))))
| null | https://raw.githubusercontent.com/nuprl/gradual-typing-performance/35442b3221299a9cadba6810573007736b0d65d4/paper/jfp-2016/src/worst-configurations-6.4/quadMB/0010101000000101/quick-sample.rkt | racket | -----------------------------------------------------------------------------
============================================================================= | #lang racket/base
(provide quick-sample)
(require
benchmark-util
racket/file
(only-in racket/include include)
(only-in "quads.rkt"
page-break
column-break
word
box
block
block-break))
(define (quick-sample)
(block '(measure 240.0 font "Times New Roman" leading 16.0 vmeasure 300.0 size 13.5 x-align justify x-align-last-line left)
(box '(width 15.0))
(block '()
(block '(weight bold) "Hot " (word '(size 22.0) "D") "ang, My Fellow Americans.")
" This "
(block '(no-break #t) "is some truly")
" nonsense generated from my typesetting system, which is called Quad. I’m writing this in a source file in DrRacket. When I click [Run], a PDF pops out. Not bad\u200a—\u200aand no LaTeX needed. Quad, however, does use the fancy linebreaking algorithm developed for TeX. (It also includes a faster linebreaking algorithm for when speed is more important than quality.) Of course, it can also handle "
(block '(font "Courier") "different fonts,")
(block '(style italic) " styles, ")
(word '(size 14.0 weight bold) "and sizes-")
" within the same line. As you can see, it can also justify paragraphs."
(block-break '())
(box '(width 15.0))
(block '() "“Each horizontal row represents " (box '(color "Red" background "Yellow") "an OS-level thread,") " and the colored dots represent important events in the execution of the program (they are color-coded to distinguish one event type from another). The upper-left blue dot in the timeline represents the future’s creation. The future executes for a brief period (represented by a green bar in the second line) on thread 1, and then pauses to allow the runtime thread to perform a future-unsafe operation.")
(column-break)
(box '(width 15.0))
(block '() "In the Racket implementation, future-unsafe operations fall into one of two categories. A blocking operation halts the evaluation of the future, and will not allow it to continue until it is touched. After the operation completes within touch, the remainder of the future’s work will be evaluated sequentially by the runtime thread. A synchronized operation also halts the future, but the runtime thread may perform the operation at any time and, once completed, the future may continue running in parallel. Memory allocation and JIT compilation are two common examples of synchronized operations." (page-break) "another page"))))
|
211224a9170bb489eb70a2d49259b2ee961ee15d5e8b08991ac00fc3ab418b05 | stchang/parsack | csv-parser-sepBy.rkt | #lang racket
(require parsack)
(provide (all-defined-out))
csv parser using sepBy combinator
;; - does not support quoted cells
;; cellContent in csv-parser.rkt
(define $cell (many (noneOf ",\n\r")))
;; a line must end in \n
(define $line (sepBy $cell (char #\,)))
;; result is list of list of chars
(define $csv (endBy $line $eol))
;; csvFile : Path -> String
(define (csvFile filename)
(parse $csv filename))
| null | https://raw.githubusercontent.com/stchang/parsack/57b21873e8e3eb7ffbdfa253251c3c27a66723b1/parsack-test/parsack/examples/csv-parser-sepBy.rkt | racket | - does not support quoted cells
cellContent in csv-parser.rkt
a line must end in \n
result is list of list of chars
csvFile : Path -> String | #lang racket
(require parsack)
(provide (all-defined-out))
csv parser using sepBy combinator
(define $cell (many (noneOf ",\n\r")))
(define $line (sepBy $cell (char #\,)))
(define $csv (endBy $line $eol))
(define (csvFile filename)
(parse $csv filename))
|
09bcdc81b884c1db68310558b7f8aa2d847f3827f46274ed53374ac7713188d2 | lehitoskin/blight | group.rkt | #lang racket/gui
; group.rkt
; contains group-window definitions
(require libtoxcore-racket/functions
"../config.rkt"
"chat.rkt"
"msg-editor.rkt"
"msg-history.rkt"
(only-in pict
bitmap
scale-to-fit
pict->bitmap))
(provide (all-defined-out))
(define group-window%
(class frame%
(inherit set-label)
(init-field this-label
this-width
this-height
this-tox
group-number)
(define mute-mic? #f)
(define mute-speakers? #f)
(set-default-chatframe-bindings chatframe-keymap)
(define/private repeat
(λ (proc times)
(cond [(zero? times) #t]
[else (proc) (repeat proc (- times 1))])))
; create a new top-level window
; make a frame by instantiating the frame% class
(define group-frame (new frame%
[label this-label]
[width this-width]
[height this-height]))
; set the frame icon
(let ([icon-bmp (make-bitmap 32 32)])
(send icon-bmp load-file logo)
(send group-frame set-icon icon-bmp))
; menu bar for group-frame
(define group-frame-menu-bar (new menu-bar%
[parent group-frame]))
; menu File for menu bar
(define menu-file (new menu% [parent group-frame-menu-bar]
[label "&File"]))
(define invite-frame (new frame%
[label "Blight - Invite Friend"]
[width 200]
[height 400]))
(define invite-list-box (new list-box%
[parent invite-frame]
[label "Friends"]
[style (list 'single 'vertical-label)]
[choices (list "")]
[callback (λ (l e)
(when (eq? (send e get-event-type)
'list-box-dclick)
(let ([selection (send l get-selection)])
(invite-friend this-tox selection group-number)
(send invite-frame show #f))))]))
(new button% [parent invite-frame]
[label "&Cancel"]
[callback (λ (button event)
(send invite-frame show #f))])
(define/public update-invite-list
(λ ()
(define num-friends (self-friend-list-size this-tox))
(unless (zero? num-friends)
(send invite-list-box clear)
; loop until we get all our friends
(do ((num 0 (+ num 1)))
((= num num-friends))
(let-values ([(success err friend-name-bytes) (friend-name this-tox num)])
; add to the invite list
(send invite-list-box append (bytes->string/utf-8 friend-name-bytes)))))))
(update-invite-list)
(new menu-item% [parent menu-file]
[label "Invite"]
[help-string "Invite a friend"]
[callback (λ (button event)
(send invite-frame show #t))])
; close the current window
(new menu-item% [parent menu-file]
[label "&Close"]
[shortcut #\W]
[help-string "Close Window"]
[callback (λ (button event)
(send this show #f))])
(define group-frame-msg (new message%
[parent group-frame]
[label this-label]
[min-width 40]))
(send group-frame-msg auto-resize #t)
(define group-text-receive (new text%
[line-spacing 1.0]
[auto-wrap #t]))
(send group-text-receive change-style black-style)
(define messages-keymap (init-messages-keymap this))
(set-default-messages-bindings messages-keymap)
(send messages-keymap chain-to-keymap chatframe-keymap #t)
(define custom-receive-canvas%
(class editor-canvas%
(inherit refresh get-dc get-size)
(init-field parent
label
editor
style
wheel-step
min-height
vert-margin
this-chat-window)
(define/public (get-chat-window) this-chat-window)
(define/override (on-char key-event)
(send messages-keymap handle-key-event editor key-event))
(super-new
[parent parent]
[label label]
[editor editor]
[style style]
[wheel-step wheel-step]
[min-height min-height]
[vert-margin vert-margin])))
(define topside-panel (new horizontal-panel%
[parent group-frame]))
(define custom-editor-canvas%
(class editor-canvas%
(inherit get-dc)
(init-field this-parent
this-label
this-editor
this-style
this-wheel-step
this-min-height
this-vert-margin
this-chat-window)
(define/public (get-chat-window) this-chat-window)
(define/override (on-char key-event)
(when (not (send editor-keymap handle-key-event this-editor key-event))
(let ([key (send key-event get-key-code)])
(when (char? (send key-event get-key-code))
(send this-editor insert key)))))
(super-new
[parent this-parent]
[label this-label]
[editor this-editor]
[style this-style]
[wheel-step this-wheel-step]
[min-height this-min-height]
[vert-margin this-vert-margin]
[stretchable-height #f])))
(define group-text-send (new text%
[line-spacing 1.0]
[auto-wrap #t]))
(define group-editor-canvas-receive (new custom-receive-canvas%
[parent topside-panel]
[label "Messages received"]
[editor group-text-receive]
400
[min-width (- this-width 100)]
[vert-margin 5]
[style (list 'control-border 'no-hscroll
'auto-vscroll)]
[wheel-step 3]
[this-chat-window this]))
(define message-history (new message-history%
[editor group-text-receive]))
; an editor canvas where text% messages will appear
(define group-editor-canvas-send (new custom-editor-canvas%
[this-parent group-frame]
[this-label "Your message goes here"]
[this-editor group-text-send]
[this-style (list 'control-border 'no-hscroll
'auto-vscroll)]
[this-wheel-step 3]
[this-min-height 100]
[this-vert-margin 5]
[this-chat-window this]))
(define cur-focused-wdg group-editor-canvas-send)
(define/public set-editor-black-style
(λ (editor)
(send editor change-style black-style)
))
(define/public cycle-focus
(λ (forward)
(cond
[(eq? cur-focused-wdg group-editor-canvas-receive)
(set! cur-focused-wdg group-editor-canvas-send)]
[else (set! cur-focused-wdg group-editor-canvas-receive)])
(send cur-focused-wdg focus)))
(define group-list-box (new list-box%
[parent topside-panel]
[label "0 Peers "]
[style (list 'single 'vertical-label)]
[stretchable-width 200]
[choices (list "")]
[callback (λ (list-box control-event)
(match (send control-event get-event-type)
['list-box-dclick
(define selection (send list-box get-selection))
(define nick
(send list-box get-string selection))
(send group-text-send insert nick)]
[_ (void)]))]))
(define hpanel (new horizontal-panel%
[parent group-frame]
[stretchable-height #f]
[alignment '(right center)]))
bitmap stuff for the un / mute button
(define unmuted-speaker-bitmap (make-object bitmap%
(sixth icons)
'png/alpha
(make-object color% "white")))
(define muted-speaker-bitmap (make-object bitmap%
(last icons)
'png/alpha
(make-object color% "white")))
(define unmuted-speaker-pict
(scale-to-fit (bitmap unmuted-speaker-bitmap) 18 18))
(define muted-speaker-pict
(scale-to-fit (bitmap muted-speaker-bitmap) 18 18))
(define mute-speakers
(new button%
[parent hpanel]
[label (pict->bitmap unmuted-speaker-pict)]
[callback (λ (button event)
(set! mute-speakers? (not mute-speakers?))
(if mute-speakers?
(send button set-label (pict->bitmap muted-speaker-pict))
(send button set-label (pict->bitmap unmuted-speaker-pict))))]))
(define emoji-button (new button%
[parent hpanel]
[label "Enter Emoji"]
[callback (λ (button event)
(send emoji-dialog show #t))]))
# # # # # # # # # # # # # # # # # # # # # BEGIN EMOJI STUFF # # # # # # # # # # # # # # # # # # # #
(define emoji-dialog (new dialog%
[label "Blight - Select Emoji"]
[style (list 'close-button)]))
; first row of emoji
(define row-one (new horizontal-panel%
[parent emoji-dialog]))
(for ([i (in-range 6)])
(make-object button%
(format "~a" (list-ref emojis i))
row-one
(λ (button event)
(send group-text-send insert (list-ref emojis i))
(send emoji-dialog show #f))))
second row of emoji
(define row-two (new horizontal-panel%
[parent emoji-dialog]))
(for ([i (in-range 6)])
(make-object button%
(format "~a" (list-ref emojis (+ i 6)))
row-two
(λ (button event)
(send group-text-send insert (list-ref emojis (+ i 6)))
(send emoji-dialog show #f))))
; third row of emoji
(define row-three (new horizontal-panel%
[parent emoji-dialog]))
(for ([i (in-range 6)])
(make-object button%
(format "~a" (list-ref emojis (+ i 12)))
row-three
(λ (button event)
(send group-text-send insert (list-ref emojis (+ i 12)))
(send emoji-dialog show #f))))
; fourth row of emoji
(define row-four (new horizontal-panel%
[parent emoji-dialog]))
(for ((i (in-range 6)))
(make-object button%
(format "~a" (list-ref emojis (+ i 18)))
row-four
(λ (button event)
(send group-text-send insert (list-ref emojis (+ i 18)))
(send emoji-dialog show #f))))
fifth row of emoji
(define row-five (new horizontal-panel%
[parent emoji-dialog]))
(for ((i (in-range 6)))
(make-object button%
(format "~a" (list-ref emojis (+ i 24)))
row-five
(λ (button event)
(send group-text-send insert (list-ref emojis (+ i 24)))
(send emoji-dialog show #f))))
; sixth row of emoji
(define row-six (new horizontal-panel%
[parent emoji-dialog]))
(for ((i (in-range 6)))
(make-object button%
(format "~a" (list-ref emojis (+ i 30)))
row-six
(λ (button event)
(send group-text-send insert (list-ref emojis (+ i 30)))
(send emoji-dialog show #f))))
seventh row of emoji
(define row-seven (new horizontal-panel%
[parent emoji-dialog]))
(for ((i (in-range 6)))
(make-object button%
(format "~a" (list-ref emojis (+ i 36)))
row-seven
(λ (button event)
(send group-text-send insert (list-ref emojis (+ i 36)))
(send emoji-dialog show #f))))
; eighth row of emoji
(define row-eight (new horizontal-panel%
[parent emoji-dialog]))
(for ((i (in-range 6)))
(make-object button%
(format "~a" (list-ref emojis (+ i 42)))
row-eight
(λ (button event)
(send group-text-send insert (list-ref emojis (+ i 42)))
(send emoji-dialog show #f))))
; ninth row of emoji
(define row-nine (new horizontal-panel%
[parent emoji-dialog]))
(for ((i (in-range 6)))
(make-object button%
(format "~a" (list-ref emojis (+ i 48)))
row-nine
(λ (button event)
(send group-text-send insert (list-ref emojis (+ i 48)))
(send emoji-dialog show #f))))
; tenth and final row of emoji
(define row-ten (new horizontal-panel%
[parent emoji-dialog]))
(for ((i (in-range 6)))
(make-object button%
(format "~a" (list-ref emojis (+ i 54)))
row-ten
(λ (button event)
(send group-text-send insert (list-ref emojis (+ i 54)))
(send emoji-dialog show #f))))
(new button%
[parent emoji-dialog]
[label "Close"]
[callback (λ (button event)
(send emoji-dialog show #f))])
# # # # # # # # # # # # # # # # # # # # END EMOJI STUFF # # # # # # # # # # # # # # # # # # # #
; send the message through tox
; message is a string
;
; we don't need to worry about putting the message into the receiving editor
; because when we send a group message/action it is caught by both
; callback-group-message and callback-group-action
(define/public do-send-message
(λ (editor message)
; get message type
(define msg-type
(send message-history get-msg-type message))
; procedure to send to the editor and to tox
(define do-send
(λ (byte-str)
(cond
; we're sending an action!
[(eq? msg-type 'action)
" /me " - > 4 bytes
(group-action-send this-tox group-number (subbytes byte-str 4))]
; we're not doing anything special
[else (group-message-send this-tox group-number byte-str)])))
; split the message if it exceeds TOX_MAX_MESSAGE_LENGTH
; otherwise, just send it.
(define split-message
(λ (msg-bytes)
(let ([len (bytes-length msg-bytes)])
(cond [(<= len TOX_MAX_MESSAGE_LENGTH)
(do-send msg-bytes)]
[(> len TOX_MAX_MESSAGE_LENGTH)
(do-send (subbytes msg-bytes 0 TOX_MAX_MESSAGE_LENGTH))
(split-message (subbytes msg-bytes TOX_MAX_MESSAGE_LENGTH))]))))
(split-message (string->bytes/utf-8 message))))
(send group-text-send change-style black-style)
; guess I need to override some shit to get the keys just right
(define editor-keymap (init-editor-keymap this))
(set-default-editor-bindings editor-keymap)
(send editor-keymap chain-to-keymap chatframe-keymap #t)
(define/public (get-tox)
this-tox)
(define/public (set-new-label x)
(send group-frame set-label x)
; check the title for &'s and "escape" them
(send group-frame-msg set-label
(string-replace (substring x 8) "&" "&&")))
(define/override (show x)
(send group-frame show x))
(define/override (is-shown?)
(send group-frame is-shown?))
(define/override (is-enabled?)
(send group-frame is-enabled?))
(define/public (get-receive-editor)
(send group-editor-canvas-receive get-editor))
(define/public (get-msg-history)
message-history)
(define/public (get-send-editor)
(send group-editor-canvas-send get-editor))
(define/public (get-group-number)
group-number)
(define/public (set-group-number num)
(set! group-number num))
(define/public (get-list-box)
group-list-box)
(define/public (speakers-muted?)
mute-speakers?)
(define/public (mic-muted?)
mute-mic?)
(define/public (set-speakers-muted! bool)
(set! mute-speakers? bool))
(define/public (set-mic-muted! bool)
(set! mute-mic? bool))
(super-new
[label this-label]
[height this-height]
[width this-width])))
| null | https://raw.githubusercontent.com/lehitoskin/blight/807b0437c92ee41c68ca5a767d973817ae416b65/gui/group.rkt | racket | group.rkt
contains group-window definitions
create a new top-level window
make a frame by instantiating the frame% class
set the frame icon
menu bar for group-frame
menu File for menu bar
loop until we get all our friends
add to the invite list
close the current window
an editor canvas where text% messages will appear
first row of emoji
third row of emoji
fourth row of emoji
sixth row of emoji
eighth row of emoji
ninth row of emoji
tenth and final row of emoji
send the message through tox
message is a string
we don't need to worry about putting the message into the receiving editor
because when we send a group message/action it is caught by both
callback-group-message and callback-group-action
get message type
procedure to send to the editor and to tox
we're sending an action!
we're not doing anything special
split the message if it exceeds TOX_MAX_MESSAGE_LENGTH
otherwise, just send it.
guess I need to override some shit to get the keys just right
check the title for &'s and "escape" them | #lang racket/gui
(require libtoxcore-racket/functions
"../config.rkt"
"chat.rkt"
"msg-editor.rkt"
"msg-history.rkt"
(only-in pict
bitmap
scale-to-fit
pict->bitmap))
(provide (all-defined-out))
(define group-window%
(class frame%
(inherit set-label)
(init-field this-label
this-width
this-height
this-tox
group-number)
(define mute-mic? #f)
(define mute-speakers? #f)
(set-default-chatframe-bindings chatframe-keymap)
(define/private repeat
(λ (proc times)
(cond [(zero? times) #t]
[else (proc) (repeat proc (- times 1))])))
(define group-frame (new frame%
[label this-label]
[width this-width]
[height this-height]))
(let ([icon-bmp (make-bitmap 32 32)])
(send icon-bmp load-file logo)
(send group-frame set-icon icon-bmp))
(define group-frame-menu-bar (new menu-bar%
[parent group-frame]))
(define menu-file (new menu% [parent group-frame-menu-bar]
[label "&File"]))
(define invite-frame (new frame%
[label "Blight - Invite Friend"]
[width 200]
[height 400]))
(define invite-list-box (new list-box%
[parent invite-frame]
[label "Friends"]
[style (list 'single 'vertical-label)]
[choices (list "")]
[callback (λ (l e)
(when (eq? (send e get-event-type)
'list-box-dclick)
(let ([selection (send l get-selection)])
(invite-friend this-tox selection group-number)
(send invite-frame show #f))))]))
(new button% [parent invite-frame]
[label "&Cancel"]
[callback (λ (button event)
(send invite-frame show #f))])
(define/public update-invite-list
(λ ()
(define num-friends (self-friend-list-size this-tox))
(unless (zero? num-friends)
(send invite-list-box clear)
(do ((num 0 (+ num 1)))
((= num num-friends))
(let-values ([(success err friend-name-bytes) (friend-name this-tox num)])
(send invite-list-box append (bytes->string/utf-8 friend-name-bytes)))))))
(update-invite-list)
(new menu-item% [parent menu-file]
[label "Invite"]
[help-string "Invite a friend"]
[callback (λ (button event)
(send invite-frame show #t))])
(new menu-item% [parent menu-file]
[label "&Close"]
[shortcut #\W]
[help-string "Close Window"]
[callback (λ (button event)
(send this show #f))])
(define group-frame-msg (new message%
[parent group-frame]
[label this-label]
[min-width 40]))
(send group-frame-msg auto-resize #t)
(define group-text-receive (new text%
[line-spacing 1.0]
[auto-wrap #t]))
(send group-text-receive change-style black-style)
(define messages-keymap (init-messages-keymap this))
(set-default-messages-bindings messages-keymap)
(send messages-keymap chain-to-keymap chatframe-keymap #t)
(define custom-receive-canvas%
(class editor-canvas%
(inherit refresh get-dc get-size)
(init-field parent
label
editor
style
wheel-step
min-height
vert-margin
this-chat-window)
(define/public (get-chat-window) this-chat-window)
(define/override (on-char key-event)
(send messages-keymap handle-key-event editor key-event))
(super-new
[parent parent]
[label label]
[editor editor]
[style style]
[wheel-step wheel-step]
[min-height min-height]
[vert-margin vert-margin])))
(define topside-panel (new horizontal-panel%
[parent group-frame]))
(define custom-editor-canvas%
(class editor-canvas%
(inherit get-dc)
(init-field this-parent
this-label
this-editor
this-style
this-wheel-step
this-min-height
this-vert-margin
this-chat-window)
(define/public (get-chat-window) this-chat-window)
(define/override (on-char key-event)
(when (not (send editor-keymap handle-key-event this-editor key-event))
(let ([key (send key-event get-key-code)])
(when (char? (send key-event get-key-code))
(send this-editor insert key)))))
(super-new
[parent this-parent]
[label this-label]
[editor this-editor]
[style this-style]
[wheel-step this-wheel-step]
[min-height this-min-height]
[vert-margin this-vert-margin]
[stretchable-height #f])))
(define group-text-send (new text%
[line-spacing 1.0]
[auto-wrap #t]))
(define group-editor-canvas-receive (new custom-receive-canvas%
[parent topside-panel]
[label "Messages received"]
[editor group-text-receive]
400
[min-width (- this-width 100)]
[vert-margin 5]
[style (list 'control-border 'no-hscroll
'auto-vscroll)]
[wheel-step 3]
[this-chat-window this]))
(define message-history (new message-history%
[editor group-text-receive]))
(define group-editor-canvas-send (new custom-editor-canvas%
[this-parent group-frame]
[this-label "Your message goes here"]
[this-editor group-text-send]
[this-style (list 'control-border 'no-hscroll
'auto-vscroll)]
[this-wheel-step 3]
[this-min-height 100]
[this-vert-margin 5]
[this-chat-window this]))
(define cur-focused-wdg group-editor-canvas-send)
(define/public set-editor-black-style
(λ (editor)
(send editor change-style black-style)
))
(define/public cycle-focus
(λ (forward)
(cond
[(eq? cur-focused-wdg group-editor-canvas-receive)
(set! cur-focused-wdg group-editor-canvas-send)]
[else (set! cur-focused-wdg group-editor-canvas-receive)])
(send cur-focused-wdg focus)))
(define group-list-box (new list-box%
[parent topside-panel]
[label "0 Peers "]
[style (list 'single 'vertical-label)]
[stretchable-width 200]
[choices (list "")]
[callback (λ (list-box control-event)
(match (send control-event get-event-type)
['list-box-dclick
(define selection (send list-box get-selection))
(define nick
(send list-box get-string selection))
(send group-text-send insert nick)]
[_ (void)]))]))
(define hpanel (new horizontal-panel%
[parent group-frame]
[stretchable-height #f]
[alignment '(right center)]))
bitmap stuff for the un / mute button
(define unmuted-speaker-bitmap (make-object bitmap%
(sixth icons)
'png/alpha
(make-object color% "white")))
(define muted-speaker-bitmap (make-object bitmap%
(last icons)
'png/alpha
(make-object color% "white")))
(define unmuted-speaker-pict
(scale-to-fit (bitmap unmuted-speaker-bitmap) 18 18))
(define muted-speaker-pict
(scale-to-fit (bitmap muted-speaker-bitmap) 18 18))
(define mute-speakers
(new button%
[parent hpanel]
[label (pict->bitmap unmuted-speaker-pict)]
[callback (λ (button event)
(set! mute-speakers? (not mute-speakers?))
(if mute-speakers?
(send button set-label (pict->bitmap muted-speaker-pict))
(send button set-label (pict->bitmap unmuted-speaker-pict))))]))
(define emoji-button (new button%
[parent hpanel]
[label "Enter Emoji"]
[callback (λ (button event)
(send emoji-dialog show #t))]))
# # # # # # # # # # # # # # # # # # # # # BEGIN EMOJI STUFF # # # # # # # # # # # # # # # # # # # #
(define emoji-dialog (new dialog%
[label "Blight - Select Emoji"]
[style (list 'close-button)]))
(define row-one (new horizontal-panel%
[parent emoji-dialog]))
(for ([i (in-range 6)])
(make-object button%
(format "~a" (list-ref emojis i))
row-one
(λ (button event)
(send group-text-send insert (list-ref emojis i))
(send emoji-dialog show #f))))
second row of emoji
(define row-two (new horizontal-panel%
[parent emoji-dialog]))
(for ([i (in-range 6)])
(make-object button%
(format "~a" (list-ref emojis (+ i 6)))
row-two
(λ (button event)
(send group-text-send insert (list-ref emojis (+ i 6)))
(send emoji-dialog show #f))))
(define row-three (new horizontal-panel%
[parent emoji-dialog]))
(for ([i (in-range 6)])
(make-object button%
(format "~a" (list-ref emojis (+ i 12)))
row-three
(λ (button event)
(send group-text-send insert (list-ref emojis (+ i 12)))
(send emoji-dialog show #f))))
(define row-four (new horizontal-panel%
[parent emoji-dialog]))
(for ((i (in-range 6)))
(make-object button%
(format "~a" (list-ref emojis (+ i 18)))
row-four
(λ (button event)
(send group-text-send insert (list-ref emojis (+ i 18)))
(send emoji-dialog show #f))))
fifth row of emoji
(define row-five (new horizontal-panel%
[parent emoji-dialog]))
(for ((i (in-range 6)))
(make-object button%
(format "~a" (list-ref emojis (+ i 24)))
row-five
(λ (button event)
(send group-text-send insert (list-ref emojis (+ i 24)))
(send emoji-dialog show #f))))
(define row-six (new horizontal-panel%
[parent emoji-dialog]))
(for ((i (in-range 6)))
(make-object button%
(format "~a" (list-ref emojis (+ i 30)))
row-six
(λ (button event)
(send group-text-send insert (list-ref emojis (+ i 30)))
(send emoji-dialog show #f))))
seventh row of emoji
(define row-seven (new horizontal-panel%
[parent emoji-dialog]))
(for ((i (in-range 6)))
(make-object button%
(format "~a" (list-ref emojis (+ i 36)))
row-seven
(λ (button event)
(send group-text-send insert (list-ref emojis (+ i 36)))
(send emoji-dialog show #f))))
(define row-eight (new horizontal-panel%
[parent emoji-dialog]))
(for ((i (in-range 6)))
(make-object button%
(format "~a" (list-ref emojis (+ i 42)))
row-eight
(λ (button event)
(send group-text-send insert (list-ref emojis (+ i 42)))
(send emoji-dialog show #f))))
(define row-nine (new horizontal-panel%
[parent emoji-dialog]))
(for ((i (in-range 6)))
(make-object button%
(format "~a" (list-ref emojis (+ i 48)))
row-nine
(λ (button event)
(send group-text-send insert (list-ref emojis (+ i 48)))
(send emoji-dialog show #f))))
(define row-ten (new horizontal-panel%
[parent emoji-dialog]))
(for ((i (in-range 6)))
(make-object button%
(format "~a" (list-ref emojis (+ i 54)))
row-ten
(λ (button event)
(send group-text-send insert (list-ref emojis (+ i 54)))
(send emoji-dialog show #f))))
(new button%
[parent emoji-dialog]
[label "Close"]
[callback (λ (button event)
(send emoji-dialog show #f))])
# # # # # # # # # # # # # # # # # # # # END EMOJI STUFF # # # # # # # # # # # # # # # # # # # #
(define/public do-send-message
(λ (editor message)
(define msg-type
(send message-history get-msg-type message))
(define do-send
(λ (byte-str)
(cond
[(eq? msg-type 'action)
" /me " - > 4 bytes
(group-action-send this-tox group-number (subbytes byte-str 4))]
[else (group-message-send this-tox group-number byte-str)])))
(define split-message
(λ (msg-bytes)
(let ([len (bytes-length msg-bytes)])
(cond [(<= len TOX_MAX_MESSAGE_LENGTH)
(do-send msg-bytes)]
[(> len TOX_MAX_MESSAGE_LENGTH)
(do-send (subbytes msg-bytes 0 TOX_MAX_MESSAGE_LENGTH))
(split-message (subbytes msg-bytes TOX_MAX_MESSAGE_LENGTH))]))))
(split-message (string->bytes/utf-8 message))))
(send group-text-send change-style black-style)
(define editor-keymap (init-editor-keymap this))
(set-default-editor-bindings editor-keymap)
(send editor-keymap chain-to-keymap chatframe-keymap #t)
(define/public (get-tox)
this-tox)
(define/public (set-new-label x)
(send group-frame set-label x)
(send group-frame-msg set-label
(string-replace (substring x 8) "&" "&&")))
(define/override (show x)
(send group-frame show x))
(define/override (is-shown?)
(send group-frame is-shown?))
(define/override (is-enabled?)
(send group-frame is-enabled?))
(define/public (get-receive-editor)
(send group-editor-canvas-receive get-editor))
(define/public (get-msg-history)
message-history)
(define/public (get-send-editor)
(send group-editor-canvas-send get-editor))
(define/public (get-group-number)
group-number)
(define/public (set-group-number num)
(set! group-number num))
(define/public (get-list-box)
group-list-box)
(define/public (speakers-muted?)
mute-speakers?)
(define/public (mic-muted?)
mute-mic?)
(define/public (set-speakers-muted! bool)
(set! mute-speakers? bool))
(define/public (set-mic-muted! bool)
(set! mute-mic? bool))
(super-new
[label this-label]
[height this-height]
[width this-width])))
|
8f7b4a162029fa9974d5869b90b5175655c1006a8b611b9afd87f226bb564872 | pkel/cpr | nakamoto_ssz.ml | open Cpr_lib
module type Parameters = sig
* [ false ] : Maintain natural scale of observation .
[ true ] : Map observation to [ 0,1]{^n } .
[true]: Map observation floatarray to [0,1]{^n}. *)
val unit_observation : bool
end
module Make (Parameters : Parameters) = struct
open Parameters
module Protocol = Nakamoto
open Protocol
let key = Format.asprintf "ssz-%s" (if unit_observation then "unitobs" else "rawobs")
let info =
Format.asprintf
"SSZ'16 attack space with %s observations"
(if unit_observation then "unit" else "raw")
;;
module Observation = struct
type t =
{ public_blocks : int (** number of public blocks after common ancestor *)
; private_blocks : int (** number of private blocks after common ancestor *)
; diff_blocks : int (** private_blocks - public_blocks *)
; event : [ `ProofOfWork | `Network ] (* What is currently going on? *)
}
[@@deriving fields]
module Normalizers = struct
open Ssz_tools.NormalizeObs
let public_blocks = UnboundedInt { non_negative = true; scale = 1 }
let private_blocks = UnboundedInt { non_negative = true; scale = 1 }
let diff_blocks = UnboundedInt { non_negative = false; scale = 1 }
let event = Discrete [ `ProofOfWork; `Network ]
end
let length = List.length Fields.names
let low, high =
let low, high = Float.Array.make length 0., Float.Array.make length 0. in
let set spec i _field =
let l, h = Ssz_tools.NormalizeObs.range ~unit:unit_observation spec in
Float.Array.set low i l;
Float.Array.set high i h;
i + 1
in
let _ =
let open Normalizers in
Fields.fold
~init:0
~public_blocks:(set public_blocks)
~private_blocks:(set private_blocks)
~diff_blocks:(set diff_blocks)
~event:(set event)
in
low, high
;;
let to_floatarray t =
let a = Float.Array.make length Float.nan in
let set spec i field =
Float.Array.set
a
i
(Fieldslib.Field.get field t
|> Ssz_tools.NormalizeObs.to_float ~unit:unit_observation spec);
i + 1
in
let _ =
let open Normalizers in
Fields.fold
~init:0
~public_blocks:(set public_blocks)
~private_blocks:(set private_blocks)
~diff_blocks:(set diff_blocks)
~event:(set event)
in
a
;;
let of_floatarray =
let get spec _ i =
( (fun a ->
Float.Array.get a i
|> Ssz_tools.NormalizeObs.of_float ~unit:unit_observation spec)
, i + 1 )
in
let open Normalizers in
fst
(Fields.make_creator
0
~public_blocks:(get public_blocks)
~private_blocks:(get private_blocks)
~diff_blocks:(get diff_blocks)
~event:(get event))
;;
let to_string t =
let conv to_s field =
Printf.sprintf
"%s: %s"
(Fieldslib.Field.name field)
(to_s (Fieldslib.Field.get field t))
in
let int = conv string_of_int in
let event = conv Ssz_tools.event_to_string in
Fields.to_list ~public_blocks:int ~private_blocks:int ~diff_blocks:int ~event
|> String.concat "\n"
;;
end
module Action = struct
type t =
| Adopt
* Adopt the defender 's preferred chain as attacker 's preferred chain . Withheld
attacker blocks are discarded .
Equivalent to SSZ'16 model .
attacker blocks are discarded.
Equivalent to SSZ'16 model. *)
| Override
* Publish just enough information to make the defender adopt the chain just
released . The attacker continues mining the private chain .
If override is impossible , this still results in a release of withheld
information .
Equivalent to SSZ'16 model .
released. The attacker continues mining the private chain.
If override is impossible, this still results in a release of withheld
information.
Equivalent to SSZ'16 model. *)
| Match
* Publish just enough information such that the defender observes a tie between
two chains . The attacker continues mining the private chain .
If match is impossible , this still results in a release of withheld
information .
Equivalent to SSZ'16 model .
two chains. The attacker continues mining the private chain.
If match is impossible, this still results in a release of withheld
information.
Equivalent to SSZ'16 model. *)
* Continue withholding . Always possible . Equivalent to SSZ'16 model .
[@@deriving variants]
let to_string = Variants.to_name
let to_int = Variants.to_rank
let table =
let add acc var = var.Variantslib.Variant.constructor :: acc in
Variants.fold ~init:[] ~adopt:add ~override:add ~match_:add ~wait:add
|> List.rev
|> Array.of_list
;;
let of_int i = table.(i)
let n = Array.length table
end
module Agent (V : View with type data = data) = struct
include V
module N = Honest (V)
type state =
| BetweenActions of
{ public : block (* defender's preferred block *)
; private_ : block (* attacker's preferred block *)
; pending_private_to_public_messages :
block list (* messages sent with last action *)
}
type state_before_action =
| BeforeAction of
{ public : block
; private_ : block
}
type observable_state =
| Observable of
{ public : block
; private_ : block
; common : block
; event : [ `ProofOfWork | `Network ]
}
let init ~roots =
let root = N.init ~roots in
BetweenActions
{ private_ = root; public = root; pending_private_to_public_messages = [] }
;;
let preferred (BetweenActions s) = s.private_
let puzzle_payload (BetweenActions s) = N.puzzle_payload s.private_
let deliver_private_to_public_messages (BetweenActions state) =
let public =
List.fold_left
(fun old consider -> N.update_head ~old consider)
state.public
state.pending_private_to_public_messages
in
BeforeAction { public; private_ = state.private_ }
;;
module Dagtools = Dagtools.Make (Block)
let prepare (BeforeAction state) event =
let public, private_, event =
match event with
| Append _ -> failwith "not implemented"
| Network x ->
(* simulate defender *)
N.update_head ~old:state.public x, state.private_, `Network
| ProofOfWork x ->
(* work on private chain *)
state.public, x, `ProofOfWork
in
let common = Dagtools.common_ancestor public private_ |> Option.get in
Observable { public; private_; common; event }
;;
let prepare state = deliver_private_to_public_messages state |> prepare
let observe (Observable state) =
let open Observation in
let ca_height = data state.common |> height
and private_height = data state.private_ |> height
and public_height = data state.public |> height in
{ private_blocks = private_height - ca_height
; public_blocks = public_height - ca_height
; diff_blocks = private_height - public_height
; event = state.event
}
;;
let apply (Observable state) action =
let parent vtx =
match parents vtx with
| [ x ] -> Some x
| _ -> None
in
let match_ offset =
let h =
(* height of to be released block *)
height (data state.public) + offset
in
(* look for to be released block backwards from private head *)
let rec f b = if height (data b) <= h then b else parent b |> Option.get |> f in
[ f state.private_ ]
(* NOTE: if private height is smaller target height, then private head is
released. *)
in
let share, private_ =
match (action : Action.t) with
| Adopt -> [], state.public
| Match -> match_ 0, state.private_
| Override -> match_ 1, state.private_
| Wait -> [], state.private_
in
BetweenActions
{ private_; public = state.public; pending_private_to_public_messages = share }
|> return ~share
;;
end
let attacker (type a) policy ((module V) : (a, data) view) : (a, data) node =
Node
(module struct
include Agent (V)
let handler s e =
let s = prepare s e in
observe s |> policy |> apply s
;;
end)
;;
module Policies = struct
let honest o =
let open Observation in
let open Action in
if o.private_blocks > o.public_blocks
then Override
else if o.private_blocks < o.public_blocks
then Adopt
else Wait
;;
(* Patrik's ad-hoc strategy *)
let simple o =
let open Observation in
let open Action in
if o.public_blocks > 0
then if o.private_blocks < o.public_blocks then Adopt else Override
else Wait
;;
Eyal and Sirer . Majority is not enough : Bitcoin mining is vulnerable . 2014 .
let es_2014 o =
(* I interpret this from the textual description of the strategy. There is an
algorithmic version in the paper, but it depends on the observation whether the
last mined block is honest or not. *)
let open Observation in
let open Action in
if o.private_blocks < o.public_blocks
1 .
else if o.public_blocks = 0 && o.private_blocks = 1
2 .
else if o.public_blocks = 1 && o.private_blocks = 1
3 .
else if o.public_blocks = 1 && o.private_blocks = 2
4 .
else if o.public_blocks = 2 && o.private_blocks = 1
5 . Redundant : included in 1 .
Adopt
else (
The attacker established a lead of more than two before :
let _ = () in
if o.public_blocks > 0
then
if o.private_blocks - o.public_blocks = 1
6 .
7 .
else Wait)
;;
Sapirshtein , , . Optimal Selfish Mining Strategies in Bitcoin .
2016 .
2016. *)
let ssz_2016_sm1 o =
The authors rephrase the policy of ES'14 and call it SM1 . Their version is much
shorter .
The authors define an MDP to find better strategies for various parameters alpha
and gamma . We can not reproduce this here in this module . Our RL framework should
be able to find these policies , though .
shorter.
The authors define an MDP to find better strategies for various parameters alpha
and gamma. We cannot reproduce this here in this module. Our RL framework should
be able to find these policies, though. *)
let open Observation in
let open Action in
match o.public_blocks, o.private_blocks with
| h, a when h > a -> Adopt
| 1, 1 -> Match
| h, a when h = a - 1 && h >= 1 -> Override
| _ (* Otherwise *) -> Wait
;;
end
let policies =
let open Collection in
let open Policies in
empty
|> add ~info:"emulate honest behaviour" "honest" honest
|> add ~info:"simple withholding policy" "simple" simple
|> add ~info:"Eyal and Sirer 2014" "eyal-sirer-2014" es_2014
|> add ~info:"Sapirshtein et al. 2016, SM1" "sapirshtein-2016-sm1" ssz_2016_sm1
;;
end
| null | https://raw.githubusercontent.com/pkel/cpr/77130b3f4ce1e2294c4c49cb3dbb001980d0bfad/simulator/protocols/nakamoto_ssz.ml | ocaml | * number of public blocks after common ancestor
* number of private blocks after common ancestor
* private_blocks - public_blocks
What is currently going on?
defender's preferred block
attacker's preferred block
messages sent with last action
simulate defender
work on private chain
height of to be released block
look for to be released block backwards from private head
NOTE: if private height is smaller target height, then private head is
released.
Patrik's ad-hoc strategy
I interpret this from the textual description of the strategy. There is an
algorithmic version in the paper, but it depends on the observation whether the
last mined block is honest or not.
Otherwise | open Cpr_lib
module type Parameters = sig
* [ false ] : Maintain natural scale of observation .
[ true ] : Map observation to [ 0,1]{^n } .
[true]: Map observation floatarray to [0,1]{^n}. *)
val unit_observation : bool
end
module Make (Parameters : Parameters) = struct
open Parameters
module Protocol = Nakamoto
open Protocol
let key = Format.asprintf "ssz-%s" (if unit_observation then "unitobs" else "rawobs")
let info =
Format.asprintf
"SSZ'16 attack space with %s observations"
(if unit_observation then "unit" else "raw")
;;
module Observation = struct
type t =
}
[@@deriving fields]
module Normalizers = struct
open Ssz_tools.NormalizeObs
let public_blocks = UnboundedInt { non_negative = true; scale = 1 }
let private_blocks = UnboundedInt { non_negative = true; scale = 1 }
let diff_blocks = UnboundedInt { non_negative = false; scale = 1 }
let event = Discrete [ `ProofOfWork; `Network ]
end
let length = List.length Fields.names
let low, high =
let low, high = Float.Array.make length 0., Float.Array.make length 0. in
let set spec i _field =
let l, h = Ssz_tools.NormalizeObs.range ~unit:unit_observation spec in
Float.Array.set low i l;
Float.Array.set high i h;
i + 1
in
let _ =
let open Normalizers in
Fields.fold
~init:0
~public_blocks:(set public_blocks)
~private_blocks:(set private_blocks)
~diff_blocks:(set diff_blocks)
~event:(set event)
in
low, high
;;
let to_floatarray t =
let a = Float.Array.make length Float.nan in
let set spec i field =
Float.Array.set
a
i
(Fieldslib.Field.get field t
|> Ssz_tools.NormalizeObs.to_float ~unit:unit_observation spec);
i + 1
in
let _ =
let open Normalizers in
Fields.fold
~init:0
~public_blocks:(set public_blocks)
~private_blocks:(set private_blocks)
~diff_blocks:(set diff_blocks)
~event:(set event)
in
a
;;
let of_floatarray =
let get spec _ i =
( (fun a ->
Float.Array.get a i
|> Ssz_tools.NormalizeObs.of_float ~unit:unit_observation spec)
, i + 1 )
in
let open Normalizers in
fst
(Fields.make_creator
0
~public_blocks:(get public_blocks)
~private_blocks:(get private_blocks)
~diff_blocks:(get diff_blocks)
~event:(get event))
;;
let to_string t =
let conv to_s field =
Printf.sprintf
"%s: %s"
(Fieldslib.Field.name field)
(to_s (Fieldslib.Field.get field t))
in
let int = conv string_of_int in
let event = conv Ssz_tools.event_to_string in
Fields.to_list ~public_blocks:int ~private_blocks:int ~diff_blocks:int ~event
|> String.concat "\n"
;;
end
module Action = struct
type t =
| Adopt
* Adopt the defender 's preferred chain as attacker 's preferred chain . Withheld
attacker blocks are discarded .
Equivalent to SSZ'16 model .
attacker blocks are discarded.
Equivalent to SSZ'16 model. *)
| Override
* Publish just enough information to make the defender adopt the chain just
released . The attacker continues mining the private chain .
If override is impossible , this still results in a release of withheld
information .
Equivalent to SSZ'16 model .
released. The attacker continues mining the private chain.
If override is impossible, this still results in a release of withheld
information.
Equivalent to SSZ'16 model. *)
| Match
* Publish just enough information such that the defender observes a tie between
two chains . The attacker continues mining the private chain .
If match is impossible , this still results in a release of withheld
information .
Equivalent to SSZ'16 model .
two chains. The attacker continues mining the private chain.
If match is impossible, this still results in a release of withheld
information.
Equivalent to SSZ'16 model. *)
* Continue withholding . Always possible . Equivalent to SSZ'16 model .
[@@deriving variants]
let to_string = Variants.to_name
let to_int = Variants.to_rank
let table =
let add acc var = var.Variantslib.Variant.constructor :: acc in
Variants.fold ~init:[] ~adopt:add ~override:add ~match_:add ~wait:add
|> List.rev
|> Array.of_list
;;
let of_int i = table.(i)
let n = Array.length table
end
module Agent (V : View with type data = data) = struct
include V
module N = Honest (V)
type state =
| BetweenActions of
; pending_private_to_public_messages :
}
type state_before_action =
| BeforeAction of
{ public : block
; private_ : block
}
type observable_state =
| Observable of
{ public : block
; private_ : block
; common : block
; event : [ `ProofOfWork | `Network ]
}
let init ~roots =
let root = N.init ~roots in
BetweenActions
{ private_ = root; public = root; pending_private_to_public_messages = [] }
;;
let preferred (BetweenActions s) = s.private_
let puzzle_payload (BetweenActions s) = N.puzzle_payload s.private_
let deliver_private_to_public_messages (BetweenActions state) =
let public =
List.fold_left
(fun old consider -> N.update_head ~old consider)
state.public
state.pending_private_to_public_messages
in
BeforeAction { public; private_ = state.private_ }
;;
module Dagtools = Dagtools.Make (Block)
let prepare (BeforeAction state) event =
let public, private_, event =
match event with
| Append _ -> failwith "not implemented"
| Network x ->
N.update_head ~old:state.public x, state.private_, `Network
| ProofOfWork x ->
state.public, x, `ProofOfWork
in
let common = Dagtools.common_ancestor public private_ |> Option.get in
Observable { public; private_; common; event }
;;
let prepare state = deliver_private_to_public_messages state |> prepare
let observe (Observable state) =
let open Observation in
let ca_height = data state.common |> height
and private_height = data state.private_ |> height
and public_height = data state.public |> height in
{ private_blocks = private_height - ca_height
; public_blocks = public_height - ca_height
; diff_blocks = private_height - public_height
; event = state.event
}
;;
let apply (Observable state) action =
let parent vtx =
match parents vtx with
| [ x ] -> Some x
| _ -> None
in
let match_ offset =
let h =
height (data state.public) + offset
in
let rec f b = if height (data b) <= h then b else parent b |> Option.get |> f in
[ f state.private_ ]
in
let share, private_ =
match (action : Action.t) with
| Adopt -> [], state.public
| Match -> match_ 0, state.private_
| Override -> match_ 1, state.private_
| Wait -> [], state.private_
in
BetweenActions
{ private_; public = state.public; pending_private_to_public_messages = share }
|> return ~share
;;
end
let attacker (type a) policy ((module V) : (a, data) view) : (a, data) node =
Node
(module struct
include Agent (V)
let handler s e =
let s = prepare s e in
observe s |> policy |> apply s
;;
end)
;;
module Policies = struct
let honest o =
let open Observation in
let open Action in
if o.private_blocks > o.public_blocks
then Override
else if o.private_blocks < o.public_blocks
then Adopt
else Wait
;;
let simple o =
let open Observation in
let open Action in
if o.public_blocks > 0
then if o.private_blocks < o.public_blocks then Adopt else Override
else Wait
;;
Eyal and Sirer . Majority is not enough : Bitcoin mining is vulnerable . 2014 .
let es_2014 o =
let open Observation in
let open Action in
if o.private_blocks < o.public_blocks
1 .
else if o.public_blocks = 0 && o.private_blocks = 1
2 .
else if o.public_blocks = 1 && o.private_blocks = 1
3 .
else if o.public_blocks = 1 && o.private_blocks = 2
4 .
else if o.public_blocks = 2 && o.private_blocks = 1
5 . Redundant : included in 1 .
Adopt
else (
The attacker established a lead of more than two before :
let _ = () in
if o.public_blocks > 0
then
if o.private_blocks - o.public_blocks = 1
6 .
7 .
else Wait)
;;
Sapirshtein , , . Optimal Selfish Mining Strategies in Bitcoin .
2016 .
2016. *)
let ssz_2016_sm1 o =
The authors rephrase the policy of ES'14 and call it SM1 . Their version is much
shorter .
The authors define an MDP to find better strategies for various parameters alpha
and gamma . We can not reproduce this here in this module . Our RL framework should
be able to find these policies , though .
shorter.
The authors define an MDP to find better strategies for various parameters alpha
and gamma. We cannot reproduce this here in this module. Our RL framework should
be able to find these policies, though. *)
let open Observation in
let open Action in
match o.public_blocks, o.private_blocks with
| h, a when h > a -> Adopt
| 1, 1 -> Match
| h, a when h = a - 1 && h >= 1 -> Override
;;
end
let policies =
let open Collection in
let open Policies in
empty
|> add ~info:"emulate honest behaviour" "honest" honest
|> add ~info:"simple withholding policy" "simple" simple
|> add ~info:"Eyal and Sirer 2014" "eyal-sirer-2014" es_2014
|> add ~info:"Sapirshtein et al. 2016, SM1" "sapirshtein-2016-sm1" ssz_2016_sm1
;;
end
|
279816970ba0acdd069616b1f89d23bb67fb93b6bbf0c71662a09fe651755ebc | dmitryvk/sbcl-win32-threads | mop-10.impure-cload.lisp | miscellaneous side - effectful tests of the MOP
This software is part of the SBCL system . See the README file for
;;;; more information.
;;;;
While most of SBCL is derived from the CMU CL system , the test
;;;; files (like this one) were written from scratch after the fork
from CMU CL .
;;;;
;;;; This software is in the public domain and is provided with
;;;; absolutely no warranty. See the COPYING and CREDITS files for
;;;; more information.
;;; this file contains tests of REINITIALIZE-INSTANCE on generic
;;; functions.
(defpackage "MOP-10"
(:use "CL" "SB-MOP" "TEST-UTIL"))
(in-package "MOP-10")
(defclass my-generic-function (standard-generic-function)
()
(:metaclass funcallable-standard-class))
(defgeneric foo (x)
(:method-combination list)
(:method list ((x float)) (* x x))
(:method list ((x integer)) (1+ x))
(:method list ((x number)) (expt x 2))
(:generic-function-class my-generic-function))
(assert (equal (foo 3) '(4 9)))
(defmethod compute-discriminating-function ((gf my-generic-function))
(let ((orig (call-next-method)))
(lambda (&rest args)
(let ((orig-result (apply orig args)))
(cons gf (reverse orig-result))))))
(assert (equal (foo 3) '(4 9)))
(reinitialize-instance #'foo)
(assert (equal (foo 3) (cons #'foo '(9 4))))
| null | https://raw.githubusercontent.com/dmitryvk/sbcl-win32-threads/5abfd64b00a0937ba2df2919f177697d1d91bde4/tests/mop-10.impure-cload.lisp | lisp | more information.
files (like this one) were written from scratch after the fork
This software is in the public domain and is provided with
absolutely no warranty. See the COPYING and CREDITS files for
more information.
this file contains tests of REINITIALIZE-INSTANCE on generic
functions. | miscellaneous side - effectful tests of the MOP
This software is part of the SBCL system . See the README file for
While most of SBCL is derived from the CMU CL system , the test
from CMU CL .
(defpackage "MOP-10"
(:use "CL" "SB-MOP" "TEST-UTIL"))
(in-package "MOP-10")
(defclass my-generic-function (standard-generic-function)
()
(:metaclass funcallable-standard-class))
(defgeneric foo (x)
(:method-combination list)
(:method list ((x float)) (* x x))
(:method list ((x integer)) (1+ x))
(:method list ((x number)) (expt x 2))
(:generic-function-class my-generic-function))
(assert (equal (foo 3) '(4 9)))
(defmethod compute-discriminating-function ((gf my-generic-function))
(let ((orig (call-next-method)))
(lambda (&rest args)
(let ((orig-result (apply orig args)))
(cons gf (reverse orig-result))))))
(assert (equal (foo 3) '(4 9)))
(reinitialize-instance #'foo)
(assert (equal (foo 3) (cons #'foo '(9 4))))
|
62b0d7d69ed7d9887538cb5d0f20e8c835ce4ab2591bcacb421343a49d3416de | fulcrologic/fulcro | hooks.cljc | (ns com.fulcrologic.fulcro.react.hooks
"React hooks wrappers and helpers. The wrappers are simple API simplifications that help when using hooks from
Clojurescript, but this namespace also includes utilities for using Fulcro's data/network management from raw React
via hooks.
See `use-root`, `use-component`, and `use-uism`."
#?(:cljs
(:require-macros [com.fulcrologic.fulcro.react.hooks :refer [use-effect use-lifecycle]]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; WARNING TO MAINTAINERS: DO NOT REFERENCE DOM IN HERE. This has to work with native.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(:require
[com.fulcrologic.fulcro.algorithms.tempid :as tempid]
#?(:cljs ["react" :as react])
[com.fulcrologic.fulcro.components :as comp]
[com.fulcrologic.fulcro.raw.components :as rc]
[com.fulcrologic.fulcro.raw.application :as rapp]
[com.fulcrologic.fulcro.algorithms.denormalize :as fdn]
[com.fulcrologic.fulcro.algorithms.merge :as merge]
[com.fulcrologic.fulcro.ui-state-machines :as uism]
[com.fulcrologic.fulcro.rendering.multiple-roots-renderer :as mrr]
[com.fulcrologic.fulcro.algorithms.normalized-state :as fns]
[edn-query-language.core :as eql]
[taoensso.encore :as enc]
[taoensso.timbre :as log]
[com.fulcrologic.fulcro.application :as app])
#?(:clj (:import (cljs.tagged_literals JSValue))))
(defn useState
"A simple CLJC wrapper around React/useState. Returns a JS vector for speed. You probably want use-state, which is more
convenient.
React docs: -reference.html#usestate"
[initial-value]
#?(:cljs (react/useState initial-value)))
(defn use-state
"A simple wrapper around React/useState. Returns a cljs vector for easy destructuring.
`initial-value` can be a function.
React docs: -reference.html#usestate"
[initial-value]
#?(:cljs (into-array (react/useState initial-value))))
(defn useEffect
"A CLJC wrapper around js/React.useEffect that does NO conversion of
dependencies. You probably want the macro use-effect instead.
React docs: -reference.html#useeffect"
([f]
#?(:cljs (react/useEffect f)))
([f js-deps]
#?(:cljs (react/useEffect f js-deps))))
#?(:clj
(defmacro use-effect
"A simple macro wrapper around React/useEffect that does compile-time conversion of `dependencies` to a js-array
for convenience without affecting performance.
React docs: -reference.html#useeffect"
([f]
`(useEffect ~f))
([f dependencies]
(if (enc/compiling-cljs?)
(let [deps (cond
(nil? dependencies) nil
(instance? JSValue dependencies) dependencies
:else (JSValue. dependencies))]
`(useEffect ~f ~deps))
`(useEffect ~f ~dependencies)))))
(defn use-context
"A simple wrapper around the RAW React/useContext. You should probably prefer the context support from c.f.f.r.context."
[ctx]
#?(:cljs (react/useContext ctx)))
(defn use-reducer
"A simple wrapper around React/useReducer. Returns a cljs vector for easy destructuring
React docs: -reference.html#usecontext"
([reducer initial-arg]
#?(:cljs (into-array (react/useReducer reducer initial-arg))))
([reducer initial-arg init]
#?(:cljs (into-array (react/useReducer reducer initial-arg init)))))
(defn use-callback
"A simple wrapper around React/useCallback. Converts args to js array before send.
React docs: -reference.html#usecallback"
([cb]
#?(:cljs (react/useCallback cb)))
([cb args]
#?(:cljs (react/useCallback cb (to-array args)))))
(defn use-memo
"A simple wrapper around React/useMemo. Converts args to js array before send.
NOTE: React does NOT guarantee it won't re-create the value during the lifetime of the
component, so it is sorta crappy in terms of actual memoization. Purely for optimizations, not
for guarantees.
React docs: -reference.html#usememo"
([value-factory-fn]
#?(:cljs (react/useMemo value-factory-fn)))
([value-factory-fn dependencies]
#?(:cljs (react/useMemo value-factory-fn (to-array dependencies)))))
(defn use-ref
"A simple wrapper around React/useRef.
React docs: -reference.html#useref"
([] #?(:cljs (react/useRef nil)))
([value] #?(:cljs (react/useRef value))))
(defn use-imperative-handle
"A simple wrapper around React/useImperativeHandle.
React docs: -reference.html#useimperativehandle"
[ref f]
#?(:cljs (react/useImperativeHandle ref f)))
(defn use-layout-effect
"A simple wrapper around React/useLayoutEffect.
React docs: -reference.html#uselayouteffect"
([f]
#?(:cljs (react/useLayoutEffect f)))
([f args]
#?(:cljs (react/useLayoutEffect f (to-array args)))))
(defn use-debug-value
"A simple wrapper around React/useDebugValue.
React docs: -reference.html#uselayouteffect"
([value]
#?(:cljs (react/useDebugValue value)))
([value formatter]
#?(:cljs (react/useDebugValue value formatter))))
(defn use-deferred-value
"A simple wrapper around React/useDeferredValue.
React docs: -reference.html#usedeferredvalue"
[value]
#?(:cljs (react/useDeferredValue value)))
(defn use-transition
"A simple wrapper around React/useTransition.
React docs: -reference.html#usetransition"
[value]
#?(:cljs (into-array (react/useTransition value))))
(defn use-id
"A simple wrapper around React/useId. See also use-generated-id, which is a Fulcro-specific function for generating
random uuids.
React docs: -reference.html#useid"
[]
#?(:cljs (react/useId)))
(defn use-sync-external-store
"A simple wrapper around React/useSyncExternalStore.
React docs: -reference.html#usesyncexternalstore"
([subscribe get-snapshot get-server-ss]
#?(:cljs (react/useSyncExternalStore subscribe get-snapshot get-server-ss)))
([subscribe get-snapshot]
#?(:cljs (react/useSyncExternalStore subscribe get-snapshot))))
(defn use-insertion-effect
"A simple wrapper around React/useInsertionEffect.
React docs: -reference.html#useinsertioneffect"
[didUpdate]
#?(:cljs (react/useInsertionEffect didUpdate)))
#?(:clj
(defmacro use-lifecycle
"A macro shorthand that evaluates to low-level js at compile time for
`(use-effect (fn [] (when setup (setup)) (when teardown teardown)) [])`"
([setup] `(use-lifecycle ~setup nil))
([setup teardown]
(cond
(and setup teardown) `(use-effect (fn [] (~setup) ~teardown) [])
setup `(use-effect (fn [] (~setup) ~(when (enc/compiling-cljs?) 'js/undefined)) [])
teardown `(use-effect (fn [] ~teardown) [])))))
(let [id (fn [] (tempid/uuid))]
(defn use-generated-id
"Returns a constant ident with a generated ID component."
[]
(aget (useState id) 0)))
(defn use-gc
"Effect handler. Creates an effect that will garbage-collect the given ident from fulcro app state on cleanup, and
will follow any `edges` (a set of keywords) and remove any things pointed through those keywords as well. See
normalized-state's `remove-entity`.
```
(defsc NewRoot [this props]
{:use-hooks? true}
(let [generated-id (hooks/use-generated-id)
f (use-fulcro-mount this {:child-class SomeChild
:initial-state-params {:id generated-id})]
;; will garbage-collect the floating root child on unmount
(use-gc this [:child/id generated-id] #{})
(f props)))
```
"
[this-or-app ident edges]
(use-lifecycle
nil
(fn []
(let [state (-> this-or-app comp/any->app :com.fulcrologic.fulcro.application/state-atom)]
(swap! state fns/remove-entity ident edges)))))
(let [initial-mount-state (fn []
(let [componentName (keyword "com.fulcrologic.fulcro.floating-root" (gensym "generated-root"))]
#?(:clj [componentName nil] :cljs #js [componentName nil])))]
(defn use-fulcro-mount
"
NOTE: In many cases you are better off using the other hooks support in this ns, such as `use-component`, since
they do not have a render integration requirement.
Generate a new sub-root that is controlled and rendered by Fulcro's multi-root-renderer.
```
;; important, you must use hooks (`defhc` or `:use-hooks? true`)
(defsc NewRoot [this props]
{:use-hooks? true}
(let [f (use-fulcro-mount this {:child-class SomeChild})]
parent props will show up in SomeChild as computed props .
(f props)))
```
WARNING: Requires you use multi-root-renderer."
[parent-this {:keys [child-class
initial-state-params]}]
factories are functions , and if you pass a function to setState it will run it , which is NOT what we want ...
(let [st (useState initial-mount-state)
pass-through-props (atom {})
key-and-root (aget st 0)
setRoot! (aget st 1)
_ (use-lifecycle
(fn []
(let [join-key (aget key-and-root 0)
child-factory (comp/computed-factory child-class)
initial-state (comp/get-initial-state child-class (or initial-state-params {}))
cls (comp/configure-hooks-component!
(fn [this fulcro-props]
(use-lifecycle
(fn [] (mrr/register-root! this))
(fn [] (mrr/deregister-root! this)))
(comp/with-parent-context parent-this
(child-factory (get fulcro-props join-key initial-state) @pass-through-props)))
{:query (fn [_] [{join-key (comp/get-query child-class)}])
:initial-state (fn [_] {join-key initial-state})
:componentName join-key})
real-factory (comp/factory cls {:keyfn (fn [_] join-key)})
factory (fn [props]
(reset! pass-through-props props)
(real-factory {}))]
(setRoot! #?(:clj [join-key factory] :cljs #js [join-key factory]))))
(fn []
(let [join-key (aget key-and-root 0)
state (-> parent-this comp/any->app :com.fulcrologic.fulcro.application/state-atom)]
(swap! state dissoc join-key))))]
(aget key-and-root 1))))
(defn- pcs [app component prior-props-tree-or-ident]
(let [ident (if (eql/ident? prior-props-tree-or-ident)
prior-props-tree-or-ident
(comp/get-ident component prior-props-tree-or-ident))
state-map (rapp/current-state app)
starting-entity (get-in state-map ident)
query (comp/get-query component state-map)]
(fdn/db->tree query starting-entity state-map)))
(defn- use-db-lifecycle [app component current-props-tree set-state!]
(let [[id _] (use-state #?(:cljs (random-uuid) :clj (java.util.UUID/randomUUID)))]
(use-lifecycle
(fn []
(let [state-map (rapp/current-state app)
ident (comp/get-ident component current-props-tree)
exists? (map? (get-in state-map ident))]
(when-not exists?
(merge/merge-component! app component current-props-tree))
(rapp/add-render-listener! app id
(fn [app _]
(let [props (pcs app component ident)]
(set-state! props))))))
(fn [] (rapp/remove-render-listener! app id)))))
(defn use-component
"Use Fulcro from raw React. This is a Hook effect/state combo that will connect you to the transaction/network/data
processing of Fulcro, but will not rely on Fulcro's render. Thus, you can embed the use of the returned props in any
stock React context. Technically, you do not have to use Fulcro components for rendering, but they are necessary to define the
query/ident/initial-state for startup and normalization. You may also use this within normal (Fulcro)
components to generate dynamic components on-the-fly (see `nc`).
The arguments are:
`app` - A Fulcro app
`component` - A component with query/ident. Queries MUST have co-located normalization info. You
can create this with normal `defsc` or as an anonymous component via `raw.components/nc`.
`options` - A map of options, containing:
* `:initial-params` - The parameters to use when getting the initial state of the component. See `comp/get-initial-state`.
If no initial state exists on the top-level component, then an empty map will be used. This will mean your props will be
empty to start.
* `initialize?` - A boolean (default true). If true then the initial state of the component will be used to pre-populate the component's state
in the app database.
* `:keep-existing?` - A boolean. If true, then the state of the component will not be initialized if there
is already data at the component's ident (which will be computed using the initial state params provided, if
necessary).
* `:ident` - Only needed if you are NOT initializing state, AND the component has a dynamic ident.
Returns the props from the Fulcro database. The component using this function will automatically refresh after Fulcro
transactions run (Fulcro is not a watched-atom system. Updates happen at transaction boundaries).
MAY return nil if no data is at that component's ident.
See also `use-root`.
"
[app component
{:keys [initialize? initial-params keep-existing?]
:or {initial-params {}}
:as options}]
#?(:cljs
(let [prior-props-ref (use-ref nil)
get-props (fn [ident]
(rc/get-traced-props (rapp/current-state app) component
ident
(.-current prior-props-ref)))
[current-props
set-props!] (use-state
(fn initialize-component-state []
(let [initial-entity (comp/get-initial-state component initial-params)
initial-ident (or (:ident options) (rc/get-ident component initial-entity))]
(rapp/maybe-merge-new-component! app component initial-entity options)
(let [initial-props (get-props initial-ident)]
(set! (.-current prior-props-ref) initial-props)
initial-props))))
current-ident (or (:ident options) (rc/get-ident component current-props))]
(use-effect
(fn [] (let [listener-id (random-uuid)]
(rapp/add-render-listener! app listener-id
(fn [app _]
(let [props (get-props current-ident)]
(when-not (identical? (.-current prior-props-ref) props)
(set! (.-current prior-props-ref) props)
(set-props! props)))))
(fn use-tree-remove-render-listener* []
(rapp/remove-render-listener! app listener-id)
(set! (.-current prior-props-ref) nil))))
[(hash current-ident)])
current-props)))
(defn use-root
"Use a root key and component as a subtree managed by Fulcro from raw React. The `root-key` must be a unique
(namespace recommended) key among all keys used within the application, since the root of the database is where it
will live.
The `component` should be a real Fulcro component or a generated normalizing component from `nc` (or similar).
Returns the props (not including `root-key`) that satisfy the query of `component`. MAY return nil if no data is available.
See also `use-component`.
"
[app root-key component {:keys [initialize? keep-existing? initial-params] :as options}]
(let [prior-props-ref (use-ref nil)
get-props #(rapp/get-root-subtree-props app root-key component (.-current prior-props-ref))
[current-props set-props!] (use-state (fn []
(rapp/maybe-merge-new-root! app root-key component options)
(let [initial-props (get-props)]
(set! (.-current prior-props-ref) initial-props)
initial-props)))]
(use-lifecycle
(fn [] (rapp/add-render-listener! app root-key (fn use-root-render-listener* [app _]
(let [props (get-props)]
(when-not (identical? (.-current prior-props-ref) props)
(set! (.-current prior-props-ref) props)
(set-props! props))))))
(fn use-tree-remove-render-listener* [] (rapp/remove-root! app root-key)))
(get current-props root-key)))
(defn use-uism
"Use a UISM as an effect hook. This will set up the given state machine under the given ID, and start it (if not
already started). Your initial state handler MUST set up actors and otherwise initialize based on options.
If the machine is already started at the given ID then this effect will send it an `:event/remounted` event.
You MUST include `:componentName` in each of your actor's normalizing component options (e.g. `(nc query {:componentName ::uniqueName})`)
because UISM requires component appear in the component registry (components cannot be safely stored in app state, just their
names).
`options` is a map that can contain `::uism/actors` as an actor definition map (see `begin!`). Any other keys in options
are sent as the initial event data when the machine is started.
Returns a map that contains the actor props (by actor name) and the current state of the state machine as `:active-state`."
[app state-machine-definition id options]
(let [[uism-data set-uism-data!] (use-state (fn initialize-component-state []
(uism/current-state-and-actors (app/current-state app) id)))]
(use-lifecycle
(fn []
(uism/add-uism! app {:state-machine-definition state-machine-definition
:id id
:receive-props set-uism-data!
:actors (::uism/actors options)
:initial-event-data (dissoc options ::uism/actors)}))
(fn [] (uism/remove-uism! app id)))
uism-data))
| null | https://raw.githubusercontent.com/fulcrologic/fulcro/608422c7eb600ed30b1a9d83a5a43a8f2af96ac9/src/main/com/fulcrologic/fulcro/react/hooks.cljc | clojure |
WARNING TO MAINTAINERS: DO NOT REFERENCE DOM IN HERE. This has to work with native.
will garbage-collect the floating root child on unmount
important, you must use hooks (`defhc` or `:use-hooks? true`) | (ns com.fulcrologic.fulcro.react.hooks
"React hooks wrappers and helpers. The wrappers are simple API simplifications that help when using hooks from
Clojurescript, but this namespace also includes utilities for using Fulcro's data/network management from raw React
via hooks.
See `use-root`, `use-component`, and `use-uism`."
#?(:cljs
(:require-macros [com.fulcrologic.fulcro.react.hooks :refer [use-effect use-lifecycle]]))
(:require
[com.fulcrologic.fulcro.algorithms.tempid :as tempid]
#?(:cljs ["react" :as react])
[com.fulcrologic.fulcro.components :as comp]
[com.fulcrologic.fulcro.raw.components :as rc]
[com.fulcrologic.fulcro.raw.application :as rapp]
[com.fulcrologic.fulcro.algorithms.denormalize :as fdn]
[com.fulcrologic.fulcro.algorithms.merge :as merge]
[com.fulcrologic.fulcro.ui-state-machines :as uism]
[com.fulcrologic.fulcro.rendering.multiple-roots-renderer :as mrr]
[com.fulcrologic.fulcro.algorithms.normalized-state :as fns]
[edn-query-language.core :as eql]
[taoensso.encore :as enc]
[taoensso.timbre :as log]
[com.fulcrologic.fulcro.application :as app])
#?(:clj (:import (cljs.tagged_literals JSValue))))
(defn useState
"A simple CLJC wrapper around React/useState. Returns a JS vector for speed. You probably want use-state, which is more
convenient.
React docs: -reference.html#usestate"
[initial-value]
#?(:cljs (react/useState initial-value)))
(defn use-state
"A simple wrapper around React/useState. Returns a cljs vector for easy destructuring.
`initial-value` can be a function.
React docs: -reference.html#usestate"
[initial-value]
#?(:cljs (into-array (react/useState initial-value))))
(defn useEffect
"A CLJC wrapper around js/React.useEffect that does NO conversion of
dependencies. You probably want the macro use-effect instead.
React docs: -reference.html#useeffect"
([f]
#?(:cljs (react/useEffect f)))
([f js-deps]
#?(:cljs (react/useEffect f js-deps))))
#?(:clj
(defmacro use-effect
"A simple macro wrapper around React/useEffect that does compile-time conversion of `dependencies` to a js-array
for convenience without affecting performance.
React docs: -reference.html#useeffect"
([f]
`(useEffect ~f))
([f dependencies]
(if (enc/compiling-cljs?)
(let [deps (cond
(nil? dependencies) nil
(instance? JSValue dependencies) dependencies
:else (JSValue. dependencies))]
`(useEffect ~f ~deps))
`(useEffect ~f ~dependencies)))))
(defn use-context
"A simple wrapper around the RAW React/useContext. You should probably prefer the context support from c.f.f.r.context."
[ctx]
#?(:cljs (react/useContext ctx)))
(defn use-reducer
"A simple wrapper around React/useReducer. Returns a cljs vector for easy destructuring
React docs: -reference.html#usecontext"
([reducer initial-arg]
#?(:cljs (into-array (react/useReducer reducer initial-arg))))
([reducer initial-arg init]
#?(:cljs (into-array (react/useReducer reducer initial-arg init)))))
(defn use-callback
"A simple wrapper around React/useCallback. Converts args to js array before send.
React docs: -reference.html#usecallback"
([cb]
#?(:cljs (react/useCallback cb)))
([cb args]
#?(:cljs (react/useCallback cb (to-array args)))))
(defn use-memo
"A simple wrapper around React/useMemo. Converts args to js array before send.
NOTE: React does NOT guarantee it won't re-create the value during the lifetime of the
component, so it is sorta crappy in terms of actual memoization. Purely for optimizations, not
for guarantees.
React docs: -reference.html#usememo"
([value-factory-fn]
#?(:cljs (react/useMemo value-factory-fn)))
([value-factory-fn dependencies]
#?(:cljs (react/useMemo value-factory-fn (to-array dependencies)))))
(defn use-ref
"A simple wrapper around React/useRef.
React docs: -reference.html#useref"
([] #?(:cljs (react/useRef nil)))
([value] #?(:cljs (react/useRef value))))
(defn use-imperative-handle
"A simple wrapper around React/useImperativeHandle.
React docs: -reference.html#useimperativehandle"
[ref f]
#?(:cljs (react/useImperativeHandle ref f)))
(defn use-layout-effect
"A simple wrapper around React/useLayoutEffect.
React docs: -reference.html#uselayouteffect"
([f]
#?(:cljs (react/useLayoutEffect f)))
([f args]
#?(:cljs (react/useLayoutEffect f (to-array args)))))
(defn use-debug-value
"A simple wrapper around React/useDebugValue.
React docs: -reference.html#uselayouteffect"
([value]
#?(:cljs (react/useDebugValue value)))
([value formatter]
#?(:cljs (react/useDebugValue value formatter))))
(defn use-deferred-value
"A simple wrapper around React/useDeferredValue.
React docs: -reference.html#usedeferredvalue"
[value]
#?(:cljs (react/useDeferredValue value)))
(defn use-transition
"A simple wrapper around React/useTransition.
React docs: -reference.html#usetransition"
[value]
#?(:cljs (into-array (react/useTransition value))))
(defn use-id
"A simple wrapper around React/useId. See also use-generated-id, which is a Fulcro-specific function for generating
random uuids.
React docs: -reference.html#useid"
[]
#?(:cljs (react/useId)))
(defn use-sync-external-store
"A simple wrapper around React/useSyncExternalStore.
React docs: -reference.html#usesyncexternalstore"
([subscribe get-snapshot get-server-ss]
#?(:cljs (react/useSyncExternalStore subscribe get-snapshot get-server-ss)))
([subscribe get-snapshot]
#?(:cljs (react/useSyncExternalStore subscribe get-snapshot))))
(defn use-insertion-effect
"A simple wrapper around React/useInsertionEffect.
React docs: -reference.html#useinsertioneffect"
[didUpdate]
#?(:cljs (react/useInsertionEffect didUpdate)))
#?(:clj
(defmacro use-lifecycle
"A macro shorthand that evaluates to low-level js at compile time for
`(use-effect (fn [] (when setup (setup)) (when teardown teardown)) [])`"
([setup] `(use-lifecycle ~setup nil))
([setup teardown]
(cond
(and setup teardown) `(use-effect (fn [] (~setup) ~teardown) [])
setup `(use-effect (fn [] (~setup) ~(when (enc/compiling-cljs?) 'js/undefined)) [])
teardown `(use-effect (fn [] ~teardown) [])))))
(let [id (fn [] (tempid/uuid))]
(defn use-generated-id
"Returns a constant ident with a generated ID component."
[]
(aget (useState id) 0)))
(defn use-gc
"Effect handler. Creates an effect that will garbage-collect the given ident from fulcro app state on cleanup, and
will follow any `edges` (a set of keywords) and remove any things pointed through those keywords as well. See
normalized-state's `remove-entity`.
```
(defsc NewRoot [this props]
{:use-hooks? true}
(let [generated-id (hooks/use-generated-id)
f (use-fulcro-mount this {:child-class SomeChild
:initial-state-params {:id generated-id})]
(use-gc this [:child/id generated-id] #{})
(f props)))
```
"
[this-or-app ident edges]
(use-lifecycle
nil
(fn []
(let [state (-> this-or-app comp/any->app :com.fulcrologic.fulcro.application/state-atom)]
(swap! state fns/remove-entity ident edges)))))
(let [initial-mount-state (fn []
(let [componentName (keyword "com.fulcrologic.fulcro.floating-root" (gensym "generated-root"))]
#?(:clj [componentName nil] :cljs #js [componentName nil])))]
(defn use-fulcro-mount
"
NOTE: In many cases you are better off using the other hooks support in this ns, such as `use-component`, since
they do not have a render integration requirement.
Generate a new sub-root that is controlled and rendered by Fulcro's multi-root-renderer.
```
(defsc NewRoot [this props]
{:use-hooks? true}
(let [f (use-fulcro-mount this {:child-class SomeChild})]
parent props will show up in SomeChild as computed props .
(f props)))
```
WARNING: Requires you use multi-root-renderer."
[parent-this {:keys [child-class
initial-state-params]}]
factories are functions , and if you pass a function to setState it will run it , which is NOT what we want ...
(let [st (useState initial-mount-state)
pass-through-props (atom {})
key-and-root (aget st 0)
setRoot! (aget st 1)
_ (use-lifecycle
(fn []
(let [join-key (aget key-and-root 0)
child-factory (comp/computed-factory child-class)
initial-state (comp/get-initial-state child-class (or initial-state-params {}))
cls (comp/configure-hooks-component!
(fn [this fulcro-props]
(use-lifecycle
(fn [] (mrr/register-root! this))
(fn [] (mrr/deregister-root! this)))
(comp/with-parent-context parent-this
(child-factory (get fulcro-props join-key initial-state) @pass-through-props)))
{:query (fn [_] [{join-key (comp/get-query child-class)}])
:initial-state (fn [_] {join-key initial-state})
:componentName join-key})
real-factory (comp/factory cls {:keyfn (fn [_] join-key)})
factory (fn [props]
(reset! pass-through-props props)
(real-factory {}))]
(setRoot! #?(:clj [join-key factory] :cljs #js [join-key factory]))))
(fn []
(let [join-key (aget key-and-root 0)
state (-> parent-this comp/any->app :com.fulcrologic.fulcro.application/state-atom)]
(swap! state dissoc join-key))))]
(aget key-and-root 1))))
(defn- pcs [app component prior-props-tree-or-ident]
(let [ident (if (eql/ident? prior-props-tree-or-ident)
prior-props-tree-or-ident
(comp/get-ident component prior-props-tree-or-ident))
state-map (rapp/current-state app)
starting-entity (get-in state-map ident)
query (comp/get-query component state-map)]
(fdn/db->tree query starting-entity state-map)))
(defn- use-db-lifecycle [app component current-props-tree set-state!]
(let [[id _] (use-state #?(:cljs (random-uuid) :clj (java.util.UUID/randomUUID)))]
(use-lifecycle
(fn []
(let [state-map (rapp/current-state app)
ident (comp/get-ident component current-props-tree)
exists? (map? (get-in state-map ident))]
(when-not exists?
(merge/merge-component! app component current-props-tree))
(rapp/add-render-listener! app id
(fn [app _]
(let [props (pcs app component ident)]
(set-state! props))))))
(fn [] (rapp/remove-render-listener! app id)))))
(defn use-component
"Use Fulcro from raw React. This is a Hook effect/state combo that will connect you to the transaction/network/data
processing of Fulcro, but will not rely on Fulcro's render. Thus, you can embed the use of the returned props in any
stock React context. Technically, you do not have to use Fulcro components for rendering, but they are necessary to define the
query/ident/initial-state for startup and normalization. You may also use this within normal (Fulcro)
components to generate dynamic components on-the-fly (see `nc`).
The arguments are:
`app` - A Fulcro app
`component` - A component with query/ident. Queries MUST have co-located normalization info. You
can create this with normal `defsc` or as an anonymous component via `raw.components/nc`.
`options` - A map of options, containing:
* `:initial-params` - The parameters to use when getting the initial state of the component. See `comp/get-initial-state`.
If no initial state exists on the top-level component, then an empty map will be used. This will mean your props will be
empty to start.
* `initialize?` - A boolean (default true). If true then the initial state of the component will be used to pre-populate the component's state
in the app database.
* `:keep-existing?` - A boolean. If true, then the state of the component will not be initialized if there
is already data at the component's ident (which will be computed using the initial state params provided, if
necessary).
* `:ident` - Only needed if you are NOT initializing state, AND the component has a dynamic ident.
Returns the props from the Fulcro database. The component using this function will automatically refresh after Fulcro
transactions run (Fulcro is not a watched-atom system. Updates happen at transaction boundaries).
MAY return nil if no data is at that component's ident.
See also `use-root`.
"
[app component
{:keys [initialize? initial-params keep-existing?]
:or {initial-params {}}
:as options}]
#?(:cljs
(let [prior-props-ref (use-ref nil)
get-props (fn [ident]
(rc/get-traced-props (rapp/current-state app) component
ident
(.-current prior-props-ref)))
[current-props
set-props!] (use-state
(fn initialize-component-state []
(let [initial-entity (comp/get-initial-state component initial-params)
initial-ident (or (:ident options) (rc/get-ident component initial-entity))]
(rapp/maybe-merge-new-component! app component initial-entity options)
(let [initial-props (get-props initial-ident)]
(set! (.-current prior-props-ref) initial-props)
initial-props))))
current-ident (or (:ident options) (rc/get-ident component current-props))]
(use-effect
(fn [] (let [listener-id (random-uuid)]
(rapp/add-render-listener! app listener-id
(fn [app _]
(let [props (get-props current-ident)]
(when-not (identical? (.-current prior-props-ref) props)
(set! (.-current prior-props-ref) props)
(set-props! props)))))
(fn use-tree-remove-render-listener* []
(rapp/remove-render-listener! app listener-id)
(set! (.-current prior-props-ref) nil))))
[(hash current-ident)])
current-props)))
(defn use-root
"Use a root key and component as a subtree managed by Fulcro from raw React. The `root-key` must be a unique
(namespace recommended) key among all keys used within the application, since the root of the database is where it
will live.
The `component` should be a real Fulcro component or a generated normalizing component from `nc` (or similar).
Returns the props (not including `root-key`) that satisfy the query of `component`. MAY return nil if no data is available.
See also `use-component`.
"
[app root-key component {:keys [initialize? keep-existing? initial-params] :as options}]
(let [prior-props-ref (use-ref nil)
get-props #(rapp/get-root-subtree-props app root-key component (.-current prior-props-ref))
[current-props set-props!] (use-state (fn []
(rapp/maybe-merge-new-root! app root-key component options)
(let [initial-props (get-props)]
(set! (.-current prior-props-ref) initial-props)
initial-props)))]
(use-lifecycle
(fn [] (rapp/add-render-listener! app root-key (fn use-root-render-listener* [app _]
(let [props (get-props)]
(when-not (identical? (.-current prior-props-ref) props)
(set! (.-current prior-props-ref) props)
(set-props! props))))))
(fn use-tree-remove-render-listener* [] (rapp/remove-root! app root-key)))
(get current-props root-key)))
(defn use-uism
"Use a UISM as an effect hook. This will set up the given state machine under the given ID, and start it (if not
already started). Your initial state handler MUST set up actors and otherwise initialize based on options.
If the machine is already started at the given ID then this effect will send it an `:event/remounted` event.
You MUST include `:componentName` in each of your actor's normalizing component options (e.g. `(nc query {:componentName ::uniqueName})`)
because UISM requires component appear in the component registry (components cannot be safely stored in app state, just their
names).
`options` is a map that can contain `::uism/actors` as an actor definition map (see `begin!`). Any other keys in options
are sent as the initial event data when the machine is started.
Returns a map that contains the actor props (by actor name) and the current state of the state machine as `:active-state`."
[app state-machine-definition id options]
(let [[uism-data set-uism-data!] (use-state (fn initialize-component-state []
(uism/current-state-and-actors (app/current-state app) id)))]
(use-lifecycle
(fn []
(uism/add-uism! app {:state-machine-definition state-machine-definition
:id id
:receive-props set-uism-data!
:actors (::uism/actors options)
:initial-event-data (dissoc options ::uism/actors)}))
(fn [] (uism/remove-uism! app id)))
uism-data))
|
90e1a905d09301aae05b2564e2bf88857ce0195901fe77174ee10143e2221372 | UU-ComputerScience/uu-cco | Parser.hs | -------------------------------------------------------------------------------
-- |
Module : CCO.ArithBool .
Copyright : ( c ) 2008 Utrecht University
-- License : All rights reserved
--
-- Maintainer :
-- Stability : provisional
-- Portability : portable
--
A ' Parser ' for arithmetic and boolean expressions .
--
-------------------------------------------------------------------------------
module CCO.ArithBool.Parser (
*
parser -- :: Component String Tm
) where
import CCO.ArithBool.Base (Tm (Tm), Tm_ (..))
import CCO.ArithBool.Lexer
import CCO.Component (Component)
import qualified CCO.Component as C (parser)
import CCO.Parsing (Parser, sourcePos, eof, (<!>), chainl)
import Control.Applicative
-------------------------------------------------------------------------------
-- Token parsers
-------------------------------------------------------------------------------
| Type of ' Parser 's that consume symbols described by ' 's .
type TokenParser = Parser Token
-------------------------------------------------------------------------------
Parser
-------------------------------------------------------------------------------
-- A 'Component' for parsing arithmetic and boolean expressions.
parser :: Component String Tm
parser = C.parser lexer (pTm <* eof)
-- | Parses a 'Tm'.
pTm :: TokenParser Tm
pTm = pEqPrio <!> "term"
where
pEqPrio =
(\t1 op t2 -> op t1 t2) <$>
pAddPrio <*>
(pOp Lt "<" <|> pOp Eq "==" <|> pOp Gt ">" <!> "relational operator") <*>
pAddPrio <|>
pAddPrio
pAddPrio =
chainl (pOp Add "+" <|> pOp Sub "-" <!> "arithmetic operator") pMulPrio
pMulPrio =
chainl (pOp Mul "*" <|> pOp Div "/" <!> "arithmetic operator") pBase
pBase = pPos (Num <$> num) <|>
pPos (False_ <$ keyword "false") <|>
pPos (True_ <$ keyword "true") <|>
pPos (If <$ keyword "if" <*> pTm <* keyword "then" <*> pTm <*
keyword "else" <*> pTm <* keyword "fi") <|>
spec '(' *> pTm <* spec ')' <!>
"term"
pPos p = Tm <$> sourcePos <*> p
pOp f op = (\t1@(Tm pos _) t2 -> Tm pos (f t1 t2)) <$ operator op | null | https://raw.githubusercontent.com/UU-ComputerScience/uu-cco/cca433c8a6f4d27407800404dea80c08fd567093/uu-cco-examples/src/CCO/ArithBool/Parser.hs | haskell | -----------------------------------------------------------------------------
|
License : All rights reserved
Maintainer :
Stability : provisional
Portability : portable
-----------------------------------------------------------------------------
:: Component String Tm
-----------------------------------------------------------------------------
Token parsers
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
A 'Component' for parsing arithmetic and boolean expressions.
| Parses a 'Tm'. | Module : CCO.ArithBool .
Copyright : ( c ) 2008 Utrecht University
A ' Parser ' for arithmetic and boolean expressions .
module CCO.ArithBool.Parser (
*
) where
import CCO.ArithBool.Base (Tm (Tm), Tm_ (..))
import CCO.ArithBool.Lexer
import CCO.Component (Component)
import qualified CCO.Component as C (parser)
import CCO.Parsing (Parser, sourcePos, eof, (<!>), chainl)
import Control.Applicative
| Type of ' Parser 's that consume symbols described by ' 's .
type TokenParser = Parser Token
Parser
parser :: Component String Tm
parser = C.parser lexer (pTm <* eof)
pTm :: TokenParser Tm
pTm = pEqPrio <!> "term"
where
pEqPrio =
(\t1 op t2 -> op t1 t2) <$>
pAddPrio <*>
(pOp Lt "<" <|> pOp Eq "==" <|> pOp Gt ">" <!> "relational operator") <*>
pAddPrio <|>
pAddPrio
pAddPrio =
chainl (pOp Add "+" <|> pOp Sub "-" <!> "arithmetic operator") pMulPrio
pMulPrio =
chainl (pOp Mul "*" <|> pOp Div "/" <!> "arithmetic operator") pBase
pBase = pPos (Num <$> num) <|>
pPos (False_ <$ keyword "false") <|>
pPos (True_ <$ keyword "true") <|>
pPos (If <$ keyword "if" <*> pTm <* keyword "then" <*> pTm <*
keyword "else" <*> pTm <* keyword "fi") <|>
spec '(' *> pTm <* spec ')' <!>
"term"
pPos p = Tm <$> sourcePos <*> p
pOp f op = (\t1@(Tm pos _) t2 -> Tm pos (f t1 t2)) <$ operator op |
5cbef6bb837822dadefca1505eda05778f735131fd8fbf6999bfecc0e4d68e05 | OCamlPro/OCamlPro-OCaml-Branch | printtyp.ml | (***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
and , 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 .
(* *)
(***********************************************************************)
$ Id$
(* Printing functions *)
open Misc
open Ctype
open Format
open Longident
open Path
open Asttypes
open Types
open Btype
open Outcometree
(* Print a long identifier *)
let rec longident ppf = function
| Lident s -> fprintf ppf "%s" s
| Ldot(p, s) -> fprintf ppf "%a.%s" longident p s
| Lapply(p1, p2) -> fprintf ppf "%a(%a)" longident p1 longident p2
(* Print an identifier *)
let unique_names = ref Ident.empty
let ident_name id =
try Ident.find_same id !unique_names with Not_found -> Ident.name id
let add_unique id =
try ignore (Ident.find_same id !unique_names)
with Not_found ->
unique_names := Ident.add id (Ident.unique_toplevel_name id) !unique_names
let ident ppf id = fprintf ppf "%s" (ident_name id)
(* Print a path *)
let ident_pervasive = Ident.create_persistent "Pervasives"
let rec tree_of_path = function
| Pident id ->
Oide_ident (ident_name id)
| Pdot(Pident id, s, pos) when Ident.same id ident_pervasive ->
Oide_ident s
| Pdot(p, s, pos) ->
Oide_dot (tree_of_path p, s)
| Papply(p1, p2) ->
Oide_apply (tree_of_path p1, tree_of_path p2)
let rec path ppf = function
| Pident id ->
ident ppf id
| Pdot(Pident id, s, pos) when Ident.same id ident_pervasive ->
fprintf ppf "%s" s
| Pdot(p, s, pos) ->
fprintf ppf "%a.%s" path p s
| Papply(p1, p2) ->
fprintf ppf "%a(%a)" path p1 path p2
(* Print a recursive annotation *)
let tree_of_rec = function
| Trec_not -> Orec_not
| Trec_first -> Orec_first
| Trec_next -> Orec_next
(* Print a raw type expression, with sharing *)
let raw_list pr ppf = function
[] -> fprintf ppf "[]"
| a :: l ->
fprintf ppf "@[<1>[%a%t]@]" pr a
(fun ppf -> List.iter (fun x -> fprintf ppf ";@,%a" pr x) l)
let rec safe_kind_repr v = function
Fvar {contents=Some k} ->
if List.memq k v then "Fvar loop" else
safe_kind_repr (k::v) k
| Fvar _ -> "Fvar None"
| Fpresent -> "Fpresent"
| Fabsent -> "Fabsent"
let rec safe_commu_repr v = function
Cok -> "Cok"
| Cunknown -> "Cunknown"
| Clink r ->
if List.memq r v then "Clink loop" else
safe_commu_repr (r::v) !r
let rec safe_repr v = function
{desc = Tlink t} when not (List.memq t v) ->
safe_repr (t::v) t
| t -> t
let rec list_of_memo = function
Mnil -> []
| Mcons (priv, p, t1, t2, rem) -> p :: list_of_memo rem
| Mlink rem -> list_of_memo !rem
let visited = ref []
let rec raw_type ppf ty =
let ty = safe_repr [] ty in
if List.memq ty !visited then fprintf ppf "{id=%d}" ty.id else begin
visited := ty :: !visited;
fprintf ppf "@[<1>{id=%d;level=%d;desc=@,%a}@]" ty.id ty.level
raw_type_desc ty.desc
end
and raw_type_list tl = raw_list raw_type tl
and raw_type_desc ppf = function
Tvar -> fprintf ppf "Tvar"
| Tarrow(l,t1,t2,c) ->
fprintf ppf "@[<hov1>Tarrow(%s,@,%a,@,%a,@,%s)@]"
l raw_type t1 raw_type t2
(safe_commu_repr [] c)
| Ttuple tl ->
fprintf ppf "@[<1>Ttuple@,%a@]" raw_type_list tl
| Tconstr (p, tl, abbrev) ->
fprintf ppf "@[<hov1>Tconstr(@,%a,@,%a,@,%a)@]" path p
raw_type_list tl
(raw_list path) (list_of_memo !abbrev)
| Tobject (t, nm) ->
fprintf ppf "@[<hov1>Tobject(@,%a,@,@[<1>ref%t@])@]" raw_type t
(fun ppf ->
match !nm with None -> fprintf ppf " None"
| Some(p,tl) ->
fprintf ppf "(Some(@,%a,@,%a))" path p raw_type_list tl)
| Tfield (f, k, t1, t2) ->
fprintf ppf "@[<hov1>Tfield(@,%s,@,%s,@,%a,@;<0 -1>%a)@]" f
(safe_kind_repr [] k)
raw_type t1 raw_type t2
| Tnil -> fprintf ppf "Tnil"
| Tlink t -> fprintf ppf "@[<1>Tlink@,%a@]" raw_type t
| Tsubst t -> fprintf ppf "@[<1>Tsubst@,%a@]" raw_type t
| Tunivar -> fprintf ppf "Tunivar"
| Tpoly (t, tl) ->
fprintf ppf "@[<hov1>Tpoly(@,%a,@,%a)@]"
raw_type t
raw_type_list tl
| Tvariant row ->
fprintf ppf
"@[<hov1>{@[%s@,%a;@]@ @[%s@,%a;@]@ %s%b;@ %s%b;@ @[<1>%s%t@]}@]"
"row_fields="
(raw_list (fun ppf (l, f) ->
fprintf ppf "@[%s,@ %a@]" l raw_field f))
row.row_fields
"row_more=" raw_type row.row_more
"row_closed=" row.row_closed
"row_fixed=" row.row_fixed
"row_name="
(fun ppf ->
match row.row_name with None -> fprintf ppf "None"
| Some(p,tl) ->
fprintf ppf "Some(@,%a,@,%a)" path p raw_type_list tl)
| Tpackage (p, _, tl) ->
fprintf ppf "@[<hov1>Tpackage(@,%a@,%a)@]" path p
raw_type_list tl
and raw_field ppf = function
Rpresent None -> fprintf ppf "Rpresent None"
| Rpresent (Some t) -> fprintf ppf "@[<1>Rpresent(Some@,%a)@]" raw_type t
| Reither (c,tl,m,e) ->
fprintf ppf "@[<hov1>Reither(%b,@,%a,@,%b,@,@[<1>ref%t@])@]" c
raw_type_list tl m
(fun ppf ->
match !e with None -> fprintf ppf " None"
| Some f -> fprintf ppf "@,@[<1>(%a)@]" raw_field f)
| Rabsent -> fprintf ppf "Rabsent"
let raw_type_expr ppf t =
visited := [];
raw_type ppf t;
visited := []
(* Print a type expression *)
let names = ref ([] : (type_expr * string) list)
let name_counter = ref 0
let reset_names () = names := []; name_counter := 0
let new_name () =
let name =
if !name_counter < 26
then String.make 1 (Char.chr(97 + !name_counter))
else String.make 1 (Char.chr(97 + !name_counter mod 26)) ^
string_of_int(!name_counter / 26) in
incr name_counter;
name
let name_of_type t =
try List.assq t !names with Not_found ->
let name = new_name () in
names := (t, name) :: !names;
name
let check_name_of_type t = ignore(name_of_type t)
let non_gen_mark sch ty =
if sch && ty.desc = Tvar && ty.level <> generic_level then "_" else ""
let print_name_of_type sch ppf t =
fprintf ppf "'%s%s" (non_gen_mark sch t) (name_of_type t)
let visited_objects = ref ([] : type_expr list)
let aliased = ref ([] : type_expr list)
let delayed = ref ([] : type_expr list)
let add_delayed t =
if not (List.memq t !delayed) then delayed := t :: !delayed
let is_aliased ty = List.memq (proxy ty) !aliased
let add_alias ty =
let px = proxy ty in
if not (is_aliased px) then aliased := px :: !aliased
let aliasable ty =
match ty.desc with Tvar | Tunivar | Tpoly _ -> false | _ -> true
let namable_row row =
row.row_name <> None &&
List.for_all
(fun (_, f) ->
match row_field_repr f with
| Reither(c, l, _, _) ->
row.row_closed && if c then l = [] else List.length l = 1
| _ -> true)
row.row_fields
let rec mark_loops_rec visited ty =
let ty = repr ty in
let px = proxy ty in
if List.memq px visited && aliasable ty then add_alias px else
let visited = px :: visited in
match ty.desc with
| Tvar -> ()
| Tarrow(_, ty1, ty2, _) ->
mark_loops_rec visited ty1; mark_loops_rec visited ty2
| Ttuple tyl -> List.iter (mark_loops_rec visited) tyl
| Tconstr(_, tyl, _) | Tpackage (_, _, tyl) ->
List.iter (mark_loops_rec visited) tyl
| Tvariant row ->
if List.memq px !visited_objects then add_alias px else
begin
let row = row_repr row in
if not (static_row row) then
visited_objects := px :: !visited_objects;
match row.row_name with
| Some(p, tyl) when namable_row row ->
List.iter (mark_loops_rec visited) tyl
| _ ->
iter_row (mark_loops_rec visited) row
end
| Tobject (fi, nm) ->
if List.memq px !visited_objects then add_alias px else
begin
if opened_object ty then
visited_objects := px :: !visited_objects;
begin match !nm with
| None ->
let fields, _ = flatten_fields fi in
List.iter
(fun (_, kind, ty) ->
if field_kind_repr kind = Fpresent then
mark_loops_rec visited ty)
fields
| Some (_, l) ->
List.iter (mark_loops_rec visited) (List.tl l)
end
end
| Tfield(_, kind, ty1, ty2) when field_kind_repr kind = Fpresent ->
mark_loops_rec visited ty1; mark_loops_rec visited ty2
| Tfield(_, _, _, ty2) ->
mark_loops_rec visited ty2
| Tnil -> ()
| Tsubst ty -> mark_loops_rec visited ty
| Tlink _ -> fatal_error "Printtyp.mark_loops_rec (2)"
| Tpoly (ty, tyl) ->
List.iter (fun t -> add_alias t) tyl;
mark_loops_rec visited ty
| Tunivar -> ()
let mark_loops ty =
normalize_type Env.empty ty;
mark_loops_rec [] ty;;
let reset_loop_marks () =
visited_objects := []; aliased := []; delayed := []
let reset () =
unique_names := Ident.empty; reset_names (); reset_loop_marks ()
let reset_and_mark_loops ty =
reset (); mark_loops ty
let reset_and_mark_loops_list tyl =
reset (); List.iter mark_loops tyl
(* Disabled in classic mode when printing an unification error *)
let print_labels = ref true
let print_label ppf l =
if !print_labels && l <> "" || is_optional l then fprintf ppf "%s:" l
let rec tree_of_typexp sch ty =
let ty = repr ty in
let px = proxy ty in
if List.mem_assq px !names && not (List.memq px !delayed) then
let mark = is_non_gen sch ty in
Otyp_var (mark, name_of_type px) else
let pr_typ () =
match ty.desc with
| Tvar ->
Otyp_var (is_non_gen sch ty, name_of_type ty)
| Tarrow(l, ty1, ty2, _) ->
let pr_arrow l ty1 ty2 =
let lab =
if !print_labels && l <> "" || is_optional l then l else ""
in
let t1 =
if is_optional l then
match (repr ty1).desc with
| Tconstr(path, [ty], _)
when Path.same path Predef.path_option ->
tree_of_typexp sch ty
| _ -> Otyp_stuff "<hidden>"
else tree_of_typexp sch ty1 in
Otyp_arrow (lab, t1, tree_of_typexp sch ty2) in
pr_arrow l ty1 ty2
| Ttuple tyl ->
Otyp_tuple (tree_of_typlist sch tyl)
| Tconstr(p, tyl, abbrev) ->
Otyp_constr (tree_of_path p, tree_of_typlist sch tyl)
| Tvariant row ->
let row = row_repr row in
let fields =
if row.row_closed then
List.filter (fun (_, f) -> row_field_repr f <> Rabsent)
row.row_fields
else row.row_fields in
let present =
List.filter
(fun (_, f) ->
match row_field_repr f with
| Rpresent _ -> true
| _ -> false)
fields in
let all_present = List.length present = List.length fields in
begin match row.row_name with
| Some(p, tyl) when namable_row row ->
let id = tree_of_path p in
let args = tree_of_typlist sch tyl in
if row.row_closed && all_present then
Otyp_constr (id, args)
else
let non_gen = is_non_gen sch px in
let tags =
if all_present then None else Some (List.map fst present) in
Otyp_variant (non_gen, Ovar_name(tree_of_path p, args),
row.row_closed, tags)
| _ ->
let non_gen =
not (row.row_closed && all_present) && is_non_gen sch px in
let fields = List.map (tree_of_row_field sch) fields in
let tags =
if all_present then None else Some (List.map fst present) in
Otyp_variant (non_gen, Ovar_fields fields, row.row_closed, tags)
end
| Tobject (fi, nm) ->
tree_of_typobject sch fi nm
| Tsubst ty ->
tree_of_typexp sch ty
| Tlink _ | Tnil | Tfield _ ->
fatal_error "Printtyp.tree_of_typexp"
| Tpoly (ty, []) ->
tree_of_typexp sch ty
| Tpoly (ty, tyl) ->
let tyl = List.map repr tyl in
let tyl = List.filter is_aliased tyl in
if tyl = [] then tree_of_typexp sch ty else begin
let old_delayed = !delayed in
List.iter add_delayed tyl;
let tl = List.map name_of_type tyl in
let tr = Otyp_poly (tl, tree_of_typexp sch ty) in
delayed := old_delayed; tr
end
| Tunivar ->
Otyp_var (false, name_of_type ty)
| Tpackage (p, n, tyl) ->
Otyp_module (Path.name p, n, tree_of_typlist sch tyl)
in
if List.memq px !delayed then delayed := List.filter ((!=) px) !delayed;
if is_aliased px && aliasable ty then begin
check_name_of_type px;
Otyp_alias (pr_typ (), name_of_type px) end
else pr_typ ()
and tree_of_row_field sch (l, f) =
match row_field_repr f with
| Rpresent None | Reither(true, [], _, _) -> (l, false, [])
| Rpresent(Some ty) -> (l, false, [tree_of_typexp sch ty])
| Reither(c, tyl, _, _) ->
contradiction : un constructeur constant qui a un argument
then (l, true, tree_of_typlist sch tyl)
else (l, false, tree_of_typlist sch tyl)
| Rabsent -> (l, false, [] (* une erreur, en fait *))
and tree_of_typlist sch tyl =
List.map (tree_of_typexp sch) tyl
and tree_of_typobject sch fi nm =
begin match !nm with
| None ->
let pr_fields fi =
let (fields, rest) = flatten_fields fi in
let present_fields =
List.fold_right
(fun (n, k, t) l ->
match field_kind_repr k with
| Fpresent -> (n, t) :: l
| _ -> l)
fields [] in
let sorted_fields =
Sort.list (fun (n, _) (n', _) -> n <= n') present_fields in
tree_of_typfields sch rest sorted_fields in
let (fields, rest) = pr_fields fi in
Otyp_object (fields, rest)
| Some (p, ty :: tyl) ->
let non_gen = is_non_gen sch (repr ty) in
let args = tree_of_typlist sch tyl in
Otyp_class (non_gen, tree_of_path p, args)
| _ ->
fatal_error "Printtyp.tree_of_typobject"
end
and is_non_gen sch ty =
sch && ty.desc = Tvar && ty.level <> generic_level
and tree_of_typfields sch rest = function
| [] ->
let rest =
match rest.desc with
| Tvar | Tunivar -> Some (is_non_gen sch rest)
| Tconstr _ -> Some false
| Tnil -> None
| _ -> fatal_error "typfields (1)"
in
([], rest)
| (s, t) :: l ->
let field = (s, tree_of_typexp sch t) in
let (fields, rest) = tree_of_typfields sch rest l in
(field :: fields, rest)
let typexp sch prio ppf ty =
!Oprint.out_type ppf (tree_of_typexp sch ty)
let type_expr ppf ty = typexp false 0 ppf ty
and type_sch ppf ty = typexp true 0 ppf ty
and type_scheme ppf ty = reset_and_mark_loops ty; typexp true 0 ppf ty
(* Maxence *)
let type_scheme_max ?(b_reset_names=true) ppf ty =
if b_reset_names then reset_names () ;
typexp true 0 ppf ty
let tree_of_type_scheme ty = reset_and_mark_loops ty; tree_of_typexp true ty
Print one type declaration
let tree_of_constraints params =
List.fold_right
(fun ty list ->
let ty' = unalias ty in
if proxy ty != proxy ty' then
let tr = tree_of_typexp true ty in
(tr, tree_of_typexp true ty') :: list
else list)
params []
let filter_params tyl =
let params =
List.fold_left
(fun tyl ty ->
let ty = repr ty in
if List.memq ty tyl then Btype.newgenty (Tsubst ty) :: tyl
else ty :: tyl)
[] tyl
in List.rev params
let string_of_mutable = function
| Immutable -> ""
| Mutable -> "mutable "
let rec tree_of_type_decl id decl =
reset();
let params = filter_params decl.type_params in
List.iter add_alias params;
List.iter mark_loops params;
List.iter check_name_of_type (List.map proxy params);
let ty_manifest =
match decl.type_manifest with
| None -> None
| Some ty ->
let ty =
(* Special hack to hide variant name *)
match repr ty with {desc=Tvariant row} ->
let row = row_repr row in
begin match row.row_name with
Some (Pident id', _) when Ident.same id id' ->
newgenty (Tvariant {row with row_name = None})
| _ -> ty
end
| _ -> ty
in
mark_loops ty;
Some ty
in
begin match decl.type_kind with
| Type_abstract -> ()
| Type_variant [] -> ()
| Type_variant cstrs ->
List.iter (fun (_, args) -> List.iter mark_loops args) cstrs
| Type_record(l, rep) ->
List.iter (fun (_, _, ty) -> mark_loops ty) l
end;
let type_param =
function
| Otyp_var (_, id) -> id
| _ -> "?"
in
let type_defined decl =
let abstr =
match decl.type_kind with
Type_abstract ->
decl.type_manifest = None || decl.type_private = Private
| Type_variant _ | Type_record _ ->
decl.type_private = Private
in
let vari =
List.map2
(fun ty (co,cn,ct) ->
if abstr || (repr ty).desc <> Tvar then (co,cn) else (true,true))
decl.type_params decl.type_variance
in
(Ident.name id,
List.map2 (fun ty cocn -> type_param (tree_of_typexp false ty), cocn)
params vari)
in
let tree_of_manifest ty1 =
match ty_manifest with
| None -> ty1
| Some ty -> Otyp_manifest (tree_of_typexp false ty, ty1)
in
let (name, args) = type_defined decl in
let constraints = tree_of_constraints params in
let ty, priv =
match decl.type_kind with
| Type_abstract ->
begin match ty_manifest with
| None -> (Otyp_abstract, Public)
| Some ty ->
tree_of_typexp false ty, decl.type_private
end
| Type_variant cstrs ->
tree_of_manifest (Otyp_sum (List.map tree_of_constructor cstrs)),
decl.type_private
| Type_record(lbls, rep) ->
tree_of_manifest (Otyp_record (List.map tree_of_label lbls)),
decl.type_private
in
(name, args, ty, priv, constraints)
and tree_of_constructor (name, args) =
(name, tree_of_typlist false args)
and tree_of_label (name, mut, arg) =
(name, mut = Mutable, tree_of_typexp false arg)
let tree_of_type_declaration id decl rs =
Osig_type (tree_of_type_decl id decl, tree_of_rec rs)
let type_declaration id ppf decl =
!Oprint.out_sig_item ppf (tree_of_type_declaration id decl Trec_first)
(* Print an exception declaration *)
let tree_of_exception_declaration id decl =
reset_and_mark_loops_list decl;
let tyl = tree_of_typlist false decl in
Osig_exception (Ident.name id, tyl)
let exception_declaration id ppf decl =
!Oprint.out_sig_item ppf (tree_of_exception_declaration id decl)
(* Print a value declaration *)
let tree_of_value_description id decl =
let id = Ident.name id in
let ty = tree_of_type_scheme decl.val_type in
let prims =
match decl.val_kind with
| Val_prim p -> Primitive.description_list p
| _ -> []
in
Osig_value (id, ty, prims)
let value_description id ppf decl =
!Oprint.out_sig_item ppf (tree_of_value_description id decl)
(* Print a class type *)
let class_var sch ppf l (m, t) =
fprintf ppf
"@ @[<2>val %s%s :@ %a@]" (string_of_mutable m) l (typexp sch 0) t
let method_type (_, kind, ty) =
match field_kind_repr kind, repr ty with
Fpresent, {desc=Tpoly(ty, _)} -> ty
| _ , ty -> ty
let tree_of_metho sch concrete csil (lab, kind, ty) =
if lab <> dummy_method then begin
let kind = field_kind_repr kind in
let priv = kind <> Fpresent in
let virt = not (Concr.mem lab concrete) in
let ty = method_type (lab, kind, ty) in
Ocsg_method (lab, priv, virt, tree_of_typexp sch ty) :: csil
end
else csil
let rec prepare_class_type params = function
| Tcty_constr (p, tyl, cty) ->
let sty = Ctype.self_type cty in
if List.memq (proxy sty) !visited_objects
|| List.exists (fun ty -> (repr ty).desc <> Tvar) params
|| List.exists (deep_occur sty) tyl
then prepare_class_type params cty
else List.iter mark_loops tyl
| Tcty_signature sign ->
let sty = repr sign.cty_self in
(* Self may have a name *)
let px = proxy sty in
if List.memq px !visited_objects then add_alias sty
else visited_objects := px :: !visited_objects;
let (fields, _) =
Ctype.flatten_fields (Ctype.object_fields sign.cty_self)
in
List.iter (fun met -> mark_loops (method_type met)) fields;
Vars.iter (fun _ (_, _, ty) -> mark_loops ty) sign.cty_vars
| Tcty_fun (_, ty, cty) ->
mark_loops ty;
prepare_class_type params cty
let rec tree_of_class_type sch params =
function
| Tcty_constr (p', tyl, cty) ->
let sty = Ctype.self_type cty in
if List.memq (proxy sty) !visited_objects
|| List.exists (fun ty -> (repr ty).desc <> Tvar) params
then
tree_of_class_type sch params cty
else
Octy_constr (tree_of_path p', tree_of_typlist true tyl)
| Tcty_signature sign ->
let sty = repr sign.cty_self in
let self_ty =
if is_aliased sty then
Some (Otyp_var (false, name_of_type (proxy sty)))
else None
in
let (fields, _) =
Ctype.flatten_fields (Ctype.object_fields sign.cty_self)
in
let csil = [] in
let csil =
List.fold_left
(fun csil (ty1, ty2) -> Ocsg_constraint (ty1, ty2) :: csil)
csil (tree_of_constraints params)
in
let all_vars =
Vars.fold (fun l (m, v, t) all -> (l, m, v, t) :: all) sign.cty_vars []
in
Consequence of PR#3607 : order of Map.fold has changed !
let all_vars = List.rev all_vars in
let csil =
List.fold_left
(fun csil (l, m, v, t) ->
Ocsg_value (l, m = Mutable, v = Virtual, tree_of_typexp sch t)
:: csil)
csil all_vars
in
let csil =
List.fold_left (tree_of_metho sch sign.cty_concr) csil fields
in
Octy_signature (self_ty, List.rev csil)
| Tcty_fun (l, ty, cty) ->
let lab = if !print_labels && l <> "" || is_optional l then l else "" in
let ty =
if is_optional l then
match (repr ty).desc with
| Tconstr(path, [ty], _) when Path.same path Predef.path_option -> ty
| _ -> newconstr (Path.Pident(Ident.create "<hidden>")) []
else ty in
let tr = tree_of_typexp sch ty in
Octy_fun (lab, tr, tree_of_class_type sch params cty)
let class_type ppf cty =
reset ();
prepare_class_type [] cty;
!Oprint.out_class_type ppf (tree_of_class_type false [] cty)
let tree_of_class_param param variance =
(match tree_of_typexp true param with
Otyp_var (_, s) -> s
| _ -> "?"),
if (repr param).desc = Tvar then (true, true) else variance
let tree_of_class_params params =
let tyl = tree_of_typlist true params in
List.map (function Otyp_var (_, s) -> s | _ -> "?") tyl
let tree_of_class_declaration id cl rs =
let params = filter_params cl.cty_params in
reset ();
List.iter add_alias params;
prepare_class_type params cl.cty_type;
let sty = self_type cl.cty_type in
List.iter mark_loops params;
List.iter check_name_of_type (List.map proxy params);
if is_aliased sty then check_name_of_type (proxy sty);
let vir_flag = cl.cty_new = None in
Osig_class
(vir_flag, Ident.name id,
List.map2 tree_of_class_param params cl.cty_variance,
tree_of_class_type true params cl.cty_type,
tree_of_rec rs)
let class_declaration id ppf cl =
!Oprint.out_sig_item ppf (tree_of_class_declaration id cl Trec_first)
let tree_of_cltype_declaration id cl rs =
let params = List.map repr cl.clty_params in
reset ();
List.iter add_alias params;
prepare_class_type params cl.clty_type;
let sty = self_type cl.clty_type in
List.iter mark_loops params;
List.iter check_name_of_type (List.map proxy params);
if is_aliased sty then check_name_of_type (proxy sty);
let sign = Ctype.signature_of_class_type cl.clty_type in
let virt =
let (fields, _) =
Ctype.flatten_fields (Ctype.object_fields sign.cty_self) in
List.exists
(fun (lab, _, ty) ->
not (lab = dummy_method || Concr.mem lab sign.cty_concr))
fields
|| Vars.fold (fun _ (_,vr,_) b -> vr = Virtual || b) sign.cty_vars false
in
Osig_class_type
(virt, Ident.name id,
List.map2 tree_of_class_param params cl.clty_variance,
tree_of_class_type true params cl.clty_type,
tree_of_rec rs)
let cltype_declaration id ppf cl =
!Oprint.out_sig_item ppf (tree_of_cltype_declaration id cl Trec_first)
(* Print a module type *)
let rec tree_of_modtype = function
| Tmty_ident p ->
Omty_ident (tree_of_path p)
| Tmty_signature sg ->
Omty_signature (tree_of_signature sg)
| Tmty_functor(param, ty_arg, ty_res) ->
Omty_functor
(Ident.name param, tree_of_modtype ty_arg, tree_of_modtype ty_res)
and tree_of_signature = function
| [] -> []
| Tsig_value(id, decl) :: rem ->
tree_of_value_description id decl :: tree_of_signature rem
| Tsig_type(id, _, _) :: rem when is_row_name (Ident.name id) ->
tree_of_signature rem
| Tsig_type(id, decl, rs) :: rem ->
Osig_type(tree_of_type_decl id decl, tree_of_rec rs) ::
tree_of_signature rem
| Tsig_exception(id, decl) :: rem ->
tree_of_exception_declaration id decl :: tree_of_signature rem
| Tsig_module(id, mty, rs) :: rem ->
Osig_module (Ident.name id, tree_of_modtype mty, tree_of_rec rs) ::
tree_of_signature rem
| Tsig_modtype(id, decl) :: rem ->
tree_of_modtype_declaration id decl :: tree_of_signature rem
| Tsig_class(id, decl, rs) :: ctydecl :: tydecl1 :: tydecl2 :: rem ->
tree_of_class_declaration id decl rs :: tree_of_signature rem
| Tsig_cltype(id, decl, rs) :: tydecl1 :: tydecl2 :: rem ->
tree_of_cltype_declaration id decl rs :: tree_of_signature rem
| _ ->
assert false
and tree_of_modtype_declaration id decl =
let mty =
match decl with
| Tmodtype_abstract -> Omty_abstract
| Tmodtype_manifest mty -> tree_of_modtype mty
in
Osig_modtype (Ident.name id, mty)
let tree_of_module id mty rs =
Osig_module (Ident.name id, tree_of_modtype mty, tree_of_rec rs)
let modtype ppf mty = !Oprint.out_module_type ppf (tree_of_modtype mty)
let modtype_declaration id ppf decl =
!Oprint.out_sig_item ppf (tree_of_modtype_declaration id decl)
Print a signature body ( used by -i when compiling a .ml )
let print_signature ppf tree =
fprintf ppf "@[<v>%a@]" !Oprint.out_signature tree
let signature ppf sg =
fprintf ppf "%a" print_signature (tree_of_signature sg)
(* Print an unification error *)
let type_expansion t ppf t' =
if t == t' then type_expr ppf t else
let t' = if proxy t == proxy t' then unalias t' else t' in
fprintf ppf "@[<2>%a@ =@ %a@]" type_expr t type_expr t'
let rec trace fst txt ppf = function
| (t1, t1') :: (t2, t2') :: rem ->
if not fst then fprintf ppf "@,";
fprintf ppf "@[Type@;<1 2>%a@ %s@;<1 2>%a@] %a"
(type_expansion t1) t1' txt (type_expansion t2) t2'
(trace false txt) rem
| _ -> ()
let rec filter_trace = function
| (t1, t1') :: (t2, t2') :: rem ->
let rem' = filter_trace rem in
if t1 == t1' && t2 == t2'
then rem'
else (t1, t1') :: (t2, t2') :: rem'
| _ -> []
(* Hide variant name and var, to force printing the expanded type *)
let hide_variant_name t =
match repr t with
| {desc = Tvariant row} as t when (row_repr row).row_name <> None ->
newty2 t.level
(Tvariant {(row_repr row) with row_name = None;
row_more = newty2 (row_more row).level Tvar})
| _ -> t
let prepare_expansion (t, t') =
let t' = hide_variant_name t' in
mark_loops t; if t != t' then mark_loops t';
(t, t')
let may_prepare_expansion compact (t, t') =
match (repr t').desc with
Tvariant _ | Tobject _ when compact ->
mark_loops t; (t, t)
| _ -> prepare_expansion (t, t')
let print_tags ppf fields =
match fields with [] -> ()
| (t, _) :: fields ->
fprintf ppf "`%s" t;
List.iter (fun (t, _) -> fprintf ppf ",@ `%s" t) fields
let has_explanation unif t3 t4 =
match t3.desc, t4.desc with
Tfield _, _ | _, Tfield _
| Tunivar, Tvar | Tvar, Tunivar
| Tvariant _, Tvariant _ -> true
| Tconstr (p, _, _), Tvar | Tvar, Tconstr (p, _, _) ->
unif && min t3.level t4.level < Path.binding_time p
| _ -> false
let rec mismatch unif = function
(_, t) :: (_, t') :: rem ->
begin match mismatch unif rem with
Some _ as m -> m
| None ->
if has_explanation unif t t' then Some(t,t') else None
end
| [] -> None
| _ -> assert false
let explanation unif t3 t4 ppf =
match t3.desc, t4.desc with
| Tfield _, Tvar | Tvar, Tfield _ ->
fprintf ppf "@,Self type cannot escape its class"
| Tconstr (p, _, _), Tvar
when unif && t4.level < Path.binding_time p ->
fprintf ppf
"@,@[The type constructor@;<1 2>%a@ would escape its scope@]"
path p
| Tvar, Tconstr (p, _, _)
when unif && t3.level < Path.binding_time p ->
fprintf ppf
"@,@[The type constructor@;<1 2>%a@ would escape its scope@]"
path p
| Tvar, Tunivar | Tunivar, Tvar ->
fprintf ppf "@,The universal variable %a would escape its scope"
type_expr (if t3.desc = Tunivar then t3 else t4)
| Tfield (lab, _, _, _), _
| _, Tfield (lab, _, _, _) when lab = dummy_method ->
fprintf ppf
"@,Self type cannot be unified with a closed object type"
| Tfield (l, _, _, _), Tfield (l', _, _, _) when l = l' ->
fprintf ppf "@,Types for method %s are incompatible" l
| _, Tfield (l, _, _, _) ->
fprintf ppf
"@,@[The first object type has no method %s@]" l
| Tfield (l, _, _, _), _ ->
fprintf ppf
"@,@[The second object type has no method %s@]" l
| Tvariant row1, Tvariant row2 ->
let row1 = row_repr row1 and row2 = row_repr row2 in
begin match
row1.row_fields, row1.row_closed, row2.row_fields, row2.row_closed with
| [], true, [], true ->
fprintf ppf "@,These two variant types have no intersection"
| [], true, fields, _ ->
fprintf ppf
"@,@[The first variant type does not allow tag(s)@ @[<hov>%a@]@]"
print_tags fields
| fields, _, [], true ->
fprintf ppf
"@,@[The second variant type does not allow tag(s)@ @[<hov>%a@]@]"
print_tags fields
| [l1,_], true, [l2,_], true when l1 = l2 ->
fprintf ppf "@,Types for tag `%s are incompatible" l1
| _ -> ()
end
| _ -> ()
let explanation unif mis ppf =
match mis with
None -> ()
| Some (t3, t4) -> explanation unif t3 t4 ppf
let ident_same_name id1 id2 =
if Ident.equal id1 id2 && not (Ident.same id1 id2) then begin
add_unique id1; add_unique id2
end
let rec path_same_name p1 p2 =
match p1, p2 with
Pident id1, Pident id2 -> ident_same_name id1 id2
| Pdot (p1, s1, _), Pdot (p2, s2, _) when s1 = s2 -> path_same_name p1 p2
| Papply (p1, p1'), Papply (p2, p2') ->
path_same_name p1 p2; path_same_name p1' p2'
| _ -> ()
let type_same_name t1 t2 =
match (repr t1).desc, (repr t2).desc with
Tconstr (p1, _, _), Tconstr (p2, _, _) -> path_same_name p1 p2
| _ -> ()
let rec trace_same_names = function
(t1, t1') :: (t2, t2') :: rem ->
type_same_name t1 t2; type_same_name t1' t2'; trace_same_names rem
| _ -> ()
let unification_error unif tr txt1 ppf txt2 =
reset ();
trace_same_names tr;
let tr = List.map (fun (t, t') -> (t, hide_variant_name t')) tr in
let mis = mismatch unif tr in
match tr with
| [] | _ :: [] -> assert false
| t1 :: t2 :: tr ->
try
let tr = filter_trace tr in
let t1, t1' = may_prepare_expansion (tr = []) t1
and t2, t2' = may_prepare_expansion (tr = []) t2 in
print_labels := not !Clflags.classic;
let tr = List.map prepare_expansion tr in
fprintf ppf
"@[<v>\
@[%t@;<1 2>%a@ \
%t@;<1 2>%a\
@]%a%t\
@]"
txt1 (type_expansion t1) t1'
txt2 (type_expansion t2) t2'
(trace false "is not compatible with type") tr
(explanation unif mis);
print_labels := true
with exn ->
print_labels := true;
raise exn
let report_unification_error ppf tr txt1 txt2 =
unification_error true tr txt1 ppf txt2;;
let trace fst txt ppf tr =
print_labels := not !Clflags.classic;
trace_same_names tr;
try match tr with
t1 :: t2 :: tr' ->
if fst then trace fst txt ppf (t1 :: t2 :: filter_trace tr')
else trace fst txt ppf (filter_trace tr);
print_labels := true
| _ -> ()
with exn ->
print_labels := true;
raise exn
let report_subtyping_error ppf tr1 txt1 tr2 =
reset ();
let tr1 = List.map prepare_expansion tr1
and tr2 = List.map prepare_expansion tr2 in
trace true txt1 ppf tr1;
if tr2 = [] then () else
let mis = mismatch true tr2 in
trace false "is not compatible with type" ppf tr2;
explanation true mis ppf
| null | https://raw.githubusercontent.com/OCamlPro/OCamlPro-OCaml-Branch/3a522985649389f89dac73e655d562c54f0456a5/inline-more/typing/printtyp.ml | ocaml | *********************************************************************
Objective Caml
*********************************************************************
Printing functions
Print a long identifier
Print an identifier
Print a path
Print a recursive annotation
Print a raw type expression, with sharing
Print a type expression
Disabled in classic mode when printing an unification error
une erreur, en fait
Maxence
Special hack to hide variant name
Print an exception declaration
Print a value declaration
Print a class type
Self may have a name
Print a module type
Print an unification error
Hide variant name and var, to force printing the expanded type | and , 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 .
$ Id$
open Misc
open Ctype
open Format
open Longident
open Path
open Asttypes
open Types
open Btype
open Outcometree
let rec longident ppf = function
| Lident s -> fprintf ppf "%s" s
| Ldot(p, s) -> fprintf ppf "%a.%s" longident p s
| Lapply(p1, p2) -> fprintf ppf "%a(%a)" longident p1 longident p2
let unique_names = ref Ident.empty
let ident_name id =
try Ident.find_same id !unique_names with Not_found -> Ident.name id
let add_unique id =
try ignore (Ident.find_same id !unique_names)
with Not_found ->
unique_names := Ident.add id (Ident.unique_toplevel_name id) !unique_names
let ident ppf id = fprintf ppf "%s" (ident_name id)
let ident_pervasive = Ident.create_persistent "Pervasives"
let rec tree_of_path = function
| Pident id ->
Oide_ident (ident_name id)
| Pdot(Pident id, s, pos) when Ident.same id ident_pervasive ->
Oide_ident s
| Pdot(p, s, pos) ->
Oide_dot (tree_of_path p, s)
| Papply(p1, p2) ->
Oide_apply (tree_of_path p1, tree_of_path p2)
let rec path ppf = function
| Pident id ->
ident ppf id
| Pdot(Pident id, s, pos) when Ident.same id ident_pervasive ->
fprintf ppf "%s" s
| Pdot(p, s, pos) ->
fprintf ppf "%a.%s" path p s
| Papply(p1, p2) ->
fprintf ppf "%a(%a)" path p1 path p2
let tree_of_rec = function
| Trec_not -> Orec_not
| Trec_first -> Orec_first
| Trec_next -> Orec_next
let raw_list pr ppf = function
[] -> fprintf ppf "[]"
| a :: l ->
fprintf ppf "@[<1>[%a%t]@]" pr a
(fun ppf -> List.iter (fun x -> fprintf ppf ";@,%a" pr x) l)
let rec safe_kind_repr v = function
Fvar {contents=Some k} ->
if List.memq k v then "Fvar loop" else
safe_kind_repr (k::v) k
| Fvar _ -> "Fvar None"
| Fpresent -> "Fpresent"
| Fabsent -> "Fabsent"
let rec safe_commu_repr v = function
Cok -> "Cok"
| Cunknown -> "Cunknown"
| Clink r ->
if List.memq r v then "Clink loop" else
safe_commu_repr (r::v) !r
let rec safe_repr v = function
{desc = Tlink t} when not (List.memq t v) ->
safe_repr (t::v) t
| t -> t
let rec list_of_memo = function
Mnil -> []
| Mcons (priv, p, t1, t2, rem) -> p :: list_of_memo rem
| Mlink rem -> list_of_memo !rem
let visited = ref []
let rec raw_type ppf ty =
let ty = safe_repr [] ty in
if List.memq ty !visited then fprintf ppf "{id=%d}" ty.id else begin
visited := ty :: !visited;
fprintf ppf "@[<1>{id=%d;level=%d;desc=@,%a}@]" ty.id ty.level
raw_type_desc ty.desc
end
and raw_type_list tl = raw_list raw_type tl
and raw_type_desc ppf = function
Tvar -> fprintf ppf "Tvar"
| Tarrow(l,t1,t2,c) ->
fprintf ppf "@[<hov1>Tarrow(%s,@,%a,@,%a,@,%s)@]"
l raw_type t1 raw_type t2
(safe_commu_repr [] c)
| Ttuple tl ->
fprintf ppf "@[<1>Ttuple@,%a@]" raw_type_list tl
| Tconstr (p, tl, abbrev) ->
fprintf ppf "@[<hov1>Tconstr(@,%a,@,%a,@,%a)@]" path p
raw_type_list tl
(raw_list path) (list_of_memo !abbrev)
| Tobject (t, nm) ->
fprintf ppf "@[<hov1>Tobject(@,%a,@,@[<1>ref%t@])@]" raw_type t
(fun ppf ->
match !nm with None -> fprintf ppf " None"
| Some(p,tl) ->
fprintf ppf "(Some(@,%a,@,%a))" path p raw_type_list tl)
| Tfield (f, k, t1, t2) ->
fprintf ppf "@[<hov1>Tfield(@,%s,@,%s,@,%a,@;<0 -1>%a)@]" f
(safe_kind_repr [] k)
raw_type t1 raw_type t2
| Tnil -> fprintf ppf "Tnil"
| Tlink t -> fprintf ppf "@[<1>Tlink@,%a@]" raw_type t
| Tsubst t -> fprintf ppf "@[<1>Tsubst@,%a@]" raw_type t
| Tunivar -> fprintf ppf "Tunivar"
| Tpoly (t, tl) ->
fprintf ppf "@[<hov1>Tpoly(@,%a,@,%a)@]"
raw_type t
raw_type_list tl
| Tvariant row ->
fprintf ppf
"@[<hov1>{@[%s@,%a;@]@ @[%s@,%a;@]@ %s%b;@ %s%b;@ @[<1>%s%t@]}@]"
"row_fields="
(raw_list (fun ppf (l, f) ->
fprintf ppf "@[%s,@ %a@]" l raw_field f))
row.row_fields
"row_more=" raw_type row.row_more
"row_closed=" row.row_closed
"row_fixed=" row.row_fixed
"row_name="
(fun ppf ->
match row.row_name with None -> fprintf ppf "None"
| Some(p,tl) ->
fprintf ppf "Some(@,%a,@,%a)" path p raw_type_list tl)
| Tpackage (p, _, tl) ->
fprintf ppf "@[<hov1>Tpackage(@,%a@,%a)@]" path p
raw_type_list tl
and raw_field ppf = function
Rpresent None -> fprintf ppf "Rpresent None"
| Rpresent (Some t) -> fprintf ppf "@[<1>Rpresent(Some@,%a)@]" raw_type t
| Reither (c,tl,m,e) ->
fprintf ppf "@[<hov1>Reither(%b,@,%a,@,%b,@,@[<1>ref%t@])@]" c
raw_type_list tl m
(fun ppf ->
match !e with None -> fprintf ppf " None"
| Some f -> fprintf ppf "@,@[<1>(%a)@]" raw_field f)
| Rabsent -> fprintf ppf "Rabsent"
let raw_type_expr ppf t =
visited := [];
raw_type ppf t;
visited := []
let names = ref ([] : (type_expr * string) list)
let name_counter = ref 0
let reset_names () = names := []; name_counter := 0
let new_name () =
let name =
if !name_counter < 26
then String.make 1 (Char.chr(97 + !name_counter))
else String.make 1 (Char.chr(97 + !name_counter mod 26)) ^
string_of_int(!name_counter / 26) in
incr name_counter;
name
let name_of_type t =
try List.assq t !names with Not_found ->
let name = new_name () in
names := (t, name) :: !names;
name
let check_name_of_type t = ignore(name_of_type t)
let non_gen_mark sch ty =
if sch && ty.desc = Tvar && ty.level <> generic_level then "_" else ""
let print_name_of_type sch ppf t =
fprintf ppf "'%s%s" (non_gen_mark sch t) (name_of_type t)
let visited_objects = ref ([] : type_expr list)
let aliased = ref ([] : type_expr list)
let delayed = ref ([] : type_expr list)
let add_delayed t =
if not (List.memq t !delayed) then delayed := t :: !delayed
let is_aliased ty = List.memq (proxy ty) !aliased
let add_alias ty =
let px = proxy ty in
if not (is_aliased px) then aliased := px :: !aliased
let aliasable ty =
match ty.desc with Tvar | Tunivar | Tpoly _ -> false | _ -> true
let namable_row row =
row.row_name <> None &&
List.for_all
(fun (_, f) ->
match row_field_repr f with
| Reither(c, l, _, _) ->
row.row_closed && if c then l = [] else List.length l = 1
| _ -> true)
row.row_fields
let rec mark_loops_rec visited ty =
let ty = repr ty in
let px = proxy ty in
if List.memq px visited && aliasable ty then add_alias px else
let visited = px :: visited in
match ty.desc with
| Tvar -> ()
| Tarrow(_, ty1, ty2, _) ->
mark_loops_rec visited ty1; mark_loops_rec visited ty2
| Ttuple tyl -> List.iter (mark_loops_rec visited) tyl
| Tconstr(_, tyl, _) | Tpackage (_, _, tyl) ->
List.iter (mark_loops_rec visited) tyl
| Tvariant row ->
if List.memq px !visited_objects then add_alias px else
begin
let row = row_repr row in
if not (static_row row) then
visited_objects := px :: !visited_objects;
match row.row_name with
| Some(p, tyl) when namable_row row ->
List.iter (mark_loops_rec visited) tyl
| _ ->
iter_row (mark_loops_rec visited) row
end
| Tobject (fi, nm) ->
if List.memq px !visited_objects then add_alias px else
begin
if opened_object ty then
visited_objects := px :: !visited_objects;
begin match !nm with
| None ->
let fields, _ = flatten_fields fi in
List.iter
(fun (_, kind, ty) ->
if field_kind_repr kind = Fpresent then
mark_loops_rec visited ty)
fields
| Some (_, l) ->
List.iter (mark_loops_rec visited) (List.tl l)
end
end
| Tfield(_, kind, ty1, ty2) when field_kind_repr kind = Fpresent ->
mark_loops_rec visited ty1; mark_loops_rec visited ty2
| Tfield(_, _, _, ty2) ->
mark_loops_rec visited ty2
| Tnil -> ()
| Tsubst ty -> mark_loops_rec visited ty
| Tlink _ -> fatal_error "Printtyp.mark_loops_rec (2)"
| Tpoly (ty, tyl) ->
List.iter (fun t -> add_alias t) tyl;
mark_loops_rec visited ty
| Tunivar -> ()
let mark_loops ty =
normalize_type Env.empty ty;
mark_loops_rec [] ty;;
let reset_loop_marks () =
visited_objects := []; aliased := []; delayed := []
let reset () =
unique_names := Ident.empty; reset_names (); reset_loop_marks ()
let reset_and_mark_loops ty =
reset (); mark_loops ty
let reset_and_mark_loops_list tyl =
reset (); List.iter mark_loops tyl
let print_labels = ref true
let print_label ppf l =
if !print_labels && l <> "" || is_optional l then fprintf ppf "%s:" l
let rec tree_of_typexp sch ty =
let ty = repr ty in
let px = proxy ty in
if List.mem_assq px !names && not (List.memq px !delayed) then
let mark = is_non_gen sch ty in
Otyp_var (mark, name_of_type px) else
let pr_typ () =
match ty.desc with
| Tvar ->
Otyp_var (is_non_gen sch ty, name_of_type ty)
| Tarrow(l, ty1, ty2, _) ->
let pr_arrow l ty1 ty2 =
let lab =
if !print_labels && l <> "" || is_optional l then l else ""
in
let t1 =
if is_optional l then
match (repr ty1).desc with
| Tconstr(path, [ty], _)
when Path.same path Predef.path_option ->
tree_of_typexp sch ty
| _ -> Otyp_stuff "<hidden>"
else tree_of_typexp sch ty1 in
Otyp_arrow (lab, t1, tree_of_typexp sch ty2) in
pr_arrow l ty1 ty2
| Ttuple tyl ->
Otyp_tuple (tree_of_typlist sch tyl)
| Tconstr(p, tyl, abbrev) ->
Otyp_constr (tree_of_path p, tree_of_typlist sch tyl)
| Tvariant row ->
let row = row_repr row in
let fields =
if row.row_closed then
List.filter (fun (_, f) -> row_field_repr f <> Rabsent)
row.row_fields
else row.row_fields in
let present =
List.filter
(fun (_, f) ->
match row_field_repr f with
| Rpresent _ -> true
| _ -> false)
fields in
let all_present = List.length present = List.length fields in
begin match row.row_name with
| Some(p, tyl) when namable_row row ->
let id = tree_of_path p in
let args = tree_of_typlist sch tyl in
if row.row_closed && all_present then
Otyp_constr (id, args)
else
let non_gen = is_non_gen sch px in
let tags =
if all_present then None else Some (List.map fst present) in
Otyp_variant (non_gen, Ovar_name(tree_of_path p, args),
row.row_closed, tags)
| _ ->
let non_gen =
not (row.row_closed && all_present) && is_non_gen sch px in
let fields = List.map (tree_of_row_field sch) fields in
let tags =
if all_present then None else Some (List.map fst present) in
Otyp_variant (non_gen, Ovar_fields fields, row.row_closed, tags)
end
| Tobject (fi, nm) ->
tree_of_typobject sch fi nm
| Tsubst ty ->
tree_of_typexp sch ty
| Tlink _ | Tnil | Tfield _ ->
fatal_error "Printtyp.tree_of_typexp"
| Tpoly (ty, []) ->
tree_of_typexp sch ty
| Tpoly (ty, tyl) ->
let tyl = List.map repr tyl in
let tyl = List.filter is_aliased tyl in
if tyl = [] then tree_of_typexp sch ty else begin
let old_delayed = !delayed in
List.iter add_delayed tyl;
let tl = List.map name_of_type tyl in
let tr = Otyp_poly (tl, tree_of_typexp sch ty) in
delayed := old_delayed; tr
end
| Tunivar ->
Otyp_var (false, name_of_type ty)
| Tpackage (p, n, tyl) ->
Otyp_module (Path.name p, n, tree_of_typlist sch tyl)
in
if List.memq px !delayed then delayed := List.filter ((!=) px) !delayed;
if is_aliased px && aliasable ty then begin
check_name_of_type px;
Otyp_alias (pr_typ (), name_of_type px) end
else pr_typ ()
and tree_of_row_field sch (l, f) =
match row_field_repr f with
| Rpresent None | Reither(true, [], _, _) -> (l, false, [])
| Rpresent(Some ty) -> (l, false, [tree_of_typexp sch ty])
| Reither(c, tyl, _, _) ->
contradiction : un constructeur constant qui a un argument
then (l, true, tree_of_typlist sch tyl)
else (l, false, tree_of_typlist sch tyl)
and tree_of_typlist sch tyl =
List.map (tree_of_typexp sch) tyl
and tree_of_typobject sch fi nm =
begin match !nm with
| None ->
let pr_fields fi =
let (fields, rest) = flatten_fields fi in
let present_fields =
List.fold_right
(fun (n, k, t) l ->
match field_kind_repr k with
| Fpresent -> (n, t) :: l
| _ -> l)
fields [] in
let sorted_fields =
Sort.list (fun (n, _) (n', _) -> n <= n') present_fields in
tree_of_typfields sch rest sorted_fields in
let (fields, rest) = pr_fields fi in
Otyp_object (fields, rest)
| Some (p, ty :: tyl) ->
let non_gen = is_non_gen sch (repr ty) in
let args = tree_of_typlist sch tyl in
Otyp_class (non_gen, tree_of_path p, args)
| _ ->
fatal_error "Printtyp.tree_of_typobject"
end
and is_non_gen sch ty =
sch && ty.desc = Tvar && ty.level <> generic_level
and tree_of_typfields sch rest = function
| [] ->
let rest =
match rest.desc with
| Tvar | Tunivar -> Some (is_non_gen sch rest)
| Tconstr _ -> Some false
| Tnil -> None
| _ -> fatal_error "typfields (1)"
in
([], rest)
| (s, t) :: l ->
let field = (s, tree_of_typexp sch t) in
let (fields, rest) = tree_of_typfields sch rest l in
(field :: fields, rest)
let typexp sch prio ppf ty =
!Oprint.out_type ppf (tree_of_typexp sch ty)
let type_expr ppf ty = typexp false 0 ppf ty
and type_sch ppf ty = typexp true 0 ppf ty
and type_scheme ppf ty = reset_and_mark_loops ty; typexp true 0 ppf ty
let type_scheme_max ?(b_reset_names=true) ppf ty =
if b_reset_names then reset_names () ;
typexp true 0 ppf ty
let tree_of_type_scheme ty = reset_and_mark_loops ty; tree_of_typexp true ty
Print one type declaration
let tree_of_constraints params =
List.fold_right
(fun ty list ->
let ty' = unalias ty in
if proxy ty != proxy ty' then
let tr = tree_of_typexp true ty in
(tr, tree_of_typexp true ty') :: list
else list)
params []
let filter_params tyl =
let params =
List.fold_left
(fun tyl ty ->
let ty = repr ty in
if List.memq ty tyl then Btype.newgenty (Tsubst ty) :: tyl
else ty :: tyl)
[] tyl
in List.rev params
let string_of_mutable = function
| Immutable -> ""
| Mutable -> "mutable "
let rec tree_of_type_decl id decl =
reset();
let params = filter_params decl.type_params in
List.iter add_alias params;
List.iter mark_loops params;
List.iter check_name_of_type (List.map proxy params);
let ty_manifest =
match decl.type_manifest with
| None -> None
| Some ty ->
let ty =
match repr ty with {desc=Tvariant row} ->
let row = row_repr row in
begin match row.row_name with
Some (Pident id', _) when Ident.same id id' ->
newgenty (Tvariant {row with row_name = None})
| _ -> ty
end
| _ -> ty
in
mark_loops ty;
Some ty
in
begin match decl.type_kind with
| Type_abstract -> ()
| Type_variant [] -> ()
| Type_variant cstrs ->
List.iter (fun (_, args) -> List.iter mark_loops args) cstrs
| Type_record(l, rep) ->
List.iter (fun (_, _, ty) -> mark_loops ty) l
end;
let type_param =
function
| Otyp_var (_, id) -> id
| _ -> "?"
in
let type_defined decl =
let abstr =
match decl.type_kind with
Type_abstract ->
decl.type_manifest = None || decl.type_private = Private
| Type_variant _ | Type_record _ ->
decl.type_private = Private
in
let vari =
List.map2
(fun ty (co,cn,ct) ->
if abstr || (repr ty).desc <> Tvar then (co,cn) else (true,true))
decl.type_params decl.type_variance
in
(Ident.name id,
List.map2 (fun ty cocn -> type_param (tree_of_typexp false ty), cocn)
params vari)
in
let tree_of_manifest ty1 =
match ty_manifest with
| None -> ty1
| Some ty -> Otyp_manifest (tree_of_typexp false ty, ty1)
in
let (name, args) = type_defined decl in
let constraints = tree_of_constraints params in
let ty, priv =
match decl.type_kind with
| Type_abstract ->
begin match ty_manifest with
| None -> (Otyp_abstract, Public)
| Some ty ->
tree_of_typexp false ty, decl.type_private
end
| Type_variant cstrs ->
tree_of_manifest (Otyp_sum (List.map tree_of_constructor cstrs)),
decl.type_private
| Type_record(lbls, rep) ->
tree_of_manifest (Otyp_record (List.map tree_of_label lbls)),
decl.type_private
in
(name, args, ty, priv, constraints)
and tree_of_constructor (name, args) =
(name, tree_of_typlist false args)
and tree_of_label (name, mut, arg) =
(name, mut = Mutable, tree_of_typexp false arg)
let tree_of_type_declaration id decl rs =
Osig_type (tree_of_type_decl id decl, tree_of_rec rs)
let type_declaration id ppf decl =
!Oprint.out_sig_item ppf (tree_of_type_declaration id decl Trec_first)
let tree_of_exception_declaration id decl =
reset_and_mark_loops_list decl;
let tyl = tree_of_typlist false decl in
Osig_exception (Ident.name id, tyl)
let exception_declaration id ppf decl =
!Oprint.out_sig_item ppf (tree_of_exception_declaration id decl)
let tree_of_value_description id decl =
let id = Ident.name id in
let ty = tree_of_type_scheme decl.val_type in
let prims =
match decl.val_kind with
| Val_prim p -> Primitive.description_list p
| _ -> []
in
Osig_value (id, ty, prims)
let value_description id ppf decl =
!Oprint.out_sig_item ppf (tree_of_value_description id decl)
let class_var sch ppf l (m, t) =
fprintf ppf
"@ @[<2>val %s%s :@ %a@]" (string_of_mutable m) l (typexp sch 0) t
let method_type (_, kind, ty) =
match field_kind_repr kind, repr ty with
Fpresent, {desc=Tpoly(ty, _)} -> ty
| _ , ty -> ty
let tree_of_metho sch concrete csil (lab, kind, ty) =
if lab <> dummy_method then begin
let kind = field_kind_repr kind in
let priv = kind <> Fpresent in
let virt = not (Concr.mem lab concrete) in
let ty = method_type (lab, kind, ty) in
Ocsg_method (lab, priv, virt, tree_of_typexp sch ty) :: csil
end
else csil
let rec prepare_class_type params = function
| Tcty_constr (p, tyl, cty) ->
let sty = Ctype.self_type cty in
if List.memq (proxy sty) !visited_objects
|| List.exists (fun ty -> (repr ty).desc <> Tvar) params
|| List.exists (deep_occur sty) tyl
then prepare_class_type params cty
else List.iter mark_loops tyl
| Tcty_signature sign ->
let sty = repr sign.cty_self in
let px = proxy sty in
if List.memq px !visited_objects then add_alias sty
else visited_objects := px :: !visited_objects;
let (fields, _) =
Ctype.flatten_fields (Ctype.object_fields sign.cty_self)
in
List.iter (fun met -> mark_loops (method_type met)) fields;
Vars.iter (fun _ (_, _, ty) -> mark_loops ty) sign.cty_vars
| Tcty_fun (_, ty, cty) ->
mark_loops ty;
prepare_class_type params cty
let rec tree_of_class_type sch params =
function
| Tcty_constr (p', tyl, cty) ->
let sty = Ctype.self_type cty in
if List.memq (proxy sty) !visited_objects
|| List.exists (fun ty -> (repr ty).desc <> Tvar) params
then
tree_of_class_type sch params cty
else
Octy_constr (tree_of_path p', tree_of_typlist true tyl)
| Tcty_signature sign ->
let sty = repr sign.cty_self in
let self_ty =
if is_aliased sty then
Some (Otyp_var (false, name_of_type (proxy sty)))
else None
in
let (fields, _) =
Ctype.flatten_fields (Ctype.object_fields sign.cty_self)
in
let csil = [] in
let csil =
List.fold_left
(fun csil (ty1, ty2) -> Ocsg_constraint (ty1, ty2) :: csil)
csil (tree_of_constraints params)
in
let all_vars =
Vars.fold (fun l (m, v, t) all -> (l, m, v, t) :: all) sign.cty_vars []
in
Consequence of PR#3607 : order of Map.fold has changed !
let all_vars = List.rev all_vars in
let csil =
List.fold_left
(fun csil (l, m, v, t) ->
Ocsg_value (l, m = Mutable, v = Virtual, tree_of_typexp sch t)
:: csil)
csil all_vars
in
let csil =
List.fold_left (tree_of_metho sch sign.cty_concr) csil fields
in
Octy_signature (self_ty, List.rev csil)
| Tcty_fun (l, ty, cty) ->
let lab = if !print_labels && l <> "" || is_optional l then l else "" in
let ty =
if is_optional l then
match (repr ty).desc with
| Tconstr(path, [ty], _) when Path.same path Predef.path_option -> ty
| _ -> newconstr (Path.Pident(Ident.create "<hidden>")) []
else ty in
let tr = tree_of_typexp sch ty in
Octy_fun (lab, tr, tree_of_class_type sch params cty)
let class_type ppf cty =
reset ();
prepare_class_type [] cty;
!Oprint.out_class_type ppf (tree_of_class_type false [] cty)
let tree_of_class_param param variance =
(match tree_of_typexp true param with
Otyp_var (_, s) -> s
| _ -> "?"),
if (repr param).desc = Tvar then (true, true) else variance
let tree_of_class_params params =
let tyl = tree_of_typlist true params in
List.map (function Otyp_var (_, s) -> s | _ -> "?") tyl
let tree_of_class_declaration id cl rs =
let params = filter_params cl.cty_params in
reset ();
List.iter add_alias params;
prepare_class_type params cl.cty_type;
let sty = self_type cl.cty_type in
List.iter mark_loops params;
List.iter check_name_of_type (List.map proxy params);
if is_aliased sty then check_name_of_type (proxy sty);
let vir_flag = cl.cty_new = None in
Osig_class
(vir_flag, Ident.name id,
List.map2 tree_of_class_param params cl.cty_variance,
tree_of_class_type true params cl.cty_type,
tree_of_rec rs)
let class_declaration id ppf cl =
!Oprint.out_sig_item ppf (tree_of_class_declaration id cl Trec_first)
let tree_of_cltype_declaration id cl rs =
let params = List.map repr cl.clty_params in
reset ();
List.iter add_alias params;
prepare_class_type params cl.clty_type;
let sty = self_type cl.clty_type in
List.iter mark_loops params;
List.iter check_name_of_type (List.map proxy params);
if is_aliased sty then check_name_of_type (proxy sty);
let sign = Ctype.signature_of_class_type cl.clty_type in
let virt =
let (fields, _) =
Ctype.flatten_fields (Ctype.object_fields sign.cty_self) in
List.exists
(fun (lab, _, ty) ->
not (lab = dummy_method || Concr.mem lab sign.cty_concr))
fields
|| Vars.fold (fun _ (_,vr,_) b -> vr = Virtual || b) sign.cty_vars false
in
Osig_class_type
(virt, Ident.name id,
List.map2 tree_of_class_param params cl.clty_variance,
tree_of_class_type true params cl.clty_type,
tree_of_rec rs)
let cltype_declaration id ppf cl =
!Oprint.out_sig_item ppf (tree_of_cltype_declaration id cl Trec_first)
let rec tree_of_modtype = function
| Tmty_ident p ->
Omty_ident (tree_of_path p)
| Tmty_signature sg ->
Omty_signature (tree_of_signature sg)
| Tmty_functor(param, ty_arg, ty_res) ->
Omty_functor
(Ident.name param, tree_of_modtype ty_arg, tree_of_modtype ty_res)
and tree_of_signature = function
| [] -> []
| Tsig_value(id, decl) :: rem ->
tree_of_value_description id decl :: tree_of_signature rem
| Tsig_type(id, _, _) :: rem when is_row_name (Ident.name id) ->
tree_of_signature rem
| Tsig_type(id, decl, rs) :: rem ->
Osig_type(tree_of_type_decl id decl, tree_of_rec rs) ::
tree_of_signature rem
| Tsig_exception(id, decl) :: rem ->
tree_of_exception_declaration id decl :: tree_of_signature rem
| Tsig_module(id, mty, rs) :: rem ->
Osig_module (Ident.name id, tree_of_modtype mty, tree_of_rec rs) ::
tree_of_signature rem
| Tsig_modtype(id, decl) :: rem ->
tree_of_modtype_declaration id decl :: tree_of_signature rem
| Tsig_class(id, decl, rs) :: ctydecl :: tydecl1 :: tydecl2 :: rem ->
tree_of_class_declaration id decl rs :: tree_of_signature rem
| Tsig_cltype(id, decl, rs) :: tydecl1 :: tydecl2 :: rem ->
tree_of_cltype_declaration id decl rs :: tree_of_signature rem
| _ ->
assert false
and tree_of_modtype_declaration id decl =
let mty =
match decl with
| Tmodtype_abstract -> Omty_abstract
| Tmodtype_manifest mty -> tree_of_modtype mty
in
Osig_modtype (Ident.name id, mty)
let tree_of_module id mty rs =
Osig_module (Ident.name id, tree_of_modtype mty, tree_of_rec rs)
let modtype ppf mty = !Oprint.out_module_type ppf (tree_of_modtype mty)
let modtype_declaration id ppf decl =
!Oprint.out_sig_item ppf (tree_of_modtype_declaration id decl)
Print a signature body ( used by -i when compiling a .ml )
let print_signature ppf tree =
fprintf ppf "@[<v>%a@]" !Oprint.out_signature tree
let signature ppf sg =
fprintf ppf "%a" print_signature (tree_of_signature sg)
let type_expansion t ppf t' =
if t == t' then type_expr ppf t else
let t' = if proxy t == proxy t' then unalias t' else t' in
fprintf ppf "@[<2>%a@ =@ %a@]" type_expr t type_expr t'
let rec trace fst txt ppf = function
| (t1, t1') :: (t2, t2') :: rem ->
if not fst then fprintf ppf "@,";
fprintf ppf "@[Type@;<1 2>%a@ %s@;<1 2>%a@] %a"
(type_expansion t1) t1' txt (type_expansion t2) t2'
(trace false txt) rem
| _ -> ()
let rec filter_trace = function
| (t1, t1') :: (t2, t2') :: rem ->
let rem' = filter_trace rem in
if t1 == t1' && t2 == t2'
then rem'
else (t1, t1') :: (t2, t2') :: rem'
| _ -> []
let hide_variant_name t =
match repr t with
| {desc = Tvariant row} as t when (row_repr row).row_name <> None ->
newty2 t.level
(Tvariant {(row_repr row) with row_name = None;
row_more = newty2 (row_more row).level Tvar})
| _ -> t
let prepare_expansion (t, t') =
let t' = hide_variant_name t' in
mark_loops t; if t != t' then mark_loops t';
(t, t')
let may_prepare_expansion compact (t, t') =
match (repr t').desc with
Tvariant _ | Tobject _ when compact ->
mark_loops t; (t, t)
| _ -> prepare_expansion (t, t')
let print_tags ppf fields =
match fields with [] -> ()
| (t, _) :: fields ->
fprintf ppf "`%s" t;
List.iter (fun (t, _) -> fprintf ppf ",@ `%s" t) fields
let has_explanation unif t3 t4 =
match t3.desc, t4.desc with
Tfield _, _ | _, Tfield _
| Tunivar, Tvar | Tvar, Tunivar
| Tvariant _, Tvariant _ -> true
| Tconstr (p, _, _), Tvar | Tvar, Tconstr (p, _, _) ->
unif && min t3.level t4.level < Path.binding_time p
| _ -> false
let rec mismatch unif = function
(_, t) :: (_, t') :: rem ->
begin match mismatch unif rem with
Some _ as m -> m
| None ->
if has_explanation unif t t' then Some(t,t') else None
end
| [] -> None
| _ -> assert false
let explanation unif t3 t4 ppf =
match t3.desc, t4.desc with
| Tfield _, Tvar | Tvar, Tfield _ ->
fprintf ppf "@,Self type cannot escape its class"
| Tconstr (p, _, _), Tvar
when unif && t4.level < Path.binding_time p ->
fprintf ppf
"@,@[The type constructor@;<1 2>%a@ would escape its scope@]"
path p
| Tvar, Tconstr (p, _, _)
when unif && t3.level < Path.binding_time p ->
fprintf ppf
"@,@[The type constructor@;<1 2>%a@ would escape its scope@]"
path p
| Tvar, Tunivar | Tunivar, Tvar ->
fprintf ppf "@,The universal variable %a would escape its scope"
type_expr (if t3.desc = Tunivar then t3 else t4)
| Tfield (lab, _, _, _), _
| _, Tfield (lab, _, _, _) when lab = dummy_method ->
fprintf ppf
"@,Self type cannot be unified with a closed object type"
| Tfield (l, _, _, _), Tfield (l', _, _, _) when l = l' ->
fprintf ppf "@,Types for method %s are incompatible" l
| _, Tfield (l, _, _, _) ->
fprintf ppf
"@,@[The first object type has no method %s@]" l
| Tfield (l, _, _, _), _ ->
fprintf ppf
"@,@[The second object type has no method %s@]" l
| Tvariant row1, Tvariant row2 ->
let row1 = row_repr row1 and row2 = row_repr row2 in
begin match
row1.row_fields, row1.row_closed, row2.row_fields, row2.row_closed with
| [], true, [], true ->
fprintf ppf "@,These two variant types have no intersection"
| [], true, fields, _ ->
fprintf ppf
"@,@[The first variant type does not allow tag(s)@ @[<hov>%a@]@]"
print_tags fields
| fields, _, [], true ->
fprintf ppf
"@,@[The second variant type does not allow tag(s)@ @[<hov>%a@]@]"
print_tags fields
| [l1,_], true, [l2,_], true when l1 = l2 ->
fprintf ppf "@,Types for tag `%s are incompatible" l1
| _ -> ()
end
| _ -> ()
let explanation unif mis ppf =
match mis with
None -> ()
| Some (t3, t4) -> explanation unif t3 t4 ppf
let ident_same_name id1 id2 =
if Ident.equal id1 id2 && not (Ident.same id1 id2) then begin
add_unique id1; add_unique id2
end
let rec path_same_name p1 p2 =
match p1, p2 with
Pident id1, Pident id2 -> ident_same_name id1 id2
| Pdot (p1, s1, _), Pdot (p2, s2, _) when s1 = s2 -> path_same_name p1 p2
| Papply (p1, p1'), Papply (p2, p2') ->
path_same_name p1 p2; path_same_name p1' p2'
| _ -> ()
let type_same_name t1 t2 =
match (repr t1).desc, (repr t2).desc with
Tconstr (p1, _, _), Tconstr (p2, _, _) -> path_same_name p1 p2
| _ -> ()
let rec trace_same_names = function
(t1, t1') :: (t2, t2') :: rem ->
type_same_name t1 t2; type_same_name t1' t2'; trace_same_names rem
| _ -> ()
let unification_error unif tr txt1 ppf txt2 =
reset ();
trace_same_names tr;
let tr = List.map (fun (t, t') -> (t, hide_variant_name t')) tr in
let mis = mismatch unif tr in
match tr with
| [] | _ :: [] -> assert false
| t1 :: t2 :: tr ->
try
let tr = filter_trace tr in
let t1, t1' = may_prepare_expansion (tr = []) t1
and t2, t2' = may_prepare_expansion (tr = []) t2 in
print_labels := not !Clflags.classic;
let tr = List.map prepare_expansion tr in
fprintf ppf
"@[<v>\
@[%t@;<1 2>%a@ \
%t@;<1 2>%a\
@]%a%t\
@]"
txt1 (type_expansion t1) t1'
txt2 (type_expansion t2) t2'
(trace false "is not compatible with type") tr
(explanation unif mis);
print_labels := true
with exn ->
print_labels := true;
raise exn
let report_unification_error ppf tr txt1 txt2 =
unification_error true tr txt1 ppf txt2;;
let trace fst txt ppf tr =
print_labels := not !Clflags.classic;
trace_same_names tr;
try match tr with
t1 :: t2 :: tr' ->
if fst then trace fst txt ppf (t1 :: t2 :: filter_trace tr')
else trace fst txt ppf (filter_trace tr);
print_labels := true
| _ -> ()
with exn ->
print_labels := true;
raise exn
let report_subtyping_error ppf tr1 txt1 tr2 =
reset ();
let tr1 = List.map prepare_expansion tr1
and tr2 = List.map prepare_expansion tr2 in
trace true txt1 ppf tr1;
if tr2 = [] then () else
let mis = mismatch true tr2 in
trace false "is not compatible with type" ppf tr2;
explanation true mis ppf
|
ecd734bd15ff81bd76f1ef0ec5241b1aa0c79b08fee3298ec05b64cc77771bd9 | igorhvr/bedlam | bindings.scm | The contents of this file are subject to the Mozilla Public License Version
1.1 ( the " License " ) ; you may not use this file except in compliance with
;;; the License. You may obtain a copy of the License at
;;; /
;;;
Software distributed under the License is distributed on an " AS IS " basis ,
;;; WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
;;; for the specific language governing rights and limitations under the
;;; License.
;;;
The Original Code is SISCweb .
;;;
The Initial Developer of the Original Code is .
Portions created by the Initial Developer are Copyright ( C ) 2005 - 2007
. All Rights Reserved .
;;;
;;; Contributor(s):
;;;
;;; Alternatively, the contents of this file may be used under the terms of
either the GNU General Public License Version 2 or later ( the " GPL " ) , or
the GNU Lesser General Public License Version 2.1 or later ( the " LGPL " ) ,
;;; in which case the provisions of the GPL or the LGPL are applicable instead
;;; of those above. If you wish to allow use of your version of this file only
;;; under the terms of either the GPL or the LGPL, and not to allow others to
use your version of this file under the terms of the MPL , indicate your
;;; decision by deleting the provisions above and replace them with the notice
;;; and other provisions required by the GPL or the LGPL. If you do not delete
;;; the provisions above, a recipient may use your version of this file under
the terms of any one of the MPL , the GPL or the LGPL .
(require-library 'sisc/libs/srfi/srfi-78) ; lightweight testing
(require-library 'siscweb/bindings)
(module test/bindings
(test-bindings)
(import srfi-78)
(import siscweb/bindings)
(define binding-alist `((a 1) (b "2") ("c" 3) ("d" "4")
(e . 5) (f . "6") ("g" . 7) ("h" . "8")
(i 1 2) (j "2" "3") ("k" 3 4) (l . ("6" "7")) ("m" . (7 8))
(x) (y . #f)))
(define (test-bindings)
(let ((bindings (alist->bindings binding-alist)))
(check-reset!)
1 . checks extract - bindings
(check-ec (:list x binding-alist)
(:let key (if (symbol? (car x))
(car x)
(string->symbol (car x))))
(:let expected-value (if (not (cdr x))
'()
(cdr x)))
(:let actual-value (extract-bindings key bindings))
actual-value => expected-value)
2 . checks extract - single - binding
(check-ec (:list x binding-alist)
(:let key (if (symbol? (car x))
(car x)
(string->symbol (car x))))
(:let expected-value (cond ((null? (cdr x)) #f)
((pair? (cdr x)) (cadr x))
(else (cdr x))))
(:let actual-value (extract-single-binding key bindings))
actual-value => expected-value)
checks exists - binding ? ( 1/2 )
(check-ec (:list x binding-alist)
(:let key (car x))
(:let flip-key (if (symbol? (car x))
(symbol->string (car x))
(string->symbol (car x))))
(and (exists-binding? key bindings)
(exists-binding? flip-key bindings))
=> #t)
check exists - binding ( 1/2 )
(check (exists-binding? 'xxx bindings) => #f)
;; final report
(check-report)))
)
| null | https://raw.githubusercontent.com/igorhvr/bedlam/b62e0d047105bb0473bdb47c58b23f6ca0f79a4e/siscweb/siscweb-src-0.5/test/bindings.scm | scheme | you may not use this file except in compliance with
the License. You may obtain a copy of the License at
/
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the
License.
Contributor(s):
Alternatively, the contents of this file may be used under the terms of
in which case the provisions of the GPL or the LGPL are applicable instead
of those above. If you wish to allow use of your version of this file only
under the terms of either the GPL or the LGPL, and not to allow others to
decision by deleting the provisions above and replace them with the notice
and other provisions required by the GPL or the LGPL. If you do not delete
the provisions above, a recipient may use your version of this file under
lightweight testing
final report | The contents of this file are subject to the Mozilla Public License Version
Software distributed under the License is distributed on an " AS IS " basis ,
The Original Code is SISCweb .
The Initial Developer of the Original Code is .
Portions created by the Initial Developer are Copyright ( C ) 2005 - 2007
. All Rights Reserved .
either the GNU General Public License Version 2 or later ( the " GPL " ) , or
the GNU Lesser General Public License Version 2.1 or later ( the " LGPL " ) ,
use your version of this file under the terms of the MPL , indicate your
the terms of any one of the MPL , the GPL or the LGPL .
(require-library 'siscweb/bindings)
(module test/bindings
(test-bindings)
(import srfi-78)
(import siscweb/bindings)
(define binding-alist `((a 1) (b "2") ("c" 3) ("d" "4")
(e . 5) (f . "6") ("g" . 7) ("h" . "8")
(i 1 2) (j "2" "3") ("k" 3 4) (l . ("6" "7")) ("m" . (7 8))
(x) (y . #f)))
(define (test-bindings)
(let ((bindings (alist->bindings binding-alist)))
(check-reset!)
1 . checks extract - bindings
(check-ec (:list x binding-alist)
(:let key (if (symbol? (car x))
(car x)
(string->symbol (car x))))
(:let expected-value (if (not (cdr x))
'()
(cdr x)))
(:let actual-value (extract-bindings key bindings))
actual-value => expected-value)
2 . checks extract - single - binding
(check-ec (:list x binding-alist)
(:let key (if (symbol? (car x))
(car x)
(string->symbol (car x))))
(:let expected-value (cond ((null? (cdr x)) #f)
((pair? (cdr x)) (cadr x))
(else (cdr x))))
(:let actual-value (extract-single-binding key bindings))
actual-value => expected-value)
checks exists - binding ? ( 1/2 )
(check-ec (:list x binding-alist)
(:let key (car x))
(:let flip-key (if (symbol? (car x))
(symbol->string (car x))
(string->symbol (car x))))
(and (exists-binding? key bindings)
(exists-binding? flip-key bindings))
=> #t)
check exists - binding ( 1/2 )
(check (exists-binding? 'xxx bindings) => #f)
(check-report)))
)
|
60792e6e83a64a5dbe842f53fc3be64dd7d95112269338634b1847c87246ab2a | IagoAbal/haskell-z3 | Regression.hs | module Z3.Regression
( spec )
where
import Test.Hspec
import Control.Monad(forM_)
import Control.Monad.IO.Class
import qualified Z3.Base as Z3
import qualified Z3.Monad
spec :: Spec
spec = do
describe "issue#23: Crash on parseSMTLib2String" $ do
it "should not crash" $
Z3.Monad.evalZ3 issue23script `shouldReturn` Z3.Monad.Unsat
describe "issue#27: non-deterministic crashes during parallel GC" $ do
it "should not crash" $
issue27script `shouldReturn` ()
describe "issue#29: evalBv" $ do
it "should correctly evaluate example" $
Z3.Monad.evalZ3 issue29script `shouldReturn` Just 35
issue23script :: Z3.Monad.Z3 Z3.Monad.Result
issue23script = do
asts <- Z3.Monad.parseSMTLib2String "(assert (= 1 2))" [] [] [] []
forM_ asts $ \ast -> do
Z3.Monad.assert ast
Z3.Monad.check
issue29script :: Z3.Monad.Z3 (Maybe Integer)
issue29script = do
i32sort <- Z3.Monad.mkBvSort 32
let mkV name = do sym <- Z3.Monad.mkStringSymbol name
Z3.Monad.mkVar sym i32sort
c <- Z3.Monad.mkBitvector 32 35
x <- mkV "x"
-- Perform some operations on the values
e <- Z3.Monad.mkEq c x
Z3.Monad.assert e
z3result <- Z3.Monad.solverCheckAndGetModel
case z3result of
(Z3.Monad.Sat, Just model) -> Z3.Monad.evalBv True model x
_ -> return Nothing
issue27script :: IO ()
issue27script = do
cfg <- Z3.mkConfig
ctx <- Z3.mkContext cfg
int <- Z3.mkIntSort ctx
forM_ [1..100000] $ \i -> do
Z3.mkNumeral ctx (show i) int
| null | https://raw.githubusercontent.com/IagoAbal/haskell-z3/247dac33c82b52f6ca568c1cdb3ec5153351394d/test/Z3/Regression.hs | haskell | Perform some operations on the values | module Z3.Regression
( spec )
where
import Test.Hspec
import Control.Monad(forM_)
import Control.Monad.IO.Class
import qualified Z3.Base as Z3
import qualified Z3.Monad
spec :: Spec
spec = do
describe "issue#23: Crash on parseSMTLib2String" $ do
it "should not crash" $
Z3.Monad.evalZ3 issue23script `shouldReturn` Z3.Monad.Unsat
describe "issue#27: non-deterministic crashes during parallel GC" $ do
it "should not crash" $
issue27script `shouldReturn` ()
describe "issue#29: evalBv" $ do
it "should correctly evaluate example" $
Z3.Monad.evalZ3 issue29script `shouldReturn` Just 35
issue23script :: Z3.Monad.Z3 Z3.Monad.Result
issue23script = do
asts <- Z3.Monad.parseSMTLib2String "(assert (= 1 2))" [] [] [] []
forM_ asts $ \ast -> do
Z3.Monad.assert ast
Z3.Monad.check
issue29script :: Z3.Monad.Z3 (Maybe Integer)
issue29script = do
i32sort <- Z3.Monad.mkBvSort 32
let mkV name = do sym <- Z3.Monad.mkStringSymbol name
Z3.Monad.mkVar sym i32sort
c <- Z3.Monad.mkBitvector 32 35
x <- mkV "x"
e <- Z3.Monad.mkEq c x
Z3.Monad.assert e
z3result <- Z3.Monad.solverCheckAndGetModel
case z3result of
(Z3.Monad.Sat, Just model) -> Z3.Monad.evalBv True model x
_ -> return Nothing
issue27script :: IO ()
issue27script = do
cfg <- Z3.mkConfig
ctx <- Z3.mkContext cfg
int <- Z3.mkIntSort ctx
forM_ [1..100000] $ \i -> do
Z3.mkNumeral ctx (show i) int
|
00e987aa47ade4ee9644e81dca2dcb683f58983e768c864ba95c0e9cd8746c1b | zkat/squirl | util.lisp | ;;;; -*- Mode: Lisp; indent-tabs-mode: nil -*-
(in-package :squirl)
(defun apply-impulses (body1 body2 r1 r2 j)
(body-apply-impulse body1 (vec- j) r1)
(body-apply-impulse body2 j r2)
(values))
(defun k-tensor (body1 body2 r1 r2)
;; calculate mass matrix
;; C sources say: "If I wasn't lazy and wrote a proper matrix class, this wouldn't be so gross...
(let* ((mass-sum (+ (body-inverse-mass body1)
(body-inverse-mass body2)))
;; Start with I*mass-sum
(k11 mass-sum) (k12 0d0)
(k21 0d0) (k22 mass-sum)
;; influence from r1
(b1-inverse-inertia (body-inverse-inertia body1))
(r1xsq (* (vec-x r1) (vec-x r1) b1-inverse-inertia))
(r1ysq (* (vec-y r1) (vec-y r1) b1-inverse-inertia))
(r1nxy (- (* (vec-x r1) (vec-y r1) b1-inverse-inertia)))
;; influence from r2
(b2-inverse-inertia (body-inverse-inertia body2))
(r2xsq (* (vec-x r2) (vec-x r2) b2-inverse-inertia))
(r2ysq (* (vec-y r2) (vec-y r2) b2-inverse-inertia))
(r2nxy (- (* (vec-x r2) (vec-y r2) b2-inverse-inertia))))
;; apply influence from r1
(incf k11 r1ysq) (incf k12 r1nxy)
(incf k21 r1nxy) (incf k22 r1xsq)
;; apply influence from r2
(incf k11 r2ysq) (incf k12 r2nxy)
(incf k21 r2nxy) (incf k22 r2xsq)
;; invert
(let ((det-inv (/ (- (* k11 k22) (* k12 k21)))))
;; and we're done.
(values (vec (* k22 det-inv) (- (* k12 det-inv)))
(vec (- (* k21 det-inv)) (* k11 det-inv))))))
(defun mult-k (vr k1 k2)
(vec (vec. vr k1) (vec. vr k2)))
(defun impulse-max (constraint dt)
(* (constraint-max-force constraint) dt))
| null | https://raw.githubusercontent.com/zkat/squirl/d5ab125b389008696a66f5a0d1bbb7449584db90/src/constraints/util.lisp | lisp | -*- Mode: Lisp; indent-tabs-mode: nil -*-
calculate mass matrix
C sources say: "If I wasn't lazy and wrote a proper matrix class, this wouldn't be so gross...
Start with I*mass-sum
influence from r1
influence from r2
apply influence from r1
apply influence from r2
invert
and we're done. | (in-package :squirl)
(defun apply-impulses (body1 body2 r1 r2 j)
(body-apply-impulse body1 (vec- j) r1)
(body-apply-impulse body2 j r2)
(values))
(defun k-tensor (body1 body2 r1 r2)
(let* ((mass-sum (+ (body-inverse-mass body1)
(body-inverse-mass body2)))
(k11 mass-sum) (k12 0d0)
(k21 0d0) (k22 mass-sum)
(b1-inverse-inertia (body-inverse-inertia body1))
(r1xsq (* (vec-x r1) (vec-x r1) b1-inverse-inertia))
(r1ysq (* (vec-y r1) (vec-y r1) b1-inverse-inertia))
(r1nxy (- (* (vec-x r1) (vec-y r1) b1-inverse-inertia)))
(b2-inverse-inertia (body-inverse-inertia body2))
(r2xsq (* (vec-x r2) (vec-x r2) b2-inverse-inertia))
(r2ysq (* (vec-y r2) (vec-y r2) b2-inverse-inertia))
(r2nxy (- (* (vec-x r2) (vec-y r2) b2-inverse-inertia))))
(incf k11 r1ysq) (incf k12 r1nxy)
(incf k21 r1nxy) (incf k22 r1xsq)
(incf k11 r2ysq) (incf k12 r2nxy)
(incf k21 r2nxy) (incf k22 r2xsq)
(let ((det-inv (/ (- (* k11 k22) (* k12 k21)))))
(values (vec (* k22 det-inv) (- (* k12 det-inv)))
(vec (- (* k21 det-inv)) (* k11 det-inv))))))
(defun mult-k (vr k1 k2)
(vec (vec. vr k1) (vec. vr k2)))
(defun impulse-max (constraint dt)
(* (constraint-max-force constraint) dt))
|
07848b07c30b7c54a18ffff4a8fd4dbdbeec96960f50c16864c14f87823ece75 | EgorDm/fp-pacman | Game.hs | module Game (
start
) where
import Graphics.Gloss(Picture)
import Graphics.Gloss.Game
import Graphics.Gloss.Interface.IO.Game
import qualified SDL
import qualified SDL.Mixer as Mix
import Constants
import Resources
import Engine.Base
import Game.Base
import qualified Game.Menu.Base as Menu
import qualified Game.GameModes.Base as Mode
window :: Display
window = InWindow gameName (width, height) (offset, offset)
playFn = playIO window background fps
start :: IO ()
start = do
classic <- Mode.classicMode
classicCustom <- Mode.classicCustomMode
let rooms = RoomCollection ("tut", Menu.menuTut) [
("main", Menu.mainMenu),
("classic", classic),
("classicRnd", classicCustom),
("gameover", Menu.gameOverMenu),
("win", Menu.winGameMenu),
("pause", Menu.pauseMenu),
("help", Menu.helpMenu),
("controls", Menu.controlsMenu)]
SDL.initialize [SDL.InitAudio]
let chunkSz = 256 in Mix.withAudio Mix.defaultAudio chunkSz $ do
sounds <- loadSounds
let context = makeContext rooms sounds
playContext playFn context
SDL.quit | null | https://raw.githubusercontent.com/EgorDm/fp-pacman/19781c92c97641b0a01b8f1554f50f19ff6d3bf4/src/Game.hs | haskell | module Game (
start
) where
import Graphics.Gloss(Picture)
import Graphics.Gloss.Game
import Graphics.Gloss.Interface.IO.Game
import qualified SDL
import qualified SDL.Mixer as Mix
import Constants
import Resources
import Engine.Base
import Game.Base
import qualified Game.Menu.Base as Menu
import qualified Game.GameModes.Base as Mode
window :: Display
window = InWindow gameName (width, height) (offset, offset)
playFn = playIO window background fps
start :: IO ()
start = do
classic <- Mode.classicMode
classicCustom <- Mode.classicCustomMode
let rooms = RoomCollection ("tut", Menu.menuTut) [
("main", Menu.mainMenu),
("classic", classic),
("classicRnd", classicCustom),
("gameover", Menu.gameOverMenu),
("win", Menu.winGameMenu),
("pause", Menu.pauseMenu),
("help", Menu.helpMenu),
("controls", Menu.controlsMenu)]
SDL.initialize [SDL.InitAudio]
let chunkSz = 256 in Mix.withAudio Mix.defaultAudio chunkSz $ do
sounds <- loadSounds
let context = makeContext rooms sounds
playContext playFn context
SDL.quit | |
ef001bc788902e065000abed2d4aacbe7c93549bef2c213a8ba1ad495e8525dc | ruhler/smten | Ix.hs |
# LANGUAGE NoImplicitPrelude #
module Smten.Data.Ix where
import Smten.Prelude
class (Ord a) => Ix a where
range :: (a, a) -> [a]
index :: (a, a) -> a -> Int
rangeSize :: (a, a) -> Int
rangeSize b@(l, h) = index b h + 1
instance Ix Int where
range (l, h) = [l..h]
index (l, h) x = x - l
instance Ix Integer where
range (l, h) = [l..h]
index (l, h) x = fromInteger (x - l)
instance (Ix a, Ix b) => Ix (a, b) where
range ((l1,l2),(u1,u2)) =
[ (i1,i2) | i1 <- range (l1,u1), i2 <- range (l2,u2) ]
index ((l1,l2),(u1,u2)) (i1,i2) =
index (l1,u1) i1 * rangeSize (l2,u2) + index (l2,u2) i2
instance (Ix a, Ix b, Ix c) => Ix (a, b, c) where
range ((l1,l2,l3), (u1, u2, u3)) =
[ (i1,i2,i3) | i1 <- range (l1,u1),
i2 <- range (l2,u2),
i3 <- range (l3,u3)]
index ((l1,l2,l3),(u1,u2,u3)) (i1,i2,i3) =
index (l3,u3) i3 + rangeSize (l3,u3) * (
index (l2,u2) i2 + rangeSize (l2,u2) * (
index (l1,u1) i1))
| null | https://raw.githubusercontent.com/ruhler/smten/16dd37fb0ee3809408803d4be20401211b6c4027/smten-lib/Smten/Data/Ix.hs | haskell |
# LANGUAGE NoImplicitPrelude #
module Smten.Data.Ix where
import Smten.Prelude
class (Ord a) => Ix a where
range :: (a, a) -> [a]
index :: (a, a) -> a -> Int
rangeSize :: (a, a) -> Int
rangeSize b@(l, h) = index b h + 1
instance Ix Int where
range (l, h) = [l..h]
index (l, h) x = x - l
instance Ix Integer where
range (l, h) = [l..h]
index (l, h) x = fromInteger (x - l)
instance (Ix a, Ix b) => Ix (a, b) where
range ((l1,l2),(u1,u2)) =
[ (i1,i2) | i1 <- range (l1,u1), i2 <- range (l2,u2) ]
index ((l1,l2),(u1,u2)) (i1,i2) =
index (l1,u1) i1 * rangeSize (l2,u2) + index (l2,u2) i2
instance (Ix a, Ix b, Ix c) => Ix (a, b, c) where
range ((l1,l2,l3), (u1, u2, u3)) =
[ (i1,i2,i3) | i1 <- range (l1,u1),
i2 <- range (l2,u2),
i3 <- range (l3,u3)]
index ((l1,l2,l3),(u1,u2,u3)) (i1,i2,i3) =
index (l3,u3) i3 + rangeSize (l3,u3) * (
index (l2,u2) i2 + rangeSize (l2,u2) * (
index (l1,u1) i1))
| |
e84850eac9ef48398ae54e75eb403afa7882b787e8d47848f770dd80af9871a0 | jarcane/heresy | things.rkt | #lang s-exp "../private/base.rkt"
(require racket/stxparam
"list.rkt"
"require-stuff.rkt"
"theory.rkt"
"string.rkt"
(only-in racket/base
define-syntax
gensym
begin
let*
for/and
case-lambda
with-handlers
struct
exn:fail
exn:fail?
gen:custom-write
write-string
prop:procedure
struct-field-index
raise
current-continuation-marks
equal-hash-code)
syntax/parse/define
(for-syntax racket/base syntax/parse unstable/syntax))
(provide (all-defined-out))
(define-simple-macro (define-thing-literal-ids id:id ...)
(begin (define-syntax-parameter id
(lambda (stx)
(raise-syntax-error #f "cannot be used outside a thing definition" stx)))
...))
(define-thing-literal-ids Self extends inherit super)
(def (alist-ref alist fld)
(head (tail (assoc fld alist))))
(define-simple-macro (def-field-id id:id ths:id)
(define-syntax id
(make-variable-like-transformer #'(ths 'id))))
(define-simple-macro (define-syntax-parser name:id opt-or-clause ...)
(define-syntax name (syntax-parser opt-or-clause ...)))
(define-simple-macro (build-type-list (field (type arg0 ...)) ...)
(list
`(field (,(partial type arg0 ...) (type arg0 ...))) ...))
(def fn empty-type-list (fields)
(for (x in fields with Null)
(carry (join `(,x (,any? (any?)))
cry))))
(def fn get-type-pred (name types)
(head (alist-ref types name)))
(def fn get-type-name (name types)
(head (tail (alist-ref types name))))
; (describe *thing* (*field* *value*) ...)
; Declare a new kind of Thing, with the given fields and default values.
(define-syntax-parser describe #:literals (extends inherit super)
[(describe name:id extends super-thing:expr
(~or (~optional (~seq inherit (inherit-id:id ...)) #:defaults ([(inherit-id 1) '()]))
(~optional (~seq super ([super-id1:id super-id2:id] ...))
#:defaults ([(super-id1 1) '()] [(super-id2 1) '()])))
...
(field:id (type?:id arg0:expr ...) value:expr) ...)
#'(def name (thing name extends super-thing inherit (inherit-id ...) super ([super-id1 super-id2] ...)
(field (type? arg0 ...) value) ...))]
[(describe name:id extends super-thing:expr
(~or (~optional (~seq inherit (inherit-id:id ...)) #:defaults ([(inherit-id 1) '()]))
(~optional (~seq super ([super-id1:id super-id2:id] ...))
#:defaults ([(super-id1 1) '()] [(super-id2 1) '()])))
...
(field:id value:expr) ...)
#'(def name (thing name extends super-thing inherit (inherit-id ...) super ([super-id1 super-id2] ...)
(field value) ...))]
[(describe name:id (field:id (type?:id arg0:expr ...) value:expr) ...)
#'(def name (thing name (field (type? arg0 ...) value) ...))]
[(describe name:id (field:id value:expr) ...)
#'(def name (thing name (field value) ...))])
(define-syntax-parser thing #:literals (extends inherit super)
[(thing (~optional name:id #:defaults ([name #'thing])) (field:id (type?:id arg0:expr ...) value:expr) ...)
#'(let ([types (build-type-list (field (type? arg0 ...)) ...)])
(make-thing `([field
,(let ([field
(fn (ths)
(syntax-parameterize ([Self (make-rename-transformer #'ths)])
(def-field-id field ths) ...
value))])
field)]
...)
'name
types))]
[(thing (~optional name:id #:defaults ([name #'thing])) (field:id value:expr) ...)
#'(make-thing `([field
,(let ([field
(fn (ths)
(syntax-parameterize ([Self (make-rename-transformer #'ths)])
(def-field-id field ths) ...
value))])
field)]
...)
'name)]
[(thing (~optional name:id #:defaults ([name #'thing])) extends super-thing:expr
(~or (~optional (~seq inherit (inherit-id:id ...)) #:defaults ([(inherit-id 1) '()]))
(~optional (~seq super ([super-id1:id super-id2:id] ...))
#:defaults ([(super-id1 1) '()] [(super-id2 1) '()])))
...
(field:id (type?:id arg0:expr ...) value:expr) ...)
#'(let* ([super super-thing]
[super-λlst (super λlst-sym)]
[super-parents (super '__parents)]
[super-ident (super '__ident)]
[super-types (super '__types)]
[types (alist-merge super-types (build-type-list (field (type? arg0 ...)) ...))])
(make-thing (alist-merge
super-λlst
`([field
,(let ([field
(fn (ths)
(syntax-parameterize ([Self (make-rename-transformer #'ths)])
(def-field-id field ths) ...
(def-field-id inherit-id ths) ...
(def super-id1 ((alist-ref super-λlst 'super-id2) ths)) ...
value))])
field)]
...))
'name
types
(join super-ident super-parents)))]
[(thing (~optional name:id #:defaults ([name #'thing])) extends super-thing:expr
(~or (~optional (~seq inherit (inherit-id:id ...)) #:defaults ([(inherit-id 1) '()]))
(~optional (~seq super ([super-id1:id super-id2:id] ...))
#:defaults ([(super-id1 1) '()] [(super-id2 1) '()])))
...
(field:id value:expr) ...)
#'(let* ([super super-thing]
[super-λlst (super λlst-sym)]
[super-parents (super '__parents)]
[super-ident (super '__ident)]
[super-fields (super 'fields)]
[super-types (super '__types)]
[types (alist-merge super-types
(build-type-list (field (any?)) ...))])
(make-thing (alist-merge
super-λlst
`([field
,(let ([field
(fn (ths)
(syntax-parameterize ([Self (make-rename-transformer #'ths)])
(def-field-id field ths) ...
(def-field-id inherit-id ths) ...
(def super-id1 ((alist-ref super-λlst 'super-id2) ths)) ...
value))])
field)]
...))
'name
types
(join super-ident super-parents)))])
(def λlst-sym (gensym 'λlst))
(struct exn:bad-thing-ref exn:fail ())
(struct exn:thing-type-err exn:fail ())
;; Wrapper struct for things. Provides custom printing while still behaving as procedure.
(def fn thing-print (obj port mode)
(let* ([thng (thing-s-proc obj)]
[as-str (str$ (join (thing-s-name obj) (thng)))])
(write-string as-str port)))
(struct thing-s (name proc)
#:methods gen:custom-write
[(def write-proc
thing-print)]
#:property prop:procedure
(struct-field-index proc))
(def fn make-thing (λlst name [types Null] [parents Null] [ident (gensym 'thing)])
(let ()
(def this
(fn args*
(let* ([alst lst]
[hash (equal-hash-code lst)]
[fields (heads lst)]
[type-list (if (null? types) then (empty-type-list fields) else types)])
(select
[(null? args*) alst]
[(eq? 'fields (head args*)) fields]
[(eq? '__hash (head args*)) hash]
[(eq? '__ident (head args*)) ident]
[(eq? '__parents (head args*)) parents]
[(eq? '__types (head args*)) type-list]
[(eq? λlst-sym (head args*)) λlst]
[(and (symbol? (head args*))
(assoc (head args*) alst)) (alist-ref alst (head args*))]
[(list-of? list? (head args*))
(let ([new-lst (for (x in (head args*) with λlst)
(let ([pred? (get-type-pred (head x) type-list)]
[type (get-type-name (head x) type-list)])
(if (pred? (head (tail x)))
then
(carry (subst (head x) (fn (_) (head (tail x))) cry))
else
(raise (exn:thing-type-err
(format$ "Thing encountered type error in assignment: #_ must be #_" (head x) type)
(current-continuation-marks))))))])
(make-thing new-lst name types parents ident))]
[(list? (head args*))
(let recur ([λl λlst]
[pat (head args*)]
[c 1])
(select
[(null? pat) (make-thing λl name types parents ident)]
[(eq? (head pat) '*) (recur λl (tail pat) (+ 1 c))]
[else
(let* ([hd (head pat)]
[pair (index c type-list)]
[field (head pair)]
[type (get-type-name field type-list)]
[pred? (get-type-pred field type-list)])
(if (pred? hd)
then
(recur (subst (head (index c λl))
(fn (_) hd)
λl)
(tail pat)
(+ 1 c))
else
(raise (exn:thing-type-err
(format$ "Thing encountered type error in assignment: #_ must be #_" field type)
(current-continuation-marks)))))]))]
[else (raise (exn:bad-thing-ref
"Thing expected a valid symbol or a pattern"
(current-continuation-marks)))]))))
(def lst
(map (fn (p)
(list (index 1 p) ((index 2 p) this)))
λlst))
(if (null? types) then (thing-s name this) else
(do
(for (x in lst)
(let* ([val (head (tail x))]
[field (head x)]
[type (get-type-name field types)]
[pred? (get-type-pred field types)])
(if (pred? val)
then val
else (raise (exn:thing-type-err
(format$ "Thing encountered type error in declaration: #_ must be #_" field type)
(current-continuation-marks))))))
(thing-s name this)))))
(def (send thing method . args)
(apply (thing method) args))
(define-simple-macro (send* obj-expr:expr (method:id arg ...) ...+)
(let ([obj obj-expr])
(send obj 'method arg ...)
...))
(define-simple-macro (send+ obj-expr:expr msg:expr ...)
(let* ([obj obj-expr]
[obj (send* obj msg)] ...)
obj))
; (thing? v)
; Any -> Bool
; Returns True if value is a Thing
(def fn thing? (v)
(and (fn? v)
(with-handlers ((exn:bad-thing-ref? (fn (e) False)))
(and (list? (v))
(list? (v 'fields))
(v '__hash)
(fn? (v '()))))))
; (is-a? Type Thing)
; Thing Thing -> Bool
; Returns True if Thing is the same type as Type
(def fn is-a? (Type Thing)
(and (thing? Type)
(thing? Thing)
(or (equal? (Type '__ident)
(Thing '__ident))
(number? (inlst (Type '__ident)
(Thing '__parents))))))
( thing= ? )
; Thing Thing -> Bool
; Returns True if both Things are the same type and their hash values are equal?
(def fn thing=? (thing1 thing2)
(and (is-a? thing1 thing2)
(equal? (thing1 '__hash)
(thing2 '__hash))))
; (any? v)
; Any -> True
; Always returns True regardless of value
(def fn any? (v) True)
; (list-of? pred? xs)
Fn(Any - > Bool ) List(Any ) - > Bool
; Returns True of all elements in the list match pred?
(def fn list-of? (pred? xs)
(select
((null? xs) True)
((not (pred? (head xs))) False)
(else (list-of? pred? (tail xs)))))
;; Placeholder values
;; These are simple values predefined for common primitive types, to provide more self-documenting default values for newly described things
;; Note that no error checking is actually performed, these are merely for documentation purposes
Placeholders that take an argument allow you to also specify what type is within the container , ie . ( List Number )
(def Any Null)
(def String "")
(def Number 0)
(def Boolean False)
(def Symbol 'default)
(def Fn (fn (v) v))
(def Thing (thing))
(def fn List (type) (list type))
;; alist-merge
(def alist-merge
(case-lambda
[() '()]
[(a) a]
[(a b)
(select
[(null? b) a]
[(null? a) b]
[else (let* ([b.fst (head b)]
[b.rst (tail b)]
[a.hds (map head a)]
[b.fst.fst (head b.fst)]
[b.fst.rst (tail b.fst)])
(select
[(inlst b.fst.fst a.hds) (alist-merge (subst* b.fst.fst b.fst.rst a) b.rst)]
[else (alist-merge (append a (list b.fst)) b.rst)]))])]
[(a b . rst) (apply alist-merge (alist-merge a b) rst)]))
| null | https://raw.githubusercontent.com/jarcane/heresy/a736b69178dffa2ef97f5eb5204f3e06840088c2/lib/things.rkt | racket | (describe *thing* (*field* *value*) ...)
Declare a new kind of Thing, with the given fields and default values.
Wrapper struct for things. Provides custom printing while still behaving as procedure.
(thing? v)
Any -> Bool
Returns True if value is a Thing
(is-a? Type Thing)
Thing Thing -> Bool
Returns True if Thing is the same type as Type
Thing Thing -> Bool
Returns True if both Things are the same type and their hash values are equal?
(any? v)
Any -> True
Always returns True regardless of value
(list-of? pred? xs)
Returns True of all elements in the list match pred?
Placeholder values
These are simple values predefined for common primitive types, to provide more self-documenting default values for newly described things
Note that no error checking is actually performed, these are merely for documentation purposes
alist-merge | #lang s-exp "../private/base.rkt"
(require racket/stxparam
"list.rkt"
"require-stuff.rkt"
"theory.rkt"
"string.rkt"
(only-in racket/base
define-syntax
gensym
begin
let*
for/and
case-lambda
with-handlers
struct
exn:fail
exn:fail?
gen:custom-write
write-string
prop:procedure
struct-field-index
raise
current-continuation-marks
equal-hash-code)
syntax/parse/define
(for-syntax racket/base syntax/parse unstable/syntax))
(provide (all-defined-out))
(define-simple-macro (define-thing-literal-ids id:id ...)
(begin (define-syntax-parameter id
(lambda (stx)
(raise-syntax-error #f "cannot be used outside a thing definition" stx)))
...))
(define-thing-literal-ids Self extends inherit super)
(def (alist-ref alist fld)
(head (tail (assoc fld alist))))
(define-simple-macro (def-field-id id:id ths:id)
(define-syntax id
(make-variable-like-transformer #'(ths 'id))))
(define-simple-macro (define-syntax-parser name:id opt-or-clause ...)
(define-syntax name (syntax-parser opt-or-clause ...)))
(define-simple-macro (build-type-list (field (type arg0 ...)) ...)
(list
`(field (,(partial type arg0 ...) (type arg0 ...))) ...))
(def fn empty-type-list (fields)
(for (x in fields with Null)
(carry (join `(,x (,any? (any?)))
cry))))
(def fn get-type-pred (name types)
(head (alist-ref types name)))
(def fn get-type-name (name types)
(head (tail (alist-ref types name))))
(define-syntax-parser describe #:literals (extends inherit super)
[(describe name:id extends super-thing:expr
(~or (~optional (~seq inherit (inherit-id:id ...)) #:defaults ([(inherit-id 1) '()]))
(~optional (~seq super ([super-id1:id super-id2:id] ...))
#:defaults ([(super-id1 1) '()] [(super-id2 1) '()])))
...
(field:id (type?:id arg0:expr ...) value:expr) ...)
#'(def name (thing name extends super-thing inherit (inherit-id ...) super ([super-id1 super-id2] ...)
(field (type? arg0 ...) value) ...))]
[(describe name:id extends super-thing:expr
(~or (~optional (~seq inherit (inherit-id:id ...)) #:defaults ([(inherit-id 1) '()]))
(~optional (~seq super ([super-id1:id super-id2:id] ...))
#:defaults ([(super-id1 1) '()] [(super-id2 1) '()])))
...
(field:id value:expr) ...)
#'(def name (thing name extends super-thing inherit (inherit-id ...) super ([super-id1 super-id2] ...)
(field value) ...))]
[(describe name:id (field:id (type?:id arg0:expr ...) value:expr) ...)
#'(def name (thing name (field (type? arg0 ...) value) ...))]
[(describe name:id (field:id value:expr) ...)
#'(def name (thing name (field value) ...))])
(define-syntax-parser thing #:literals (extends inherit super)
[(thing (~optional name:id #:defaults ([name #'thing])) (field:id (type?:id arg0:expr ...) value:expr) ...)
#'(let ([types (build-type-list (field (type? arg0 ...)) ...)])
(make-thing `([field
,(let ([field
(fn (ths)
(syntax-parameterize ([Self (make-rename-transformer #'ths)])
(def-field-id field ths) ...
value))])
field)]
...)
'name
types))]
[(thing (~optional name:id #:defaults ([name #'thing])) (field:id value:expr) ...)
#'(make-thing `([field
,(let ([field
(fn (ths)
(syntax-parameterize ([Self (make-rename-transformer #'ths)])
(def-field-id field ths) ...
value))])
field)]
...)
'name)]
[(thing (~optional name:id #:defaults ([name #'thing])) extends super-thing:expr
(~or (~optional (~seq inherit (inherit-id:id ...)) #:defaults ([(inherit-id 1) '()]))
(~optional (~seq super ([super-id1:id super-id2:id] ...))
#:defaults ([(super-id1 1) '()] [(super-id2 1) '()])))
...
(field:id (type?:id arg0:expr ...) value:expr) ...)
#'(let* ([super super-thing]
[super-λlst (super λlst-sym)]
[super-parents (super '__parents)]
[super-ident (super '__ident)]
[super-types (super '__types)]
[types (alist-merge super-types (build-type-list (field (type? arg0 ...)) ...))])
(make-thing (alist-merge
super-λlst
`([field
,(let ([field
(fn (ths)
(syntax-parameterize ([Self (make-rename-transformer #'ths)])
(def-field-id field ths) ...
(def-field-id inherit-id ths) ...
(def super-id1 ((alist-ref super-λlst 'super-id2) ths)) ...
value))])
field)]
...))
'name
types
(join super-ident super-parents)))]
[(thing (~optional name:id #:defaults ([name #'thing])) extends super-thing:expr
(~or (~optional (~seq inherit (inherit-id:id ...)) #:defaults ([(inherit-id 1) '()]))
(~optional (~seq super ([super-id1:id super-id2:id] ...))
#:defaults ([(super-id1 1) '()] [(super-id2 1) '()])))
...
(field:id value:expr) ...)
#'(let* ([super super-thing]
[super-λlst (super λlst-sym)]
[super-parents (super '__parents)]
[super-ident (super '__ident)]
[super-fields (super 'fields)]
[super-types (super '__types)]
[types (alist-merge super-types
(build-type-list (field (any?)) ...))])
(make-thing (alist-merge
super-λlst
`([field
,(let ([field
(fn (ths)
(syntax-parameterize ([Self (make-rename-transformer #'ths)])
(def-field-id field ths) ...
(def-field-id inherit-id ths) ...
(def super-id1 ((alist-ref super-λlst 'super-id2) ths)) ...
value))])
field)]
...))
'name
types
(join super-ident super-parents)))])
(def λlst-sym (gensym 'λlst))
(struct exn:bad-thing-ref exn:fail ())
(struct exn:thing-type-err exn:fail ())
(def fn thing-print (obj port mode)
(let* ([thng (thing-s-proc obj)]
[as-str (str$ (join (thing-s-name obj) (thng)))])
(write-string as-str port)))
(struct thing-s (name proc)
#:methods gen:custom-write
[(def write-proc
thing-print)]
#:property prop:procedure
(struct-field-index proc))
(def fn make-thing (λlst name [types Null] [parents Null] [ident (gensym 'thing)])
(let ()
(def this
(fn args*
(let* ([alst lst]
[hash (equal-hash-code lst)]
[fields (heads lst)]
[type-list (if (null? types) then (empty-type-list fields) else types)])
(select
[(null? args*) alst]
[(eq? 'fields (head args*)) fields]
[(eq? '__hash (head args*)) hash]
[(eq? '__ident (head args*)) ident]
[(eq? '__parents (head args*)) parents]
[(eq? '__types (head args*)) type-list]
[(eq? λlst-sym (head args*)) λlst]
[(and (symbol? (head args*))
(assoc (head args*) alst)) (alist-ref alst (head args*))]
[(list-of? list? (head args*))
(let ([new-lst (for (x in (head args*) with λlst)
(let ([pred? (get-type-pred (head x) type-list)]
[type (get-type-name (head x) type-list)])
(if (pred? (head (tail x)))
then
(carry (subst (head x) (fn (_) (head (tail x))) cry))
else
(raise (exn:thing-type-err
(format$ "Thing encountered type error in assignment: #_ must be #_" (head x) type)
(current-continuation-marks))))))])
(make-thing new-lst name types parents ident))]
[(list? (head args*))
(let recur ([λl λlst]
[pat (head args*)]
[c 1])
(select
[(null? pat) (make-thing λl name types parents ident)]
[(eq? (head pat) '*) (recur λl (tail pat) (+ 1 c))]
[else
(let* ([hd (head pat)]
[pair (index c type-list)]
[field (head pair)]
[type (get-type-name field type-list)]
[pred? (get-type-pred field type-list)])
(if (pred? hd)
then
(recur (subst (head (index c λl))
(fn (_) hd)
λl)
(tail pat)
(+ 1 c))
else
(raise (exn:thing-type-err
(format$ "Thing encountered type error in assignment: #_ must be #_" field type)
(current-continuation-marks)))))]))]
[else (raise (exn:bad-thing-ref
"Thing expected a valid symbol or a pattern"
(current-continuation-marks)))]))))
(def lst
(map (fn (p)
(list (index 1 p) ((index 2 p) this)))
λlst))
(if (null? types) then (thing-s name this) else
(do
(for (x in lst)
(let* ([val (head (tail x))]
[field (head x)]
[type (get-type-name field types)]
[pred? (get-type-pred field types)])
(if (pred? val)
then val
else (raise (exn:thing-type-err
(format$ "Thing encountered type error in declaration: #_ must be #_" field type)
(current-continuation-marks))))))
(thing-s name this)))))
(def (send thing method . args)
(apply (thing method) args))
(define-simple-macro (send* obj-expr:expr (method:id arg ...) ...+)
(let ([obj obj-expr])
(send obj 'method arg ...)
...))
(define-simple-macro (send+ obj-expr:expr msg:expr ...)
(let* ([obj obj-expr]
[obj (send* obj msg)] ...)
obj))
(def fn thing? (v)
(and (fn? v)
(with-handlers ((exn:bad-thing-ref? (fn (e) False)))
(and (list? (v))
(list? (v 'fields))
(v '__hash)
(fn? (v '()))))))
(def fn is-a? (Type Thing)
(and (thing? Type)
(thing? Thing)
(or (equal? (Type '__ident)
(Thing '__ident))
(number? (inlst (Type '__ident)
(Thing '__parents))))))
( thing= ? )
(def fn thing=? (thing1 thing2)
(and (is-a? thing1 thing2)
(equal? (thing1 '__hash)
(thing2 '__hash))))
(def fn any? (v) True)
Fn(Any - > Bool ) List(Any ) - > Bool
(def fn list-of? (pred? xs)
(select
((null? xs) True)
((not (pred? (head xs))) False)
(else (list-of? pred? (tail xs)))))
Placeholders that take an argument allow you to also specify what type is within the container , ie . ( List Number )
(def Any Null)
(def String "")
(def Number 0)
(def Boolean False)
(def Symbol 'default)
(def Fn (fn (v) v))
(def Thing (thing))
(def fn List (type) (list type))
(def alist-merge
(case-lambda
[() '()]
[(a) a]
[(a b)
(select
[(null? b) a]
[(null? a) b]
[else (let* ([b.fst (head b)]
[b.rst (tail b)]
[a.hds (map head a)]
[b.fst.fst (head b.fst)]
[b.fst.rst (tail b.fst)])
(select
[(inlst b.fst.fst a.hds) (alist-merge (subst* b.fst.fst b.fst.rst a) b.rst)]
[else (alist-merge (append a (list b.fst)) b.rst)]))])]
[(a b . rst) (apply alist-merge (alist-merge a b) rst)]))
|
9e243eebde459c988fc1c8aa204a4bcb81a04c6a8058094973bbe8dff24dafa5 | G-Corp/rfile | rfile_app.erl | % @hidden
-module(rfile_app).
-behaviour(application).
-export([start/2, stop/1]).
start(_StartType, _StartArgs) ->
rfile_sup:start_link().
stop(_State) ->
ok.
| null | https://raw.githubusercontent.com/G-Corp/rfile/64464534904c026211f23ab735ea6b15ea17401c/src/rfile_app.erl | erlang | @hidden | -module(rfile_app).
-behaviour(application).
-export([start/2, stop/1]).
start(_StartType, _StartArgs) ->
rfile_sup:start_link().
stop(_State) ->
ok.
|
fe01062856a9d18263465a5df65bb7706d6521e75f64b29dab5c4e9fe21bfc5e | Gbury/archsat | ext_constraints.mli | This file is free software , part of Archsat . See file " LICENSE " for more details .
(** Extension for constraints *)
val register : unit -> unit
(** Register the extension. *)
| null | https://raw.githubusercontent.com/Gbury/archsat/322fbefa4a58023ddafb3fa1a51f8199c25cde3d/src/core/ext_constraints.mli | ocaml | * Extension for constraints
* Register the extension. | This file is free software , part of Archsat . See file " LICENSE " for more details .
val register : unit -> unit
|
41e0aaa6f75dc33990630070f2a3929ba6717e7bc0a4339faca31c3f5ff3676a | f-o-a-m/kepler | App.hs | module Network.ABCI.Server.App
( App(..)
, runApp
, transformApp
, withProto
, Middleware
, MessageType(..)
, demoteRequestType
, msgTypeKey
, Request(..)
, hashRequest
, Response(..)
, LPByteStrings(..)
, decodeLengthPrefix
, encodeLengthPrefix
) where
import Control.Lens ((?~), (^.))
import Control.Lens.Wrapped (Wrapped (..),
_Unwrapped')
import Control.Monad ((>=>))
import Data.Aeson (FromJSON (..),
ToJSON (..), Value (..),
object, withObject, (.:),
(.=))
import Data.Aeson.Types (Parser)
import Data.Bifunctor (first)
import qualified Data.ByteString as BS
import Data.Function ((&))
import Data.Kind (Type)
import qualified Data.ProtoLens as PL
import Data.ProtoLens.Encoding.Bytes (getVarInt, putVarInt,
runBuilder, runParser,
signedInt64ToWord,
wordToSignedInt64)
import Data.String.Conversions (cs)
import Data.Text (Text)
import Network.ABCI.Server.App.DecodeError (DecodeError)
import qualified Network.ABCI.Server.App.DecodeError as DecodeError
import qualified Network.ABCI.Types.Messages.Request as Request
import qualified Network.ABCI.Types.Messages.Response as Response
import Crypto.Hash (hashWith)
import Crypto.Hash.Algorithms (SHA256 (..))
import Data.ByteArray (convert)
import qualified Data.ByteArray.HexString as Hex
import Data.Default.Class (Default (..))
import Data.ProtoLens.Message (Message (defMessage))
import Data.ProtoLens.Prism (( # ))
import qualified Proto.Types as PT
import qualified Proto.Types_Fields as PT
-- | Used to parametrize Request and Response types
data MessageType
= MTEcho
| MTFlush
| MTInfo
| MTSetOption
| MTInitChain
| MTQuery
| MTBeginBlock
| MTCheckTx
| MTDeliverTx
| MTEndBlock
| MTCommit
deriving (Eq, Ord, Enum)
msgTypeKey :: MessageType -> String
msgTypeKey m = case m of
MTEcho -> "echo"
MTFlush -> "flush"
MTInfo -> "info"
MTSetOption -> "setOption"
MTInitChain -> "initChain"
MTQuery -> "query"
MTBeginBlock -> "beginBlock"
MTCheckTx -> "checkTx"
MTDeliverTx -> "deliverTx"
MTEndBlock -> "endBlock"
MTCommit -> "commit"
demoteRequestType :: forall (t :: MessageType). Request t -> MessageType
demoteRequestType req = case req of
RequestEcho _ -> MTEcho
RequestInfo _ -> MTInfo
RequestSetOption _ -> MTSetOption
RequestQuery _ -> MTQuery
RequestCheckTx _ -> MTCheckTx
RequestFlush _ -> MTFlush
RequestInitChain _ -> MTInitChain
RequestBeginBlock _ -> MTBeginBlock
RequestDeliverTx _ -> MTDeliverTx
RequestEndBlock _ -> MTEndBlock
RequestCommit _ -> MTCommit
reqParseJSON :: forall t inner. FromJSON inner => MessageType -> (inner -> Request t) -> Value -> Parser (Request t)
reqParseJSON msgType ctr = withObject ("req:" <> expectedType) $ \v -> do
actualType <- v .: "type"
if actualType == expectedType
then ctr <$> v .: "message"
else fail $ "expected `type` to equal: " <> show expectedType <> ", but got: " <> show actualType
where
expectedType = msgTypeKey msgType
resParseJSON :: FromJSON inner => MessageType -> (inner -> Response t) -> Value -> Parser (Response t)
resParseJSON msgType ctr = withObject ("res:" <> expectedType) $ \v -> do
actualType <- v .: "type"
if actualType == "exception"
then ResponseException <$> v .: "message"
else if actualType == expectedType
then ctr <$> v .: "message"
else fail $ "expected `type` to equal: " <> show expectedType <> ", but got: " <> show actualType
where
expectedType = msgTypeKey msgType
reqResToJSON :: ToJSON inner => MessageType -> inner -> Value
reqResToJSON msgType message = reqResToJSON' (cs $ msgTypeKey msgType) message
reqResToJSON' :: ToJSON inner => Text -> inner -> Value
reqResToJSON' msgType message = object
[ "type" .= String msgType, "message" .= toJSON message]
--------------------------------------------------------------------------------
-- Request
--------------------------------------------------------------------------------
Note : that there are 3 type of connection made by tendermint to the ABCI application :
* Info / Query Connection , sends only : Echo , Info and SetOption requests
* , sends only : CheckTx and Flush requests
* Consensus Connection , InitChain , : BeginBlock , DeliverTx , EndBlock and Commit requests
-- #L11-L41
data Request (m :: MessageType) :: Type where
-- Info/Query Connection
RequestEcho :: Request.Echo -> Request 'MTEcho
RequestInfo :: Request.Info -> Request 'MTInfo
RequestSetOption :: Request.SetOption -> Request 'MTSetOption
RequestQuery :: Request.Query -> Request 'MTQuery
-- Mempool Connection
RequestCheckTx :: Request.CheckTx -> Request 'MTCheckTx
RequestFlush :: Request.Flush -> Request 'MTFlush
-- Consensus Connection
RequestInitChain :: Request.InitChain -> Request 'MTInitChain
RequestBeginBlock :: Request.BeginBlock -> Request 'MTBeginBlock
RequestDeliverTx :: Request.DeliverTx -> Request 'MTDeliverTx
RequestEndBlock :: Request.EndBlock -> Request 'MTEndBlock
RequestCommit :: Request.Commit -> Request 'MTCommit
instance ToJSON (Request (t :: MessageType)) where
toJSON (RequestEcho v) = reqResToJSON MTEcho v
toJSON (RequestInfo v) = reqResToJSON MTInfo v
toJSON (RequestSetOption v) = reqResToJSON MTSetOption v
toJSON (RequestQuery v) = reqResToJSON MTQuery v
toJSON (RequestCheckTx v) = reqResToJSON MTCheckTx v
toJSON (RequestFlush v) = reqResToJSON MTFlush v
toJSON (RequestInitChain v) = reqResToJSON MTInitChain v
toJSON (RequestBeginBlock v) = reqResToJSON MTBeginBlock v
toJSON (RequestDeliverTx v) = reqResToJSON MTDeliverTx v
toJSON (RequestEndBlock v) = reqResToJSON MTEndBlock v
toJSON (RequestCommit v) = reqResToJSON MTCommit v
instance FromJSON (Request 'MTEcho) where parseJSON = reqParseJSON MTEcho RequestEcho
instance FromJSON (Request 'MTInfo) where parseJSON = reqParseJSON MTInfo RequestInfo
instance FromJSON (Request 'MTSetOption) where parseJSON = reqParseJSON MTSetOption RequestSetOption
instance FromJSON (Request 'MTQuery) where parseJSON = reqParseJSON MTQuery RequestQuery
instance FromJSON (Request 'MTCheckTx) where parseJSON = reqParseJSON MTCheckTx RequestCheckTx
instance FromJSON (Request 'MTFlush) where parseJSON = reqParseJSON MTFlush RequestFlush
instance FromJSON (Request 'MTInitChain) where parseJSON = reqParseJSON MTInitChain RequestInitChain
instance FromJSON (Request 'MTBeginBlock) where parseJSON = reqParseJSON MTBeginBlock RequestBeginBlock
instance FromJSON (Request 'MTDeliverTx) where parseJSON = reqParseJSON MTDeliverTx RequestDeliverTx
instance FromJSON (Request 'MTEndBlock) where parseJSON = reqParseJSON MTEndBlock RequestEndBlock
instance FromJSON (Request 'MTCommit) where parseJSON = reqParseJSON MTCommit RequestCommit
hashRequest
:: forall (t :: MessageType).
Request t
-> Hex.HexString
hashRequest req =
let requestBytes :: BS.ByteString = case req of
RequestEcho v -> PL.encodeMessage $ v ^. _Wrapped'
RequestFlush v -> PL.encodeMessage $ v ^. _Wrapped'
RequestInfo v -> PL.encodeMessage $ v ^. _Wrapped'
RequestSetOption v -> PL.encodeMessage $ v ^. _Wrapped'
RequestInitChain v -> PL.encodeMessage $ v ^. _Wrapped'
RequestQuery v -> PL.encodeMessage $ v ^. _Wrapped'
RequestBeginBlock v -> PL.encodeMessage $ v ^. _Wrapped'
RequestCheckTx v -> PL.encodeMessage $ v ^. _Wrapped'
RequestDeliverTx v -> PL.encodeMessage $ v ^. _Wrapped'
RequestEndBlock v -> PL.encodeMessage $ v ^. _Wrapped'
RequestCommit v -> PL.encodeMessage $ v ^. _Wrapped'
in Hex.fromBytes @BS.ByteString . convert $ hashWith SHA256 requestBytes
withProto
:: (forall (t :: MessageType). Request t -> a)
-> PT.Request'Value
-> a
withProto f value = case value of
PT.Request'Echo echo -> f $ RequestEcho $ echo ^. _Unwrapped'
PT.Request'Flush flush -> f $ RequestFlush $ flush ^. _Unwrapped'
PT.Request'Info info -> f $ RequestInfo $ info ^. _Unwrapped'
PT.Request'SetOption setOption -> f $ RequestSetOption $ setOption ^. _Unwrapped'
PT.Request'InitChain initChain -> f $ RequestInitChain $ initChain ^. _Unwrapped'
PT.Request'Query query -> f $ RequestQuery $ query ^. _Unwrapped'
PT.Request'BeginBlock beginBlock -> f $ RequestBeginBlock $ beginBlock ^. _Unwrapped'
PT.Request'CheckTx checkTx -> f $ RequestCheckTx $ checkTx ^. _Unwrapped'
PT.Request'DeliverTx deliverTx -> f $ RequestDeliverTx $ deliverTx ^. _Unwrapped'
PT.Request'EndBlock endBlock -> f $ RequestEndBlock $ endBlock ^. _Unwrapped'
PT.Request'Commit commit -> f $ RequestCommit $ commit ^. _Unwrapped'
--------------------------------------------------------------------------------
-- Response
--------------------------------------------------------------------------------
data Response (m :: MessageType) :: Type where
ResponseEcho :: Response.Echo -> Response 'MTEcho
ResponseFlush :: Response.Flush -> Response 'MTFlush
ResponseInfo :: Response.Info -> Response 'MTInfo
ResponseSetOption :: Response.SetOption -> Response 'MTSetOption
ResponseInitChain :: Response.InitChain -> Response 'MTInitChain
ResponseQuery :: Response.Query -> Response 'MTQuery
ResponseBeginBlock :: Response.BeginBlock -> Response 'MTBeginBlock
ResponseCheckTx :: Response.CheckTx -> Response 'MTCheckTx
ResponseDeliverTx :: Response.DeliverTx -> Response 'MTDeliverTx
ResponseEndBlock :: Response.EndBlock -> Response 'MTEndBlock
ResponseCommit :: Response.Commit -> Response 'MTCommit
ResponseException :: forall (m :: MessageType) . Response.Exception -> Response m
instance ToJSON (Response (t :: MessageType)) where
toJSON (ResponseEcho v) = reqResToJSON MTEcho v
toJSON (ResponseFlush v) = reqResToJSON MTFlush v
toJSON (ResponseInfo v) = reqResToJSON MTInfo v
toJSON (ResponseSetOption v) = reqResToJSON MTSetOption v
toJSON (ResponseInitChain v) = reqResToJSON MTInitChain v
toJSON (ResponseQuery v) = reqResToJSON MTQuery v
toJSON (ResponseBeginBlock v) = reqResToJSON MTBeginBlock v
toJSON (ResponseCheckTx v) = reqResToJSON MTCheckTx v
toJSON (ResponseDeliverTx v) = reqResToJSON MTDeliverTx v
toJSON (ResponseEndBlock v) = reqResToJSON MTEndBlock v
toJSON (ResponseCommit v) = reqResToJSON MTCommit v
toJSON (ResponseException v) = reqResToJSON' "exception" v
instance FromJSON (Response 'MTEcho) where parseJSON = resParseJSON MTEcho ResponseEcho
instance FromJSON (Response 'MTFlush) where parseJSON = resParseJSON MTFlush ResponseFlush
instance FromJSON (Response 'MTInfo) where parseJSON = resParseJSON MTInfo ResponseInfo
instance FromJSON (Response 'MTSetOption) where parseJSON = resParseJSON MTSetOption ResponseSetOption
instance FromJSON (Response 'MTInitChain) where parseJSON = resParseJSON MTInitChain ResponseInitChain
instance FromJSON (Response 'MTQuery) where parseJSON = resParseJSON MTQuery ResponseQuery
instance FromJSON (Response 'MTBeginBlock) where parseJSON = resParseJSON MTBeginBlock ResponseBeginBlock
instance FromJSON (Response 'MTCheckTx) where parseJSON = resParseJSON MTCheckTx ResponseCheckTx
instance FromJSON (Response 'MTDeliverTx) where parseJSON = resParseJSON MTDeliverTx ResponseDeliverTx
instance FromJSON (Response 'MTEndBlock) where parseJSON = resParseJSON MTEndBlock ResponseEndBlock
instance FromJSON (Response 'MTCommit) where parseJSON = resParseJSON MTCommit ResponseCommit
instance Default (Response 'MTEcho) where def = ResponseEcho def
instance Default (Response 'MTFlush) where def = ResponseFlush def
instance Default (Response 'MTInfo) where def = ResponseInfo def
instance Default (Response 'MTSetOption) where def = ResponseSetOption def
instance Default (Response 'MTInitChain) where def = ResponseInitChain def
instance Default (Response 'MTQuery) where def = ResponseQuery def
instance Default (Response 'MTBeginBlock) where def = ResponseBeginBlock def
instance Default (Response 'MTCheckTx) where def = ResponseCheckTx def
instance Default (Response 'MTDeliverTx) where def = ResponseDeliverTx def
instance Default (Response 'MTEndBlock) where def = ResponseEndBlock def
instance Default (Response 'MTCommit) where def = ResponseCommit def
-- | Translates type-safe 'Response' GADT to the unsafe
auto - generated ' Proto . Response '
toProto :: Response t -> PT.Response
toProto r = case r of
ResponseEcho msg -> wrap PT._Response'Echo msg
ResponseFlush msg -> wrap PT._Response'Flush msg
ResponseInfo msg -> wrap PT._Response'Info msg
ResponseSetOption msg -> wrap PT._Response'SetOption msg
ResponseInitChain msg -> wrap PT._Response'InitChain msg
ResponseQuery msg -> wrap PT._Response'Query msg
ResponseBeginBlock msg -> wrap PT._Response'BeginBlock msg
ResponseCheckTx msg -> wrap PT._Response'CheckTx msg
ResponseDeliverTx msg -> wrap PT._Response'DeliverTx msg
ResponseEndBlock msg -> wrap PT._Response'EndBlock msg
ResponseCommit msg -> wrap PT._Response'Commit msg
ResponseException msg -> wrap PT._Response'Exception msg
where
wrap v msg = defMessage & PT.maybe'value ?~ v # (msg ^. _Wrapped')
-- | Application type that represents a well typed application, i.e. a
-- function from a typed `Request` to a typed `Response`.
newtype App m = App
{ unApp :: forall (t :: MessageType). Request t -> m (Response t) }
-- | Middleware is a component that sits between the server and application.
-- It can do such tasks as logging or response caching. What follows is the general
-- definition of middleware, though a middleware author should feel free to modify this.
type Middleware m = App m -> App m
-- | Transform an application from running in a custom monad to running in `IO`.
transformApp :: (forall (t :: MessageType). m (Response t) -> g (Response t)) -> App m -> App g
transformApp nat (App f) = App $ nat . f
-- | Compiles `App` down to `AppBS`
runApp :: forall m. Applicative m => App m -> LPByteStrings -> m LPByteStrings
runApp (App app) bs =
bs
& (decodeLengthPrefix >=> decodeRequests)
& either (pure . onError) (traverse onResponse)
& fmap (encodeLengthPrefix . encodeResponses)
where
onError :: DecodeError -> [PT.Response]
onError err = [toProto $ ResponseException $ Response.Exception $ cs $ DecodeError.print err]
onResponse :: PT.Request'Value -> m PT.Response
onResponse = withProto $ fmap toProto . app
-- | Encodes responses to bytestrings
encodeResponses :: [PT.Response] -> [BS.ByteString]
encodeResponses = map PL.encodeMessage
-- | Decodes bytestrings into requests
decodeRequests :: [BS.ByteString] -> Either DecodeError [PT.Request'Value]
decodeRequests = traverse $ \packet -> case PL.decodeMessage packet of
Left parseError -> Left $ DecodeError.CanNotDecodeRequest packet parseError
Right (request :: PT.Request) -> case request ^. PT.maybe'value of
Nothing -> Left $ DecodeError.NoValueInRequest packet (request ^. PL.unknownFields)
Just value -> Right $ value
| ByteString which contains multiple length prefixed ByteStrings
newtype LPByteStrings = LPByteStrings { unLPByteStrings :: BS.ByteString } deriving (Ord,Eq)
| into varlength - prefixed ByteString
encodeLengthPrefix :: [BS.ByteString] -> LPByteStrings
encodeLengthPrefix = LPByteStrings . foldMap encoder
where
encoder bytes =
let
headerN = signedInt64ToWord . fromIntegral . BS.length $ bytes
header = runBuilder $ putVarInt headerN
in
header `BS.append` bytes
| ByteString into ByteStrings
decodeLengthPrefix :: LPByteStrings -> Either DecodeError [BS.ByteString]
decodeLengthPrefix (LPByteStrings bs)
| bs == mempty = Right []
| otherwise = do
n <- first (DecodeError.ProtoLensParseError bs) $ runParser getVarInt bs
let lengthHeader = runBuilder $ putVarInt n
messageBytesWithTail <- case BS.stripPrefix lengthHeader bs of
Nothing -> Left $ DecodeError.InvalidPrefix lengthHeader bs
Just a -> Right a
let (messageBytes, remainder) = BS.splitAt (fromIntegral $ wordToSignedInt64 n) messageBytesWithTail
(messageBytes : ) <$> decodeLengthPrefix (LPByteStrings remainder)
| null | https://raw.githubusercontent.com/f-o-a-m/kepler/6c1ad7f37683f509c2f1660e3561062307d3056b/hs-abci-server/src/Network/ABCI/Server/App.hs | haskell | | Used to parametrize Request and Response types
------------------------------------------------------------------------------
Request
------------------------------------------------------------------------------
#L11-L41
Info/Query Connection
Mempool Connection
Consensus Connection
------------------------------------------------------------------------------
Response
------------------------------------------------------------------------------
| Translates type-safe 'Response' GADT to the unsafe
| Application type that represents a well typed application, i.e. a
function from a typed `Request` to a typed `Response`.
| Middleware is a component that sits between the server and application.
It can do such tasks as logging or response caching. What follows is the general
definition of middleware, though a middleware author should feel free to modify this.
| Transform an application from running in a custom monad to running in `IO`.
| Compiles `App` down to `AppBS`
| Encodes responses to bytestrings
| Decodes bytestrings into requests | module Network.ABCI.Server.App
( App(..)
, runApp
, transformApp
, withProto
, Middleware
, MessageType(..)
, demoteRequestType
, msgTypeKey
, Request(..)
, hashRequest
, Response(..)
, LPByteStrings(..)
, decodeLengthPrefix
, encodeLengthPrefix
) where
import Control.Lens ((?~), (^.))
import Control.Lens.Wrapped (Wrapped (..),
_Unwrapped')
import Control.Monad ((>=>))
import Data.Aeson (FromJSON (..),
ToJSON (..), Value (..),
object, withObject, (.:),
(.=))
import Data.Aeson.Types (Parser)
import Data.Bifunctor (first)
import qualified Data.ByteString as BS
import Data.Function ((&))
import Data.Kind (Type)
import qualified Data.ProtoLens as PL
import Data.ProtoLens.Encoding.Bytes (getVarInt, putVarInt,
runBuilder, runParser,
signedInt64ToWord,
wordToSignedInt64)
import Data.String.Conversions (cs)
import Data.Text (Text)
import Network.ABCI.Server.App.DecodeError (DecodeError)
import qualified Network.ABCI.Server.App.DecodeError as DecodeError
import qualified Network.ABCI.Types.Messages.Request as Request
import qualified Network.ABCI.Types.Messages.Response as Response
import Crypto.Hash (hashWith)
import Crypto.Hash.Algorithms (SHA256 (..))
import Data.ByteArray (convert)
import qualified Data.ByteArray.HexString as Hex
import Data.Default.Class (Default (..))
import Data.ProtoLens.Message (Message (defMessage))
import Data.ProtoLens.Prism (( # ))
import qualified Proto.Types as PT
import qualified Proto.Types_Fields as PT
data MessageType
= MTEcho
| MTFlush
| MTInfo
| MTSetOption
| MTInitChain
| MTQuery
| MTBeginBlock
| MTCheckTx
| MTDeliverTx
| MTEndBlock
| MTCommit
deriving (Eq, Ord, Enum)
msgTypeKey :: MessageType -> String
msgTypeKey m = case m of
MTEcho -> "echo"
MTFlush -> "flush"
MTInfo -> "info"
MTSetOption -> "setOption"
MTInitChain -> "initChain"
MTQuery -> "query"
MTBeginBlock -> "beginBlock"
MTCheckTx -> "checkTx"
MTDeliverTx -> "deliverTx"
MTEndBlock -> "endBlock"
MTCommit -> "commit"
demoteRequestType :: forall (t :: MessageType). Request t -> MessageType
demoteRequestType req = case req of
RequestEcho _ -> MTEcho
RequestInfo _ -> MTInfo
RequestSetOption _ -> MTSetOption
RequestQuery _ -> MTQuery
RequestCheckTx _ -> MTCheckTx
RequestFlush _ -> MTFlush
RequestInitChain _ -> MTInitChain
RequestBeginBlock _ -> MTBeginBlock
RequestDeliverTx _ -> MTDeliverTx
RequestEndBlock _ -> MTEndBlock
RequestCommit _ -> MTCommit
reqParseJSON :: forall t inner. FromJSON inner => MessageType -> (inner -> Request t) -> Value -> Parser (Request t)
reqParseJSON msgType ctr = withObject ("req:" <> expectedType) $ \v -> do
actualType <- v .: "type"
if actualType == expectedType
then ctr <$> v .: "message"
else fail $ "expected `type` to equal: " <> show expectedType <> ", but got: " <> show actualType
where
expectedType = msgTypeKey msgType
resParseJSON :: FromJSON inner => MessageType -> (inner -> Response t) -> Value -> Parser (Response t)
resParseJSON msgType ctr = withObject ("res:" <> expectedType) $ \v -> do
actualType <- v .: "type"
if actualType == "exception"
then ResponseException <$> v .: "message"
else if actualType == expectedType
then ctr <$> v .: "message"
else fail $ "expected `type` to equal: " <> show expectedType <> ", but got: " <> show actualType
where
expectedType = msgTypeKey msgType
reqResToJSON :: ToJSON inner => MessageType -> inner -> Value
reqResToJSON msgType message = reqResToJSON' (cs $ msgTypeKey msgType) message
reqResToJSON' :: ToJSON inner => Text -> inner -> Value
reqResToJSON' msgType message = object
[ "type" .= String msgType, "message" .= toJSON message]
Note : that there are 3 type of connection made by tendermint to the ABCI application :
* Info / Query Connection , sends only : Echo , Info and SetOption requests
* , sends only : CheckTx and Flush requests
* Consensus Connection , InitChain , : BeginBlock , DeliverTx , EndBlock and Commit requests
data Request (m :: MessageType) :: Type where
RequestEcho :: Request.Echo -> Request 'MTEcho
RequestInfo :: Request.Info -> Request 'MTInfo
RequestSetOption :: Request.SetOption -> Request 'MTSetOption
RequestQuery :: Request.Query -> Request 'MTQuery
RequestCheckTx :: Request.CheckTx -> Request 'MTCheckTx
RequestFlush :: Request.Flush -> Request 'MTFlush
RequestInitChain :: Request.InitChain -> Request 'MTInitChain
RequestBeginBlock :: Request.BeginBlock -> Request 'MTBeginBlock
RequestDeliverTx :: Request.DeliverTx -> Request 'MTDeliverTx
RequestEndBlock :: Request.EndBlock -> Request 'MTEndBlock
RequestCommit :: Request.Commit -> Request 'MTCommit
instance ToJSON (Request (t :: MessageType)) where
toJSON (RequestEcho v) = reqResToJSON MTEcho v
toJSON (RequestInfo v) = reqResToJSON MTInfo v
toJSON (RequestSetOption v) = reqResToJSON MTSetOption v
toJSON (RequestQuery v) = reqResToJSON MTQuery v
toJSON (RequestCheckTx v) = reqResToJSON MTCheckTx v
toJSON (RequestFlush v) = reqResToJSON MTFlush v
toJSON (RequestInitChain v) = reqResToJSON MTInitChain v
toJSON (RequestBeginBlock v) = reqResToJSON MTBeginBlock v
toJSON (RequestDeliverTx v) = reqResToJSON MTDeliverTx v
toJSON (RequestEndBlock v) = reqResToJSON MTEndBlock v
toJSON (RequestCommit v) = reqResToJSON MTCommit v
instance FromJSON (Request 'MTEcho) where parseJSON = reqParseJSON MTEcho RequestEcho
instance FromJSON (Request 'MTInfo) where parseJSON = reqParseJSON MTInfo RequestInfo
instance FromJSON (Request 'MTSetOption) where parseJSON = reqParseJSON MTSetOption RequestSetOption
instance FromJSON (Request 'MTQuery) where parseJSON = reqParseJSON MTQuery RequestQuery
instance FromJSON (Request 'MTCheckTx) where parseJSON = reqParseJSON MTCheckTx RequestCheckTx
instance FromJSON (Request 'MTFlush) where parseJSON = reqParseJSON MTFlush RequestFlush
instance FromJSON (Request 'MTInitChain) where parseJSON = reqParseJSON MTInitChain RequestInitChain
instance FromJSON (Request 'MTBeginBlock) where parseJSON = reqParseJSON MTBeginBlock RequestBeginBlock
instance FromJSON (Request 'MTDeliverTx) where parseJSON = reqParseJSON MTDeliverTx RequestDeliverTx
instance FromJSON (Request 'MTEndBlock) where parseJSON = reqParseJSON MTEndBlock RequestEndBlock
instance FromJSON (Request 'MTCommit) where parseJSON = reqParseJSON MTCommit RequestCommit
hashRequest
:: forall (t :: MessageType).
Request t
-> Hex.HexString
hashRequest req =
let requestBytes :: BS.ByteString = case req of
RequestEcho v -> PL.encodeMessage $ v ^. _Wrapped'
RequestFlush v -> PL.encodeMessage $ v ^. _Wrapped'
RequestInfo v -> PL.encodeMessage $ v ^. _Wrapped'
RequestSetOption v -> PL.encodeMessage $ v ^. _Wrapped'
RequestInitChain v -> PL.encodeMessage $ v ^. _Wrapped'
RequestQuery v -> PL.encodeMessage $ v ^. _Wrapped'
RequestBeginBlock v -> PL.encodeMessage $ v ^. _Wrapped'
RequestCheckTx v -> PL.encodeMessage $ v ^. _Wrapped'
RequestDeliverTx v -> PL.encodeMessage $ v ^. _Wrapped'
RequestEndBlock v -> PL.encodeMessage $ v ^. _Wrapped'
RequestCommit v -> PL.encodeMessage $ v ^. _Wrapped'
in Hex.fromBytes @BS.ByteString . convert $ hashWith SHA256 requestBytes
withProto
:: (forall (t :: MessageType). Request t -> a)
-> PT.Request'Value
-> a
withProto f value = case value of
PT.Request'Echo echo -> f $ RequestEcho $ echo ^. _Unwrapped'
PT.Request'Flush flush -> f $ RequestFlush $ flush ^. _Unwrapped'
PT.Request'Info info -> f $ RequestInfo $ info ^. _Unwrapped'
PT.Request'SetOption setOption -> f $ RequestSetOption $ setOption ^. _Unwrapped'
PT.Request'InitChain initChain -> f $ RequestInitChain $ initChain ^. _Unwrapped'
PT.Request'Query query -> f $ RequestQuery $ query ^. _Unwrapped'
PT.Request'BeginBlock beginBlock -> f $ RequestBeginBlock $ beginBlock ^. _Unwrapped'
PT.Request'CheckTx checkTx -> f $ RequestCheckTx $ checkTx ^. _Unwrapped'
PT.Request'DeliverTx deliverTx -> f $ RequestDeliverTx $ deliverTx ^. _Unwrapped'
PT.Request'EndBlock endBlock -> f $ RequestEndBlock $ endBlock ^. _Unwrapped'
PT.Request'Commit commit -> f $ RequestCommit $ commit ^. _Unwrapped'
data Response (m :: MessageType) :: Type where
ResponseEcho :: Response.Echo -> Response 'MTEcho
ResponseFlush :: Response.Flush -> Response 'MTFlush
ResponseInfo :: Response.Info -> Response 'MTInfo
ResponseSetOption :: Response.SetOption -> Response 'MTSetOption
ResponseInitChain :: Response.InitChain -> Response 'MTInitChain
ResponseQuery :: Response.Query -> Response 'MTQuery
ResponseBeginBlock :: Response.BeginBlock -> Response 'MTBeginBlock
ResponseCheckTx :: Response.CheckTx -> Response 'MTCheckTx
ResponseDeliverTx :: Response.DeliverTx -> Response 'MTDeliverTx
ResponseEndBlock :: Response.EndBlock -> Response 'MTEndBlock
ResponseCommit :: Response.Commit -> Response 'MTCommit
ResponseException :: forall (m :: MessageType) . Response.Exception -> Response m
instance ToJSON (Response (t :: MessageType)) where
toJSON (ResponseEcho v) = reqResToJSON MTEcho v
toJSON (ResponseFlush v) = reqResToJSON MTFlush v
toJSON (ResponseInfo v) = reqResToJSON MTInfo v
toJSON (ResponseSetOption v) = reqResToJSON MTSetOption v
toJSON (ResponseInitChain v) = reqResToJSON MTInitChain v
toJSON (ResponseQuery v) = reqResToJSON MTQuery v
toJSON (ResponseBeginBlock v) = reqResToJSON MTBeginBlock v
toJSON (ResponseCheckTx v) = reqResToJSON MTCheckTx v
toJSON (ResponseDeliverTx v) = reqResToJSON MTDeliverTx v
toJSON (ResponseEndBlock v) = reqResToJSON MTEndBlock v
toJSON (ResponseCommit v) = reqResToJSON MTCommit v
toJSON (ResponseException v) = reqResToJSON' "exception" v
instance FromJSON (Response 'MTEcho) where parseJSON = resParseJSON MTEcho ResponseEcho
instance FromJSON (Response 'MTFlush) where parseJSON = resParseJSON MTFlush ResponseFlush
instance FromJSON (Response 'MTInfo) where parseJSON = resParseJSON MTInfo ResponseInfo
instance FromJSON (Response 'MTSetOption) where parseJSON = resParseJSON MTSetOption ResponseSetOption
instance FromJSON (Response 'MTInitChain) where parseJSON = resParseJSON MTInitChain ResponseInitChain
instance FromJSON (Response 'MTQuery) where parseJSON = resParseJSON MTQuery ResponseQuery
instance FromJSON (Response 'MTBeginBlock) where parseJSON = resParseJSON MTBeginBlock ResponseBeginBlock
instance FromJSON (Response 'MTCheckTx) where parseJSON = resParseJSON MTCheckTx ResponseCheckTx
instance FromJSON (Response 'MTDeliverTx) where parseJSON = resParseJSON MTDeliverTx ResponseDeliverTx
instance FromJSON (Response 'MTEndBlock) where parseJSON = resParseJSON MTEndBlock ResponseEndBlock
instance FromJSON (Response 'MTCommit) where parseJSON = resParseJSON MTCommit ResponseCommit
instance Default (Response 'MTEcho) where def = ResponseEcho def
instance Default (Response 'MTFlush) where def = ResponseFlush def
instance Default (Response 'MTInfo) where def = ResponseInfo def
instance Default (Response 'MTSetOption) where def = ResponseSetOption def
instance Default (Response 'MTInitChain) where def = ResponseInitChain def
instance Default (Response 'MTQuery) where def = ResponseQuery def
instance Default (Response 'MTBeginBlock) where def = ResponseBeginBlock def
instance Default (Response 'MTCheckTx) where def = ResponseCheckTx def
instance Default (Response 'MTDeliverTx) where def = ResponseDeliverTx def
instance Default (Response 'MTEndBlock) where def = ResponseEndBlock def
instance Default (Response 'MTCommit) where def = ResponseCommit def
auto - generated ' Proto . Response '
toProto :: Response t -> PT.Response
toProto r = case r of
ResponseEcho msg -> wrap PT._Response'Echo msg
ResponseFlush msg -> wrap PT._Response'Flush msg
ResponseInfo msg -> wrap PT._Response'Info msg
ResponseSetOption msg -> wrap PT._Response'SetOption msg
ResponseInitChain msg -> wrap PT._Response'InitChain msg
ResponseQuery msg -> wrap PT._Response'Query msg
ResponseBeginBlock msg -> wrap PT._Response'BeginBlock msg
ResponseCheckTx msg -> wrap PT._Response'CheckTx msg
ResponseDeliverTx msg -> wrap PT._Response'DeliverTx msg
ResponseEndBlock msg -> wrap PT._Response'EndBlock msg
ResponseCommit msg -> wrap PT._Response'Commit msg
ResponseException msg -> wrap PT._Response'Exception msg
where
wrap v msg = defMessage & PT.maybe'value ?~ v # (msg ^. _Wrapped')
newtype App m = App
{ unApp :: forall (t :: MessageType). Request t -> m (Response t) }
type Middleware m = App m -> App m
transformApp :: (forall (t :: MessageType). m (Response t) -> g (Response t)) -> App m -> App g
transformApp nat (App f) = App $ nat . f
runApp :: forall m. Applicative m => App m -> LPByteStrings -> m LPByteStrings
runApp (App app) bs =
bs
& (decodeLengthPrefix >=> decodeRequests)
& either (pure . onError) (traverse onResponse)
& fmap (encodeLengthPrefix . encodeResponses)
where
onError :: DecodeError -> [PT.Response]
onError err = [toProto $ ResponseException $ Response.Exception $ cs $ DecodeError.print err]
onResponse :: PT.Request'Value -> m PT.Response
onResponse = withProto $ fmap toProto . app
encodeResponses :: [PT.Response] -> [BS.ByteString]
encodeResponses = map PL.encodeMessage
decodeRequests :: [BS.ByteString] -> Either DecodeError [PT.Request'Value]
decodeRequests = traverse $ \packet -> case PL.decodeMessage packet of
Left parseError -> Left $ DecodeError.CanNotDecodeRequest packet parseError
Right (request :: PT.Request) -> case request ^. PT.maybe'value of
Nothing -> Left $ DecodeError.NoValueInRequest packet (request ^. PL.unknownFields)
Just value -> Right $ value
| ByteString which contains multiple length prefixed ByteStrings
newtype LPByteStrings = LPByteStrings { unLPByteStrings :: BS.ByteString } deriving (Ord,Eq)
| into varlength - prefixed ByteString
encodeLengthPrefix :: [BS.ByteString] -> LPByteStrings
encodeLengthPrefix = LPByteStrings . foldMap encoder
where
encoder bytes =
let
headerN = signedInt64ToWord . fromIntegral . BS.length $ bytes
header = runBuilder $ putVarInt headerN
in
header `BS.append` bytes
| ByteString into ByteStrings
decodeLengthPrefix :: LPByteStrings -> Either DecodeError [BS.ByteString]
decodeLengthPrefix (LPByteStrings bs)
| bs == mempty = Right []
| otherwise = do
n <- first (DecodeError.ProtoLensParseError bs) $ runParser getVarInt bs
let lengthHeader = runBuilder $ putVarInt n
messageBytesWithTail <- case BS.stripPrefix lengthHeader bs of
Nothing -> Left $ DecodeError.InvalidPrefix lengthHeader bs
Just a -> Right a
let (messageBytes, remainder) = BS.splitAt (fromIntegral $ wordToSignedInt64 n) messageBytesWithTail
(messageBytes : ) <$> decodeLengthPrefix (LPByteStrings remainder)
|
f410c241c186d568dc173d800d203ff8be1612ab31be0bfc3419500ffce56a28 | hercules-ci/hercules-ci-agent | AttributeIFDEvent.hs | {-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DeriveAnyClass #-}
module Hercules.API.Agent.Evaluate.EvaluateEvent.AttributeIFDEvent where
import Hercules.API.Prelude
data AttributeIFDEvent = AttributeIFDEvent
{ expressionPath :: [Text],
derivationPath :: Text,
derivationOutput :: Text,
done :: Bool,
index :: Int
}
deriving (Generic, Show, Eq, NFData, FromJSON, ToJSON)
| null | https://raw.githubusercontent.com/hercules-ci/hercules-ci-agent/2437ff55720063dcbb9f85a63c40e2589867a29b/hercules-ci-api-agent/src/Hercules/API/Agent/Evaluate/EvaluateEvent/AttributeIFDEvent.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE DeriveAnyClass # |
module Hercules.API.Agent.Evaluate.EvaluateEvent.AttributeIFDEvent where
import Hercules.API.Prelude
data AttributeIFDEvent = AttributeIFDEvent
{ expressionPath :: [Text],
derivationPath :: Text,
derivationOutput :: Text,
done :: Bool,
index :: Int
}
deriving (Generic, Show, Eq, NFData, FromJSON, ToJSON)
|
8cfaa08808508d183a484275362d1e97e61f4079b6301c6a612078bfe88f04e9 | Bogdanp/deta | info.rkt | #lang info
(define license 'BSD-3-Clause)
(define version "0.12")
(define collection "deta")
(define deps '("base"
"db-lib"
"gregor-lib"))
(define build-deps '("at-exp-lib"))
| null | https://raw.githubusercontent.com/Bogdanp/deta/fc2df774c8fa41a83e46dc017f7a7fbf90e137f9/deta-lib/info.rkt | racket | #lang info
(define license 'BSD-3-Clause)
(define version "0.12")
(define collection "deta")
(define deps '("base"
"db-lib"
"gregor-lib"))
(define build-deps '("at-exp-lib"))
| |
6dbd755da77f33e8d83142cb41f6e89178c054d08acc261acdb8ec2f7cf039c6 | peterholko/pax_server | test.erl | Author :
Created : Apr 2 , 2009
%% Description: TODO: Add description to test
-module(test).
%%
%% Include files
%%
-include("packet.hrl").
%%
%% Exported Functions
%%
-export([run/1, market/0]).
%%
%% API Functions
%%
run(Account) ->
spawn(fun() -> connect(Account) end).
connect(Account) ->
{ok,Socket} = gen_tcp:connect("localhost",2345,[binary,{active, true},{nodelay, true}, {keepalive, true}, {packet,0}]),
t:start(Socket),
t:login(Account),
loop(Socket).
market() ->
t:add_claim(),
timer:sleep(1000),
t:build_farm(),
timer:sleep(1000),
t:assign_task().
%%
%% Local Functions
%%
loop(Socket) ->
receive
{tcp, Socket, Bin} ->
io:fwrite("Test - Bin: ~w~n", [Bin]),
case packet:read(Bin) of
#player_id{id = PlayerId} ->
io:fwrite("PlayerId: ~w~n", [PlayerId]),
ok = gen_tcp:send(Socket, <<?CMD_CLIENTREADY>>),
loop(Socket);
#info_kingdom{id = Id, name = Name, gold = Gold} ->
io:fwrite("KingdomId: ~w Name: ~w Gold: ~w~n", [Id, Name, Gold]),
loop(Socket);
#map{tiles = Tiles } ->
io:fwrite("Tiles: ~w~n", [Tiles]),
loop(Socket);
#perception{entities = Entities, tiles = Tiles} ->
io:fwrite("Perception: ~w ~w~n",[Entities, Tiles]),
loop(Socket);
#info_army{id = Id, units = Units} ->
io:fwrite("Info Army: ~w ~w~n", [Id, Units]),
loop(Socket);
#info_city{id = Id,
buildings = Buildings,
units = Units,
claims = Claims,
improvements = Improvements,
assignments = Assignments,
items = Items,
populations = Populations
} ->
io:fwrite("Info City: ~w~n ~w~n ~w~n ~w~n ~w~n ~w~n ~w~n ~w~n",
[Id, Buildings, Units, Claims, Assignments, Improvements, Items, Populations]),
loop(Socket);
#battle_info{battle_id = BattleId, armies = Armies} ->
io:fwrite("Battle Info: ~w ~w~n", [BattleId, Armies]),
loop(Socket);
#battle_damage{battle_id = BattleId, source_id = SourceId, target_id = TargetId, damage = Damage} ->
io:fwrite("Battle Damage: ~w ~w ~w ~w~n", [BattleId, SourceId, TargetId, Damage]),
loop(Socket);
_Any ->
io:fwrite("Do not recognize command.~nBin: ~w~n", [Bin]),
loop(Socket)
end;
{error, closed} ->
io:fwrite("Connection closed.");
_Any ->
io:fwrite("Epic failure.")
end.
| null | https://raw.githubusercontent.com/peterholko/pax_server/62b2ec1fae195ff915d19af06e56a7c4567fd4b8/src/test.erl | erlang | Description: TODO: Add description to test
Include files
Exported Functions
API Functions
Local Functions
| Author :
Created : Apr 2 , 2009
-module(test).
-include("packet.hrl").
-export([run/1, market/0]).
run(Account) ->
spawn(fun() -> connect(Account) end).
connect(Account) ->
{ok,Socket} = gen_tcp:connect("localhost",2345,[binary,{active, true},{nodelay, true}, {keepalive, true}, {packet,0}]),
t:start(Socket),
t:login(Account),
loop(Socket).
market() ->
t:add_claim(),
timer:sleep(1000),
t:build_farm(),
timer:sleep(1000),
t:assign_task().
loop(Socket) ->
receive
{tcp, Socket, Bin} ->
io:fwrite("Test - Bin: ~w~n", [Bin]),
case packet:read(Bin) of
#player_id{id = PlayerId} ->
io:fwrite("PlayerId: ~w~n", [PlayerId]),
ok = gen_tcp:send(Socket, <<?CMD_CLIENTREADY>>),
loop(Socket);
#info_kingdom{id = Id, name = Name, gold = Gold} ->
io:fwrite("KingdomId: ~w Name: ~w Gold: ~w~n", [Id, Name, Gold]),
loop(Socket);
#map{tiles = Tiles } ->
io:fwrite("Tiles: ~w~n", [Tiles]),
loop(Socket);
#perception{entities = Entities, tiles = Tiles} ->
io:fwrite("Perception: ~w ~w~n",[Entities, Tiles]),
loop(Socket);
#info_army{id = Id, units = Units} ->
io:fwrite("Info Army: ~w ~w~n", [Id, Units]),
loop(Socket);
#info_city{id = Id,
buildings = Buildings,
units = Units,
claims = Claims,
improvements = Improvements,
assignments = Assignments,
items = Items,
populations = Populations
} ->
io:fwrite("Info City: ~w~n ~w~n ~w~n ~w~n ~w~n ~w~n ~w~n ~w~n",
[Id, Buildings, Units, Claims, Assignments, Improvements, Items, Populations]),
loop(Socket);
#battle_info{battle_id = BattleId, armies = Armies} ->
io:fwrite("Battle Info: ~w ~w~n", [BattleId, Armies]),
loop(Socket);
#battle_damage{battle_id = BattleId, source_id = SourceId, target_id = TargetId, damage = Damage} ->
io:fwrite("Battle Damage: ~w ~w ~w ~w~n", [BattleId, SourceId, TargetId, Damage]),
loop(Socket);
_Any ->
io:fwrite("Do not recognize command.~nBin: ~w~n", [Bin]),
loop(Socket)
end;
{error, closed} ->
io:fwrite("Connection closed.");
_Any ->
io:fwrite("Epic failure.")
end.
|
b594d4a6f3ca14afb1ba88afb7c6539fde42acf07bf02bb3063d51e30e923f44 | racket/syntax-color | info.rkt | #lang info
(define collection 'multi)
(define build-deps '("gui-doc"
"scribble-doc"
"gui-lib"
"scribble-lib"
"racket-doc"
"syntax-color-lib"))
(define deps '("base"))
(define update-implies '("syntax-color-lib"))
(define pkg-desc "documentation part of \"syntax-color\"")
(define pkg-authors '(mflatt))
(define license
'(Apache-2.0 OR MIT))
| null | https://raw.githubusercontent.com/racket/syntax-color/02c5faaf6cb3f08ef07069763755e373ef11cd50/syntax-color-doc/info.rkt | racket | #lang info
(define collection 'multi)
(define build-deps '("gui-doc"
"scribble-doc"
"gui-lib"
"scribble-lib"
"racket-doc"
"syntax-color-lib"))
(define deps '("base"))
(define update-implies '("syntax-color-lib"))
(define pkg-desc "documentation part of \"syntax-color\"")
(define pkg-authors '(mflatt))
(define license
'(Apache-2.0 OR MIT))
| |
80b442406abd2ff0670c391abe06f8b24fdcf515f006fcc3ba2ee1a114d72b93 | binaryage/chromex | test_utils.cljs | (ns chromex.test-utils
(:require-macros [chromex.test-utils :refer [test-mode]]))
(def advanced-mode? (= (test-mode) "advanced"))
| null | https://raw.githubusercontent.com/binaryage/chromex/33834ba5dd4f4238a3c51f99caa0416f30c308c5/test/src/chromex/test_utils.cljs | clojure | (ns chromex.test-utils
(:require-macros [chromex.test-utils :refer [test-mode]]))
(def advanced-mode? (= (test-mode) "advanced"))
| |
5f2d03de86734e85323e6759beb20c6eff6b2c4e989442d851e331c403f1cd6b | coq/coq | configwin_ihm.ml | (*********************************************************************************)
Cameleon
(* *)
Copyright ( C ) 2005 Institut National de Recherche en Informatique et
(* en Automatique. All rights reserved. *)
(* *)
(* This program is free software; you can redistribute it and/or modify *)
it under the terms of the GNU Library General Public License as
published by the Free Software Foundation ; either version 2 of the
(* License, or any later version. *)
(* *)
(* This program is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
GNU Library General Public License for more details .
(* *)
You should have received a copy of the GNU Library 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
(* *)
(* Contact: *)
(* *)
(*********************************************************************************)
* This module contains the gui functions of Configwin .
open Configwin_types
let set_help_tip wev = function
| None -> ()
| Some help -> GtkBase.Widget.Tooltip.set_text wev#as_widget help
let select_arch m m_osx =
if Coq_config.arch = "Darwin" then m_osx else m
(* How the modifiers are named in the preference box *)
let modifiers_to_string m =
let rec iter m s =
match m with
[] -> s
| c :: m ->
iter m ((
match c with
`CONTROL -> "<ctrl>"
| `SHIFT -> "<shft>"
| `LOCK -> "<lock>"
| `META -> select_arch "<meta>" "<cmd>"
| `MOD1 -> "<alt>"
| `MOD2 -> "<mod2>"
| `MOD3 -> "<mod3>"
| `MOD4 -> "<mod4>"
| `MOD5 -> "<mod5>"
| _ -> raise Not_found
) ^ s)
in
iter m ""
class type widget =
object
method box : GObj.widget
method apply : unit -> unit
end
let debug = false
let dbg s = if debug then Minilib.log s else ()
( * * This class builds a frame with a clist and two buttons :
one to add items and one to remove the selected items .
The class takes in parameter a function used to add items and
a string list ref which is used to store the content of the clist .
At last , a title for the frame is also in parameter , so that
each instance of the class creates a frame .
(** This class builds a frame with a clist and two buttons :
one to add items and one to remove the selected items.
The class takes in parameter a function used to add items and
a string list ref which is used to store the content of the clist.
At last, a title for the frame is also in parameter, so that
each instance of the class creates a frame. *)
class ['a] list_selection_box
(listref : 'a list ref)
titles_opt
help_opt
f_edit_opt
f_strings
f_color
(eq : 'a -> 'a -> bool)
add_function title editable
=
let _ = dbg "list_selection_box" in
let wev = GBin.event_box () in
let wf = GBin.frame ~label: title ~packing: wev#add () in
let hbox = GPack.hbox ~packing: wf#add () in
the scroll window and the
let wscroll = GBin.scrolled_window
~vpolicy: `AUTOMATIC
~hpolicy: `AUTOMATIC
~packing: (hbox#pack ~expand: true) ()
in
let wlist = match titles_opt with
None ->
GList.clist ~selection_mode: `MULTIPLE
~titles_show: false
~packing: wscroll#add ()
| Some l ->
GList.clist ~selection_mode: `MULTIPLE
~titles: l
~titles_show: true
~packing: wscroll#add ()
in
let _ = set_help_tip wev help_opt in
the vbox for the buttons
let vbox_buttons = GPack.vbox () in
let _ =
if editable then
let _ = hbox#pack ~expand: false vbox_buttons#coerce in
()
else
()
in
let _ = dbg "list_selection_box: wb_add" in
let wb_add = GButton.button
~label: Configwin_messages.mAdd
~packing: (vbox_buttons#pack ~expand:false ~padding:2)
()
in
let wb_edit = GButton.button
~label: Configwin_messages.mEdit
()
in
let _ = match f_edit_opt with
None -> ()
| Some _ -> vbox_buttons#pack ~expand:false ~padding:2 wb_edit#coerce
in
let wb_up = GButton.button
~label: Configwin_messages.mUp
~packing: (vbox_buttons#pack ~expand:false ~padding:2)
()
in
let wb_remove = GButton.button
~label: Configwin_messages.mRemove
~packing: (vbox_buttons#pack ~expand:false ~padding:2)
()
in
let _ = dbg "list_selection_box: object(self)" in
object (self)
(** the list of selected rows *)
val mutable list_select = []
(** This method returns the frame created. *)
method box = wev
method update l =
(* set the new list in the provided listref *)
listref := l;
insert the elements in the
wlist#freeze ();
wlist#clear ();
List.iter
(fun ele ->
ignore (wlist#append (f_strings ele));
match f_color ele with
None -> ()
| Some c ->
try wlist#set_row ~foreground: (`NAME c) (wlist#rows - 1)
with _ -> ()
)
!listref;
(match titles_opt with
None -> wlist#columns_autosize ()
| Some _ -> GToolbox.autosize_clist wlist);
wlist#thaw ();
(* the list of selectd elements is now empty *)
list_select <- []
(** Move up the selected rows. *)
method up_selected =
let rec iter n selrows l =
match selrows with
[] -> (l, [])
| m :: qrows ->
match l with
[] -> ([],[])
| [_] -> (l,[])
| e1 :: e2 :: q when m = n + 1 ->
let newl, newrows = iter (n+1) qrows (e1 :: q) in
(e2 :: newl, n :: newrows)
| e1 :: q ->
let newl, newrows = iter (n+1) selrows q in
(e1 :: newl, newrows)
in
let sorted_select = List.sort compare list_select in
let new_list, new_rows = iter 0 sorted_select !listref in
self#update new_list;
List.iter (fun n -> wlist#select n 0) new_rows
* Make the user edit the first selected row .
method edit_selected f_edit =
let sorted_select = List.sort compare list_select in
match sorted_select with
[] -> ()
| n :: _ ->
try
let ele = List.nth !listref n in
let ele2 = f_edit ele in
let rec iter m = function
[] -> []
| e :: q ->
if n = m then
ele2 :: q
else
e :: (iter (m+1) q)
in
self#update (iter 0 !listref);
wlist#select n 0
with
Not_found ->
()
initializer
(* create the functions called when the buttons are clicked *)
let f_add () =
(* get the files to add with the function provided *)
let l = add_function () in
(* remove from the list the ones which are already in
the listref, using the eq predicate *)
let l2 = List.fold_left
(fun acc -> fun ele ->
if List.exists (eq ele) acc then
acc
else
acc @ [ele])
!listref
l
in
self#update l2
in
let f_remove () =
remove the selected items from the listref and the
let rec iter n = function
[] -> []
| h :: q ->
if List.mem n list_select then
iter (n+1) q
else
h :: (iter (n+1) q)
in
let new_list = iter 0 !listref in
self#update new_list
in
let _ = dbg "list_selection_box: connecting wb_add" in
(* connect the functions to the buttons *)
ignore (wb_add#connect#clicked ~callback:f_add);
let _ = dbg "list_selection_box: connecting wb_remove" in
ignore (wb_remove#connect#clicked ~callback:f_remove);
let _ = dbg "list_selection_box: connecting wb_up" in
ignore (wb_up#connect#clicked ~callback:(fun () -> self#up_selected));
(
match f_edit_opt with
None -> ()
| Some f ->
let _ = dbg "list_selection_box: connecting wb_edit" in
ignore (wb_edit#connect#clicked ~callback:(fun () -> self#edit_selected f))
);
connect the selection and deselection of items in the
let f_select ~row ~column ~event =
try
list_select <- row :: list_select
with
Failure _ ->
()
in
let f_unselect ~row ~column ~event =
try
let new_list_select = List.filter (fun n -> n <> row) list_select in
list_select <- new_list_select
with
Failure _ ->
()
in
(* connect the select and deselect events *)
let _ = dbg "list_selection_box: connecting select_row" in
ignore(wlist#connect#select_row ~callback:f_select);
let _ = dbg "list_selection_box: connecting unselect_row" in
ignore(wlist#connect#unselect_row ~callback:f_unselect);
(* initialize the clist with the listref *)
self#update !listref
end;;
*)
(** This class is used to build a box for a string parameter.*)
class string_param_box param =
let _ = dbg "string_param_box" in
let hbox = GPack.hbox () in
let wev = GBin.event_box ~packing: (hbox#pack ~expand: false ~padding: 2) () in
let _wl = GMisc.label ~text: param.string_label ~packing: wev#add () in
let we = GEdit.entry
~editable: param.string_editable
~packing: (hbox#pack ~expand: param.string_expand ~padding: 2)
()
in
let _ = set_help_tip wev param.string_help in
let _ = we#set_text (param.string_to_string param.string_value) in
object (self)
(** This method returns the main box ready to be packed. *)
method box = hbox#coerce
(** This method applies the new value of the parameter. *)
method apply =
let new_value = param.string_of_string we#text in
if new_value <> param.string_value then
let _ = param.string_f_apply new_value in
param.string_value <- new_value
else
()
end ;;
(** This class is used to build a box for a combo parameter.*)
class combo_param_box param =
let _ = dbg "combo_param_box" in
let hbox = GPack.hbox () in
let wev = GBin.event_box ~packing: (hbox#pack ~expand: false ~padding: 2) () in
let _wl = GMisc.label ~text: param.combo_label ~packing: wev#add () in
let _ = set_help_tip wev param.combo_help in
let get_value = if not param.combo_new_allowed then
let wc = GEdit.combo_box_text
~strings: param.combo_choices
?active:(let rec aux i = function
|[] -> None
|h::_ when h = param.combo_value -> Some i
|_::t -> aux (succ i) t
in aux 0 param.combo_choices)
~packing: (hbox#pack ~expand: param.combo_expand ~padding: 2)
()
in
fun () -> match GEdit.text_combo_get_active wc with |None -> "" |Some s -> s
else
let (wc,_) = GEdit.combo_box_entry_text
~strings: param.combo_choices
~packing: (hbox#pack ~expand: param.combo_expand ~padding: 2)
()
in
let _ = wc#entry#set_editable param.combo_editable in
let _ = wc#entry#set_text param.combo_value in
fun () -> wc#entry#text
in
object (self)
(** This method returns the main box ready to be packed. *)
method box = hbox#coerce
(** This method applies the new value of the parameter. *)
method apply =
let new_value = get_value () in
if new_value <> param.combo_value then
let _ = param.combo_f_apply new_value in
param.combo_value <- new_value
else
()
end ;;
(** Class used to pack a custom box. *)
class custom_param_box param =
let _ = dbg "custom_param_box" in
let top =
match param.custom_framed with
None -> param.custom_box#coerce
| Some l ->
let wf = GBin.frame ~label: l () in
wf#add param.custom_box#coerce;
wf#coerce
in
object (self)
method box = top
method apply = param.custom_f_apply ()
end
(** This class is used to build a box for a text parameter.*)
class text_param_box param =
let _ = dbg "text_param_box" in
let wf = GBin.frame ~label: param.string_label ~height: 100 () in
let wev = GBin.event_box ~packing: wf#add () in
let wscroll = GBin.scrolled_window
~vpolicy: `AUTOMATIC
~hpolicy: `AUTOMATIC
~packing: wev#add ()
in
let wview = GText.view
~editable: param.string_editable
~packing: wscroll#add
()
in
let _ = set_help_tip wev param.string_help in
let _ = dbg "text_param_box: buffer creation" in
let buffer = GText.buffer () in
let _ = wview#set_buffer buffer in
let _ = buffer#insert (param.string_to_string param.string_value) in
let _ = dbg "text_param_box: object(self)" in
object (self)
val wview = wview
(** This method returns the main box ready to be packed. *)
method box = wf#coerce
(** This method applies the new value of the parameter. *)
method apply =
let v = param.string_of_string (buffer#get_text ()) in
if v <> param.string_value then
(
dbg "apply new value!";
let _ = param.string_f_apply v in
param.string_value <- v
)
else
()
end ;;
(** This class is used to build a box for a boolean parameter.*)
class bool_param_box param =
let _ = dbg "bool_param_box" in
let wchk = GButton.check_button
~label: param.bool_label
()
in
let _ = set_help_tip wchk param.bool_help in
let _ = wchk#set_active param.bool_value in
let _ = wchk#misc#set_sensitive param.bool_editable in
object (self)
(** This method returns the check button ready to be packed. *)
method box = wchk#coerce
(** This method applies the new value of the parameter. *)
method apply =
let new_value = wchk#active in
if new_value <> param.bool_value then
let _ = param.bool_f_apply new_value in
param.bool_value <- new_value
else
()
end ;;
class modifiers_param_box param =
let hbox = GPack.hbox () in
let wev = GBin.event_box ~packing: (hbox#pack ~expand:true ~fill:true ~padding: 2) () in
let _wl = GMisc.label ~text: param.md_label ~packing: wev#add () in
let value = ref param.md_value in
let _ = List.map (fun modifier ->
let but = GButton.toggle_button
~label:(modifiers_to_string [modifier])
~active:(List.mem modifier param.md_value)
~packing:(hbox#pack ~expand:false) () in
ignore (but#connect#toggled
~callback:(fun _ -> if but#active then value := modifier::!value
else value := List.filter ((<>) modifier) !value)))
param.md_allow
in
let _ = set_help_tip wev param.md_help in
object (self)
(** This method returns the main box ready to be packed. *)
method box = hbox#coerce
(** This method applies the new value of the parameter. *)
method apply =
let new_value = !value in
if new_value <> param.md_value then
let _ = param.md_f_apply new_value in
param.md_value <- new_value
else
()
end ;;
(*
(** This class is used to build a box for a parameter whose values are a list.*)
class ['a] list_param_box (param : 'a list_param) =
let _ = dbg "list_param_box" in
let listref = ref param.list_value in
let frame_selection = new list_selection_box
listref
param.list_titles
param.list_help
param.list_f_edit
param.list_strings
param.list_color
param.list_eq
param.list_f_add param.list_label param.list_editable
tt
in
object (self)
(** This method returns the main box ready to be packed. *)
method box = frame_selection#box#coerce
(** This method applies the new value of the parameter. *)
method apply =
param.list_f_apply !listref ;
param.list_value <- !listref
end ;;
*)
(** This class creates a configuration box from a configuration structure *)
class configuration_box conf_struct =
let main_box = GPack.hbox () in
let columns = new GTree.column_list in
let icon_col = columns#add GtkStock.conv in
let label_col = columns#add Gobject.Data.string in
let box_col = columns#add Gobject.Data.caml in
let () = columns#lock () in
let pane = GPack.paned `HORIZONTAL ~packing:main_box#add () in
(* Tree view part *)
let scroll = GBin.scrolled_window ~hpolicy:`NEVER ~packing:pane#pack1 () in
let tree = GTree.tree_store columns in
let view = GTree.view ~model:tree ~headers_visible:false ~packing:scroll#add_with_viewport () in
let selection = view#selection in
let _ = selection#set_mode `SINGLE in
let menu_box = GPack.vbox ~packing:pane#pack2 () in
let renderer = (GTree.cell_renderer_pixbuf [], ["stock-id", icon_col]) in
let col = GTree.view_column ~renderer () in
let _ = view#append_column col in
let renderer = (GTree.cell_renderer_text [], ["text", label_col]) in
let col = GTree.view_column ~renderer () in
let _ = view#append_column col in
let make_param (main_box : #GPack.box) = function
| String_param p ->
let box = new string_param_box p in
let _ = main_box#pack ~expand: false ~padding: 2 box#box in
box
| Combo_param p ->
let box = new combo_param_box p in
let _ = main_box#pack ~expand: false ~padding: 2 box#box in
box
| Text_param p ->
let box = new text_param_box p in
let _ = main_box#pack ~expand: p.string_expand ~padding: 2 box#box in
box
| Bool_param p ->
let box = new bool_param_box p in
let _ = main_box#pack ~expand: false ~padding: 2 box#box in
box
| List_param f ->
let box = f () in
let _ = main_box#pack ~expand: true ~padding: 2 box#box in
box
| Custom_param p ->
let box = new custom_param_box p in
let _ = main_box#pack ~expand: p.custom_expand ~padding: 2 box#box in
box
| Modifiers_param p ->
let box = new modifiers_param_box p in
let _ = main_box#pack ~expand: false ~padding: 2 box#box in
box
in
let set_icon iter = function
| None -> ()
| Some icon -> tree#set ~row:iter ~column:icon_col icon
in
(* Populate the tree *)
let rec make_tree iter conf_struct =
box is not shown at first
let box = GPack.vbox ~packing:(menu_box#pack ~expand:true) ~show:false () in
let new_iter = match iter with
| None -> tree#append ()
| Some parent -> tree#append ~parent ()
in
match conf_struct with
| Section (label, icon, param_list) ->
let params = List.map (make_param box) param_list in
let widget =
object
method box = box#coerce
method apply () = List.iter (fun param -> param#apply) params
end
in
let () = tree#set ~row:new_iter ~column:label_col label in
let () = set_icon new_iter icon in
let () = tree#set ~row:new_iter ~column:box_col widget in
()
| Section_list (label, icon, struct_list) ->
let widget =
object
(* Section_list does not contain any effect widget, so we do not have to
apply anything. *)
method apply () = ()
method box = box#coerce
end
in
let () = tree#set ~row:new_iter ~column:label_col label in
let () = set_icon new_iter icon in
let () = tree#set ~row:new_iter ~column:box_col widget in
List.iter (make_tree (Some new_iter)) struct_list
in
let () = List.iter (make_tree None) conf_struct in
(* Dealing with signals *)
let current_prop : widget option ref = ref None in
let select_iter iter =
let () = match !current_prop with
| None -> ()
| Some box -> box#box#misc#hide ()
in
let box = tree#get ~row:iter ~column:box_col in
let () = box#box#misc#show () in
current_prop := Some box
in
let when_selected () =
let rows = selection#get_selected_rows in
match rows with
| [] -> ()
| row :: _ ->
let iter = tree#get_iter row in
select_iter iter
in
Focus on a box when selected
let _ = selection#connect#changed ~callback:when_selected in
let _ = match tree#get_iter_first with
| None -> ()
| Some iter -> select_iter iter
in
object
method box = main_box
method apply =
let foreach _ iter =
let widget = tree#get ~row:iter ~column:box_col in
widget#apply(); false
in
tree#foreach foreach
end
(** This function takes a configuration structure list and creates a window
to configure the various parameters. *)
let edit ?(with_apply=true)
?(apply=(fun () -> ()))
title ?parent ?width ?height
conf_struct =
let dialog = GWindow.dialog
~position:`CENTER
~modal: true ~title: title
~type_hint:`DIALOG
?parent ?height ?width
()
in
let config_box = new configuration_box conf_struct in
let _ = dialog#vbox#pack ~expand:true config_box#box#coerce in
if with_apply then
dialog#add_button Configwin_messages.mApply `APPLY;
dialog#add_button Configwin_messages.mOk `OK;
dialog#add_button Configwin_messages.mCancel `CANCEL;
let destroy () =
dialog#destroy ();
in
let rec iter rep =
try
match dialog#run () with
| `APPLY -> config_box#apply; iter Return_apply
| `OK -> config_box#apply; destroy (); Return_ok
| _ -> destroy (); rep
with
Failure s ->
GToolbox.message_box ~title:"Error" s; iter rep
| e ->
GToolbox.message_box ~title:"Error" (Printexc.to_string e); iter rep
in
iter Return_cancel
let edit_string l s =
match GToolbox.input_string ~title : l : s Configwin_messages.mValue with
None - > s
| Some s2 - > s2
let edit_string l s =
match GToolbox.input_string ~title: l ~text: s Configwin_messages.mValue with
None -> s
| Some s2 -> s2
*)
(** Create a string param. *)
let string ?(editable=true) ?(expand=true) ?help ?(f=(fun _ -> ())) label v =
String_param
{
string_label = label ;
string_help = help ;
string_value = v ;
string_editable = editable ;
string_f_apply = f ;
string_expand = expand ;
string_to_string = (fun x -> x) ;
string_of_string = (fun x -> x) ;
}
(** Create a bool param. *)
let bool ?(editable=true) ?help ?(f=(fun _ -> ())) label v =
Bool_param
{
bool_label = label ;
bool_help = help ;
bool_value = v ;
bool_editable = editable ;
bool_f_apply = f ;
}
(*
(** Create a list param. *)
let list ?(editable=true) ?help
?(f=(fun (_:'a list) -> ()))
?(eq=Pervasives.(=))
?(edit:('a -> 'a) option)
?(add=(fun () -> ([] : 'a list)))
?titles ?(color=(fun (_:'a) -> (None : string option)))
label (f_strings : 'a -> string list) v =
List_param
(fun () ->
new list_param_box
{
list_label = label ;
list_help = help ;
list_value = v ;
list_editable = editable ;
list_titles = titles;
list_eq = eq ;
list_strings = f_strings ;
list_color = color ;
list_f_edit = edit ;
list_f_add = add ;
list_f_apply = f ;
}
)
(** Create a strings param. *)
let strings ?(editable=true) ?help
?(f=(fun _ -> ()))
?(eq=Pervasives.(=))
?(add=(fun () -> [])) label v =
list ~editable ?help ~f ~eq ~edit: (edit_string label) ~add label (fun s -> [s]) v
*)
(** Create a combo param. *)
let combo ?(editable=true) ?(expand=true) ?help ?(f=(fun _ -> ()))
?(new_allowed=false)
?(blank_allowed=false) label choices v =
Combo_param
{
combo_label = label ;
combo_help = help ;
combo_value = v ;
combo_editable = editable ;
combo_choices = choices ;
combo_new_allowed = new_allowed ;
combo_blank_allowed = blank_allowed ;
combo_f_apply = f ;
combo_expand = expand ;
}
let modifiers
?(editable=true)
?(expand=true)
?help
?(allow=[`CONTROL;`SHIFT;`LOCK;`META;`MOD1;`MOD2;`MOD3;`MOD4;`MOD5])
?(f=(fun _ -> ())) label v =
Modifiers_param
{
md_label = label ;
md_help = help ;
md_value = v ;
md_editable = editable ;
md_f_apply = f ;
md_expand = expand ;
md_allow = allow ;
}
(** Create a custom param.*)
let custom ?label box f expand =
Custom_param
{
custom_box = box ;
custom_f_apply = f ;
custom_expand = expand ;
custom_framed = label ;
}
(* Copying lablgtk question_box + forbidding hiding *)
let question_box ~title ~buttons ?(default=1) ?icon ?parent message =
let button_nb = ref 0 in
let window = GWindow.dialog ~position:`CENTER ~modal:true ?parent ~type_hint:`DIALOG ~title () in
let hbox = GPack.hbox ~border_width:10 ~packing:window#vbox#add () in
let bbox = window#action_area in
begin match icon with
None -> ()
| Some i -> hbox#pack i#coerce ~padding:4
end;
ignore (GMisc.label ~text: message ~packing: hbox#add ());
(* the function called to create each button by iterating *)
let rec iter_buttons n = function
[] ->
()
| button_label :: q ->
let b = GButton.button ~label: button_label
~packing:(bbox#pack ~expand:true ~padding:4) ()
in
ignore (b#connect#clicked ~callback:
(fun () -> button_nb := n; window#destroy ()));
If it 's the first button then give it the focus
if n = default then b#grab_default () else ();
iter_buttons (n+1) q
in
iter_buttons 1 buttons;
ignore (window#connect#destroy ~callback: GMain.Main.quit);
window#set_position `CENTER;
window#show ();
GMain.Main.main ();
!button_nb
let message_box ~title ?icon ?parent ?(ok="Ok") message =
ignore (question_box ?icon ?parent ~title message ~buttons:[ ok ])
| null | https://raw.githubusercontent.com/coq/coq/f7e05393addb9a45fa1eaef2a72da9b2c4c14396/ide/coqide/configwin_ihm.ml | ocaml | *******************************************************************************
en Automatique. All rights reserved.
This program is free software; you can redistribute it and/or modify
License, or any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
Contact:
*******************************************************************************
How the modifiers are named in the preference box
* This class builds a frame with a clist and two buttons :
one to add items and one to remove the selected items.
The class takes in parameter a function used to add items and
a string list ref which is used to store the content of the clist.
At last, a title for the frame is also in parameter, so that
each instance of the class creates a frame.
* the list of selected rows
* This method returns the frame created.
set the new list in the provided listref
the list of selectd elements is now empty
* Move up the selected rows.
create the functions called when the buttons are clicked
get the files to add with the function provided
remove from the list the ones which are already in
the listref, using the eq predicate
connect the functions to the buttons
connect the select and deselect events
initialize the clist with the listref
* This class is used to build a box for a string parameter.
* This method returns the main box ready to be packed.
* This method applies the new value of the parameter.
* This class is used to build a box for a combo parameter.
* This method returns the main box ready to be packed.
* This method applies the new value of the parameter.
* Class used to pack a custom box.
* This class is used to build a box for a text parameter.
* This method returns the main box ready to be packed.
* This method applies the new value of the parameter.
* This class is used to build a box for a boolean parameter.
* This method returns the check button ready to be packed.
* This method applies the new value of the parameter.
* This method returns the main box ready to be packed.
* This method applies the new value of the parameter.
(** This class is used to build a box for a parameter whose values are a list.
* This method returns the main box ready to be packed.
* This method applies the new value of the parameter.
* This class creates a configuration box from a configuration structure
Tree view part
Populate the tree
Section_list does not contain any effect widget, so we do not have to
apply anything.
Dealing with signals
* This function takes a configuration structure list and creates a window
to configure the various parameters.
* Create a string param.
* Create a bool param.
(** Create a list param.
* Create a strings param.
* Create a combo param.
* Create a custom param.
Copying lablgtk question_box + forbidding hiding
the function called to create each button by iterating | Cameleon
Copyright ( C ) 2005 Institut National de Recherche en Informatique et
it under the terms of the GNU Library General Public License as
published by the Free Software Foundation ; either version 2 of the
GNU Library General Public License for more details .
You should have received a copy of the GNU Library General Public
License along with this program ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA
02111 - 1307 USA
* This module contains the gui functions of Configwin .
open Configwin_types
let set_help_tip wev = function
| None -> ()
| Some help -> GtkBase.Widget.Tooltip.set_text wev#as_widget help
let select_arch m m_osx =
if Coq_config.arch = "Darwin" then m_osx else m
let modifiers_to_string m =
let rec iter m s =
match m with
[] -> s
| c :: m ->
iter m ((
match c with
`CONTROL -> "<ctrl>"
| `SHIFT -> "<shft>"
| `LOCK -> "<lock>"
| `META -> select_arch "<meta>" "<cmd>"
| `MOD1 -> "<alt>"
| `MOD2 -> "<mod2>"
| `MOD3 -> "<mod3>"
| `MOD4 -> "<mod4>"
| `MOD5 -> "<mod5>"
| _ -> raise Not_found
) ^ s)
in
iter m ""
class type widget =
object
method box : GObj.widget
method apply : unit -> unit
end
let debug = false
let dbg s = if debug then Minilib.log s else ()
( * * This class builds a frame with a clist and two buttons :
one to add items and one to remove the selected items .
The class takes in parameter a function used to add items and
a string list ref which is used to store the content of the clist .
At last , a title for the frame is also in parameter , so that
each instance of the class creates a frame .
class ['a] list_selection_box
(listref : 'a list ref)
titles_opt
help_opt
f_edit_opt
f_strings
f_color
(eq : 'a -> 'a -> bool)
add_function title editable
=
let _ = dbg "list_selection_box" in
let wev = GBin.event_box () in
let wf = GBin.frame ~label: title ~packing: wev#add () in
let hbox = GPack.hbox ~packing: wf#add () in
the scroll window and the
let wscroll = GBin.scrolled_window
~vpolicy: `AUTOMATIC
~hpolicy: `AUTOMATIC
~packing: (hbox#pack ~expand: true) ()
in
let wlist = match titles_opt with
None ->
GList.clist ~selection_mode: `MULTIPLE
~titles_show: false
~packing: wscroll#add ()
| Some l ->
GList.clist ~selection_mode: `MULTIPLE
~titles: l
~titles_show: true
~packing: wscroll#add ()
in
let _ = set_help_tip wev help_opt in
the vbox for the buttons
let vbox_buttons = GPack.vbox () in
let _ =
if editable then
let _ = hbox#pack ~expand: false vbox_buttons#coerce in
()
else
()
in
let _ = dbg "list_selection_box: wb_add" in
let wb_add = GButton.button
~label: Configwin_messages.mAdd
~packing: (vbox_buttons#pack ~expand:false ~padding:2)
()
in
let wb_edit = GButton.button
~label: Configwin_messages.mEdit
()
in
let _ = match f_edit_opt with
None -> ()
| Some _ -> vbox_buttons#pack ~expand:false ~padding:2 wb_edit#coerce
in
let wb_up = GButton.button
~label: Configwin_messages.mUp
~packing: (vbox_buttons#pack ~expand:false ~padding:2)
()
in
let wb_remove = GButton.button
~label: Configwin_messages.mRemove
~packing: (vbox_buttons#pack ~expand:false ~padding:2)
()
in
let _ = dbg "list_selection_box: object(self)" in
object (self)
val mutable list_select = []
method box = wev
method update l =
listref := l;
insert the elements in the
wlist#freeze ();
wlist#clear ();
List.iter
(fun ele ->
ignore (wlist#append (f_strings ele));
match f_color ele with
None -> ()
| Some c ->
try wlist#set_row ~foreground: (`NAME c) (wlist#rows - 1)
with _ -> ()
)
!listref;
(match titles_opt with
None -> wlist#columns_autosize ()
| Some _ -> GToolbox.autosize_clist wlist);
wlist#thaw ();
list_select <- []
method up_selected =
let rec iter n selrows l =
match selrows with
[] -> (l, [])
| m :: qrows ->
match l with
[] -> ([],[])
| [_] -> (l,[])
| e1 :: e2 :: q when m = n + 1 ->
let newl, newrows = iter (n+1) qrows (e1 :: q) in
(e2 :: newl, n :: newrows)
| e1 :: q ->
let newl, newrows = iter (n+1) selrows q in
(e1 :: newl, newrows)
in
let sorted_select = List.sort compare list_select in
let new_list, new_rows = iter 0 sorted_select !listref in
self#update new_list;
List.iter (fun n -> wlist#select n 0) new_rows
* Make the user edit the first selected row .
method edit_selected f_edit =
let sorted_select = List.sort compare list_select in
match sorted_select with
[] -> ()
| n :: _ ->
try
let ele = List.nth !listref n in
let ele2 = f_edit ele in
let rec iter m = function
[] -> []
| e :: q ->
if n = m then
ele2 :: q
else
e :: (iter (m+1) q)
in
self#update (iter 0 !listref);
wlist#select n 0
with
Not_found ->
()
initializer
let f_add () =
let l = add_function () in
let l2 = List.fold_left
(fun acc -> fun ele ->
if List.exists (eq ele) acc then
acc
else
acc @ [ele])
!listref
l
in
self#update l2
in
let f_remove () =
remove the selected items from the listref and the
let rec iter n = function
[] -> []
| h :: q ->
if List.mem n list_select then
iter (n+1) q
else
h :: (iter (n+1) q)
in
let new_list = iter 0 !listref in
self#update new_list
in
let _ = dbg "list_selection_box: connecting wb_add" in
ignore (wb_add#connect#clicked ~callback:f_add);
let _ = dbg "list_selection_box: connecting wb_remove" in
ignore (wb_remove#connect#clicked ~callback:f_remove);
let _ = dbg "list_selection_box: connecting wb_up" in
ignore (wb_up#connect#clicked ~callback:(fun () -> self#up_selected));
(
match f_edit_opt with
None -> ()
| Some f ->
let _ = dbg "list_selection_box: connecting wb_edit" in
ignore (wb_edit#connect#clicked ~callback:(fun () -> self#edit_selected f))
);
connect the selection and deselection of items in the
let f_select ~row ~column ~event =
try
list_select <- row :: list_select
with
Failure _ ->
()
in
let f_unselect ~row ~column ~event =
try
let new_list_select = List.filter (fun n -> n <> row) list_select in
list_select <- new_list_select
with
Failure _ ->
()
in
let _ = dbg "list_selection_box: connecting select_row" in
ignore(wlist#connect#select_row ~callback:f_select);
let _ = dbg "list_selection_box: connecting unselect_row" in
ignore(wlist#connect#unselect_row ~callback:f_unselect);
self#update !listref
end;;
*)
class string_param_box param =
let _ = dbg "string_param_box" in
let hbox = GPack.hbox () in
let wev = GBin.event_box ~packing: (hbox#pack ~expand: false ~padding: 2) () in
let _wl = GMisc.label ~text: param.string_label ~packing: wev#add () in
let we = GEdit.entry
~editable: param.string_editable
~packing: (hbox#pack ~expand: param.string_expand ~padding: 2)
()
in
let _ = set_help_tip wev param.string_help in
let _ = we#set_text (param.string_to_string param.string_value) in
object (self)
method box = hbox#coerce
method apply =
let new_value = param.string_of_string we#text in
if new_value <> param.string_value then
let _ = param.string_f_apply new_value in
param.string_value <- new_value
else
()
end ;;
class combo_param_box param =
let _ = dbg "combo_param_box" in
let hbox = GPack.hbox () in
let wev = GBin.event_box ~packing: (hbox#pack ~expand: false ~padding: 2) () in
let _wl = GMisc.label ~text: param.combo_label ~packing: wev#add () in
let _ = set_help_tip wev param.combo_help in
let get_value = if not param.combo_new_allowed then
let wc = GEdit.combo_box_text
~strings: param.combo_choices
?active:(let rec aux i = function
|[] -> None
|h::_ when h = param.combo_value -> Some i
|_::t -> aux (succ i) t
in aux 0 param.combo_choices)
~packing: (hbox#pack ~expand: param.combo_expand ~padding: 2)
()
in
fun () -> match GEdit.text_combo_get_active wc with |None -> "" |Some s -> s
else
let (wc,_) = GEdit.combo_box_entry_text
~strings: param.combo_choices
~packing: (hbox#pack ~expand: param.combo_expand ~padding: 2)
()
in
let _ = wc#entry#set_editable param.combo_editable in
let _ = wc#entry#set_text param.combo_value in
fun () -> wc#entry#text
in
object (self)
method box = hbox#coerce
method apply =
let new_value = get_value () in
if new_value <> param.combo_value then
let _ = param.combo_f_apply new_value in
param.combo_value <- new_value
else
()
end ;;
class custom_param_box param =
let _ = dbg "custom_param_box" in
let top =
match param.custom_framed with
None -> param.custom_box#coerce
| Some l ->
let wf = GBin.frame ~label: l () in
wf#add param.custom_box#coerce;
wf#coerce
in
object (self)
method box = top
method apply = param.custom_f_apply ()
end
class text_param_box param =
let _ = dbg "text_param_box" in
let wf = GBin.frame ~label: param.string_label ~height: 100 () in
let wev = GBin.event_box ~packing: wf#add () in
let wscroll = GBin.scrolled_window
~vpolicy: `AUTOMATIC
~hpolicy: `AUTOMATIC
~packing: wev#add ()
in
let wview = GText.view
~editable: param.string_editable
~packing: wscroll#add
()
in
let _ = set_help_tip wev param.string_help in
let _ = dbg "text_param_box: buffer creation" in
let buffer = GText.buffer () in
let _ = wview#set_buffer buffer in
let _ = buffer#insert (param.string_to_string param.string_value) in
let _ = dbg "text_param_box: object(self)" in
object (self)
val wview = wview
method box = wf#coerce
method apply =
let v = param.string_of_string (buffer#get_text ()) in
if v <> param.string_value then
(
dbg "apply new value!";
let _ = param.string_f_apply v in
param.string_value <- v
)
else
()
end ;;
class bool_param_box param =
let _ = dbg "bool_param_box" in
let wchk = GButton.check_button
~label: param.bool_label
()
in
let _ = set_help_tip wchk param.bool_help in
let _ = wchk#set_active param.bool_value in
let _ = wchk#misc#set_sensitive param.bool_editable in
object (self)
method box = wchk#coerce
method apply =
let new_value = wchk#active in
if new_value <> param.bool_value then
let _ = param.bool_f_apply new_value in
param.bool_value <- new_value
else
()
end ;;
class modifiers_param_box param =
let hbox = GPack.hbox () in
let wev = GBin.event_box ~packing: (hbox#pack ~expand:true ~fill:true ~padding: 2) () in
let _wl = GMisc.label ~text: param.md_label ~packing: wev#add () in
let value = ref param.md_value in
let _ = List.map (fun modifier ->
let but = GButton.toggle_button
~label:(modifiers_to_string [modifier])
~active:(List.mem modifier param.md_value)
~packing:(hbox#pack ~expand:false) () in
ignore (but#connect#toggled
~callback:(fun _ -> if but#active then value := modifier::!value
else value := List.filter ((<>) modifier) !value)))
param.md_allow
in
let _ = set_help_tip wev param.md_help in
object (self)
method box = hbox#coerce
method apply =
let new_value = !value in
if new_value <> param.md_value then
let _ = param.md_f_apply new_value in
param.md_value <- new_value
else
()
end ;;
class ['a] list_param_box (param : 'a list_param) =
let _ = dbg "list_param_box" in
let listref = ref param.list_value in
let frame_selection = new list_selection_box
listref
param.list_titles
param.list_help
param.list_f_edit
param.list_strings
param.list_color
param.list_eq
param.list_f_add param.list_label param.list_editable
tt
in
object (self)
method box = frame_selection#box#coerce
method apply =
param.list_f_apply !listref ;
param.list_value <- !listref
end ;;
*)
class configuration_box conf_struct =
let main_box = GPack.hbox () in
let columns = new GTree.column_list in
let icon_col = columns#add GtkStock.conv in
let label_col = columns#add Gobject.Data.string in
let box_col = columns#add Gobject.Data.caml in
let () = columns#lock () in
let pane = GPack.paned `HORIZONTAL ~packing:main_box#add () in
let scroll = GBin.scrolled_window ~hpolicy:`NEVER ~packing:pane#pack1 () in
let tree = GTree.tree_store columns in
let view = GTree.view ~model:tree ~headers_visible:false ~packing:scroll#add_with_viewport () in
let selection = view#selection in
let _ = selection#set_mode `SINGLE in
let menu_box = GPack.vbox ~packing:pane#pack2 () in
let renderer = (GTree.cell_renderer_pixbuf [], ["stock-id", icon_col]) in
let col = GTree.view_column ~renderer () in
let _ = view#append_column col in
let renderer = (GTree.cell_renderer_text [], ["text", label_col]) in
let col = GTree.view_column ~renderer () in
let _ = view#append_column col in
let make_param (main_box : #GPack.box) = function
| String_param p ->
let box = new string_param_box p in
let _ = main_box#pack ~expand: false ~padding: 2 box#box in
box
| Combo_param p ->
let box = new combo_param_box p in
let _ = main_box#pack ~expand: false ~padding: 2 box#box in
box
| Text_param p ->
let box = new text_param_box p in
let _ = main_box#pack ~expand: p.string_expand ~padding: 2 box#box in
box
| Bool_param p ->
let box = new bool_param_box p in
let _ = main_box#pack ~expand: false ~padding: 2 box#box in
box
| List_param f ->
let box = f () in
let _ = main_box#pack ~expand: true ~padding: 2 box#box in
box
| Custom_param p ->
let box = new custom_param_box p in
let _ = main_box#pack ~expand: p.custom_expand ~padding: 2 box#box in
box
| Modifiers_param p ->
let box = new modifiers_param_box p in
let _ = main_box#pack ~expand: false ~padding: 2 box#box in
box
in
let set_icon iter = function
| None -> ()
| Some icon -> tree#set ~row:iter ~column:icon_col icon
in
let rec make_tree iter conf_struct =
box is not shown at first
let box = GPack.vbox ~packing:(menu_box#pack ~expand:true) ~show:false () in
let new_iter = match iter with
| None -> tree#append ()
| Some parent -> tree#append ~parent ()
in
match conf_struct with
| Section (label, icon, param_list) ->
let params = List.map (make_param box) param_list in
let widget =
object
method box = box#coerce
method apply () = List.iter (fun param -> param#apply) params
end
in
let () = tree#set ~row:new_iter ~column:label_col label in
let () = set_icon new_iter icon in
let () = tree#set ~row:new_iter ~column:box_col widget in
()
| Section_list (label, icon, struct_list) ->
let widget =
object
method apply () = ()
method box = box#coerce
end
in
let () = tree#set ~row:new_iter ~column:label_col label in
let () = set_icon new_iter icon in
let () = tree#set ~row:new_iter ~column:box_col widget in
List.iter (make_tree (Some new_iter)) struct_list
in
let () = List.iter (make_tree None) conf_struct in
let current_prop : widget option ref = ref None in
let select_iter iter =
let () = match !current_prop with
| None -> ()
| Some box -> box#box#misc#hide ()
in
let box = tree#get ~row:iter ~column:box_col in
let () = box#box#misc#show () in
current_prop := Some box
in
let when_selected () =
let rows = selection#get_selected_rows in
match rows with
| [] -> ()
| row :: _ ->
let iter = tree#get_iter row in
select_iter iter
in
Focus on a box when selected
let _ = selection#connect#changed ~callback:when_selected in
let _ = match tree#get_iter_first with
| None -> ()
| Some iter -> select_iter iter
in
object
method box = main_box
method apply =
let foreach _ iter =
let widget = tree#get ~row:iter ~column:box_col in
widget#apply(); false
in
tree#foreach foreach
end
let edit ?(with_apply=true)
?(apply=(fun () -> ()))
title ?parent ?width ?height
conf_struct =
let dialog = GWindow.dialog
~position:`CENTER
~modal: true ~title: title
~type_hint:`DIALOG
?parent ?height ?width
()
in
let config_box = new configuration_box conf_struct in
let _ = dialog#vbox#pack ~expand:true config_box#box#coerce in
if with_apply then
dialog#add_button Configwin_messages.mApply `APPLY;
dialog#add_button Configwin_messages.mOk `OK;
dialog#add_button Configwin_messages.mCancel `CANCEL;
let destroy () =
dialog#destroy ();
in
let rec iter rep =
try
match dialog#run () with
| `APPLY -> config_box#apply; iter Return_apply
| `OK -> config_box#apply; destroy (); Return_ok
| _ -> destroy (); rep
with
Failure s ->
GToolbox.message_box ~title:"Error" s; iter rep
| e ->
GToolbox.message_box ~title:"Error" (Printexc.to_string e); iter rep
in
iter Return_cancel
let edit_string l s =
match GToolbox.input_string ~title : l : s Configwin_messages.mValue with
None - > s
| Some s2 - > s2
let edit_string l s =
match GToolbox.input_string ~title: l ~text: s Configwin_messages.mValue with
None -> s
| Some s2 -> s2
*)
let string ?(editable=true) ?(expand=true) ?help ?(f=(fun _ -> ())) label v =
String_param
{
string_label = label ;
string_help = help ;
string_value = v ;
string_editable = editable ;
string_f_apply = f ;
string_expand = expand ;
string_to_string = (fun x -> x) ;
string_of_string = (fun x -> x) ;
}
let bool ?(editable=true) ?help ?(f=(fun _ -> ())) label v =
Bool_param
{
bool_label = label ;
bool_help = help ;
bool_value = v ;
bool_editable = editable ;
bool_f_apply = f ;
}
let list ?(editable=true) ?help
?(f=(fun (_:'a list) -> ()))
?(eq=Pervasives.(=))
?(edit:('a -> 'a) option)
?(add=(fun () -> ([] : 'a list)))
?titles ?(color=(fun (_:'a) -> (None : string option)))
label (f_strings : 'a -> string list) v =
List_param
(fun () ->
new list_param_box
{
list_label = label ;
list_help = help ;
list_value = v ;
list_editable = editable ;
list_titles = titles;
list_eq = eq ;
list_strings = f_strings ;
list_color = color ;
list_f_edit = edit ;
list_f_add = add ;
list_f_apply = f ;
}
)
let strings ?(editable=true) ?help
?(f=(fun _ -> ()))
?(eq=Pervasives.(=))
?(add=(fun () -> [])) label v =
list ~editable ?help ~f ~eq ~edit: (edit_string label) ~add label (fun s -> [s]) v
*)
let combo ?(editable=true) ?(expand=true) ?help ?(f=(fun _ -> ()))
?(new_allowed=false)
?(blank_allowed=false) label choices v =
Combo_param
{
combo_label = label ;
combo_help = help ;
combo_value = v ;
combo_editable = editable ;
combo_choices = choices ;
combo_new_allowed = new_allowed ;
combo_blank_allowed = blank_allowed ;
combo_f_apply = f ;
combo_expand = expand ;
}
let modifiers
?(editable=true)
?(expand=true)
?help
?(allow=[`CONTROL;`SHIFT;`LOCK;`META;`MOD1;`MOD2;`MOD3;`MOD4;`MOD5])
?(f=(fun _ -> ())) label v =
Modifiers_param
{
md_label = label ;
md_help = help ;
md_value = v ;
md_editable = editable ;
md_f_apply = f ;
md_expand = expand ;
md_allow = allow ;
}
let custom ?label box f expand =
Custom_param
{
custom_box = box ;
custom_f_apply = f ;
custom_expand = expand ;
custom_framed = label ;
}
let question_box ~title ~buttons ?(default=1) ?icon ?parent message =
let button_nb = ref 0 in
let window = GWindow.dialog ~position:`CENTER ~modal:true ?parent ~type_hint:`DIALOG ~title () in
let hbox = GPack.hbox ~border_width:10 ~packing:window#vbox#add () in
let bbox = window#action_area in
begin match icon with
None -> ()
| Some i -> hbox#pack i#coerce ~padding:4
end;
ignore (GMisc.label ~text: message ~packing: hbox#add ());
let rec iter_buttons n = function
[] ->
()
| button_label :: q ->
let b = GButton.button ~label: button_label
~packing:(bbox#pack ~expand:true ~padding:4) ()
in
ignore (b#connect#clicked ~callback:
(fun () -> button_nb := n; window#destroy ()));
If it 's the first button then give it the focus
if n = default then b#grab_default () else ();
iter_buttons (n+1) q
in
iter_buttons 1 buttons;
ignore (window#connect#destroy ~callback: GMain.Main.quit);
window#set_position `CENTER;
window#show ();
GMain.Main.main ();
!button_nb
let message_box ~title ?icon ?parent ?(ok="Ok") message =
ignore (question_box ?icon ?parent ~title message ~buttons:[ ok ])
|
887882078bd90ed981c38e866b2ff6ac24891060028602f9a46b14e103e8768b | haskell-CI/haskell-ci | Project.hs | {-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
# LANGUAGE DeriveGeneric #
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE OverloadedStrings #-}
-- | License: GPL-3.0-or-later AND BSD-3-Clause
--
module Cabal.Project (
-- * Project
Project (..),
triverseProject,
emptyProject,
* project
readProject,
parseProject,
-- * Resolve project
resolveProject,
ResolveError (..),
renderResolveError,
-- * Read packages
readPackagesOfProject
) where
import Control.DeepSeq (NFData (..))
import Control.Exception (Exception (..), throwIO)
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Trans.Except (ExceptT, runExceptT, throwE)
import Data.Bifoldable (Bifoldable (..))
import Data.Bifunctor (Bifunctor (..))
import Data.Bitraversable (Bitraversable (..), bifoldMapDefault, bimapDefault)
import Data.ByteString (ByteString)
import Data.Either (partitionEithers)
import Data.Foldable (toList)
import Data.Function ((&))
import Data.Functor (void)
import Data.List (foldl', isSuffixOf)
import Data.List.NonEmpty (NonEmpty)
import Data.Maybe (mapMaybe)
import Data.Traversable (for)
import Data.Void (Void)
import Distribution.Compat.Lens (LensLike', over)
import GHC.Generics (Generic)
import Network.URI (URI (URI), parseURI)
import System.Directory (doesDirectoryExist, doesFileExist)
import System.FilePath (isAbsolute, normalise, splitDirectories, splitDrive, takeDirectory, (</>))
import qualified Data.ByteString as BS
import qualified Data.Map.Strict as M
import qualified Distribution.CabalSpecVersion as C
import qualified Distribution.FieldGrammar as C
import qualified Distribution.Fields as C
import qualified Distribution.PackageDescription as C
import qualified Distribution.Parsec as C
import Cabal.Internal.Glob
import Cabal.Internal.Newtypes
import Cabal.Optimization
import Cabal.Package
import Cabal.Parse
import Cabal.SourceRepo
infixl 1 <&>
(<&>) :: Functor f => f a -> (a -> b) -> f b
(<&>) = flip fmap
-- $setup
-- >>> :set -XOverloadedStrings
-- | @cabal.project@ file
data Project uri opt pkg = Project
{ prjPackages :: [pkg] -- ^ packages field
, prjOptPackages :: [opt] -- ^ optional packages
^ URI packages , filled in by ' '
^ , parsed as ' 's .
^ allow - newer , parsed as ' 's .
, prjReorderGoals :: Bool
, prjMaxBackjumps :: Maybe Int
, prjOptimization :: Optimization
, prjSourceRepos :: [SourceRepositoryPackage Maybe]
, prjOtherFields :: [C.PrettyField ()] -- ^ other fields
}
deriving (Functor, Foldable, Traversable, Generic)
-- | Doesn't compare 'prjOtherFields'
instance (Eq uri, Eq opt, Eq pkg) => Eq (Project uri opt pkg) where
x == y = and
[ eqOn prjPackages
, eqOn prjOptPackages
, eqOn prjUriPackages
, eqOn prjConstraints
, eqOn prjAllowNewer
, eqOn prjReorderGoals
, eqOn prjMaxBackjumps
, eqOn prjOptimization
, eqOn prjSourceRepos
]
where
eqOn f = f x == f y
-- | Doesn't show 'prjOtherFields'
--
-- @since 0.4.4
instance (Show uri, Show opt, Show pkg) => Show (Project uri opt pkg) where
showsPrec p prj =
showParen (p > 10)
( showString "Project{prjPackages = " . shows (prjPackages prj)
. showString ", prjOptPackages = " . shows (prjOptPackages prj)
. showString ", prjUriPackages = " . shows (prjUriPackages prj)
. showString ", prjConstraints = " . shows (prjConstraints prj)
. showString ", prjAllowNewer = " . shows (prjAllowNewer prj)
. showString ", prjReorderGoals = " . shows (prjReorderGoals prj)
. showString ", prjMaxBackjumps = " . shows (prjMaxBackjumps prj)
. showString ", prjOptimization = " . shows (prjOptimization prj)
. showString ", prjSourceRepos = " . shows (prjSourceRepos prj)
. showChar '}'
)
instance Bifunctor (Project c) where bimap = bimapDefault
instance Bifoldable (Project c) where bifoldMap = bifoldMapDefault
| ' traverse ' over all three type arguments of ' Project ' .
triverseProject
:: Applicative f
=> (uri -> f uri')
-> (opt -> f opt')
-> (pkg -> f pkg')
-> Project uri opt pkg -> f (Project uri' opt' pkg')
triverseProject f g h prj =
(\c b a -> prj { prjPackages = a, prjOptPackages = b, prjUriPackages = c })
<$> traverse f (prjUriPackages prj)
<*> traverse g (prjOptPackages prj)
<*> traverse h (prjPackages prj)
instance Bitraversable (Project uri) where
bitraverse = triverseProject pure
-- | Empty project.
emptyProject :: Project c b a
emptyProject = Project [] [] [] [] [] False Nothing OptimizationOn [] []
-- | @since 0.2.1
instance (NFData c, NFData b, NFData a) => NFData (Project c b a) where
rnf (Project x1 x2 x3 x4 x5 x6 x7 x8 x9 x10) =
rnf x1 `seq` rnf x2 `seq` rnf x3 `seq`
rnf x4 `seq` rnf x5 `seq` rnf x6 `seq`
rnf x7 `seq` rnf x8 `seq` rnf x9 `seq`
rnfList rnfPrettyField x10
where
rnfList :: (a -> ()) -> [a] -> ()
rnfList _ [] = ()
rnfList f (x:xs) = f x `seq` rnfList f xs
rnfPrettyField :: NFData x => C.PrettyField x -> ()
rnfPrettyField C.PrettyEmpty = ()
rnfPrettyField (C.PrettyField ann fn d) =
rnf ann `seq` rnf fn `seq` rnf d
rnfPrettyField (C.PrettySection ann fn ds fs) =
rnf ann `seq` rnf fn `seq` rnf ds `seq` rnfList rnfPrettyField fs
-------------------------------------------------------------------------------
-- Initial parsing
-------------------------------------------------------------------------------
-- | High level convenience function to read and elaborate @cabal.project@ files
--
May throw ' IOException ' when file does n't exist , ' ParseError '
on parse errors , or ' ResolveError ' on package resolution error .
--
readProject :: FilePath -> IO (Project URI Void (FilePath, C.GenericPackageDescription))
readProject fp = do
contents <- BS.readFile fp
prj0 <- either throwIO return (parseProject fp contents)
prj1 <- resolveProject fp prj0 >>= either throwIO return
readPackagesOfProject prj1 >>= either throwIO return
| Parse project file . Extracts only few fields .
--
> > > fmap prjPackages $ parseProject " cabal.project " " packages : foo bar/*.cabal "
-- Right ["foo","bar/*.cabal"]
--
parseProject :: FilePath -> ByteString -> Either (ParseError NonEmpty) (Project Void String String)
parseProject = parseWith $ \fields0 -> do
let (fields1, sections) = C.partitionFields fields0
let fields2 = M.filterWithKey (\k _ -> k `elem` knownFields) fields1
parse fields0 fields2 sections
where
knownFields = C.fieldGrammarKnownFieldList $ grammar []
parse otherFields fields sections = do
let prettyOtherFields = map void $ C.fromParsecFields $ filter otherFieldName otherFields
prj <- C.parseFieldGrammar C.cabalSpecLatest fields $ grammar prettyOtherFields
foldl' (&) prj <$> traverse parseSec (concat sections)
-- Special case for source-repository-package. If you add another such
-- special case, make sure to update otherFieldName appropriately.
parseSec :: C.Section C.Position -> C.ParseResult (Project Void String String -> Project Void String String)
parseSec (C.MkSection (C.Name _pos name) [] fields) | name == sourceRepoSectionName = do
let fields' = fst $ C.partitionFields fields
repos <- C.parseFieldGrammar C.cabalSpecLatest fields' sourceRepositoryPackageGrammar
return $ over prjSourceReposL (++ toList (srpFanOut repos))
parseSec _ = return id
-- | Returns 'True' if a field should be a part of 'prjOtherFields'. This
-- excludes any field that is a part of 'grammar' as well as
@source - repository - package@ ( see ' parseProject ' , which has a special case
-- for it).
otherFieldName :: C.Field ann -> Bool
otherFieldName (C.Field (C.Name _ fn) _) = fn `notElem` C.fieldGrammarKnownFieldList (grammar [])
otherFieldName (C.Section (C.Name _ fn) _ _) = fn /= sourceRepoSectionName
-- | This contains a subset of the fields in the @cabal.project@ grammar that
are distinguished by a ' Project ' . Note that this does not /not/ contain
@source - repository - package@ , as that is handled separately in ' parseProject ' .
grammar :: [C.PrettyField ()] -> C.ParsecFieldGrammar (Project Void String String) (Project Void String String)
grammar otherFields = Project
<$> C.monoidalFieldAla "packages" (C.alaList' C.FSep PackageLocation) prjPackagesL
<*> C.monoidalFieldAla "optional-packages" (C.alaList' C.FSep PackageLocation) prjOptPackagesL
<*> pure []
<*> C.monoidalFieldAla "constraints" (C.alaList' C.CommaVCat NoCommas) prjConstraintsL
<*> C.monoidalFieldAla "allow-newer" (C.alaList' C.CommaVCat NoCommas) prjAllowNewerL
<*> C.booleanFieldDef "reorder-goals" prjReorderGoalsL False
<*> C.optionalFieldAla "max-backjumps" Int' prjMaxBackjumpsL
<*> C.optionalFieldDef "optimization" prjOptimizationL OptimizationOn
<*> pure []
<*> pure otherFields
sourceRepoSectionName :: C.FieldName
sourceRepoSectionName = "source-repository-package"
-------------------------------------------------------------------------------
-- Lenses
-------------------------------------------------------------------------------
prjPackagesL :: Functor f => LensLike' f (Project uri opt pkg) [pkg]
prjPackagesL f prj = f (prjPackages prj) <&> \x -> prj { prjPackages = x }
prjOptPackagesL :: Functor f => LensLike' f (Project uri opt pkg) [opt]
prjOptPackagesL f prj = f (prjOptPackages prj) <&> \x -> prj { prjOptPackages = x }
prjConstraintsL :: Functor f => LensLike' f (Project uri opt pkg) [String]
prjConstraintsL f prj = f (prjConstraints prj) <&> \x -> prj { prjConstraints = x }
prjAllowNewerL :: Functor f => LensLike' f (Project uri opt pkg) [String]
prjAllowNewerL f prj = f (prjAllowNewer prj) <&> \x -> prj { prjAllowNewer = x }
prjReorderGoalsL :: Functor f => LensLike' f (Project uri opt pkg) Bool
prjReorderGoalsL f prj = f (prjReorderGoals prj) <&> \x -> prj { prjReorderGoals = x }
prjMaxBackjumpsL :: Functor f => LensLike' f (Project uri opt pkg) (Maybe Int)
prjMaxBackjumpsL f prj = f (prjMaxBackjumps prj) <&> \x -> prj { prjMaxBackjumps = x }
prjOptimizationL :: Functor f => LensLike' f (Project uri opt pkg) Optimization
prjOptimizationL f prj = f (prjOptimization prj) <&> \x -> prj { prjOptimization = x }
prjSourceReposL :: Functor f => LensLike' f (Project uri opt pkg) [SourceRepositoryPackage Maybe]
prjSourceReposL f prj = f (prjSourceRepos prj) <&> \x -> prj { prjSourceRepos = x }
-------------------------------------------------------------------------------
-- Resolving
-------------------------------------------------------------------------------
-- | A 'resolveProject' error.
newtype ResolveError = BadPackageLocation String
deriving Show
instance Exception ResolveError where
displayException = renderResolveError
-- | Pretty print 'ResolveError'.
renderResolveError :: ResolveError -> String
renderResolveError (BadPackageLocation s) = "Bad package location: " ++ show s
-- | Resolve project package locations.
--
-- Separate 'URI' packages, glob @packages@ and @optional-packages@
-- into individual fields.
--
The result ' prjPackages ' ' FilePath 's will be relative to the
-- directory of the project file.
--
resolveProject
:: FilePath -- ^ filename of project file
-> Project Void String String -- ^ parsed project file
-> IO (Either ResolveError (Project URI Void FilePath)) -- ^ resolved project
resolveProject filePath prj = runExceptT $ do
prj' <- bitraverse findOptProjectPackage findProjectPackage prj
let (uris, pkgs) = partitionEithers $ concat $ prjPackages prj'
let (uris', pkgs') = partitionEithers $ concat $ prjOptPackages prj'
return prj'
{ prjPackages = pkgs ++ pkgs'
, prjOptPackages = []
, prjUriPackages = uris ++ uris'
}
where
rootdir = takeDirectory filePath
addroot p = normalise (rootdir </> p)
findProjectPackage :: String -> ExceptT ResolveError IO [Either URI FilePath]
findProjectPackage pkglocstr = do
mfp <- checkisFileGlobPackage pkglocstr `mplusMaybeT`
checkIsSingleFilePackage pkglocstr `mplusMaybeT`
return (maybe [] (singleton . Left) (parseURI pkglocstr))
case mfp of
[] -> throwE $ BadPackageLocation pkglocstr
_ -> return mfp
singleton x = [x]
findOptProjectPackage :: String -> ExceptT ResolveError IO [Either URI FilePath]
findOptProjectPackage pkglocstr =
checkisFileGlobPackage pkglocstr `mplusMaybeT`
checkIsSingleFilePackage pkglocstr
checkIsSingleFilePackage :: String -> ExceptT ResolveError IO [Either URI FilePath]
checkIsSingleFilePackage pkglocstr = do
let abspath = addroot pkglocstr
isFile <- liftIO $ doesFileExist abspath
isDir <- liftIO $ doesDirectoryExist abspath
if | isFile, Just p <- checkFile abspath -> return [p]
| isDir -> checkGlob (globStarDotCabal pkglocstr)
| otherwise -> return []
-- if it looks like glob, glob
checkisFileGlobPackage :: String -> ExceptT ResolveError IO [Either URI FilePath]
checkisFileGlobPackage pkglocstr = case C.eitherParsec pkglocstr of
Right g -> checkGlob g
Left _ -> return []
checkGlob :: FilePathGlob -> ExceptT ResolveError IO [Either URI FilePath]
checkGlob glob = do
files <- liftIO $ matchFileGlob rootdir glob
return $ mapMaybe checkFile files
checkFile :: FilePath -> Maybe (Either URI FilePath)
checkFile abspath
| ".cabal" `isSuffixOf` abspath = Just $ Right abspath
| ".tar.gz" `isSuffixOf` abspath = Just $ Left $ URI "file:" Nothing abspath "" ""
| otherwise = Nothing
-- A glob to find all the cabal files in a directory.
--
For a directory @some / dir/@ , this is a glob of the form @some / dir/\*.cabal@.
-- The directory part can be either absolute or relative.
--
globStarDotCabal :: FilePath -> FilePathGlob
globStarDotCabal dir =
FilePathGlob
(if isAbsolute dir then FilePathRoot root else FilePathRelative)
(foldr (\d -> GlobDir [Literal d])
(GlobFile [WildCard, Literal ".cabal"]) dirComponents)
where
(root, dirComponents) = fmap splitDirectories (splitDrive dir)
mplusMaybeT :: Monad m => m [a] -> m [a] -> m [a]
mplusMaybeT ma mb = do
mx <- ma
case mx of
[] -> mb
xs -> return xs
-------------------------------------------------------------------------------
-- Read package files
-------------------------------------------------------------------------------
-- | Read and parse the cabal files of packages in the 'Project'.
--
May throw ' IOException ' .
--
readPackagesOfProject :: Project uri opt FilePath -> IO (Either (ParseError NonEmpty) (Project uri opt (FilePath, C.GenericPackageDescription)))
readPackagesOfProject prj = runExceptT $ for prj $ \fp -> do
contents <- liftIO $ BS.readFile fp
either throwE (\gpd -> return (fp, gpd)) (parsePackage fp contents)
| null | https://raw.githubusercontent.com/haskell-CI/haskell-ci/336d76e1b992c4889e707c7d367497a50ebe9218/cabal-install-parsers/src/Cabal/Project.hs | haskell | # LANGUAGE DeriveFoldable #
# LANGUAGE DeriveFunctor #
# LANGUAGE DeriveTraversable #
# LANGUAGE MultiWayIf #
# LANGUAGE OverloadedStrings #
| License: GPL-3.0-or-later AND BSD-3-Clause
* Project
* Resolve project
* Read packages
$setup
>>> :set -XOverloadedStrings
| @cabal.project@ file
^ packages field
^ optional packages
^ other fields
| Doesn't compare 'prjOtherFields'
| Doesn't show 'prjOtherFields'
@since 0.4.4
| Empty project.
| @since 0.2.1
-----------------------------------------------------------------------------
Initial parsing
-----------------------------------------------------------------------------
| High level convenience function to read and elaborate @cabal.project@ files
Right ["foo","bar/*.cabal"]
Special case for source-repository-package. If you add another such
special case, make sure to update otherFieldName appropriately.
| Returns 'True' if a field should be a part of 'prjOtherFields'. This
excludes any field that is a part of 'grammar' as well as
for it).
| This contains a subset of the fields in the @cabal.project@ grammar that
-----------------------------------------------------------------------------
Lenses
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
Resolving
-----------------------------------------------------------------------------
| A 'resolveProject' error.
| Pretty print 'ResolveError'.
| Resolve project package locations.
Separate 'URI' packages, glob @packages@ and @optional-packages@
into individual fields.
directory of the project file.
^ filename of project file
^ parsed project file
^ resolved project
if it looks like glob, glob
A glob to find all the cabal files in a directory.
The directory part can be either absolute or relative.
-----------------------------------------------------------------------------
Read package files
-----------------------------------------------------------------------------
| Read and parse the cabal files of packages in the 'Project'.
| # LANGUAGE DeriveGeneric #
module Cabal.Project (
Project (..),
triverseProject,
emptyProject,
* project
readProject,
parseProject,
resolveProject,
ResolveError (..),
renderResolveError,
readPackagesOfProject
) where
import Control.DeepSeq (NFData (..))
import Control.Exception (Exception (..), throwIO)
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Trans.Except (ExceptT, runExceptT, throwE)
import Data.Bifoldable (Bifoldable (..))
import Data.Bifunctor (Bifunctor (..))
import Data.Bitraversable (Bitraversable (..), bifoldMapDefault, bimapDefault)
import Data.ByteString (ByteString)
import Data.Either (partitionEithers)
import Data.Foldable (toList)
import Data.Function ((&))
import Data.Functor (void)
import Data.List (foldl', isSuffixOf)
import Data.List.NonEmpty (NonEmpty)
import Data.Maybe (mapMaybe)
import Data.Traversable (for)
import Data.Void (Void)
import Distribution.Compat.Lens (LensLike', over)
import GHC.Generics (Generic)
import Network.URI (URI (URI), parseURI)
import System.Directory (doesDirectoryExist, doesFileExist)
import System.FilePath (isAbsolute, normalise, splitDirectories, splitDrive, takeDirectory, (</>))
import qualified Data.ByteString as BS
import qualified Data.Map.Strict as M
import qualified Distribution.CabalSpecVersion as C
import qualified Distribution.FieldGrammar as C
import qualified Distribution.Fields as C
import qualified Distribution.PackageDescription as C
import qualified Distribution.Parsec as C
import Cabal.Internal.Glob
import Cabal.Internal.Newtypes
import Cabal.Optimization
import Cabal.Package
import Cabal.Parse
import Cabal.SourceRepo
infixl 1 <&>
(<&>) :: Functor f => f a -> (a -> b) -> f b
(<&>) = flip fmap
data Project uri opt pkg = Project
^ URI packages , filled in by ' '
^ , parsed as ' 's .
^ allow - newer , parsed as ' 's .
, prjReorderGoals :: Bool
, prjMaxBackjumps :: Maybe Int
, prjOptimization :: Optimization
, prjSourceRepos :: [SourceRepositoryPackage Maybe]
}
deriving (Functor, Foldable, Traversable, Generic)
instance (Eq uri, Eq opt, Eq pkg) => Eq (Project uri opt pkg) where
x == y = and
[ eqOn prjPackages
, eqOn prjOptPackages
, eqOn prjUriPackages
, eqOn prjConstraints
, eqOn prjAllowNewer
, eqOn prjReorderGoals
, eqOn prjMaxBackjumps
, eqOn prjOptimization
, eqOn prjSourceRepos
]
where
eqOn f = f x == f y
instance (Show uri, Show opt, Show pkg) => Show (Project uri opt pkg) where
showsPrec p prj =
showParen (p > 10)
( showString "Project{prjPackages = " . shows (prjPackages prj)
. showString ", prjOptPackages = " . shows (prjOptPackages prj)
. showString ", prjUriPackages = " . shows (prjUriPackages prj)
. showString ", prjConstraints = " . shows (prjConstraints prj)
. showString ", prjAllowNewer = " . shows (prjAllowNewer prj)
. showString ", prjReorderGoals = " . shows (prjReorderGoals prj)
. showString ", prjMaxBackjumps = " . shows (prjMaxBackjumps prj)
. showString ", prjOptimization = " . shows (prjOptimization prj)
. showString ", prjSourceRepos = " . shows (prjSourceRepos prj)
. showChar '}'
)
instance Bifunctor (Project c) where bimap = bimapDefault
instance Bifoldable (Project c) where bifoldMap = bifoldMapDefault
| ' traverse ' over all three type arguments of ' Project ' .
triverseProject
:: Applicative f
=> (uri -> f uri')
-> (opt -> f opt')
-> (pkg -> f pkg')
-> Project uri opt pkg -> f (Project uri' opt' pkg')
triverseProject f g h prj =
(\c b a -> prj { prjPackages = a, prjOptPackages = b, prjUriPackages = c })
<$> traverse f (prjUriPackages prj)
<*> traverse g (prjOptPackages prj)
<*> traverse h (prjPackages prj)
instance Bitraversable (Project uri) where
bitraverse = triverseProject pure
emptyProject :: Project c b a
emptyProject = Project [] [] [] [] [] False Nothing OptimizationOn [] []
instance (NFData c, NFData b, NFData a) => NFData (Project c b a) where
rnf (Project x1 x2 x3 x4 x5 x6 x7 x8 x9 x10) =
rnf x1 `seq` rnf x2 `seq` rnf x3 `seq`
rnf x4 `seq` rnf x5 `seq` rnf x6 `seq`
rnf x7 `seq` rnf x8 `seq` rnf x9 `seq`
rnfList rnfPrettyField x10
where
rnfList :: (a -> ()) -> [a] -> ()
rnfList _ [] = ()
rnfList f (x:xs) = f x `seq` rnfList f xs
rnfPrettyField :: NFData x => C.PrettyField x -> ()
rnfPrettyField C.PrettyEmpty = ()
rnfPrettyField (C.PrettyField ann fn d) =
rnf ann `seq` rnf fn `seq` rnf d
rnfPrettyField (C.PrettySection ann fn ds fs) =
rnf ann `seq` rnf fn `seq` rnf ds `seq` rnfList rnfPrettyField fs
May throw ' IOException ' when file does n't exist , ' ParseError '
on parse errors , or ' ResolveError ' on package resolution error .
readProject :: FilePath -> IO (Project URI Void (FilePath, C.GenericPackageDescription))
readProject fp = do
contents <- BS.readFile fp
prj0 <- either throwIO return (parseProject fp contents)
prj1 <- resolveProject fp prj0 >>= either throwIO return
readPackagesOfProject prj1 >>= either throwIO return
| Parse project file . Extracts only few fields .
> > > fmap prjPackages $ parseProject " cabal.project " " packages : foo bar/*.cabal "
parseProject :: FilePath -> ByteString -> Either (ParseError NonEmpty) (Project Void String String)
parseProject = parseWith $ \fields0 -> do
let (fields1, sections) = C.partitionFields fields0
let fields2 = M.filterWithKey (\k _ -> k `elem` knownFields) fields1
parse fields0 fields2 sections
where
knownFields = C.fieldGrammarKnownFieldList $ grammar []
parse otherFields fields sections = do
let prettyOtherFields = map void $ C.fromParsecFields $ filter otherFieldName otherFields
prj <- C.parseFieldGrammar C.cabalSpecLatest fields $ grammar prettyOtherFields
foldl' (&) prj <$> traverse parseSec (concat sections)
parseSec :: C.Section C.Position -> C.ParseResult (Project Void String String -> Project Void String String)
parseSec (C.MkSection (C.Name _pos name) [] fields) | name == sourceRepoSectionName = do
let fields' = fst $ C.partitionFields fields
repos <- C.parseFieldGrammar C.cabalSpecLatest fields' sourceRepositoryPackageGrammar
return $ over prjSourceReposL (++ toList (srpFanOut repos))
parseSec _ = return id
@source - repository - package@ ( see ' parseProject ' , which has a special case
otherFieldName :: C.Field ann -> Bool
otherFieldName (C.Field (C.Name _ fn) _) = fn `notElem` C.fieldGrammarKnownFieldList (grammar [])
otherFieldName (C.Section (C.Name _ fn) _ _) = fn /= sourceRepoSectionName
are distinguished by a ' Project ' . Note that this does not /not/ contain
@source - repository - package@ , as that is handled separately in ' parseProject ' .
grammar :: [C.PrettyField ()] -> C.ParsecFieldGrammar (Project Void String String) (Project Void String String)
grammar otherFields = Project
<$> C.monoidalFieldAla "packages" (C.alaList' C.FSep PackageLocation) prjPackagesL
<*> C.monoidalFieldAla "optional-packages" (C.alaList' C.FSep PackageLocation) prjOptPackagesL
<*> pure []
<*> C.monoidalFieldAla "constraints" (C.alaList' C.CommaVCat NoCommas) prjConstraintsL
<*> C.monoidalFieldAla "allow-newer" (C.alaList' C.CommaVCat NoCommas) prjAllowNewerL
<*> C.booleanFieldDef "reorder-goals" prjReorderGoalsL False
<*> C.optionalFieldAla "max-backjumps" Int' prjMaxBackjumpsL
<*> C.optionalFieldDef "optimization" prjOptimizationL OptimizationOn
<*> pure []
<*> pure otherFields
sourceRepoSectionName :: C.FieldName
sourceRepoSectionName = "source-repository-package"
prjPackagesL :: Functor f => LensLike' f (Project uri opt pkg) [pkg]
prjPackagesL f prj = f (prjPackages prj) <&> \x -> prj { prjPackages = x }
prjOptPackagesL :: Functor f => LensLike' f (Project uri opt pkg) [opt]
prjOptPackagesL f prj = f (prjOptPackages prj) <&> \x -> prj { prjOptPackages = x }
prjConstraintsL :: Functor f => LensLike' f (Project uri opt pkg) [String]
prjConstraintsL f prj = f (prjConstraints prj) <&> \x -> prj { prjConstraints = x }
prjAllowNewerL :: Functor f => LensLike' f (Project uri opt pkg) [String]
prjAllowNewerL f prj = f (prjAllowNewer prj) <&> \x -> prj { prjAllowNewer = x }
prjReorderGoalsL :: Functor f => LensLike' f (Project uri opt pkg) Bool
prjReorderGoalsL f prj = f (prjReorderGoals prj) <&> \x -> prj { prjReorderGoals = x }
prjMaxBackjumpsL :: Functor f => LensLike' f (Project uri opt pkg) (Maybe Int)
prjMaxBackjumpsL f prj = f (prjMaxBackjumps prj) <&> \x -> prj { prjMaxBackjumps = x }
prjOptimizationL :: Functor f => LensLike' f (Project uri opt pkg) Optimization
prjOptimizationL f prj = f (prjOptimization prj) <&> \x -> prj { prjOptimization = x }
prjSourceReposL :: Functor f => LensLike' f (Project uri opt pkg) [SourceRepositoryPackage Maybe]
prjSourceReposL f prj = f (prjSourceRepos prj) <&> \x -> prj { prjSourceRepos = x }
newtype ResolveError = BadPackageLocation String
deriving Show
instance Exception ResolveError where
displayException = renderResolveError
renderResolveError :: ResolveError -> String
renderResolveError (BadPackageLocation s) = "Bad package location: " ++ show s
The result ' prjPackages ' ' FilePath 's will be relative to the
resolveProject
resolveProject filePath prj = runExceptT $ do
prj' <- bitraverse findOptProjectPackage findProjectPackage prj
let (uris, pkgs) = partitionEithers $ concat $ prjPackages prj'
let (uris', pkgs') = partitionEithers $ concat $ prjOptPackages prj'
return prj'
{ prjPackages = pkgs ++ pkgs'
, prjOptPackages = []
, prjUriPackages = uris ++ uris'
}
where
rootdir = takeDirectory filePath
addroot p = normalise (rootdir </> p)
findProjectPackage :: String -> ExceptT ResolveError IO [Either URI FilePath]
findProjectPackage pkglocstr = do
mfp <- checkisFileGlobPackage pkglocstr `mplusMaybeT`
checkIsSingleFilePackage pkglocstr `mplusMaybeT`
return (maybe [] (singleton . Left) (parseURI pkglocstr))
case mfp of
[] -> throwE $ BadPackageLocation pkglocstr
_ -> return mfp
singleton x = [x]
findOptProjectPackage :: String -> ExceptT ResolveError IO [Either URI FilePath]
findOptProjectPackage pkglocstr =
checkisFileGlobPackage pkglocstr `mplusMaybeT`
checkIsSingleFilePackage pkglocstr
checkIsSingleFilePackage :: String -> ExceptT ResolveError IO [Either URI FilePath]
checkIsSingleFilePackage pkglocstr = do
let abspath = addroot pkglocstr
isFile <- liftIO $ doesFileExist abspath
isDir <- liftIO $ doesDirectoryExist abspath
if | isFile, Just p <- checkFile abspath -> return [p]
| isDir -> checkGlob (globStarDotCabal pkglocstr)
| otherwise -> return []
checkisFileGlobPackage :: String -> ExceptT ResolveError IO [Either URI FilePath]
checkisFileGlobPackage pkglocstr = case C.eitherParsec pkglocstr of
Right g -> checkGlob g
Left _ -> return []
checkGlob :: FilePathGlob -> ExceptT ResolveError IO [Either URI FilePath]
checkGlob glob = do
files <- liftIO $ matchFileGlob rootdir glob
return $ mapMaybe checkFile files
checkFile :: FilePath -> Maybe (Either URI FilePath)
checkFile abspath
| ".cabal" `isSuffixOf` abspath = Just $ Right abspath
| ".tar.gz" `isSuffixOf` abspath = Just $ Left $ URI "file:" Nothing abspath "" ""
| otherwise = Nothing
For a directory @some / dir/@ , this is a glob of the form @some / dir/\*.cabal@.
globStarDotCabal :: FilePath -> FilePathGlob
globStarDotCabal dir =
FilePathGlob
(if isAbsolute dir then FilePathRoot root else FilePathRelative)
(foldr (\d -> GlobDir [Literal d])
(GlobFile [WildCard, Literal ".cabal"]) dirComponents)
where
(root, dirComponents) = fmap splitDirectories (splitDrive dir)
mplusMaybeT :: Monad m => m [a] -> m [a] -> m [a]
mplusMaybeT ma mb = do
mx <- ma
case mx of
[] -> mb
xs -> return xs
May throw ' IOException ' .
readPackagesOfProject :: Project uri opt FilePath -> IO (Either (ParseError NonEmpty) (Project uri opt (FilePath, C.GenericPackageDescription)))
readPackagesOfProject prj = runExceptT $ for prj $ \fp -> do
contents <- liftIO $ BS.readFile fp
either throwE (\gpd -> return (fp, gpd)) (parsePackage fp contents)
|
2ce82e73426afdb8ebbd7d0dd61dce4b93854ddebd612437b934ad9e8e729f16 | elastic/eui-cljs | tabs.cljs | (ns eui.tabs
(:require ["@elastic/eui/lib/components/tabs/tabs.js" :as eui]))
(def SIZES eui/SIZES)
(def EuiTabs eui/EuiTabs)
| null | https://raw.githubusercontent.com/elastic/eui-cljs/ad60b57470a2eb8db9bca050e02f52dd964d9f8e/src/eui/tabs.cljs | clojure | (ns eui.tabs
(:require ["@elastic/eui/lib/components/tabs/tabs.js" :as eui]))
(def SIZES eui/SIZES)
(def EuiTabs eui/EuiTabs)
| |
e3b1131d0f68d04192bb0bf158fc1a58455c77a8d38825530579f46242d7110a | launchdarkly/erlang-server-sdk | ldclient_instance_sup.erl | %%-------------------------------------------------------------------
%% @doc Instance supervisor
@private
%% @end
%%-------------------------------------------------------------------
-module(ldclient_instance_sup).
-behaviour(supervisor).
%% Supervision
-export([start_link/5, init/1, child_spec/1, child_spec/2]).
%% Helper macro for declaring children of supervisor
-define(CHILD(Id, Module, Args, Type), {Id, {Module, start_link, Args}, permanent, 5000, Type, [Module]}).
child_spec(Args) -> child_spec(?MODULE, Args).
child_spec(Id, Args) ->
#{
id => Id,
start => {?MODULE, start_link, Args},
restart => permanent,
shutdown => 5000, % shutdown time
type => supervisor,
modules => [?MODULE]
}.
%%===================================================================
%% Supervision
%%===================================================================
-spec start_link(
SupName :: atom(),
UpdateSupName :: atom(),
UpdateWorkerModule :: atom(),
EventSupName :: atom(),
Tag :: atom()
) ->
{ok, Pid :: pid()} | ignore | {error, Reason :: term()}.
start_link(SupName, UpdateSupName, UpdateWorkerModule, EventSupName, Tag) ->
error_logger:info_msg("Starting instance supervisor for ~p with name ~p", [Tag, SupName]),
supervisor:start_link({local, SupName}, ?MODULE, [UpdateSupName, UpdateWorkerModule, EventSupName, Tag]).
-spec init(Args :: term()) ->
{ok, {{supervisor:strategy(), non_neg_integer(), pos_integer()}, [supervisor:child_spec()]}}.
init([UpdateSupName, UpdateWorkerModule, EventSupName, Tag]) ->
{ok, {{one_for_one, 1, 5}, children(UpdateSupName, UpdateWorkerModule, EventSupName, Tag)}}.
%%===================================================================
Internal functions
%%===================================================================
-spec children(
UpdateSupName :: atom(),
UpdateWorkerModule :: atom(),
EventSupName :: atom(),
Tag :: atom()
) -> [supervisor:child_spec()].
children(UpdateSupName, UpdateWorkerModule, EventSupName, Tag) ->
UpdateSup = ?CHILD(ldclient_update_sup, ldclient_update_sup, [UpdateSupName, UpdateWorkerModule], supervisor),
EventSup = ?CHILD(ldclient_event_sup, ldclient_event_sup, [EventSupName, Tag], supervisor),
[UpdateSup, EventSup].
| null | https://raw.githubusercontent.com/launchdarkly/erlang-server-sdk/fabbcae4953020a0c93bce99e80c1729ebd447d5/src/ldclient_instance_sup.erl | erlang | -------------------------------------------------------------------
@doc Instance supervisor
@end
-------------------------------------------------------------------
Supervision
Helper macro for declaring children of supervisor
shutdown time
===================================================================
Supervision
===================================================================
===================================================================
=================================================================== | @private
-module(ldclient_instance_sup).
-behaviour(supervisor).
-export([start_link/5, init/1, child_spec/1, child_spec/2]).
-define(CHILD(Id, Module, Args, Type), {Id, {Module, start_link, Args}, permanent, 5000, Type, [Module]}).
child_spec(Args) -> child_spec(?MODULE, Args).
child_spec(Id, Args) ->
#{
id => Id,
start => {?MODULE, start_link, Args},
restart => permanent,
type => supervisor,
modules => [?MODULE]
}.
-spec start_link(
SupName :: atom(),
UpdateSupName :: atom(),
UpdateWorkerModule :: atom(),
EventSupName :: atom(),
Tag :: atom()
) ->
{ok, Pid :: pid()} | ignore | {error, Reason :: term()}.
start_link(SupName, UpdateSupName, UpdateWorkerModule, EventSupName, Tag) ->
error_logger:info_msg("Starting instance supervisor for ~p with name ~p", [Tag, SupName]),
supervisor:start_link({local, SupName}, ?MODULE, [UpdateSupName, UpdateWorkerModule, EventSupName, Tag]).
-spec init(Args :: term()) ->
{ok, {{supervisor:strategy(), non_neg_integer(), pos_integer()}, [supervisor:child_spec()]}}.
init([UpdateSupName, UpdateWorkerModule, EventSupName, Tag]) ->
{ok, {{one_for_one, 1, 5}, children(UpdateSupName, UpdateWorkerModule, EventSupName, Tag)}}.
Internal functions
-spec children(
UpdateSupName :: atom(),
UpdateWorkerModule :: atom(),
EventSupName :: atom(),
Tag :: atom()
) -> [supervisor:child_spec()].
children(UpdateSupName, UpdateWorkerModule, EventSupName, Tag) ->
UpdateSup = ?CHILD(ldclient_update_sup, ldclient_update_sup, [UpdateSupName, UpdateWorkerModule], supervisor),
EventSup = ?CHILD(ldclient_event_sup, ldclient_event_sup, [EventSupName, Tag], supervisor),
[UpdateSup, EventSup].
|
5f87ed4653ec14c77ce348901efd0e99f461eb23711a1712d5e0bac1e5da294e | facebook/Haxl | Bench.hs | Copyright ( c ) 2014 - present , Facebook , Inc.
-- All rights reserved.
--
This source code is distributed under the terms of a BSD license ,
-- found in the LICENSE file.
# LANGUAGE RankNTypes , GADTs , BangPatterns , DeriveDataTypeable ,
StandaloneDeriving #
StandaloneDeriving #-}
# OPTIONS_GHC -fno - warn - unused - do - bind -fno - warn - type - defaults #
module Bench where
import Haxl.Core.DataCache as DataCache
import Prelude hiding (mapM)
import Data.Hashable
import Data.IORef
import Data.Time.Clock
import Data.Traversable
import Data.Typeable
import System.Environment
import Text.Printf
data TestReq a where
ReqInt :: {-# UNPACK #-} !Int -> TestReq Int
ReqDouble :: {-# UNPACK #-} !Int -> TestReq Double
ReqBool :: {-# UNPACK #-} !Int -> TestReq Bool
deriving Typeable
deriving instance Eq (TestReq a)
deriving instance Show (TestReq a)
instance Hashable (TestReq a) where
hashWithSalt salt (ReqInt i) = hashWithSalt salt (0::Int, i)
hashWithSalt salt (ReqDouble i) = hashWithSalt salt (1::Int, i)
hashWithSalt salt (ReqBool i) = hashWithSalt salt (2::Int, i)
main = do
[n] <- fmap (fmap read) getArgs
t0 <- getCurrentTime
cache <- emptyDataCache
let
f 0 = return ()
f !n = do
m <- newIORef 0
DataCache.insert (ReqInt n) m cache
f (n-1)
--
f n
m <- DataCache.lookup (ReqInt (n `div` 2)) cache
print =<< mapM readIORef m
t1 <- getCurrentTime
printf "insert: %.2fs\n" (realToFrac (t1 `diffUTCTime` t0) :: Double)
t0 <- getCurrentTime
let
f 0 !m = return m
f !n !m = do
mbRes <- DataCache.lookup (ReqInt n) cache
case mbRes of
Nothing -> f (n-1) m
Just _ -> f (n-1) (m+1)
f n 0 >>= print
t1 <- getCurrentTime
printf "lookup: %.2fs\n" (realToFrac (t1 `diffUTCTime` t0) :: Double)
| null | https://raw.githubusercontent.com/facebook/Haxl/8f018dc9cffe641bc0d88d29934d378c82a1246d/tests/Bench.hs | haskell | All rights reserved.
found in the LICENSE file.
# UNPACK #
# UNPACK #
# UNPACK #
| Copyright ( c ) 2014 - present , Facebook , Inc.
This source code is distributed under the terms of a BSD license ,
# LANGUAGE RankNTypes , GADTs , BangPatterns , DeriveDataTypeable ,
StandaloneDeriving #
StandaloneDeriving #-}
# OPTIONS_GHC -fno - warn - unused - do - bind -fno - warn - type - defaults #
module Bench where
import Haxl.Core.DataCache as DataCache
import Prelude hiding (mapM)
import Data.Hashable
import Data.IORef
import Data.Time.Clock
import Data.Traversable
import Data.Typeable
import System.Environment
import Text.Printf
data TestReq a where
deriving Typeable
deriving instance Eq (TestReq a)
deriving instance Show (TestReq a)
instance Hashable (TestReq a) where
hashWithSalt salt (ReqInt i) = hashWithSalt salt (0::Int, i)
hashWithSalt salt (ReqDouble i) = hashWithSalt salt (1::Int, i)
hashWithSalt salt (ReqBool i) = hashWithSalt salt (2::Int, i)
main = do
[n] <- fmap (fmap read) getArgs
t0 <- getCurrentTime
cache <- emptyDataCache
let
f 0 = return ()
f !n = do
m <- newIORef 0
DataCache.insert (ReqInt n) m cache
f (n-1)
f n
m <- DataCache.lookup (ReqInt (n `div` 2)) cache
print =<< mapM readIORef m
t1 <- getCurrentTime
printf "insert: %.2fs\n" (realToFrac (t1 `diffUTCTime` t0) :: Double)
t0 <- getCurrentTime
let
f 0 !m = return m
f !n !m = do
mbRes <- DataCache.lookup (ReqInt n) cache
case mbRes of
Nothing -> f (n-1) m
Just _ -> f (n-1) (m+1)
f n 0 >>= print
t1 <- getCurrentTime
printf "lookup: %.2fs\n" (realToFrac (t1 `diffUTCTime` t0) :: Double)
|
c7126ec2ca2d9613a252976aa8b72642d2e3a9f50384de4a061afeec308d6586 | polyfy/polylith | table.clj | (ns polylith.clj.core.text-table.table
(:require [clojure.string :as str]
[polylith.clj.core.util.interface.color :as c]
[polylith.clj.core.util.interface.str :as str-util]))
(defn none [_ & strings]
(str/join strings))
(def color->function
{:none none
:cyan c/cyan
:grey c/grey
:yellow c/yellow
:green c/green
:blue c/blue
:purple c/purple})
(defn align [[[x y] {:keys [value align color]}] max-width color-mode]
(let [cnt (- max-width (-> value str c/clean-colors count))
cnt-left (quot cnt 2)
cnt-right (- cnt cnt-left)
color-fn (color->function color)
spc (str-util/spaces cnt)
spc-left (str-util/spaces cnt-left)
spc-right (str-util/spaces cnt-right)
new-value (condp = align
:left (color-fn color-mode value spc)
:right (color-fn color-mode spc value)
:center (color-fn color-mode spc-left value spc-right)
(str "Error. Can't find alignment: " align))]
[[x y] {:value new-value}]))
(defn column [x cells]
(filter #(= x (ffirst %)) cells))
(defn max-column-width [x cells]
(apply max (mapv #(-> % second :value c/clean-colors count)
(column x cells))))
(defn align-column [x cells color-mode]
(let [max-width (max-column-width x cells)]
(map #(align % max-width color-mode)
(column x cells))))
(defn align-table [cells color-mode]
(into {} (mapcat #(align-column % cells color-mode) (set (map ffirst cells)))))
(defn value [x y x->spaces cells]
(if-let [{:keys [value]} (cells [x y])]
value
(or (x->spaces x) "#ERROR#")))
(defn row [initial-spaces y xs x->spaces cells]
(str initial-spaces (str/join (mapv #(value % y x->spaces cells) xs))))
(defn table [initial-spaces cells color-mode]
(let [aligned-cells (align-table cells color-mode)
xs (sort (set (map ffirst aligned-cells)))
ys (sort (set (map #(-> % first second) aligned-cells)))
x->spaces (into {} (map (juxt identity #(str-util/spaces (max-column-width % aligned-cells))) xs))]
(mapv #(row initial-spaces % xs x->spaces aligned-cells) ys)))
| null | https://raw.githubusercontent.com/polyfy/polylith/76936c752fb5b729c216b23d92c8a8d71cfdc92f/components/text-table/src/polylith/clj/core/text_table/table.clj | clojure | (ns polylith.clj.core.text-table.table
(:require [clojure.string :as str]
[polylith.clj.core.util.interface.color :as c]
[polylith.clj.core.util.interface.str :as str-util]))
(defn none [_ & strings]
(str/join strings))
(def color->function
{:none none
:cyan c/cyan
:grey c/grey
:yellow c/yellow
:green c/green
:blue c/blue
:purple c/purple})
(defn align [[[x y] {:keys [value align color]}] max-width color-mode]
(let [cnt (- max-width (-> value str c/clean-colors count))
cnt-left (quot cnt 2)
cnt-right (- cnt cnt-left)
color-fn (color->function color)
spc (str-util/spaces cnt)
spc-left (str-util/spaces cnt-left)
spc-right (str-util/spaces cnt-right)
new-value (condp = align
:left (color-fn color-mode value spc)
:right (color-fn color-mode spc value)
:center (color-fn color-mode spc-left value spc-right)
(str "Error. Can't find alignment: " align))]
[[x y] {:value new-value}]))
(defn column [x cells]
(filter #(= x (ffirst %)) cells))
(defn max-column-width [x cells]
(apply max (mapv #(-> % second :value c/clean-colors count)
(column x cells))))
(defn align-column [x cells color-mode]
(let [max-width (max-column-width x cells)]
(map #(align % max-width color-mode)
(column x cells))))
(defn align-table [cells color-mode]
(into {} (mapcat #(align-column % cells color-mode) (set (map ffirst cells)))))
(defn value [x y x->spaces cells]
(if-let [{:keys [value]} (cells [x y])]
value
(or (x->spaces x) "#ERROR#")))
(defn row [initial-spaces y xs x->spaces cells]
(str initial-spaces (str/join (mapv #(value % y x->spaces cells) xs))))
(defn table [initial-spaces cells color-mode]
(let [aligned-cells (align-table cells color-mode)
xs (sort (set (map ffirst aligned-cells)))
ys (sort (set (map #(-> % first second) aligned-cells)))
x->spaces (into {} (map (juxt identity #(str-util/spaces (max-column-width % aligned-cells))) xs))]
(mapv #(row initial-spaces % xs x->spaces aligned-cells) ys)))
| |
12533c7ecf9f01ab9254a050b6abd13d2c91454b2543f3971c518863f6ed2c13 | wadehennessey/wcl | keysyms.lisp | -*- Mode : Lisp ; Package : XLIB ; Syntax : COMMON - LISP ; ; Lowercase : YES -*-
;;; Define lisp character to keysym mappings
;;;
TEXAS INSTRUMENTS INCORPORATED
;;; P.O. BOX 2909
AUSTIN , TEXAS 78769
;;;
Copyright ( C ) 1987 Texas Instruments Incorporated .
;;;
;;; Permission is granted to any individual or institution to use, copy, modify,
;;; and distribute this software, provided that this complete copyright and
;;; permission notice is maintained, intact, in all copies and supporting
;;; documentation.
;;;
Texas Instruments Incorporated provides this software " as is " without
;;; express or implied warranty.
;;;
(in-package "XLIB")
(define-keysym-set :latin-1 (keysym 0 0) (keysym 0 255))
(define-keysym-set :latin-2 (keysym 1 0) (keysym 1 255))
(define-keysym-set :latin-3 (keysym 2 0) (keysym 2 255))
(define-keysym-set :latin-4 (keysym 3 0) (keysym 3 255))
(define-keysym-set :kana (keysym 4 0) (keysym 4 255))
(define-keysym-set :arabic (keysym 5 0) (keysym 5 255))
(define-keysym-set :cryllic (keysym 6 0) (keysym 6 255))
(define-keysym-set :greek (keysym 7 0) (keysym 7 255))
(define-keysym-set :tech (keysym 8 0) (keysym 8 255))
(define-keysym-set :special (keysym 9 0) (keysym 9 255))
(define-keysym-set :publish (keysym 10 0) (keysym 10 255))
(define-keysym-set :apl (keysym 11 0) (keysym 11 255))
(define-keysym-set :hebrew (keysym 12 0) (keysym 12 255))
(define-keysym-set :keyboard (keysym 255 0) (keysym 255 255))
(define-keysym :character-set-switch character-set-switch-keysym)
(define-keysym :left-shift left-shift-keysym)
(define-keysym :right-shift right-shift-keysym)
(define-keysym :left-control left-control-keysym)
(define-keysym :right-control right-control-keysym)
(define-keysym :caps-lock caps-lock-keysym)
(define-keysym :shift-lock shift-lock-keysym)
(define-keysym :left-meta left-meta-keysym)
(define-keysym :right-meta right-meta-keysym)
(define-keysym :left-alt left-alt-keysym)
(define-keysym :right-alt right-alt-keysym)
(define-keysym :left-super left-super-keysym)
(define-keysym :right-super right-super-keysym)
(define-keysym :left-hyper left-hyper-keysym)
(define-keysym :right-hyper right-hyper-keysym)
(define-keysym #\space 032)
(define-keysym #\! 033)
(define-keysym #\" 034)
(define-keysym #\# 035)
(define-keysym #\$ 036)
(define-keysym #\% 037)
(define-keysym #\& 038)
(define-keysym #\' 039)
(define-keysym #\( 040)
(define-keysym #\) 041)
(define-keysym #\* 042)
(define-keysym #\+ 043)
(define-keysym #\, 044)
(define-keysym #\- 045)
(define-keysym #\. 046)
(define-keysym #\/ 047)
(define-keysym #\0 048)
(define-keysym #\1 049)
(define-keysym #\2 050)
(define-keysym #\3 051)
(define-keysym #\4 052)
(define-keysym #\5 053)
(define-keysym #\6 054)
(define-keysym #\7 055)
(define-keysym #\8 056)
(define-keysym #\9 057)
(define-keysym #\: 058)
059 )
(define-keysym #\< 060)
(define-keysym #\= 061)
(define-keysym #\> 062)
(define-keysym #\? 063)
(define-keysym #\@ 064)
(define-keysym #\A 065 :lowercase 097)
(define-keysym #\B 066 :lowercase 098)
(define-keysym #\C 067 :lowercase 099)
(define-keysym #\D 068 :lowercase 100)
(define-keysym #\E 069 :lowercase 101)
(define-keysym #\F 070 :lowercase 102)
(define-keysym #\G 071 :lowercase 103)
(define-keysym #\H 072 :lowercase 104)
(define-keysym #\I 073 :lowercase 105)
(define-keysym #\J 074 :lowercase 106)
(define-keysym #\K 075 :lowercase 107)
(define-keysym #\L 076 :lowercase 108)
(define-keysym #\M 077 :lowercase 109)
(define-keysym #\N 078 :lowercase 110)
(define-keysym #\O 079 :lowercase 111)
(define-keysym #\P 080 :lowercase 112)
(define-keysym #\Q 081 :lowercase 113)
(define-keysym #\R 082 :lowercase 114)
(define-keysym #\S 083 :lowercase 115)
(define-keysym #\T 084 :lowercase 116)
(define-keysym #\U 085 :lowercase 117)
(define-keysym #\V 086 :lowercase 118)
(define-keysym #\W 087 :lowercase 119)
(define-keysym #\X 088 :lowercase 120)
(define-keysym #\Y 089 :lowercase 121)
(define-keysym #\Z 090 :lowercase 122)
(define-keysym #\[ 091)
(define-keysym #\\ 092)
(define-keysym #\] 093)
(define-keysym #\^ 094)
(define-keysym #\_ 095)
(define-keysym #\` 096)
(define-keysym #\a 097)
(define-keysym #\b 098)
(define-keysym #\c 099)
(define-keysym #\d 100)
(define-keysym #\e 101)
(define-keysym #\f 102)
(define-keysym #\g 103)
(define-keysym #\h 104)
(define-keysym #\i 105)
(define-keysym #\j 106)
(define-keysym #\k 107)
(define-keysym #\l 108)
(define-keysym #\m 109)
(define-keysym #\n 110)
(define-keysym #\o 111)
(define-keysym #\p 112)
(define-keysym #\q 113)
(define-keysym #\r 114)
(define-keysym #\s 115)
(define-keysym #\t 116)
(define-keysym #\u 117)
(define-keysym #\v 118)
(define-keysym #\w 119)
(define-keysym #\x 120)
(define-keysym #\y 121)
(define-keysym #\z 122)
(define-keysym #\{ 123)
(define-keysym #\| 124)
(define-keysym #\} 125)
(define-keysym #\~ 126)
(progn ;; Semi-standard characters
(define-keysym #\rubout (keysym 255 255)) ; :tty
(define-keysym #\tab (keysym 255 009)) ; :tty
(define-keysym #\linefeed (keysym 255 010)) ; :tty
(define-keysym #\page (keysym 009 227)) ; :special
(define-keysym #\return (keysym 255 013)) ; :tty
(define-keysym #\backspace (keysym 255 008)) ; :tty
)
| null | https://raw.githubusercontent.com/wadehennessey/wcl/841316ffe06743d4c14b4ed70819bdb39158df6a/src/clx/keysyms.lisp | lisp | Package : XLIB ; Syntax : COMMON - LISP ; ; Lowercase : YES -*-
Define lisp character to keysym mappings
P.O. BOX 2909
Permission is granted to any individual or institution to use, copy, modify,
and distribute this software, provided that this complete copyright and
permission notice is maintained, intact, in all copies and supporting
documentation.
express or implied warranty.
Semi-standard characters
:tty
:tty
:tty
:special
:tty
:tty |
TEXAS INSTRUMENTS INCORPORATED
AUSTIN , TEXAS 78769
Copyright ( C ) 1987 Texas Instruments Incorporated .
Texas Instruments Incorporated provides this software " as is " without
(in-package "XLIB")
(define-keysym-set :latin-1 (keysym 0 0) (keysym 0 255))
(define-keysym-set :latin-2 (keysym 1 0) (keysym 1 255))
(define-keysym-set :latin-3 (keysym 2 0) (keysym 2 255))
(define-keysym-set :latin-4 (keysym 3 0) (keysym 3 255))
(define-keysym-set :kana (keysym 4 0) (keysym 4 255))
(define-keysym-set :arabic (keysym 5 0) (keysym 5 255))
(define-keysym-set :cryllic (keysym 6 0) (keysym 6 255))
(define-keysym-set :greek (keysym 7 0) (keysym 7 255))
(define-keysym-set :tech (keysym 8 0) (keysym 8 255))
(define-keysym-set :special (keysym 9 0) (keysym 9 255))
(define-keysym-set :publish (keysym 10 0) (keysym 10 255))
(define-keysym-set :apl (keysym 11 0) (keysym 11 255))
(define-keysym-set :hebrew (keysym 12 0) (keysym 12 255))
(define-keysym-set :keyboard (keysym 255 0) (keysym 255 255))
(define-keysym :character-set-switch character-set-switch-keysym)
(define-keysym :left-shift left-shift-keysym)
(define-keysym :right-shift right-shift-keysym)
(define-keysym :left-control left-control-keysym)
(define-keysym :right-control right-control-keysym)
(define-keysym :caps-lock caps-lock-keysym)
(define-keysym :shift-lock shift-lock-keysym)
(define-keysym :left-meta left-meta-keysym)
(define-keysym :right-meta right-meta-keysym)
(define-keysym :left-alt left-alt-keysym)
(define-keysym :right-alt right-alt-keysym)
(define-keysym :left-super left-super-keysym)
(define-keysym :right-super right-super-keysym)
(define-keysym :left-hyper left-hyper-keysym)
(define-keysym :right-hyper right-hyper-keysym)
(define-keysym #\space 032)
(define-keysym #\! 033)
(define-keysym #\" 034)
(define-keysym #\# 035)
(define-keysym #\$ 036)
(define-keysym #\% 037)
(define-keysym #\& 038)
(define-keysym #\' 039)
(define-keysym #\( 040)
(define-keysym #\) 041)
(define-keysym #\* 042)
(define-keysym #\+ 043)
(define-keysym #\, 044)
(define-keysym #\- 045)
(define-keysym #\. 046)
(define-keysym #\/ 047)
(define-keysym #\0 048)
(define-keysym #\1 049)
(define-keysym #\2 050)
(define-keysym #\3 051)
(define-keysym #\4 052)
(define-keysym #\5 053)
(define-keysym #\6 054)
(define-keysym #\7 055)
(define-keysym #\8 056)
(define-keysym #\9 057)
(define-keysym #\: 058)
059 )
(define-keysym #\< 060)
(define-keysym #\= 061)
(define-keysym #\> 062)
(define-keysym #\? 063)
(define-keysym #\@ 064)
(define-keysym #\A 065 :lowercase 097)
(define-keysym #\B 066 :lowercase 098)
(define-keysym #\C 067 :lowercase 099)
(define-keysym #\D 068 :lowercase 100)
(define-keysym #\E 069 :lowercase 101)
(define-keysym #\F 070 :lowercase 102)
(define-keysym #\G 071 :lowercase 103)
(define-keysym #\H 072 :lowercase 104)
(define-keysym #\I 073 :lowercase 105)
(define-keysym #\J 074 :lowercase 106)
(define-keysym #\K 075 :lowercase 107)
(define-keysym #\L 076 :lowercase 108)
(define-keysym #\M 077 :lowercase 109)
(define-keysym #\N 078 :lowercase 110)
(define-keysym #\O 079 :lowercase 111)
(define-keysym #\P 080 :lowercase 112)
(define-keysym #\Q 081 :lowercase 113)
(define-keysym #\R 082 :lowercase 114)
(define-keysym #\S 083 :lowercase 115)
(define-keysym #\T 084 :lowercase 116)
(define-keysym #\U 085 :lowercase 117)
(define-keysym #\V 086 :lowercase 118)
(define-keysym #\W 087 :lowercase 119)
(define-keysym #\X 088 :lowercase 120)
(define-keysym #\Y 089 :lowercase 121)
(define-keysym #\Z 090 :lowercase 122)
(define-keysym #\[ 091)
(define-keysym #\\ 092)
(define-keysym #\] 093)
(define-keysym #\^ 094)
(define-keysym #\_ 095)
(define-keysym #\` 096)
(define-keysym #\a 097)
(define-keysym #\b 098)
(define-keysym #\c 099)
(define-keysym #\d 100)
(define-keysym #\e 101)
(define-keysym #\f 102)
(define-keysym #\g 103)
(define-keysym #\h 104)
(define-keysym #\i 105)
(define-keysym #\j 106)
(define-keysym #\k 107)
(define-keysym #\l 108)
(define-keysym #\m 109)
(define-keysym #\n 110)
(define-keysym #\o 111)
(define-keysym #\p 112)
(define-keysym #\q 113)
(define-keysym #\r 114)
(define-keysym #\s 115)
(define-keysym #\t 116)
(define-keysym #\u 117)
(define-keysym #\v 118)
(define-keysym #\w 119)
(define-keysym #\x 120)
(define-keysym #\y 121)
(define-keysym #\z 122)
(define-keysym #\{ 123)
(define-keysym #\| 124)
(define-keysym #\} 125)
(define-keysym #\~ 126)
)
|
50c0f1d4ad50f8f7a08ebfbddddcb6148e67259571fbaec06856e9e06217d192 | ocaml-ppx/ppx | ast_pattern_generated.ml | open! Import
open Current_ast
open Ast_pattern0
(*$ Ppxlib_cinaps_helpers.generate_ast_pattern_impl () *)
let lident (T f0') =
T (fun c' l' x' k' ->
match Longident.to_concrete_opt x' with
| Some (Lident (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Lident"
)
let ldot (T f0') (T f1') =
T (fun c' l' x' k' ->
match Longident.to_concrete_opt x' with
| Some (Ldot (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Ldot"
)
let lapply (T f0') (T f1') =
T (fun c' l' x' k' ->
match Longident.to_concrete_opt x' with
| Some (Lapply (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Lapply"
)
let labelled (T f0') =
T (fun c' l' x' k' ->
match Arg_label.to_concrete_opt x' with
| Some (Labelled (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Labelled"
)
let optional (T f0') =
T (fun c' l' x' k' ->
match Arg_label.to_concrete_opt x' with
| Some (Optional (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Optional"
)
let pconst_integer (T f0') (T f1') =
T (fun c' l' x' k' ->
match Constant.to_concrete_opt x' with
| Some (Pconst_integer (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pconst_integer"
)
let pconst_char (T f0') =
T (fun c' l' x' k' ->
match Constant.to_concrete_opt x' with
| Some (Pconst_char (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pconst_char"
)
let pconst_string (T f0') (T f1') =
T (fun c' l' x' k' ->
match Constant.to_concrete_opt x' with
| Some (Pconst_string (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pconst_string"
)
let pconst_float (T f0') (T f1') =
T (fun c' l' x' k' ->
match Constant.to_concrete_opt x' with
| Some (Pconst_float (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pconst_float"
)
let pstr (T f0') =
T (fun c' l' x' k' ->
match Payload.to_concrete_opt x' with
| Some (PStr (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Structure.to_concrete x0') (k')
end
| _ -> fail l' "PStr"
)
let psig (T f0') =
T (fun c' l' x' k' ->
match Payload.to_concrete_opt x' with
| Some (PSig (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Signature.to_concrete x0') (k')
end
| _ -> fail l' "PSig"
)
let ptyp (T f0') =
T (fun c' l' x' k' ->
match Payload.to_concrete_opt x' with
| Some (PTyp (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "PTyp"
)
let ppat (T f0') (T f1') =
T (fun c' l' x' k' ->
match Payload.to_concrete_opt x' with
| Some (PPat (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "PPat"
)
let ptyp_var (T f0') =
T (fun c' l' x' k' ->
match Core_type.to_concrete_opt x' with
| Some { ptyp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Core_type_desc.to_concrete_opt x' with
| Some (Ptyp_var (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Ptyp_var"
end
| _ -> fail l' "Ptyp_var"
)
let ptyp_arrow (T f0') (T f1') (T f2') =
T (fun c' l' x' k' ->
match Core_type.to_concrete_opt x' with
| Some { ptyp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Core_type_desc.to_concrete_opt x' with
| Some (Ptyp_arrow (x0', x1', x2')) ->
begin
c'.matched <- c'.matched + 1;
f2' c' l' x2' (f1' c' l' x1' (f0' c' l' x0' (k')))
end
| _ -> fail l' "Ptyp_arrow"
end
| _ -> fail l' "Ptyp_arrow"
)
let ptyp_tuple (T f0') =
T (fun c' l' x' k' ->
match Core_type.to_concrete_opt x' with
| Some { ptyp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Core_type_desc.to_concrete_opt x' with
| Some (Ptyp_tuple (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Ptyp_tuple"
end
| _ -> fail l' "Ptyp_tuple"
)
let ptyp_constr (T f0') (T f1') =
T (fun c' l' x' k' ->
match Core_type.to_concrete_opt x' with
| Some { ptyp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Core_type_desc.to_concrete_opt x' with
| Some (Ptyp_constr (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' (Loc.txt (Longident_loc.to_concrete x0')) (k'))
end
| _ -> fail l' "Ptyp_constr"
end
| _ -> fail l' "Ptyp_constr"
)
let ptyp_object (T f0') (T f1') =
T (fun c' l' x' k' ->
match Core_type.to_concrete_opt x' with
| Some { ptyp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Core_type_desc.to_concrete_opt x' with
| Some (Ptyp_object (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Ptyp_object"
end
| _ -> fail l' "Ptyp_object"
)
let ptyp_class (T f0') (T f1') =
T (fun c' l' x' k' ->
match Core_type.to_concrete_opt x' with
| Some { ptyp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Core_type_desc.to_concrete_opt x' with
| Some (Ptyp_class (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' (Loc.txt (Longident_loc.to_concrete x0')) (k'))
end
| _ -> fail l' "Ptyp_class"
end
| _ -> fail l' "Ptyp_class"
)
let ptyp_alias (T f0') (T f1') =
T (fun c' l' x' k' ->
match Core_type.to_concrete_opt x' with
| Some { ptyp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Core_type_desc.to_concrete_opt x' with
| Some (Ptyp_alias (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Ptyp_alias"
end
| _ -> fail l' "Ptyp_alias"
)
let ptyp_variant (T f0') (T f1') (T f2') =
T (fun c' l' x' k' ->
match Core_type.to_concrete_opt x' with
| Some { ptyp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Core_type_desc.to_concrete_opt x' with
| Some (Ptyp_variant (x0', x1', x2')) ->
begin
c'.matched <- c'.matched + 1;
f2' c' l' x2' (f1' c' l' x1' (f0' c' l' x0' (k')))
end
| _ -> fail l' "Ptyp_variant"
end
| _ -> fail l' "Ptyp_variant"
)
let ptyp_poly (T f0') (T f1') =
T (fun c' l' x' k' ->
match Core_type.to_concrete_opt x' with
| Some { ptyp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Core_type_desc.to_concrete_opt x' with
| Some (Ptyp_poly (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Ptyp_poly"
end
| _ -> fail l' "Ptyp_poly"
)
let ptyp_package (T f0') =
T (fun c' l' x' k' ->
match Core_type.to_concrete_opt x' with
| Some { ptyp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Core_type_desc.to_concrete_opt x' with
| Some (Ptyp_package (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Package_type.to_concrete x0') (k')
end
| _ -> fail l' "Ptyp_package"
end
| _ -> fail l' "Ptyp_package"
)
let ptyp_extension (T f0') =
T (fun c' l' x' k' ->
match Core_type.to_concrete_opt x' with
| Some { ptyp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Core_type_desc.to_concrete_opt x' with
| Some (Ptyp_extension (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Extension.to_concrete x0') (k')
end
| _ -> fail l' "Ptyp_extension"
end
| _ -> fail l' "Ptyp_extension"
)
let ptyp_loc (T f') =
T (fun c' l' x' k' ->
match Core_type.to_concrete_opt x' with
| Some { ptyp_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "ptyp_loc"
)
let ptyp_attributes (T f') =
T (fun c' l' x' k' ->
match Core_type.to_concrete_opt x' with
| Some { ptyp_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "ptyp_attributes"
)
let rtag (T f0') (T f1') (T f2') (T f3') =
T (fun c' l' x' k' ->
match Row_field.to_concrete_opt x' with
| Some (Rtag (x0', x1', x2', x3')) ->
begin
c'.matched <- c'.matched + 1;
f3' c' l' x3' (f2' c' l' x2' (f1' c' l' (Attributes.to_concrete x1') (f0' c' l' (Loc.txt x0') (k'))))
end
| _ -> fail l' "Rtag"
)
let rinherit (T f0') =
T (fun c' l' x' k' ->
match Row_field.to_concrete_opt x' with
| Some (Rinherit (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Rinherit"
)
let otag (T f0') (T f1') (T f2') =
T (fun c' l' x' k' ->
match Object_field.to_concrete_opt x' with
| Some (Otag (x0', x1', x2')) ->
begin
c'.matched <- c'.matched + 1;
f2' c' l' x2' (f1' c' l' (Attributes.to_concrete x1') (f0' c' l' (Loc.txt x0') (k')))
end
| _ -> fail l' "Otag"
)
let oinherit (T f0') =
T (fun c' l' x' k' ->
match Object_field.to_concrete_opt x' with
| Some (Oinherit (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Oinherit"
)
let ppat_var (T f0') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Pattern_desc.to_concrete_opt x' with
| Some (Ppat_var (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Loc.txt x0') (k')
end
| _ -> fail l' "Ppat_var"
end
| _ -> fail l' "Ppat_var"
)
let ppat_alias (T f0') (T f1') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Pattern_desc.to_concrete_opt x' with
| Some (Ppat_alias (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' (Loc.txt x1') (f0' c' l' x0' (k'))
end
| _ -> fail l' "Ppat_alias"
end
| _ -> fail l' "Ppat_alias"
)
let ppat_constant (T f0') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Pattern_desc.to_concrete_opt x' with
| Some (Ppat_constant (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Ppat_constant"
end
| _ -> fail l' "Ppat_constant"
)
let ppat_interval (T f0') (T f1') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Pattern_desc.to_concrete_opt x' with
| Some (Ppat_interval (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Ppat_interval"
end
| _ -> fail l' "Ppat_interval"
)
let ppat_tuple (T f0') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Pattern_desc.to_concrete_opt x' with
| Some (Ppat_tuple (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Ppat_tuple"
end
| _ -> fail l' "Ppat_tuple"
)
let ppat_construct (T f0') (T f1') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Pattern_desc.to_concrete_opt x' with
| Some (Ppat_construct (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' (Loc.txt (Longident_loc.to_concrete x0')) (k'))
end
| _ -> fail l' "Ppat_construct"
end
| _ -> fail l' "Ppat_construct"
)
let ppat_variant (T f0') (T f1') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Pattern_desc.to_concrete_opt x' with
| Some (Ppat_variant (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Ppat_variant"
end
| _ -> fail l' "Ppat_variant"
)
let ppat_record (T f0') (T f1') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Pattern_desc.to_concrete_opt x' with
| Some (Ppat_record (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Ppat_record"
end
| _ -> fail l' "Ppat_record"
)
let ppat_array (T f0') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Pattern_desc.to_concrete_opt x' with
| Some (Ppat_array (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Ppat_array"
end
| _ -> fail l' "Ppat_array"
)
let ppat_or (T f0') (T f1') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Pattern_desc.to_concrete_opt x' with
| Some (Ppat_or (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Ppat_or"
end
| _ -> fail l' "Ppat_or"
)
let ppat_constraint (T f0') (T f1') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Pattern_desc.to_concrete_opt x' with
| Some (Ppat_constraint (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Ppat_constraint"
end
| _ -> fail l' "Ppat_constraint"
)
let ppat_type (T f0') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Pattern_desc.to_concrete_opt x' with
| Some (Ppat_type (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Loc.txt (Longident_loc.to_concrete x0')) (k')
end
| _ -> fail l' "Ppat_type"
end
| _ -> fail l' "Ppat_type"
)
let ppat_lazy (T f0') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Pattern_desc.to_concrete_opt x' with
| Some (Ppat_lazy (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Ppat_lazy"
end
| _ -> fail l' "Ppat_lazy"
)
let ppat_unpack (T f0') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Pattern_desc.to_concrete_opt x' with
| Some (Ppat_unpack (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Loc.txt x0') (k')
end
| _ -> fail l' "Ppat_unpack"
end
| _ -> fail l' "Ppat_unpack"
)
let ppat_exception (T f0') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Pattern_desc.to_concrete_opt x' with
| Some (Ppat_exception (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Ppat_exception"
end
| _ -> fail l' "Ppat_exception"
)
let ppat_extension (T f0') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Pattern_desc.to_concrete_opt x' with
| Some (Ppat_extension (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Extension.to_concrete x0') (k')
end
| _ -> fail l' "Ppat_extension"
end
| _ -> fail l' "Ppat_extension"
)
let ppat_open (T f0') (T f1') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Pattern_desc.to_concrete_opt x' with
| Some (Ppat_open (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' (Loc.txt (Longident_loc.to_concrete x0')) (k'))
end
| _ -> fail l' "Ppat_open"
end
| _ -> fail l' "Ppat_open"
)
let ppat_loc (T f') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "ppat_loc"
)
let ppat_attributes (T f') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "ppat_attributes"
)
let pexp_ident (T f0') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_ident (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Loc.txt (Longident_loc.to_concrete x0')) (k')
end
| _ -> fail l' "Pexp_ident"
end
| _ -> fail l' "Pexp_ident"
)
let pexp_constant (T f0') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_constant (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pexp_constant"
end
| _ -> fail l' "Pexp_constant"
)
let pexp_let (T f0') (T f1') (T f2') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_let (x0', x1', x2')) ->
begin
c'.matched <- c'.matched + 1;
f2' c' l' x2' (f1' c' l' x1' (f0' c' l' x0' (k')))
end
| _ -> fail l' "Pexp_let"
end
| _ -> fail l' "Pexp_let"
)
let pexp_function (T f0') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_function (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pexp_function"
end
| _ -> fail l' "Pexp_function"
)
let pexp_fun (T f0') (T f1') (T f2') (T f3') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_fun (x0', x1', x2', x3')) ->
begin
c'.matched <- c'.matched + 1;
f3' c' l' x3' (f2' c' l' x2' (f1' c' l' x1' (f0' c' l' x0' (k'))))
end
| _ -> fail l' "Pexp_fun"
end
| _ -> fail l' "Pexp_fun"
)
let pexp_apply (T f0') (T f1') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_apply (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pexp_apply"
end
| _ -> fail l' "Pexp_apply"
)
let pexp_match (T f0') (T f1') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_match (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pexp_match"
end
| _ -> fail l' "Pexp_match"
)
let pexp_try (T f0') (T f1') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_try (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pexp_try"
end
| _ -> fail l' "Pexp_try"
)
let pexp_tuple (T f0') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_tuple (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pexp_tuple"
end
| _ -> fail l' "Pexp_tuple"
)
let pexp_construct (T f0') (T f1') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_construct (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' (Loc.txt (Longident_loc.to_concrete x0')) (k'))
end
| _ -> fail l' "Pexp_construct"
end
| _ -> fail l' "Pexp_construct"
)
let pexp_variant (T f0') (T f1') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_variant (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pexp_variant"
end
| _ -> fail l' "Pexp_variant"
)
let pexp_record (T f0') (T f1') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_record (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pexp_record"
end
| _ -> fail l' "Pexp_record"
)
let pexp_field (T f0') (T f1') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_field (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' (Loc.txt (Longident_loc.to_concrete x1')) (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pexp_field"
end
| _ -> fail l' "Pexp_field"
)
let pexp_setfield (T f0') (T f1') (T f2') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_setfield (x0', x1', x2')) ->
begin
c'.matched <- c'.matched + 1;
f2' c' l' x2' (f1' c' l' (Loc.txt (Longident_loc.to_concrete x1')) (f0' c' l' x0' (k')))
end
| _ -> fail l' "Pexp_setfield"
end
| _ -> fail l' "Pexp_setfield"
)
let pexp_array (T f0') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_array (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pexp_array"
end
| _ -> fail l' "Pexp_array"
)
let pexp_ifthenelse (T f0') (T f1') (T f2') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_ifthenelse (x0', x1', x2')) ->
begin
c'.matched <- c'.matched + 1;
f2' c' l' x2' (f1' c' l' x1' (f0' c' l' x0' (k')))
end
| _ -> fail l' "Pexp_ifthenelse"
end
| _ -> fail l' "Pexp_ifthenelse"
)
let pexp_sequence (T f0') (T f1') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_sequence (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pexp_sequence"
end
| _ -> fail l' "Pexp_sequence"
)
let pexp_while (T f0') (T f1') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_while (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pexp_while"
end
| _ -> fail l' "Pexp_while"
)
let pexp_for (T f0') (T f1') (T f2') (T f3') (T f4') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_for (x0', x1', x2', x3', x4')) ->
begin
c'.matched <- c'.matched + 1;
f4' c' l' x4' (f3' c' l' x3' (f2' c' l' x2' (f1' c' l' x1' (f0' c' l' x0' (k')))))
end
| _ -> fail l' "Pexp_for"
end
| _ -> fail l' "Pexp_for"
)
let pexp_constraint (T f0') (T f1') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_constraint (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pexp_constraint"
end
| _ -> fail l' "Pexp_constraint"
)
let pexp_coerce (T f0') (T f1') (T f2') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_coerce (x0', x1', x2')) ->
begin
c'.matched <- c'.matched + 1;
f2' c' l' x2' (f1' c' l' x1' (f0' c' l' x0' (k')))
end
| _ -> fail l' "Pexp_coerce"
end
| _ -> fail l' "Pexp_coerce"
)
let pexp_send (T f0') (T f1') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_send (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' (Loc.txt x1') (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pexp_send"
end
| _ -> fail l' "Pexp_send"
)
let pexp_new (T f0') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_new (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Loc.txt (Longident_loc.to_concrete x0')) (k')
end
| _ -> fail l' "Pexp_new"
end
| _ -> fail l' "Pexp_new"
)
let pexp_setinstvar (T f0') (T f1') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_setinstvar (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' (Loc.txt x0') (k'))
end
| _ -> fail l' "Pexp_setinstvar"
end
| _ -> fail l' "Pexp_setinstvar"
)
let pexp_override (T f0') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_override (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pexp_override"
end
| _ -> fail l' "Pexp_override"
)
let pexp_letmodule (T f0') (T f1') (T f2') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_letmodule (x0', x1', x2')) ->
begin
c'.matched <- c'.matched + 1;
f2' c' l' x2' (f1' c' l' x1' (f0' c' l' (Loc.txt x0') (k')))
end
| _ -> fail l' "Pexp_letmodule"
end
| _ -> fail l' "Pexp_letmodule"
)
let pexp_letexception (T f0') (T f1') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_letexception (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pexp_letexception"
end
| _ -> fail l' "Pexp_letexception"
)
let pexp_assert (T f0') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_assert (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pexp_assert"
end
| _ -> fail l' "Pexp_assert"
)
let pexp_lazy (T f0') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_lazy (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pexp_lazy"
end
| _ -> fail l' "Pexp_lazy"
)
let pexp_poly (T f0') (T f1') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_poly (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pexp_poly"
end
| _ -> fail l' "Pexp_poly"
)
let pexp_object (T f0') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_object (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pexp_object"
end
| _ -> fail l' "Pexp_object"
)
let pexp_newtype (T f0') (T f1') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_newtype (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' (Loc.txt x0') (k'))
end
| _ -> fail l' "Pexp_newtype"
end
| _ -> fail l' "Pexp_newtype"
)
let pexp_pack (T f0') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_pack (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pexp_pack"
end
| _ -> fail l' "Pexp_pack"
)
let pexp_open (T f0') (T f1') (T f2') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_open (x0', x1', x2')) ->
begin
c'.matched <- c'.matched + 1;
f2' c' l' x2' (f1' c' l' (Loc.txt (Longident_loc.to_concrete x1')) (f0' c' l' x0' (k')))
end
| _ -> fail l' "Pexp_open"
end
| _ -> fail l' "Pexp_open"
)
let pexp_extension (T f0') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_extension (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Extension.to_concrete x0') (k')
end
| _ -> fail l' "Pexp_extension"
end
| _ -> fail l' "Pexp_extension"
)
let pexp_loc (T f') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "pexp_loc"
)
let pexp_attributes (T f') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "pexp_attributes"
)
let pval_attributes (T f') =
T (fun c' l' x' k' ->
match Value_description.to_concrete_opt x' with
| Some { pval_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "pval_attributes"
)
let pval_loc (T f') =
T (fun c' l' x' k' ->
match Value_description.to_concrete_opt x' with
| Some { pval_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "pval_loc"
)
let ptype_attributes (T f') =
T (fun c' l' x' k' ->
match Type_declaration.to_concrete_opt x' with
| Some { ptype_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "ptype_attributes"
)
let ptype_loc (T f') =
T (fun c' l' x' k' ->
match Type_declaration.to_concrete_opt x' with
| Some { ptype_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "ptype_loc"
)
let ptype_variant (T f0') =
T (fun c' l' x' k' ->
match Type_kind.to_concrete_opt x' with
| Some (Ptype_variant (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Ptype_variant"
)
let ptype_record (T f0') =
T (fun c' l' x' k' ->
match Type_kind.to_concrete_opt x' with
| Some (Ptype_record (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Ptype_record"
)
let pld_loc (T f') =
T (fun c' l' x' k' ->
match Label_declaration.to_concrete_opt x' with
| Some { pld_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "pld_loc"
)
let pld_attributes (T f') =
T (fun c' l' x' k' ->
match Label_declaration.to_concrete_opt x' with
| Some { pld_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "pld_attributes"
)
let pcd_loc (T f') =
T (fun c' l' x' k' ->
match Constructor_declaration.to_concrete_opt x' with
| Some { pcd_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "pcd_loc"
)
let pcd_attributes (T f') =
T (fun c' l' x' k' ->
match Constructor_declaration.to_concrete_opt x' with
| Some { pcd_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "pcd_attributes"
)
let pcstr_tuple (T f0') =
T (fun c' l' x' k' ->
match Constructor_arguments.to_concrete_opt x' with
| Some (Pcstr_tuple (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pcstr_tuple"
)
let pcstr_record (T f0') =
T (fun c' l' x' k' ->
match Constructor_arguments.to_concrete_opt x' with
| Some (Pcstr_record (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pcstr_record"
)
let ptyext_attributes (T f') =
T (fun c' l' x' k' ->
match Type_extension.to_concrete_opt x' with
| Some { ptyext_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "ptyext_attributes"
)
let pext_loc (T f') =
T (fun c' l' x' k' ->
match Extension_constructor.to_concrete_opt x' with
| Some { pext_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "pext_loc"
)
let pext_attributes (T f') =
T (fun c' l' x' k' ->
match Extension_constructor.to_concrete_opt x' with
| Some { pext_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "pext_attributes"
)
let pext_decl (T f0') (T f1') =
T (fun c' l' x' k' ->
match Extension_constructor_kind.to_concrete_opt x' with
| Some (Pext_decl (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pext_decl"
)
let pext_rebind (T f0') =
T (fun c' l' x' k' ->
match Extension_constructor_kind.to_concrete_opt x' with
| Some (Pext_rebind (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Loc.txt (Longident_loc.to_concrete x0')) (k')
end
| _ -> fail l' "Pext_rebind"
)
let pcty_constr (T f0') (T f1') =
T (fun c' l' x' k' ->
match Class_type.to_concrete_opt x' with
| Some { pcty_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_type_desc.to_concrete_opt x' with
| Some (Pcty_constr (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' (Loc.txt (Longident_loc.to_concrete x0')) (k'))
end
| _ -> fail l' "Pcty_constr"
end
| _ -> fail l' "Pcty_constr"
)
let pcty_signature (T f0') =
T (fun c' l' x' k' ->
match Class_type.to_concrete_opt x' with
| Some { pcty_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_type_desc.to_concrete_opt x' with
| Some (Pcty_signature (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pcty_signature"
end
| _ -> fail l' "Pcty_signature"
)
let pcty_arrow (T f0') (T f1') (T f2') =
T (fun c' l' x' k' ->
match Class_type.to_concrete_opt x' with
| Some { pcty_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_type_desc.to_concrete_opt x' with
| Some (Pcty_arrow (x0', x1', x2')) ->
begin
c'.matched <- c'.matched + 1;
f2' c' l' x2' (f1' c' l' x1' (f0' c' l' x0' (k')))
end
| _ -> fail l' "Pcty_arrow"
end
| _ -> fail l' "Pcty_arrow"
)
let pcty_extension (T f0') =
T (fun c' l' x' k' ->
match Class_type.to_concrete_opt x' with
| Some { pcty_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_type_desc.to_concrete_opt x' with
| Some (Pcty_extension (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Extension.to_concrete x0') (k')
end
| _ -> fail l' "Pcty_extension"
end
| _ -> fail l' "Pcty_extension"
)
let pcty_open (T f0') (T f1') (T f2') =
T (fun c' l' x' k' ->
match Class_type.to_concrete_opt x' with
| Some { pcty_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_type_desc.to_concrete_opt x' with
| Some (Pcty_open (x0', x1', x2')) ->
begin
c'.matched <- c'.matched + 1;
f2' c' l' x2' (f1' c' l' (Loc.txt (Longident_loc.to_concrete x1')) (f0' c' l' x0' (k')))
end
| _ -> fail l' "Pcty_open"
end
| _ -> fail l' "Pcty_open"
)
let pcty_loc (T f') =
T (fun c' l' x' k' ->
match Class_type.to_concrete_opt x' with
| Some { pcty_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "pcty_loc"
)
let pcty_attributes (T f') =
T (fun c' l' x' k' ->
match Class_type.to_concrete_opt x' with
| Some { pcty_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "pcty_attributes"
)
let pctf_inherit (T f0') =
T (fun c' l' x' k' ->
match Class_type_field.to_concrete_opt x' with
| Some { pctf_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_type_field_desc.to_concrete_opt x' with
| Some (Pctf_inherit (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pctf_inherit"
end
| _ -> fail l' "Pctf_inherit"
)
let pctf_val (T f0') =
T (fun c' l' x' k' ->
match Class_type_field.to_concrete_opt x' with
| Some { pctf_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_type_field_desc.to_concrete_opt x' with
| Some (Pctf_val (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pctf_val"
end
| _ -> fail l' "Pctf_val"
)
let pctf_method (T f0') =
T (fun c' l' x' k' ->
match Class_type_field.to_concrete_opt x' with
| Some { pctf_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_type_field_desc.to_concrete_opt x' with
| Some (Pctf_method (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pctf_method"
end
| _ -> fail l' "Pctf_method"
)
let pctf_constraint (T f0') =
T (fun c' l' x' k' ->
match Class_type_field.to_concrete_opt x' with
| Some { pctf_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_type_field_desc.to_concrete_opt x' with
| Some (Pctf_constraint (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pctf_constraint"
end
| _ -> fail l' "Pctf_constraint"
)
let pctf_attribute (T f0') =
T (fun c' l' x' k' ->
match Class_type_field.to_concrete_opt x' with
| Some { pctf_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_type_field_desc.to_concrete_opt x' with
| Some (Pctf_attribute (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Attribute.to_concrete x0') (k')
end
| _ -> fail l' "Pctf_attribute"
end
| _ -> fail l' "Pctf_attribute"
)
let pctf_extension (T f0') =
T (fun c' l' x' k' ->
match Class_type_field.to_concrete_opt x' with
| Some { pctf_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_type_field_desc.to_concrete_opt x' with
| Some (Pctf_extension (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Extension.to_concrete x0') (k')
end
| _ -> fail l' "Pctf_extension"
end
| _ -> fail l' "Pctf_extension"
)
let pctf_loc (T f') =
T (fun c' l' x' k' ->
match Class_type_field.to_concrete_opt x' with
| Some { pctf_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "pctf_loc"
)
let pctf_attributes (T f') =
T (fun c' l' x' k' ->
match Class_type_field.to_concrete_opt x' with
| Some { pctf_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "pctf_attributes"
)
let pci_loc (T f') =
T (fun c' l' x' k' ->
match Class_infos.to_concrete_opt x' with
| Some { pci_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "pci_loc"
)
let pci_attributes (T f') =
T (fun c' l' x' k' ->
match Class_infos.to_concrete_opt x' with
| Some { pci_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "pci_attributes"
)
let pcl_constr (T f0') (T f1') =
T (fun c' l' x' k' ->
match Class_expr.to_concrete_opt x' with
| Some { pcl_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_expr_desc.to_concrete_opt x' with
| Some (Pcl_constr (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' (Loc.txt (Longident_loc.to_concrete x0')) (k'))
end
| _ -> fail l' "Pcl_constr"
end
| _ -> fail l' "Pcl_constr"
)
let pcl_structure (T f0') =
T (fun c' l' x' k' ->
match Class_expr.to_concrete_opt x' with
| Some { pcl_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_expr_desc.to_concrete_opt x' with
| Some (Pcl_structure (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pcl_structure"
end
| _ -> fail l' "Pcl_structure"
)
let pcl_fun (T f0') (T f1') (T f2') (T f3') =
T (fun c' l' x' k' ->
match Class_expr.to_concrete_opt x' with
| Some { pcl_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_expr_desc.to_concrete_opt x' with
| Some (Pcl_fun (x0', x1', x2', x3')) ->
begin
c'.matched <- c'.matched + 1;
f3' c' l' x3' (f2' c' l' x2' (f1' c' l' x1' (f0' c' l' x0' (k'))))
end
| _ -> fail l' "Pcl_fun"
end
| _ -> fail l' "Pcl_fun"
)
let pcl_apply (T f0') (T f1') =
T (fun c' l' x' k' ->
match Class_expr.to_concrete_opt x' with
| Some { pcl_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_expr_desc.to_concrete_opt x' with
| Some (Pcl_apply (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pcl_apply"
end
| _ -> fail l' "Pcl_apply"
)
let pcl_let (T f0') (T f1') (T f2') =
T (fun c' l' x' k' ->
match Class_expr.to_concrete_opt x' with
| Some { pcl_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_expr_desc.to_concrete_opt x' with
| Some (Pcl_let (x0', x1', x2')) ->
begin
c'.matched <- c'.matched + 1;
f2' c' l' x2' (f1' c' l' x1' (f0' c' l' x0' (k')))
end
| _ -> fail l' "Pcl_let"
end
| _ -> fail l' "Pcl_let"
)
let pcl_constraint (T f0') (T f1') =
T (fun c' l' x' k' ->
match Class_expr.to_concrete_opt x' with
| Some { pcl_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_expr_desc.to_concrete_opt x' with
| Some (Pcl_constraint (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pcl_constraint"
end
| _ -> fail l' "Pcl_constraint"
)
let pcl_extension (T f0') =
T (fun c' l' x' k' ->
match Class_expr.to_concrete_opt x' with
| Some { pcl_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_expr_desc.to_concrete_opt x' with
| Some (Pcl_extension (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Extension.to_concrete x0') (k')
end
| _ -> fail l' "Pcl_extension"
end
| _ -> fail l' "Pcl_extension"
)
let pcl_open (T f0') (T f1') (T f2') =
T (fun c' l' x' k' ->
match Class_expr.to_concrete_opt x' with
| Some { pcl_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_expr_desc.to_concrete_opt x' with
| Some (Pcl_open (x0', x1', x2')) ->
begin
c'.matched <- c'.matched + 1;
f2' c' l' x2' (f1' c' l' (Loc.txt (Longident_loc.to_concrete x1')) (f0' c' l' x0' (k')))
end
| _ -> fail l' "Pcl_open"
end
| _ -> fail l' "Pcl_open"
)
let pcl_loc (T f') =
T (fun c' l' x' k' ->
match Class_expr.to_concrete_opt x' with
| Some { pcl_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "pcl_loc"
)
let pcl_attributes (T f') =
T (fun c' l' x' k' ->
match Class_expr.to_concrete_opt x' with
| Some { pcl_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "pcl_attributes"
)
let pcf_inherit (T f0') (T f1') (T f2') =
T (fun c' l' x' k' ->
match Class_field.to_concrete_opt x' with
| Some { pcf_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_field_desc.to_concrete_opt x' with
| Some (Pcf_inherit (x0', x1', x2')) ->
begin
c'.matched <- c'.matched + 1;
f2' c' l' x2' (f1' c' l' x1' (f0' c' l' x0' (k')))
end
| _ -> fail l' "Pcf_inherit"
end
| _ -> fail l' "Pcf_inherit"
)
let pcf_val (T f0') =
T (fun c' l' x' k' ->
match Class_field.to_concrete_opt x' with
| Some { pcf_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_field_desc.to_concrete_opt x' with
| Some (Pcf_val (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pcf_val"
end
| _ -> fail l' "Pcf_val"
)
let pcf_method (T f0') =
T (fun c' l' x' k' ->
match Class_field.to_concrete_opt x' with
| Some { pcf_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_field_desc.to_concrete_opt x' with
| Some (Pcf_method (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pcf_method"
end
| _ -> fail l' "Pcf_method"
)
let pcf_constraint (T f0') =
T (fun c' l' x' k' ->
match Class_field.to_concrete_opt x' with
| Some { pcf_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_field_desc.to_concrete_opt x' with
| Some (Pcf_constraint (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pcf_constraint"
end
| _ -> fail l' "Pcf_constraint"
)
let pcf_initializer (T f0') =
T (fun c' l' x' k' ->
match Class_field.to_concrete_opt x' with
| Some { pcf_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_field_desc.to_concrete_opt x' with
| Some (Pcf_initializer (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pcf_initializer"
end
| _ -> fail l' "Pcf_initializer"
)
let pcf_attribute (T f0') =
T (fun c' l' x' k' ->
match Class_field.to_concrete_opt x' with
| Some { pcf_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_field_desc.to_concrete_opt x' with
| Some (Pcf_attribute (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Attribute.to_concrete x0') (k')
end
| _ -> fail l' "Pcf_attribute"
end
| _ -> fail l' "Pcf_attribute"
)
let pcf_extension (T f0') =
T (fun c' l' x' k' ->
match Class_field.to_concrete_opt x' with
| Some { pcf_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_field_desc.to_concrete_opt x' with
| Some (Pcf_extension (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Extension.to_concrete x0') (k')
end
| _ -> fail l' "Pcf_extension"
end
| _ -> fail l' "Pcf_extension"
)
let pcf_loc (T f') =
T (fun c' l' x' k' ->
match Class_field.to_concrete_opt x' with
| Some { pcf_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "pcf_loc"
)
let pcf_attributes (T f') =
T (fun c' l' x' k' ->
match Class_field.to_concrete_opt x' with
| Some { pcf_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "pcf_attributes"
)
let cfk_virtual (T f0') =
T (fun c' l' x' k' ->
match Class_field_kind.to_concrete_opt x' with
| Some (Cfk_virtual (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Cfk_virtual"
)
let cfk_concrete (T f0') (T f1') =
T (fun c' l' x' k' ->
match Class_field_kind.to_concrete_opt x' with
| Some (Cfk_concrete (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Cfk_concrete"
)
let pmty_ident (T f0') =
T (fun c' l' x' k' ->
match Module_type.to_concrete_opt x' with
| Some { pmty_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Module_type_desc.to_concrete_opt x' with
| Some (Pmty_ident (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Loc.txt (Longident_loc.to_concrete x0')) (k')
end
| _ -> fail l' "Pmty_ident"
end
| _ -> fail l' "Pmty_ident"
)
let pmty_signature (T f0') =
T (fun c' l' x' k' ->
match Module_type.to_concrete_opt x' with
| Some { pmty_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Module_type_desc.to_concrete_opt x' with
| Some (Pmty_signature (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Signature.to_concrete x0') (k')
end
| _ -> fail l' "Pmty_signature"
end
| _ -> fail l' "Pmty_signature"
)
let pmty_functor (T f0') (T f1') (T f2') =
T (fun c' l' x' k' ->
match Module_type.to_concrete_opt x' with
| Some { pmty_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Module_type_desc.to_concrete_opt x' with
| Some (Pmty_functor (x0', x1', x2')) ->
begin
c'.matched <- c'.matched + 1;
f2' c' l' x2' (f1' c' l' x1' (f0' c' l' (Loc.txt x0') (k')))
end
| _ -> fail l' "Pmty_functor"
end
| _ -> fail l' "Pmty_functor"
)
let pmty_with (T f0') (T f1') =
T (fun c' l' x' k' ->
match Module_type.to_concrete_opt x' with
| Some { pmty_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Module_type_desc.to_concrete_opt x' with
| Some (Pmty_with (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pmty_with"
end
| _ -> fail l' "Pmty_with"
)
let pmty_typeof (T f0') =
T (fun c' l' x' k' ->
match Module_type.to_concrete_opt x' with
| Some { pmty_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Module_type_desc.to_concrete_opt x' with
| Some (Pmty_typeof (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pmty_typeof"
end
| _ -> fail l' "Pmty_typeof"
)
let pmty_extension (T f0') =
T (fun c' l' x' k' ->
match Module_type.to_concrete_opt x' with
| Some { pmty_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Module_type_desc.to_concrete_opt x' with
| Some (Pmty_extension (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Extension.to_concrete x0') (k')
end
| _ -> fail l' "Pmty_extension"
end
| _ -> fail l' "Pmty_extension"
)
let pmty_alias (T f0') =
T (fun c' l' x' k' ->
match Module_type.to_concrete_opt x' with
| Some { pmty_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Module_type_desc.to_concrete_opt x' with
| Some (Pmty_alias (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Loc.txt (Longident_loc.to_concrete x0')) (k')
end
| _ -> fail l' "Pmty_alias"
end
| _ -> fail l' "Pmty_alias"
)
let pmty_loc (T f') =
T (fun c' l' x' k' ->
match Module_type.to_concrete_opt x' with
| Some { pmty_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "pmty_loc"
)
let pmty_attributes (T f') =
T (fun c' l' x' k' ->
match Module_type.to_concrete_opt x' with
| Some { pmty_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "pmty_attributes"
)
let psig_value (T f0') =
T (fun c' l' x' k' ->
match Signature_item.to_concrete_opt x' with
| Some { psig_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Signature_item_desc.to_concrete_opt x' with
| Some (Psig_value (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Psig_value"
end
| _ -> fail l' "Psig_value"
)
let psig_type (T f0') (T f1') =
T (fun c' l' x' k' ->
match Signature_item.to_concrete_opt x' with
| Some { psig_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Signature_item_desc.to_concrete_opt x' with
| Some (Psig_type (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Psig_type"
end
| _ -> fail l' "Psig_type"
)
let psig_typext (T f0') =
T (fun c' l' x' k' ->
match Signature_item.to_concrete_opt x' with
| Some { psig_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Signature_item_desc.to_concrete_opt x' with
| Some (Psig_typext (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Psig_typext"
end
| _ -> fail l' "Psig_typext"
)
let psig_exception (T f0') =
T (fun c' l' x' k' ->
match Signature_item.to_concrete_opt x' with
| Some { psig_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Signature_item_desc.to_concrete_opt x' with
| Some (Psig_exception (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Psig_exception"
end
| _ -> fail l' "Psig_exception"
)
let psig_module (T f0') =
T (fun c' l' x' k' ->
match Signature_item.to_concrete_opt x' with
| Some { psig_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Signature_item_desc.to_concrete_opt x' with
| Some (Psig_module (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Psig_module"
end
| _ -> fail l' "Psig_module"
)
let psig_recmodule (T f0') =
T (fun c' l' x' k' ->
match Signature_item.to_concrete_opt x' with
| Some { psig_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Signature_item_desc.to_concrete_opt x' with
| Some (Psig_recmodule (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Psig_recmodule"
end
| _ -> fail l' "Psig_recmodule"
)
let psig_modtype (T f0') =
T (fun c' l' x' k' ->
match Signature_item.to_concrete_opt x' with
| Some { psig_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Signature_item_desc.to_concrete_opt x' with
| Some (Psig_modtype (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Psig_modtype"
end
| _ -> fail l' "Psig_modtype"
)
let psig_open (T f0') =
T (fun c' l' x' k' ->
match Signature_item.to_concrete_opt x' with
| Some { psig_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Signature_item_desc.to_concrete_opt x' with
| Some (Psig_open (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Psig_open"
end
| _ -> fail l' "Psig_open"
)
let psig_include (T f0') =
T (fun c' l' x' k' ->
match Signature_item.to_concrete_opt x' with
| Some { psig_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Signature_item_desc.to_concrete_opt x' with
| Some (Psig_include (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Include_description.to_concrete x0') (k')
end
| _ -> fail l' "Psig_include"
end
| _ -> fail l' "Psig_include"
)
let psig_class (T f0') =
T (fun c' l' x' k' ->
match Signature_item.to_concrete_opt x' with
| Some { psig_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Signature_item_desc.to_concrete_opt x' with
| Some (Psig_class (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Psig_class"
end
| _ -> fail l' "Psig_class"
)
let psig_class_type (T f0') =
T (fun c' l' x' k' ->
match Signature_item.to_concrete_opt x' with
| Some { psig_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Signature_item_desc.to_concrete_opt x' with
| Some (Psig_class_type (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Psig_class_type"
end
| _ -> fail l' "Psig_class_type"
)
let psig_attribute (T f0') =
T (fun c' l' x' k' ->
match Signature_item.to_concrete_opt x' with
| Some { psig_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Signature_item_desc.to_concrete_opt x' with
| Some (Psig_attribute (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Attribute.to_concrete x0') (k')
end
| _ -> fail l' "Psig_attribute"
end
| _ -> fail l' "Psig_attribute"
)
let psig_extension (T f0') (T f1') =
T (fun c' l' x' k' ->
match Signature_item.to_concrete_opt x' with
| Some { psig_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Signature_item_desc.to_concrete_opt x' with
| Some (Psig_extension (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' (Attributes.to_concrete x1') (f0' c' l' (Extension.to_concrete x0') (k'))
end
| _ -> fail l' "Psig_extension"
end
| _ -> fail l' "Psig_extension"
)
let psig_loc (T f') =
T (fun c' l' x' k' ->
match Signature_item.to_concrete_opt x' with
| Some { psig_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "psig_loc"
)
let pmd_attributes (T f') =
T (fun c' l' x' k' ->
match Module_declaration.to_concrete_opt x' with
| Some { pmd_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "pmd_attributes"
)
let pmd_loc (T f') =
T (fun c' l' x' k' ->
match Module_declaration.to_concrete_opt x' with
| Some { pmd_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "pmd_loc"
)
let pmtd_attributes (T f') =
T (fun c' l' x' k' ->
match Module_type_declaration.to_concrete_opt x' with
| Some { pmtd_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "pmtd_attributes"
)
let pmtd_loc (T f') =
T (fun c' l' x' k' ->
match Module_type_declaration.to_concrete_opt x' with
| Some { pmtd_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "pmtd_loc"
)
let popen_loc (T f') =
T (fun c' l' x' k' ->
match Open_description.to_concrete_opt x' with
| Some { popen_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "popen_loc"
)
let popen_attributes (T f') =
T (fun c' l' x' k' ->
match Open_description.to_concrete_opt x' with
| Some { popen_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "popen_attributes"
)
let pincl_loc (T f') =
T (fun c' l' x' k' ->
match Include_infos.to_concrete_opt x' with
| Some { pincl_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "pincl_loc"
)
let pincl_attributes (T f') =
T (fun c' l' x' k' ->
match Include_infos.to_concrete_opt x' with
| Some { pincl_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "pincl_attributes"
)
let pwith_type (T f0') (T f1') =
T (fun c' l' x' k' ->
match With_constraint.to_concrete_opt x' with
| Some (Pwith_type (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' (Loc.txt (Longident_loc.to_concrete x0')) (k'))
end
| _ -> fail l' "Pwith_type"
)
let pwith_module (T f0') (T f1') =
T (fun c' l' x' k' ->
match With_constraint.to_concrete_opt x' with
| Some (Pwith_module (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' (Loc.txt (Longident_loc.to_concrete x1')) (f0' c' l' (Loc.txt (Longident_loc.to_concrete x0')) (k'))
end
| _ -> fail l' "Pwith_module"
)
let pwith_typesubst (T f0') (T f1') =
T (fun c' l' x' k' ->
match With_constraint.to_concrete_opt x' with
| Some (Pwith_typesubst (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' (Loc.txt (Longident_loc.to_concrete x0')) (k'))
end
| _ -> fail l' "Pwith_typesubst"
)
let pwith_modsubst (T f0') (T f1') =
T (fun c' l' x' k' ->
match With_constraint.to_concrete_opt x' with
| Some (Pwith_modsubst (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' (Loc.txt (Longident_loc.to_concrete x1')) (f0' c' l' (Loc.txt (Longident_loc.to_concrete x0')) (k'))
end
| _ -> fail l' "Pwith_modsubst"
)
let pmod_ident (T f0') =
T (fun c' l' x' k' ->
match Module_expr.to_concrete_opt x' with
| Some { pmod_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Module_expr_desc.to_concrete_opt x' with
| Some (Pmod_ident (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Loc.txt (Longident_loc.to_concrete x0')) (k')
end
| _ -> fail l' "Pmod_ident"
end
| _ -> fail l' "Pmod_ident"
)
let pmod_structure (T f0') =
T (fun c' l' x' k' ->
match Module_expr.to_concrete_opt x' with
| Some { pmod_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Module_expr_desc.to_concrete_opt x' with
| Some (Pmod_structure (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Structure.to_concrete x0') (k')
end
| _ -> fail l' "Pmod_structure"
end
| _ -> fail l' "Pmod_structure"
)
let pmod_functor (T f0') (T f1') (T f2') =
T (fun c' l' x' k' ->
match Module_expr.to_concrete_opt x' with
| Some { pmod_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Module_expr_desc.to_concrete_opt x' with
| Some (Pmod_functor (x0', x1', x2')) ->
begin
c'.matched <- c'.matched + 1;
f2' c' l' x2' (f1' c' l' x1' (f0' c' l' (Loc.txt x0') (k')))
end
| _ -> fail l' "Pmod_functor"
end
| _ -> fail l' "Pmod_functor"
)
let pmod_apply (T f0') (T f1') =
T (fun c' l' x' k' ->
match Module_expr.to_concrete_opt x' with
| Some { pmod_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Module_expr_desc.to_concrete_opt x' with
| Some (Pmod_apply (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pmod_apply"
end
| _ -> fail l' "Pmod_apply"
)
let pmod_constraint (T f0') (T f1') =
T (fun c' l' x' k' ->
match Module_expr.to_concrete_opt x' with
| Some { pmod_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Module_expr_desc.to_concrete_opt x' with
| Some (Pmod_constraint (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pmod_constraint"
end
| _ -> fail l' "Pmod_constraint"
)
let pmod_unpack (T f0') =
T (fun c' l' x' k' ->
match Module_expr.to_concrete_opt x' with
| Some { pmod_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Module_expr_desc.to_concrete_opt x' with
| Some (Pmod_unpack (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pmod_unpack"
end
| _ -> fail l' "Pmod_unpack"
)
let pmod_extension (T f0') =
T (fun c' l' x' k' ->
match Module_expr.to_concrete_opt x' with
| Some { pmod_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Module_expr_desc.to_concrete_opt x' with
| Some (Pmod_extension (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Extension.to_concrete x0') (k')
end
| _ -> fail l' "Pmod_extension"
end
| _ -> fail l' "Pmod_extension"
)
let pmod_loc (T f') =
T (fun c' l' x' k' ->
match Module_expr.to_concrete_opt x' with
| Some { pmod_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "pmod_loc"
)
let pmod_attributes (T f') =
T (fun c' l' x' k' ->
match Module_expr.to_concrete_opt x' with
| Some { pmod_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "pmod_attributes"
)
let pstr_eval (T f0') (T f1') =
T (fun c' l' x' k' ->
match Structure_item.to_concrete_opt x' with
| Some { pstr_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Structure_item_desc.to_concrete_opt x' with
| Some (Pstr_eval (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' (Attributes.to_concrete x1') (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pstr_eval"
end
| _ -> fail l' "Pstr_eval"
)
let pstr_value (T f0') (T f1') =
T (fun c' l' x' k' ->
match Structure_item.to_concrete_opt x' with
| Some { pstr_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Structure_item_desc.to_concrete_opt x' with
| Some (Pstr_value (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pstr_value"
end
| _ -> fail l' "Pstr_value"
)
let pstr_primitive (T f0') =
T (fun c' l' x' k' ->
match Structure_item.to_concrete_opt x' with
| Some { pstr_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Structure_item_desc.to_concrete_opt x' with
| Some (Pstr_primitive (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pstr_primitive"
end
| _ -> fail l' "Pstr_primitive"
)
let pstr_type (T f0') (T f1') =
T (fun c' l' x' k' ->
match Structure_item.to_concrete_opt x' with
| Some { pstr_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Structure_item_desc.to_concrete_opt x' with
| Some (Pstr_type (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pstr_type"
end
| _ -> fail l' "Pstr_type"
)
let pstr_typext (T f0') =
T (fun c' l' x' k' ->
match Structure_item.to_concrete_opt x' with
| Some { pstr_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Structure_item_desc.to_concrete_opt x' with
| Some (Pstr_typext (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pstr_typext"
end
| _ -> fail l' "Pstr_typext"
)
let pstr_exception (T f0') =
T (fun c' l' x' k' ->
match Structure_item.to_concrete_opt x' with
| Some { pstr_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Structure_item_desc.to_concrete_opt x' with
| Some (Pstr_exception (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pstr_exception"
end
| _ -> fail l' "Pstr_exception"
)
let pstr_module (T f0') =
T (fun c' l' x' k' ->
match Structure_item.to_concrete_opt x' with
| Some { pstr_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Structure_item_desc.to_concrete_opt x' with
| Some (Pstr_module (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pstr_module"
end
| _ -> fail l' "Pstr_module"
)
let pstr_recmodule (T f0') =
T (fun c' l' x' k' ->
match Structure_item.to_concrete_opt x' with
| Some { pstr_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Structure_item_desc.to_concrete_opt x' with
| Some (Pstr_recmodule (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pstr_recmodule"
end
| _ -> fail l' "Pstr_recmodule"
)
let pstr_modtype (T f0') =
T (fun c' l' x' k' ->
match Structure_item.to_concrete_opt x' with
| Some { pstr_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Structure_item_desc.to_concrete_opt x' with
| Some (Pstr_modtype (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pstr_modtype"
end
| _ -> fail l' "Pstr_modtype"
)
let pstr_open (T f0') =
T (fun c' l' x' k' ->
match Structure_item.to_concrete_opt x' with
| Some { pstr_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Structure_item_desc.to_concrete_opt x' with
| Some (Pstr_open (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pstr_open"
end
| _ -> fail l' "Pstr_open"
)
let pstr_class (T f0') =
T (fun c' l' x' k' ->
match Structure_item.to_concrete_opt x' with
| Some { pstr_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Structure_item_desc.to_concrete_opt x' with
| Some (Pstr_class (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pstr_class"
end
| _ -> fail l' "Pstr_class"
)
let pstr_class_type (T f0') =
T (fun c' l' x' k' ->
match Structure_item.to_concrete_opt x' with
| Some { pstr_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Structure_item_desc.to_concrete_opt x' with
| Some (Pstr_class_type (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pstr_class_type"
end
| _ -> fail l' "Pstr_class_type"
)
let pstr_include (T f0') =
T (fun c' l' x' k' ->
match Structure_item.to_concrete_opt x' with
| Some { pstr_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Structure_item_desc.to_concrete_opt x' with
| Some (Pstr_include (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Include_declaration.to_concrete x0') (k')
end
| _ -> fail l' "Pstr_include"
end
| _ -> fail l' "Pstr_include"
)
let pstr_attribute (T f0') =
T (fun c' l' x' k' ->
match Structure_item.to_concrete_opt x' with
| Some { pstr_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Structure_item_desc.to_concrete_opt x' with
| Some (Pstr_attribute (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Attribute.to_concrete x0') (k')
end
| _ -> fail l' "Pstr_attribute"
end
| _ -> fail l' "Pstr_attribute"
)
let pstr_extension (T f0') (T f1') =
T (fun c' l' x' k' ->
match Structure_item.to_concrete_opt x' with
| Some { pstr_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Structure_item_desc.to_concrete_opt x' with
| Some (Pstr_extension (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' (Attributes.to_concrete x1') (f0' c' l' (Extension.to_concrete x0') (k'))
end
| _ -> fail l' "Pstr_extension"
end
| _ -> fail l' "Pstr_extension"
)
let pstr_loc (T f') =
T (fun c' l' x' k' ->
match Structure_item.to_concrete_opt x' with
| Some { pstr_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "pstr_loc"
)
let pvb_attributes (T f') =
T (fun c' l' x' k' ->
match Value_binding.to_concrete_opt x' with
| Some { pvb_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "pvb_attributes"
)
let pvb_loc (T f') =
T (fun c' l' x' k' ->
match Value_binding.to_concrete_opt x' with
| Some { pvb_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "pvb_loc"
)
let pmb_attributes (T f') =
T (fun c' l' x' k' ->
match Module_binding.to_concrete_opt x' with
| Some { pmb_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "pmb_attributes"
)
let pmb_loc (T f') =
T (fun c' l' x' k' ->
match Module_binding.to_concrete_opt x' with
| Some { pmb_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "pmb_loc"
)
let ptop_def (T f0') =
T (fun c' l' x' k' ->
match Toplevel_phrase.to_concrete_opt x' with
| Some (Ptop_def (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Structure.to_concrete x0') (k')
end
| _ -> fail l' "Ptop_def"
)
let ptop_dir (T f0') (T f1') =
T (fun c' l' x' k' ->
match Toplevel_phrase.to_concrete_opt x' with
| Some (Ptop_dir (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Ptop_dir"
)
let pdir_string (T f0') =
T (fun c' l' x' k' ->
match Directive_argument.to_concrete_opt x' with
| Some (Pdir_string (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pdir_string"
)
let pdir_int (T f0') (T f1') =
T (fun c' l' x' k' ->
match Directive_argument.to_concrete_opt x' with
| Some (Pdir_int (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pdir_int"
)
let pdir_ident (T f0') =
T (fun c' l' x' k' ->
match Directive_argument.to_concrete_opt x' with
| Some (Pdir_ident (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pdir_ident"
)
let pdir_bool (T f0') =
T (fun c' l' x' k' ->
match Directive_argument.to_concrete_opt x' with
| Some (Pdir_bool (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pdir_bool"
)
(*$*)
| null | https://raw.githubusercontent.com/ocaml-ppx/ppx/40e5a35a4386d969effaf428078c900bd03b78ec/src/ast_pattern_generated.ml | ocaml | $ Ppxlib_cinaps_helpers.generate_ast_pattern_impl ()
$ | open! Import
open Current_ast
open Ast_pattern0
let lident (T f0') =
T (fun c' l' x' k' ->
match Longident.to_concrete_opt x' with
| Some (Lident (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Lident"
)
let ldot (T f0') (T f1') =
T (fun c' l' x' k' ->
match Longident.to_concrete_opt x' with
| Some (Ldot (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Ldot"
)
let lapply (T f0') (T f1') =
T (fun c' l' x' k' ->
match Longident.to_concrete_opt x' with
| Some (Lapply (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Lapply"
)
let labelled (T f0') =
T (fun c' l' x' k' ->
match Arg_label.to_concrete_opt x' with
| Some (Labelled (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Labelled"
)
let optional (T f0') =
T (fun c' l' x' k' ->
match Arg_label.to_concrete_opt x' with
| Some (Optional (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Optional"
)
let pconst_integer (T f0') (T f1') =
T (fun c' l' x' k' ->
match Constant.to_concrete_opt x' with
| Some (Pconst_integer (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pconst_integer"
)
let pconst_char (T f0') =
T (fun c' l' x' k' ->
match Constant.to_concrete_opt x' with
| Some (Pconst_char (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pconst_char"
)
let pconst_string (T f0') (T f1') =
T (fun c' l' x' k' ->
match Constant.to_concrete_opt x' with
| Some (Pconst_string (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pconst_string"
)
let pconst_float (T f0') (T f1') =
T (fun c' l' x' k' ->
match Constant.to_concrete_opt x' with
| Some (Pconst_float (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pconst_float"
)
let pstr (T f0') =
T (fun c' l' x' k' ->
match Payload.to_concrete_opt x' with
| Some (PStr (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Structure.to_concrete x0') (k')
end
| _ -> fail l' "PStr"
)
let psig (T f0') =
T (fun c' l' x' k' ->
match Payload.to_concrete_opt x' with
| Some (PSig (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Signature.to_concrete x0') (k')
end
| _ -> fail l' "PSig"
)
let ptyp (T f0') =
T (fun c' l' x' k' ->
match Payload.to_concrete_opt x' with
| Some (PTyp (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "PTyp"
)
let ppat (T f0') (T f1') =
T (fun c' l' x' k' ->
match Payload.to_concrete_opt x' with
| Some (PPat (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "PPat"
)
let ptyp_var (T f0') =
T (fun c' l' x' k' ->
match Core_type.to_concrete_opt x' with
| Some { ptyp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Core_type_desc.to_concrete_opt x' with
| Some (Ptyp_var (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Ptyp_var"
end
| _ -> fail l' "Ptyp_var"
)
let ptyp_arrow (T f0') (T f1') (T f2') =
T (fun c' l' x' k' ->
match Core_type.to_concrete_opt x' with
| Some { ptyp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Core_type_desc.to_concrete_opt x' with
| Some (Ptyp_arrow (x0', x1', x2')) ->
begin
c'.matched <- c'.matched + 1;
f2' c' l' x2' (f1' c' l' x1' (f0' c' l' x0' (k')))
end
| _ -> fail l' "Ptyp_arrow"
end
| _ -> fail l' "Ptyp_arrow"
)
let ptyp_tuple (T f0') =
T (fun c' l' x' k' ->
match Core_type.to_concrete_opt x' with
| Some { ptyp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Core_type_desc.to_concrete_opt x' with
| Some (Ptyp_tuple (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Ptyp_tuple"
end
| _ -> fail l' "Ptyp_tuple"
)
let ptyp_constr (T f0') (T f1') =
T (fun c' l' x' k' ->
match Core_type.to_concrete_opt x' with
| Some { ptyp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Core_type_desc.to_concrete_opt x' with
| Some (Ptyp_constr (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' (Loc.txt (Longident_loc.to_concrete x0')) (k'))
end
| _ -> fail l' "Ptyp_constr"
end
| _ -> fail l' "Ptyp_constr"
)
let ptyp_object (T f0') (T f1') =
T (fun c' l' x' k' ->
match Core_type.to_concrete_opt x' with
| Some { ptyp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Core_type_desc.to_concrete_opt x' with
| Some (Ptyp_object (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Ptyp_object"
end
| _ -> fail l' "Ptyp_object"
)
let ptyp_class (T f0') (T f1') =
T (fun c' l' x' k' ->
match Core_type.to_concrete_opt x' with
| Some { ptyp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Core_type_desc.to_concrete_opt x' with
| Some (Ptyp_class (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' (Loc.txt (Longident_loc.to_concrete x0')) (k'))
end
| _ -> fail l' "Ptyp_class"
end
| _ -> fail l' "Ptyp_class"
)
let ptyp_alias (T f0') (T f1') =
T (fun c' l' x' k' ->
match Core_type.to_concrete_opt x' with
| Some { ptyp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Core_type_desc.to_concrete_opt x' with
| Some (Ptyp_alias (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Ptyp_alias"
end
| _ -> fail l' "Ptyp_alias"
)
let ptyp_variant (T f0') (T f1') (T f2') =
T (fun c' l' x' k' ->
match Core_type.to_concrete_opt x' with
| Some { ptyp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Core_type_desc.to_concrete_opt x' with
| Some (Ptyp_variant (x0', x1', x2')) ->
begin
c'.matched <- c'.matched + 1;
f2' c' l' x2' (f1' c' l' x1' (f0' c' l' x0' (k')))
end
| _ -> fail l' "Ptyp_variant"
end
| _ -> fail l' "Ptyp_variant"
)
let ptyp_poly (T f0') (T f1') =
T (fun c' l' x' k' ->
match Core_type.to_concrete_opt x' with
| Some { ptyp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Core_type_desc.to_concrete_opt x' with
| Some (Ptyp_poly (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Ptyp_poly"
end
| _ -> fail l' "Ptyp_poly"
)
let ptyp_package (T f0') =
T (fun c' l' x' k' ->
match Core_type.to_concrete_opt x' with
| Some { ptyp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Core_type_desc.to_concrete_opt x' with
| Some (Ptyp_package (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Package_type.to_concrete x0') (k')
end
| _ -> fail l' "Ptyp_package"
end
| _ -> fail l' "Ptyp_package"
)
let ptyp_extension (T f0') =
T (fun c' l' x' k' ->
match Core_type.to_concrete_opt x' with
| Some { ptyp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Core_type_desc.to_concrete_opt x' with
| Some (Ptyp_extension (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Extension.to_concrete x0') (k')
end
| _ -> fail l' "Ptyp_extension"
end
| _ -> fail l' "Ptyp_extension"
)
let ptyp_loc (T f') =
T (fun c' l' x' k' ->
match Core_type.to_concrete_opt x' with
| Some { ptyp_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "ptyp_loc"
)
let ptyp_attributes (T f') =
T (fun c' l' x' k' ->
match Core_type.to_concrete_opt x' with
| Some { ptyp_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "ptyp_attributes"
)
let rtag (T f0') (T f1') (T f2') (T f3') =
T (fun c' l' x' k' ->
match Row_field.to_concrete_opt x' with
| Some (Rtag (x0', x1', x2', x3')) ->
begin
c'.matched <- c'.matched + 1;
f3' c' l' x3' (f2' c' l' x2' (f1' c' l' (Attributes.to_concrete x1') (f0' c' l' (Loc.txt x0') (k'))))
end
| _ -> fail l' "Rtag"
)
let rinherit (T f0') =
T (fun c' l' x' k' ->
match Row_field.to_concrete_opt x' with
| Some (Rinherit (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Rinherit"
)
let otag (T f0') (T f1') (T f2') =
T (fun c' l' x' k' ->
match Object_field.to_concrete_opt x' with
| Some (Otag (x0', x1', x2')) ->
begin
c'.matched <- c'.matched + 1;
f2' c' l' x2' (f1' c' l' (Attributes.to_concrete x1') (f0' c' l' (Loc.txt x0') (k')))
end
| _ -> fail l' "Otag"
)
let oinherit (T f0') =
T (fun c' l' x' k' ->
match Object_field.to_concrete_opt x' with
| Some (Oinherit (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Oinherit"
)
let ppat_var (T f0') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Pattern_desc.to_concrete_opt x' with
| Some (Ppat_var (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Loc.txt x0') (k')
end
| _ -> fail l' "Ppat_var"
end
| _ -> fail l' "Ppat_var"
)
let ppat_alias (T f0') (T f1') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Pattern_desc.to_concrete_opt x' with
| Some (Ppat_alias (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' (Loc.txt x1') (f0' c' l' x0' (k'))
end
| _ -> fail l' "Ppat_alias"
end
| _ -> fail l' "Ppat_alias"
)
let ppat_constant (T f0') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Pattern_desc.to_concrete_opt x' with
| Some (Ppat_constant (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Ppat_constant"
end
| _ -> fail l' "Ppat_constant"
)
let ppat_interval (T f0') (T f1') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Pattern_desc.to_concrete_opt x' with
| Some (Ppat_interval (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Ppat_interval"
end
| _ -> fail l' "Ppat_interval"
)
let ppat_tuple (T f0') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Pattern_desc.to_concrete_opt x' with
| Some (Ppat_tuple (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Ppat_tuple"
end
| _ -> fail l' "Ppat_tuple"
)
let ppat_construct (T f0') (T f1') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Pattern_desc.to_concrete_opt x' with
| Some (Ppat_construct (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' (Loc.txt (Longident_loc.to_concrete x0')) (k'))
end
| _ -> fail l' "Ppat_construct"
end
| _ -> fail l' "Ppat_construct"
)
let ppat_variant (T f0') (T f1') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Pattern_desc.to_concrete_opt x' with
| Some (Ppat_variant (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Ppat_variant"
end
| _ -> fail l' "Ppat_variant"
)
let ppat_record (T f0') (T f1') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Pattern_desc.to_concrete_opt x' with
| Some (Ppat_record (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Ppat_record"
end
| _ -> fail l' "Ppat_record"
)
let ppat_array (T f0') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Pattern_desc.to_concrete_opt x' with
| Some (Ppat_array (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Ppat_array"
end
| _ -> fail l' "Ppat_array"
)
let ppat_or (T f0') (T f1') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Pattern_desc.to_concrete_opt x' with
| Some (Ppat_or (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Ppat_or"
end
| _ -> fail l' "Ppat_or"
)
let ppat_constraint (T f0') (T f1') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Pattern_desc.to_concrete_opt x' with
| Some (Ppat_constraint (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Ppat_constraint"
end
| _ -> fail l' "Ppat_constraint"
)
let ppat_type (T f0') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Pattern_desc.to_concrete_opt x' with
| Some (Ppat_type (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Loc.txt (Longident_loc.to_concrete x0')) (k')
end
| _ -> fail l' "Ppat_type"
end
| _ -> fail l' "Ppat_type"
)
let ppat_lazy (T f0') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Pattern_desc.to_concrete_opt x' with
| Some (Ppat_lazy (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Ppat_lazy"
end
| _ -> fail l' "Ppat_lazy"
)
let ppat_unpack (T f0') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Pattern_desc.to_concrete_opt x' with
| Some (Ppat_unpack (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Loc.txt x0') (k')
end
| _ -> fail l' "Ppat_unpack"
end
| _ -> fail l' "Ppat_unpack"
)
let ppat_exception (T f0') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Pattern_desc.to_concrete_opt x' with
| Some (Ppat_exception (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Ppat_exception"
end
| _ -> fail l' "Ppat_exception"
)
let ppat_extension (T f0') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Pattern_desc.to_concrete_opt x' with
| Some (Ppat_extension (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Extension.to_concrete x0') (k')
end
| _ -> fail l' "Ppat_extension"
end
| _ -> fail l' "Ppat_extension"
)
let ppat_open (T f0') (T f1') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Pattern_desc.to_concrete_opt x' with
| Some (Ppat_open (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' (Loc.txt (Longident_loc.to_concrete x0')) (k'))
end
| _ -> fail l' "Ppat_open"
end
| _ -> fail l' "Ppat_open"
)
let ppat_loc (T f') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "ppat_loc"
)
let ppat_attributes (T f') =
T (fun c' l' x' k' ->
match Pattern.to_concrete_opt x' with
| Some { ppat_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "ppat_attributes"
)
let pexp_ident (T f0') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_ident (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Loc.txt (Longident_loc.to_concrete x0')) (k')
end
| _ -> fail l' "Pexp_ident"
end
| _ -> fail l' "Pexp_ident"
)
let pexp_constant (T f0') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_constant (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pexp_constant"
end
| _ -> fail l' "Pexp_constant"
)
let pexp_let (T f0') (T f1') (T f2') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_let (x0', x1', x2')) ->
begin
c'.matched <- c'.matched + 1;
f2' c' l' x2' (f1' c' l' x1' (f0' c' l' x0' (k')))
end
| _ -> fail l' "Pexp_let"
end
| _ -> fail l' "Pexp_let"
)
let pexp_function (T f0') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_function (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pexp_function"
end
| _ -> fail l' "Pexp_function"
)
let pexp_fun (T f0') (T f1') (T f2') (T f3') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_fun (x0', x1', x2', x3')) ->
begin
c'.matched <- c'.matched + 1;
f3' c' l' x3' (f2' c' l' x2' (f1' c' l' x1' (f0' c' l' x0' (k'))))
end
| _ -> fail l' "Pexp_fun"
end
| _ -> fail l' "Pexp_fun"
)
let pexp_apply (T f0') (T f1') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_apply (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pexp_apply"
end
| _ -> fail l' "Pexp_apply"
)
let pexp_match (T f0') (T f1') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_match (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pexp_match"
end
| _ -> fail l' "Pexp_match"
)
let pexp_try (T f0') (T f1') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_try (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pexp_try"
end
| _ -> fail l' "Pexp_try"
)
let pexp_tuple (T f0') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_tuple (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pexp_tuple"
end
| _ -> fail l' "Pexp_tuple"
)
let pexp_construct (T f0') (T f1') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_construct (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' (Loc.txt (Longident_loc.to_concrete x0')) (k'))
end
| _ -> fail l' "Pexp_construct"
end
| _ -> fail l' "Pexp_construct"
)
let pexp_variant (T f0') (T f1') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_variant (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pexp_variant"
end
| _ -> fail l' "Pexp_variant"
)
let pexp_record (T f0') (T f1') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_record (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pexp_record"
end
| _ -> fail l' "Pexp_record"
)
let pexp_field (T f0') (T f1') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_field (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' (Loc.txt (Longident_loc.to_concrete x1')) (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pexp_field"
end
| _ -> fail l' "Pexp_field"
)
let pexp_setfield (T f0') (T f1') (T f2') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_setfield (x0', x1', x2')) ->
begin
c'.matched <- c'.matched + 1;
f2' c' l' x2' (f1' c' l' (Loc.txt (Longident_loc.to_concrete x1')) (f0' c' l' x0' (k')))
end
| _ -> fail l' "Pexp_setfield"
end
| _ -> fail l' "Pexp_setfield"
)
let pexp_array (T f0') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_array (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pexp_array"
end
| _ -> fail l' "Pexp_array"
)
let pexp_ifthenelse (T f0') (T f1') (T f2') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_ifthenelse (x0', x1', x2')) ->
begin
c'.matched <- c'.matched + 1;
f2' c' l' x2' (f1' c' l' x1' (f0' c' l' x0' (k')))
end
| _ -> fail l' "Pexp_ifthenelse"
end
| _ -> fail l' "Pexp_ifthenelse"
)
let pexp_sequence (T f0') (T f1') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_sequence (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pexp_sequence"
end
| _ -> fail l' "Pexp_sequence"
)
let pexp_while (T f0') (T f1') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_while (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pexp_while"
end
| _ -> fail l' "Pexp_while"
)
let pexp_for (T f0') (T f1') (T f2') (T f3') (T f4') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_for (x0', x1', x2', x3', x4')) ->
begin
c'.matched <- c'.matched + 1;
f4' c' l' x4' (f3' c' l' x3' (f2' c' l' x2' (f1' c' l' x1' (f0' c' l' x0' (k')))))
end
| _ -> fail l' "Pexp_for"
end
| _ -> fail l' "Pexp_for"
)
let pexp_constraint (T f0') (T f1') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_constraint (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pexp_constraint"
end
| _ -> fail l' "Pexp_constraint"
)
let pexp_coerce (T f0') (T f1') (T f2') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_coerce (x0', x1', x2')) ->
begin
c'.matched <- c'.matched + 1;
f2' c' l' x2' (f1' c' l' x1' (f0' c' l' x0' (k')))
end
| _ -> fail l' "Pexp_coerce"
end
| _ -> fail l' "Pexp_coerce"
)
let pexp_send (T f0') (T f1') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_send (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' (Loc.txt x1') (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pexp_send"
end
| _ -> fail l' "Pexp_send"
)
let pexp_new (T f0') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_new (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Loc.txt (Longident_loc.to_concrete x0')) (k')
end
| _ -> fail l' "Pexp_new"
end
| _ -> fail l' "Pexp_new"
)
let pexp_setinstvar (T f0') (T f1') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_setinstvar (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' (Loc.txt x0') (k'))
end
| _ -> fail l' "Pexp_setinstvar"
end
| _ -> fail l' "Pexp_setinstvar"
)
let pexp_override (T f0') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_override (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pexp_override"
end
| _ -> fail l' "Pexp_override"
)
let pexp_letmodule (T f0') (T f1') (T f2') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_letmodule (x0', x1', x2')) ->
begin
c'.matched <- c'.matched + 1;
f2' c' l' x2' (f1' c' l' x1' (f0' c' l' (Loc.txt x0') (k')))
end
| _ -> fail l' "Pexp_letmodule"
end
| _ -> fail l' "Pexp_letmodule"
)
let pexp_letexception (T f0') (T f1') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_letexception (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pexp_letexception"
end
| _ -> fail l' "Pexp_letexception"
)
let pexp_assert (T f0') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_assert (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pexp_assert"
end
| _ -> fail l' "Pexp_assert"
)
let pexp_lazy (T f0') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_lazy (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pexp_lazy"
end
| _ -> fail l' "Pexp_lazy"
)
let pexp_poly (T f0') (T f1') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_poly (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pexp_poly"
end
| _ -> fail l' "Pexp_poly"
)
let pexp_object (T f0') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_object (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pexp_object"
end
| _ -> fail l' "Pexp_object"
)
let pexp_newtype (T f0') (T f1') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_newtype (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' (Loc.txt x0') (k'))
end
| _ -> fail l' "Pexp_newtype"
end
| _ -> fail l' "Pexp_newtype"
)
let pexp_pack (T f0') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_pack (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pexp_pack"
end
| _ -> fail l' "Pexp_pack"
)
let pexp_open (T f0') (T f1') (T f2') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_open (x0', x1', x2')) ->
begin
c'.matched <- c'.matched + 1;
f2' c' l' x2' (f1' c' l' (Loc.txt (Longident_loc.to_concrete x1')) (f0' c' l' x0' (k')))
end
| _ -> fail l' "Pexp_open"
end
| _ -> fail l' "Pexp_open"
)
let pexp_extension (T f0') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Expression_desc.to_concrete_opt x' with
| Some (Pexp_extension (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Extension.to_concrete x0') (k')
end
| _ -> fail l' "Pexp_extension"
end
| _ -> fail l' "Pexp_extension"
)
let pexp_loc (T f') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "pexp_loc"
)
let pexp_attributes (T f') =
T (fun c' l' x' k' ->
match Expression.to_concrete_opt x' with
| Some { pexp_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "pexp_attributes"
)
let pval_attributes (T f') =
T (fun c' l' x' k' ->
match Value_description.to_concrete_opt x' with
| Some { pval_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "pval_attributes"
)
let pval_loc (T f') =
T (fun c' l' x' k' ->
match Value_description.to_concrete_opt x' with
| Some { pval_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "pval_loc"
)
let ptype_attributes (T f') =
T (fun c' l' x' k' ->
match Type_declaration.to_concrete_opt x' with
| Some { ptype_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "ptype_attributes"
)
let ptype_loc (T f') =
T (fun c' l' x' k' ->
match Type_declaration.to_concrete_opt x' with
| Some { ptype_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "ptype_loc"
)
let ptype_variant (T f0') =
T (fun c' l' x' k' ->
match Type_kind.to_concrete_opt x' with
| Some (Ptype_variant (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Ptype_variant"
)
let ptype_record (T f0') =
T (fun c' l' x' k' ->
match Type_kind.to_concrete_opt x' with
| Some (Ptype_record (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Ptype_record"
)
let pld_loc (T f') =
T (fun c' l' x' k' ->
match Label_declaration.to_concrete_opt x' with
| Some { pld_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "pld_loc"
)
let pld_attributes (T f') =
T (fun c' l' x' k' ->
match Label_declaration.to_concrete_opt x' with
| Some { pld_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "pld_attributes"
)
let pcd_loc (T f') =
T (fun c' l' x' k' ->
match Constructor_declaration.to_concrete_opt x' with
| Some { pcd_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "pcd_loc"
)
let pcd_attributes (T f') =
T (fun c' l' x' k' ->
match Constructor_declaration.to_concrete_opt x' with
| Some { pcd_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "pcd_attributes"
)
let pcstr_tuple (T f0') =
T (fun c' l' x' k' ->
match Constructor_arguments.to_concrete_opt x' with
| Some (Pcstr_tuple (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pcstr_tuple"
)
let pcstr_record (T f0') =
T (fun c' l' x' k' ->
match Constructor_arguments.to_concrete_opt x' with
| Some (Pcstr_record (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pcstr_record"
)
let ptyext_attributes (T f') =
T (fun c' l' x' k' ->
match Type_extension.to_concrete_opt x' with
| Some { ptyext_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "ptyext_attributes"
)
let pext_loc (T f') =
T (fun c' l' x' k' ->
match Extension_constructor.to_concrete_opt x' with
| Some { pext_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "pext_loc"
)
let pext_attributes (T f') =
T (fun c' l' x' k' ->
match Extension_constructor.to_concrete_opt x' with
| Some { pext_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "pext_attributes"
)
let pext_decl (T f0') (T f1') =
T (fun c' l' x' k' ->
match Extension_constructor_kind.to_concrete_opt x' with
| Some (Pext_decl (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pext_decl"
)
let pext_rebind (T f0') =
T (fun c' l' x' k' ->
match Extension_constructor_kind.to_concrete_opt x' with
| Some (Pext_rebind (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Loc.txt (Longident_loc.to_concrete x0')) (k')
end
| _ -> fail l' "Pext_rebind"
)
let pcty_constr (T f0') (T f1') =
T (fun c' l' x' k' ->
match Class_type.to_concrete_opt x' with
| Some { pcty_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_type_desc.to_concrete_opt x' with
| Some (Pcty_constr (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' (Loc.txt (Longident_loc.to_concrete x0')) (k'))
end
| _ -> fail l' "Pcty_constr"
end
| _ -> fail l' "Pcty_constr"
)
let pcty_signature (T f0') =
T (fun c' l' x' k' ->
match Class_type.to_concrete_opt x' with
| Some { pcty_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_type_desc.to_concrete_opt x' with
| Some (Pcty_signature (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pcty_signature"
end
| _ -> fail l' "Pcty_signature"
)
let pcty_arrow (T f0') (T f1') (T f2') =
T (fun c' l' x' k' ->
match Class_type.to_concrete_opt x' with
| Some { pcty_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_type_desc.to_concrete_opt x' with
| Some (Pcty_arrow (x0', x1', x2')) ->
begin
c'.matched <- c'.matched + 1;
f2' c' l' x2' (f1' c' l' x1' (f0' c' l' x0' (k')))
end
| _ -> fail l' "Pcty_arrow"
end
| _ -> fail l' "Pcty_arrow"
)
let pcty_extension (T f0') =
T (fun c' l' x' k' ->
match Class_type.to_concrete_opt x' with
| Some { pcty_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_type_desc.to_concrete_opt x' with
| Some (Pcty_extension (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Extension.to_concrete x0') (k')
end
| _ -> fail l' "Pcty_extension"
end
| _ -> fail l' "Pcty_extension"
)
let pcty_open (T f0') (T f1') (T f2') =
T (fun c' l' x' k' ->
match Class_type.to_concrete_opt x' with
| Some { pcty_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_type_desc.to_concrete_opt x' with
| Some (Pcty_open (x0', x1', x2')) ->
begin
c'.matched <- c'.matched + 1;
f2' c' l' x2' (f1' c' l' (Loc.txt (Longident_loc.to_concrete x1')) (f0' c' l' x0' (k')))
end
| _ -> fail l' "Pcty_open"
end
| _ -> fail l' "Pcty_open"
)
let pcty_loc (T f') =
T (fun c' l' x' k' ->
match Class_type.to_concrete_opt x' with
| Some { pcty_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "pcty_loc"
)
let pcty_attributes (T f') =
T (fun c' l' x' k' ->
match Class_type.to_concrete_opt x' with
| Some { pcty_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "pcty_attributes"
)
let pctf_inherit (T f0') =
T (fun c' l' x' k' ->
match Class_type_field.to_concrete_opt x' with
| Some { pctf_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_type_field_desc.to_concrete_opt x' with
| Some (Pctf_inherit (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pctf_inherit"
end
| _ -> fail l' "Pctf_inherit"
)
let pctf_val (T f0') =
T (fun c' l' x' k' ->
match Class_type_field.to_concrete_opt x' with
| Some { pctf_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_type_field_desc.to_concrete_opt x' with
| Some (Pctf_val (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pctf_val"
end
| _ -> fail l' "Pctf_val"
)
let pctf_method (T f0') =
T (fun c' l' x' k' ->
match Class_type_field.to_concrete_opt x' with
| Some { pctf_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_type_field_desc.to_concrete_opt x' with
| Some (Pctf_method (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pctf_method"
end
| _ -> fail l' "Pctf_method"
)
let pctf_constraint (T f0') =
T (fun c' l' x' k' ->
match Class_type_field.to_concrete_opt x' with
| Some { pctf_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_type_field_desc.to_concrete_opt x' with
| Some (Pctf_constraint (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pctf_constraint"
end
| _ -> fail l' "Pctf_constraint"
)
let pctf_attribute (T f0') =
T (fun c' l' x' k' ->
match Class_type_field.to_concrete_opt x' with
| Some { pctf_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_type_field_desc.to_concrete_opt x' with
| Some (Pctf_attribute (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Attribute.to_concrete x0') (k')
end
| _ -> fail l' "Pctf_attribute"
end
| _ -> fail l' "Pctf_attribute"
)
let pctf_extension (T f0') =
T (fun c' l' x' k' ->
match Class_type_field.to_concrete_opt x' with
| Some { pctf_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_type_field_desc.to_concrete_opt x' with
| Some (Pctf_extension (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Extension.to_concrete x0') (k')
end
| _ -> fail l' "Pctf_extension"
end
| _ -> fail l' "Pctf_extension"
)
let pctf_loc (T f') =
T (fun c' l' x' k' ->
match Class_type_field.to_concrete_opt x' with
| Some { pctf_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "pctf_loc"
)
let pctf_attributes (T f') =
T (fun c' l' x' k' ->
match Class_type_field.to_concrete_opt x' with
| Some { pctf_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "pctf_attributes"
)
let pci_loc (T f') =
T (fun c' l' x' k' ->
match Class_infos.to_concrete_opt x' with
| Some { pci_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "pci_loc"
)
let pci_attributes (T f') =
T (fun c' l' x' k' ->
match Class_infos.to_concrete_opt x' with
| Some { pci_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "pci_attributes"
)
let pcl_constr (T f0') (T f1') =
T (fun c' l' x' k' ->
match Class_expr.to_concrete_opt x' with
| Some { pcl_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_expr_desc.to_concrete_opt x' with
| Some (Pcl_constr (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' (Loc.txt (Longident_loc.to_concrete x0')) (k'))
end
| _ -> fail l' "Pcl_constr"
end
| _ -> fail l' "Pcl_constr"
)
let pcl_structure (T f0') =
T (fun c' l' x' k' ->
match Class_expr.to_concrete_opt x' with
| Some { pcl_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_expr_desc.to_concrete_opt x' with
| Some (Pcl_structure (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pcl_structure"
end
| _ -> fail l' "Pcl_structure"
)
let pcl_fun (T f0') (T f1') (T f2') (T f3') =
T (fun c' l' x' k' ->
match Class_expr.to_concrete_opt x' with
| Some { pcl_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_expr_desc.to_concrete_opt x' with
| Some (Pcl_fun (x0', x1', x2', x3')) ->
begin
c'.matched <- c'.matched + 1;
f3' c' l' x3' (f2' c' l' x2' (f1' c' l' x1' (f0' c' l' x0' (k'))))
end
| _ -> fail l' "Pcl_fun"
end
| _ -> fail l' "Pcl_fun"
)
let pcl_apply (T f0') (T f1') =
T (fun c' l' x' k' ->
match Class_expr.to_concrete_opt x' with
| Some { pcl_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_expr_desc.to_concrete_opt x' with
| Some (Pcl_apply (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pcl_apply"
end
| _ -> fail l' "Pcl_apply"
)
let pcl_let (T f0') (T f1') (T f2') =
T (fun c' l' x' k' ->
match Class_expr.to_concrete_opt x' with
| Some { pcl_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_expr_desc.to_concrete_opt x' with
| Some (Pcl_let (x0', x1', x2')) ->
begin
c'.matched <- c'.matched + 1;
f2' c' l' x2' (f1' c' l' x1' (f0' c' l' x0' (k')))
end
| _ -> fail l' "Pcl_let"
end
| _ -> fail l' "Pcl_let"
)
let pcl_constraint (T f0') (T f1') =
T (fun c' l' x' k' ->
match Class_expr.to_concrete_opt x' with
| Some { pcl_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_expr_desc.to_concrete_opt x' with
| Some (Pcl_constraint (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pcl_constraint"
end
| _ -> fail l' "Pcl_constraint"
)
let pcl_extension (T f0') =
T (fun c' l' x' k' ->
match Class_expr.to_concrete_opt x' with
| Some { pcl_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_expr_desc.to_concrete_opt x' with
| Some (Pcl_extension (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Extension.to_concrete x0') (k')
end
| _ -> fail l' "Pcl_extension"
end
| _ -> fail l' "Pcl_extension"
)
let pcl_open (T f0') (T f1') (T f2') =
T (fun c' l' x' k' ->
match Class_expr.to_concrete_opt x' with
| Some { pcl_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_expr_desc.to_concrete_opt x' with
| Some (Pcl_open (x0', x1', x2')) ->
begin
c'.matched <- c'.matched + 1;
f2' c' l' x2' (f1' c' l' (Loc.txt (Longident_loc.to_concrete x1')) (f0' c' l' x0' (k')))
end
| _ -> fail l' "Pcl_open"
end
| _ -> fail l' "Pcl_open"
)
let pcl_loc (T f') =
T (fun c' l' x' k' ->
match Class_expr.to_concrete_opt x' with
| Some { pcl_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "pcl_loc"
)
let pcl_attributes (T f') =
T (fun c' l' x' k' ->
match Class_expr.to_concrete_opt x' with
| Some { pcl_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "pcl_attributes"
)
let pcf_inherit (T f0') (T f1') (T f2') =
T (fun c' l' x' k' ->
match Class_field.to_concrete_opt x' with
| Some { pcf_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_field_desc.to_concrete_opt x' with
| Some (Pcf_inherit (x0', x1', x2')) ->
begin
c'.matched <- c'.matched + 1;
f2' c' l' x2' (f1' c' l' x1' (f0' c' l' x0' (k')))
end
| _ -> fail l' "Pcf_inherit"
end
| _ -> fail l' "Pcf_inherit"
)
let pcf_val (T f0') =
T (fun c' l' x' k' ->
match Class_field.to_concrete_opt x' with
| Some { pcf_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_field_desc.to_concrete_opt x' with
| Some (Pcf_val (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pcf_val"
end
| _ -> fail l' "Pcf_val"
)
let pcf_method (T f0') =
T (fun c' l' x' k' ->
match Class_field.to_concrete_opt x' with
| Some { pcf_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_field_desc.to_concrete_opt x' with
| Some (Pcf_method (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pcf_method"
end
| _ -> fail l' "Pcf_method"
)
let pcf_constraint (T f0') =
T (fun c' l' x' k' ->
match Class_field.to_concrete_opt x' with
| Some { pcf_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_field_desc.to_concrete_opt x' with
| Some (Pcf_constraint (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pcf_constraint"
end
| _ -> fail l' "Pcf_constraint"
)
let pcf_initializer (T f0') =
T (fun c' l' x' k' ->
match Class_field.to_concrete_opt x' with
| Some { pcf_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_field_desc.to_concrete_opt x' with
| Some (Pcf_initializer (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pcf_initializer"
end
| _ -> fail l' "Pcf_initializer"
)
let pcf_attribute (T f0') =
T (fun c' l' x' k' ->
match Class_field.to_concrete_opt x' with
| Some { pcf_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_field_desc.to_concrete_opt x' with
| Some (Pcf_attribute (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Attribute.to_concrete x0') (k')
end
| _ -> fail l' "Pcf_attribute"
end
| _ -> fail l' "Pcf_attribute"
)
let pcf_extension (T f0') =
T (fun c' l' x' k' ->
match Class_field.to_concrete_opt x' with
| Some { pcf_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Class_field_desc.to_concrete_opt x' with
| Some (Pcf_extension (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Extension.to_concrete x0') (k')
end
| _ -> fail l' "Pcf_extension"
end
| _ -> fail l' "Pcf_extension"
)
let pcf_loc (T f') =
T (fun c' l' x' k' ->
match Class_field.to_concrete_opt x' with
| Some { pcf_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "pcf_loc"
)
let pcf_attributes (T f') =
T (fun c' l' x' k' ->
match Class_field.to_concrete_opt x' with
| Some { pcf_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "pcf_attributes"
)
let cfk_virtual (T f0') =
T (fun c' l' x' k' ->
match Class_field_kind.to_concrete_opt x' with
| Some (Cfk_virtual (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Cfk_virtual"
)
let cfk_concrete (T f0') (T f1') =
T (fun c' l' x' k' ->
match Class_field_kind.to_concrete_opt x' with
| Some (Cfk_concrete (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Cfk_concrete"
)
let pmty_ident (T f0') =
T (fun c' l' x' k' ->
match Module_type.to_concrete_opt x' with
| Some { pmty_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Module_type_desc.to_concrete_opt x' with
| Some (Pmty_ident (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Loc.txt (Longident_loc.to_concrete x0')) (k')
end
| _ -> fail l' "Pmty_ident"
end
| _ -> fail l' "Pmty_ident"
)
let pmty_signature (T f0') =
T (fun c' l' x' k' ->
match Module_type.to_concrete_opt x' with
| Some { pmty_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Module_type_desc.to_concrete_opt x' with
| Some (Pmty_signature (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Signature.to_concrete x0') (k')
end
| _ -> fail l' "Pmty_signature"
end
| _ -> fail l' "Pmty_signature"
)
let pmty_functor (T f0') (T f1') (T f2') =
T (fun c' l' x' k' ->
match Module_type.to_concrete_opt x' with
| Some { pmty_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Module_type_desc.to_concrete_opt x' with
| Some (Pmty_functor (x0', x1', x2')) ->
begin
c'.matched <- c'.matched + 1;
f2' c' l' x2' (f1' c' l' x1' (f0' c' l' (Loc.txt x0') (k')))
end
| _ -> fail l' "Pmty_functor"
end
| _ -> fail l' "Pmty_functor"
)
let pmty_with (T f0') (T f1') =
T (fun c' l' x' k' ->
match Module_type.to_concrete_opt x' with
| Some { pmty_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Module_type_desc.to_concrete_opt x' with
| Some (Pmty_with (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pmty_with"
end
| _ -> fail l' "Pmty_with"
)
let pmty_typeof (T f0') =
T (fun c' l' x' k' ->
match Module_type.to_concrete_opt x' with
| Some { pmty_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Module_type_desc.to_concrete_opt x' with
| Some (Pmty_typeof (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pmty_typeof"
end
| _ -> fail l' "Pmty_typeof"
)
let pmty_extension (T f0') =
T (fun c' l' x' k' ->
match Module_type.to_concrete_opt x' with
| Some { pmty_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Module_type_desc.to_concrete_opt x' with
| Some (Pmty_extension (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Extension.to_concrete x0') (k')
end
| _ -> fail l' "Pmty_extension"
end
| _ -> fail l' "Pmty_extension"
)
let pmty_alias (T f0') =
T (fun c' l' x' k' ->
match Module_type.to_concrete_opt x' with
| Some { pmty_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Module_type_desc.to_concrete_opt x' with
| Some (Pmty_alias (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Loc.txt (Longident_loc.to_concrete x0')) (k')
end
| _ -> fail l' "Pmty_alias"
end
| _ -> fail l' "Pmty_alias"
)
let pmty_loc (T f') =
T (fun c' l' x' k' ->
match Module_type.to_concrete_opt x' with
| Some { pmty_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "pmty_loc"
)
let pmty_attributes (T f') =
T (fun c' l' x' k' ->
match Module_type.to_concrete_opt x' with
| Some { pmty_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "pmty_attributes"
)
let psig_value (T f0') =
T (fun c' l' x' k' ->
match Signature_item.to_concrete_opt x' with
| Some { psig_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Signature_item_desc.to_concrete_opt x' with
| Some (Psig_value (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Psig_value"
end
| _ -> fail l' "Psig_value"
)
let psig_type (T f0') (T f1') =
T (fun c' l' x' k' ->
match Signature_item.to_concrete_opt x' with
| Some { psig_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Signature_item_desc.to_concrete_opt x' with
| Some (Psig_type (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Psig_type"
end
| _ -> fail l' "Psig_type"
)
let psig_typext (T f0') =
T (fun c' l' x' k' ->
match Signature_item.to_concrete_opt x' with
| Some { psig_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Signature_item_desc.to_concrete_opt x' with
| Some (Psig_typext (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Psig_typext"
end
| _ -> fail l' "Psig_typext"
)
let psig_exception (T f0') =
T (fun c' l' x' k' ->
match Signature_item.to_concrete_opt x' with
| Some { psig_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Signature_item_desc.to_concrete_opt x' with
| Some (Psig_exception (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Psig_exception"
end
| _ -> fail l' "Psig_exception"
)
let psig_module (T f0') =
T (fun c' l' x' k' ->
match Signature_item.to_concrete_opt x' with
| Some { psig_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Signature_item_desc.to_concrete_opt x' with
| Some (Psig_module (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Psig_module"
end
| _ -> fail l' "Psig_module"
)
let psig_recmodule (T f0') =
T (fun c' l' x' k' ->
match Signature_item.to_concrete_opt x' with
| Some { psig_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Signature_item_desc.to_concrete_opt x' with
| Some (Psig_recmodule (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Psig_recmodule"
end
| _ -> fail l' "Psig_recmodule"
)
let psig_modtype (T f0') =
T (fun c' l' x' k' ->
match Signature_item.to_concrete_opt x' with
| Some { psig_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Signature_item_desc.to_concrete_opt x' with
| Some (Psig_modtype (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Psig_modtype"
end
| _ -> fail l' "Psig_modtype"
)
let psig_open (T f0') =
T (fun c' l' x' k' ->
match Signature_item.to_concrete_opt x' with
| Some { psig_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Signature_item_desc.to_concrete_opt x' with
| Some (Psig_open (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Psig_open"
end
| _ -> fail l' "Psig_open"
)
let psig_include (T f0') =
T (fun c' l' x' k' ->
match Signature_item.to_concrete_opt x' with
| Some { psig_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Signature_item_desc.to_concrete_opt x' with
| Some (Psig_include (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Include_description.to_concrete x0') (k')
end
| _ -> fail l' "Psig_include"
end
| _ -> fail l' "Psig_include"
)
let psig_class (T f0') =
T (fun c' l' x' k' ->
match Signature_item.to_concrete_opt x' with
| Some { psig_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Signature_item_desc.to_concrete_opt x' with
| Some (Psig_class (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Psig_class"
end
| _ -> fail l' "Psig_class"
)
let psig_class_type (T f0') =
T (fun c' l' x' k' ->
match Signature_item.to_concrete_opt x' with
| Some { psig_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Signature_item_desc.to_concrete_opt x' with
| Some (Psig_class_type (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Psig_class_type"
end
| _ -> fail l' "Psig_class_type"
)
let psig_attribute (T f0') =
T (fun c' l' x' k' ->
match Signature_item.to_concrete_opt x' with
| Some { psig_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Signature_item_desc.to_concrete_opt x' with
| Some (Psig_attribute (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Attribute.to_concrete x0') (k')
end
| _ -> fail l' "Psig_attribute"
end
| _ -> fail l' "Psig_attribute"
)
let psig_extension (T f0') (T f1') =
T (fun c' l' x' k' ->
match Signature_item.to_concrete_opt x' with
| Some { psig_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Signature_item_desc.to_concrete_opt x' with
| Some (Psig_extension (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' (Attributes.to_concrete x1') (f0' c' l' (Extension.to_concrete x0') (k'))
end
| _ -> fail l' "Psig_extension"
end
| _ -> fail l' "Psig_extension"
)
let psig_loc (T f') =
T (fun c' l' x' k' ->
match Signature_item.to_concrete_opt x' with
| Some { psig_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "psig_loc"
)
let pmd_attributes (T f') =
T (fun c' l' x' k' ->
match Module_declaration.to_concrete_opt x' with
| Some { pmd_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "pmd_attributes"
)
let pmd_loc (T f') =
T (fun c' l' x' k' ->
match Module_declaration.to_concrete_opt x' with
| Some { pmd_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "pmd_loc"
)
let pmtd_attributes (T f') =
T (fun c' l' x' k' ->
match Module_type_declaration.to_concrete_opt x' with
| Some { pmtd_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "pmtd_attributes"
)
let pmtd_loc (T f') =
T (fun c' l' x' k' ->
match Module_type_declaration.to_concrete_opt x' with
| Some { pmtd_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "pmtd_loc"
)
let popen_loc (T f') =
T (fun c' l' x' k' ->
match Open_description.to_concrete_opt x' with
| Some { popen_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "popen_loc"
)
let popen_attributes (T f') =
T (fun c' l' x' k' ->
match Open_description.to_concrete_opt x' with
| Some { popen_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "popen_attributes"
)
let pincl_loc (T f') =
T (fun c' l' x' k' ->
match Include_infos.to_concrete_opt x' with
| Some { pincl_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "pincl_loc"
)
let pincl_attributes (T f') =
T (fun c' l' x' k' ->
match Include_infos.to_concrete_opt x' with
| Some { pincl_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "pincl_attributes"
)
let pwith_type (T f0') (T f1') =
T (fun c' l' x' k' ->
match With_constraint.to_concrete_opt x' with
| Some (Pwith_type (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' (Loc.txt (Longident_loc.to_concrete x0')) (k'))
end
| _ -> fail l' "Pwith_type"
)
let pwith_module (T f0') (T f1') =
T (fun c' l' x' k' ->
match With_constraint.to_concrete_opt x' with
| Some (Pwith_module (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' (Loc.txt (Longident_loc.to_concrete x1')) (f0' c' l' (Loc.txt (Longident_loc.to_concrete x0')) (k'))
end
| _ -> fail l' "Pwith_module"
)
let pwith_typesubst (T f0') (T f1') =
T (fun c' l' x' k' ->
match With_constraint.to_concrete_opt x' with
| Some (Pwith_typesubst (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' (Loc.txt (Longident_loc.to_concrete x0')) (k'))
end
| _ -> fail l' "Pwith_typesubst"
)
let pwith_modsubst (T f0') (T f1') =
T (fun c' l' x' k' ->
match With_constraint.to_concrete_opt x' with
| Some (Pwith_modsubst (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' (Loc.txt (Longident_loc.to_concrete x1')) (f0' c' l' (Loc.txt (Longident_loc.to_concrete x0')) (k'))
end
| _ -> fail l' "Pwith_modsubst"
)
let pmod_ident (T f0') =
T (fun c' l' x' k' ->
match Module_expr.to_concrete_opt x' with
| Some { pmod_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Module_expr_desc.to_concrete_opt x' with
| Some (Pmod_ident (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Loc.txt (Longident_loc.to_concrete x0')) (k')
end
| _ -> fail l' "Pmod_ident"
end
| _ -> fail l' "Pmod_ident"
)
let pmod_structure (T f0') =
T (fun c' l' x' k' ->
match Module_expr.to_concrete_opt x' with
| Some { pmod_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Module_expr_desc.to_concrete_opt x' with
| Some (Pmod_structure (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Structure.to_concrete x0') (k')
end
| _ -> fail l' "Pmod_structure"
end
| _ -> fail l' "Pmod_structure"
)
let pmod_functor (T f0') (T f1') (T f2') =
T (fun c' l' x' k' ->
match Module_expr.to_concrete_opt x' with
| Some { pmod_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Module_expr_desc.to_concrete_opt x' with
| Some (Pmod_functor (x0', x1', x2')) ->
begin
c'.matched <- c'.matched + 1;
f2' c' l' x2' (f1' c' l' x1' (f0' c' l' (Loc.txt x0') (k')))
end
| _ -> fail l' "Pmod_functor"
end
| _ -> fail l' "Pmod_functor"
)
let pmod_apply (T f0') (T f1') =
T (fun c' l' x' k' ->
match Module_expr.to_concrete_opt x' with
| Some { pmod_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Module_expr_desc.to_concrete_opt x' with
| Some (Pmod_apply (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pmod_apply"
end
| _ -> fail l' "Pmod_apply"
)
let pmod_constraint (T f0') (T f1') =
T (fun c' l' x' k' ->
match Module_expr.to_concrete_opt x' with
| Some { pmod_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Module_expr_desc.to_concrete_opt x' with
| Some (Pmod_constraint (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pmod_constraint"
end
| _ -> fail l' "Pmod_constraint"
)
let pmod_unpack (T f0') =
T (fun c' l' x' k' ->
match Module_expr.to_concrete_opt x' with
| Some { pmod_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Module_expr_desc.to_concrete_opt x' with
| Some (Pmod_unpack (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pmod_unpack"
end
| _ -> fail l' "Pmod_unpack"
)
let pmod_extension (T f0') =
T (fun c' l' x' k' ->
match Module_expr.to_concrete_opt x' with
| Some { pmod_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Module_expr_desc.to_concrete_opt x' with
| Some (Pmod_extension (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Extension.to_concrete x0') (k')
end
| _ -> fail l' "Pmod_extension"
end
| _ -> fail l' "Pmod_extension"
)
let pmod_loc (T f') =
T (fun c' l' x' k' ->
match Module_expr.to_concrete_opt x' with
| Some { pmod_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "pmod_loc"
)
let pmod_attributes (T f') =
T (fun c' l' x' k' ->
match Module_expr.to_concrete_opt x' with
| Some { pmod_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "pmod_attributes"
)
let pstr_eval (T f0') (T f1') =
T (fun c' l' x' k' ->
match Structure_item.to_concrete_opt x' with
| Some { pstr_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Structure_item_desc.to_concrete_opt x' with
| Some (Pstr_eval (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' (Attributes.to_concrete x1') (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pstr_eval"
end
| _ -> fail l' "Pstr_eval"
)
let pstr_value (T f0') (T f1') =
T (fun c' l' x' k' ->
match Structure_item.to_concrete_opt x' with
| Some { pstr_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Structure_item_desc.to_concrete_opt x' with
| Some (Pstr_value (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pstr_value"
end
| _ -> fail l' "Pstr_value"
)
let pstr_primitive (T f0') =
T (fun c' l' x' k' ->
match Structure_item.to_concrete_opt x' with
| Some { pstr_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Structure_item_desc.to_concrete_opt x' with
| Some (Pstr_primitive (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pstr_primitive"
end
| _ -> fail l' "Pstr_primitive"
)
let pstr_type (T f0') (T f1') =
T (fun c' l' x' k' ->
match Structure_item.to_concrete_opt x' with
| Some { pstr_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Structure_item_desc.to_concrete_opt x' with
| Some (Pstr_type (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pstr_type"
end
| _ -> fail l' "Pstr_type"
)
let pstr_typext (T f0') =
T (fun c' l' x' k' ->
match Structure_item.to_concrete_opt x' with
| Some { pstr_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Structure_item_desc.to_concrete_opt x' with
| Some (Pstr_typext (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pstr_typext"
end
| _ -> fail l' "Pstr_typext"
)
let pstr_exception (T f0') =
T (fun c' l' x' k' ->
match Structure_item.to_concrete_opt x' with
| Some { pstr_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Structure_item_desc.to_concrete_opt x' with
| Some (Pstr_exception (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pstr_exception"
end
| _ -> fail l' "Pstr_exception"
)
let pstr_module (T f0') =
T (fun c' l' x' k' ->
match Structure_item.to_concrete_opt x' with
| Some { pstr_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Structure_item_desc.to_concrete_opt x' with
| Some (Pstr_module (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pstr_module"
end
| _ -> fail l' "Pstr_module"
)
let pstr_recmodule (T f0') =
T (fun c' l' x' k' ->
match Structure_item.to_concrete_opt x' with
| Some { pstr_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Structure_item_desc.to_concrete_opt x' with
| Some (Pstr_recmodule (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pstr_recmodule"
end
| _ -> fail l' "Pstr_recmodule"
)
let pstr_modtype (T f0') =
T (fun c' l' x' k' ->
match Structure_item.to_concrete_opt x' with
| Some { pstr_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Structure_item_desc.to_concrete_opt x' with
| Some (Pstr_modtype (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pstr_modtype"
end
| _ -> fail l' "Pstr_modtype"
)
let pstr_open (T f0') =
T (fun c' l' x' k' ->
match Structure_item.to_concrete_opt x' with
| Some { pstr_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Structure_item_desc.to_concrete_opt x' with
| Some (Pstr_open (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pstr_open"
end
| _ -> fail l' "Pstr_open"
)
let pstr_class (T f0') =
T (fun c' l' x' k' ->
match Structure_item.to_concrete_opt x' with
| Some { pstr_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Structure_item_desc.to_concrete_opt x' with
| Some (Pstr_class (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pstr_class"
end
| _ -> fail l' "Pstr_class"
)
let pstr_class_type (T f0') =
T (fun c' l' x' k' ->
match Structure_item.to_concrete_opt x' with
| Some { pstr_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Structure_item_desc.to_concrete_opt x' with
| Some (Pstr_class_type (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pstr_class_type"
end
| _ -> fail l' "Pstr_class_type"
)
let pstr_include (T f0') =
T (fun c' l' x' k' ->
match Structure_item.to_concrete_opt x' with
| Some { pstr_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Structure_item_desc.to_concrete_opt x' with
| Some (Pstr_include (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Include_declaration.to_concrete x0') (k')
end
| _ -> fail l' "Pstr_include"
end
| _ -> fail l' "Pstr_include"
)
let pstr_attribute (T f0') =
T (fun c' l' x' k' ->
match Structure_item.to_concrete_opt x' with
| Some { pstr_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Structure_item_desc.to_concrete_opt x' with
| Some (Pstr_attribute (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Attribute.to_concrete x0') (k')
end
| _ -> fail l' "Pstr_attribute"
end
| _ -> fail l' "Pstr_attribute"
)
let pstr_extension (T f0') (T f1') =
T (fun c' l' x' k' ->
match Structure_item.to_concrete_opt x' with
| Some { pstr_desc = x'; _ } ->
c'.matched <- c'.matched + 1;
begin
match Structure_item_desc.to_concrete_opt x' with
| Some (Pstr_extension (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' (Attributes.to_concrete x1') (f0' c' l' (Extension.to_concrete x0') (k'))
end
| _ -> fail l' "Pstr_extension"
end
| _ -> fail l' "Pstr_extension"
)
let pstr_loc (T f') =
T (fun c' l' x' k' ->
match Structure_item.to_concrete_opt x' with
| Some { pstr_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "pstr_loc"
)
let pvb_attributes (T f') =
T (fun c' l' x' k' ->
match Value_binding.to_concrete_opt x' with
| Some { pvb_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "pvb_attributes"
)
let pvb_loc (T f') =
T (fun c' l' x' k' ->
match Value_binding.to_concrete_opt x' with
| Some { pvb_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "pvb_loc"
)
let pmb_attributes (T f') =
T (fun c' l' x' k' ->
match Module_binding.to_concrete_opt x' with
| Some { pmb_attributes = x'; _ } -> f' c' l' (Attributes.to_concrete x') k'
| _ -> fail l' "pmb_attributes"
)
let pmb_loc (T f') =
T (fun c' l' x' k' ->
match Module_binding.to_concrete_opt x' with
| Some { pmb_loc = x'; _ } -> f' c' l' x' k'
| _ -> fail l' "pmb_loc"
)
let ptop_def (T f0') =
T (fun c' l' x' k' ->
match Toplevel_phrase.to_concrete_opt x' with
| Some (Ptop_def (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' (Structure.to_concrete x0') (k')
end
| _ -> fail l' "Ptop_def"
)
let ptop_dir (T f0') (T f1') =
T (fun c' l' x' k' ->
match Toplevel_phrase.to_concrete_opt x' with
| Some (Ptop_dir (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Ptop_dir"
)
let pdir_string (T f0') =
T (fun c' l' x' k' ->
match Directive_argument.to_concrete_opt x' with
| Some (Pdir_string (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pdir_string"
)
let pdir_int (T f0') (T f1') =
T (fun c' l' x' k' ->
match Directive_argument.to_concrete_opt x' with
| Some (Pdir_int (x0', x1')) ->
begin
c'.matched <- c'.matched + 1;
f1' c' l' x1' (f0' c' l' x0' (k'))
end
| _ -> fail l' "Pdir_int"
)
let pdir_ident (T f0') =
T (fun c' l' x' k' ->
match Directive_argument.to_concrete_opt x' with
| Some (Pdir_ident (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pdir_ident"
)
let pdir_bool (T f0') =
T (fun c' l' x' k' ->
match Directive_argument.to_concrete_opt x' with
| Some (Pdir_bool (x0')) ->
begin
c'.matched <- c'.matched + 1;
f0' c' l' x0' (k')
end
| _ -> fail l' "Pdir_bool"
)
|
9bc2f3fae6937376ef017563c327b767b86ee1a5fb6de2fadb7b4eea199cc818 | dym/movitz | los-closette-compiler.lisp | ;;;;------------------------------------------------------------------
;;;;
Copyright ( C ) 2001 - 2005 ,
Department of Computer Science , University of Tromso , Norway .
;;;;
;;;; For distribution policy, see the accompanying file COPYING.
;;;;
Filename : los-closette-compiler.lisp
;;;; Description:
Author : < >
Created at : Thu Aug 29 13:15:11 2002
;;;;
$ I d : los - closette - compiler.lisp , v 1.23 2008 - 04 - 27 19:42:26 Exp $
;;;;
;;;;------------------------------------------------------------------
(provide :muerte/los-closette-compiler)
(in-package muerte)
(define-compile-time-variable *class-table*
(make-hash-table :test 'eq))
(define-compile-time-variable *eql-specializer-table*
(make-hash-table :test 'eql))
(define-compile-time-variable *the-slots-of-standard-class* nil)
(define-compile-time-variable *the-position-of-standard-effective-slots* nil)
(define-compile-time-variable *the-class-standard-class* nil)
(define-compile-time-variable *the-standard-method-combination* nil)
extends to EOF
(defvar *classes-with-old-slot-definitions* nil)
;; standard-class -> std-slotted-class -> class -> ..
(defconstant +the-defclasses-before-class+
'(progn
(defclass-los metaobject () ())
(defclass-los specializer (metaobject) ())
(defclass-los eql-specializer (specializer)
((object)))))
(defconstant +the-defclass-class+ ; class's defclass form
'(defclass-los class (specializer)
((name
:initarg name)
(class-precedence-list) ; :accessor class-precedence-list
: accessor class - direct - superclasses
:initarg :direct-superclasses)
(direct-subclasses ; :accessor class-direct-subclasses
:initform ())
(direct-methods
:initarg :direct-methods
:initform ())
(plist
:initform nil)
(prototype
:initform nil))))
(defconstant +the-defclass-std-slotted-class+
'(defclass-los std-slotted-class (class)
((effective-slots) ; :accessor class-slots
(direct-slots)))) ; :accessor class-direct-slots
(defconstant +the-defclasses-slots+
'(progn
(defclass-los slot-definition (metaobject) (name))
(defclass-los effective-slot-definition (slot-definition) ())
(defclass-los direct-slot-definition (slot-definition) ())
(defclass-los standard-slot-definition (slot-definition)
(type initform initfunction initargs allocation))
(defclass-los standard-effective-slot-definition (standard-slot-definition effective-slot-definition)
(location))))
(defconstant +the-defclass-standard-direct-slot-definition+
'(defclass-los standard-direct-slot-definition
(standard-slot-definition direct-slot-definition)
(position readers writers)))
(defconstant +the-defclass-instance-slotted-class+
'(defclass-los instance-slotted-class (class)
((instance-slots))))
(defconstant +the-defclass-standard-class+ ;standard-class's defclass form
'(defclass-los standard-class (instance-slotted-class std-slotted-class)
()))
(defmacro push-on-end (value location)
`(setf ,location (nconc ,location (list ,value))))
(defun mapappend (fun &rest args)
(declare (dynamic-extent args))
(if (some #'null args)
()
(append (apply fun (mapcar #'car args))
(apply #'mapappend fun (mapcar #'cdr args)))))
(defun make-direct-slot-definition (class-name
&key name (initargs ()) (initform nil) (initfunction nil)
(readers ()) (writers ()) (allocation :instance)
(type t)
documentation)
(declare (ignore documentation type)) ; for now
(cond
((movitz-find-class 'standard-direct-slot-definition nil)
(let ((slot (std-allocate-instance (movitz-find-class 'standard-direct-slot-definition))))
(setf (std-slot-value slot 'name) name
(std-slot-value slot 'initargs) initargs
(std-slot-value slot 'initform) initform
(std-slot-value slot 'initfunction) initfunction
(std-slot-value slot 'allocation) allocation
(std-slot-value slot 'readers) readers
(std-slot-value slot 'writers) writers)
slot))
(t (pushnew class-name *classes-with-old-slot-definitions*)
1
3
5
7
9
11
writers
nil)
:cl :muerte.cl))))
(defun translate-direct-slot-definition (old-slot)
(if (not (vectorp old-slot))
old-slot
(loop with slot = (std-allocate-instance (movitz-find-class 'standard-direct-slot-definition))
for slot-name in '(name initargs initform initfunction allocation readers writers)
as value across old-slot
do (setf (std-slot-value slot slot-name) value)
finally (return slot))))
(defun make-effective-slot-definition (class &key name (initargs ()) (initform nil) (initfunction nil)
(allocation :instance) location)
(cond
((movitz-find-class 'standard-effective-slot-definition nil)
(let ((slot (std-allocate-instance (movitz-find-class 'standard-effective-slot-definition))))
(setf (std-slot-value slot 'name) name
(std-slot-value slot 'initargs) initargs
(std-slot-value slot 'initform) initform
(std-slot-value slot 'initfunction) initfunction
(std-slot-value slot 'allocation) allocation
(std-slot-value slot 'location) location)
slot))
(t (pushnew class *classes-with-old-slot-definitions*)
(translate-program (vector name
initargs
initform
initfunction
allocation
nil nil
location)
:cl :muerte.cl))))
(defun translate-effective-slot-definition (old-slot)
(if (not (vectorp old-slot))
old-slot
(loop with slot = (std-allocate-instance (movitz-find-class 'standard-effective-slot-definition))
for slot-name in '(name initargs initform initfunction allocation nil nil location)
as value across old-slot
when slot-name
do (setf (std-slot-value slot slot-name) value)
finally (assert (integerp (std-slot-value slot 'location)) ()
"No location for ~S: ~S" slot (std-slot-value slot 'location))
finally (return slot))))
(defun slot-definition-name (slot)
(if (vectorp slot)
(svref slot 0)
(std-slot-value slot 'name)))
(defun (setf slot-definition-name) (new-value slot)
(setf (svref slot 0) new-value))
(defun slot-definition-initargs (slot)
(if (vectorp slot)
(svref slot 1)
(std-slot-value slot 'initargs)))
(defun (setf slot-definition-initargs) (new-value slot)
(setf (svref slot 1) new-value))
(defun slot-definition-initform (slot)
(if (vectorp slot)
(svref slot 2)
(std-slot-value slot 'initform)))
(defun (setf slot-definition-initform) (new-value slot)
(setf (svref slot 2) new-value))
(defun slot-definition-initfunction (slot)
(if (vectorp slot)
(svref slot 3)
(std-slot-value slot 'initfunction)))
(defun (setf slot-definition-initfunction) (new-value slot)
(setf (svref slot 3) new-value))
(defun slot-definition-allocation (slot)
(if (vectorp slot)
(svref slot 4)
(std-slot-value slot 'allocation)))
(defun (setf slot-definition-allocation) (new-value slot)
(setf (svref slot 4) new-value))
(defun instance-slot-p (slot)
(eq (slot-definition-allocation slot) :instance))
(defun slot-definition-readers (slot)
(if (vectorp slot)
(svref slot 5)
(std-slot-value slot 'readers)))
(defun (setf slot-definition-readers) (new-value slot)
(setf (svref slot 5) new-value))
(defun slot-definition-writers (slot)
(if (vectorp slot)
(svref slot 6)
(std-slot-value slot 'writers)))
(defun (setf slot-definition-writers) (new-value slot)
(setf (svref slot 6) new-value))
(defun slot-definition-location (slot)
(if (vectorp slot)
(svref slot 7)
(std-slot-value slot 'location)))
(defun (setf slot-definition-location) (new-value slot)
(check-type new-value integer)
(if (vectorp slot)
(setf (svref slot 7) new-value)
(setf (std-slot-value slot 'location) new-value)))
Defining the metaobject slot accessor function as regular functions
;;; greatly simplifies the implementation without removing functionality.
(defun movitz-class-name (class) (std-slot-value class 'name))
(defun (setf movitz-class-name) (new-value class)
(setf (movitz-slot-value class 'name) new-value))
(defun class-direct-superclasses (class)
(movitz-slot-value class 'direct-superclasses))
(defun (setf class-direct-superclasses) (new-value class)
(setf (movitz-slot-value class 'direct-superclasses) new-value))
(defun class-direct-slots (class)
(if (and (eq (movitz-class-of (movitz-class-of class)) *the-class-standard-class*)
(movitz-slot-exists-p class 'direct-slots))
(movitz-slot-value class 'direct-slots)
#+ignore (warn "no direct-slots for ~W" class)))
(defun (setf class-direct-slots) (new-value class)
(setf (movitz-slot-value class 'direct-slots) new-value))
(defun class-precedence-list (class)
(movitz-slot-value class 'class-precedence-list))
(defun (setf class-precedence-list) (new-value class)
(setf (movitz-slot-value class 'class-precedence-list) new-value))
(defun class-slots (class)
(movitz-slot-value class 'effective-slots))
(defun (setf class-slots) (new-value class)
(setf (movitz-slot-value class 'effective-slots) new-value))
(defun class-direct-subclasses (class)
(movitz-slot-value class 'direct-subclasses))
(defun (setf class-direct-subclasses) (new-value class)
(setf (movitz-slot-value class 'direct-subclasses) new-value))
(defun class-direct-methods (class)
(movitz-slot-value class 'direct-methods))
(defun (setf class-direct-methods) (new-value class)
(setf (movitz-slot-value class 'direct-methods) new-value))
;;; defclass
(defmacro defclass-los (name direct-superclasses direct-slots &rest options)
`(ensure-class ',name
:direct-superclasses
,(canonicalize-direct-superclasses direct-superclasses)
:direct-slots
,(canonicalize-direct-slots direct-slots name nil)
,@(canonicalize-defclass-options options nil name)))
(defun canonicalize-direct-slots (direct-slots class-name env)
`(list ,@(mapcar (lambda (ds) (canonicalize-direct-slot ds class-name env)) direct-slots)))
(defun canonicalize-direct-slot (spec class-name env)
(if (symbolp spec)
`(list :name ',spec)
(let ((name (car spec))
(initfunction nil)
(initform nil)
(initargs ())
(readers ())
(writers ())
(other-options ()))
(do ((olist (cdr spec) (cddr olist)))
((null olist))
(case (car olist)
(:initform
(let ((form (cadr olist)))
(setq initfunction
(if (movitz:movitz-constantp form env)
(list 'quote (list 'quote (movitz::eval-form form env)))
(compile-in-lexical-environment env
(muerte::translate-program
(list 'slot-initfunction
class-name name)
:cl :muerte.cl)
`(lambda () ,form))))
(setq initform `',form)))
(:initarg
(push-on-end (cadr olist) initargs))
(:reader
(push-on-end (cadr olist) readers))
(:writer
(push-on-end (cadr olist) writers))
(:accessor
(push-on-end (cadr olist) readers)
(push-on-end `(setf ,(cadr olist)) writers))
(otherwise
(push-on-end `',(car olist) other-options)
(push-on-end `',(cadr olist) other-options))))
`(list
:name ',name
,@(when initfunction
`(:initform ,initform :initfunction ,initfunction))
,@(when initargs `(:initargs ',initargs))
,@(when readers `(:readers ',readers))
,@(when writers `(:writers ',writers))
,@other-options))))
(defun canonicalize-direct-superclasses (direct-superclasses)
`(list ,@(mapcar #'canonicalize-direct-superclass direct-superclasses)))
(defun canonicalize-direct-superclass (class-name)
`(movitz-find-class ',class-name))
(defun intern-eql-specializer (object)
(or (gethash object *eql-specializer-table*)
(setf (gethash object *eql-specializer-table*)
(let ((s (std-allocate-instance (movitz-find-class 'eql-specializer))))
(setf (movitz-slot-value s 'object) object)
s))))
(defun canonicalize-defclass-options (options env class-name)
(mapcan (lambda (o) (canonicalize-defclass-option o env class-name)) options))
(defun canonicalize-defclass-option (option env class-name)
(case (car option)
((:metaclass)
(list ':metaclass
`(movitz-find-class ',(cadr option))))
((:default-initargs)
(list :default-initargs-function
(list 'quote
(cons (compile-in-lexical-environment
env (gensym (format nil "default-initargs-~A-" class-name))
`(lambda (o)
(case o
,@(loop for (arg val) on (cdr option) by #'cddr
collect `(,arg ,val)))))
(loop for arg in (cdr option) by #'cddr collect arg)))))
(t (list `',(car option) `',(cadr option)))))
;;; Class name-space accessors
(defun movitz-find-class (symbol &optional (errorp t))
(let ((symbol (muerte::translate-program symbol :cl :muerte.cl)))
(let ((class (gethash symbol *class-table*)))
(if (and (null class) errorp)
(error "Closette compiler: No LOS class named ~W." symbol)
class))))
(defun movitz-find-class-name (class)
(maphash (lambda (key value)
(when (eq value class)
(return-from movitz-find-class-name key)))
*class-table*))
(defun (setf movitz-find-class) (new-value symbol)
(let ((symbol (muerte::translate-program symbol :cl :muerte.cl)))
(if new-value
(setf (gethash symbol *class-table*) new-value)
(remhash symbol *class-table*)))
new-value)
(defun forget-all-classes ()
(clrhash *class-table*)
(values))
(defun find-specializer (name)
(cond
((symbolp name)
(movitz-find-class name))
((and (consp name)
(string= 'eql (car name)))
(intern-eql-specializer (movitz::eval-form (cadr name))))
(t (error "Unknown specializer: ~S" name))))
(defun specializer-name (specializer)
(if (eq (movitz-find-class 'eql-specializer)
(movitz-class-of specializer))
(translate-program (list 'eql (movitz-slot-value specializer 'object))
:cl :muerte.cl)
(movitz-class-name specializer)))
;;;
;; LOS standard-instance
(defun allocate-std-instance (class slots)
(movitz::make-movitz-std-instance class slots))
(defun std-instance-class (class)
(etypecase class
(movitz::movitz-std-instance
(movitz::movitz-std-instance-class class))
(movitz::movitz-funobj-standard-gf
(movitz::standard-gf-class class))))
(defun (setf std-instance-class) (value class)
(etypecase class
(movitz::movitz-std-instance
(setf (movitz::movitz-std-instance-class class) value))
(movitz::movitz-funobj-standard-gf
(setf (movitz::standard-gf-class class) value))))
(defun std-instance-slots (class)
(etypecase class
(movitz::movitz-std-instance
(movitz::movitz-std-instance-slots class))
(movitz::movitz-funobj-standard-gf
(movitz::standard-gf-slots class))))
(defun (setf std-instance-slots) (value class)
(etypecase class
(movitz::movitz-std-instance
(setf (movitz::movitz-std-instance-slots class) value))
(movitz::movitz-funobj-standard-gf
(setf (movitz::standard-gf-slots class) value))))
(defun std-allocate-instance (class)
(allocate-std-instance class (make-array (count-if #'instance-slot-p (class-slots class))
:initial-element (movitz::unbound-value))))
;; LOS standard-gf-instance
(defun allocate-std-gf-instance (class slots &rest init-args)
(apply #'movitz::make-standard-gf class slots init-args))
(defun std-allocate-gf-instance (class &rest init-args)
(apply #'allocate-std-gf-instance
class
(make-array (count-if #'instance-slot-p (class-slots class))
:initial-element (movitz::unbound-value))
init-args))
(defun std-gf-instance-class (class)
(movitz::standard-gf-class class))
(defun (setf std-gf-instance-class) (value class)
(setf (movitz::standard-gf-class class) value))
(defun std-gf-instance-slots (class)
(movitz::standard-gf-slots class))
(defun (setf std-gf-instance-slots) (value class)
(setf (movitz::standard-gf-slots class) value))
;;;
(defvar *slot-location-nesting* 0)
(defun slot-location (class slot-name)
(when (< 10 *slot-location-nesting*)
(break "Unbounded slot-location?"))
(let ((*slot-location-nesting* (1+ *slot-location-nesting*)))
(cond
((and (eq slot-name 'effective-slots)
(eq class *the-class-standard-class*))
(position 'effective-slots *the-slots-of-standard-class*
:key #'slot-definition-name))
((eq class (movitz-find-class 'standard-effective-slot-definition nil))
(or (position slot-name '(name type initform initfunction initargs allocation location))
(error "No slot ~S in ~S." slot-name (movitz-class-name class))))
(t #+ignore
(when (and (eq slot-name 'effective-slots)
(subclassp class *the-class-standard-class*))
(break "Looking for slot ~S in class ~S, while std-class is ~S."
slot-name class *the-class-standard-class*))
(let ((slot (find slot-name
(std-slot-value class 'effective-slots)
:key #'slot-definition-name)))
(if (null slot)
(error "Closette compiler: The slot ~S is missing from the class ~S."
slot-name class)
(let ((pos (position slot
(remove-if-not #'instance-slot-p
(std-slot-value class 'effective-slots)))))
(if (null pos)
(error "Closette compiler: The slot ~S is not an instance slot in the class ~S."
slot-name class)
pos))))))))
(defun movitz-class-of (instance)
(std-instance-class instance))
(defun subclassp (c1 c2)
(find c2 (class-precedence-list c1)))
(defun sub-specializer-p (c1 c2 c-arg)
(let ((cpl (class-precedence-list c-arg)))
(find c2 (cdr (member c1 cpl)))))
(defun std-slot-value (instance slot-name)
(let* ((slot-name (translate-program slot-name :cl :muerte.cl))
(location (slot-location (movitz-class-of instance) slot-name))
(slots (std-instance-slots instance))
(val (svref slots location)))
(if (eq (movitz::unbound-value) val)
(error "Closette compiler: The slot ~S at ~D is unbound in the object ~S."
slot-name location instance)
val)))
(defun (setf std-slot-value) (value instance slot-name)
(let* ((location (slot-location (movitz-class-of instance)
(translate-program slot-name :cl :muerte.cl)))
(slots (std-instance-slots instance)))
(setf (svref slots location) (muerte::translate-program value :cl :muerte.cl))))
(defun movitz-slot-value (object slot-name)
(std-slot-value object (translate-program slot-name :cl :muerte.cl)))
(defun (setf movitz-slot-value) (new-value object slot-name)
(setf (std-slot-value object (translate-program slot-name :cl :muerte.cl))
new-value))
(defun std-slot-exists-p (instance slot-name)
(not (null (find slot-name (class-slots (movitz-class-of instance))
:key #'slot-definition-name))))
(defun movitz-slot-exists-p (object slot-name)
(if (eq (movitz-class-of (movitz-class-of object)) *the-class-standard-class*)
(std-slot-exists-p object slot-name)
(error "Can't do this.")
#+ignore (movitz-slot-exists-p-using-class (movitz-class-of object)
object slot-name)))
;;;
;;; Ensure class
(defun ensure-class (name &rest all-keys &key (metaclass *the-class-standard-class*)
direct-slots direct-superclasses
&allow-other-keys)
(declare (dynamic-extent all-keys))
(remf all-keys :metaclass)
(let ((old-class (movitz-find-class name nil)))
(if (and old-class
(eq metaclass *the-class-standard-class*))
(std-after-initialization-for-classes old-class
:direct-slots direct-slots
:direct-superclasses direct-superclasses)
(let ((class (apply (cond
((eq metaclass *the-class-standard-class*)
'make-instance-standard-class)
((eq metaclass (movitz-find-class 'structure-class nil))
'make-instance-structure-class)
((eq metaclass (movitz-find-class 'built-in-class nil))
'make-instance-built-in-class)
((eq metaclass (movitz-find-class 'funcallable-standard-class nil))
'movitz-make-instance)
((eq metaclass (movitz-find-class 'run-time-context-class nil))
'movitz-make-instance)
((member *the-class-standard-class*
(class-precedence-list metaclass))
'make-instance-standard-class)
(t (break "Unknown metaclass: ~S" metaclass)
#+ignore 'make-instance-built-in-class
'movitz-make-instance))
metaclass
:name name
all-keys)))
(setf (movitz-find-class name) class)))))
(defun movitz-make-instance-funcallable (metaclass &rest all-keys &key name direct-superclasses direct-slots &allow-other-keys)
(declare (ignore all-keys))
(let ((class (std-allocate-instance metaclass)))
(setf (movitz-class-name class) name)
(setf (class-direct-subclasses class) ())
(setf (class-direct-methods class) ())
(std-after-initialization-for-classes class
:direct-slots direct-slots
:direct-superclasses direct-superclasses)
class))
(defun movitz-make-instance-run-time-context (metaclass &rest all-keys &key name direct-superclasses direct-slots size slot-map plist &allow-other-keys)
(declare (ignore all-keys))
(let ((class (std-allocate-instance metaclass)))
(setf (std-slot-value class 'size)
(or size (bt:sizeof 'movitz::movitz-run-time-context)))
(setf (std-slot-value class 'slot-map)
(or slot-map
(movitz::slot-map 'movitz::movitz-run-time-context
(cl:+ (bt:slot-offset 'movitz::movitz-run-time-context
'movitz::run-time-context-start)
0))))
(setf (std-slot-value class 'plist) plist)
(setf (movitz-class-name class) name)
(setf (class-direct-subclasses class) ())
(setf (class-direct-methods class) ())
(std-after-initialization-for-classes class
:direct-slots direct-slots
:direct-superclasses direct-superclasses)
class))
(defun movitz-make-instance (class &rest all-keys)
;; (warn "movitz-make-instance: ~S ~S" class all-keys)
(when (symbolp class)
(setf class (movitz-find-class class)))
(cond
((eq class (movitz-find-class 'funcallable-standard-class nil))
(apply 'movitz-make-instance-funcallable class all-keys) )
((eq class (movitz-find-class 'run-time-context-class nil))
(apply 'movitz-make-instance-run-time-context class all-keys))
(t (let ((instance (std-allocate-instance class)))
(dolist (slot (class-slots (movitz-class-of instance)))
(let ((slot-name (slot-definition-name slot)))
(multiple-value-bind (init-key init-value foundp)
(get-properties all-keys (slot-definition-initargs slot))
(declare (ignore init-key))
(when foundp
(setf (movitz-slot-value instance slot-name) init-value)))))
instance))))
;;; make-instance-standard-class creates and initializes an instance of
;;; standard-class without falling into method lookup. However, it cannot be
;;; called until standard-class itself exists.
(defun initialize-class-object (class &key name plist direct-methods
(direct-superclasses (list (movitz-find-class t)))
&allow-other-keys)
(setf (movitz-class-name class) name
(std-slot-value class 'plist) plist
(class-direct-subclasses class) ()
(class-direct-methods class) direct-methods)
(let ((supers direct-superclasses))
(setf (class-direct-superclasses class) supers)
(dolist (superclass supers)
(push class (class-direct-subclasses superclass))))
(setf (class-precedence-list class)
(std-compute-class-precedence-list class))
class)
(defun make-instance-structure-class (metaclass &rest all-keys
&key name slots direct-slots ((:metaclass dummy))
(direct-superclasses
(list (movitz-find-class 'structure-object))))
(declare (ignore dummy all-keys))
(assert (null direct-slots))
(let ((class (std-allocate-instance (if (symbolp metaclass)
(movitz-find-class metaclass)
metaclass))))
(setf (std-slot-value class 'slots) slots)
(initialize-class-object class :name name
:direct-superclasses direct-superclasses)))
(defun make-instance-built-in-class (metaclass &rest all-keys
&key name direct-superclasses
direct-methods direct-slots plist size slot-map
&allow-other-keys)
(declare (ignore plist direct-methods direct-slots direct-superclasses name))
;;; (assert (null direct-slots) (direct-slots)
;;; "Closette compiler: This class can't have slots: ~S" direct-slots)
(let ((class (std-allocate-instance (if (symbolp metaclass)
(movitz-find-class metaclass)
metaclass))))
(when size (setf (std-slot-value class 'size) size))
(setf (std-slot-value class 'slot-map) slot-map)
(apply #'initialize-class-object class all-keys)))
(defun make-instance-standard-class (metaclass &key name direct-superclasses direct-slots
default-initargs-function
documentation)
(declare (ignore metaclass documentation))
(let ((class (std-allocate-instance metaclass)))
(setf (movitz-class-name class) name)
(setf (class-direct-subclasses class) ())
(setf (class-direct-methods class) ())
(setf (movitz-slot-value class 'prototype) ())
(setf (movitz-slot-value class 'plist)
(when default-initargs-function
(list :default-initargs-function default-initargs-function)))
(dolist (slot (class-slots (movitz-class-of class)))
(let ((slot-name (slot-definition-name slot))
(slot-initform (muerte::translate-program (slot-definition-initform slot)
'#:muerte.cl '#:cl)))
(when slot-initform
(setf (movitz-slot-value class slot-name) (movitz::eval-form slot-initform)))))
(std-after-initialization-for-classes class
:direct-slots direct-slots
:direct-superclasses direct-superclasses)
class))
(defun std-after-initialization-for-classes (class &key direct-superclasses direct-slots)
(let ((supers (or direct-superclasses
(list (movitz-find-class 'standard-object)))))
(setf (class-direct-superclasses class) supers)
(dolist (superclass supers)
(pushnew class (class-direct-subclasses superclass))))
(let ((slots (mapcar #'(lambda (slot-properties)
(apply #'make-direct-slot-definition
(movitz-class-name class)
slot-properties))
direct-slots)))
(setf (class-direct-slots class) slots)
(dolist (direct-slot slots)
(dolist (reader (slot-definition-readers direct-slot))
(add-reader-method
class reader (slot-definition-name direct-slot)))
(dolist (writer (slot-definition-writers direct-slot))
(add-writer-method
class writer (slot-definition-name direct-slot)))))
(funcall (if (or (eq (movitz-class-of class)
*the-class-standard-class*)
(subclassp (movitz-class-of class)
(movitz-find-class 'std-slotted-class)))
#'std-finalize-inheritance
#'finalize-inheritance)
class)
(values))
;;; finalize-inheritance
(defun std-finalize-inheritance (class)
(setf (class-precedence-list class)
(funcall (if (or (eq (movitz-class-of class) *the-class-standard-class*)
(subclassp (movitz-class-of class) (movitz-find-class 'std-slotted-class)))
#'std-compute-class-precedence-list
#'compute-class-precedence-list)
class))
(setf (class-slots class)
(funcall (if (or (eq (movitz-class-of class) *the-class-standard-class*)
(subclassp (movitz-class-of class) (movitz-find-class 'std-slotted-class)))
#'std-compute-slots
#'compute-slots)
class))
(values))
(defun finalize-inheritance (class)
(error "Don't know how to finalize-inheritance for class ~S of class ~S."
class (class-of class)))
;;; Class precedence lists
(defun std-compute-class-precedence-list (class)
(let ((classes-to-order (collect-superclasses* class)))
;;; (warn "class: ~W" class)
;;; (warn "classes-to-order: ~W" classes-to-order)
(topological-sort classes-to-order
(remove-duplicates
(mapappend #'local-precedence-ordering
classes-to-order)
:test #'equal)
#'std-tie-breaker-rule)))
(defun compute-class-precedence-list (class)
(error "Don't know how to compute class-precedence-list for ~S of class ~S."
class (class-of class)))
;;; topological-sort implements the standard algorithm for topologically
;;; sorting an arbitrary set of elements while honoring the precedence
;;; constraints given by a set of (X,Y) pairs that indicate that element
;;; X must precede element Y. The tie-breaker procedure is called when it
;;; is necessary to choose from multiple minimal elements; both a list of
;;; candidates and the ordering so far are provided as arguments.
(defun topological-sort (elements constraints tie-breaker)
;; (warn "topological-sort:~% ~W~% ~W~% ~W" elements constraints tie-breaker)
(let ((remaining-constraints constraints)
(remaining-elements elements)
(result ()))
(loop
(let ((minimal-elements
(remove-if #'(lambda (class)
(member class remaining-constraints
:key #'cadr))
remaining-elements)))
(when (null minimal-elements)
(if (null remaining-elements)
(return-from topological-sort result)
(error "Closette compiler: Inconsistent precedence graph.")))
(let ((choice (if (null (cdr minimal-elements))
(car minimal-elements)
(funcall tie-breaker
minimal-elements
result))))
(setq result (append result (list choice)))
(setq remaining-elements
(remove choice remaining-elements))
(setq remaining-constraints
(remove choice
remaining-constraints
:test #'member)))))))
;;; In the event of a tie while topologically sorting class precedence lists,
the CLOS Specification says to " select the one that has a direct subclass
;;; rightmost in the class precedence list computed so far." The same result
;;; is obtained by inspecting the partially constructed class precedence list
from right to left , looking for the first minimal element to show up among
the direct superclasses of the class precedence list constituent .
;;; (There's a lemma that shows that this rule yields a unique result.)
(defun std-tie-breaker-rule (minimal-elements cpl-so-far)
(dolist (cpl-constituent (reverse cpl-so-far))
(let* ((supers (class-direct-superclasses cpl-constituent))
(common (intersection minimal-elements supers)))
(when (not (null common))
(return-from std-tie-breaker-rule (car common))))))
;;; This version of collect-superclasses* isn't bothered by cycles in the class
;;; hierarchy, which sometimes happen by accident.
(defun collect-superclasses* (class)
(labels ((all-superclasses-loop (seen superclasses)
(let ((to-be-processed (set-difference superclasses seen)))
(if (null to-be-processed)
superclasses
(let ((class-to-process (car to-be-processed)))
(all-superclasses-loop (cons class-to-process seen)
(union (class-direct-superclasses class-to-process)
superclasses)))))))
(all-superclasses-loop () (list class))))
The local precedence ordering of a class C with direct superclasses C_1 ,
;;; C_2, ..., C_n is the set ((C C_1) (C_1 C_2) ...(C_n-1 C_n)).
(defun local-precedence-ordering (class)
(mapcar #'list
(cons class
(butlast (class-direct-superclasses class)))
(class-direct-superclasses class)))
;;; Slot inheritance
(defun std-compute-slots (class)
(let* ((all-slots (mapcan (lambda (c)
(copy-list (class-direct-slots c)))
(reverse (class-precedence-list class))))
(all-names (remove-duplicates (mapcar #'slot-definition-name all-slots)))
(effective-slots (mapcar #'(lambda (name)
(funcall (if (or (eq (movitz-class-of class)
*the-class-standard-class*)
(subclassp (movitz-class-of class)
(movitz-find-class 'std-slotted-class)))
#'std-compute-effective-slot-definition
#'compute-effective-slot-definition)
class
name
(remove name all-slots
:key #'slot-definition-name
:test (complement #'eq))))
all-names)))
(loop for i upfrom 0 as slot in effective-slots
do (setf (slot-definition-location slot) i))
effective-slots))
(defun compute-slots (class)
(error "Don't know how to compute-slots for class ~S of class ~S."
class (class-of class)))
(defun std-compute-effective-slot-definition (class name direct-slots)
(declare (ignore name))
(let ((initer (find-if-not #'null direct-slots
:key #'slot-definition-initfunction)))
(make-effective-slot-definition (movitz-class-name class)
:name (slot-definition-name (car direct-slots))
:initform (if initer
(slot-definition-initform initer)
nil)
:initfunction (if initer
(slot-definition-initfunction initer)
nil)
:initargs (remove-duplicates
(mapappend #'slot-definition-initargs
direct-slots))
:allocation (slot-definition-allocation (car direct-slots)))))
(defun compute-effective-slot-definition (class name direct-slots)
(declare (ignore name direct-slots))
(error "Don't know how to compute-effective-slot-definition for class ~S of class ~S."
class (class-of class)))
;;;;
;;;
Generic function metaobjects and standard - generic - function
;;;
(defun generic-function-name (gf)
(slot-value gf 'movitz::name)
#+ignore (movitz-slot-value gf 'name))
(defun (setf generic-function-name) (new-value gf)
(setf (slot-value gf 'movitz::name) new-value))
(defun generic-function-lambda-list (gf)
(slot-value gf 'movitz::lambda-list)
#+ignore (movitz-slot-value gf 'lambda-list))
(defun (setf generic-function-lambda-list) (new-value gf)
(setf (slot-value gf 'movitz::lambda-list)
new-value))
(defun generic-function-methods (gf)
(movitz-slot-value gf 'methods))
(defun (setf generic-function-methods) (new-value gf)
(setf (movitz-slot-value gf 'methods) new-value))
(defun generic-function-method-combination (gf)
(movitz-slot-value gf 'method-combination))
(defun (setf generic-function-method-combination) (new-value gf)
(setf (movitz-slot-value gf 'method-combination) new-value))
(defun generic-function-discriminating-function (gf)
(slot-value gf 'movitz::standard-gf-function))
(defun (setf generic-function-discriminating-function) (new-value gf)
(setf (slot-value gf 'movitz::standard-gf-function) new-value))
(defun generic-function-method-class (gf)
(movitz-slot-value gf 'method-class))
(defun (setf generic-function-method-class) (new-value gf)
(setf (movitz-slot-value gf 'method-class) new-value))
;;; accessor for effective method function table
(defun classes-to-emf-table (gf)
(slot-value gf 'movitz::classes-to-emf-table)
#+ignore (movitz-slot-value gf 'classes-to-emf-table))
(defun (setf classes-to-emf-table) (new-value gf)
(setf (slot-value gf 'movitz::classes-to-emf-table) new-value)
#+ignore (setf (movitz-slot-value gf 'classes-to-emf-table) new-value))
(defun num-required-arguments (gf)
(slot-value gf 'movitz::num-required-arguments))
;;;
;;; Method metaobjects and standard-method
;;;
( defvar * the - class - standard - method * ) ; standard - method 's class metaobject
(defun method-lambda-list (method)
(movitz-slot-value method 'lambda-list))
(defun (setf method-lambda-list) (new-value method)
(setf (movitz-slot-value method 'lambda-list) new-value))
(defun movitz-method-qualifiers (method)
(movitz-slot-value method 'qualifiers))
(defun (setf movitz-method-qualifiers) (new-value method)
(setf (movitz-slot-value method 'qualifiers) new-value))
(defun method-specializers (method)
(movitz-slot-value method 'specializers))
(defun (setf method-specializers) (new-value method)
(setf (movitz-slot-value method 'specializers) new-value))
(defun method-body (method)
(movitz-slot-value method 'body))
(defun (setf method-body) (new-value method)
(setf (movitz-slot-value method 'body) new-value))
(defun method-declarations (method)
(movitz-slot-value method 'declarations))
(defun (setf method-declarations) (new-value method)
(setf (movitz-slot-value method 'declarations) new-value))
(defun method-environment (method)
(movitz-slot-value method 'environment))
(defun (setf method-environment) (new-value method)
(setf (movitz-slot-value method 'environment) new-value))
(defun method-generic-function (method)
(movitz-slot-value method 'generic-function))
(defun (setf method-generic-function) (new-value method)
(setf (movitz-slot-value method 'generic-function) new-value))
(defun method-function (method) (movitz-slot-value method 'function))
(defun (setf method-function) (new-value method)
(setf (movitz-slot-value method 'function) new-value))
(defun method-optional-arguments-p (method) (movitz-slot-value method 'optional-arguments-p))
(defun (setf method-optional-arguments-p) (new-value method)
(setf (movitz-slot-value method 'optional-arguments-p) new-value))
;;; defgeneric
(defmacro movitz-defgeneric (function-name lambda-list &rest options)
`(movitz-ensure-generic-function ',function-name
:lambda-list ',lambda-list
,@(canonicalize-defgeneric-options options)))
(defun canonicalize-defgeneric-options (options)
(mapappend #'canonicalize-defgeneric-option options))
(defun canonicalize-defgeneric-option (option)
(case (car option)
(declare nil)
(:generic-function-class
(list ':generic-function-class
`(movitz-find-class ',(cadr option))))
(:method-class
(list ':method-class
`(movitz-find-class ',(cadr option))))
(:method nil)
(t (list `',(car option) `',(cadr option)))))
;;; ensure-generic-function
(defun movitz-ensure-generic-function (function-name &rest all-keys
&key (generic-function-class (movitz-find-class 'standard-generic-function))
lambda-list (no-clos-fallback nil ncf-p)
(method-class (movitz-find-class 'standard-method))
&allow-other-keys)
(declare (dynamic-extent all-keys))
(let ((function-name (muerte::translate-program function-name :cl :muerte.cl))
(remove-old-p nil))
(let ((gf (movitz::movitz-env-named-function function-name)))
(with-simple-restart (nil "Remove the old definition for ~S." function-name)
(when gf
(assert (typep gf 'movitz::movitz-funobj-standard-gf) ()
"There is already a non-generic function-definition for ~S of type ~S."
function-name (type-of gf))
(assert (= (length (getf (analyze-lambda-list lambda-list)
:required-args))
(num-required-arguments gf))
() "The lambda-list ~S doesn't match the old generic function's lambda-list ~S."
lambda-list (generic-function-lambda-list gf))))
(when (and gf (or (not (typep gf 'movitz::movitz-funobj-standard-gf))
(not (= (length (getf (analyze-lambda-list lambda-list)
:required-args))
(num-required-arguments gf)))))
(setf remove-old-p t)))
(let ((gf (or (and (not remove-old-p)
(movitz::movitz-env-named-function function-name))
(let ((gf (apply (if (eq generic-function-class
(movitz-find-class 'standard-generic-function))
#'make-instance-standard-generic-function
#'movitz-make-instance)
generic-function-class
:name function-name
:method-class method-class
(muerte::translate-program all-keys :cl :muerte.cl))))
(setf (movitz::movitz-env-named-function function-name) gf)
gf))))
(when ncf-p
(setf (getf (slot-value gf 'movitz::plist) :no-clos-fallback)
no-clos-fallback)
(finalize-generic-function gf))
gf)))
;;; finalize-generic-function
;;; N.B. Same basic idea as finalize-inheritance. Takes care of recomputing
;;; and storing the discriminating function, and clearing the effective method
;;; function table.
(defun finalize-generic-function (gf)
(setf (movitz::movitz-env-named-function (generic-function-name gf)) gf)
(setf (classes-to-emf-table gf) nil)
(setf (movitz::standard-gf-function gf)
'initial-discriminating-function)
(let ((ncf (getf (slot-value gf 'movitz::plist) :no-clos-fallback)))
(cond
((not ncf))
((member ncf '(:unspecialized-method t))
(let ((m (find-if (lambda (method)
(every (lambda (specializer)
(eq specializer
(movitz-find-class t)))
(method-specializers method)))
(generic-function-methods gf))))
(setf (classes-to-emf-table gf)
(if m (method-function m) 'no-unspecialized-fallback))))
((symbolp ncf)
(setf (classes-to-emf-table gf)
ncf))
((and (listp ncf) (eq 'muerte.cl:setf (car ncf)))
(setf (classes-to-emf-table gf)
(movitz::movitz-env-setf-operator-name (cadr ncf))))
(t (error "Unknown ncf."))))
#+ignore
(let ((eql-specializer-table (or (slot-value gf 'movitz::eql-specializer-table)
(make-hash-table :test #'eql))))
(clrhash eql-specializer-table)
(dolist (method (generic-function-methods gf))
(dolist (specializer (method-specializers method))
(when (eq (movitz-find-class 'eql-specializer)
(movitz-class-of specializer))
(setf (gethash (movitz-slot-value specializer 'object)
eql-specializer-table)
specializer))))
(setf (slot-value gf 'movitz::eql-specializer-table)
(if (plusp (hash-table-count eql-specializer-table))
eql-specializer-table
nil)))
(values))
;;; make-instance-standard-generic-function creates and initializes an
;;; instance of standard-generic-function without falling into method lookup.
;;; However, it cannot be called until standard-generic-function exists.
(defun make-instance-standard-generic-function (generic-function-class
&key name lambda-list method-class method-combination
no-clos-fallback
documentation)
(declare (ignore documentation no-clos-fallback method-combination))
(assert (not (null lambda-list)) (lambda-list)
"Can't make a generic function with nil lambda-list.")
(let ((gf (std-allocate-gf-instance generic-function-class
:name name
:lambda-list lambda-list
:num-required-arguments
(length (getf (analyze-lambda-list lambda-list)
:required-args)))))
(setf (generic-function-name gf) name
(generic-function-lambda-list gf) lambda-list
(generic-function-methods gf) ()
(generic-function-method-class gf) method-class
(generic-function-method-combination gf) *the-standard-method-combination*)
(finalize-generic-function gf)
gf))
;;; defmethod
(defmacro movitz-defmethod (&rest args)
(multiple-value-bind (function-name qualifiers lambda-list specializers body declarations documentation)
(parse-defmethod args)
(declare (ignore documentation declarations body))
`(ensure-method (movitz::movitz-env-named-function ',function-name)
:lambda-list ',lambda-list
:qualifiers ',qualifiers
:specializers ,(canonicalize-specializers specializers)
;; :body ',body
;; :declarations ',declarations
;; :environment ,env)))
)))
(defun canonicalize-specializers (specializers)
`(list ,@(mapcar #'canonicalize-specializer specializers)))
(defun canonicalize-specializer (specializer)
`(find-specializer ',specializer))
(defun parse-defmethod (args)
(let ((fn-spec (car args))
(qualifiers ())
(specialized-lambda-list nil)
(decl-doc-body ())
(parse-state :qualifiers))
(dolist (arg (cdr args))
(ecase parse-state
(:qualifiers
(if (and (atom arg) (not (null arg)))
(push-on-end arg qualifiers)
(progn (setq specialized-lambda-list arg)
(setq parse-state :body))))
(:body (push-on-end arg decl-doc-body))))
(multiple-value-bind (body declarations documentation)
(movitz::parse-docstring-declarations-and-body decl-doc-body 'cl:declare)
(values fn-spec
qualifiers
(extract-lambda-list specialized-lambda-list)
(extract-specializers specialized-lambda-list)
(list* 'block
(if (consp fn-spec)
(cadr fn-spec)
fn-spec)
body)
declarations
documentation))))
;;; Several tedious functions for analyzing lambda lists
(defun required-portion (gf args)
(let ((number-required (length (gf-required-arglist gf))))
(when (< (length args) number-required)
(error "Closette compiler: Too few arguments to generic function ~S." gf))
(subseq args 0 number-required)))
(defun gf-required-arglist (gf)
(let ((plist (analyze-lambda-list (generic-function-lambda-list gf))))
(getf plist ':required-args)))
(defun extract-lambda-list (specialized-lambda-list)
(let* ((plist (analyze-lambda-list specialized-lambda-list))
(requireds (getf plist ':required-names))
(rv (getf plist ':rest-var))
(ks (getf plist ':key-args))
(aok (getf plist ':allow-other-keys))
(opts (getf plist ':optional-args))
(auxs (getf plist ':auxiliary-args)))
`(,@requireds
,@(if rv `(&rest ,rv) ())
,@(if (or ks aok) `(&key ,@ks) ())
,@(if aok '(&allow-other-keys) ())
,@(if opts `(&optional ,@opts) ())
,@(if auxs `(&aux ,@auxs) ()))))
(defun extract-specializers (specialized-lambda-list)
(let ((plist (analyze-lambda-list specialized-lambda-list)))
(getf plist ':specializers)))
(defun analyze-lambda-list (lambda-list)
(labels ((make-keyword (symbol)
(intern (symbol-name symbol)
(find-package 'keyword)))
(get-keyword-from-arg (arg)
(if (listp arg)
(if (listp (car arg))
(caar arg)
(make-keyword (car arg)))
(make-keyword arg))))
(let ((keys ()) ; Just the keywords
Keywords argument specs
(required-names ()) ; Just the variable names
(required-args ()) ; Variable names & specializers
(specializers ()) ; Just the specializers
(rest-var nil)
(optionals ())
(auxs ())
(allow-other-keys nil)
(state :parsing-required))
(dolist (arg (translate-program lambda-list :muerte.cl :cl))
(if (member arg lambda-list-keywords)
(ecase arg
(&optional
(setq state :parsing-optional))
(&rest
(setq state :parsing-rest))
(&key
(setq state :parsing-key))
(&allow-other-keys
(setq allow-other-keys 't))
(&aux
(setq state :parsing-aux)))
(case state
(:parsing-required
(push-on-end arg required-args)
(if (listp arg)
(progn (push-on-end (car arg) required-names)
(push-on-end (cadr arg) specializers))
(progn (push-on-end arg required-names)
(push-on-end 't specializers))))
(:parsing-optional (push-on-end arg optionals))
(:parsing-rest (setq rest-var arg))
(:parsing-key
(push-on-end (get-keyword-from-arg arg) keys)
(push-on-end arg key-args))
(:parsing-aux (push-on-end arg auxs)))))
(translate-program (list :required-names required-names
:required-args required-args
:specializers specializers
:rest-var rest-var
:keywords keys
:key-args key-args
:auxiliary-args auxs
:optional-args optionals
:allow-other-keys allow-other-keys)
:cl :muerte.cl))))
;;; ensure method
(defun ensure-method (gf &rest all-keys &key lambda-list &allow-other-keys)
(declare (dynamic-extent all-keys))
(assert (= (length (getf (analyze-lambda-list lambda-list)
:required-args))
(num-required-arguments gf))
() "The method's lambda-list ~S doesn't match the gf's lambda-list ~S."
lambda-list (generic-function-lambda-list gf))
(let ((new-method (apply (if (eq (generic-function-method-class gf)
(movitz-find-class 'standard-method))
#'make-instance-standard-method
#'make-instance)
gf
:name (generic-function-name gf)
all-keys)))
(movitz-add-method gf new-method)
new-method))
;;; make-instance-standard-method creates and initializes an instance of
;;; standard-method without falling into method lookup. However, it cannot
;;; be called until standard-method exists.
(defun make-instance-standard-method (gf &key (method-class 'standard-method) name lambda-list qualifiers
specializers body declarations environment slot-definition)
(let ((method (std-allocate-instance (movitz-find-class method-class))))
(setf ;; (method-lambda-list method) lambda-list
(movitz-method-qualifiers method) qualifiers
(method-specializers method) specializers
;;; (method-body method) body
;;; (method-declarations method) declarations
(method-generic-function method) nil
(method-optional-arguments-p method) (let ((analysis (analyze-lambda-list lambda-list)))
(if (or (getf analysis :optional-args)
(getf analysis :key-args)
(getf analysis :rest-var))
t nil))
(method-function method) (std-compute-method-function method name gf environment
lambda-list declarations body))
(when slot-definition
(setf (movitz-slot-value method 'slot-definition) slot-definition))
method))
;;; add-method
;;; N.B. This version first removes any existing method on the generic function
with the same qualifiers and specializers . It 's a pain to develop
programs without this feature of full CLOS .
(defun movitz-add-method (gf method)
(let ((old-method (movitz-find-method gf (movitz-method-qualifiers method)
(method-specializers method) nil)))
(when old-method (movitz-remove-method gf old-method)))
(setf (method-generic-function method) gf)
(push method (generic-function-methods gf))
(dolist (specializer (method-specializers method))
(when (subclassp (movitz-class-of specializer) (movitz-find-class 'class))
(pushnew method (class-direct-methods specializer))))
(finalize-generic-function gf)
method)
(defun movitz-remove-method (gf method)
(setf (generic-function-methods gf)
(remove method (generic-function-methods gf)))
(setf (method-generic-function method) nil)
(dolist (specializer (method-specializers method))
(when (subclassp (movitz-class-of specializer) (movitz-find-class 'class))
(setf (class-direct-methods specializer)
(remove method (class-direct-methods specializer)))))
(finalize-generic-function gf)
method)
(defun movitz-find-method (gf qualifiers specializers &optional (errorp t))
(let ((method (find-if (lambda (method)
(and (equal qualifiers
(movitz-method-qualifiers method))
(equal specializers
(method-specializers method))))
(generic-function-methods gf))))
(if (and (null method) errorp)
(error "Closette compiler: No method for ~S matching ~S~@[ qualifiers ~S~]."
(generic-function-name gf)
specializers
qualifiers)
method)))
;;; Reader and write methods
(defun add-reader-method (class fn-name slot-name)
(ensure-method (movitz-ensure-generic-function fn-name :lambda-list '(object))
:method-class 'standard-reader-method
:slot-definition (find slot-name (std-slot-value class 'direct-slots)
:key 'slot-definition-name)
:lambda-list '(object)
:qualifiers ()
:specializers (list class)
:body `(slot-value object ',slot-name) ; this is LOS code!
:environment (top-level-environment))
(values))
(defun add-writer-method (class fn-name slot-name)
(ensure-method (movitz-ensure-generic-function fn-name :lambda-list '(new-value object))
:method-class 'standard-writer-method
:lambda-list '(new-value object)
:slot-definition (find slot-name (std-slot-value class 'direct-slots)
:key 'slot-definition-name)
:qualifiers ()
:specializers (list (movitz-find-class 't) class)
:body `(setf (slot-value object ',slot-name) ; this is LOS code!
new-value)
:environment (top-level-environment))
(values))
;;;
Generic function invocation
;;;
;;; apply-generic-function
(defun apply-generic-function (gf args)
(apply (generic-function-discriminating-function gf) args))
;;; compute-discriminating-function
(defun std-compute-discriminating-function (gf)
(declare (ignore gf))
'discriminating-function
#+ignore
(movitz::make-compiled-funobj 'discriminating-function
(muerte::translate-program
'(&edx gf &rest args) :cl :muerte.cl)
(muerte::translate-program
'((dynamic-extent args)) :cl :muerte.cl)
(muerte::translate-program
`(apply #'std-discriminating-function gf args args)
#+ignore
`(let* ((requireds (subseq args 0 (length (gf-required-arglist ,gf))))
(classes (map-into requireds #'class-of requireds))
(emfun (gethash classes (classes-to-emf-table ,gf) nil)))
(if emfun
(funcall emfun args)
(slow-method-lookup ,gf args classes)))
#+ignore
`(let ((requireds (subseq args 0 (length (gf-required-arglist ,gf)))))
(slow-method-lookup ,gf args (map-into requireds #'class-of requireds)))
:cl :muerte.cl)
nil nil))
(defun slow-method-lookup (gf args classes)
(let* ((applicable-methods (compute-applicable-methods-using-classes gf classes))
(emfun (funcall (if (eq (movitz-class-of gf) (movitz-find-class 'standard-generic-function))
#'std-compute-effective-method-function
#'compute-effective-method-function)
gf applicable-methods)))
(setf (gethash classes (classes-to-emf-table gf)) emfun)
(funcall emfun args)))
;;; compute-applicable-methods-using-classes
(defun compute-applicable-methods-using-classes (gf required-classes)
(sort (copy-list (remove-if-not #'(lambda (method)
(every #'subclassp
required-classes
(method-specializers method)))
(generic-function-methods gf)))
(lambda (m1 m2)
(funcall (if (eq (movitz-class-of gf) (movitz-find-class 'standard-generic-function))
#'std-method-more-specific-p
#'method-more-specific-p)
gf m1 m2 required-classes))))
;;; method-more-specific-p
(defun std-method-more-specific-p (gf method1 method2 required-classes)
"When applying arguments of <required-classes> to <gf>, which of <method1>
and <method2> is more specific?"
(declare (ignore gf))
# + movitz ( loop
for spec1 in ( method - specializers method1 )
;;; for spec2 in (method-specializers method2)
;;; for arg-class in required-classes
;;; do (unless (eq spec1 spec2)
;;; (return-from std-method-more-specific-p
;;; (sub-specializer-p spec1 spec2 arg-class))))
(mapc #'(lambda (spec1 spec2 arg-class)
(unless (eq spec1 spec2)
(return-from std-method-more-specific-p
(sub-specializer-p spec1 spec2 arg-class))))
(method-specializers method1)
(method-specializers method2)
required-classes)
nil)
;;; apply-methods and compute-effective-method-function
#+ignore
(defun apply-methods (gf args methods)
(funcall (compute-effective-method-function gf methods)
args))
(defun primary-method-p (method)
(null (movitz-method-qualifiers method)))
(defun before-method-p (method)
(equal '(:before) (movitz-method-qualifiers method)))
(defun after-method-p (method)
(equal '(:after) (movitz-method-qualifiers method)))
(defun around-method-p (method)
(equal '(:around) (movitz-method-qualifiers method)))
#+ignore
(defun std-compute-effective-method-function (gf methods)
(let ((primaries (remove-if-not #'primary-method-p methods))
(around (find-if #'around-method-p methods)))
(when (null primaries)
(error "Closette compiler: No primary methods for the generic function ~S." gf))
(if around
(let ((next-emfun (funcall (if (eq (movitz-class-of gf) (movitz-find-class 'standard-generic-function))
#'std-compute-effective-method-function
#'compute-effective-method-function)
gf (remove around methods))))
`(lambda (args)
(funcall (method-function ,around) args ,next-emfun)))
(let ((next-emfun (compute-primary-emfun (cdr primaries)))
(befores (remove-if-not #'before-method-p methods))
(reverse-afters
(reverse (remove-if-not #'after-method-p methods))))
`(lambda (args)
(dolist (before ',befores)
(funcall (method-function before) args nil))
(multiple-value-prog1
(funcall (method-function ,(car primaries)) args ,next-emfun)
(dolist (after ',reverse-afters)
(funcall (method-function after) args nil))))))))
;;; compute an effective method function from a list of primary methods:
#+ignore
(defun compute-primary-emfun (methods)
(if (null methods)
nil
(let ((next-emfun (compute-primary-emfun (cdr methods))))
'(lambda (args)
(funcall (method-function (car methods)) args next-emfun)))))
;;; apply-method and compute-method-function
#+ignore
(defun apply-method (method args next-methods)
(funcall (method-function method)
args
(if (null next-methods)
nil
(compute-effective-method-function
(method-generic-function method) next-methods))))
(defun std-compute-method-function (method name gf env lambda-list declarations body)
(let* ((block-name (compute-function-block-name name))
(analysis (analyze-lambda-list lambda-list))
(lambda-variables (append (getf analysis :required-args)
(mapcar #'decode-optional-formal
(getf analysis :optional-args))
(mapcar #'decode-keyword-formal
(getf analysis :key-args))
(when (getf analysis :rest-var)
(list (getf analysis :rest-var)))))
(required-variables (subseq lambda-variables
0 (num-required-arguments gf)))
(funobj
(compile-in-lexical-environment
env
(translate-program (nconc (list 'method name)
(copy-list (movitz-method-qualifiers method))
(list (mapcar #'specializer-name (method-specializers method))))
:cl :muerte.cl)
(if (movitz::tree-search body '(call-next-method next-method-p))
`(lambda ,lambda-list
(declare (ignorable ,@required-variables)
,@(mapcan (lambda (declaration)
(case (car declaration)
(dynamic-extent
(list declaration))
(ignore
(list (cons 'ignorable (cdr declaration))))))
declarations))
(let ((next-emf 'proto-next-emf))
;; We must capture the value of the dynamic *next-methods*
(declare (ignorable next-emf))
;; this is an ugly hack so next-emf wont be a constant-binding..
(setf next-emf 'proto-next-emf)
(flet ((call-next-method (&rest cnm-args)
(declare (dynamic-extent cnm-args))
;; XXX &key args not handled.
(if (not (functionp next-emf))
(if cnm-args
(apply 'no-next-method ,gf ,method cnm-args)
(no-next-method ,gf ,method ,@lambda-variables))
(if cnm-args
(apply next-emf cnm-args)
(funcall next-emf ,@lambda-variables)))))
(declare (ignorable call-next-method))
(block ,block-name
(let ,(mapcar #'list lambda-variables lambda-variables)
(declare (ignorable ,@required-variables)
,@declarations)
,body)))))
`(lambda ,lambda-list
(declare (ignorable ,@required-variables)
,@declarations)
(block ,block-name
,body))))))
(setf (slot-value funobj 'movitz::funobj-type) :method-function)
funobj))
;;; N.B. The function kludge-arglist is used to pave over the differences
;;; between argument keyword compatibility for regular functions versus
;;; generic functions.
(defun kludge-arglist (lambda-list)
(if (and (member '&key lambda-list)
(not (member '&allow-other-keys lambda-list)))
(append lambda-list '(&allow-other-keys))
(if (and (not (member '&rest lambda-list))
(not (member '&key lambda-list)))
(append lambda-list '(&key &allow-other-keys))
lambda-list)))
;;; Run-time environment hacking (Common Lisp ain't got 'em).
(defun top-level-environment ()
nil) ; Bogus top level lexical environment
(defun compile-in-lexical-environment (env name lambda-expr)
(declare (ignore env))
;; (warn "lambda: ~W" lambda-expr)
(destructuring-bind (operator lambda-list &body decl-doc-body)
lambda-expr
(assert (eq 'lambda operator) (lambda-expr)
"Closette compiler: Lambda wasn't lambda.")
(multiple-value-bind (body declarations)
(movitz::parse-docstring-declarations-and-body decl-doc-body 'cl:declare)
(movitz::make-compiled-funobj name
(translate-program lambda-list :cl :muerte.cl)
(translate-program declarations :cl :muerte.cl)
(translate-program (cons 'muerte.cl:progn body) :cl :muerte.cl)
nil nil))))
;;;
;;; Bootstrap
;;;
(defun bootstrap-closette ()
;; (format t "~&;; Beginning to bootstrap Closette...~%")
(setf *classes-with-old-slot-definitions* nil)
(forget-all-classes)
;;;(forget-all-generic-functions)
How to create the class hierarchy in 10 easy steps :
1 . Figure out standard - class 's slots .
(setq *the-slots-of-standard-class*
(mapcar (lambda (slotd)
(make-effective-slot-definition
(movitz::translate-program 'standard-class :cl :muerte.cl)
:name (car slotd)
:initargs (let ((a (getf (cdr slotd) :initarg)))
(if a (list a) ()))
:initform (getf (cdr slotd) :initform)
:initfunction (getf (cdr slotd) :initform)
:allocation :instance))
(append (nth 3 +the-defclass-class+) ; slots inherited from "class"
(nth 3 +the-defclass-std-slotted-class+) ; slots inherited from "std-slotted-class"
(nth 3 +the-defclass-instance-slotted-class+) ; ..
(nth 3 +the-defclass-standard-class+))))
(loop for s in *the-slots-of-standard-class* as i upfrom 0
do (setf (slot-definition-location s) i))
(setq *the-position-of-standard-effective-slots*
(position 'effective-slots *the-slots-of-standard-class*
:key #'slot-definition-name))
2 . Create the standard - class metaobject by hand .
(setq *the-class-standard-class*
(allocate-std-instance 'tba (make-array (length *the-slots-of-standard-class*)
:initial-element (movitz::unbound-value))))
3 . Install standard - class 's ( circular ) class - of link .
(setf (std-instance-class *the-class-standard-class*)
*the-class-standard-class*)
;; (It's now okay to use class-... accessor).
4 . Fill in standard - class 's class - slots .
(setf (class-slots *the-class-standard-class*) *the-slots-of-standard-class*)
( Skeleton built ; it 's now okay to call make - instance - standard - class . )
5 . Hand build the class t so that it has no direct superclasses .
(setf (movitz-find-class 't)
(let ((class (std-allocate-instance *the-class-standard-class*)))
(setf (movitz-class-name class) 't)
(setf (class-direct-subclasses class) ())
(setf (class-direct-superclasses class) ())
(setf (class-direct-methods class) ())
(setf (class-direct-slots class) ())
(setf (class-precedence-list class) (list class))
(setf (class-slots class) ())
(setf (class-direct-methods class) nil)
class))
;; (It's now okay to define subclasses of t.)
6 . Create the other superclass of standard - class ( i.e. , standard - object ) .
(defclass-los standard-object (t) ())
7 . Define the full - blown version of class and standard - class .
( warn " step 7 ... " )
(eval +the-defclasses-before-class+)
(eval +the-defclass-class+) ; Create the class class.
(eval +the-defclass-std-slotted-class+)
(eval +the-defclass-instance-slotted-class+)
(eval +the-defclass-standard-class+) ; Re-create the standard-class..
(setf (std-instance-slots *the-class-standard-class*) ; ..and copy it into the old standard-class..
(std-instance-slots (movitz-find-class 'standard-class))) ; (keeping it's identity intact.)
(setf (movitz-find-class 'standard-class)
*the-class-standard-class*)
(setf (class-precedence-list *the-class-standard-class*)
(std-compute-class-precedence-list *the-class-standard-class*))
8 . Replace all ( x .. ) existing pointers to the skeleton with real one .
;; Not necessary because we kept standard-class's identity by the above.
;; Define the built-in-class..
(defclass-los built-in-class (class)
((size :initarg :size)
(slot-map :initarg :slot-map)))
;; Change t to be a built-in-class..
(let ((t-prototype (make-instance-built-in-class 'built-in-class :name t :direct-superclasses nil)))
;; both class and slots of t-prototype are copied into the old t metaclass instance,
;; so that object's identity is preserved.
(setf (std-instance-class (movitz-find-class t)) (std-instance-class t-prototype)
(std-instance-slots (movitz-find-class t)) (std-instance-slots t-prototype)
(class-precedence-list (movitz-find-class t)) (std-compute-class-precedence-list (movitz-find-class t))))
(eval +the-defclasses-slots+)
(eval +the-defclass-standard-direct-slot-definition+)
( warn " classes with old defs : ~S " * classes - with - old - slot - definitions * )
(dolist (class-name *classes-with-old-slot-definitions*)
(let ((class (movitz-find-class class-name)))
(setf (std-slot-value class 'direct-slots)
(mapcar #'translate-direct-slot-definition
(std-slot-value class 'direct-slots)))
(setf (std-slot-value class 'effective-slots)
(loop for position upfrom 0
as slot in (std-slot-value class 'effective-slots)
as slot-name = (slot-definition-name slot)
do (if (slot-definition-location slot)
(assert (= (slot-definition-location slot) position))
(setf (slot-definition-location slot) position))
collect (translate-effective-slot-definition slot)
;;; do (warn "setting ~S ~S to ~S" class-name slot-name position)
do (setf (movitz::movitz-env-get class-name slot-name) position)))))
(map-into *the-slots-of-standard-class*
#'translate-effective-slot-definition
*the-slots-of-standard-class*)
#+ignore (format t "~&;; Closette bootstrap completed."))
;; (Clear sailing from here on in).
9 . Define the other built - in classes .
;;; (defclass-los symbol (t) () (:metaclass built-in-class))
;;; (defclass-los sequence (t) () (:metaclass built-in-class))
;;; (defclass-los array (t) () (:metaclass built-in-class))
;;; (defclass-los number (t) () (:metaclass built-in-class))
;;; (defclass-los character (t) () (:metaclass built-in-class))
;;; (defclass-los function (t) () (:metaclass built-in-class))
;;; (defclass-los hash-table (t) () (:metaclass built-in-class))
;;;;;; (defclass-los package (t) () (:metaclass built-in-class))
;;;;;; (defclass-los pathname (t) () (:metaclass built-in-class))
;;;;;; (defclass-los readtable (t) () (:metaclass built-in-class))
;;;;;; (defclass-los stream (t) () (:metaclass built-in-class))
;;; (defclass-los list (sequence) () (:metaclass built-in-class))
;;; (defclass-los null (symbol list) () (:metaclass built-in-class))
;;; (defclass-los cons (list) () (:metaclass built-in-class))
;;; (defclass-los vector (array sequence) () (:metaclass built-in-class))
;;; (defclass-los bit-vector (vector) () (:metaclass built-in-class))
;;; (defclass-los string (vector) () (:metaclass built-in-class))
;;; (defclass-los complex (number) () (:metaclass built-in-class))
;;; (defclass-los integer (number) () (:metaclass built-in-class))
;;; (defclass-los float (number) () (:metaclass built-in-class))
; ; 10 . Define the other standard metaobject classes .
;;; (setq *the-class-standard-gf* (eval *the-defclass-standard-generic-function*))
;;; (setq *the-class-standard-method* (eval *the-defclass-standard-method*))
;;; ;; Voila! The class hierarchy is in place.
;;; (format t "Class hierarchy created.")
;;; ;; (It's now okay to define generic functions and methods.)
;; (setq *the-class-standard-method* (eval +the-defclass-standard-method+)))
(when (zerop (hash-table-count *class-table*))
(bootstrap-closette)))
| null | https://raw.githubusercontent.com/dym/movitz/56176e1ebe3eabc15c768df92eca7df3c197cb3d/losp/muerte/los-closette-compiler.lisp | lisp | ------------------------------------------------------------------
For distribution policy, see the accompanying file COPYING.
Description:
------------------------------------------------------------------
standard-class -> std-slotted-class -> class -> ..
class's defclass form
:accessor class-precedence-list
:accessor class-direct-subclasses
:accessor class-slots
:accessor class-direct-slots
standard-class's defclass form
for now
greatly simplifies the implementation without removing functionality.
defclass
Class name-space accessors
LOS standard-instance
LOS standard-gf-instance
Ensure class
(warn "movitz-make-instance: ~S ~S" class all-keys)
make-instance-standard-class creates and initializes an instance of
standard-class without falling into method lookup. However, it cannot be
called until standard-class itself exists.
(assert (null direct-slots) (direct-slots)
"Closette compiler: This class can't have slots: ~S" direct-slots)
finalize-inheritance
Class precedence lists
(warn "class: ~W" class)
(warn "classes-to-order: ~W" classes-to-order)
topological-sort implements the standard algorithm for topologically
sorting an arbitrary set of elements while honoring the precedence
constraints given by a set of (X,Y) pairs that indicate that element
X must precede element Y. The tie-breaker procedure is called when it
is necessary to choose from multiple minimal elements; both a list of
candidates and the ordering so far are provided as arguments.
(warn "topological-sort:~% ~W~% ~W~% ~W" elements constraints tie-breaker)
In the event of a tie while topologically sorting class precedence lists,
rightmost in the class precedence list computed so far." The same result
is obtained by inspecting the partially constructed class precedence list
(There's a lemma that shows that this rule yields a unique result.)
This version of collect-superclasses* isn't bothered by cycles in the class
hierarchy, which sometimes happen by accident.
C_2, ..., C_n is the set ((C C_1) (C_1 C_2) ...(C_n-1 C_n)).
Slot inheritance
accessor for effective method function table
Method metaobjects and standard-method
standard - method 's class metaobject
defgeneric
ensure-generic-function
finalize-generic-function
N.B. Same basic idea as finalize-inheritance. Takes care of recomputing
and storing the discriminating function, and clearing the effective method
function table.
make-instance-standard-generic-function creates and initializes an
instance of standard-generic-function without falling into method lookup.
However, it cannot be called until standard-generic-function exists.
defmethod
:body ',body
:declarations ',declarations
:environment ,env)))
Several tedious functions for analyzing lambda lists
Just the keywords
Just the variable names
Variable names & specializers
Just the specializers
ensure method
make-instance-standard-method creates and initializes an instance of
standard-method without falling into method lookup. However, it cannot
be called until standard-method exists.
(method-lambda-list method) lambda-list
(method-body method) body
(method-declarations method) declarations
add-method
N.B. This version first removes any existing method on the generic function
Reader and write methods
this is LOS code!
this is LOS code!
apply-generic-function
compute-discriminating-function
compute-applicable-methods-using-classes
method-more-specific-p
for spec2 in (method-specializers method2)
for arg-class in required-classes
do (unless (eq spec1 spec2)
(return-from std-method-more-specific-p
(sub-specializer-p spec1 spec2 arg-class))))
apply-methods and compute-effective-method-function
compute an effective method function from a list of primary methods:
apply-method and compute-method-function
We must capture the value of the dynamic *next-methods*
this is an ugly hack so next-emf wont be a constant-binding..
XXX &key args not handled.
N.B. The function kludge-arglist is used to pave over the differences
between argument keyword compatibility for regular functions versus
generic functions.
Run-time environment hacking (Common Lisp ain't got 'em).
Bogus top level lexical environment
(warn "lambda: ~W" lambda-expr)
Bootstrap
(format t "~&;; Beginning to bootstrap Closette...~%")
(forget-all-generic-functions)
slots inherited from "class"
slots inherited from "std-slotted-class"
..
(It's now okay to use class-... accessor).
it 's now okay to call make - instance - standard - class . )
(It's now okay to define subclasses of t.)
Create the class class.
Re-create the standard-class..
..and copy it into the old standard-class..
(keeping it's identity intact.)
Not necessary because we kept standard-class's identity by the above.
Define the built-in-class..
Change t to be a built-in-class..
both class and slots of t-prototype are copied into the old t metaclass instance,
so that object's identity is preserved.
do (warn "setting ~S ~S to ~S" class-name slot-name position)
(Clear sailing from here on in).
(defclass-los symbol (t) () (:metaclass built-in-class))
(defclass-los sequence (t) () (:metaclass built-in-class))
(defclass-los array (t) () (:metaclass built-in-class))
(defclass-los number (t) () (:metaclass built-in-class))
(defclass-los character (t) () (:metaclass built-in-class))
(defclass-los function (t) () (:metaclass built-in-class))
(defclass-los hash-table (t) () (:metaclass built-in-class))
(defclass-los package (t) () (:metaclass built-in-class))
(defclass-los pathname (t) () (:metaclass built-in-class))
(defclass-los readtable (t) () (:metaclass built-in-class))
(defclass-los stream (t) () (:metaclass built-in-class))
(defclass-los list (sequence) () (:metaclass built-in-class))
(defclass-los null (symbol list) () (:metaclass built-in-class))
(defclass-los cons (list) () (:metaclass built-in-class))
(defclass-los vector (array sequence) () (:metaclass built-in-class))
(defclass-los bit-vector (vector) () (:metaclass built-in-class))
(defclass-los string (vector) () (:metaclass built-in-class))
(defclass-los complex (number) () (:metaclass built-in-class))
(defclass-los integer (number) () (:metaclass built-in-class))
(defclass-los float (number) () (:metaclass built-in-class))
; 10 . Define the other standard metaobject classes .
(setq *the-class-standard-gf* (eval *the-defclass-standard-generic-function*))
(setq *the-class-standard-method* (eval *the-defclass-standard-method*))
;; Voila! The class hierarchy is in place.
(format t "Class hierarchy created.")
;; (It's now okay to define generic functions and methods.)
(setq *the-class-standard-method* (eval +the-defclass-standard-method+))) | Copyright ( C ) 2001 - 2005 ,
Department of Computer Science , University of Tromso , Norway .
Filename : los-closette-compiler.lisp
Author : < >
Created at : Thu Aug 29 13:15:11 2002
$ I d : los - closette - compiler.lisp , v 1.23 2008 - 04 - 27 19:42:26 Exp $
(provide :muerte/los-closette-compiler)
(in-package muerte)
(define-compile-time-variable *class-table*
(make-hash-table :test 'eq))
(define-compile-time-variable *eql-specializer-table*
(make-hash-table :test 'eql))
(define-compile-time-variable *the-slots-of-standard-class* nil)
(define-compile-time-variable *the-position-of-standard-effective-slots* nil)
(define-compile-time-variable *the-class-standard-class* nil)
(define-compile-time-variable *the-standard-method-combination* nil)
extends to EOF
(defvar *classes-with-old-slot-definitions* nil)
(defconstant +the-defclasses-before-class+
'(progn
(defclass-los metaobject () ())
(defclass-los specializer (metaobject) ())
(defclass-los eql-specializer (specializer)
((object)))))
'(defclass-los class (specializer)
((name
:initarg name)
: accessor class - direct - superclasses
:initarg :direct-superclasses)
:initform ())
(direct-methods
:initarg :direct-methods
:initform ())
(plist
:initform nil)
(prototype
:initform nil))))
(defconstant +the-defclass-std-slotted-class+
'(defclass-los std-slotted-class (class)
(defconstant +the-defclasses-slots+
'(progn
(defclass-los slot-definition (metaobject) (name))
(defclass-los effective-slot-definition (slot-definition) ())
(defclass-los direct-slot-definition (slot-definition) ())
(defclass-los standard-slot-definition (slot-definition)
(type initform initfunction initargs allocation))
(defclass-los standard-effective-slot-definition (standard-slot-definition effective-slot-definition)
(location))))
(defconstant +the-defclass-standard-direct-slot-definition+
'(defclass-los standard-direct-slot-definition
(standard-slot-definition direct-slot-definition)
(position readers writers)))
(defconstant +the-defclass-instance-slotted-class+
'(defclass-los instance-slotted-class (class)
((instance-slots))))
'(defclass-los standard-class (instance-slotted-class std-slotted-class)
()))
(defmacro push-on-end (value location)
`(setf ,location (nconc ,location (list ,value))))
(defun mapappend (fun &rest args)
(declare (dynamic-extent args))
(if (some #'null args)
()
(append (apply fun (mapcar #'car args))
(apply #'mapappend fun (mapcar #'cdr args)))))
(defun make-direct-slot-definition (class-name
&key name (initargs ()) (initform nil) (initfunction nil)
(readers ()) (writers ()) (allocation :instance)
(type t)
documentation)
(cond
((movitz-find-class 'standard-direct-slot-definition nil)
(let ((slot (std-allocate-instance (movitz-find-class 'standard-direct-slot-definition))))
(setf (std-slot-value slot 'name) name
(std-slot-value slot 'initargs) initargs
(std-slot-value slot 'initform) initform
(std-slot-value slot 'initfunction) initfunction
(std-slot-value slot 'allocation) allocation
(std-slot-value slot 'readers) readers
(std-slot-value slot 'writers) writers)
slot))
(t (pushnew class-name *classes-with-old-slot-definitions*)
1
3
5
7
9
11
writers
nil)
:cl :muerte.cl))))
(defun translate-direct-slot-definition (old-slot)
(if (not (vectorp old-slot))
old-slot
(loop with slot = (std-allocate-instance (movitz-find-class 'standard-direct-slot-definition))
for slot-name in '(name initargs initform initfunction allocation readers writers)
as value across old-slot
do (setf (std-slot-value slot slot-name) value)
finally (return slot))))
(defun make-effective-slot-definition (class &key name (initargs ()) (initform nil) (initfunction nil)
(allocation :instance) location)
(cond
((movitz-find-class 'standard-effective-slot-definition nil)
(let ((slot (std-allocate-instance (movitz-find-class 'standard-effective-slot-definition))))
(setf (std-slot-value slot 'name) name
(std-slot-value slot 'initargs) initargs
(std-slot-value slot 'initform) initform
(std-slot-value slot 'initfunction) initfunction
(std-slot-value slot 'allocation) allocation
(std-slot-value slot 'location) location)
slot))
(t (pushnew class *classes-with-old-slot-definitions*)
(translate-program (vector name
initargs
initform
initfunction
allocation
nil nil
location)
:cl :muerte.cl))))
(defun translate-effective-slot-definition (old-slot)
(if (not (vectorp old-slot))
old-slot
(loop with slot = (std-allocate-instance (movitz-find-class 'standard-effective-slot-definition))
for slot-name in '(name initargs initform initfunction allocation nil nil location)
as value across old-slot
when slot-name
do (setf (std-slot-value slot slot-name) value)
finally (assert (integerp (std-slot-value slot 'location)) ()
"No location for ~S: ~S" slot (std-slot-value slot 'location))
finally (return slot))))
(defun slot-definition-name (slot)
(if (vectorp slot)
(svref slot 0)
(std-slot-value slot 'name)))
(defun (setf slot-definition-name) (new-value slot)
(setf (svref slot 0) new-value))
(defun slot-definition-initargs (slot)
(if (vectorp slot)
(svref slot 1)
(std-slot-value slot 'initargs)))
(defun (setf slot-definition-initargs) (new-value slot)
(setf (svref slot 1) new-value))
(defun slot-definition-initform (slot)
(if (vectorp slot)
(svref slot 2)
(std-slot-value slot 'initform)))
(defun (setf slot-definition-initform) (new-value slot)
(setf (svref slot 2) new-value))
(defun slot-definition-initfunction (slot)
(if (vectorp slot)
(svref slot 3)
(std-slot-value slot 'initfunction)))
(defun (setf slot-definition-initfunction) (new-value slot)
(setf (svref slot 3) new-value))
(defun slot-definition-allocation (slot)
(if (vectorp slot)
(svref slot 4)
(std-slot-value slot 'allocation)))
(defun (setf slot-definition-allocation) (new-value slot)
(setf (svref slot 4) new-value))
(defun instance-slot-p (slot)
(eq (slot-definition-allocation slot) :instance))
(defun slot-definition-readers (slot)
(if (vectorp slot)
(svref slot 5)
(std-slot-value slot 'readers)))
(defun (setf slot-definition-readers) (new-value slot)
(setf (svref slot 5) new-value))
(defun slot-definition-writers (slot)
(if (vectorp slot)
(svref slot 6)
(std-slot-value slot 'writers)))
(defun (setf slot-definition-writers) (new-value slot)
(setf (svref slot 6) new-value))
(defun slot-definition-location (slot)
(if (vectorp slot)
(svref slot 7)
(std-slot-value slot 'location)))
(defun (setf slot-definition-location) (new-value slot)
(check-type new-value integer)
(if (vectorp slot)
(setf (svref slot 7) new-value)
(setf (std-slot-value slot 'location) new-value)))
Defining the metaobject slot accessor function as regular functions
(defun movitz-class-name (class) (std-slot-value class 'name))
(defun (setf movitz-class-name) (new-value class)
(setf (movitz-slot-value class 'name) new-value))
(defun class-direct-superclasses (class)
(movitz-slot-value class 'direct-superclasses))
(defun (setf class-direct-superclasses) (new-value class)
(setf (movitz-slot-value class 'direct-superclasses) new-value))
(defun class-direct-slots (class)
(if (and (eq (movitz-class-of (movitz-class-of class)) *the-class-standard-class*)
(movitz-slot-exists-p class 'direct-slots))
(movitz-slot-value class 'direct-slots)
#+ignore (warn "no direct-slots for ~W" class)))
(defun (setf class-direct-slots) (new-value class)
(setf (movitz-slot-value class 'direct-slots) new-value))
(defun class-precedence-list (class)
(movitz-slot-value class 'class-precedence-list))
(defun (setf class-precedence-list) (new-value class)
(setf (movitz-slot-value class 'class-precedence-list) new-value))
(defun class-slots (class)
(movitz-slot-value class 'effective-slots))
(defun (setf class-slots) (new-value class)
(setf (movitz-slot-value class 'effective-slots) new-value))
(defun class-direct-subclasses (class)
(movitz-slot-value class 'direct-subclasses))
(defun (setf class-direct-subclasses) (new-value class)
(setf (movitz-slot-value class 'direct-subclasses) new-value))
(defun class-direct-methods (class)
(movitz-slot-value class 'direct-methods))
(defun (setf class-direct-methods) (new-value class)
(setf (movitz-slot-value class 'direct-methods) new-value))
(defmacro defclass-los (name direct-superclasses direct-slots &rest options)
`(ensure-class ',name
:direct-superclasses
,(canonicalize-direct-superclasses direct-superclasses)
:direct-slots
,(canonicalize-direct-slots direct-slots name nil)
,@(canonicalize-defclass-options options nil name)))
(defun canonicalize-direct-slots (direct-slots class-name env)
`(list ,@(mapcar (lambda (ds) (canonicalize-direct-slot ds class-name env)) direct-slots)))
(defun canonicalize-direct-slot (spec class-name env)
(if (symbolp spec)
`(list :name ',spec)
(let ((name (car spec))
(initfunction nil)
(initform nil)
(initargs ())
(readers ())
(writers ())
(other-options ()))
(do ((olist (cdr spec) (cddr olist)))
((null olist))
(case (car olist)
(:initform
(let ((form (cadr olist)))
(setq initfunction
(if (movitz:movitz-constantp form env)
(list 'quote (list 'quote (movitz::eval-form form env)))
(compile-in-lexical-environment env
(muerte::translate-program
(list 'slot-initfunction
class-name name)
:cl :muerte.cl)
`(lambda () ,form))))
(setq initform `',form)))
(:initarg
(push-on-end (cadr olist) initargs))
(:reader
(push-on-end (cadr olist) readers))
(:writer
(push-on-end (cadr olist) writers))
(:accessor
(push-on-end (cadr olist) readers)
(push-on-end `(setf ,(cadr olist)) writers))
(otherwise
(push-on-end `',(car olist) other-options)
(push-on-end `',(cadr olist) other-options))))
`(list
:name ',name
,@(when initfunction
`(:initform ,initform :initfunction ,initfunction))
,@(when initargs `(:initargs ',initargs))
,@(when readers `(:readers ',readers))
,@(when writers `(:writers ',writers))
,@other-options))))
(defun canonicalize-direct-superclasses (direct-superclasses)
`(list ,@(mapcar #'canonicalize-direct-superclass direct-superclasses)))
(defun canonicalize-direct-superclass (class-name)
`(movitz-find-class ',class-name))
(defun intern-eql-specializer (object)
(or (gethash object *eql-specializer-table*)
(setf (gethash object *eql-specializer-table*)
(let ((s (std-allocate-instance (movitz-find-class 'eql-specializer))))
(setf (movitz-slot-value s 'object) object)
s))))
(defun canonicalize-defclass-options (options env class-name)
(mapcan (lambda (o) (canonicalize-defclass-option o env class-name)) options))
(defun canonicalize-defclass-option (option env class-name)
(case (car option)
((:metaclass)
(list ':metaclass
`(movitz-find-class ',(cadr option))))
((:default-initargs)
(list :default-initargs-function
(list 'quote
(cons (compile-in-lexical-environment
env (gensym (format nil "default-initargs-~A-" class-name))
`(lambda (o)
(case o
,@(loop for (arg val) on (cdr option) by #'cddr
collect `(,arg ,val)))))
(loop for arg in (cdr option) by #'cddr collect arg)))))
(t (list `',(car option) `',(cadr option)))))
(defun movitz-find-class (symbol &optional (errorp t))
(let ((symbol (muerte::translate-program symbol :cl :muerte.cl)))
(let ((class (gethash symbol *class-table*)))
(if (and (null class) errorp)
(error "Closette compiler: No LOS class named ~W." symbol)
class))))
(defun movitz-find-class-name (class)
(maphash (lambda (key value)
(when (eq value class)
(return-from movitz-find-class-name key)))
*class-table*))
(defun (setf movitz-find-class) (new-value symbol)
(let ((symbol (muerte::translate-program symbol :cl :muerte.cl)))
(if new-value
(setf (gethash symbol *class-table*) new-value)
(remhash symbol *class-table*)))
new-value)
(defun forget-all-classes ()
(clrhash *class-table*)
(values))
(defun find-specializer (name)
(cond
((symbolp name)
(movitz-find-class name))
((and (consp name)
(string= 'eql (car name)))
(intern-eql-specializer (movitz::eval-form (cadr name))))
(t (error "Unknown specializer: ~S" name))))
(defun specializer-name (specializer)
(if (eq (movitz-find-class 'eql-specializer)
(movitz-class-of specializer))
(translate-program (list 'eql (movitz-slot-value specializer 'object))
:cl :muerte.cl)
(movitz-class-name specializer)))
(defun allocate-std-instance (class slots)
(movitz::make-movitz-std-instance class slots))
(defun std-instance-class (class)
(etypecase class
(movitz::movitz-std-instance
(movitz::movitz-std-instance-class class))
(movitz::movitz-funobj-standard-gf
(movitz::standard-gf-class class))))
(defun (setf std-instance-class) (value class)
(etypecase class
(movitz::movitz-std-instance
(setf (movitz::movitz-std-instance-class class) value))
(movitz::movitz-funobj-standard-gf
(setf (movitz::standard-gf-class class) value))))
(defun std-instance-slots (class)
(etypecase class
(movitz::movitz-std-instance
(movitz::movitz-std-instance-slots class))
(movitz::movitz-funobj-standard-gf
(movitz::standard-gf-slots class))))
(defun (setf std-instance-slots) (value class)
(etypecase class
(movitz::movitz-std-instance
(setf (movitz::movitz-std-instance-slots class) value))
(movitz::movitz-funobj-standard-gf
(setf (movitz::standard-gf-slots class) value))))
(defun std-allocate-instance (class)
(allocate-std-instance class (make-array (count-if #'instance-slot-p (class-slots class))
:initial-element (movitz::unbound-value))))
(defun allocate-std-gf-instance (class slots &rest init-args)
(apply #'movitz::make-standard-gf class slots init-args))
(defun std-allocate-gf-instance (class &rest init-args)
(apply #'allocate-std-gf-instance
class
(make-array (count-if #'instance-slot-p (class-slots class))
:initial-element (movitz::unbound-value))
init-args))
(defun std-gf-instance-class (class)
(movitz::standard-gf-class class))
(defun (setf std-gf-instance-class) (value class)
(setf (movitz::standard-gf-class class) value))
(defun std-gf-instance-slots (class)
(movitz::standard-gf-slots class))
(defun (setf std-gf-instance-slots) (value class)
(setf (movitz::standard-gf-slots class) value))
(defvar *slot-location-nesting* 0)
(defun slot-location (class slot-name)
(when (< 10 *slot-location-nesting*)
(break "Unbounded slot-location?"))
(let ((*slot-location-nesting* (1+ *slot-location-nesting*)))
(cond
((and (eq slot-name 'effective-slots)
(eq class *the-class-standard-class*))
(position 'effective-slots *the-slots-of-standard-class*
:key #'slot-definition-name))
((eq class (movitz-find-class 'standard-effective-slot-definition nil))
(or (position slot-name '(name type initform initfunction initargs allocation location))
(error "No slot ~S in ~S." slot-name (movitz-class-name class))))
(t #+ignore
(when (and (eq slot-name 'effective-slots)
(subclassp class *the-class-standard-class*))
(break "Looking for slot ~S in class ~S, while std-class is ~S."
slot-name class *the-class-standard-class*))
(let ((slot (find slot-name
(std-slot-value class 'effective-slots)
:key #'slot-definition-name)))
(if (null slot)
(error "Closette compiler: The slot ~S is missing from the class ~S."
slot-name class)
(let ((pos (position slot
(remove-if-not #'instance-slot-p
(std-slot-value class 'effective-slots)))))
(if (null pos)
(error "Closette compiler: The slot ~S is not an instance slot in the class ~S."
slot-name class)
pos))))))))
(defun movitz-class-of (instance)
(std-instance-class instance))
(defun subclassp (c1 c2)
(find c2 (class-precedence-list c1)))
(defun sub-specializer-p (c1 c2 c-arg)
(let ((cpl (class-precedence-list c-arg)))
(find c2 (cdr (member c1 cpl)))))
(defun std-slot-value (instance slot-name)
(let* ((slot-name (translate-program slot-name :cl :muerte.cl))
(location (slot-location (movitz-class-of instance) slot-name))
(slots (std-instance-slots instance))
(val (svref slots location)))
(if (eq (movitz::unbound-value) val)
(error "Closette compiler: The slot ~S at ~D is unbound in the object ~S."
slot-name location instance)
val)))
(defun (setf std-slot-value) (value instance slot-name)
(let* ((location (slot-location (movitz-class-of instance)
(translate-program slot-name :cl :muerte.cl)))
(slots (std-instance-slots instance)))
(setf (svref slots location) (muerte::translate-program value :cl :muerte.cl))))
(defun movitz-slot-value (object slot-name)
(std-slot-value object (translate-program slot-name :cl :muerte.cl)))
(defun (setf movitz-slot-value) (new-value object slot-name)
(setf (std-slot-value object (translate-program slot-name :cl :muerte.cl))
new-value))
(defun std-slot-exists-p (instance slot-name)
(not (null (find slot-name (class-slots (movitz-class-of instance))
:key #'slot-definition-name))))
(defun movitz-slot-exists-p (object slot-name)
(if (eq (movitz-class-of (movitz-class-of object)) *the-class-standard-class*)
(std-slot-exists-p object slot-name)
(error "Can't do this.")
#+ignore (movitz-slot-exists-p-using-class (movitz-class-of object)
object slot-name)))
(defun ensure-class (name &rest all-keys &key (metaclass *the-class-standard-class*)
direct-slots direct-superclasses
&allow-other-keys)
(declare (dynamic-extent all-keys))
(remf all-keys :metaclass)
(let ((old-class (movitz-find-class name nil)))
(if (and old-class
(eq metaclass *the-class-standard-class*))
(std-after-initialization-for-classes old-class
:direct-slots direct-slots
:direct-superclasses direct-superclasses)
(let ((class (apply (cond
((eq metaclass *the-class-standard-class*)
'make-instance-standard-class)
((eq metaclass (movitz-find-class 'structure-class nil))
'make-instance-structure-class)
((eq metaclass (movitz-find-class 'built-in-class nil))
'make-instance-built-in-class)
((eq metaclass (movitz-find-class 'funcallable-standard-class nil))
'movitz-make-instance)
((eq metaclass (movitz-find-class 'run-time-context-class nil))
'movitz-make-instance)
((member *the-class-standard-class*
(class-precedence-list metaclass))
'make-instance-standard-class)
(t (break "Unknown metaclass: ~S" metaclass)
#+ignore 'make-instance-built-in-class
'movitz-make-instance))
metaclass
:name name
all-keys)))
(setf (movitz-find-class name) class)))))
(defun movitz-make-instance-funcallable (metaclass &rest all-keys &key name direct-superclasses direct-slots &allow-other-keys)
(declare (ignore all-keys))
(let ((class (std-allocate-instance metaclass)))
(setf (movitz-class-name class) name)
(setf (class-direct-subclasses class) ())
(setf (class-direct-methods class) ())
(std-after-initialization-for-classes class
:direct-slots direct-slots
:direct-superclasses direct-superclasses)
class))
(defun movitz-make-instance-run-time-context (metaclass &rest all-keys &key name direct-superclasses direct-slots size slot-map plist &allow-other-keys)
(declare (ignore all-keys))
(let ((class (std-allocate-instance metaclass)))
(setf (std-slot-value class 'size)
(or size (bt:sizeof 'movitz::movitz-run-time-context)))
(setf (std-slot-value class 'slot-map)
(or slot-map
(movitz::slot-map 'movitz::movitz-run-time-context
(cl:+ (bt:slot-offset 'movitz::movitz-run-time-context
'movitz::run-time-context-start)
0))))
(setf (std-slot-value class 'plist) plist)
(setf (movitz-class-name class) name)
(setf (class-direct-subclasses class) ())
(setf (class-direct-methods class) ())
(std-after-initialization-for-classes class
:direct-slots direct-slots
:direct-superclasses direct-superclasses)
class))
(defun movitz-make-instance (class &rest all-keys)
(when (symbolp class)
(setf class (movitz-find-class class)))
(cond
((eq class (movitz-find-class 'funcallable-standard-class nil))
(apply 'movitz-make-instance-funcallable class all-keys) )
((eq class (movitz-find-class 'run-time-context-class nil))
(apply 'movitz-make-instance-run-time-context class all-keys))
(t (let ((instance (std-allocate-instance class)))
(dolist (slot (class-slots (movitz-class-of instance)))
(let ((slot-name (slot-definition-name slot)))
(multiple-value-bind (init-key init-value foundp)
(get-properties all-keys (slot-definition-initargs slot))
(declare (ignore init-key))
(when foundp
(setf (movitz-slot-value instance slot-name) init-value)))))
instance))))
(defun initialize-class-object (class &key name plist direct-methods
(direct-superclasses (list (movitz-find-class t)))
&allow-other-keys)
(setf (movitz-class-name class) name
(std-slot-value class 'plist) plist
(class-direct-subclasses class) ()
(class-direct-methods class) direct-methods)
(let ((supers direct-superclasses))
(setf (class-direct-superclasses class) supers)
(dolist (superclass supers)
(push class (class-direct-subclasses superclass))))
(setf (class-precedence-list class)
(std-compute-class-precedence-list class))
class)
(defun make-instance-structure-class (metaclass &rest all-keys
&key name slots direct-slots ((:metaclass dummy))
(direct-superclasses
(list (movitz-find-class 'structure-object))))
(declare (ignore dummy all-keys))
(assert (null direct-slots))
(let ((class (std-allocate-instance (if (symbolp metaclass)
(movitz-find-class metaclass)
metaclass))))
(setf (std-slot-value class 'slots) slots)
(initialize-class-object class :name name
:direct-superclasses direct-superclasses)))
(defun make-instance-built-in-class (metaclass &rest all-keys
&key name direct-superclasses
direct-methods direct-slots plist size slot-map
&allow-other-keys)
(declare (ignore plist direct-methods direct-slots direct-superclasses name))
(let ((class (std-allocate-instance (if (symbolp metaclass)
(movitz-find-class metaclass)
metaclass))))
(when size (setf (std-slot-value class 'size) size))
(setf (std-slot-value class 'slot-map) slot-map)
(apply #'initialize-class-object class all-keys)))
(defun make-instance-standard-class (metaclass &key name direct-superclasses direct-slots
default-initargs-function
documentation)
(declare (ignore metaclass documentation))
(let ((class (std-allocate-instance metaclass)))
(setf (movitz-class-name class) name)
(setf (class-direct-subclasses class) ())
(setf (class-direct-methods class) ())
(setf (movitz-slot-value class 'prototype) ())
(setf (movitz-slot-value class 'plist)
(when default-initargs-function
(list :default-initargs-function default-initargs-function)))
(dolist (slot (class-slots (movitz-class-of class)))
(let ((slot-name (slot-definition-name slot))
(slot-initform (muerte::translate-program (slot-definition-initform slot)
'#:muerte.cl '#:cl)))
(when slot-initform
(setf (movitz-slot-value class slot-name) (movitz::eval-form slot-initform)))))
(std-after-initialization-for-classes class
:direct-slots direct-slots
:direct-superclasses direct-superclasses)
class))
(defun std-after-initialization-for-classes (class &key direct-superclasses direct-slots)
(let ((supers (or direct-superclasses
(list (movitz-find-class 'standard-object)))))
(setf (class-direct-superclasses class) supers)
(dolist (superclass supers)
(pushnew class (class-direct-subclasses superclass))))
(let ((slots (mapcar #'(lambda (slot-properties)
(apply #'make-direct-slot-definition
(movitz-class-name class)
slot-properties))
direct-slots)))
(setf (class-direct-slots class) slots)
(dolist (direct-slot slots)
(dolist (reader (slot-definition-readers direct-slot))
(add-reader-method
class reader (slot-definition-name direct-slot)))
(dolist (writer (slot-definition-writers direct-slot))
(add-writer-method
class writer (slot-definition-name direct-slot)))))
(funcall (if (or (eq (movitz-class-of class)
*the-class-standard-class*)
(subclassp (movitz-class-of class)
(movitz-find-class 'std-slotted-class)))
#'std-finalize-inheritance
#'finalize-inheritance)
class)
(values))
(defun std-finalize-inheritance (class)
(setf (class-precedence-list class)
(funcall (if (or (eq (movitz-class-of class) *the-class-standard-class*)
(subclassp (movitz-class-of class) (movitz-find-class 'std-slotted-class)))
#'std-compute-class-precedence-list
#'compute-class-precedence-list)
class))
(setf (class-slots class)
(funcall (if (or (eq (movitz-class-of class) *the-class-standard-class*)
(subclassp (movitz-class-of class) (movitz-find-class 'std-slotted-class)))
#'std-compute-slots
#'compute-slots)
class))
(values))
(defun finalize-inheritance (class)
(error "Don't know how to finalize-inheritance for class ~S of class ~S."
class (class-of class)))
(defun std-compute-class-precedence-list (class)
(let ((classes-to-order (collect-superclasses* class)))
(topological-sort classes-to-order
(remove-duplicates
(mapappend #'local-precedence-ordering
classes-to-order)
:test #'equal)
#'std-tie-breaker-rule)))
(defun compute-class-precedence-list (class)
(error "Don't know how to compute class-precedence-list for ~S of class ~S."
class (class-of class)))
(defun topological-sort (elements constraints tie-breaker)
(let ((remaining-constraints constraints)
(remaining-elements elements)
(result ()))
(loop
(let ((minimal-elements
(remove-if #'(lambda (class)
(member class remaining-constraints
:key #'cadr))
remaining-elements)))
(when (null minimal-elements)
(if (null remaining-elements)
(return-from topological-sort result)
(error "Closette compiler: Inconsistent precedence graph.")))
(let ((choice (if (null (cdr minimal-elements))
(car minimal-elements)
(funcall tie-breaker
minimal-elements
result))))
(setq result (append result (list choice)))
(setq remaining-elements
(remove choice remaining-elements))
(setq remaining-constraints
(remove choice
remaining-constraints
:test #'member)))))))
the CLOS Specification says to " select the one that has a direct subclass
from right to left , looking for the first minimal element to show up among
the direct superclasses of the class precedence list constituent .
(defun std-tie-breaker-rule (minimal-elements cpl-so-far)
(dolist (cpl-constituent (reverse cpl-so-far))
(let* ((supers (class-direct-superclasses cpl-constituent))
(common (intersection minimal-elements supers)))
(when (not (null common))
(return-from std-tie-breaker-rule (car common))))))
(defun collect-superclasses* (class)
(labels ((all-superclasses-loop (seen superclasses)
(let ((to-be-processed (set-difference superclasses seen)))
(if (null to-be-processed)
superclasses
(let ((class-to-process (car to-be-processed)))
(all-superclasses-loop (cons class-to-process seen)
(union (class-direct-superclasses class-to-process)
superclasses)))))))
(all-superclasses-loop () (list class))))
The local precedence ordering of a class C with direct superclasses C_1 ,
(defun local-precedence-ordering (class)
(mapcar #'list
(cons class
(butlast (class-direct-superclasses class)))
(class-direct-superclasses class)))
(defun std-compute-slots (class)
(let* ((all-slots (mapcan (lambda (c)
(copy-list (class-direct-slots c)))
(reverse (class-precedence-list class))))
(all-names (remove-duplicates (mapcar #'slot-definition-name all-slots)))
(effective-slots (mapcar #'(lambda (name)
(funcall (if (or (eq (movitz-class-of class)
*the-class-standard-class*)
(subclassp (movitz-class-of class)
(movitz-find-class 'std-slotted-class)))
#'std-compute-effective-slot-definition
#'compute-effective-slot-definition)
class
name
(remove name all-slots
:key #'slot-definition-name
:test (complement #'eq))))
all-names)))
(loop for i upfrom 0 as slot in effective-slots
do (setf (slot-definition-location slot) i))
effective-slots))
(defun compute-slots (class)
(error "Don't know how to compute-slots for class ~S of class ~S."
class (class-of class)))
(defun std-compute-effective-slot-definition (class name direct-slots)
(declare (ignore name))
(let ((initer (find-if-not #'null direct-slots
:key #'slot-definition-initfunction)))
(make-effective-slot-definition (movitz-class-name class)
:name (slot-definition-name (car direct-slots))
:initform (if initer
(slot-definition-initform initer)
nil)
:initfunction (if initer
(slot-definition-initfunction initer)
nil)
:initargs (remove-duplicates
(mapappend #'slot-definition-initargs
direct-slots))
:allocation (slot-definition-allocation (car direct-slots)))))
(defun compute-effective-slot-definition (class name direct-slots)
(declare (ignore name direct-slots))
(error "Don't know how to compute-effective-slot-definition for class ~S of class ~S."
class (class-of class)))
Generic function metaobjects and standard - generic - function
(defun generic-function-name (gf)
(slot-value gf 'movitz::name)
#+ignore (movitz-slot-value gf 'name))
(defun (setf generic-function-name) (new-value gf)
(setf (slot-value gf 'movitz::name) new-value))
(defun generic-function-lambda-list (gf)
(slot-value gf 'movitz::lambda-list)
#+ignore (movitz-slot-value gf 'lambda-list))
(defun (setf generic-function-lambda-list) (new-value gf)
(setf (slot-value gf 'movitz::lambda-list)
new-value))
(defun generic-function-methods (gf)
(movitz-slot-value gf 'methods))
(defun (setf generic-function-methods) (new-value gf)
(setf (movitz-slot-value gf 'methods) new-value))
(defun generic-function-method-combination (gf)
(movitz-slot-value gf 'method-combination))
(defun (setf generic-function-method-combination) (new-value gf)
(setf (movitz-slot-value gf 'method-combination) new-value))
(defun generic-function-discriminating-function (gf)
(slot-value gf 'movitz::standard-gf-function))
(defun (setf generic-function-discriminating-function) (new-value gf)
(setf (slot-value gf 'movitz::standard-gf-function) new-value))
(defun generic-function-method-class (gf)
(movitz-slot-value gf 'method-class))
(defun (setf generic-function-method-class) (new-value gf)
(setf (movitz-slot-value gf 'method-class) new-value))
(defun classes-to-emf-table (gf)
(slot-value gf 'movitz::classes-to-emf-table)
#+ignore (movitz-slot-value gf 'classes-to-emf-table))
(defun (setf classes-to-emf-table) (new-value gf)
(setf (slot-value gf 'movitz::classes-to-emf-table) new-value)
#+ignore (setf (movitz-slot-value gf 'classes-to-emf-table) new-value))
(defun num-required-arguments (gf)
(slot-value gf 'movitz::num-required-arguments))
(defun method-lambda-list (method)
(movitz-slot-value method 'lambda-list))
(defun (setf method-lambda-list) (new-value method)
(setf (movitz-slot-value method 'lambda-list) new-value))
(defun movitz-method-qualifiers (method)
(movitz-slot-value method 'qualifiers))
(defun (setf movitz-method-qualifiers) (new-value method)
(setf (movitz-slot-value method 'qualifiers) new-value))
(defun method-specializers (method)
(movitz-slot-value method 'specializers))
(defun (setf method-specializers) (new-value method)
(setf (movitz-slot-value method 'specializers) new-value))
(defun method-body (method)
(movitz-slot-value method 'body))
(defun (setf method-body) (new-value method)
(setf (movitz-slot-value method 'body) new-value))
(defun method-declarations (method)
(movitz-slot-value method 'declarations))
(defun (setf method-declarations) (new-value method)
(setf (movitz-slot-value method 'declarations) new-value))
(defun method-environment (method)
(movitz-slot-value method 'environment))
(defun (setf method-environment) (new-value method)
(setf (movitz-slot-value method 'environment) new-value))
(defun method-generic-function (method)
(movitz-slot-value method 'generic-function))
(defun (setf method-generic-function) (new-value method)
(setf (movitz-slot-value method 'generic-function) new-value))
(defun method-function (method) (movitz-slot-value method 'function))
(defun (setf method-function) (new-value method)
(setf (movitz-slot-value method 'function) new-value))
(defun method-optional-arguments-p (method) (movitz-slot-value method 'optional-arguments-p))
(defun (setf method-optional-arguments-p) (new-value method)
(setf (movitz-slot-value method 'optional-arguments-p) new-value))
(defmacro movitz-defgeneric (function-name lambda-list &rest options)
`(movitz-ensure-generic-function ',function-name
:lambda-list ',lambda-list
,@(canonicalize-defgeneric-options options)))
(defun canonicalize-defgeneric-options (options)
(mapappend #'canonicalize-defgeneric-option options))
(defun canonicalize-defgeneric-option (option)
(case (car option)
(declare nil)
(:generic-function-class
(list ':generic-function-class
`(movitz-find-class ',(cadr option))))
(:method-class
(list ':method-class
`(movitz-find-class ',(cadr option))))
(:method nil)
(t (list `',(car option) `',(cadr option)))))
(defun movitz-ensure-generic-function (function-name &rest all-keys
&key (generic-function-class (movitz-find-class 'standard-generic-function))
lambda-list (no-clos-fallback nil ncf-p)
(method-class (movitz-find-class 'standard-method))
&allow-other-keys)
(declare (dynamic-extent all-keys))
(let ((function-name (muerte::translate-program function-name :cl :muerte.cl))
(remove-old-p nil))
(let ((gf (movitz::movitz-env-named-function function-name)))
(with-simple-restart (nil "Remove the old definition for ~S." function-name)
(when gf
(assert (typep gf 'movitz::movitz-funobj-standard-gf) ()
"There is already a non-generic function-definition for ~S of type ~S."
function-name (type-of gf))
(assert (= (length (getf (analyze-lambda-list lambda-list)
:required-args))
(num-required-arguments gf))
() "The lambda-list ~S doesn't match the old generic function's lambda-list ~S."
lambda-list (generic-function-lambda-list gf))))
(when (and gf (or (not (typep gf 'movitz::movitz-funobj-standard-gf))
(not (= (length (getf (analyze-lambda-list lambda-list)
:required-args))
(num-required-arguments gf)))))
(setf remove-old-p t)))
(let ((gf (or (and (not remove-old-p)
(movitz::movitz-env-named-function function-name))
(let ((gf (apply (if (eq generic-function-class
(movitz-find-class 'standard-generic-function))
#'make-instance-standard-generic-function
#'movitz-make-instance)
generic-function-class
:name function-name
:method-class method-class
(muerte::translate-program all-keys :cl :muerte.cl))))
(setf (movitz::movitz-env-named-function function-name) gf)
gf))))
(when ncf-p
(setf (getf (slot-value gf 'movitz::plist) :no-clos-fallback)
no-clos-fallback)
(finalize-generic-function gf))
gf)))
(defun finalize-generic-function (gf)
(setf (movitz::movitz-env-named-function (generic-function-name gf)) gf)
(setf (classes-to-emf-table gf) nil)
(setf (movitz::standard-gf-function gf)
'initial-discriminating-function)
(let ((ncf (getf (slot-value gf 'movitz::plist) :no-clos-fallback)))
(cond
((not ncf))
((member ncf '(:unspecialized-method t))
(let ((m (find-if (lambda (method)
(every (lambda (specializer)
(eq specializer
(movitz-find-class t)))
(method-specializers method)))
(generic-function-methods gf))))
(setf (classes-to-emf-table gf)
(if m (method-function m) 'no-unspecialized-fallback))))
((symbolp ncf)
(setf (classes-to-emf-table gf)
ncf))
((and (listp ncf) (eq 'muerte.cl:setf (car ncf)))
(setf (classes-to-emf-table gf)
(movitz::movitz-env-setf-operator-name (cadr ncf))))
(t (error "Unknown ncf."))))
#+ignore
(let ((eql-specializer-table (or (slot-value gf 'movitz::eql-specializer-table)
(make-hash-table :test #'eql))))
(clrhash eql-specializer-table)
(dolist (method (generic-function-methods gf))
(dolist (specializer (method-specializers method))
(when (eq (movitz-find-class 'eql-specializer)
(movitz-class-of specializer))
(setf (gethash (movitz-slot-value specializer 'object)
eql-specializer-table)
specializer))))
(setf (slot-value gf 'movitz::eql-specializer-table)
(if (plusp (hash-table-count eql-specializer-table))
eql-specializer-table
nil)))
(values))
(defun make-instance-standard-generic-function (generic-function-class
&key name lambda-list method-class method-combination
no-clos-fallback
documentation)
(declare (ignore documentation no-clos-fallback method-combination))
(assert (not (null lambda-list)) (lambda-list)
"Can't make a generic function with nil lambda-list.")
(let ((gf (std-allocate-gf-instance generic-function-class
:name name
:lambda-list lambda-list
:num-required-arguments
(length (getf (analyze-lambda-list lambda-list)
:required-args)))))
(setf (generic-function-name gf) name
(generic-function-lambda-list gf) lambda-list
(generic-function-methods gf) ()
(generic-function-method-class gf) method-class
(generic-function-method-combination gf) *the-standard-method-combination*)
(finalize-generic-function gf)
gf))
(defmacro movitz-defmethod (&rest args)
(multiple-value-bind (function-name qualifiers lambda-list specializers body declarations documentation)
(parse-defmethod args)
(declare (ignore documentation declarations body))
`(ensure-method (movitz::movitz-env-named-function ',function-name)
:lambda-list ',lambda-list
:qualifiers ',qualifiers
:specializers ,(canonicalize-specializers specializers)
)))
(defun canonicalize-specializers (specializers)
`(list ,@(mapcar #'canonicalize-specializer specializers)))
(defun canonicalize-specializer (specializer)
`(find-specializer ',specializer))
(defun parse-defmethod (args)
(let ((fn-spec (car args))
(qualifiers ())
(specialized-lambda-list nil)
(decl-doc-body ())
(parse-state :qualifiers))
(dolist (arg (cdr args))
(ecase parse-state
(:qualifiers
(if (and (atom arg) (not (null arg)))
(push-on-end arg qualifiers)
(progn (setq specialized-lambda-list arg)
(setq parse-state :body))))
(:body (push-on-end arg decl-doc-body))))
(multiple-value-bind (body declarations documentation)
(movitz::parse-docstring-declarations-and-body decl-doc-body 'cl:declare)
(values fn-spec
qualifiers
(extract-lambda-list specialized-lambda-list)
(extract-specializers specialized-lambda-list)
(list* 'block
(if (consp fn-spec)
(cadr fn-spec)
fn-spec)
body)
declarations
documentation))))
(defun required-portion (gf args)
(let ((number-required (length (gf-required-arglist gf))))
(when (< (length args) number-required)
(error "Closette compiler: Too few arguments to generic function ~S." gf))
(subseq args 0 number-required)))
(defun gf-required-arglist (gf)
(let ((plist (analyze-lambda-list (generic-function-lambda-list gf))))
(getf plist ':required-args)))
(defun extract-lambda-list (specialized-lambda-list)
(let* ((plist (analyze-lambda-list specialized-lambda-list))
(requireds (getf plist ':required-names))
(rv (getf plist ':rest-var))
(ks (getf plist ':key-args))
(aok (getf plist ':allow-other-keys))
(opts (getf plist ':optional-args))
(auxs (getf plist ':auxiliary-args)))
`(,@requireds
,@(if rv `(&rest ,rv) ())
,@(if (or ks aok) `(&key ,@ks) ())
,@(if aok '(&allow-other-keys) ())
,@(if opts `(&optional ,@opts) ())
,@(if auxs `(&aux ,@auxs) ()))))
(defun extract-specializers (specialized-lambda-list)
(let ((plist (analyze-lambda-list specialized-lambda-list)))
(getf plist ':specializers)))
(defun analyze-lambda-list (lambda-list)
(labels ((make-keyword (symbol)
(intern (symbol-name symbol)
(find-package 'keyword)))
(get-keyword-from-arg (arg)
(if (listp arg)
(if (listp (car arg))
(caar arg)
(make-keyword (car arg)))
(make-keyword arg))))
Keywords argument specs
(rest-var nil)
(optionals ())
(auxs ())
(allow-other-keys nil)
(state :parsing-required))
(dolist (arg (translate-program lambda-list :muerte.cl :cl))
(if (member arg lambda-list-keywords)
(ecase arg
(&optional
(setq state :parsing-optional))
(&rest
(setq state :parsing-rest))
(&key
(setq state :parsing-key))
(&allow-other-keys
(setq allow-other-keys 't))
(&aux
(setq state :parsing-aux)))
(case state
(:parsing-required
(push-on-end arg required-args)
(if (listp arg)
(progn (push-on-end (car arg) required-names)
(push-on-end (cadr arg) specializers))
(progn (push-on-end arg required-names)
(push-on-end 't specializers))))
(:parsing-optional (push-on-end arg optionals))
(:parsing-rest (setq rest-var arg))
(:parsing-key
(push-on-end (get-keyword-from-arg arg) keys)
(push-on-end arg key-args))
(:parsing-aux (push-on-end arg auxs)))))
(translate-program (list :required-names required-names
:required-args required-args
:specializers specializers
:rest-var rest-var
:keywords keys
:key-args key-args
:auxiliary-args auxs
:optional-args optionals
:allow-other-keys allow-other-keys)
:cl :muerte.cl))))
(defun ensure-method (gf &rest all-keys &key lambda-list &allow-other-keys)
(declare (dynamic-extent all-keys))
(assert (= (length (getf (analyze-lambda-list lambda-list)
:required-args))
(num-required-arguments gf))
() "The method's lambda-list ~S doesn't match the gf's lambda-list ~S."
lambda-list (generic-function-lambda-list gf))
(let ((new-method (apply (if (eq (generic-function-method-class gf)
(movitz-find-class 'standard-method))
#'make-instance-standard-method
#'make-instance)
gf
:name (generic-function-name gf)
all-keys)))
(movitz-add-method gf new-method)
new-method))
(defun make-instance-standard-method (gf &key (method-class 'standard-method) name lambda-list qualifiers
specializers body declarations environment slot-definition)
(let ((method (std-allocate-instance (movitz-find-class method-class))))
(movitz-method-qualifiers method) qualifiers
(method-specializers method) specializers
(method-generic-function method) nil
(method-optional-arguments-p method) (let ((analysis (analyze-lambda-list lambda-list)))
(if (or (getf analysis :optional-args)
(getf analysis :key-args)
(getf analysis :rest-var))
t nil))
(method-function method) (std-compute-method-function method name gf environment
lambda-list declarations body))
(when slot-definition
(setf (movitz-slot-value method 'slot-definition) slot-definition))
method))
with the same qualifiers and specializers . It 's a pain to develop
programs without this feature of full CLOS .
(defun movitz-add-method (gf method)
(let ((old-method (movitz-find-method gf (movitz-method-qualifiers method)
(method-specializers method) nil)))
(when old-method (movitz-remove-method gf old-method)))
(setf (method-generic-function method) gf)
(push method (generic-function-methods gf))
(dolist (specializer (method-specializers method))
(when (subclassp (movitz-class-of specializer) (movitz-find-class 'class))
(pushnew method (class-direct-methods specializer))))
(finalize-generic-function gf)
method)
(defun movitz-remove-method (gf method)
(setf (generic-function-methods gf)
(remove method (generic-function-methods gf)))
(setf (method-generic-function method) nil)
(dolist (specializer (method-specializers method))
(when (subclassp (movitz-class-of specializer) (movitz-find-class 'class))
(setf (class-direct-methods specializer)
(remove method (class-direct-methods specializer)))))
(finalize-generic-function gf)
method)
(defun movitz-find-method (gf qualifiers specializers &optional (errorp t))
(let ((method (find-if (lambda (method)
(and (equal qualifiers
(movitz-method-qualifiers method))
(equal specializers
(method-specializers method))))
(generic-function-methods gf))))
(if (and (null method) errorp)
(error "Closette compiler: No method for ~S matching ~S~@[ qualifiers ~S~]."
(generic-function-name gf)
specializers
qualifiers)
method)))
(defun add-reader-method (class fn-name slot-name)
(ensure-method (movitz-ensure-generic-function fn-name :lambda-list '(object))
:method-class 'standard-reader-method
:slot-definition (find slot-name (std-slot-value class 'direct-slots)
:key 'slot-definition-name)
:lambda-list '(object)
:qualifiers ()
:specializers (list class)
:environment (top-level-environment))
(values))
(defun add-writer-method (class fn-name slot-name)
(ensure-method (movitz-ensure-generic-function fn-name :lambda-list '(new-value object))
:method-class 'standard-writer-method
:lambda-list '(new-value object)
:slot-definition (find slot-name (std-slot-value class 'direct-slots)
:key 'slot-definition-name)
:qualifiers ()
:specializers (list (movitz-find-class 't) class)
new-value)
:environment (top-level-environment))
(values))
Generic function invocation
(defun apply-generic-function (gf args)
(apply (generic-function-discriminating-function gf) args))
(defun std-compute-discriminating-function (gf)
(declare (ignore gf))
'discriminating-function
#+ignore
(movitz::make-compiled-funobj 'discriminating-function
(muerte::translate-program
'(&edx gf &rest args) :cl :muerte.cl)
(muerte::translate-program
'((dynamic-extent args)) :cl :muerte.cl)
(muerte::translate-program
`(apply #'std-discriminating-function gf args args)
#+ignore
`(let* ((requireds (subseq args 0 (length (gf-required-arglist ,gf))))
(classes (map-into requireds #'class-of requireds))
(emfun (gethash classes (classes-to-emf-table ,gf) nil)))
(if emfun
(funcall emfun args)
(slow-method-lookup ,gf args classes)))
#+ignore
`(let ((requireds (subseq args 0 (length (gf-required-arglist ,gf)))))
(slow-method-lookup ,gf args (map-into requireds #'class-of requireds)))
:cl :muerte.cl)
nil nil))
(defun slow-method-lookup (gf args classes)
(let* ((applicable-methods (compute-applicable-methods-using-classes gf classes))
(emfun (funcall (if (eq (movitz-class-of gf) (movitz-find-class 'standard-generic-function))
#'std-compute-effective-method-function
#'compute-effective-method-function)
gf applicable-methods)))
(setf (gethash classes (classes-to-emf-table gf)) emfun)
(funcall emfun args)))
(defun compute-applicable-methods-using-classes (gf required-classes)
(sort (copy-list (remove-if-not #'(lambda (method)
(every #'subclassp
required-classes
(method-specializers method)))
(generic-function-methods gf)))
(lambda (m1 m2)
(funcall (if (eq (movitz-class-of gf) (movitz-find-class 'standard-generic-function))
#'std-method-more-specific-p
#'method-more-specific-p)
gf m1 m2 required-classes))))
(defun std-method-more-specific-p (gf method1 method2 required-classes)
"When applying arguments of <required-classes> to <gf>, which of <method1>
and <method2> is more specific?"
(declare (ignore gf))
# + movitz ( loop
for spec1 in ( method - specializers method1 )
(mapc #'(lambda (spec1 spec2 arg-class)
(unless (eq spec1 spec2)
(return-from std-method-more-specific-p
(sub-specializer-p spec1 spec2 arg-class))))
(method-specializers method1)
(method-specializers method2)
required-classes)
nil)
#+ignore
(defun apply-methods (gf args methods)
(funcall (compute-effective-method-function gf methods)
args))
(defun primary-method-p (method)
(null (movitz-method-qualifiers method)))
(defun before-method-p (method)
(equal '(:before) (movitz-method-qualifiers method)))
(defun after-method-p (method)
(equal '(:after) (movitz-method-qualifiers method)))
(defun around-method-p (method)
(equal '(:around) (movitz-method-qualifiers method)))
#+ignore
(defun std-compute-effective-method-function (gf methods)
(let ((primaries (remove-if-not #'primary-method-p methods))
(around (find-if #'around-method-p methods)))
(when (null primaries)
(error "Closette compiler: No primary methods for the generic function ~S." gf))
(if around
(let ((next-emfun (funcall (if (eq (movitz-class-of gf) (movitz-find-class 'standard-generic-function))
#'std-compute-effective-method-function
#'compute-effective-method-function)
gf (remove around methods))))
`(lambda (args)
(funcall (method-function ,around) args ,next-emfun)))
(let ((next-emfun (compute-primary-emfun (cdr primaries)))
(befores (remove-if-not #'before-method-p methods))
(reverse-afters
(reverse (remove-if-not #'after-method-p methods))))
`(lambda (args)
(dolist (before ',befores)
(funcall (method-function before) args nil))
(multiple-value-prog1
(funcall (method-function ,(car primaries)) args ,next-emfun)
(dolist (after ',reverse-afters)
(funcall (method-function after) args nil))))))))
#+ignore
(defun compute-primary-emfun (methods)
(if (null methods)
nil
(let ((next-emfun (compute-primary-emfun (cdr methods))))
'(lambda (args)
(funcall (method-function (car methods)) args next-emfun)))))
#+ignore
(defun apply-method (method args next-methods)
(funcall (method-function method)
args
(if (null next-methods)
nil
(compute-effective-method-function
(method-generic-function method) next-methods))))
(defun std-compute-method-function (method name gf env lambda-list declarations body)
(let* ((block-name (compute-function-block-name name))
(analysis (analyze-lambda-list lambda-list))
(lambda-variables (append (getf analysis :required-args)
(mapcar #'decode-optional-formal
(getf analysis :optional-args))
(mapcar #'decode-keyword-formal
(getf analysis :key-args))
(when (getf analysis :rest-var)
(list (getf analysis :rest-var)))))
(required-variables (subseq lambda-variables
0 (num-required-arguments gf)))
(funobj
(compile-in-lexical-environment
env
(translate-program (nconc (list 'method name)
(copy-list (movitz-method-qualifiers method))
(list (mapcar #'specializer-name (method-specializers method))))
:cl :muerte.cl)
(if (movitz::tree-search body '(call-next-method next-method-p))
`(lambda ,lambda-list
(declare (ignorable ,@required-variables)
,@(mapcan (lambda (declaration)
(case (car declaration)
(dynamic-extent
(list declaration))
(ignore
(list (cons 'ignorable (cdr declaration))))))
declarations))
(let ((next-emf 'proto-next-emf))
(declare (ignorable next-emf))
(setf next-emf 'proto-next-emf)
(flet ((call-next-method (&rest cnm-args)
(declare (dynamic-extent cnm-args))
(if (not (functionp next-emf))
(if cnm-args
(apply 'no-next-method ,gf ,method cnm-args)
(no-next-method ,gf ,method ,@lambda-variables))
(if cnm-args
(apply next-emf cnm-args)
(funcall next-emf ,@lambda-variables)))))
(declare (ignorable call-next-method))
(block ,block-name
(let ,(mapcar #'list lambda-variables lambda-variables)
(declare (ignorable ,@required-variables)
,@declarations)
,body)))))
`(lambda ,lambda-list
(declare (ignorable ,@required-variables)
,@declarations)
(block ,block-name
,body))))))
(setf (slot-value funobj 'movitz::funobj-type) :method-function)
funobj))
(defun kludge-arglist (lambda-list)
(if (and (member '&key lambda-list)
(not (member '&allow-other-keys lambda-list)))
(append lambda-list '(&allow-other-keys))
(if (and (not (member '&rest lambda-list))
(not (member '&key lambda-list)))
(append lambda-list '(&key &allow-other-keys))
lambda-list)))
(defun top-level-environment ()
(defun compile-in-lexical-environment (env name lambda-expr)
(declare (ignore env))
(destructuring-bind (operator lambda-list &body decl-doc-body)
lambda-expr
(assert (eq 'lambda operator) (lambda-expr)
"Closette compiler: Lambda wasn't lambda.")
(multiple-value-bind (body declarations)
(movitz::parse-docstring-declarations-and-body decl-doc-body 'cl:declare)
(movitz::make-compiled-funobj name
(translate-program lambda-list :cl :muerte.cl)
(translate-program declarations :cl :muerte.cl)
(translate-program (cons 'muerte.cl:progn body) :cl :muerte.cl)
nil nil))))
(defun bootstrap-closette ()
(setf *classes-with-old-slot-definitions* nil)
(forget-all-classes)
How to create the class hierarchy in 10 easy steps :
1 . Figure out standard - class 's slots .
(setq *the-slots-of-standard-class*
(mapcar (lambda (slotd)
(make-effective-slot-definition
(movitz::translate-program 'standard-class :cl :muerte.cl)
:name (car slotd)
:initargs (let ((a (getf (cdr slotd) :initarg)))
(if a (list a) ()))
:initform (getf (cdr slotd) :initform)
:initfunction (getf (cdr slotd) :initform)
:allocation :instance))
(nth 3 +the-defclass-standard-class+))))
(loop for s in *the-slots-of-standard-class* as i upfrom 0
do (setf (slot-definition-location s) i))
(setq *the-position-of-standard-effective-slots*
(position 'effective-slots *the-slots-of-standard-class*
:key #'slot-definition-name))
2 . Create the standard - class metaobject by hand .
(setq *the-class-standard-class*
(allocate-std-instance 'tba (make-array (length *the-slots-of-standard-class*)
:initial-element (movitz::unbound-value))))
3 . Install standard - class 's ( circular ) class - of link .
(setf (std-instance-class *the-class-standard-class*)
*the-class-standard-class*)
4 . Fill in standard - class 's class - slots .
(setf (class-slots *the-class-standard-class*) *the-slots-of-standard-class*)
5 . Hand build the class t so that it has no direct superclasses .
(setf (movitz-find-class 't)
(let ((class (std-allocate-instance *the-class-standard-class*)))
(setf (movitz-class-name class) 't)
(setf (class-direct-subclasses class) ())
(setf (class-direct-superclasses class) ())
(setf (class-direct-methods class) ())
(setf (class-direct-slots class) ())
(setf (class-precedence-list class) (list class))
(setf (class-slots class) ())
(setf (class-direct-methods class) nil)
class))
6 . Create the other superclass of standard - class ( i.e. , standard - object ) .
(defclass-los standard-object (t) ())
7 . Define the full - blown version of class and standard - class .
( warn " step 7 ... " )
(eval +the-defclasses-before-class+)
(eval +the-defclass-std-slotted-class+)
(eval +the-defclass-instance-slotted-class+)
(setf (movitz-find-class 'standard-class)
*the-class-standard-class*)
(setf (class-precedence-list *the-class-standard-class*)
(std-compute-class-precedence-list *the-class-standard-class*))
8 . Replace all ( x .. ) existing pointers to the skeleton with real one .
(defclass-los built-in-class (class)
((size :initarg :size)
(slot-map :initarg :slot-map)))
(let ((t-prototype (make-instance-built-in-class 'built-in-class :name t :direct-superclasses nil)))
(setf (std-instance-class (movitz-find-class t)) (std-instance-class t-prototype)
(std-instance-slots (movitz-find-class t)) (std-instance-slots t-prototype)
(class-precedence-list (movitz-find-class t)) (std-compute-class-precedence-list (movitz-find-class t))))
(eval +the-defclasses-slots+)
(eval +the-defclass-standard-direct-slot-definition+)
( warn " classes with old defs : ~S " * classes - with - old - slot - definitions * )
(dolist (class-name *classes-with-old-slot-definitions*)
(let ((class (movitz-find-class class-name)))
(setf (std-slot-value class 'direct-slots)
(mapcar #'translate-direct-slot-definition
(std-slot-value class 'direct-slots)))
(setf (std-slot-value class 'effective-slots)
(loop for position upfrom 0
as slot in (std-slot-value class 'effective-slots)
as slot-name = (slot-definition-name slot)
do (if (slot-definition-location slot)
(assert (= (slot-definition-location slot) position))
(setf (slot-definition-location slot) position))
collect (translate-effective-slot-definition slot)
do (setf (movitz::movitz-env-get class-name slot-name) position)))))
(map-into *the-slots-of-standard-class*
#'translate-effective-slot-definition
*the-slots-of-standard-class*)
#+ignore (format t "~&;; Closette bootstrap completed."))
9 . Define the other built - in classes .
(when (zerop (hash-table-count *class-table*))
(bootstrap-closette)))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.