_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 |
|---|---|---|---|---|---|---|---|---|
97e8b2754db18ec9ce8b1bfa6c6813476e96b65b212bc160c22c0ca489b3a313 | yzhs/ocamlllvm | complex.mli | (***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 2002 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
(* the special exception on linking described in file ../LICENSE. *)
(* *)
(***********************************************************************)
$ Id$
(** Complex numbers.
This module provides arithmetic operations on complex numbers.
Complex numbers are represented by their real and imaginary parts
(cartesian representation). Each part is represented by a
double-precision floating-point number (type [float]). *)
type t = { re: float; im: float }
(** The type of complex numbers. [re] is the real part and [im] the
imaginary part. *)
val zero: t
(** The complex number [0]. *)
val one: t
* The complex number [ 1 ] .
val i: t
(** The complex number [i]. *)
val neg: t -> t
(** Unary negation. *)
val conj: t -> t
(** Conjugate: given the complex [x + i.y], returns [x - i.y]. *)
val add: t -> t -> t
(** Addition *)
val sub: t -> t -> t
(** Subtraction *)
val mul: t -> t -> t
(** Multiplication *)
val inv: t -> t
(** Multiplicative inverse ([1/z]). *)
val div: t -> t -> t
(** Division *)
val sqrt: t -> t
(** Square root. The result [x + i.y] is such that [x > 0] or
[x = 0] and [y >= 0].
This function has a discontinuity along the negative real axis. *)
val norm2: t -> float
(** Norm squared: given [x + i.y], returns [x^2 + y^2]. *)
val norm: t -> float
* Norm : given [ x + i.y ] , returns [ sqrt(x^2 + y^2 ) ] .
val arg: t -> float
* Argument . The argument of a complex number is the angle
in the complex plane between the positive real axis and a line
passing through zero and the number . This angle ranges from
[ -pi ] to [ pi ] . This function has a discontinuity along the
negative real axis .
in the complex plane between the positive real axis and a line
passing through zero and the number. This angle ranges from
[-pi] to [pi]. This function has a discontinuity along the
negative real axis. *)
val polar: float -> float -> t
(** [polar norm arg] returns the complex having norm [norm]
and argument [arg]. *)
val exp: t -> t
(** Exponentiation. [exp z] returns [e] to the [z] power. *)
val log: t -> t
(** Natural logarithm (in base [e]). *)
val pow: t -> t -> t
(** Power function. [pow z1 z2] returns [z1] to the [z2] power. *)
| null | https://raw.githubusercontent.com/yzhs/ocamlllvm/45cbf449d81f2ef9d234968e49a4305aaa39ace2/src/stdlib/complex.mli | ocaml | *********************************************************************
Objective Caml
the special exception on linking described in file ../LICENSE.
*********************************************************************
* Complex numbers.
This module provides arithmetic operations on complex numbers.
Complex numbers are represented by their real and imaginary parts
(cartesian representation). Each part is represented by a
double-precision floating-point number (type [float]).
* The type of complex numbers. [re] is the real part and [im] the
imaginary part.
* The complex number [0].
* The complex number [i].
* Unary negation.
* Conjugate: given the complex [x + i.y], returns [x - i.y].
* Addition
* Subtraction
* Multiplication
* Multiplicative inverse ([1/z]).
* Division
* Square root. The result [x + i.y] is such that [x > 0] or
[x = 0] and [y >= 0].
This function has a discontinuity along the negative real axis.
* Norm squared: given [x + i.y], returns [x^2 + y^2].
* [polar norm arg] returns the complex having norm [norm]
and argument [arg].
* Exponentiation. [exp z] returns [e] to the [z] power.
* Natural logarithm (in base [e]).
* Power function. [pow z1 z2] returns [z1] to the [z2] power. | , projet Cristal , INRIA Rocquencourt
Copyright 2002 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
$ Id$
type t = { re: float; im: float }
val zero: t
val one: t
* The complex number [ 1 ] .
val i: t
val neg: t -> t
val conj: t -> t
val add: t -> t -> t
val sub: t -> t -> t
val mul: t -> t -> t
val inv: t -> t
val div: t -> t -> t
val sqrt: t -> t
val norm2: t -> float
val norm: t -> float
* Norm : given [ x + i.y ] , returns [ sqrt(x^2 + y^2 ) ] .
val arg: t -> float
* Argument . The argument of a complex number is the angle
in the complex plane between the positive real axis and a line
passing through zero and the number . This angle ranges from
[ -pi ] to [ pi ] . This function has a discontinuity along the
negative real axis .
in the complex plane between the positive real axis and a line
passing through zero and the number. This angle ranges from
[-pi] to [pi]. This function has a discontinuity along the
negative real axis. *)
val polar: float -> float -> t
val exp: t -> t
val log: t -> t
val pow: t -> t -> t
|
696a371b89c4dc0f6107e906fcefb7c3caf0fcde7cc74887294438d0b7dba0c2 | kostyushkin/erlworld | mover_state.erl |
%%%
%%% mover_state
%%%
%%% @doc A module that builds on top of the actor_state module.
%%% It adds some common movement code for moving the actor state around.
%%%
-module( mover_state ).
-author("Joseph Lenton").
-include("mover_state.hrl").
-include("blastox.hrl").
-export([
new/4
, new/5
, new_paint/0
, set_xy/2, set_xy/3
, move/2, move/3
, act_move/2
, act_turn/4
, get_angle/1
, get_img/1
, limit_xy/1
, speed_to_xy/2
]).
%%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%%
%%% Construction
%%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%%
%% new
%%
%% @doc The same as the other new function, only with no properties.
@spec new ( Name::atom ( ) , StartXY : : { number ( ) , number ( ) } , ( ) , Img::image ( ) ) - > mover_state ( )
new( Name, StartXY, StartAngle, Img ) ->
new( Name, StartXY, StartAngle, Img, [] ).
%% new
%%
%% @doc Creates a new mover state at the location given.
%% It will store the image and the angle given using these for drawing. The
%% values in the properties list will also be added to the state.
%%
The StartAngle is in radians .
%%
@spec new ( Name::atom ( ) , StartXY : : { number ( ) , number ( ) } , ( ) , Img::image ( ) , Properties : : [ { Property::atom ( ) , Value::term ( ) } ] ) - > mover_state ( )
new( Name, StartXY, StartAngle, Img, Properties ) ->
actor_state:set(
actor_state:new(
Name,
StartXY,
image:get_size(Img),
[
{ ?ACTOR_IMG, Img },
{ ?ACTOR_ANGLE, StartAngle }
]
),
Properties
).
%% new_paint
%%
%% @doc Creates a fun that can be used for painting a mover_state.
new_paint ( ) - > ( AS::actor_state ( ) , ( ) ) - > ok
new_paint() ->
fun( AS, G ) ->
{X, Y} = actor_state:get_xy(AS),
Max = max( actor_state:get_size(AS) ),
Angle = get_angle(AS),
Img = get_img(AS),
if
(X < Max/2 ) -> graphics:draw_image_rotated( G, Img, {X+?WIDTH, Y}, Angle );
(X > ?WIDTH-(Max/2)) -> graphics:draw_image_rotated( G, Img, {X-?WIDTH, Y}, Angle );
true -> ok
end,
if
(Y < Max/2 ) -> graphics:draw_image_rotated( G, Img, {X, Y+?HEIGHT}, Angle );
(Y > ?HEIGHT-(Max/2)) -> graphics:draw_image_rotated( G, Img, {X, Y-?HEIGHT}, Angle );
true -> ok
end,
graphics:draw_image_rotated( G, Img, {X, Y}, Angle )
end.
%%
@doc The same as the built in function , but works on two numbers supplied as a tuple .
( { A::number ( ) , B::number ( ) } ) - > number ( )
max( {A, B} ) when A > B -> B;
max( {A, _B}) -> A.
%%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%%
%%% Acting
%%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%%
%% act_move
%%
%% @doc Moves the given mover_state by the speed given.
%% The angle it will travel in is the angle stored within it.
%%
@spec act_move ( AS::mover_state ( ) , Speed::number ( ) ) - > NewAS::mover_state ( )
act_move( AS, Speed ) ->
set_xy(
AS,
calculate_move( actor_state:get_xy(AS), Speed, get_angle(AS) )
).
%% move
%%
%% @doc Moves the actor state by the amount given, but the location is wrapped to within the display size.
@spec move ( AS::actor_state ( ) , X::number ( ) , Y::number ( ) ) - > NewAS::actor_state ( )
move( AS, X, Y ) ->
move( AS, {X, Y} ).
%% move
%%
%% @doc Moves the actor state by the amount given, but the location is wrapped to within the display size.
@spec move ( AS::actor_state ( ) , { X::number ( ) , Y::number ( ) } ) - > NewAS::actor_state ( )
move( AS, {X, Y} ) ->
{ X2, Y2 } = actor_state:get_xy(AS),
set_xy( AS, {X+X2, Y+Y2} ).
%% set_xy
%%
%% @doc The same as the other set_xy, only this takes the X and Y values seperately.
@spec set_xy ( AS::actor_state ( ) , X::number ( ) , Y::number ( ) ) - > NewAS::actor_state ( )
set_xy( AS, X, Y ) ->
set_xy( AS, {X, Y} ).
%% set_xy
%%
%% @doc Moves the mover_state to the location given, but wrapped within the displays size.
@spec set_xy ( AS::actor_state ( ) , XY : : { number ( ) , number ( ) } ) - > NewAS::actor_state ( )
set_xy( AS, XY ) ->
actor_state:set_xy(
AS,
limit_xy( XY )
).
%% calculate_move
%%
%% @doc Adds the speed and angle to the X and Y values given.
%% Essentially returning the result of moving from the X and Y values in the
%% angle given by the given speed. The angle is in radians.
%%
@spec calculate_move ( { X::number ( ) , Y::number ( ) } , Speed::number ( ) , Angle::number ( ) ) - > { NewX::number ( ) , NewY::number ( ) }
calculate_move( {X, Y}, Speed, Angle ) -> {X + Speed*math:cos(Angle), Y+Speed*math:sin(Angle) }.
%% speed_to_xy
%%
%% @doc Returns a tuple of the X and Y movement of moving in the given angle by the given speed.
%% The angle is in radians.
%%
@spec speed_to_xy ( Speed::number ( ) , Angle::number ( ) ) - > { X::number ( ) , Y::number ( ) }
speed_to_xy( Speed, Angle ) -> { Speed*math:cos(Angle), Speed*math:sin(Angle) }.
%% act_turn
%%
%% @doc Turns the given state left, right or not at all based on the values of left and right.
%% The result of turning (or not turning) is returned as a new mover_state.
%%
%% The amount to turn is a radian whilst the left and right values should be
%% booleans.
%%
( AS::mover_state ( ) , ( ) , Left::boolean ( ) , Right::boolean ( ) ) - > NewAS::mover_state ( )
act_turn( AS, Turn, Left, Right ) ->
actor_state:set( AS, ?ACTOR_ANGLE,
act_turn_inner(
get_angle( AS ),
Turn,
Left,
Right
)
).
%% act_turn_inner
%%
%% @doc Returns Angle plus or minus turn based on the values of Left and Right.
@spec act_turn_inner ( Angle::number ( ) , ( ) , Left::boolean ( ) , Right::boolean ( ) ) - > NewAngle::number ( )
act_turn_inner( Angle, _Turn, true, true ) -> Angle;
act_turn_inner( Angle, Turn, true, _Right ) -> Angle - Turn;
act_turn_inner( Angle, Turn, _Left, true ) -> Angle + Turn;
act_turn_inner( Angle, _Turn, _Left, _Right ) -> Angle.
limit_xy
%%
%% @doc Returns a tuple where the given X and Y values wrap around the width and height of the display.
( { X::number ( ) , Y::number ( ) } ) - > { NewX::number ( ) , NewY::number ( ) }
limit_xy( {X, Y} ) -> { limit(X, ?WIDTH), limit(Y, ?HEIGHT) }.
%% limit
%%
@doc Returns the given value but translated to between 0 and .
If val is bigger then then is returned , not max . Similar if
is less then 0 ; val+max is returned not 0 .
%%
If val is between 0 and then is returned unchanged .
%%
@spec limit ( Val::number ( ) , ( ) ) - > ( )
limit( Val, Max ) when Val > Max -> Val-Max;
limit( Val, Max ) when Val < 0 -> Val+Max;
limit( Val, _Max ) -> Val.
%%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%%
%%% Getters
%%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%%
%% get_img
%%
%% @doc Return the image to use when drawing this mover.
get_img ( AS::mover_state ( ) ) - > Image::image ( )
get_img(AS) -> actor_state:get( AS, ?ACTOR_IMG ).
get_angle
%%
%% @doc Returns the angle set in this mover, in radians.
( AS::mover_state ( ) ) - > Angle::number ( )
get_angle(AS) -> actor_state:get( AS, ?ACTOR_ANGLE ). | null | https://raw.githubusercontent.com/kostyushkin/erlworld/1c55c9eb0d12db9824144b4ff7535960c53e35c8/examples/Blastoxs/src/mover_state.erl | erlang |
mover_state
@doc A module that builds on top of the actor_state module.
It adds some common movement code for moving the actor state around.
%%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%%
Construction
%%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%%
new
@doc The same as the other new function, only with no properties.
new
@doc Creates a new mover state at the location given.
It will store the image and the angle given using these for drawing. The
values in the properties list will also be added to the state.
new_paint
@doc Creates a fun that can be used for painting a mover_state.
%%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%%
Acting
%%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%%
act_move
@doc Moves the given mover_state by the speed given.
The angle it will travel in is the angle stored within it.
move
@doc Moves the actor state by the amount given, but the location is wrapped to within the display size.
move
@doc Moves the actor state by the amount given, but the location is wrapped to within the display size.
set_xy
@doc The same as the other set_xy, only this takes the X and Y values seperately.
set_xy
@doc Moves the mover_state to the location given, but wrapped within the displays size.
calculate_move
@doc Adds the speed and angle to the X and Y values given.
Essentially returning the result of moving from the X and Y values in the
angle given by the given speed. The angle is in radians.
speed_to_xy
@doc Returns a tuple of the X and Y movement of moving in the given angle by the given speed.
The angle is in radians.
act_turn
@doc Turns the given state left, right or not at all based on the values of left and right.
The result of turning (or not turning) is returned as a new mover_state.
The amount to turn is a radian whilst the left and right values should be
booleans.
act_turn_inner
@doc Returns Angle plus or minus turn based on the values of Left and Right.
@doc Returns a tuple where the given X and Y values wrap around the width and height of the display.
limit
%%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%%
Getters
%%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%%
get_img
@doc Return the image to use when drawing this mover.
@doc Returns the angle set in this mover, in radians.
|
-module( mover_state ).
-author("Joseph Lenton").
-include("mover_state.hrl").
-include("blastox.hrl").
-export([
new/4
, new/5
, new_paint/0
, set_xy/2, set_xy/3
, move/2, move/3
, act_move/2
, act_turn/4
, get_angle/1
, get_img/1
, limit_xy/1
, speed_to_xy/2
]).
@spec new ( Name::atom ( ) , StartXY : : { number ( ) , number ( ) } , ( ) , Img::image ( ) ) - > mover_state ( )
new( Name, StartXY, StartAngle, Img ) ->
new( Name, StartXY, StartAngle, Img, [] ).
The StartAngle is in radians .
@spec new ( Name::atom ( ) , StartXY : : { number ( ) , number ( ) } , ( ) , Img::image ( ) , Properties : : [ { Property::atom ( ) , Value::term ( ) } ] ) - > mover_state ( )
new( Name, StartXY, StartAngle, Img, Properties ) ->
actor_state:set(
actor_state:new(
Name,
StartXY,
image:get_size(Img),
[
{ ?ACTOR_IMG, Img },
{ ?ACTOR_ANGLE, StartAngle }
]
),
Properties
).
new_paint ( ) - > ( AS::actor_state ( ) , ( ) ) - > ok
new_paint() ->
fun( AS, G ) ->
{X, Y} = actor_state:get_xy(AS),
Max = max( actor_state:get_size(AS) ),
Angle = get_angle(AS),
Img = get_img(AS),
if
(X < Max/2 ) -> graphics:draw_image_rotated( G, Img, {X+?WIDTH, Y}, Angle );
(X > ?WIDTH-(Max/2)) -> graphics:draw_image_rotated( G, Img, {X-?WIDTH, Y}, Angle );
true -> ok
end,
if
(Y < Max/2 ) -> graphics:draw_image_rotated( G, Img, {X, Y+?HEIGHT}, Angle );
(Y > ?HEIGHT-(Max/2)) -> graphics:draw_image_rotated( G, Img, {X, Y-?HEIGHT}, Angle );
true -> ok
end,
graphics:draw_image_rotated( G, Img, {X, Y}, Angle )
end.
@doc The same as the built in function , but works on two numbers supplied as a tuple .
( { A::number ( ) , B::number ( ) } ) - > number ( )
max( {A, B} ) when A > B -> B;
max( {A, _B}) -> A.
@spec act_move ( AS::mover_state ( ) , Speed::number ( ) ) - > NewAS::mover_state ( )
act_move( AS, Speed ) ->
set_xy(
AS,
calculate_move( actor_state:get_xy(AS), Speed, get_angle(AS) )
).
@spec move ( AS::actor_state ( ) , X::number ( ) , Y::number ( ) ) - > NewAS::actor_state ( )
move( AS, X, Y ) ->
move( AS, {X, Y} ).
@spec move ( AS::actor_state ( ) , { X::number ( ) , Y::number ( ) } ) - > NewAS::actor_state ( )
move( AS, {X, Y} ) ->
{ X2, Y2 } = actor_state:get_xy(AS),
set_xy( AS, {X+X2, Y+Y2} ).
@spec set_xy ( AS::actor_state ( ) , X::number ( ) , Y::number ( ) ) - > NewAS::actor_state ( )
set_xy( AS, X, Y ) ->
set_xy( AS, {X, Y} ).
@spec set_xy ( AS::actor_state ( ) , XY : : { number ( ) , number ( ) } ) - > NewAS::actor_state ( )
set_xy( AS, XY ) ->
actor_state:set_xy(
AS,
limit_xy( XY )
).
@spec calculate_move ( { X::number ( ) , Y::number ( ) } , Speed::number ( ) , Angle::number ( ) ) - > { NewX::number ( ) , NewY::number ( ) }
calculate_move( {X, Y}, Speed, Angle ) -> {X + Speed*math:cos(Angle), Y+Speed*math:sin(Angle) }.
@spec speed_to_xy ( Speed::number ( ) , Angle::number ( ) ) - > { X::number ( ) , Y::number ( ) }
speed_to_xy( Speed, Angle ) -> { Speed*math:cos(Angle), Speed*math:sin(Angle) }.
( AS::mover_state ( ) , ( ) , Left::boolean ( ) , Right::boolean ( ) ) - > NewAS::mover_state ( )
act_turn( AS, Turn, Left, Right ) ->
actor_state:set( AS, ?ACTOR_ANGLE,
act_turn_inner(
get_angle( AS ),
Turn,
Left,
Right
)
).
@spec act_turn_inner ( Angle::number ( ) , ( ) , Left::boolean ( ) , Right::boolean ( ) ) - > NewAngle::number ( )
act_turn_inner( Angle, _Turn, true, true ) -> Angle;
act_turn_inner( Angle, Turn, true, _Right ) -> Angle - Turn;
act_turn_inner( Angle, Turn, _Left, true ) -> Angle + Turn;
act_turn_inner( Angle, _Turn, _Left, _Right ) -> Angle.
limit_xy
( { X::number ( ) , Y::number ( ) } ) - > { NewX::number ( ) , NewY::number ( ) }
limit_xy( {X, Y} ) -> { limit(X, ?WIDTH), limit(Y, ?HEIGHT) }.
@doc Returns the given value but translated to between 0 and .
If val is bigger then then is returned , not max . Similar if
is less then 0 ; val+max is returned not 0 .
If val is between 0 and then is returned unchanged .
@spec limit ( Val::number ( ) , ( ) ) - > ( )
limit( Val, Max ) when Val > Max -> Val-Max;
limit( Val, Max ) when Val < 0 -> Val+Max;
limit( Val, _Max ) -> Val.
get_img ( AS::mover_state ( ) ) - > Image::image ( )
get_img(AS) -> actor_state:get( AS, ?ACTOR_IMG ).
get_angle
( AS::mover_state ( ) ) - > Angle::number ( )
get_angle(AS) -> actor_state:get( AS, ?ACTOR_ANGLE ). |
2a0eb08b81c7fba283afa52064966d6fbef44d304cc6432966bdfbb6fb30bd76 | yjqww6/drcomplete | info.rkt | #lang info
(define collection "drcomplete-method-names")
(define deps '("base" "drracket-plugin-lib" "gui-lib"
"drcomplete-base"))
(define build-deps '("rackunit-lib"))
(define pkg-desc "auto complete for method names")
(define version "0.2")
(define pkg-authors '(yjqww6))
(define drracket-tools '(("tool.rkt")))
(define drracket-tool-names '("drcomplete-method-names"))
(define drracket-tool-icons '(#f))
| null | https://raw.githubusercontent.com/yjqww6/drcomplete/b3f7390149e8d006c92b8a8a4da1593da547e235/drcomplete-method-names/info.rkt | racket | #lang info
(define collection "drcomplete-method-names")
(define deps '("base" "drracket-plugin-lib" "gui-lib"
"drcomplete-base"))
(define build-deps '("rackunit-lib"))
(define pkg-desc "auto complete for method names")
(define version "0.2")
(define pkg-authors '(yjqww6))
(define drracket-tools '(("tool.rkt")))
(define drracket-tool-names '("drcomplete-method-names"))
(define drracket-tool-icons '(#f))
| |
20fe7705832d330c7f32d8c9dc4dd2039fd1f82a58f6d3904c43ee3f72a2cb67 | BinaryAnalysisPlatform/bap | monads_monad.ml | open Core_kernel[@@warning "-D"]
let ident = Fn.id
module Monoid = Monads_monoid
module Types = Monads_types
module Trans = Types.Trans
module type Monad = Types.Monad.S
module type Monad2 = Types.Monad.S2
module Plus = Types.Plus
module Fail = Types.Fail
module Choice = struct
include Types.Choice
module Make2(M : Basic2) : S2 with type ('a,'e) t := ('a,'e) M.t = struct
include M
let accept = pure and reject = zero
let guard c = if c then accept () else reject ()
let on c action = if c then action else accept ()
let unless c action = if c then accept () else action
end
module Make(M : Basic) : S with type 'a t := 'a M.t =
Make2(struct
type ('a,'e) t = 'a M.t
include (M : Basic with type 'a t := 'a M.t)
end)
end
module Monad = struct
include Types.Monad
module type B = Types.Monad.Basic
module type B2 = Types.Monad.Basic2
module Make2(M : B2)
: S2 with type ('a,'e) t := ('a,'e) M.t
= struct
include Monad.Make2(struct
include M
let bind m ~f = bind m f
end)
module Lift = struct
let nullary x = return x [@@inline]
let unary f a = a >>| f [@@inline]
let binary f a b = a >>= fun a -> b >>| fun b -> f a b [@@inline]
let ternary f a b c = a >>= fun a -> b >>= fun b -> c >>| fun c -> f a b c
let quaternary f a b c d =
a >>= fun a -> b >>= fun b -> c >>= fun c -> d >>| fun d ->
f a b c d
let quinary f a b c d e =
a >>= fun a -> b >>= fun b -> c >>= fun c -> d >>= fun d -> e >>| fun e ->
f a b c d e
module Syntax = struct
let (!!) x = nullary x [@@inline]
let (!$) = unary
let (!$$) = binary
let (!$$$) = ternary
let (!$$$$) = quaternary
let (!$$$$$) = quinary
end
end
open Lift.Syntax
module Fn = struct
let id x = return x [@@inline]
let nothing x = return x [@@inline]
let ignore m = m >>| ignore [@@inline]
let non f x = f x >>| not [@@inline]
let apply_n_times ~n f x =
let rec loop n x =
if n <= 0 then return x
else f x >>= loop (n-1) in
loop n x
let compose f g x = g x >>= f [@@inline]
end
module Syntax = struct
include Monad_infix
include Lift.Syntax
let (>=>) g f = Fn.compose f g [@@inline]
end
module Let = struct
let (let*) = (>>=)
let (let+) = (>>|)
let (and+) x y =
x >>= fun x ->
y >>| fun y ->
(x,y)
let (and*) = (and+)
end
open Syntax
module Pair = struct
let fst x = !$fst x
let snd x = !$snd x
end
module Triple = struct
let fst x = !$(fun (x,_,_) -> x) x
let snd x = !$(fun (_,x,_) -> x) x
let trd x = !$(fun (_,_,x) -> x) x
end
module Exn = struct
let expect ?(finally=Fn.nothing) ~f ~catch =
let invoke f x = f x >>= fun x -> finally () >>= fun () -> return x in
try invoke f () with exn -> invoke catch exn
[@@warning "-16"]
end
module Collection = struct
module type S = Types.Collection.S2
with type ('a,'e) m := ('a,'e) M.t
module type Base = sig
include Types.Collection.Basic
val foldl : 'a t -> init:'b -> f:('b -> 'a -> ('b,'e) M.t) -> ('b,'e) M.t
val foldr : 'a t -> f:('a -> 'b -> ('b,'e) M.t) -> init:'b -> ('b,'e) M.t
val find_map : 'a t -> f:('a -> ('b option,'e) M.t) -> ('b option,'e) M.t
end
module Eager_base(T : Types.Collection.Eager) = struct
include T
let foldl xs ~init ~f =
T.fold xs ~init:(fun k -> k init)
~f:(fun k x k' -> k (fun a -> f a x >>= k')) M.return
let foldr xs ~f ~init =
T.fold xs ~init:M.return ~f:(fun k x ->
(fun a -> f x a >>= k)) init
let find_map xs ~f =
foldl xs ~init:None ~f:(fun r x -> match r with
| None -> f x
| r -> M.return r)
end
module Delay_base( T : Types.Collection.Delay) = struct
include T
let foldl xs ~init ~f =
T.fold xs ~init ~f:(fun a x k -> f a x >>= k) M.return
let fold xs ~init ~f =
T.fold xs ~init ~f:(fun a x k -> k (f a x)) ident
let foldr xs ~f ~init =
fold xs ~init:M.return ~f:(fun k x a -> f x a >>= k) init
let find_map xs ~f =
T.fold xs ~init:() ~f:(fun () x k -> f x >>= function
| None -> k ()
| x -> M.return x) (fun () -> M.return None)
end
module Make(T : Base) : Types.Collection.S2
with type 'a t := 'a T.t
and type ('a,'e) m = ('a,'e) M.t = struct
type ('a,'e) m = ('a,'e) M.t
type 'a t = 'a T.t
type 'a c = 'a t
let fold = T.foldl
let fold_left = T.foldl
let fold_right = T.foldr
let find_map = T.find_map
let prepend ys x = T.plus (T.return x) ys
let map xs ~f =
let empty = T.zero () in
fold_right xs ~init:empty ~f:(fun x ys -> f x >>| prepend ys)
let all = map ~f:ident
let iter xs ~f = fold xs ~init:() ~f:(fun () x -> f x)
let all_unit = iter ~f:Fn.ignore
let all_ignore = iter ~f:Fn.ignore
let sequence = all_unit
let reduce xs ~f = fold xs ~init:None ~f:(fun acc y ->
match acc with
| None -> return (Some y)
| Some x -> f x y >>| fun z -> Some z)
let exists xs ~f =
T.find_map xs ~f:(fun x -> f x >>| function
| true -> Some ()
| false -> None) >>| Option.is_some
let for_all xs ~f = !$not @@ exists xs ~f:(Fn.non f)
let count xs ~f =
fold xs ~init:0 ~f:(fun n x ->
f x >>| function
| true -> n+1
| false -> n)
let map_reduce (type a) (module M : Monoid.S with type t = a) xs ~f =
fold xs ~init:M.zero ~f:(fun x y -> (f y >>| M.plus x))
let find xs ~f =
let f x = f x >>| function
| true -> Some x
| false -> None in
find_map xs ~f
let filter_map xs ~f =
let empty = T.zero () in
fold_right xs ~init:empty ~f:(fun x ys -> f x >>| function
| None -> ys
| Some y -> prepend ys y)
let filter xs ~f = filter_map xs ~f:(fun x ->
f x >>| function
| true -> Some x
| false -> None)
end
module Delay(B : Types.Collection.Delay) = struct
module Base = Delay_base(B)
include Make(Base)
end
module Eager(B : Types.Collection.Eager) = struct
module Base = Eager_base(B)
include Make(Base)
end
end
module List = Collection.Delay(struct
type 'a t = 'a list
let fold xs ~init ~f =
let rec loop xs k = match xs with
| [] -> k
| x :: xs -> fun k' -> k (fun a -> loop xs (f a x) k') in
loop xs (fun k -> k init)
let zero () = []
let return x = [x]
let plus = (@)
end)
module Seq = Collection.Delay(struct
type 'a t = 'a Sequence.t
let fold xs ~init ~f finish =
Sequence.delayed_fold xs ~init ~f:(fun a x ~k ->
f a x k) ~finish
let zero () = Sequence.empty [@@inline]
let return x = Sequence.return x [@@inline]
let plus = Sequence.append
end)
let void t = Fn.ignore t
let sequence = List.sequence
let rec forever t = bind t (fun _ -> forever t)
include Syntax
include Let
end
module Make(M : B) : S with type 'a t := 'a M.t =
Make2(struct
type ('a, 'e) t = 'a M.t
include (M : B with type 'a t := 'a M.t)
end)
module Core2(M : Core2) = struct
type ('a,'e) t = ('a,'e) M.t
include Make2(struct
include M
let bind m f = bind m ~f
let map = `Custom map
end)
let join = M.join
let ignore_m = M.ignore_m
let all = M.all
let all_unit = M.all_unit
let all_ignore = M.all_unit
end
the intended usage of this module is
[ ) ) ] to upcast a monad of type [ Core ]
to a monad of type [ S ] , to make it possible
we should n't erase types from this monad , otherwise
this functor would be much harder to use .
Since we ca n't erase types , we ca n't implement Core
module via the Core2 . So we need to repeat the code .
Since , the code does n't contain any implementation ( just
renaming ) it can be considered OK .
[F(Core(M))] to upcast a monad of type [Core]
to a monad of type [S], to make it possible
we shouldn't erase types from this monad, otherwise
this functor would be much harder to use.
Since we can't erase types, we can't implement Core
module via the Core2. So we need to repeat the code.
Since, the code doesn't contain any implementation (just
renaming) it can be considered OK.
*)
module Core(M : Core) = struct
type 'a t = 'a M.t
include Make(struct
include M
let bind m f = bind m ~f
let map = `Custom map
end)
let join = M.join
let ignore_m = M.ignore_m
let all = M.all
let all_unit = M.all_unit
let all_ignore = M.all_unit
end
this module provides a fast and dirty translation from a minimal
monad representation to our maximal . We will not erase types
from the resulting structure , as this functor is expected to
be used as a type caster , e.g. [ Monad . State . Make(Monad . Minimal(M ) ]
monad representation to our maximal. We will not erase types
from the resulting structure, as this functor is expected to
be used as a type caster, e.g. [Monad.State.Make(Monad.Minimal(M)]
*)
module Minimal( M : Minimal) = struct
type 'a t = 'a M.t
include Make(struct
include M
let map = `Define_using_bind
end)
end
module Minimal2( M : Minimal2) = struct
type ('a,'e) t = ('a,'e) M.t
include Make2(struct
include M
let map = `Define_using_bind
end)
end
end
module Ident
: Monad.S with type 'a t = 'a
= struct
type 'a t = 'a
module M = Monad.Make(struct
type 'a t = 'a
let return = ident
let bind m f = m |> f
let map = `Custom (fun x ~f -> f x)
end)
let unit = ()
module Fn = struct
let ignore = ignore
let nothing () = ()
include Fn
end
module Pair = struct
let fst = fst
let snd = snd
end
module Triple = struct
let fst (x,_,_) = x
let snd (_,x,_) = x
let trd (_,_,x) = x
end
module Exn = M.Exn
module Lift = struct
let nullary = ident
let unary = ident
let binary = ident
let ternary = ident
let quaternary = ident
let quinary = ident
end
module Collection = struct
module type S = Types.Collection.S with type 'a m := 'a t
module Eager(T : Types.Collection.Eager) :
S with type 'a t := 'a T.t = struct
include M.Collection.Eager(T)
let all = ident
let all_unit = ignore
let all_ignore = ignore
let iter xs ~f = fold xs ~init:() ~f:(fun () x -> f x)
let fold = fold
end
module Delay(T : Types.Collection.Delay) :
S with type 'a t := 'a T.t = struct
include M.Collection.Delay(T)
let all = ident
let all_unit = ignore
let all_ignore = ignore
let iter xs ~f = fold xs ~init:() ~f:(fun () x -> f x)
let fold = fold
end
end
module List = struct
module Base = Collection.Delay(struct
type 'a t = 'a list
let fold xs ~init ~f =
let rec loop xs k = match xs with
| [] -> k
| x :: xs -> fun k' -> k (fun a -> loop xs (f a x) k') in
loop xs (fun k -> k init)
let zero () = []
let return x = [x]
let plus = (@)
end)
include (Base : Collection.S with type 'a t := 'a list)
include List
let all = ident
let all_unit = ignore
let all_ignore = ignore
end
module Seq = struct
module Base = Collection.Delay(struct
type 'a t = 'a Sequence.t
let fold xs ~init ~f finish =
Sequence.delayed_fold xs ~init ~f:(fun a x ~k ->
f a x k) ~finish
let zero () = Sequence.empty
let return = Sequence.return
let plus = Sequence.append
end)
include (Base : Collection.S with type 'a t := 'a Sequence.t)
include Sequence
let all = ident
let all_unit = ignore
let all_ignore = ignore
end
module Syntax = struct
let (>>=) x f = x |> f [@@inline]
let (>>|) x f = x |> f [@@inline]
let (>=>) f g x = g (f x) [@@inline]
let (!!) = ident
let (!$) = ident
let (!$$) = ident
let (!$$$) = ident
let (!$$$$) = ident
let (!$$$$$) = ident
end
module Let = struct
open Syntax
let (let*) = (>>=)
let (let+) = (>>|)
let (and+) x y =
x >>= fun x ->
y >>| fun y ->
(x,y)
let (and*) = (and+)
end
module Let_syntax = struct
include Syntax
let return = ident
module Let_syntax = struct
let return = ident
let bind x ~f = x |> f
let map x ~f = x |> f
let both x y = x,y
module Open_on_rhs = struct let return = ident end
module Open_in_body = struct let return = ident end
end
end
let all_unit = ignore
let all_ignore = ignore
let all = ident
let ignore_m = ignore
let join = ident
let void = ignore
let rec forever x = forever x
let sequence = all_unit
module Monad_infix = Syntax
include Let_syntax.Let_syntax
include Syntax
include Let
end
module OptionT = struct
include Types.Option
module T1(M : T1) = struct
type 'a t = 'a option M.t
type 'a m = 'a M.t
type 'a e = 'a t
end
module T2(M : T2) = struct
type ('a,'e) t = ('a option, 'e) M.t
type ('a,'e) m = ('a,'e) M.t
type ('a,'e) e = ('a,'e) t
end
module Make2(M : Monad.S2)
: S2 with type ('a,'e) t := ('a,'e) T2(M).t
and type ('a,'e) m := ('a,'e) T2(M).m
and type ('a,'e) e := ('a,'e) T2(M).e
= struct
open M.Syntax
module Basic = struct
include T2(M)
let return x = M.return (Some x)
let bind m f = M.bind m (function
| Some r -> f r
| None -> M.return None)
[@@inline]
let map m ~f = M.bind m (function
| Some r -> M.return (Some (f r))
| None -> M.return None)
[@@inline]
let map = `Custom map
end
type 'a error = unit
let fail () = M.return None
let run = ident
let catch m f = m >>= function
| None -> f ()
| other -> M.return other
let plus m1 m2 = m1 >>= function
| Some m1 -> M.return (Some m1)
| None -> m2
include Choice.Make2(struct
type ('a,'e) t = ('a,'e) Basic.t
let pure = Basic.return
let zero () = M.return None
end)
include Basic
include Monad.Make2(Basic)
let lift = M.map ~f:Option.return
end
module Make(M : Monad.S)
: S with type 'a m := 'a T1(M).m
and type 'a t := 'a T1(M).t
and type 'a e := 'a T1(M).e
= Make2(struct
type ('a,'e) t = 'a M.t
type 'a error = unit
include (M : Monad.S with type 'a t := 'a M.t)
end)
include T1(Ident)
include Make(Ident)
end
module ResultT = struct
include Types.Result
type ('a,'e) result = ('a,'e) Result.t =
| Ok of 'a
| Error of 'e
module type Sp = sig
include Trans.S1
include Monad.S2 with type ('a,'e) t := ('a,'e) t
include Fail.S2 with type ('a,'e) t := ('a,'e) t
end
module Tp(T : T1)(M : Monad.S) = struct
type 'a error = 'a T.t
type 'a m = 'a M.t
type ('a,'e) t = ('a,'e error) result m
type ('a,'e) e = ('a,'e error) result m
end
module Makep(T : T1)(M : Monad.S) : Sp
with type ('a,'e) t := ('a,'e) Tp(T)(M).t
and type 'a m := 'a Tp(T)(M).m
and type ('a,'e) e := ('a,'e) Tp(T)(M).e
and type 'a error = 'a Tp(T)(M).error
= struct
include struct
let (>>=) m f = M.bind m f [@@inline]
let (>>|) m f = M.map m f [@@inline]
end
module Base = struct
include Tp(T)(M)
let return x = M.return (Ok x)
let bind m f : ('a,'e) t = m >>= function
| Ok r -> f r
| Error err -> M.return (Error err)
[@@inline]
let fail err = M.return (Error err)
let run = ident
let catch m f = m >>= function
| Error err -> f err
| other -> M.return other
let lift m = m >>| fun x -> Ok x
let map' m ~f = m >>= function
| Ok r -> return (f r)
| Error err -> M.return (Error err)
[@@inline]
let map = `Custom map'
end
include Base
include Monad.Make2(Base)
end
module T1(T : T)(M : Monad.S) = struct
type error = T.t
type 'a m = 'a M.t
type 'a t = ('a,error) result m
type 'a e = ('a,error) result m
end
module T2(M : Monad.S) = struct
type 'a m = 'a M.t
type ('a,'e) t = ('a,'e) result m
type ('a,'e) e = ('a,'e) result m
end
module Make(T : T)(M : Monad.S) : S
with type 'a t := 'a T1(T)(M).t
and type 'a m := 'a T1(T)(M).m
and type 'a e := 'a T1(T)(M).e
and type err := T.t
= struct
type err = T.t
include Makep(struct type 'a t = T.t end)(M)
end
module Make2(M : Monad.S) : S2
with type ('a,'e) t := ('a,'e) T2(M).t
and type 'a m := 'a T2(M).m
and type ('a,'e) e := ('a,'e) T2(M).e
= Makep(struct type 'a t = 'a end)(M)
module Error = struct
module T(M : Monad.S) = struct
type 'a m = 'a M.t
type 'a t = 'a Or_error.t m
type 'a e = 'a Or_error.t m
end
module type S = sig
include S
val failf : ('a, Caml.Format.formatter, unit, unit -> 'b t) format4 -> 'a
end
module Make(M : Monad.S) : S
with type 'a t := 'a T(M).t
and type 'a m := 'a T(M).m
and type 'a e := 'a T(M).e
and type err := Error.t
= struct
include Make(struct type t = Error.t end)(M)
let failf fmt =
let open Caml.Format in
let buf = Buffer.create 512 in
let ppf = formatter_of_buffer buf in
let kon ppf () =
pp_print_flush ppf ();
let err = Or_error.error_string (Buffer.contents buf) in
M.return err in
kfprintf kon ppf fmt
end
type 'a t = 'a Or_error.t
type 'a m = 'a
type 'a e = 'a Or_error.t
include Make(Ident)
end
module Exception = struct
module T(M : Monad.S) = struct
type 'a m = 'a M.t
type 'a t = ('a,exn) Result.t m
type 'a e = ('a,exn) Result.t m
end
module Make(M : Monad.S) : S
with type 'a t := 'a T(M).t
and type 'a m := 'a T(M).m
and type 'a e := 'a T(M).e
and type err := exn
= Make(struct type t = exn end)(M)
include T(Ident)
include Make(Ident)
end
module Self : S2
with type ('a,'e) t = ('a,'e) result
and type 'a m = 'a
and type ('a,'e) e = ('a,'e) result
= struct
include T2(Ident)
include Make2(Ident)
end
include Self
end
module ListT = struct
include Types.List
module T1(M : T1) = struct
type 'a t = 'a list M.t
type 'a m = 'a M.t
type 'a e = 'a t
end
module T2(M : T2) = struct
type ('a,'e) t = ('a list, 'e) M.t
type ('a,'e) m = ('a,'e) M.t
type ('a,'e) e = ('a,'e) t
end
module Make2(M : Monad.S2)
: S2 with type ('a,'e) m := ('a,'e) T2(M).m
and type ('a,'e) t := ('a,'e) T2(M).t
and type ('a,'e) e := ('a,'e) T2(M).e
= struct
open M.Syntax
type 'a result = 'a list
module Base = struct
include T2(M)
let return x = M.return [x]
let bind xsm f = xsm >>= fun xs ->
List.fold xs ~init:(!![]) ~f:(fun ysm x ->
ysm >>= fun ys -> f x >>| fun xs ->
List.rev_append xs @@ ys) >>| List.rev
let map xsm ~f = xsm >>| List.map ~f
let map = `Custom map
end
include Choice.Make2(struct
type ('a,'e) t = ('a,'e) T2(M).t
let pure x = M.return [x]
let zero () = M.return []
end)
module MT = Monad.Make2(Base)
let plus xsm ysm =
xsm >>= fun xs -> ysm >>= fun ys ->
M.return (xs @ ys)
let run = ident
let lift m = m >>| fun x -> [x]
include MT
end
module Make(M: Monad.S)
: S with type 'a m := 'a T1(M).m
and type 'a t := 'a T1(M).t
and type 'a e := 'a T1(M).e =
Make2(struct
type ('a,'e) t = 'a M.t
include (M : Monad.S with type 'a t := 'a M.t)
end)
module ListM :
S with type 'a t = 'a list and type 'a m = 'a and type 'a e = 'a list = struct
include T1(Ident)
include Make(Ident)
end
include ListM
end
module Seq = struct
include Types.List
module T1(M : T1) = struct
type 'a t = 'a Sequence.t M.t
type 'a m = 'a M.t
type 'a e = 'a t
end
module T2(M : T2) = struct
type ('a,'e) t = ('a Sequence.t, 'e) M.t
type ('a,'e) m = ('a,'e) M.t
type ('a,'e) e = ('a,'e) t
end
module Make2(M : Monad.S2)
: S2 with type ('a,'e) m := ('a,'e) T2(M).m
and type ('a,'e) t := ('a,'e) T2(M).t
and type ('a,'e) e := ('a,'e) T2(M).e
= struct
open M.Syntax
type 'a result = 'a Sequence.t
module Base = struct
include T2(M)
let return x = M.return @@ Sequence.singleton x
let bind xsm f = xsm >>= fun xs ->
Sequence.fold xs ~init:(!!Sequence.empty) ~f:(fun ysm x ->
ysm >>= fun ys -> f x >>| fun xs ->
Sequence.append xs ys)
let map xsm ~f = xsm >>| Sequence.map ~f
let map = `Custom map
end
include Choice.Make2(struct
type ('a,'e) t = ('a,'e) T2(M).t
let pure x = Base.return x
let zero () = M.return Sequence.empty
end)
module MT = Monad.Make2(Base)
let plus xsm ysm =
xsm >>= fun xs -> ysm >>= fun ys ->
M.return (Sequence.append xs ys)
let run = ident
let lift m = m >>| Sequence.singleton
include MT
end
module Make(M : Monad.S)
: S with type 'a m := 'a T1(M).m
and type 'a t := 'a T1(M).t
and type 'a e := 'a T1(M).e
= Make2(struct
type ('a,'e) t = 'a M.t
include (M : Monad.S with type 'a t := 'a M.t)
end)
module SeqM : S
with type 'a t = 'a Sequence.t
and type 'a m = 'a
and type 'a e = 'a Sequence.t =
struct
include T1(Ident)
include Make(Ident)
end
include SeqM
end
module Writer = struct
include Types.Writer
type ('a,'s) writer = Writer of ('a * 's)
module T1(T : Monoid.S)(M : Monad.S) = struct
type state = T.t
type 'a m = 'a M.t
type 'a t = ('a,state) writer m
type 'a e = ('a * state) m
end
module T2(T : Monoid.S)(M : Monad.S2) = struct
type state = T.t
type ('a,'e) m = ('a,'e) M.t
type ('a,'e) t = (('a,state) writer,'e) M.t
type ('a,'e) e = ('a * state, 'e) m
end
module Make2(T : Monoid.S)(M : Monad.S2)
: S2 with type ('a,'e) m := ('a,'e) T2(T)(M).m
and type ('a,'e) t := ('a,'e) T2(T)(M).t
and type ('a,'e) e := ('a,'e) T2(T)(M).e
and type state := T2(T)(M).state
= struct
open M.Syntax
let (+) = T.plus
module Base = struct
include T2(T)(M)
let writer x = Writer x
let return x = M.return @@ writer (x,T.zero)
let bind m f =
m >>= fun (Writer (x,a)) -> f x >>| fun (Writer (x,b)) ->
writer (x,a+b)
let map m ~f = m >>| fun (Writer (x,e)) -> writer (f x,e)
let map = `Custom map
end
include Base
let returnw x = M.return @@ writer x
let write x = M.return @@ writer ((), x)
let read m = m >>= fun (Writer (_,e)) -> returnw (e,e)
let listen m = m >>= fun (Writer (x,e)) -> returnw ((x,e),e)
let run m = m >>| fun (Writer (x,e)) -> (x,e)
let exec m = m >>| fun (Writer ((),e)) -> e
let ignore m = m >>= fun (Writer (_,e)) -> returnw ((),e)
let lift m = M.map m ~f:(fun x -> Writer (x,T.zero))
include Monad.Make2(Base)
end
module Make(T : Monoid.S)(M : Monad.S)
: S with type 'a m := 'a T1(T)(M).m
and type 'a t := 'a T1(T)(M).t
and type 'a e := 'a T1(T)(M).e
and type state := T1(T)(M).state
= struct
module M = struct
type ('a,'e) t = 'a M.t
include (M : Monad.S with type 'a t := 'a M.t)
end
type state = T.t
include Make2(T)(M)
end
end
module Reader = struct
include Types.Reader
type ('a,'e) reader = Reader of ('e -> 'a)
module type Sp = sig
type 'a env
include Trans.S1
val read : unit -> ('e env, 'e ) t
include Monad.S2 with type ('a,'e) t := ('a,'e) t
end
module Tp(T : T1)(M : Monad.S) = struct
type 'a env = 'a T.t
type 'a m = 'a M.t
type ('a,'e) t = ('a m, 'e env) reader
type ('a,'e) e = 'e env -> 'a m
end
module Makep(T : T1)(M : Monad.S) : Sp
with type ('a,'e) t := ('a,'e) Tp(T)(M).t
and type 'a m := 'a Tp(T)(M).m
and type ('a,'e) e := ('a,'e) Tp(T)(M).e
and type 'a env := 'a Tp(T)(M).env
= struct
module Base = struct
include Tp(T)(M)
open M.Monad_infix
let (=>) (Reader run) x = run x
let reader comp = Reader comp
let return x = reader @@ fun _ -> M.return x
let bind m f = reader @@ fun s -> m => s >>= fun x -> f x => s
let map m ~f = reader @@ fun s -> m => s >>| f
let read () = reader @@ fun s -> M.return s
let lift m = reader @@ fun _ -> m
let run m s = m => s
let map = `Custom map
end
include Base
include Monad.Make2(Base)
end
module T1(T : T)(M : Monad.S) = struct
type env = T.t
type 'a m = 'a M.t
type 'a t = ('a m, env) reader
type 'a e = env -> 'a m
end
module T2(M : Monad.S) = struct
type 'a m = 'a M.t
type ('a,'e) t = ('a m,'e) reader
type ('a,'e) e = 'e -> 'a m
end
module Make(T : T)(M : Monad.S): S
with type 'a t := 'a T1(T)(M).t
and type 'a m := 'a T1(T)(M).m
and type 'a e := 'a T1(T)(M).e
and type env := T.t
= Makep(struct type 'a t = T.t end)(M)
module Make2(M : Monad.S) : S2
with type ('a,'e) t := ('a,'e) T2(M).t
and type 'a m := 'a T2(M).m
and type ('a,'e) e := ('a,'e) T2(M).e
= Makep(struct type 'a t = 'a end)(M)
module Self : S2
with type ('a,'e) t = ('a,'e) reader
and type 'a m = 'a
and type ('a,'e) e = 'e -> 'a
= struct
include T2(Ident)
include Make2(Ident)
end
include Self
end
module State = struct
include Types.State
module type Sp = sig
include Trans.S1
include Monad.S2 with type ('a,'s) t := ('a,'s) t
type 'a env
val put : 's env -> (unit,'s) t
val get : unit -> ('s env,'s) t
val gets : ('s env -> 'r) -> ('r,'s) t
val update : ('s env -> 's env) -> (unit,'s) t
val modify : ('a,'s) t -> ('s env -> 's env) -> ('a,'s) t
val eval : ('a,'s) t -> 's env -> 'a m
val exec : ('a,'s) t -> 's env -> 's env m
end
type ('a,'b) storage = {
x : 'a;
s : 'b;
}
type ('a,'e) state = State of ('e -> 'a)
module Tp(T : T1)(M : Monad.S) = struct
type 'a env = 'a T.t
type 'a m = 'a M.t
type ('a,'e) t = (('a,'e env) storage m, 'e env) state
type ('a,'e) e = 'e env -> ('a * 'e env) m
end
module Makep(T : T1)(M : Monad.S) : Sp
with type ('a,'e) t := ('a,'e) Tp(T)(M).t
and type 'a m := 'a Tp(T)(M).m
and type ('a,'e) e := ('a,'e) Tp(T)(M).e
and type 'a env := 'a Tp(T)(M).env
= struct
include struct
let (>>=) m f = M.bind m f [@@inline]
let (>>|) m f = M.map m f [@@inline]
end
let make run = State run [@@inline]
let (=>) (State run) x = run x [@@inline]
type 'a result = 'a M.t
module Basic = struct
include Tp(T)(M)
let return x = (make [@inlined]) (fun s -> M.return {x;s}) [@@inline]
let bind m f = make @@ fun s -> m=>s >>= fun {x;s} -> f x => s [@@inline]
let map m ~f = make @@ fun s -> m=>s >>| fun {x;s} -> {x=f x;s} [@@inline]
let map = `Custom map
end
let put s = make @@ fun _ -> M.return {x=();s} [@@inline]
let get () = make @@ fun s -> M.return {x=s;s} [@@inline]
let gets f = make @@ fun s -> M.return {x=f s;s} [@@inline]
let update f = make @@ fun s -> M.return {x=();s = f s} [@@inline]
let modify m f =
make @@ fun s -> m=>s >>= fun {x;s} -> M.return {x; s = f s} [@@inline]
let run m s = M.(m => s >>| fun {x;s} -> (x,s))
let eval m s = M.(run m s >>| fst)
let exec m s = M.(run m s >>| snd)
let lift m = make @@ fun s -> M.bind m (fun x -> M.return {x;s}) [@@inline]
include Basic
include Monad.Make2(Basic)
end
module T1(T : T)(M : Monad.S) = struct
type env = T.t
type 'a m = 'a M.t
type 'a t = (('a,env) storage m, env) state
type 'a e = env -> ('a * env) m
end
module T2(M : Monad.S) = struct
type 'a m = 'a M.t
type ('a,'e) t = (('a,'e) storage m, 'e) state
type ('a,'e) e = 'e -> ('a * 'e) m
end
module Make(T : T)(M : Monad.S): S
with type 'a t := 'a T1(T)(M).t
and type 'a m := 'a T1(T)(M).m
and type 'a e := 'a T1(T)(M).e
and type env := T.t
= Makep(struct type 'a t = T.t end)(M)
module Make2(M : Monad.S) : S2
with type ('a,'e) t := ('a,'e) T2(M).t
and type 'a m := 'a T2(M).m
and type ('a,'e) e := ('a,'e) T2(M).e
= Makep(struct type 'a t = 'a end)(M)
module Multi = struct
include Types.Multi
module Id = struct
type t = int
let zero = Int.zero
let succ = Int.succ
include Identifiable.Make(struct
type t = int [@@deriving compare, bin_io, hash, sexp]
let module_name = "Monads.Std.Monad.State.Multi.Id"
let to_string = Int.to_string
let of_string = Int.of_string
end)
end
type id = Id.t
type 'e contexts = {
the i d of last created fork
current : id; (* the id of current context *)
parents : id Id.Map.t; (* tree of forks *)
children : Id.Set.t Id.Map.t;
init : 'e; (* father of all forks *)
forks : 'e Id.Map.t; (* all forks of the Father *)
}
module ST1 = T1
module ST2 = T2
module STp = Tp
module type Sp = sig
include Trans.S1
type id
module Id : Identifiable.S with type t = id
val global : id
val fork : unit -> (unit,'e) t
val switch : id -> (unit,'e) t
val parent : unit -> (id,'e) t
val ancestor : id list -> (id,'e) t
val current : unit -> (id,'e) t
val kill : id -> (unit,'e) t
val forks : unit -> (id Sequence.t,'e) t
val status : id -> (status,'e) t
include Sp with type ('a,'e) t := ('a,'e) t
and type ('a,'e) e := ('a,'e) e
and type 'a m := 'a m
end
module T1(T : T)(M : Monad.S) = struct
type env = T.t
type 'a m = 'a M.t
type 'a t = (('a,env contexts) storage m, env contexts) state
type 'a e = env -> ('a * env) m
end
module T2(M : Monad.S) = struct
type 'a m = 'a M.t
type ('a,'e) t = (('a,'e contexts) storage m, 'e contexts) state
type ('a,'e) e = 'e -> ('a * 'e) m
end
module Tp(T : T1)(M : Monad.S) = struct
type 'a env = 'a T.t
type 'a m = 'a M.t
type ('a,'e) t = (('a,'e env contexts) storage m, 'e env contexts) state
type ('a,'e) e = 'e env -> ('a * 'e env) m
end
module Makep(T : T1)(M : Monad.S) : Sp
with type ('a,'e) t := ('a,'e) Tp(T)(M).t
and type ('a,'e) e := ('a,'e) Tp(T)(M).e
and type 'a m := 'a Tp(T)(M).m
and type 'a env := 'a Tp(T)(M).env
and type id := id
and module Id := Id
= struct
module SM = struct
module Env = struct
type 'a t = 'a T.t contexts
end
include STp(Env)(M)
include Makep(Env)(M)
end
open SM.Syntax
include Tp(T)(M)
type id = Id.t
let global = Id.zero
let init ctxt = {
init = ctxt;
created = global;
current = global;
parents = Id.Map.empty;
children = Id.Map.empty;
forks = Id.Map.empty;
}
let rec alive_parent k child =
match Map.find k.parents child with
| None -> global
| Some p when Map.mem k.forks p -> p
| Some zombie -> alive_parent k zombie
let rec ancestor k cs =
match List.map cs ~f:(alive_parent k) with
| [] -> global
| p :: ps when List.for_all ps ~f:(fun p' -> p = p') -> p
| ps -> ancestor k ps
let ancestor cs = SM.gets @@ fun k -> ancestor k cs
let alive k id : id =
if Map.mem k.forks id then id else alive_parent k id
let forks () = SM.gets (fun k ->
let fs = Map.to_sequence k.forks |> Seq.map ~f:fst in
Sequence.shift_right fs global)
let siblings () =
SM.gets (fun k ->
match Map.find k.children (alive_parent k k.current) with
| None -> Id.Set.empty
| Some cs -> Set.filter cs ~f:(Map.mem k.forks))
let context k =
let id = alive k k.current in
if id = global then k.init
else Map.find_exn k.forks k.current
let fork () = SM.update @@ fun k ->
let ctxt = context k in
let current = Id.succ k.created in
let parents = Map.set k.parents ~key:current ~data:k.current in
let forks = Map.set k.forks ~key:current ~data:ctxt in
{k with created=current; current; parents; forks}
let switch id = SM.update @@ fun k -> {k with current = alive k id}
let current () = SM.gets @@ fun k -> alive k k.current
let get () = SM.get () >>| context
let put ctxt = SM.update @@ fun k ->
let id = alive k k.current in
if id = global then {k with init=ctxt} else {
k with forks = Map.set k.forks ~key:id ~data:ctxt
}
let parent () = SM.get () >>| fun k -> alive_parent k k.current
let status id = SM.get () >>| fun k ->
if id = k.current then `Current else
if Map.mem k.forks id then `Live else `Dead
let remove_dead_parents k =
let parents =
Map.fold k.forks ~init:Id.Map.empty ~f:(fun ~key ~data:_ ps ->
Map.set ps ~key ~data:(alive_parent k key)) in
let children = Map.filter_keys k.children ~f:(Map.mem parents) in
{k with children; parents}
let gc k =
if k.created mod 1024 = 0 then remove_dead_parents k else k
let kill id = SM.update @@ fun k ->
gc {
k with
forks = Map.remove k.forks id;
current = if id = k.current then alive_parent k id else id;
}
let gets f = get () >>| f
let update f = get () >>= fun x -> put (f x)
let modify m f = m >>= fun x -> update f >>= fun () -> SM.return x
let run m = fun ctxt -> M.bind (SM.run m (init ctxt)) ~f:(fun (x,cs) ->
M.return (x,cs.init))
include Monad.Make2(struct
type nonrec ('a,'e) t = ('a,'e) t
let return = SM.return
let bind m f = SM.bind m ~f
let map = `Custom SM.map
end)
let lift m = SM.lift m
let eval m s = M.map (run m s) ~f:fst
let exec m s = M.map (run m s) ~f:snd
module Id = Id
end
module Make(T : T)(M : Monad.S): S
with type 'a t := 'a T1(T)(M).t
and type 'a m := 'a T1(T)(M).m
and type 'a e := 'a T1(T)(M).e
and type env := T.t
and type id := id
and module Id := Id
= Makep(struct type 'a t = T.t end)(M)
module Make2(M : Monad.S) : S2
with type ('a,'e) t := ('a,'e) T2(M).t
and type 'a m := 'a T2(M).m
and type ('a,'e) e := ('a,'e) T2(M).e
and type id := id
and module Id := Id
= Makep(struct type 'a t = 'a end)(M)
include T2(Ident)
include Make2(Ident)
end
include T2(Ident)
include Make2(Ident)
let eval m s = fst (run m s)
let exec m s = snd (run m s)
end
module Fun = struct
include Types.Fun
type 'a thunk = Thunk of (unit -> 'a)
module T1(M : Monad.S) = struct
type 'a m = 'a M.t
type 'a t = 'a m thunk
type 'a e = 'a m
end
module T2(M : Monad.S2) = struct
type ('a,'e) m = ('a,'e) M.t
type ('a,'e) t = ('a,'e) m thunk
type ('a,'e) e = ('a,'e) m
end
let thunk f = Thunk f
module Make2(M : Monad.S2) : S2
with type ('a,'e) t := ('a,'e) T2(M).t
and type ('a,'e) m := ('a,'e) T2(M).m
and type ('a,'e) e := ('a,'e) T2(M).e
= struct
open M.Syntax
module Base = struct
include T2(M)
let run (Thunk f) = f ()
let return x = thunk @@ fun () -> M.return x
let bind m f = thunk @@ fun () -> run m >>= fun x -> run (f x)
let map m ~f = thunk @@ fun () -> run m >>| f
let lift m = thunk @@ fun () -> m
let map = `Custom map
end
include Base
include Monad.Make2(Base)
end
module Make(M : Monad.S) : S
with type 'a t := 'a T1(M).t
and type 'a m := 'a T1(M).m
and type 'a e := 'a T1(M).e
= Make2(struct
type ('a,'e) t = 'a M.t
include (M : Monad.S with type 'a t := 'a M.t)
end)
include T1(Ident)
include Make(Ident)
end
module LazyT = struct
include Types.Lazy
module T1(M : Monad.S) = struct
type 'a m = 'a M.t
type 'a t = 'a m Lazy.t
type 'a e = 'a m
end
module T2(M : Monad.S2) = struct
type ('a,'e) m = ('a,'e) M.t
type ('a,'e) t = ('a,'e) m Lazy.t
type ('a,'e) e = ('a,'e) m
end
module Make2(M : Monad.S2) : S2
with type ('a,'e) t := ('a,'e) T2(M).t
and type ('a,'e) m := ('a,'e) T2(M).m
and type ('a,'e) e := ('a,'e) T2(M).e
= struct
open M.Syntax
module Base = struct
include T2(M)
let return x = lazy (M.return x)
let bind m f = lazy (Lazy.force m >>= fun x ->
Lazy.force (f x))
let map = `Define_using_bind
let run = Lazy.force
let lift x = lazy x
end
include Base
include Monad.Make2(Base)
end
module Make(M : Monad.S) : S
with type 'a t := 'a T1(M).t
and type 'a m := 'a T1(M).m
and type 'a e := 'a T1(M).e
= Make2(struct
type ('a,'e) t = 'a M.t
include (M : Monad.S with type 'a t := 'a M.t)
end)
module Self : S
with type 'a t = 'a Lazy.t
and type 'a m = 'a
and type 'a e = 'a
= struct
type 'a t = 'a Lazy.t
type 'a m = 'a
type 'a e = 'a
include Make(Ident)
end
include Self
end
module Cont = struct
include Types.Cont
type ('a,'r) cont = Cont of (('a -> 'r) -> 'r)
module T(M : Monad.S) = struct
type 'a m = 'a M.t
type ('a,'e) t = ('a, 'e m) cont
type ('a,'e) e = ('a -> 'e m) -> 'e m
end
let cont k = Cont k
module Tp(T : T1)(M : Monad.S) = struct
type 'a r = 'a T.t
type 'a m = 'a M.t
type ('a,'e) t = ('a, 'e r m) cont
type ('a,'e) e = ('a -> 'e r m) -> 'e r m
end
module type Sp = sig
include Trans.S1
include Monad.S2 with type ('a,'e) t := ('a,'e) t
type 'a r
val call : f:(cc:('a -> ('r,'e r) t) -> ('a,'e r) t) -> ('a,'e r) t
end
module Makep(T : T1)(M : Monad.S) : Sp
with type ('a,'e) t := ('a,'e) Tp(T)(M).t
and type ('a,'e) e := ('a,'e) Tp(T)(M).e
and type 'a m := 'a Tp(T)(M).m
and type 'a r := 'a Tp(T)(M).r
= struct
open M.Syntax
module Base = struct
include Tp(T)(M)
let run (Cont k) f = k f
let return x = cont @@ fun k -> k x
let lift m = cont @@ fun k -> m >>= k
let bind m f = cont @@ fun k ->
run m @@ fun x -> run (f x) k
let call ~f = cont @@ fun k ->
run (f ~cc:(fun x -> cont @@ fun _ -> k x)) k
let map = `Define_using_bind
end
include Base
include Monad.Make2(Base)
end
module T1(T : T)(M : Monad.S) = struct
type r = T.t
type 'a m = 'a M.t
type 'a t = ('a,r m) cont
type 'a e = ('a -> r m) -> r m
end
module T2(M : Monad.S) = struct
type 'a m = 'a M.t
type ('a,'e) t = ('a, 'e m) cont
type ('a,'e) e = ('a -> 'e m) -> 'e m
end
module Make(T : T)(M : Monad.S): S
with type 'a t := 'a T1(T)(M).t
and type 'a m := 'a T1(T)(M).m
and type 'a e := 'a T1(T)(M).e
and type r := T.t
= Makep(struct type 'a t = T.t end)(M)
module Make2(M : Monad.S) : S2
with type ('a,'e) t := ('a,'e) T2(M).t
and type 'a m := 'a T2(M).m
and type ('a,'e) e := ('a,'e) T2(M).e
= Makep(struct type 'a t = 'a end)(M)
module Self :
S2 with type ('a,'e) t = ('a,'e) cont
and type 'a m = 'a
and type ('a,'e) e = (('a -> 'e) -> 'e)
= struct
type ('a,'e) t = ('a,'e) T(Ident).t
type 'a m = 'a
type ('a,'e) e = ('a -> 'e) -> 'e
include Make2(Ident)
end
include Self
end
module Lazy = LazyT
module List = ListT
module Result = ResultT
module Option = OptionT
include Monad
module Collection = Types.Collection
| null | https://raw.githubusercontent.com/BinaryAnalysisPlatform/bap/cbdf732d46c8e38df79d9942fc49bcb97915c657/lib/monads/monads_monad.ml | ocaml | the id of current context
tree of forks
father of all forks
all forks of the Father | open Core_kernel[@@warning "-D"]
let ident = Fn.id
module Monoid = Monads_monoid
module Types = Monads_types
module Trans = Types.Trans
module type Monad = Types.Monad.S
module type Monad2 = Types.Monad.S2
module Plus = Types.Plus
module Fail = Types.Fail
module Choice = struct
include Types.Choice
module Make2(M : Basic2) : S2 with type ('a,'e) t := ('a,'e) M.t = struct
include M
let accept = pure and reject = zero
let guard c = if c then accept () else reject ()
let on c action = if c then action else accept ()
let unless c action = if c then accept () else action
end
module Make(M : Basic) : S with type 'a t := 'a M.t =
Make2(struct
type ('a,'e) t = 'a M.t
include (M : Basic with type 'a t := 'a M.t)
end)
end
module Monad = struct
include Types.Monad
module type B = Types.Monad.Basic
module type B2 = Types.Monad.Basic2
module Make2(M : B2)
: S2 with type ('a,'e) t := ('a,'e) M.t
= struct
include Monad.Make2(struct
include M
let bind m ~f = bind m f
end)
module Lift = struct
let nullary x = return x [@@inline]
let unary f a = a >>| f [@@inline]
let binary f a b = a >>= fun a -> b >>| fun b -> f a b [@@inline]
let ternary f a b c = a >>= fun a -> b >>= fun b -> c >>| fun c -> f a b c
let quaternary f a b c d =
a >>= fun a -> b >>= fun b -> c >>= fun c -> d >>| fun d ->
f a b c d
let quinary f a b c d e =
a >>= fun a -> b >>= fun b -> c >>= fun c -> d >>= fun d -> e >>| fun e ->
f a b c d e
module Syntax = struct
let (!!) x = nullary x [@@inline]
let (!$) = unary
let (!$$) = binary
let (!$$$) = ternary
let (!$$$$) = quaternary
let (!$$$$$) = quinary
end
end
open Lift.Syntax
module Fn = struct
let id x = return x [@@inline]
let nothing x = return x [@@inline]
let ignore m = m >>| ignore [@@inline]
let non f x = f x >>| not [@@inline]
let apply_n_times ~n f x =
let rec loop n x =
if n <= 0 then return x
else f x >>= loop (n-1) in
loop n x
let compose f g x = g x >>= f [@@inline]
end
module Syntax = struct
include Monad_infix
include Lift.Syntax
let (>=>) g f = Fn.compose f g [@@inline]
end
module Let = struct
let (let*) = (>>=)
let (let+) = (>>|)
let (and+) x y =
x >>= fun x ->
y >>| fun y ->
(x,y)
let (and*) = (and+)
end
open Syntax
module Pair = struct
let fst x = !$fst x
let snd x = !$snd x
end
module Triple = struct
let fst x = !$(fun (x,_,_) -> x) x
let snd x = !$(fun (_,x,_) -> x) x
let trd x = !$(fun (_,_,x) -> x) x
end
module Exn = struct
let expect ?(finally=Fn.nothing) ~f ~catch =
let invoke f x = f x >>= fun x -> finally () >>= fun () -> return x in
try invoke f () with exn -> invoke catch exn
[@@warning "-16"]
end
module Collection = struct
module type S = Types.Collection.S2
with type ('a,'e) m := ('a,'e) M.t
module type Base = sig
include Types.Collection.Basic
val foldl : 'a t -> init:'b -> f:('b -> 'a -> ('b,'e) M.t) -> ('b,'e) M.t
val foldr : 'a t -> f:('a -> 'b -> ('b,'e) M.t) -> init:'b -> ('b,'e) M.t
val find_map : 'a t -> f:('a -> ('b option,'e) M.t) -> ('b option,'e) M.t
end
module Eager_base(T : Types.Collection.Eager) = struct
include T
let foldl xs ~init ~f =
T.fold xs ~init:(fun k -> k init)
~f:(fun k x k' -> k (fun a -> f a x >>= k')) M.return
let foldr xs ~f ~init =
T.fold xs ~init:M.return ~f:(fun k x ->
(fun a -> f x a >>= k)) init
let find_map xs ~f =
foldl xs ~init:None ~f:(fun r x -> match r with
| None -> f x
| r -> M.return r)
end
module Delay_base( T : Types.Collection.Delay) = struct
include T
let foldl xs ~init ~f =
T.fold xs ~init ~f:(fun a x k -> f a x >>= k) M.return
let fold xs ~init ~f =
T.fold xs ~init ~f:(fun a x k -> k (f a x)) ident
let foldr xs ~f ~init =
fold xs ~init:M.return ~f:(fun k x a -> f x a >>= k) init
let find_map xs ~f =
T.fold xs ~init:() ~f:(fun () x k -> f x >>= function
| None -> k ()
| x -> M.return x) (fun () -> M.return None)
end
module Make(T : Base) : Types.Collection.S2
with type 'a t := 'a T.t
and type ('a,'e) m = ('a,'e) M.t = struct
type ('a,'e) m = ('a,'e) M.t
type 'a t = 'a T.t
type 'a c = 'a t
let fold = T.foldl
let fold_left = T.foldl
let fold_right = T.foldr
let find_map = T.find_map
let prepend ys x = T.plus (T.return x) ys
let map xs ~f =
let empty = T.zero () in
fold_right xs ~init:empty ~f:(fun x ys -> f x >>| prepend ys)
let all = map ~f:ident
let iter xs ~f = fold xs ~init:() ~f:(fun () x -> f x)
let all_unit = iter ~f:Fn.ignore
let all_ignore = iter ~f:Fn.ignore
let sequence = all_unit
let reduce xs ~f = fold xs ~init:None ~f:(fun acc y ->
match acc with
| None -> return (Some y)
| Some x -> f x y >>| fun z -> Some z)
let exists xs ~f =
T.find_map xs ~f:(fun x -> f x >>| function
| true -> Some ()
| false -> None) >>| Option.is_some
let for_all xs ~f = !$not @@ exists xs ~f:(Fn.non f)
let count xs ~f =
fold xs ~init:0 ~f:(fun n x ->
f x >>| function
| true -> n+1
| false -> n)
let map_reduce (type a) (module M : Monoid.S with type t = a) xs ~f =
fold xs ~init:M.zero ~f:(fun x y -> (f y >>| M.plus x))
let find xs ~f =
let f x = f x >>| function
| true -> Some x
| false -> None in
find_map xs ~f
let filter_map xs ~f =
let empty = T.zero () in
fold_right xs ~init:empty ~f:(fun x ys -> f x >>| function
| None -> ys
| Some y -> prepend ys y)
let filter xs ~f = filter_map xs ~f:(fun x ->
f x >>| function
| true -> Some x
| false -> None)
end
module Delay(B : Types.Collection.Delay) = struct
module Base = Delay_base(B)
include Make(Base)
end
module Eager(B : Types.Collection.Eager) = struct
module Base = Eager_base(B)
include Make(Base)
end
end
module List = Collection.Delay(struct
type 'a t = 'a list
let fold xs ~init ~f =
let rec loop xs k = match xs with
| [] -> k
| x :: xs -> fun k' -> k (fun a -> loop xs (f a x) k') in
loop xs (fun k -> k init)
let zero () = []
let return x = [x]
let plus = (@)
end)
module Seq = Collection.Delay(struct
type 'a t = 'a Sequence.t
let fold xs ~init ~f finish =
Sequence.delayed_fold xs ~init ~f:(fun a x ~k ->
f a x k) ~finish
let zero () = Sequence.empty [@@inline]
let return x = Sequence.return x [@@inline]
let plus = Sequence.append
end)
let void t = Fn.ignore t
let sequence = List.sequence
let rec forever t = bind t (fun _ -> forever t)
include Syntax
include Let
end
module Make(M : B) : S with type 'a t := 'a M.t =
Make2(struct
type ('a, 'e) t = 'a M.t
include (M : B with type 'a t := 'a M.t)
end)
module Core2(M : Core2) = struct
type ('a,'e) t = ('a,'e) M.t
include Make2(struct
include M
let bind m f = bind m ~f
let map = `Custom map
end)
let join = M.join
let ignore_m = M.ignore_m
let all = M.all
let all_unit = M.all_unit
let all_ignore = M.all_unit
end
the intended usage of this module is
[ ) ) ] to upcast a monad of type [ Core ]
to a monad of type [ S ] , to make it possible
we should n't erase types from this monad , otherwise
this functor would be much harder to use .
Since we ca n't erase types , we ca n't implement Core
module via the Core2 . So we need to repeat the code .
Since , the code does n't contain any implementation ( just
renaming ) it can be considered OK .
[F(Core(M))] to upcast a monad of type [Core]
to a monad of type [S], to make it possible
we shouldn't erase types from this monad, otherwise
this functor would be much harder to use.
Since we can't erase types, we can't implement Core
module via the Core2. So we need to repeat the code.
Since, the code doesn't contain any implementation (just
renaming) it can be considered OK.
*)
module Core(M : Core) = struct
type 'a t = 'a M.t
include Make(struct
include M
let bind m f = bind m ~f
let map = `Custom map
end)
let join = M.join
let ignore_m = M.ignore_m
let all = M.all
let all_unit = M.all_unit
let all_ignore = M.all_unit
end
this module provides a fast and dirty translation from a minimal
monad representation to our maximal . We will not erase types
from the resulting structure , as this functor is expected to
be used as a type caster , e.g. [ Monad . State . Make(Monad . Minimal(M ) ]
monad representation to our maximal. We will not erase types
from the resulting structure, as this functor is expected to
be used as a type caster, e.g. [Monad.State.Make(Monad.Minimal(M)]
*)
module Minimal( M : Minimal) = struct
type 'a t = 'a M.t
include Make(struct
include M
let map = `Define_using_bind
end)
end
module Minimal2( M : Minimal2) = struct
type ('a,'e) t = ('a,'e) M.t
include Make2(struct
include M
let map = `Define_using_bind
end)
end
end
module Ident
: Monad.S with type 'a t = 'a
= struct
type 'a t = 'a
module M = Monad.Make(struct
type 'a t = 'a
let return = ident
let bind m f = m |> f
let map = `Custom (fun x ~f -> f x)
end)
let unit = ()
module Fn = struct
let ignore = ignore
let nothing () = ()
include Fn
end
module Pair = struct
let fst = fst
let snd = snd
end
module Triple = struct
let fst (x,_,_) = x
let snd (_,x,_) = x
let trd (_,_,x) = x
end
module Exn = M.Exn
module Lift = struct
let nullary = ident
let unary = ident
let binary = ident
let ternary = ident
let quaternary = ident
let quinary = ident
end
module Collection = struct
module type S = Types.Collection.S with type 'a m := 'a t
module Eager(T : Types.Collection.Eager) :
S with type 'a t := 'a T.t = struct
include M.Collection.Eager(T)
let all = ident
let all_unit = ignore
let all_ignore = ignore
let iter xs ~f = fold xs ~init:() ~f:(fun () x -> f x)
let fold = fold
end
module Delay(T : Types.Collection.Delay) :
S with type 'a t := 'a T.t = struct
include M.Collection.Delay(T)
let all = ident
let all_unit = ignore
let all_ignore = ignore
let iter xs ~f = fold xs ~init:() ~f:(fun () x -> f x)
let fold = fold
end
end
module List = struct
module Base = Collection.Delay(struct
type 'a t = 'a list
let fold xs ~init ~f =
let rec loop xs k = match xs with
| [] -> k
| x :: xs -> fun k' -> k (fun a -> loop xs (f a x) k') in
loop xs (fun k -> k init)
let zero () = []
let return x = [x]
let plus = (@)
end)
include (Base : Collection.S with type 'a t := 'a list)
include List
let all = ident
let all_unit = ignore
let all_ignore = ignore
end
module Seq = struct
module Base = Collection.Delay(struct
type 'a t = 'a Sequence.t
let fold xs ~init ~f finish =
Sequence.delayed_fold xs ~init ~f:(fun a x ~k ->
f a x k) ~finish
let zero () = Sequence.empty
let return = Sequence.return
let plus = Sequence.append
end)
include (Base : Collection.S with type 'a t := 'a Sequence.t)
include Sequence
let all = ident
let all_unit = ignore
let all_ignore = ignore
end
module Syntax = struct
let (>>=) x f = x |> f [@@inline]
let (>>|) x f = x |> f [@@inline]
let (>=>) f g x = g (f x) [@@inline]
let (!!) = ident
let (!$) = ident
let (!$$) = ident
let (!$$$) = ident
let (!$$$$) = ident
let (!$$$$$) = ident
end
module Let = struct
open Syntax
let (let*) = (>>=)
let (let+) = (>>|)
let (and+) x y =
x >>= fun x ->
y >>| fun y ->
(x,y)
let (and*) = (and+)
end
module Let_syntax = struct
include Syntax
let return = ident
module Let_syntax = struct
let return = ident
let bind x ~f = x |> f
let map x ~f = x |> f
let both x y = x,y
module Open_on_rhs = struct let return = ident end
module Open_in_body = struct let return = ident end
end
end
let all_unit = ignore
let all_ignore = ignore
let all = ident
let ignore_m = ignore
let join = ident
let void = ignore
let rec forever x = forever x
let sequence = all_unit
module Monad_infix = Syntax
include Let_syntax.Let_syntax
include Syntax
include Let
end
module OptionT = struct
include Types.Option
module T1(M : T1) = struct
type 'a t = 'a option M.t
type 'a m = 'a M.t
type 'a e = 'a t
end
module T2(M : T2) = struct
type ('a,'e) t = ('a option, 'e) M.t
type ('a,'e) m = ('a,'e) M.t
type ('a,'e) e = ('a,'e) t
end
module Make2(M : Monad.S2)
: S2 with type ('a,'e) t := ('a,'e) T2(M).t
and type ('a,'e) m := ('a,'e) T2(M).m
and type ('a,'e) e := ('a,'e) T2(M).e
= struct
open M.Syntax
module Basic = struct
include T2(M)
let return x = M.return (Some x)
let bind m f = M.bind m (function
| Some r -> f r
| None -> M.return None)
[@@inline]
let map m ~f = M.bind m (function
| Some r -> M.return (Some (f r))
| None -> M.return None)
[@@inline]
let map = `Custom map
end
type 'a error = unit
let fail () = M.return None
let run = ident
let catch m f = m >>= function
| None -> f ()
| other -> M.return other
let plus m1 m2 = m1 >>= function
| Some m1 -> M.return (Some m1)
| None -> m2
include Choice.Make2(struct
type ('a,'e) t = ('a,'e) Basic.t
let pure = Basic.return
let zero () = M.return None
end)
include Basic
include Monad.Make2(Basic)
let lift = M.map ~f:Option.return
end
module Make(M : Monad.S)
: S with type 'a m := 'a T1(M).m
and type 'a t := 'a T1(M).t
and type 'a e := 'a T1(M).e
= Make2(struct
type ('a,'e) t = 'a M.t
type 'a error = unit
include (M : Monad.S with type 'a t := 'a M.t)
end)
include T1(Ident)
include Make(Ident)
end
module ResultT = struct
include Types.Result
type ('a,'e) result = ('a,'e) Result.t =
| Ok of 'a
| Error of 'e
module type Sp = sig
include Trans.S1
include Monad.S2 with type ('a,'e) t := ('a,'e) t
include Fail.S2 with type ('a,'e) t := ('a,'e) t
end
module Tp(T : T1)(M : Monad.S) = struct
type 'a error = 'a T.t
type 'a m = 'a M.t
type ('a,'e) t = ('a,'e error) result m
type ('a,'e) e = ('a,'e error) result m
end
module Makep(T : T1)(M : Monad.S) : Sp
with type ('a,'e) t := ('a,'e) Tp(T)(M).t
and type 'a m := 'a Tp(T)(M).m
and type ('a,'e) e := ('a,'e) Tp(T)(M).e
and type 'a error = 'a Tp(T)(M).error
= struct
include struct
let (>>=) m f = M.bind m f [@@inline]
let (>>|) m f = M.map m f [@@inline]
end
module Base = struct
include Tp(T)(M)
let return x = M.return (Ok x)
let bind m f : ('a,'e) t = m >>= function
| Ok r -> f r
| Error err -> M.return (Error err)
[@@inline]
let fail err = M.return (Error err)
let run = ident
let catch m f = m >>= function
| Error err -> f err
| other -> M.return other
let lift m = m >>| fun x -> Ok x
let map' m ~f = m >>= function
| Ok r -> return (f r)
| Error err -> M.return (Error err)
[@@inline]
let map = `Custom map'
end
include Base
include Monad.Make2(Base)
end
module T1(T : T)(M : Monad.S) = struct
type error = T.t
type 'a m = 'a M.t
type 'a t = ('a,error) result m
type 'a e = ('a,error) result m
end
module T2(M : Monad.S) = struct
type 'a m = 'a M.t
type ('a,'e) t = ('a,'e) result m
type ('a,'e) e = ('a,'e) result m
end
module Make(T : T)(M : Monad.S) : S
with type 'a t := 'a T1(T)(M).t
and type 'a m := 'a T1(T)(M).m
and type 'a e := 'a T1(T)(M).e
and type err := T.t
= struct
type err = T.t
include Makep(struct type 'a t = T.t end)(M)
end
module Make2(M : Monad.S) : S2
with type ('a,'e) t := ('a,'e) T2(M).t
and type 'a m := 'a T2(M).m
and type ('a,'e) e := ('a,'e) T2(M).e
= Makep(struct type 'a t = 'a end)(M)
module Error = struct
module T(M : Monad.S) = struct
type 'a m = 'a M.t
type 'a t = 'a Or_error.t m
type 'a e = 'a Or_error.t m
end
module type S = sig
include S
val failf : ('a, Caml.Format.formatter, unit, unit -> 'b t) format4 -> 'a
end
module Make(M : Monad.S) : S
with type 'a t := 'a T(M).t
and type 'a m := 'a T(M).m
and type 'a e := 'a T(M).e
and type err := Error.t
= struct
include Make(struct type t = Error.t end)(M)
let failf fmt =
let open Caml.Format in
let buf = Buffer.create 512 in
let ppf = formatter_of_buffer buf in
let kon ppf () =
pp_print_flush ppf ();
let err = Or_error.error_string (Buffer.contents buf) in
M.return err in
kfprintf kon ppf fmt
end
type 'a t = 'a Or_error.t
type 'a m = 'a
type 'a e = 'a Or_error.t
include Make(Ident)
end
module Exception = struct
module T(M : Monad.S) = struct
type 'a m = 'a M.t
type 'a t = ('a,exn) Result.t m
type 'a e = ('a,exn) Result.t m
end
module Make(M : Monad.S) : S
with type 'a t := 'a T(M).t
and type 'a m := 'a T(M).m
and type 'a e := 'a T(M).e
and type err := exn
= Make(struct type t = exn end)(M)
include T(Ident)
include Make(Ident)
end
module Self : S2
with type ('a,'e) t = ('a,'e) result
and type 'a m = 'a
and type ('a,'e) e = ('a,'e) result
= struct
include T2(Ident)
include Make2(Ident)
end
include Self
end
module ListT = struct
include Types.List
module T1(M : T1) = struct
type 'a t = 'a list M.t
type 'a m = 'a M.t
type 'a e = 'a t
end
module T2(M : T2) = struct
type ('a,'e) t = ('a list, 'e) M.t
type ('a,'e) m = ('a,'e) M.t
type ('a,'e) e = ('a,'e) t
end
module Make2(M : Monad.S2)
: S2 with type ('a,'e) m := ('a,'e) T2(M).m
and type ('a,'e) t := ('a,'e) T2(M).t
and type ('a,'e) e := ('a,'e) T2(M).e
= struct
open M.Syntax
type 'a result = 'a list
module Base = struct
include T2(M)
let return x = M.return [x]
let bind xsm f = xsm >>= fun xs ->
List.fold xs ~init:(!![]) ~f:(fun ysm x ->
ysm >>= fun ys -> f x >>| fun xs ->
List.rev_append xs @@ ys) >>| List.rev
let map xsm ~f = xsm >>| List.map ~f
let map = `Custom map
end
include Choice.Make2(struct
type ('a,'e) t = ('a,'e) T2(M).t
let pure x = M.return [x]
let zero () = M.return []
end)
module MT = Monad.Make2(Base)
let plus xsm ysm =
xsm >>= fun xs -> ysm >>= fun ys ->
M.return (xs @ ys)
let run = ident
let lift m = m >>| fun x -> [x]
include MT
end
module Make(M: Monad.S)
: S with type 'a m := 'a T1(M).m
and type 'a t := 'a T1(M).t
and type 'a e := 'a T1(M).e =
Make2(struct
type ('a,'e) t = 'a M.t
include (M : Monad.S with type 'a t := 'a M.t)
end)
module ListM :
S with type 'a t = 'a list and type 'a m = 'a and type 'a e = 'a list = struct
include T1(Ident)
include Make(Ident)
end
include ListM
end
module Seq = struct
include Types.List
module T1(M : T1) = struct
type 'a t = 'a Sequence.t M.t
type 'a m = 'a M.t
type 'a e = 'a t
end
module T2(M : T2) = struct
type ('a,'e) t = ('a Sequence.t, 'e) M.t
type ('a,'e) m = ('a,'e) M.t
type ('a,'e) e = ('a,'e) t
end
module Make2(M : Monad.S2)
: S2 with type ('a,'e) m := ('a,'e) T2(M).m
and type ('a,'e) t := ('a,'e) T2(M).t
and type ('a,'e) e := ('a,'e) T2(M).e
= struct
open M.Syntax
type 'a result = 'a Sequence.t
module Base = struct
include T2(M)
let return x = M.return @@ Sequence.singleton x
let bind xsm f = xsm >>= fun xs ->
Sequence.fold xs ~init:(!!Sequence.empty) ~f:(fun ysm x ->
ysm >>= fun ys -> f x >>| fun xs ->
Sequence.append xs ys)
let map xsm ~f = xsm >>| Sequence.map ~f
let map = `Custom map
end
include Choice.Make2(struct
type ('a,'e) t = ('a,'e) T2(M).t
let pure x = Base.return x
let zero () = M.return Sequence.empty
end)
module MT = Monad.Make2(Base)
let plus xsm ysm =
xsm >>= fun xs -> ysm >>= fun ys ->
M.return (Sequence.append xs ys)
let run = ident
let lift m = m >>| Sequence.singleton
include MT
end
module Make(M : Monad.S)
: S with type 'a m := 'a T1(M).m
and type 'a t := 'a T1(M).t
and type 'a e := 'a T1(M).e
= Make2(struct
type ('a,'e) t = 'a M.t
include (M : Monad.S with type 'a t := 'a M.t)
end)
module SeqM : S
with type 'a t = 'a Sequence.t
and type 'a m = 'a
and type 'a e = 'a Sequence.t =
struct
include T1(Ident)
include Make(Ident)
end
include SeqM
end
module Writer = struct
include Types.Writer
type ('a,'s) writer = Writer of ('a * 's)
module T1(T : Monoid.S)(M : Monad.S) = struct
type state = T.t
type 'a m = 'a M.t
type 'a t = ('a,state) writer m
type 'a e = ('a * state) m
end
module T2(T : Monoid.S)(M : Monad.S2) = struct
type state = T.t
type ('a,'e) m = ('a,'e) M.t
type ('a,'e) t = (('a,state) writer,'e) M.t
type ('a,'e) e = ('a * state, 'e) m
end
module Make2(T : Monoid.S)(M : Monad.S2)
: S2 with type ('a,'e) m := ('a,'e) T2(T)(M).m
and type ('a,'e) t := ('a,'e) T2(T)(M).t
and type ('a,'e) e := ('a,'e) T2(T)(M).e
and type state := T2(T)(M).state
= struct
open M.Syntax
let (+) = T.plus
module Base = struct
include T2(T)(M)
let writer x = Writer x
let return x = M.return @@ writer (x,T.zero)
let bind m f =
m >>= fun (Writer (x,a)) -> f x >>| fun (Writer (x,b)) ->
writer (x,a+b)
let map m ~f = m >>| fun (Writer (x,e)) -> writer (f x,e)
let map = `Custom map
end
include Base
let returnw x = M.return @@ writer x
let write x = M.return @@ writer ((), x)
let read m = m >>= fun (Writer (_,e)) -> returnw (e,e)
let listen m = m >>= fun (Writer (x,e)) -> returnw ((x,e),e)
let run m = m >>| fun (Writer (x,e)) -> (x,e)
let exec m = m >>| fun (Writer ((),e)) -> e
let ignore m = m >>= fun (Writer (_,e)) -> returnw ((),e)
let lift m = M.map m ~f:(fun x -> Writer (x,T.zero))
include Monad.Make2(Base)
end
module Make(T : Monoid.S)(M : Monad.S)
: S with type 'a m := 'a T1(T)(M).m
and type 'a t := 'a T1(T)(M).t
and type 'a e := 'a T1(T)(M).e
and type state := T1(T)(M).state
= struct
module M = struct
type ('a,'e) t = 'a M.t
include (M : Monad.S with type 'a t := 'a M.t)
end
type state = T.t
include Make2(T)(M)
end
end
module Reader = struct
include Types.Reader
type ('a,'e) reader = Reader of ('e -> 'a)
module type Sp = sig
type 'a env
include Trans.S1
val read : unit -> ('e env, 'e ) t
include Monad.S2 with type ('a,'e) t := ('a,'e) t
end
module Tp(T : T1)(M : Monad.S) = struct
type 'a env = 'a T.t
type 'a m = 'a M.t
type ('a,'e) t = ('a m, 'e env) reader
type ('a,'e) e = 'e env -> 'a m
end
module Makep(T : T1)(M : Monad.S) : Sp
with type ('a,'e) t := ('a,'e) Tp(T)(M).t
and type 'a m := 'a Tp(T)(M).m
and type ('a,'e) e := ('a,'e) Tp(T)(M).e
and type 'a env := 'a Tp(T)(M).env
= struct
module Base = struct
include Tp(T)(M)
open M.Monad_infix
let (=>) (Reader run) x = run x
let reader comp = Reader comp
let return x = reader @@ fun _ -> M.return x
let bind m f = reader @@ fun s -> m => s >>= fun x -> f x => s
let map m ~f = reader @@ fun s -> m => s >>| f
let read () = reader @@ fun s -> M.return s
let lift m = reader @@ fun _ -> m
let run m s = m => s
let map = `Custom map
end
include Base
include Monad.Make2(Base)
end
module T1(T : T)(M : Monad.S) = struct
type env = T.t
type 'a m = 'a M.t
type 'a t = ('a m, env) reader
type 'a e = env -> 'a m
end
module T2(M : Monad.S) = struct
type 'a m = 'a M.t
type ('a,'e) t = ('a m,'e) reader
type ('a,'e) e = 'e -> 'a m
end
module Make(T : T)(M : Monad.S): S
with type 'a t := 'a T1(T)(M).t
and type 'a m := 'a T1(T)(M).m
and type 'a e := 'a T1(T)(M).e
and type env := T.t
= Makep(struct type 'a t = T.t end)(M)
module Make2(M : Monad.S) : S2
with type ('a,'e) t := ('a,'e) T2(M).t
and type 'a m := 'a T2(M).m
and type ('a,'e) e := ('a,'e) T2(M).e
= Makep(struct type 'a t = 'a end)(M)
module Self : S2
with type ('a,'e) t = ('a,'e) reader
and type 'a m = 'a
and type ('a,'e) e = 'e -> 'a
= struct
include T2(Ident)
include Make2(Ident)
end
include Self
end
module State = struct
include Types.State
module type Sp = sig
include Trans.S1
include Monad.S2 with type ('a,'s) t := ('a,'s) t
type 'a env
val put : 's env -> (unit,'s) t
val get : unit -> ('s env,'s) t
val gets : ('s env -> 'r) -> ('r,'s) t
val update : ('s env -> 's env) -> (unit,'s) t
val modify : ('a,'s) t -> ('s env -> 's env) -> ('a,'s) t
val eval : ('a,'s) t -> 's env -> 'a m
val exec : ('a,'s) t -> 's env -> 's env m
end
type ('a,'b) storage = {
x : 'a;
s : 'b;
}
type ('a,'e) state = State of ('e -> 'a)
module Tp(T : T1)(M : Monad.S) = struct
type 'a env = 'a T.t
type 'a m = 'a M.t
type ('a,'e) t = (('a,'e env) storage m, 'e env) state
type ('a,'e) e = 'e env -> ('a * 'e env) m
end
module Makep(T : T1)(M : Monad.S) : Sp
with type ('a,'e) t := ('a,'e) Tp(T)(M).t
and type 'a m := 'a Tp(T)(M).m
and type ('a,'e) e := ('a,'e) Tp(T)(M).e
and type 'a env := 'a Tp(T)(M).env
= struct
include struct
let (>>=) m f = M.bind m f [@@inline]
let (>>|) m f = M.map m f [@@inline]
end
let make run = State run [@@inline]
let (=>) (State run) x = run x [@@inline]
type 'a result = 'a M.t
module Basic = struct
include Tp(T)(M)
let return x = (make [@inlined]) (fun s -> M.return {x;s}) [@@inline]
let bind m f = make @@ fun s -> m=>s >>= fun {x;s} -> f x => s [@@inline]
let map m ~f = make @@ fun s -> m=>s >>| fun {x;s} -> {x=f x;s} [@@inline]
let map = `Custom map
end
let put s = make @@ fun _ -> M.return {x=();s} [@@inline]
let get () = make @@ fun s -> M.return {x=s;s} [@@inline]
let gets f = make @@ fun s -> M.return {x=f s;s} [@@inline]
let update f = make @@ fun s -> M.return {x=();s = f s} [@@inline]
let modify m f =
make @@ fun s -> m=>s >>= fun {x;s} -> M.return {x; s = f s} [@@inline]
let run m s = M.(m => s >>| fun {x;s} -> (x,s))
let eval m s = M.(run m s >>| fst)
let exec m s = M.(run m s >>| snd)
let lift m = make @@ fun s -> M.bind m (fun x -> M.return {x;s}) [@@inline]
include Basic
include Monad.Make2(Basic)
end
module T1(T : T)(M : Monad.S) = struct
type env = T.t
type 'a m = 'a M.t
type 'a t = (('a,env) storage m, env) state
type 'a e = env -> ('a * env) m
end
module T2(M : Monad.S) = struct
type 'a m = 'a M.t
type ('a,'e) t = (('a,'e) storage m, 'e) state
type ('a,'e) e = 'e -> ('a * 'e) m
end
module Make(T : T)(M : Monad.S): S
with type 'a t := 'a T1(T)(M).t
and type 'a m := 'a T1(T)(M).m
and type 'a e := 'a T1(T)(M).e
and type env := T.t
= Makep(struct type 'a t = T.t end)(M)
module Make2(M : Monad.S) : S2
with type ('a,'e) t := ('a,'e) T2(M).t
and type 'a m := 'a T2(M).m
and type ('a,'e) e := ('a,'e) T2(M).e
= Makep(struct type 'a t = 'a end)(M)
module Multi = struct
include Types.Multi
module Id = struct
type t = int
let zero = Int.zero
let succ = Int.succ
include Identifiable.Make(struct
type t = int [@@deriving compare, bin_io, hash, sexp]
let module_name = "Monads.Std.Monad.State.Multi.Id"
let to_string = Int.to_string
let of_string = Int.of_string
end)
end
type id = Id.t
type 'e contexts = {
the i d of last created fork
children : Id.Set.t Id.Map.t;
}
module ST1 = T1
module ST2 = T2
module STp = Tp
module type Sp = sig
include Trans.S1
type id
module Id : Identifiable.S with type t = id
val global : id
val fork : unit -> (unit,'e) t
val switch : id -> (unit,'e) t
val parent : unit -> (id,'e) t
val ancestor : id list -> (id,'e) t
val current : unit -> (id,'e) t
val kill : id -> (unit,'e) t
val forks : unit -> (id Sequence.t,'e) t
val status : id -> (status,'e) t
include Sp with type ('a,'e) t := ('a,'e) t
and type ('a,'e) e := ('a,'e) e
and type 'a m := 'a m
end
module T1(T : T)(M : Monad.S) = struct
type env = T.t
type 'a m = 'a M.t
type 'a t = (('a,env contexts) storage m, env contexts) state
type 'a e = env -> ('a * env) m
end
module T2(M : Monad.S) = struct
type 'a m = 'a M.t
type ('a,'e) t = (('a,'e contexts) storage m, 'e contexts) state
type ('a,'e) e = 'e -> ('a * 'e) m
end
module Tp(T : T1)(M : Monad.S) = struct
type 'a env = 'a T.t
type 'a m = 'a M.t
type ('a,'e) t = (('a,'e env contexts) storage m, 'e env contexts) state
type ('a,'e) e = 'e env -> ('a * 'e env) m
end
module Makep(T : T1)(M : Monad.S) : Sp
with type ('a,'e) t := ('a,'e) Tp(T)(M).t
and type ('a,'e) e := ('a,'e) Tp(T)(M).e
and type 'a m := 'a Tp(T)(M).m
and type 'a env := 'a Tp(T)(M).env
and type id := id
and module Id := Id
= struct
module SM = struct
module Env = struct
type 'a t = 'a T.t contexts
end
include STp(Env)(M)
include Makep(Env)(M)
end
open SM.Syntax
include Tp(T)(M)
type id = Id.t
let global = Id.zero
let init ctxt = {
init = ctxt;
created = global;
current = global;
parents = Id.Map.empty;
children = Id.Map.empty;
forks = Id.Map.empty;
}
let rec alive_parent k child =
match Map.find k.parents child with
| None -> global
| Some p when Map.mem k.forks p -> p
| Some zombie -> alive_parent k zombie
let rec ancestor k cs =
match List.map cs ~f:(alive_parent k) with
| [] -> global
| p :: ps when List.for_all ps ~f:(fun p' -> p = p') -> p
| ps -> ancestor k ps
let ancestor cs = SM.gets @@ fun k -> ancestor k cs
let alive k id : id =
if Map.mem k.forks id then id else alive_parent k id
let forks () = SM.gets (fun k ->
let fs = Map.to_sequence k.forks |> Seq.map ~f:fst in
Sequence.shift_right fs global)
let siblings () =
SM.gets (fun k ->
match Map.find k.children (alive_parent k k.current) with
| None -> Id.Set.empty
| Some cs -> Set.filter cs ~f:(Map.mem k.forks))
let context k =
let id = alive k k.current in
if id = global then k.init
else Map.find_exn k.forks k.current
let fork () = SM.update @@ fun k ->
let ctxt = context k in
let current = Id.succ k.created in
let parents = Map.set k.parents ~key:current ~data:k.current in
let forks = Map.set k.forks ~key:current ~data:ctxt in
{k with created=current; current; parents; forks}
let switch id = SM.update @@ fun k -> {k with current = alive k id}
let current () = SM.gets @@ fun k -> alive k k.current
let get () = SM.get () >>| context
let put ctxt = SM.update @@ fun k ->
let id = alive k k.current in
if id = global then {k with init=ctxt} else {
k with forks = Map.set k.forks ~key:id ~data:ctxt
}
let parent () = SM.get () >>| fun k -> alive_parent k k.current
let status id = SM.get () >>| fun k ->
if id = k.current then `Current else
if Map.mem k.forks id then `Live else `Dead
let remove_dead_parents k =
let parents =
Map.fold k.forks ~init:Id.Map.empty ~f:(fun ~key ~data:_ ps ->
Map.set ps ~key ~data:(alive_parent k key)) in
let children = Map.filter_keys k.children ~f:(Map.mem parents) in
{k with children; parents}
let gc k =
if k.created mod 1024 = 0 then remove_dead_parents k else k
let kill id = SM.update @@ fun k ->
gc {
k with
forks = Map.remove k.forks id;
current = if id = k.current then alive_parent k id else id;
}
let gets f = get () >>| f
let update f = get () >>= fun x -> put (f x)
let modify m f = m >>= fun x -> update f >>= fun () -> SM.return x
let run m = fun ctxt -> M.bind (SM.run m (init ctxt)) ~f:(fun (x,cs) ->
M.return (x,cs.init))
include Monad.Make2(struct
type nonrec ('a,'e) t = ('a,'e) t
let return = SM.return
let bind m f = SM.bind m ~f
let map = `Custom SM.map
end)
let lift m = SM.lift m
let eval m s = M.map (run m s) ~f:fst
let exec m s = M.map (run m s) ~f:snd
module Id = Id
end
module Make(T : T)(M : Monad.S): S
with type 'a t := 'a T1(T)(M).t
and type 'a m := 'a T1(T)(M).m
and type 'a e := 'a T1(T)(M).e
and type env := T.t
and type id := id
and module Id := Id
= Makep(struct type 'a t = T.t end)(M)
module Make2(M : Monad.S) : S2
with type ('a,'e) t := ('a,'e) T2(M).t
and type 'a m := 'a T2(M).m
and type ('a,'e) e := ('a,'e) T2(M).e
and type id := id
and module Id := Id
= Makep(struct type 'a t = 'a end)(M)
include T2(Ident)
include Make2(Ident)
end
include T2(Ident)
include Make2(Ident)
let eval m s = fst (run m s)
let exec m s = snd (run m s)
end
module Fun = struct
include Types.Fun
type 'a thunk = Thunk of (unit -> 'a)
module T1(M : Monad.S) = struct
type 'a m = 'a M.t
type 'a t = 'a m thunk
type 'a e = 'a m
end
module T2(M : Monad.S2) = struct
type ('a,'e) m = ('a,'e) M.t
type ('a,'e) t = ('a,'e) m thunk
type ('a,'e) e = ('a,'e) m
end
let thunk f = Thunk f
module Make2(M : Monad.S2) : S2
with type ('a,'e) t := ('a,'e) T2(M).t
and type ('a,'e) m := ('a,'e) T2(M).m
and type ('a,'e) e := ('a,'e) T2(M).e
= struct
open M.Syntax
module Base = struct
include T2(M)
let run (Thunk f) = f ()
let return x = thunk @@ fun () -> M.return x
let bind m f = thunk @@ fun () -> run m >>= fun x -> run (f x)
let map m ~f = thunk @@ fun () -> run m >>| f
let lift m = thunk @@ fun () -> m
let map = `Custom map
end
include Base
include Monad.Make2(Base)
end
module Make(M : Monad.S) : S
with type 'a t := 'a T1(M).t
and type 'a m := 'a T1(M).m
and type 'a e := 'a T1(M).e
= Make2(struct
type ('a,'e) t = 'a M.t
include (M : Monad.S with type 'a t := 'a M.t)
end)
include T1(Ident)
include Make(Ident)
end
module LazyT = struct
include Types.Lazy
module T1(M : Monad.S) = struct
type 'a m = 'a M.t
type 'a t = 'a m Lazy.t
type 'a e = 'a m
end
module T2(M : Monad.S2) = struct
type ('a,'e) m = ('a,'e) M.t
type ('a,'e) t = ('a,'e) m Lazy.t
type ('a,'e) e = ('a,'e) m
end
module Make2(M : Monad.S2) : S2
with type ('a,'e) t := ('a,'e) T2(M).t
and type ('a,'e) m := ('a,'e) T2(M).m
and type ('a,'e) e := ('a,'e) T2(M).e
= struct
open M.Syntax
module Base = struct
include T2(M)
let return x = lazy (M.return x)
let bind m f = lazy (Lazy.force m >>= fun x ->
Lazy.force (f x))
let map = `Define_using_bind
let run = Lazy.force
let lift x = lazy x
end
include Base
include Monad.Make2(Base)
end
module Make(M : Monad.S) : S
with type 'a t := 'a T1(M).t
and type 'a m := 'a T1(M).m
and type 'a e := 'a T1(M).e
= Make2(struct
type ('a,'e) t = 'a M.t
include (M : Monad.S with type 'a t := 'a M.t)
end)
module Self : S
with type 'a t = 'a Lazy.t
and type 'a m = 'a
and type 'a e = 'a
= struct
type 'a t = 'a Lazy.t
type 'a m = 'a
type 'a e = 'a
include Make(Ident)
end
include Self
end
module Cont = struct
include Types.Cont
type ('a,'r) cont = Cont of (('a -> 'r) -> 'r)
module T(M : Monad.S) = struct
type 'a m = 'a M.t
type ('a,'e) t = ('a, 'e m) cont
type ('a,'e) e = ('a -> 'e m) -> 'e m
end
let cont k = Cont k
module Tp(T : T1)(M : Monad.S) = struct
type 'a r = 'a T.t
type 'a m = 'a M.t
type ('a,'e) t = ('a, 'e r m) cont
type ('a,'e) e = ('a -> 'e r m) -> 'e r m
end
module type Sp = sig
include Trans.S1
include Monad.S2 with type ('a,'e) t := ('a,'e) t
type 'a r
val call : f:(cc:('a -> ('r,'e r) t) -> ('a,'e r) t) -> ('a,'e r) t
end
module Makep(T : T1)(M : Monad.S) : Sp
with type ('a,'e) t := ('a,'e) Tp(T)(M).t
and type ('a,'e) e := ('a,'e) Tp(T)(M).e
and type 'a m := 'a Tp(T)(M).m
and type 'a r := 'a Tp(T)(M).r
= struct
open M.Syntax
module Base = struct
include Tp(T)(M)
let run (Cont k) f = k f
let return x = cont @@ fun k -> k x
let lift m = cont @@ fun k -> m >>= k
let bind m f = cont @@ fun k ->
run m @@ fun x -> run (f x) k
let call ~f = cont @@ fun k ->
run (f ~cc:(fun x -> cont @@ fun _ -> k x)) k
let map = `Define_using_bind
end
include Base
include Monad.Make2(Base)
end
module T1(T : T)(M : Monad.S) = struct
type r = T.t
type 'a m = 'a M.t
type 'a t = ('a,r m) cont
type 'a e = ('a -> r m) -> r m
end
module T2(M : Monad.S) = struct
type 'a m = 'a M.t
type ('a,'e) t = ('a, 'e m) cont
type ('a,'e) e = ('a -> 'e m) -> 'e m
end
module Make(T : T)(M : Monad.S): S
with type 'a t := 'a T1(T)(M).t
and type 'a m := 'a T1(T)(M).m
and type 'a e := 'a T1(T)(M).e
and type r := T.t
= Makep(struct type 'a t = T.t end)(M)
module Make2(M : Monad.S) : S2
with type ('a,'e) t := ('a,'e) T2(M).t
and type 'a m := 'a T2(M).m
and type ('a,'e) e := ('a,'e) T2(M).e
= Makep(struct type 'a t = 'a end)(M)
module Self :
S2 with type ('a,'e) t = ('a,'e) cont
and type 'a m = 'a
and type ('a,'e) e = (('a -> 'e) -> 'e)
= struct
type ('a,'e) t = ('a,'e) T(Ident).t
type 'a m = 'a
type ('a,'e) e = ('a -> 'e) -> 'e
include Make2(Ident)
end
include Self
end
module Lazy = LazyT
module List = ListT
module Result = ResultT
module Option = OptionT
include Monad
module Collection = Types.Collection
|
199a4ae2e9a27c5ce58fe12d50ae5e79d4caee6ba2ffea0e3ef04b1c66d51e34 | RyanMcG/Cadence | user.clj | (ns cadence.views.user
(:require [cadence.views.common :as common]
[cadence.model :as m]
[cadence.model.flash :as flash]
[cadence.model.recaptcha :as recaptcha]
[cadence.model.validators :as is-valid]
[cadence.pattern-recognition :as patrec]
[ring.util.anti-forgery :refer [anti-forgery-field]]
[noir.validation :as vali]
[noir.session :as sess]
[noir.response :as resp])
(:use (hiccup core page def element util)))
(defn profile [{{:keys [username]} :route-params :as request}]
(if (= username (m/identity))
(common/layout
; When there are a suffecient number of training cadences adn the
(when (<= @patrec/training-min (count (patrec/kept-cadences)))
(let [user-id (:_id (m/get-auth))
phrase-id (:_id (sess/get :training-phrase))]
; Add cadences to mongo
(m/add-cadences user-id phrase-id (sess/get :training-cadences))
; Add the current user-id to array of trained users on the given
; phrase
(m/add-trained-user-to-phrase user-id phrase-id))
; Remove the cadenences from training stored in the client's session.
(sess/remove! :training-cadences)
(sess/remove! :training-phrase)
; Let the user know they've been a good minion ;-).
(common/alert :success "Congratulations!"
"You've sucessfully completed training!"))
[:div.page-header [:h1 username]]
[:div.container-fluid
[:div.row-fluid
[:div.span12
; No real content currently so let's just ignore this.
[:div.hero-unit
[:h2 "Hello there!"
[:p "Unfortunately, your profile is pretty boring right now."
" This should change in the near future."]]]]]])
(do
(flash/put! :error (str "You cannot access " username "'s page."))
(resp/redirect (str "/user/profile/" (m/identity))))))
(defn profile-base [request]
Simply forward /user / profile acesses to that of the signed in user .
(resp/redirect (str "/user/profile/" (m/identity))))
; ----
; ## User Signup and Login
(defn login [{:keys [login-failed username]}]
; Defines a simple inline form. Friend does all of the work.
(common/layout
[:div.page-header [:h1 "Login"]]
(common/default-form
:#login.well.form-inline
{:action "/login" :method "POST"}
[{:type "username" :name "Username" :params {:value username}}
{:type "password" :name "Password"}
(anti-forgery-field)]
[{:value "Log In"}])
(when (= login-failed "Y")
(common/alert :error "Sorry!" "You used a bad username/password."))))
(defn- clear-identity
"Removes authentication related `::identity` from the session data."
[response]
; Shamelessly stolen from friend (it's defined privately there)
(update-in response [:session] dissoc ::identity))
(defn logout [request]
(flash/put! :success "You have been logged out.")
; Calls `clear-identity` on the response to remove authentication information
; from the session.
(sess/clear!)
(clear-identity (resp/redirect "/")))
(defn signup
"A nice signup page with validation."
[user]
(common/layout
[:div.page-header [:h1 "Sign Up"]]
; Make the recaptcha theme 'clean'
[:script "var RecaptchaOptions = { theme : 'clean' };"]
(common/control-group-form
:#login.well.form-horizontal
{:action "/signup" :method "POST"}
[{:type "username" :name "Username" :required "yes"
` on user input to avoid XSS .
:value (escape-html (:usernam user))}
{:type "text" :name "Name" :placeholder "Optional"
:value (escape-html (:name user))}
{:type "email" :name "Email" :placeholder "Optional"
:value (escape-html (:email user))}
{:type "password" :name "Password" :required "yes"
:value (:password user)}
{:type "password" :name "Repeat Password"
:required "yes"}
(anti-forgery-field)
; Uses the special case `:type "custom"` to use any html as the form.
; Here there purpose is to add a captcha.
{:type "custom"
:name "Humans only"
:content (recaptcha/get-html
(escape-html (get user :errors)))}]
[{:eclass :.btn-primary
:value "Sign Up"}])))
(defn signup-check [{user :params}]
Validate user signup info and add them to mongo on success .
(if (is-valid/user? user)
(try
; Here we try adding a user
(m/add-user (select-keys user [:username :name :email :password]))
(flash/put! :success "You've signed up! Now try and login.")
(resp/redirect "/login")
(catch com.mongodb.MongoException e
; `username` is a unique key so if there's a mongo exception it's
; probably a duplicate username.
(flash/now! :error "Error: " "Sorry, that username is already in use.")
; Manually set an error on the username field.
(vali/set-error :username "Please try a different username.")
; Render the signup page so the client can try a different username.
(signup user)))
(do
; Bad user input? Let them know
(flash/now! :error "Sorry, but your input has some validation errors.")
; and then load the page again.
(signup user))))
| null | https://raw.githubusercontent.com/RyanMcG/Cadence/c7364cba7e2de48c8a0b90f0f4d16a8248c097d4/src/cadence/views/user.clj | clojure | When there are a suffecient number of training cadences adn the
Add cadences to mongo
Add the current user-id to array of trained users on the given
phrase
Remove the cadenences from training stored in the client's session.
Let the user know they've been a good minion ;-).
No real content currently so let's just ignore this.
----
## User Signup and Login
Defines a simple inline form. Friend does all of the work.
Shamelessly stolen from friend (it's defined privately there)
Calls `clear-identity` on the response to remove authentication information
from the session.
Make the recaptcha theme 'clean'
Uses the special case `:type "custom"` to use any html as the form.
Here there purpose is to add a captcha.
Here we try adding a user
`username` is a unique key so if there's a mongo exception it's
probably a duplicate username.
Manually set an error on the username field.
Render the signup page so the client can try a different username.
Bad user input? Let them know
and then load the page again. | (ns cadence.views.user
(:require [cadence.views.common :as common]
[cadence.model :as m]
[cadence.model.flash :as flash]
[cadence.model.recaptcha :as recaptcha]
[cadence.model.validators :as is-valid]
[cadence.pattern-recognition :as patrec]
[ring.util.anti-forgery :refer [anti-forgery-field]]
[noir.validation :as vali]
[noir.session :as sess]
[noir.response :as resp])
(:use (hiccup core page def element util)))
(defn profile [{{:keys [username]} :route-params :as request}]
(if (= username (m/identity))
(common/layout
(when (<= @patrec/training-min (count (patrec/kept-cadences)))
(let [user-id (:_id (m/get-auth))
phrase-id (:_id (sess/get :training-phrase))]
(m/add-cadences user-id phrase-id (sess/get :training-cadences))
(m/add-trained-user-to-phrase user-id phrase-id))
(sess/remove! :training-cadences)
(sess/remove! :training-phrase)
(common/alert :success "Congratulations!"
"You've sucessfully completed training!"))
[:div.page-header [:h1 username]]
[:div.container-fluid
[:div.row-fluid
[:div.span12
[:div.hero-unit
[:h2 "Hello there!"
[:p "Unfortunately, your profile is pretty boring right now."
" This should change in the near future."]]]]]])
(do
(flash/put! :error (str "You cannot access " username "'s page."))
(resp/redirect (str "/user/profile/" (m/identity))))))
(defn profile-base [request]
Simply forward /user / profile acesses to that of the signed in user .
(resp/redirect (str "/user/profile/" (m/identity))))
(defn login [{:keys [login-failed username]}]
(common/layout
[:div.page-header [:h1 "Login"]]
(common/default-form
:#login.well.form-inline
{:action "/login" :method "POST"}
[{:type "username" :name "Username" :params {:value username}}
{:type "password" :name "Password"}
(anti-forgery-field)]
[{:value "Log In"}])
(when (= login-failed "Y")
(common/alert :error "Sorry!" "You used a bad username/password."))))
(defn- clear-identity
"Removes authentication related `::identity` from the session data."
[response]
(update-in response [:session] dissoc ::identity))
(defn logout [request]
(flash/put! :success "You have been logged out.")
(sess/clear!)
(clear-identity (resp/redirect "/")))
(defn signup
"A nice signup page with validation."
[user]
(common/layout
[:div.page-header [:h1 "Sign Up"]]
[:script "var RecaptchaOptions = { theme : 'clean' };"]
(common/control-group-form
:#login.well.form-horizontal
{:action "/signup" :method "POST"}
[{:type "username" :name "Username" :required "yes"
` on user input to avoid XSS .
:value (escape-html (:usernam user))}
{:type "text" :name "Name" :placeholder "Optional"
:value (escape-html (:name user))}
{:type "email" :name "Email" :placeholder "Optional"
:value (escape-html (:email user))}
{:type "password" :name "Password" :required "yes"
:value (:password user)}
{:type "password" :name "Repeat Password"
:required "yes"}
(anti-forgery-field)
{:type "custom"
:name "Humans only"
:content (recaptcha/get-html
(escape-html (get user :errors)))}]
[{:eclass :.btn-primary
:value "Sign Up"}])))
(defn signup-check [{user :params}]
Validate user signup info and add them to mongo on success .
(if (is-valid/user? user)
(try
(m/add-user (select-keys user [:username :name :email :password]))
(flash/put! :success "You've signed up! Now try and login.")
(resp/redirect "/login")
(catch com.mongodb.MongoException e
(flash/now! :error "Error: " "Sorry, that username is already in use.")
(vali/set-error :username "Please try a different username.")
(signup user)))
(do
(flash/now! :error "Sorry, but your input has some validation errors.")
(signup user))))
|
31a0cfbbe7e505941a9d12296d52359636c9fb2d4e1ca84d72ad92c0e81b2af9 | weblocks-framework/weblocks | excerpt.lisp |
(in-package :weblocks-test)
;;; Test excerpt-presentation render-view-field-value
(deftest-html excerpt-presentation-render-view-field-value-1
(render-view-field-value "Hello World!"
(make-instance 'excerpt-presentation)
(make-instance 'data-view-field
:slot-name 'foo)
(make-instance 'data-view)
nil *joe*)
(:span :class "value" "Hello World!"))
(deftest-html excerpt-presentation-render-view-field-value-2
(render-view-field-value "Hello World! Hello World! Hello World! Hello World!"
(make-instance 'excerpt-presentation)
(make-instance 'data-view-field
:slot-name 'foo)
(make-instance 'data-view)
nil *joe*)
(:span :class "value" "Hello World! He"
(:span :class "ellipsis" "...")))
;;; Test excerpt-presentation print-view-field-value
(deftest excerpt-presentation-print-view-field-value-1
(print-view-field-value "Hello World!"
(make-instance 'excerpt-presentation)
(make-instance 'data-view-field
:slot-name 'foo)
(make-instance 'data-view)
nil *joe*)
"Hello World!")
(deftest excerpt-presentation-print-view-field-value-2
(print-view-field-value "Hello World! Hello World! Hello World! Hello World!"
(make-instance 'excerpt-presentation)
(make-instance 'data-view-field
:slot-name 'foo)
(make-instance 'data-view)
nil *joe*)
"Hello World! He")
| null | https://raw.githubusercontent.com/weblocks-framework/weblocks/fe96152458c8eb54d74751b3201db42dafe1708b/test/views/types/presentations/excerpt.lisp | lisp | Test excerpt-presentation render-view-field-value
Test excerpt-presentation print-view-field-value |
(in-package :weblocks-test)
(deftest-html excerpt-presentation-render-view-field-value-1
(render-view-field-value "Hello World!"
(make-instance 'excerpt-presentation)
(make-instance 'data-view-field
:slot-name 'foo)
(make-instance 'data-view)
nil *joe*)
(:span :class "value" "Hello World!"))
(deftest-html excerpt-presentation-render-view-field-value-2
(render-view-field-value "Hello World! Hello World! Hello World! Hello World!"
(make-instance 'excerpt-presentation)
(make-instance 'data-view-field
:slot-name 'foo)
(make-instance 'data-view)
nil *joe*)
(:span :class "value" "Hello World! He"
(:span :class "ellipsis" "...")))
(deftest excerpt-presentation-print-view-field-value-1
(print-view-field-value "Hello World!"
(make-instance 'excerpt-presentation)
(make-instance 'data-view-field
:slot-name 'foo)
(make-instance 'data-view)
nil *joe*)
"Hello World!")
(deftest excerpt-presentation-print-view-field-value-2
(print-view-field-value "Hello World! Hello World! Hello World! Hello World!"
(make-instance 'excerpt-presentation)
(make-instance 'data-view-field
:slot-name 'foo)
(make-instance 'data-view)
nil *joe*)
"Hello World! He")
|
aec75e395322fbdfc2273762085c2f0ee3a6ebaf5f8758ef5d6cfa915b738bae | slipstream/SlipStreamServer | test_utils.clj | (ns com.sixsq.slipstream.ssclj.resources.event.test-utils
(:require
[clj-time.core :as time]
[clj-time.format :as time-fmt]
[clojure.data.json :as json]
[clojure.string :as str]
[clojure.test :refer [is]]
[com.sixsq.slipstream.ssclj.middleware.authn-info-header :refer [authn-info-header]]
[com.sixsq.slipstream.ssclj.resources.lifecycle-test-utils :as ltu]
[peridot.core :refer :all]
[ring.util.codec :as rc]))
(defn to-time
"Tries to parse the given string as a DateTime value. Returns the DateTime
instance on success and nil on failure."
[s]
(time-fmt/parse (:date-time time-fmt/formatters) s))
(defn- urlencode-param
[p]
(->> (re-seq #"([^=]*)=(.*)" p)
first
next
(map rc/url-encode)
(str/join "=")))
(defn urlencode-params
[query-string]
(if (empty? query-string)
query-string
(let [params (subs query-string 1)]
(->> (str/split params #"&")
(map urlencode-param)
(str/join "&")
(str "?")))))
(defn exec-request
([uri query-string auth-name]
(-> (ltu/ring-app)
session
(content-type "application/json")
(header authn-info-header auth-name)
(request (str uri (urlencode-params query-string))
:content-type "application/x-www-form-urlencoded")
(ltu/body->edn)))
([uri query-string auth-name http-verb body]
(-> (ltu/ring-app)
session
(content-type "application/json")
(header authn-info-header auth-name)
(request (str uri (urlencode-params query-string))
:body (json/write-str body)
:request-method http-verb
:content-type "application/json")
(ltu/body->edn))))
(defn is-count
([uri expected-count query-string auth-name]
(-> (exec-request uri query-string auth-name)
(ltu/is-status 200)
(ltu/is-key-value :count expected-count))))
(defn are-counts
([key-to-count base-uri auth-name expected-count query-string]
(are-counts key-to-count base-uri auth-name expected-count expected-count query-string))
([key-to-count base-uri auth-name expected-count expected-paginated-count query-string]
(-> (exec-request base-uri query-string auth-name)
(ltu/is-status 200)
(ltu/is-key-value :count expected-count)
(ltu/is-key-value count key-to-count expected-paginated-count))))
(def not-before? (complement time/before?))
(defn ordered-desc?
[timestamps]
(every? (fn [[a b]] (not-before? (to-time a) (to-time b))) (partition 2 1 timestamps)))
(def not-after? (complement time/after?))
(defn ordered-asc?
[timestamps]
(every? (fn [[a b]] (not-after? (to-time a) (to-time b))) (partition 2 1 timestamps)))
| null | https://raw.githubusercontent.com/slipstream/SlipStreamServer/3ee5c516877699746c61c48fc72779fe3d4e4652/cimi-resources/test/com/sixsq/slipstream/ssclj/resources/event/test_utils.clj | clojure | (ns com.sixsq.slipstream.ssclj.resources.event.test-utils
(:require
[clj-time.core :as time]
[clj-time.format :as time-fmt]
[clojure.data.json :as json]
[clojure.string :as str]
[clojure.test :refer [is]]
[com.sixsq.slipstream.ssclj.middleware.authn-info-header :refer [authn-info-header]]
[com.sixsq.slipstream.ssclj.resources.lifecycle-test-utils :as ltu]
[peridot.core :refer :all]
[ring.util.codec :as rc]))
(defn to-time
"Tries to parse the given string as a DateTime value. Returns the DateTime
instance on success and nil on failure."
[s]
(time-fmt/parse (:date-time time-fmt/formatters) s))
(defn- urlencode-param
[p]
(->> (re-seq #"([^=]*)=(.*)" p)
first
next
(map rc/url-encode)
(str/join "=")))
(defn urlencode-params
[query-string]
(if (empty? query-string)
query-string
(let [params (subs query-string 1)]
(->> (str/split params #"&")
(map urlencode-param)
(str/join "&")
(str "?")))))
(defn exec-request
([uri query-string auth-name]
(-> (ltu/ring-app)
session
(content-type "application/json")
(header authn-info-header auth-name)
(request (str uri (urlencode-params query-string))
:content-type "application/x-www-form-urlencoded")
(ltu/body->edn)))
([uri query-string auth-name http-verb body]
(-> (ltu/ring-app)
session
(content-type "application/json")
(header authn-info-header auth-name)
(request (str uri (urlencode-params query-string))
:body (json/write-str body)
:request-method http-verb
:content-type "application/json")
(ltu/body->edn))))
(defn is-count
([uri expected-count query-string auth-name]
(-> (exec-request uri query-string auth-name)
(ltu/is-status 200)
(ltu/is-key-value :count expected-count))))
(defn are-counts
([key-to-count base-uri auth-name expected-count query-string]
(are-counts key-to-count base-uri auth-name expected-count expected-count query-string))
([key-to-count base-uri auth-name expected-count expected-paginated-count query-string]
(-> (exec-request base-uri query-string auth-name)
(ltu/is-status 200)
(ltu/is-key-value :count expected-count)
(ltu/is-key-value count key-to-count expected-paginated-count))))
(def not-before? (complement time/before?))
(defn ordered-desc?
[timestamps]
(every? (fn [[a b]] (not-before? (to-time a) (to-time b))) (partition 2 1 timestamps)))
(def not-after? (complement time/after?))
(defn ordered-asc?
[timestamps]
(every? (fn [[a b]] (not-after? (to-time a) (to-time b))) (partition 2 1 timestamps)))
| |
0b00d88afadb908be68f1fb94ef4c025fb03c0ea0e5d2ef4a7fdd902bfd64598 | greghendershott/frog | non-posts.rkt | #lang racket/base
(require racket/require
markdown
(multi-in racket (file match path string))
threading
"../config/private/load.rkt"
"bodies-page.rkt"
"paths.rkt"
"post-struct.rkt"
"read-scribble.rkt"
"stale.rkt"
"template.rkt"
(except-in "util.rkt" path-get-extension)
"verbosity.rkt"
"xexpr2text.rkt")
(provide clean-non-post-output-files
build-non-post-pages)
(module+ test (require rackunit))
(define non-post-file-px #px"\\.(?:md|markdown|mdt|scrbl)$")
;; NOTE: Since the user may manually plop HTML files anywhere in
;; (www-path), we can't just go around deleting those. Instead, we
;; need to iterate sources and delete only HTMLs corresponding to
;; those.
(define (clean-non-post-output-files)
(define (maybe-delete path type v)
(define-values (_ name __) (split-path path))
(when (and (eq? type 'file)
(regexp-match? non-post-file-px path)
(not (regexp-match? post-file-px (path->string name))))
(define dest-path (build-path (www-path)
(~> path
(path-replace-suffix ".html")
abs->rel/src)))
(delete-file* dest-path abs->rel/www)))
(fold-files maybe-delete '() (src-path) #f))
- > ( string ? )
(fold-files write-non-post-page '() (src-path) #f))
(define (write-non-post-page path type v)
(let/ec return
(define-values (path-to name __) (split-path path))
(unless (and (eq? type 'file)
(regexp-match? non-post-file-px path)
(not (regexp-match? post-file-px (path->string name))))
(return v))
(define dest-path (build-path (www-path)
(~> path
(path-replace-suffix ".html")
abs->rel/src)))
(define uri-path (canonical-uri (abs->rel/www dest-path)))
(unless (stale? dest-path path (page-template.html))
(prn2 "Already up-to-date: ~a" dest-path)
(return (cons uri-path v)))
(prn1 "Reading non-post ~a" (abs->rel/src path))
(define xs
(~> (match (path->string name)
[(pregexp "\\.scrbl$")
(define img-dest (path-replace-suffix dest-path ""))
(read-scribble-file path
#:img-local-path img-dest
#:img-uri-prefix (canonical-uri
(abs->rel/www img-dest)))]
[(pregexp "\\.(?:md|markdown)$")
(parse-markdown path)]
[(pregexp "\\.mdt$")
(define text (render-template path-to (path->string name) '()))
(parse-markdown text)])
enhance-body))
(prn1 "Generating non-post ~a" (abs->rel/www dest-path))
(~> xs
xexprs->string
(bodies->page #:title (make-title xs path)
#:description (xexprs->description xs)
#:uri-path uri-path)
(display-to-file* dest-path #:exists 'replace))
(cons uri-path v)))
(define (make-title xs path)
(or (for/or ([x (in-list xs)])
(match x
;; First h1 header, if any -- Scribble style with <a> anchor
[`(h1 (,_ ...) (a . ,_) . ,els)
(string-join (map xexpr->markdown els) "")]
;; First h1 header, if any -- otherwise
[`(h1 (,_ ...) . ,els)
(string-join (map xexpr->markdown els) "")]
[_ #f]))
;; Else name of the source file
(~> path
(path-replace-suffix "")
file-name-from-path
path->string)))
(module+ test
(check-equal?
(make-title '((h1 () "The Title")
(h1 () "Not the title")
(p () "Blah blah"))
#f)
"The Title")
(check-equal?
(make-title
'((h1 () (a ((name "(part._.The_.Title)"))) "The Title")
(h1 () "1" (tt () nbsp) (a ((name "(part._.Section_1)"))) "Section 1")
(p () "Here is some text."))
#f)
"The Title"))
| null | https://raw.githubusercontent.com/greghendershott/frog/93d8b442c2e619334612b7e2d091e4eb33995021/frog/private/non-posts.rkt | racket | NOTE: Since the user may manually plop HTML files anywhere in
(www-path), we can't just go around deleting those. Instead, we
need to iterate sources and delete only HTMLs corresponding to
those.
First h1 header, if any -- Scribble style with <a> anchor
First h1 header, if any -- otherwise
Else name of the source file | #lang racket/base
(require racket/require
markdown
(multi-in racket (file match path string))
threading
"../config/private/load.rkt"
"bodies-page.rkt"
"paths.rkt"
"post-struct.rkt"
"read-scribble.rkt"
"stale.rkt"
"template.rkt"
(except-in "util.rkt" path-get-extension)
"verbosity.rkt"
"xexpr2text.rkt")
(provide clean-non-post-output-files
build-non-post-pages)
(module+ test (require rackunit))
(define non-post-file-px #px"\\.(?:md|markdown|mdt|scrbl)$")
(define (clean-non-post-output-files)
(define (maybe-delete path type v)
(define-values (_ name __) (split-path path))
(when (and (eq? type 'file)
(regexp-match? non-post-file-px path)
(not (regexp-match? post-file-px (path->string name))))
(define dest-path (build-path (www-path)
(~> path
(path-replace-suffix ".html")
abs->rel/src)))
(delete-file* dest-path abs->rel/www)))
(fold-files maybe-delete '() (src-path) #f))
- > ( string ? )
(fold-files write-non-post-page '() (src-path) #f))
(define (write-non-post-page path type v)
(let/ec return
(define-values (path-to name __) (split-path path))
(unless (and (eq? type 'file)
(regexp-match? non-post-file-px path)
(not (regexp-match? post-file-px (path->string name))))
(return v))
(define dest-path (build-path (www-path)
(~> path
(path-replace-suffix ".html")
abs->rel/src)))
(define uri-path (canonical-uri (abs->rel/www dest-path)))
(unless (stale? dest-path path (page-template.html))
(prn2 "Already up-to-date: ~a" dest-path)
(return (cons uri-path v)))
(prn1 "Reading non-post ~a" (abs->rel/src path))
(define xs
(~> (match (path->string name)
[(pregexp "\\.scrbl$")
(define img-dest (path-replace-suffix dest-path ""))
(read-scribble-file path
#:img-local-path img-dest
#:img-uri-prefix (canonical-uri
(abs->rel/www img-dest)))]
[(pregexp "\\.(?:md|markdown)$")
(parse-markdown path)]
[(pregexp "\\.mdt$")
(define text (render-template path-to (path->string name) '()))
(parse-markdown text)])
enhance-body))
(prn1 "Generating non-post ~a" (abs->rel/www dest-path))
(~> xs
xexprs->string
(bodies->page #:title (make-title xs path)
#:description (xexprs->description xs)
#:uri-path uri-path)
(display-to-file* dest-path #:exists 'replace))
(cons uri-path v)))
(define (make-title xs path)
(or (for/or ([x (in-list xs)])
(match x
[`(h1 (,_ ...) (a . ,_) . ,els)
(string-join (map xexpr->markdown els) "")]
[`(h1 (,_ ...) . ,els)
(string-join (map xexpr->markdown els) "")]
[_ #f]))
(~> path
(path-replace-suffix "")
file-name-from-path
path->string)))
(module+ test
(check-equal?
(make-title '((h1 () "The Title")
(h1 () "Not the title")
(p () "Blah blah"))
#f)
"The Title")
(check-equal?
(make-title
'((h1 () (a ((name "(part._.The_.Title)"))) "The Title")
(h1 () "1" (tt () nbsp) (a ((name "(part._.Section_1)"))) "Section 1")
(p () "Here is some text."))
#f)
"The Title"))
|
1af96ff5df86661de30a4b3d4e4d3f853dd805c7e3fad1cbb52f3a22e524583f | haskell-repa/repa | Reduction.hs |
module Data.Repa.Eval.Generic.Par.Reduction
( foldAll
, foldInner)
where
import Data.Repa.Eval.Gang
import GHC.Exts
import qualified Data.Repa.Eval.Generic.Seq.Reduction as Seq
import Data.IORef
-- | Parallel tree reduction of an array to a single value. Each thread takes an
-- equally sized chunk of the data and computes a partial sum. The main thread
-- then reduces the array of partial sums to the final result.
--
-- We don't require that the initial value be a neutral element, so each thread
computes a fold1 on its chunk of the data , and the seed element is only
-- applied in the final reduction step.
--
foldAll :: Gang -- ^ Gang to run the operation on.
-> (Int# -> a) -- ^ Function to get an element from the source.
-> (a -> a -> a) -- ^ Binary associative combining function.
-> a -- ^ Starting value.
-> Int# -- ^ Number of elements.
-> IO a
foldAll !gang f c !z !len
| 1# <- len ==# 0# = return z
| otherwise
= do result <- newIORef z
gangIO gang
$ \tid -> fill result (split tid) (split (tid +# 1#))
readIORef result
where
!threads = gangSize gang
!step = (len +# threads -# 1#) `quotInt#` threads
split !ix = len `foldAll_min` (ix *# step)
foldAll_min x y
= case x <=# y of
1# -> x
_ -> y
# NOINLINE foldAll_min #
NOINLINE to hide the branch from the simplifier .
foldAll_combine result x
= atomicModifyIORef result (\x' -> (c x x', ()))
# NOINLINE foldAll_combine #
NOINLINE because we want to keep the final use of the combining
-- function separate from the main use in 'fill'. If the combining
function contains a branch then the combination of two instances
-- can cause code explosion.
fill !result !start !end
| 1# <- start >=# end = return ()
| otherwise
= let !x = Seq.foldRange f c (f start) (start +# 1#) end
in foldAll_combine result x
# INLINE fill #
{-# INLINE [1] foldAll #-}
-- | Parallel reduction of a multidimensional array along the innermost dimension.
-- Each output value is computed by a single thread, with the output values
-- distributed evenly amongst the available threads.
foldInner
:: Gang -- ^ Gang to run the operation on.
-> (Int# -> a -> IO ()) -- ^ Function to write into the result buffer.
-> (Int# -> a) -- ^ Function to get an element from the source.
-> (a -> a -> a) -- ^ Binary associative combination operator.
-> a -- ^ Neutral starting value.
-> Int# -- ^ Total length of source.
-> Int# -- ^ Inner dimension (length to fold over).
-> IO ()
foldInner gang write f c !r !len !n
= gangIO gang
$ \tid -> fill (split tid) (split (tid +# 1#))
where
!threads = gangSize gang
!step = (len +# threads -# 1#) `quotInt#` threads
split !ix
= let !ix' = ix *# step
in case len <# ix' of
1# -> len
_ -> ix'
# INLINE split #
fill !start !end
= iter start (start *# n)
where
iter !sh !sz
| 1# <- sh >=# end = return ()
| otherwise
= do let !next = sz +# n
write sh (Seq.foldRange f c r sz next)
iter (sh +# 1#) next
# INLINE iter #
# INLINE fill #
# INLINE [ 1 ] foldInner #
| null | https://raw.githubusercontent.com/haskell-repa/repa/c867025e99fd008f094a5b18ce4dabd29bed00ba/repa-eval/Data/Repa/Eval/Generic/Par/Reduction.hs | haskell | | Parallel tree reduction of an array to a single value. Each thread takes an
equally sized chunk of the data and computes a partial sum. The main thread
then reduces the array of partial sums to the final result.
We don't require that the initial value be a neutral element, so each thread
applied in the final reduction step.
^ Gang to run the operation on.
^ Function to get an element from the source.
^ Binary associative combining function.
^ Starting value.
^ Number of elements.
function separate from the main use in 'fill'. If the combining
can cause code explosion.
# INLINE [1] foldAll #
| Parallel reduction of a multidimensional array along the innermost dimension.
Each output value is computed by a single thread, with the output values
distributed evenly amongst the available threads.
^ Gang to run the operation on.
^ Function to write into the result buffer.
^ Function to get an element from the source.
^ Binary associative combination operator.
^ Neutral starting value.
^ Total length of source.
^ Inner dimension (length to fold over). |
module Data.Repa.Eval.Generic.Par.Reduction
( foldAll
, foldInner)
where
import Data.Repa.Eval.Gang
import GHC.Exts
import qualified Data.Repa.Eval.Generic.Seq.Reduction as Seq
import Data.IORef
computes a fold1 on its chunk of the data , and the seed element is only
-> IO a
foldAll !gang f c !z !len
| 1# <- len ==# 0# = return z
| otherwise
= do result <- newIORef z
gangIO gang
$ \tid -> fill result (split tid) (split (tid +# 1#))
readIORef result
where
!threads = gangSize gang
!step = (len +# threads -# 1#) `quotInt#` threads
split !ix = len `foldAll_min` (ix *# step)
foldAll_min x y
= case x <=# y of
1# -> x
_ -> y
# NOINLINE foldAll_min #
NOINLINE to hide the branch from the simplifier .
foldAll_combine result x
= atomicModifyIORef result (\x' -> (c x x', ()))
# NOINLINE foldAll_combine #
NOINLINE because we want to keep the final use of the combining
function contains a branch then the combination of two instances
fill !result !start !end
| 1# <- start >=# end = return ()
| otherwise
= let !x = Seq.foldRange f c (f start) (start +# 1#) end
in foldAll_combine result x
# INLINE fill #
foldInner
-> IO ()
foldInner gang write f c !r !len !n
= gangIO gang
$ \tid -> fill (split tid) (split (tid +# 1#))
where
!threads = gangSize gang
!step = (len +# threads -# 1#) `quotInt#` threads
split !ix
= let !ix' = ix *# step
in case len <# ix' of
1# -> len
_ -> ix'
# INLINE split #
fill !start !end
= iter start (start *# n)
where
iter !sh !sz
| 1# <- sh >=# end = return ()
| otherwise
= do let !next = sz +# n
write sh (Seq.foldRange f c r sz next)
iter (sh +# 1#) next
# INLINE iter #
# INLINE fill #
# INLINE [ 1 ] foldInner #
|
ae2a593b240eaeae6730f9d809868343c266b342634431615f0a4816d5e1e069 | racket/redex | iswim-language-pict.rkt | #lang racket/base
(require redex
texpict/mrpict
"../iswim/iswim.rkt")
;; type this at the prompt:
#;(render-language iswim)
| null | https://raw.githubusercontent.com/racket/redex/4c2dc96d90cedeb08ec1850575079b952c5ad396/redex-test/redex/tests/sewpr/typeset/iswim-language-pict.rkt | racket | type this at the prompt:
(render-language iswim) | #lang racket/base
(require redex
texpict/mrpict
"../iswim/iswim.rkt")
|
66aed879c2caed55e7b42931b1d575ec7d4e17a9d57f180e610b349814450e21 | Smoltbob/Caml-Est-Belle | tuple3.ml | let rec f x =
let (a,b)= x in
x
in let (y,z)= f (1,2) in () | null | https://raw.githubusercontent.com/Smoltbob/Caml-Est-Belle/3d6f53d4e8e01bbae57a0a402b7c0f02f4ed767c/tests/typechecking/valid/tuple3.ml | ocaml | let rec f x =
let (a,b)= x in
x
in let (y,z)= f (1,2) in () | |
4b2eea3126505f4519036835eaa63e609c21ba04395d8a8cb7e3e57306393095 | sionescu/bordeaux-threads | atomics-java.lisp | ;;;; -*- indent-tabs-mode: nil -*-
(in-package :bordeaux-threads-2)
(defstruct (atomic-integer
(:constructor %make-atomic-integer (cell)))
"Wrapper for java.util.concurrent.AtomicLong."
cell)
(defmethod print-object ((aint atomic-integer) stream)
(print-unreadable-object (aint stream :type t :identity t)
(format stream "~S" (atomic-integer-value aint))))
(deftype %atomic-integer-value ()
'(unsigned-byte 63))
(defun make-atomic-integer (&key (value 0))
(check-type value %atomic-integer-value)
(%make-atomic-integer
(jnew "java.util.concurrent.atomic.AtomicLong" value)))
(defconstant +atomic-long-cas+
(jmethod "java.util.concurrent.atomic.AtomicLong" "compareAndSet"
(jclass "long") (jclass "long")))
(defun atomic-integer-cas (atomic-integer old new)
(declare (type atomic-integer atomic-integer)
(type %atomic-integer-value old new)
(optimize (safety 0) (speed 3)))
(jcall +atomic-long-cas+ (atomic-integer-cell atomic-integer)
old new))
(defconstant +atomic-long-incf+
(jmethod "java.util.concurrent.atomic.AtomicLong" "getAndAdd"
(jclass "long")))
(defun atomic-integer-decf (atomic-integer &optional (delta 1))
(declare (type atomic-integer atomic-integer)
(type %atomic-integer-value delta)
(optimize (safety 0) (speed 3)))
(let ((increment (- delta)))
(+ (jcall +atomic-long-incf+ (atomic-integer-cell atomic-integer)
increment)
increment)))
(defun atomic-integer-incf (atomic-integer &optional (delta 1))
(declare (type atomic-integer atomic-integer)
(type %atomic-integer-value delta)
(optimize (safety 0) (speed 3)))
(+ (jcall +atomic-long-incf+ (atomic-integer-cell atomic-integer)
delta)
delta))
(defconstant +atomic-long-get+
(jmethod "java.util.concurrent.atomic.AtomicLong" "get"))
(defun atomic-integer-value (atomic-integer)
(declare (type atomic-integer atomic-integer)
(optimize (safety 0) (speed 3)))
(jcall +atomic-long-get+ (atomic-integer-cell atomic-integer)))
(defconstant +atomic-long-set+
(jmethod "java.util.concurrent.atomic.AtomicLong" "set"
(jclass "long")))
(defun (setf atomic-integer-value) (newval atomic-integer)
(declare (type atomic-integer atomic-integer)
(type %atomic-integer-value newval)
(optimize (safety 0) (speed 3)))
(jcall +atomic-long-set+ (atomic-integer-cell atomic-integer)
newval)
newval)
| null | https://raw.githubusercontent.com/sionescu/bordeaux-threads/552fd4dc7490a2f05ed74123f4096fb991673ac0/apiv2/atomics-java.lisp | lisp | -*- indent-tabs-mode: nil -*- |
(in-package :bordeaux-threads-2)
(defstruct (atomic-integer
(:constructor %make-atomic-integer (cell)))
"Wrapper for java.util.concurrent.AtomicLong."
cell)
(defmethod print-object ((aint atomic-integer) stream)
(print-unreadable-object (aint stream :type t :identity t)
(format stream "~S" (atomic-integer-value aint))))
(deftype %atomic-integer-value ()
'(unsigned-byte 63))
(defun make-atomic-integer (&key (value 0))
(check-type value %atomic-integer-value)
(%make-atomic-integer
(jnew "java.util.concurrent.atomic.AtomicLong" value)))
(defconstant +atomic-long-cas+
(jmethod "java.util.concurrent.atomic.AtomicLong" "compareAndSet"
(jclass "long") (jclass "long")))
(defun atomic-integer-cas (atomic-integer old new)
(declare (type atomic-integer atomic-integer)
(type %atomic-integer-value old new)
(optimize (safety 0) (speed 3)))
(jcall +atomic-long-cas+ (atomic-integer-cell atomic-integer)
old new))
(defconstant +atomic-long-incf+
(jmethod "java.util.concurrent.atomic.AtomicLong" "getAndAdd"
(jclass "long")))
(defun atomic-integer-decf (atomic-integer &optional (delta 1))
(declare (type atomic-integer atomic-integer)
(type %atomic-integer-value delta)
(optimize (safety 0) (speed 3)))
(let ((increment (- delta)))
(+ (jcall +atomic-long-incf+ (atomic-integer-cell atomic-integer)
increment)
increment)))
(defun atomic-integer-incf (atomic-integer &optional (delta 1))
(declare (type atomic-integer atomic-integer)
(type %atomic-integer-value delta)
(optimize (safety 0) (speed 3)))
(+ (jcall +atomic-long-incf+ (atomic-integer-cell atomic-integer)
delta)
delta))
(defconstant +atomic-long-get+
(jmethod "java.util.concurrent.atomic.AtomicLong" "get"))
(defun atomic-integer-value (atomic-integer)
(declare (type atomic-integer atomic-integer)
(optimize (safety 0) (speed 3)))
(jcall +atomic-long-get+ (atomic-integer-cell atomic-integer)))
(defconstant +atomic-long-set+
(jmethod "java.util.concurrent.atomic.AtomicLong" "set"
(jclass "long")))
(defun (setf atomic-integer-value) (newval atomic-integer)
(declare (type atomic-integer atomic-integer)
(type %atomic-integer-value newval)
(optimize (safety 0) (speed 3)))
(jcall +atomic-long-set+ (atomic-integer-cell atomic-integer)
newval)
newval)
|
4a4d365825ca163de76a984b175c9cea8b255048b201d7220858e22821c57c5e | facebookarchive/pfff | visitor_ml.ml |
*
* Copyright ( C ) 2010 Facebook
*
* This library is free software ; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation , with the
* special exception on linking described in file license.txt .
*
* This library is distributed in the hope that it will be useful , but
* WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the file
* license.txt for more details .
*
* Copyright (C) 2010 Facebook
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation, with the
* special exception on linking described in file license.txt.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file
* license.txt for more details.
*)
open Ast_ml
(*****************************************************************************)
(* Prelude *)
(*****************************************************************************)
* TODO : do a kmodule_name that is called by and
* a few other places where the name in the long_name is actually
* also a module name
* TODO: do a kmodule_name that is called by kqualifier and
* a few other places where the name in the long_name is actually
* also a module name
*)
(*****************************************************************************)
(* Types *)
(*****************************************************************************)
(* hooks *)
type visitor_in = {
kitem: item vin;
ktoplevel: toplevel vin;
kexpr: expr vin;
kpattern: pattern vin;
kty: ty vin;
kfield_decl: field_declaration vin;
kfield_expr: field_and_expr vin;
kfield_pat: field_pattern vin;
ktype_declaration: type_declaration vin;
klet_def: let_def vin;
klet_binding: let_binding vin;
kqualifier: qualifier vin;
kmodule_expr: module_expr vin;
kparameter: parameter vin;
kargument: argument vin;
kinfo: tok vin;
}
and 'a vin = ('a -> unit) * visitor_out -> 'a -> unit
and visitor_out = any -> unit
let default_visitor = {
kinfo = (fun (k,_) x -> k x);
kexpr = (fun (k,_) x -> k x);
kfield_decl = (fun (k,_) x -> k x);
kfield_expr = (fun (k,_) x -> k x);
kty = (fun (k,_) x -> k x);
ktype_declaration = (fun (k,_) x -> k x);
kitem = (fun (k,_) x -> k x);
klet_def = (fun (k,_) x -> k x);
kpattern = (fun (k,_) x -> k x);
klet_binding = (fun (k,_) x -> k x);
kqualifier = (fun (k,_) x -> k x);
kmodule_expr = (fun (k,_) x -> k x);
ktoplevel = (fun (k,_) x -> k x);
kparameter = (fun (k,_) x -> k x);
kargument = (fun (k,_) x -> k x);
kfield_pat = (fun (k,_) x -> k x);
}
let (mk_visitor: visitor_in -> visitor_out) = fun vin ->
(* start of auto generation *)
let rec v_info x =
let k x = match x with { Parse_info.
token = _v_pinfox; transfo = _v_transfo
} ->
(*
let _arg = Parse_info.v_pinfo v_pinfox in
let _arg = Ocaml.v_unit v_comments in
let _arg = Parse_info.v_transformation v_transfo in
*)
()
in
vin.kinfo (k, all_functions) x
and v_tok v = v_info v
and v_wrap: 'a. ('a -> unit) -> 'a wrap -> unit = fun _of_a (v1, v2) ->
let v1 = _of_a v1 and v2 = v_info v2 in ()
and v_wrap1 _of_a (v1, v2) = let v1 = _of_a v1 and v2 = v_info v2 in ()
and v_wrap2 _of_a (v1, v2) = let v1 = _of_a v1 and v2 = v_info v2 in ()
and v_wrap11 _of_a (v1, v2) = let v1 = _of_a v1 and v2 = v_info v2 in ()
and v_wrap12 _of_a (v1, v2) = let v1 = _of_a v1 and v2 = v_info v2 in ()
and v_wrap13 _of_a (v1, v2) = let v1 = _of_a v1 and v2 = v_info v2 in ()
and v_wrap14 _of_a (v1, v2) = let v1 = _of_a v1 and v2 = v_info v2 in ()
and v_wrap15 _of_a (v1, v2) = let v1 = _of_a v1 and v2 = v_info v2 in ()
and v_wrap16 _of_a (v1, v2) = let v1 = _of_a v1 and v2 = v_info v2 in ()
and v_wrap17 _of_a (v1, v2) = let v1 = _of_a v1 and v2 = v_info v2 in ()
and v_wrap18 _of_a (v1, v2) = let v1 = _of_a v1 and v2 = v_info v2 in ()
and v_paren _of_a (v1, v2, v3) =
let v1 = v_tok v1 and v2 = _of_a v2 and v3 = v_tok v3 in ()
and v_paren1 _of_a (v1, v2, v3) =
let v1 = v_tok v1 and v2 = _of_a v2 and v3 = v_tok v3 in ()
and v_paren2 _of_a (v1, v2, v3) =
let v1 = v_tok v1 and v2 = _of_a v2 and v3 = v_tok v3 in ()
and v_paren11 _of_a (v1, v2, v3) =
let v1 = v_tok v1 and v2 = _of_a v2 and v3 = v_tok v3 in ()
and v_paren12 _of_a (v1, v2, v3) =
let v1 = v_tok v1 and v2 = _of_a v2 and v3 = v_tok v3 in ()
and v_paren13 _of_a (v1, v2, v3) =
let v1 = v_tok v1 and v2 = _of_a v2 and v3 = v_tok v3 in ()
and v_brace _of_a (v1, v2, v3) =
let v1 = v_tok v1 and v2 = _of_a v2 and v3 = v_tok v3 in ()
and v_brace1 _of_a (v1, v2, v3) =
let v1 = v_tok v1 and v2 = _of_a v2 and v3 = v_tok v3 in ()
and v_brace11 _of_a (v1, v2, v3) =
let v1 = v_tok v1 and v2 = _of_a v2 and v3 = v_tok v3 in ()
and v_bracket: 'a. ('a -> unit) -> 'a bracket -> unit = fun
_of_a (v1, v2, v3) ->
let v1 = v_tok v1 and v2 = _of_a v2 and v3 = v_tok v3 in ()
and v_comma_list _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_comma_list1 _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_comma_list2 _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_comma_list11 _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_comma_list12 _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_and_list _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_and_list1 _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_and_list2 _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_and_list13 _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_pipe_list _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_pipe_list1 _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_pipe_list11 _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_pipe_list12 _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_pipe_list13 _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_semicolon_list: 'a. ('a -> unit) -> 'a semicolon_list -> unit = fun _of_a
-> Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_semicolon_list1 _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_semicolon_list2 _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_semicolon_list11 _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_semicolon_list12 _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_star_list _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_star_list1 _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_star_list2 _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_name = function | Name v1 -> let v1 = v_wrap1 Ocaml.v_string v1 in ()
and v_lname v = v_name v
and v_uname v = v_name v
and v_long_name (v1, v2) =
let v1 = v_qualifier v1 and v2 = v_name v2 in ()
and v_qualifier v =
let k _x =
Ocaml.v_list (fun (v1, v2) -> let v1 = v_name v1 and v2 = v_tok v2 in ()) v
in
vin.kqualifier (k, all_functions) v
and v_ty x =
let k x =
match x with
| TyName v1 -> let v1 = v_long_name v1 in ()
| TyVar ((v1, v2)) -> let v1 = v_tok v1 and v2 = v_name v2 in ()
| TyTuple v1 -> let v1 = v_star_list2 v_ty v1 in ()
| TyTuple2 v1 -> let v1 = v_paren (v_star_list2 v_ty) v1 in ()
| TyFunction ((v1, v2, v3)) ->
let v1 = v_ty v1 and v2 = v_tok v2 and v3 = v_ty v3 in ()
| TyApp ((v1, v2)) -> let v1 = v_ty_args v1 and v2 = v_long_name v2 in ()
| TyTodo -> ()
in
vin.kty (k, all_functions) x
and v_type_declaration x =
let k x =
match x with
| TyAbstract ((v1, v2)) -> let v1 = v_ty_params v1 and v2 = v_name v2 in ()
| TyDef ((v1, v2, v3, v4)) ->
let v1 = v_ty_params v1
and v2 = v_name v2
and v3 = v_tok v3
and v4 = v_type_def_kind v4
in ()
in
vin.ktype_declaration (k, all_functions) x
and v_type_def_kind =
function
| TyCore v1 -> let v1 = v_ty v1 in ()
| TyAlgebric v1 -> let v1 = v_pipe_list1 v_constructor_declaration v1 in ()
| TyRecord v1 ->
let v1 = v_brace1 (v_semicolon_list2 v_label_declaration) v1 in ()
and v_constructor_declaration (v1, v2) =
let v1 = v_name v1 and v2 = v_constructor_arguments v2 in ()
and v_constructor_arguments =
function
| NoConstrArg -> ()
| Of ((v1, v2)) -> let v1 = v_tok v1 and v2 = v_star_list1 v_ty v2 in ()
and
v_label_declaration x =
let k x =
match x with {
fld_mutable = v_fld_mutable;
fld_name = v_fld_name;
fld_tok = v_fld_tok;
fld_type = v_fld_type
} ->
let arg = Ocaml.v_option v_tok v_fld_mutable in
let arg = v_name v_fld_name in
let arg = v_tok v_fld_tok in let arg = v_ty v_fld_type in ()
in
vin.kfield_decl (k, all_functions) x
and v_ty_args =
function
| TyArg1 v1 -> let v1 = v_ty v1 in ()
| TyArgMulti v1 -> let v1 = v_paren2 (v_comma_list2 v_ty) v1 in ()
and v_ty_params =
function
| TyNoParam -> ()
| TyParam1 v1 -> let v1 = v_ty_parameter v1 in ()
| TyParamMulti v1 ->
let v1 = v_paren1 (v_comma_list1 v_ty_parameter) v1 in ()
and v_ty_parameter (v1, v2) = let v1 = v_tok v1 and v2 = v_name v2 in ()
and v_expr v =
let k x =
match x with
| C v1 -> let v1 = v_constant v1 in ()
| L v1 -> let v1 = v_long_name v1 in ()
| Constr ((v1, v2)) ->
let v1 = v_long_name v1 and v2 = Ocaml.v_option v_expr v2 in ()
| Tuple v1 -> let v1 = v_comma_list12 v_expr v1 in ()
| List v1 -> let v1 = v_bracket (v_semicolon_list v_expr) v1 in ()
| ParenExpr v1 -> let v1 = v_paren12 v_expr v1 in ()
| Sequence v1 -> let v1 = v_paren11 v_seq_expr v1 in ()
| Prefix ((v1, v2)) ->
let v1 = v_wrap18 Ocaml.v_string v1 and v2 = v_expr v2 in ()
| Infix ((v1, v2, v3)) ->
let v1 = v_expr v1
and v2 = v_wrap17 Ocaml.v_string v2
and v3 = v_expr v3
in ()
| FunCallSimple ((v1, v2)) ->
let v1 = v_long_name v1 and v2 = Ocaml.v_list v_argument v2 in ()
| FunCall ((v1, v2)) ->
let v1 = v_expr v1 and v2 = Ocaml.v_list v_argument v2 in ()
| RefAccess ((v1, v2)) -> let v1 = v_tok v1 and v2 = v_expr v2 in ()
| RefAssign ((v1, v2, v3)) ->
let v1 = v_expr v1 and v2 = v_tok v2 and v3 = v_expr v3 in ()
| FieldAccess ((v1, v2, v3)) ->
let v1 = v_expr v1 and v2 = v_tok v2 and v3 = v_long_name v3 in ()
| FieldAssign ((v1, v2, v3, v4, v5)) ->
let v1 = v_expr v1
and v2 = v_tok v2
and v3 = v_long_name v3
and v4 = v_tok v4
and v5 = v_expr v5
in ()
| Record v1 -> let v1 = v_brace11 v_record_expr v1 in ()
| ObjAccess ((v1, v2, v3)) ->
let v1 = v_expr v1 and v2 = v_tok v2 and v3 = v_name v3 in ()
| New ((v1, v2)) -> let v1 = v_tok v1 and v2 = v_long_name v2 in ()
| LetIn ((v1, v2, v3, v4, v5)) ->
let v1 = v_tok v1
and v2 = v_rec_opt v2
and v3 = v_and_list13 v_let_binding v3
and v4 = v_tok v4
and v5 = v_seq_expr v5
in ()
| Fun ((v1, v2, v3)) ->
let v1 = v_tok v1
and v2 = Ocaml.v_list v_parameter v2
and v3 = v_match_action v3
in ()
| Function ((v1, v2)) ->
let v1 = v_tok v1 and v2 = v_pipe_list13 v_match_case v2 in ()
| If ((v1, v2, v3, v4, v5)) ->
let v1 = v_tok v1
and v2 = v_seq_expr v2
and v3 = v_tok v3
and v4 = v_expr v4
and v5 =
Ocaml.v_option (fun (v1, v2) -> let v1 = v_tok v1 and v2 = v_expr v2 in ())
v5
in ()
| Match ((v1, v2, v3, v4)) ->
let v1 = v_tok v1
and v2 = v_seq_expr v2
and v3 = v_tok v3
and v4 = v_pipe_list12 v_match_case v4
in ()
| Try ((v1, v2, v3, v4)) ->
let v1 = v_tok v1
and v2 = v_seq_expr v2
and v3 = v_tok v3
and v4 = v_pipe_list11 v_match_case v4
in ()
| While ((v1, v2, v3, v4, v5)) ->
let v1 = v_tok v1
and v2 = v_seq_expr v2
and v3 = v_tok v3
and v4 = v_seq_expr v4
and v5 = v_tok v5
in ()
| For ((v1, v2, v3, v4, v5, v6, v7, v8, v9)) ->
let v1 = v_tok v1
and v2 = v_name v2
and v3 = v_tok v3
and v4 = v_seq_expr v4
and v5 = v_for_direction v5
and v6 = v_seq_expr v6
and v7 = v_tok v7
and v8 = v_seq_expr v8
and v9 = v_tok v9
in ()
| ExprTodo -> ()
in
vin.kexpr (k, all_functions) v
and v_constant =
function
| Int v1 -> let v1 = v_wrap16 Ocaml.v_string v1 in ()
| Float v1 -> let v1 = v_wrap15 Ocaml.v_string v1 in ()
| Char v1 -> let v1 = v_wrap14 Ocaml.v_string v1 in ()
| String v1 -> let v1 = v_wrap13 Ocaml.v_string v1 in ()
and v_record_expr =
function
| RecordNormal v1 -> let v1 = v_semicolon_list12 v_field_and_expr v1 in ()
| RecordWith ((v1, v2, v3)) ->
let v1 = v_expr v1
and v2 = v_tok v2
and v3 = v_semicolon_list11 v_field_and_expr v3
in ()
and v_field_and_expr v =
let k x =
match x with
| FieldExpr ((v1, v2, v3)) ->
let v1 = v_long_name v1 and v2 = v_tok v2 and v3 = v_expr v3 in ()
| FieldImplicitExpr v1 -> let v1 = v_long_name v1 in ()
in
vin.kfield_expr (k, all_functions) v
and v_argument v =
let k x = match x with
| ArgExpr v1 -> let v1 = v_expr v1 in ()
| ArgLabelTilde ((v1, v2)) -> let v1 = v_name v1 and v2 = v_expr v2 in ()
| ArgImplicitTildeExpr ((v1, v2)) ->
let v1 = v_tok v1 and v2 = v_name v2 in ()
| ArgImplicitQuestionExpr ((v1, v2)) ->
let v1 = v_tok v1 and v2 = v_name v2 in ()
| ArgLabelQuestion ((v1, v2)) -> let v1 = v_name v1 and v2 = v_expr v2 in ()
in
vin.kargument (k, all_functions) v
and v_match_action =
function
| Action ((v1, v2)) -> let v1 = v_tok v1 and v2 = v_seq_expr v2 in ()
| WhenAction ((v1, v2, v3, v4)) ->
let v1 = v_tok v1
and v2 = v_seq_expr v2
and v3 = v_tok v3
and v4 = v_seq_expr v4
in ()
and v_match_case (v1, v2) =
let v1 = v_pattern v1 and v2 = v_match_action v2 in ()
and v_for_direction =
function
| To v1 -> let v1 = v_tok v1 in ()
| Downto v1 -> let v1 = v_tok v1 in ()
and v_seq_expr v = v_semicolon_list1 v_expr v
and v_pattern x =
let k x = match x with
| PatVar v1 -> let v1 = v_name v1 in ()
| PatConstant v1 -> let v1 = v_signed_constant v1 in ()
| PatConstr ((v1, v2)) ->
let v1 = v_long_name v1 and v2 = Ocaml.v_option v_pattern v2 in ()
| PatConsInfix ((v1, v2, v3)) ->
let v1 = v_pattern v1 and v2 = v_tok v2 and v3 = v_pattern v3 in ()
| PatTuple v1 -> let v1 = v_comma_list11 v_pattern v1 in ()
| PatList v1 -> let v1 = v_bracket (v_semicolon_list v_pattern) v1 in ()
| PatUnderscore v1 -> let v1 = v_tok v1 in ()
| PatRecord v1 ->
let v1 = v_brace (v_semicolon_list v_field_pattern) v1 in ()
| PatAs ((v1, v2, v3)) ->
let v1 = v_pattern v1 and v2 = v_tok v2 and v3 = v_name v3 in ()
| PatDisj ((v1, v2, v3)) ->
let v1 = v_pattern v1 and v2 = v_tok v2 and v3 = v_pattern v3 in ()
| PatTyped ((v1, v2, v3, v4, v5)) ->
let v1 = v_tok v1
and v2 = v_pattern v2
and v3 = v_tok v3
and v4 = v_ty v4
and v5 = v_tok v5
in ()
| ParenPat v1 -> let v1 = v_paren13 v_pattern v1 in ()
| PatTodo -> ()
in
vin.kpattern (k, all_functions) x
and v_simple_pattern v = Ocaml.v_unit v
and v_labeled_simple_pattern v = v_parameter v
and v_parameter x =
let k x = match x with
| ParamPat v1 -> let v1 = v_pattern v1 in ()
| ParamTodo -> ()
in
vin.kparameter (k, all_functions) x
and v_field_pattern x =
let k x = match x with
| PatField ((v1, v2, v3)) ->
let v1 = v_long_name v1 and v2 = v_tok v2 and v3 = v_pattern v3 in ()
| PatImplicitField v1 -> let v1 = v_long_name v1 in ()
in
vin.kfield_pat (k, all_functions) x
and v_signed_constant =
function
| C2 v1 -> let v1 = v_constant v1 in ()
| CMinus ((v1, v2)) -> let v1 = v_tok v1 and v2 = v_constant v2 in ()
| CPlus ((v1, v2)) -> let v1 = v_tok v1 and v2 = v_constant v2 in ()
and v_let_binding x =
let k x = match x with
| LetClassic v1 -> let v1 = v_let_def v1 in ()
| LetPattern ((v1, v2, v3)) ->
let v1 = v_pattern v1 and v2 = v_tok v2 and v3 = v_seq_expr v3 in ()
in
vin.klet_binding (k, all_functions) x
and
v_let_def x =
let k x =
match x with
{
l_name = v_l_name;
l_params = v_l_args;
l_tok = v_l_tok;
l_body = v_l_body
} ->
let arg = v_name v_l_name in
let arg = Ocaml.v_list v_labeled_simple_pattern v_l_args in
let arg = v_tok v_l_tok in let arg = v_seq_expr v_l_body in ()
in
vin.klet_def (k, all_functions) x
and v_function_def v = Ocaml.v_unit v
and v_module_type v = Ocaml.v_unit v
and v_module_expr v =
let k v =
match v with
| ModuleName v1 ->
let v1 = v_long_name v1 in
()
| ModuleStruct (v1, v2, v3) ->
let v1 = v_tok v1 in
let v2 = Ocaml.v_list v_item v2 in
let v3 = v_tok v3 in
()
| ModuleTodo ->
()
in
vin.kmodule_expr (k, all_functions) v
and v_item x =
let k x =
match x with
| Type ((v1, v2)) ->
let v1 = v_tok v1 and v2 = v_and_list2 v_type_declaration v2 in ()
| Exception ((v1, v2, v3)) ->
let v1 = v_tok v1
and v2 = v_name v2
and v3 = v_constructor_arguments v3
in ()
| External ((v1, v2, v3, v4, v5, v6)) ->
let v1 = v_tok v1
and v2 = v_name v2
and v3 = v_tok v3
and v4 = v_ty v4
and v5 = v_tok v5
and v6 = Ocaml.v_list (v_wrap2 Ocaml.v_string) v6
in ()
| Open ((v1, v2)) -> let v1 = v_tok v1 and v2 = v_long_name v2 in ()
| Val ((v1, v2, v3, v4)) ->
let v1 = v_tok v1
and v2 = v_name v2
and v3 = v_tok v3
and v4 = v_ty v4
in ()
| Let ((v1, v2, v3)) ->
let v1 = v_tok v1
and v2 = v_rec_opt v2
and v3 = v_and_list1 v_let_binding v3
in ()
| Module ((v1, v2, v3, v4)) ->
let v1 = v_tok v1
and v2 = v_uname v2
and v3 = v_tok v3
and v4 = v_module_expr v4
in ()
| ItemTodo v -> v_info v
in
vin.kitem (k, all_functions) x
and v_sig_item v = v_item v
and v_struct_item v = v_item v
and v_rec_opt v = Ocaml.v_option v_tok v
and v_toplevel x =
let k = function
| TopItem v1 -> let v1 = v_item v1 in ()
| ScSc v1 -> let v1 = v_info v1 in ()
| TopSeqExpr v1 -> let v1 = v_seq_expr v1 in ()
| TopDirective v1 -> let v1 = v_info v1 in ()
in
vin.ktoplevel (k, all_functions) x
and v_program v = Ocaml.v_list v_toplevel v
and v_any = function
| Ty v1 -> let v1 = v_ty v1 in ()
| Expr v1 -> let v1 = v_expr v1 in ()
| Pattern v1 -> let v1 = v_pattern v1 in ()
| Item v1 -> let v1 = v_item v1 in ()
| Toplevel v1 -> let v1 = v_toplevel v1 in ()
| Program v1 -> let v1 = v_program v1 in ()
| TypeDeclaration v1 -> let v1 = v_type_declaration v1 in ()
| TypeDefKind v1 -> let v1 = v_type_def_kind v1 in ()
| MatchCase v1 -> let v1 = v_match_case v1 in ()
| FieldDeclaration v1 -> let v1 = v_label_declaration v1 in ()
| LetBinding v1 -> let v1 = v_let_binding v1 in ()
| Constant v1 -> let v1 = v_constant v1 in ()
| Argument v1 -> let v1 = v_argument v1 in ()
| Body v1 -> let v1 = v_seq_expr v1 in ()
| Info v1 -> let v1 = v_info v1 in ()
| InfoList v1 -> let v1 = Ocaml.v_list v_info v1 in ()
and all_functions x = v_any x
in
v_any
(*****************************************************************************)
(* Helpers *)
(*****************************************************************************)
let do_visit_with_ref mk_hooks = fun any - >
let res = ref [ ] in
let hooks = mk_hooks res in
let vout = mk_visitor hooks in
vout any ;
List.rev !
let do_visit_with_ref mk_hooks = fun any ->
let res = ref [] in
let hooks = mk_hooks res in
let vout = mk_visitor hooks in
vout any;
List.rev !res
*)
| null | https://raw.githubusercontent.com/facebookarchive/pfff/ec21095ab7d445559576513a63314e794378c367/lang_ml/parsing/visitor_ml.ml | ocaml | ***************************************************************************
Prelude
***************************************************************************
***************************************************************************
Types
***************************************************************************
hooks
start of auto generation
let _arg = Parse_info.v_pinfo v_pinfox in
let _arg = Ocaml.v_unit v_comments in
let _arg = Parse_info.v_transformation v_transfo in
***************************************************************************
Helpers
*************************************************************************** |
*
* Copyright ( C ) 2010 Facebook
*
* This library is free software ; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation , with the
* special exception on linking described in file license.txt .
*
* This library is distributed in the hope that it will be useful , but
* WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the file
* license.txt for more details .
*
* Copyright (C) 2010 Facebook
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation, with the
* special exception on linking described in file license.txt.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file
* license.txt for more details.
*)
open Ast_ml
* TODO : do a kmodule_name that is called by and
* a few other places where the name in the long_name is actually
* also a module name
* TODO: do a kmodule_name that is called by kqualifier and
* a few other places where the name in the long_name is actually
* also a module name
*)
type visitor_in = {
kitem: item vin;
ktoplevel: toplevel vin;
kexpr: expr vin;
kpattern: pattern vin;
kty: ty vin;
kfield_decl: field_declaration vin;
kfield_expr: field_and_expr vin;
kfield_pat: field_pattern vin;
ktype_declaration: type_declaration vin;
klet_def: let_def vin;
klet_binding: let_binding vin;
kqualifier: qualifier vin;
kmodule_expr: module_expr vin;
kparameter: parameter vin;
kargument: argument vin;
kinfo: tok vin;
}
and 'a vin = ('a -> unit) * visitor_out -> 'a -> unit
and visitor_out = any -> unit
let default_visitor = {
kinfo = (fun (k,_) x -> k x);
kexpr = (fun (k,_) x -> k x);
kfield_decl = (fun (k,_) x -> k x);
kfield_expr = (fun (k,_) x -> k x);
kty = (fun (k,_) x -> k x);
ktype_declaration = (fun (k,_) x -> k x);
kitem = (fun (k,_) x -> k x);
klet_def = (fun (k,_) x -> k x);
kpattern = (fun (k,_) x -> k x);
klet_binding = (fun (k,_) x -> k x);
kqualifier = (fun (k,_) x -> k x);
kmodule_expr = (fun (k,_) x -> k x);
ktoplevel = (fun (k,_) x -> k x);
kparameter = (fun (k,_) x -> k x);
kargument = (fun (k,_) x -> k x);
kfield_pat = (fun (k,_) x -> k x);
}
let (mk_visitor: visitor_in -> visitor_out) = fun vin ->
let rec v_info x =
let k x = match x with { Parse_info.
token = _v_pinfox; transfo = _v_transfo
} ->
()
in
vin.kinfo (k, all_functions) x
and v_tok v = v_info v
and v_wrap: 'a. ('a -> unit) -> 'a wrap -> unit = fun _of_a (v1, v2) ->
let v1 = _of_a v1 and v2 = v_info v2 in ()
and v_wrap1 _of_a (v1, v2) = let v1 = _of_a v1 and v2 = v_info v2 in ()
and v_wrap2 _of_a (v1, v2) = let v1 = _of_a v1 and v2 = v_info v2 in ()
and v_wrap11 _of_a (v1, v2) = let v1 = _of_a v1 and v2 = v_info v2 in ()
and v_wrap12 _of_a (v1, v2) = let v1 = _of_a v1 and v2 = v_info v2 in ()
and v_wrap13 _of_a (v1, v2) = let v1 = _of_a v1 and v2 = v_info v2 in ()
and v_wrap14 _of_a (v1, v2) = let v1 = _of_a v1 and v2 = v_info v2 in ()
and v_wrap15 _of_a (v1, v2) = let v1 = _of_a v1 and v2 = v_info v2 in ()
and v_wrap16 _of_a (v1, v2) = let v1 = _of_a v1 and v2 = v_info v2 in ()
and v_wrap17 _of_a (v1, v2) = let v1 = _of_a v1 and v2 = v_info v2 in ()
and v_wrap18 _of_a (v1, v2) = let v1 = _of_a v1 and v2 = v_info v2 in ()
and v_paren _of_a (v1, v2, v3) =
let v1 = v_tok v1 and v2 = _of_a v2 and v3 = v_tok v3 in ()
and v_paren1 _of_a (v1, v2, v3) =
let v1 = v_tok v1 and v2 = _of_a v2 and v3 = v_tok v3 in ()
and v_paren2 _of_a (v1, v2, v3) =
let v1 = v_tok v1 and v2 = _of_a v2 and v3 = v_tok v3 in ()
and v_paren11 _of_a (v1, v2, v3) =
let v1 = v_tok v1 and v2 = _of_a v2 and v3 = v_tok v3 in ()
and v_paren12 _of_a (v1, v2, v3) =
let v1 = v_tok v1 and v2 = _of_a v2 and v3 = v_tok v3 in ()
and v_paren13 _of_a (v1, v2, v3) =
let v1 = v_tok v1 and v2 = _of_a v2 and v3 = v_tok v3 in ()
and v_brace _of_a (v1, v2, v3) =
let v1 = v_tok v1 and v2 = _of_a v2 and v3 = v_tok v3 in ()
and v_brace1 _of_a (v1, v2, v3) =
let v1 = v_tok v1 and v2 = _of_a v2 and v3 = v_tok v3 in ()
and v_brace11 _of_a (v1, v2, v3) =
let v1 = v_tok v1 and v2 = _of_a v2 and v3 = v_tok v3 in ()
and v_bracket: 'a. ('a -> unit) -> 'a bracket -> unit = fun
_of_a (v1, v2, v3) ->
let v1 = v_tok v1 and v2 = _of_a v2 and v3 = v_tok v3 in ()
and v_comma_list _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_comma_list1 _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_comma_list2 _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_comma_list11 _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_comma_list12 _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_and_list _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_and_list1 _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_and_list2 _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_and_list13 _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_pipe_list _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_pipe_list1 _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_pipe_list11 _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_pipe_list12 _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_pipe_list13 _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_semicolon_list: 'a. ('a -> unit) -> 'a semicolon_list -> unit = fun _of_a
-> Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_semicolon_list1 _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_semicolon_list2 _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_semicolon_list11 _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_semicolon_list12 _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_star_list _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_star_list1 _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_star_list2 _of_a = Ocaml.v_list (Ocaml.v_either _of_a v_tok)
and v_name = function | Name v1 -> let v1 = v_wrap1 Ocaml.v_string v1 in ()
and v_lname v = v_name v
and v_uname v = v_name v
and v_long_name (v1, v2) =
let v1 = v_qualifier v1 and v2 = v_name v2 in ()
and v_qualifier v =
let k _x =
Ocaml.v_list (fun (v1, v2) -> let v1 = v_name v1 and v2 = v_tok v2 in ()) v
in
vin.kqualifier (k, all_functions) v
and v_ty x =
let k x =
match x with
| TyName v1 -> let v1 = v_long_name v1 in ()
| TyVar ((v1, v2)) -> let v1 = v_tok v1 and v2 = v_name v2 in ()
| TyTuple v1 -> let v1 = v_star_list2 v_ty v1 in ()
| TyTuple2 v1 -> let v1 = v_paren (v_star_list2 v_ty) v1 in ()
| TyFunction ((v1, v2, v3)) ->
let v1 = v_ty v1 and v2 = v_tok v2 and v3 = v_ty v3 in ()
| TyApp ((v1, v2)) -> let v1 = v_ty_args v1 and v2 = v_long_name v2 in ()
| TyTodo -> ()
in
vin.kty (k, all_functions) x
and v_type_declaration x =
let k x =
match x with
| TyAbstract ((v1, v2)) -> let v1 = v_ty_params v1 and v2 = v_name v2 in ()
| TyDef ((v1, v2, v3, v4)) ->
let v1 = v_ty_params v1
and v2 = v_name v2
and v3 = v_tok v3
and v4 = v_type_def_kind v4
in ()
in
vin.ktype_declaration (k, all_functions) x
and v_type_def_kind =
function
| TyCore v1 -> let v1 = v_ty v1 in ()
| TyAlgebric v1 -> let v1 = v_pipe_list1 v_constructor_declaration v1 in ()
| TyRecord v1 ->
let v1 = v_brace1 (v_semicolon_list2 v_label_declaration) v1 in ()
and v_constructor_declaration (v1, v2) =
let v1 = v_name v1 and v2 = v_constructor_arguments v2 in ()
and v_constructor_arguments =
function
| NoConstrArg -> ()
| Of ((v1, v2)) -> let v1 = v_tok v1 and v2 = v_star_list1 v_ty v2 in ()
and
v_label_declaration x =
let k x =
match x with {
fld_mutable = v_fld_mutable;
fld_name = v_fld_name;
fld_tok = v_fld_tok;
fld_type = v_fld_type
} ->
let arg = Ocaml.v_option v_tok v_fld_mutable in
let arg = v_name v_fld_name in
let arg = v_tok v_fld_tok in let arg = v_ty v_fld_type in ()
in
vin.kfield_decl (k, all_functions) x
and v_ty_args =
function
| TyArg1 v1 -> let v1 = v_ty v1 in ()
| TyArgMulti v1 -> let v1 = v_paren2 (v_comma_list2 v_ty) v1 in ()
and v_ty_params =
function
| TyNoParam -> ()
| TyParam1 v1 -> let v1 = v_ty_parameter v1 in ()
| TyParamMulti v1 ->
let v1 = v_paren1 (v_comma_list1 v_ty_parameter) v1 in ()
and v_ty_parameter (v1, v2) = let v1 = v_tok v1 and v2 = v_name v2 in ()
and v_expr v =
let k x =
match x with
| C v1 -> let v1 = v_constant v1 in ()
| L v1 -> let v1 = v_long_name v1 in ()
| Constr ((v1, v2)) ->
let v1 = v_long_name v1 and v2 = Ocaml.v_option v_expr v2 in ()
| Tuple v1 -> let v1 = v_comma_list12 v_expr v1 in ()
| List v1 -> let v1 = v_bracket (v_semicolon_list v_expr) v1 in ()
| ParenExpr v1 -> let v1 = v_paren12 v_expr v1 in ()
| Sequence v1 -> let v1 = v_paren11 v_seq_expr v1 in ()
| Prefix ((v1, v2)) ->
let v1 = v_wrap18 Ocaml.v_string v1 and v2 = v_expr v2 in ()
| Infix ((v1, v2, v3)) ->
let v1 = v_expr v1
and v2 = v_wrap17 Ocaml.v_string v2
and v3 = v_expr v3
in ()
| FunCallSimple ((v1, v2)) ->
let v1 = v_long_name v1 and v2 = Ocaml.v_list v_argument v2 in ()
| FunCall ((v1, v2)) ->
let v1 = v_expr v1 and v2 = Ocaml.v_list v_argument v2 in ()
| RefAccess ((v1, v2)) -> let v1 = v_tok v1 and v2 = v_expr v2 in ()
| RefAssign ((v1, v2, v3)) ->
let v1 = v_expr v1 and v2 = v_tok v2 and v3 = v_expr v3 in ()
| FieldAccess ((v1, v2, v3)) ->
let v1 = v_expr v1 and v2 = v_tok v2 and v3 = v_long_name v3 in ()
| FieldAssign ((v1, v2, v3, v4, v5)) ->
let v1 = v_expr v1
and v2 = v_tok v2
and v3 = v_long_name v3
and v4 = v_tok v4
and v5 = v_expr v5
in ()
| Record v1 -> let v1 = v_brace11 v_record_expr v1 in ()
| ObjAccess ((v1, v2, v3)) ->
let v1 = v_expr v1 and v2 = v_tok v2 and v3 = v_name v3 in ()
| New ((v1, v2)) -> let v1 = v_tok v1 and v2 = v_long_name v2 in ()
| LetIn ((v1, v2, v3, v4, v5)) ->
let v1 = v_tok v1
and v2 = v_rec_opt v2
and v3 = v_and_list13 v_let_binding v3
and v4 = v_tok v4
and v5 = v_seq_expr v5
in ()
| Fun ((v1, v2, v3)) ->
let v1 = v_tok v1
and v2 = Ocaml.v_list v_parameter v2
and v3 = v_match_action v3
in ()
| Function ((v1, v2)) ->
let v1 = v_tok v1 and v2 = v_pipe_list13 v_match_case v2 in ()
| If ((v1, v2, v3, v4, v5)) ->
let v1 = v_tok v1
and v2 = v_seq_expr v2
and v3 = v_tok v3
and v4 = v_expr v4
and v5 =
Ocaml.v_option (fun (v1, v2) -> let v1 = v_tok v1 and v2 = v_expr v2 in ())
v5
in ()
| Match ((v1, v2, v3, v4)) ->
let v1 = v_tok v1
and v2 = v_seq_expr v2
and v3 = v_tok v3
and v4 = v_pipe_list12 v_match_case v4
in ()
| Try ((v1, v2, v3, v4)) ->
let v1 = v_tok v1
and v2 = v_seq_expr v2
and v3 = v_tok v3
and v4 = v_pipe_list11 v_match_case v4
in ()
| While ((v1, v2, v3, v4, v5)) ->
let v1 = v_tok v1
and v2 = v_seq_expr v2
and v3 = v_tok v3
and v4 = v_seq_expr v4
and v5 = v_tok v5
in ()
| For ((v1, v2, v3, v4, v5, v6, v7, v8, v9)) ->
let v1 = v_tok v1
and v2 = v_name v2
and v3 = v_tok v3
and v4 = v_seq_expr v4
and v5 = v_for_direction v5
and v6 = v_seq_expr v6
and v7 = v_tok v7
and v8 = v_seq_expr v8
and v9 = v_tok v9
in ()
| ExprTodo -> ()
in
vin.kexpr (k, all_functions) v
and v_constant =
function
| Int v1 -> let v1 = v_wrap16 Ocaml.v_string v1 in ()
| Float v1 -> let v1 = v_wrap15 Ocaml.v_string v1 in ()
| Char v1 -> let v1 = v_wrap14 Ocaml.v_string v1 in ()
| String v1 -> let v1 = v_wrap13 Ocaml.v_string v1 in ()
and v_record_expr =
function
| RecordNormal v1 -> let v1 = v_semicolon_list12 v_field_and_expr v1 in ()
| RecordWith ((v1, v2, v3)) ->
let v1 = v_expr v1
and v2 = v_tok v2
and v3 = v_semicolon_list11 v_field_and_expr v3
in ()
and v_field_and_expr v =
let k x =
match x with
| FieldExpr ((v1, v2, v3)) ->
let v1 = v_long_name v1 and v2 = v_tok v2 and v3 = v_expr v3 in ()
| FieldImplicitExpr v1 -> let v1 = v_long_name v1 in ()
in
vin.kfield_expr (k, all_functions) v
and v_argument v =
let k x = match x with
| ArgExpr v1 -> let v1 = v_expr v1 in ()
| ArgLabelTilde ((v1, v2)) -> let v1 = v_name v1 and v2 = v_expr v2 in ()
| ArgImplicitTildeExpr ((v1, v2)) ->
let v1 = v_tok v1 and v2 = v_name v2 in ()
| ArgImplicitQuestionExpr ((v1, v2)) ->
let v1 = v_tok v1 and v2 = v_name v2 in ()
| ArgLabelQuestion ((v1, v2)) -> let v1 = v_name v1 and v2 = v_expr v2 in ()
in
vin.kargument (k, all_functions) v
and v_match_action =
function
| Action ((v1, v2)) -> let v1 = v_tok v1 and v2 = v_seq_expr v2 in ()
| WhenAction ((v1, v2, v3, v4)) ->
let v1 = v_tok v1
and v2 = v_seq_expr v2
and v3 = v_tok v3
and v4 = v_seq_expr v4
in ()
and v_match_case (v1, v2) =
let v1 = v_pattern v1 and v2 = v_match_action v2 in ()
and v_for_direction =
function
| To v1 -> let v1 = v_tok v1 in ()
| Downto v1 -> let v1 = v_tok v1 in ()
and v_seq_expr v = v_semicolon_list1 v_expr v
and v_pattern x =
let k x = match x with
| PatVar v1 -> let v1 = v_name v1 in ()
| PatConstant v1 -> let v1 = v_signed_constant v1 in ()
| PatConstr ((v1, v2)) ->
let v1 = v_long_name v1 and v2 = Ocaml.v_option v_pattern v2 in ()
| PatConsInfix ((v1, v2, v3)) ->
let v1 = v_pattern v1 and v2 = v_tok v2 and v3 = v_pattern v3 in ()
| PatTuple v1 -> let v1 = v_comma_list11 v_pattern v1 in ()
| PatList v1 -> let v1 = v_bracket (v_semicolon_list v_pattern) v1 in ()
| PatUnderscore v1 -> let v1 = v_tok v1 in ()
| PatRecord v1 ->
let v1 = v_brace (v_semicolon_list v_field_pattern) v1 in ()
| PatAs ((v1, v2, v3)) ->
let v1 = v_pattern v1 and v2 = v_tok v2 and v3 = v_name v3 in ()
| PatDisj ((v1, v2, v3)) ->
let v1 = v_pattern v1 and v2 = v_tok v2 and v3 = v_pattern v3 in ()
| PatTyped ((v1, v2, v3, v4, v5)) ->
let v1 = v_tok v1
and v2 = v_pattern v2
and v3 = v_tok v3
and v4 = v_ty v4
and v5 = v_tok v5
in ()
| ParenPat v1 -> let v1 = v_paren13 v_pattern v1 in ()
| PatTodo -> ()
in
vin.kpattern (k, all_functions) x
and v_simple_pattern v = Ocaml.v_unit v
and v_labeled_simple_pattern v = v_parameter v
and v_parameter x =
let k x = match x with
| ParamPat v1 -> let v1 = v_pattern v1 in ()
| ParamTodo -> ()
in
vin.kparameter (k, all_functions) x
and v_field_pattern x =
let k x = match x with
| PatField ((v1, v2, v3)) ->
let v1 = v_long_name v1 and v2 = v_tok v2 and v3 = v_pattern v3 in ()
| PatImplicitField v1 -> let v1 = v_long_name v1 in ()
in
vin.kfield_pat (k, all_functions) x
and v_signed_constant =
function
| C2 v1 -> let v1 = v_constant v1 in ()
| CMinus ((v1, v2)) -> let v1 = v_tok v1 and v2 = v_constant v2 in ()
| CPlus ((v1, v2)) -> let v1 = v_tok v1 and v2 = v_constant v2 in ()
and v_let_binding x =
let k x = match x with
| LetClassic v1 -> let v1 = v_let_def v1 in ()
| LetPattern ((v1, v2, v3)) ->
let v1 = v_pattern v1 and v2 = v_tok v2 and v3 = v_seq_expr v3 in ()
in
vin.klet_binding (k, all_functions) x
and
v_let_def x =
let k x =
match x with
{
l_name = v_l_name;
l_params = v_l_args;
l_tok = v_l_tok;
l_body = v_l_body
} ->
let arg = v_name v_l_name in
let arg = Ocaml.v_list v_labeled_simple_pattern v_l_args in
let arg = v_tok v_l_tok in let arg = v_seq_expr v_l_body in ()
in
vin.klet_def (k, all_functions) x
and v_function_def v = Ocaml.v_unit v
and v_module_type v = Ocaml.v_unit v
and v_module_expr v =
let k v =
match v with
| ModuleName v1 ->
let v1 = v_long_name v1 in
()
| ModuleStruct (v1, v2, v3) ->
let v1 = v_tok v1 in
let v2 = Ocaml.v_list v_item v2 in
let v3 = v_tok v3 in
()
| ModuleTodo ->
()
in
vin.kmodule_expr (k, all_functions) v
and v_item x =
let k x =
match x with
| Type ((v1, v2)) ->
let v1 = v_tok v1 and v2 = v_and_list2 v_type_declaration v2 in ()
| Exception ((v1, v2, v3)) ->
let v1 = v_tok v1
and v2 = v_name v2
and v3 = v_constructor_arguments v3
in ()
| External ((v1, v2, v3, v4, v5, v6)) ->
let v1 = v_tok v1
and v2 = v_name v2
and v3 = v_tok v3
and v4 = v_ty v4
and v5 = v_tok v5
and v6 = Ocaml.v_list (v_wrap2 Ocaml.v_string) v6
in ()
| Open ((v1, v2)) -> let v1 = v_tok v1 and v2 = v_long_name v2 in ()
| Val ((v1, v2, v3, v4)) ->
let v1 = v_tok v1
and v2 = v_name v2
and v3 = v_tok v3
and v4 = v_ty v4
in ()
| Let ((v1, v2, v3)) ->
let v1 = v_tok v1
and v2 = v_rec_opt v2
and v3 = v_and_list1 v_let_binding v3
in ()
| Module ((v1, v2, v3, v4)) ->
let v1 = v_tok v1
and v2 = v_uname v2
and v3 = v_tok v3
and v4 = v_module_expr v4
in ()
| ItemTodo v -> v_info v
in
vin.kitem (k, all_functions) x
and v_sig_item v = v_item v
and v_struct_item v = v_item v
and v_rec_opt v = Ocaml.v_option v_tok v
and v_toplevel x =
let k = function
| TopItem v1 -> let v1 = v_item v1 in ()
| ScSc v1 -> let v1 = v_info v1 in ()
| TopSeqExpr v1 -> let v1 = v_seq_expr v1 in ()
| TopDirective v1 -> let v1 = v_info v1 in ()
in
vin.ktoplevel (k, all_functions) x
and v_program v = Ocaml.v_list v_toplevel v
and v_any = function
| Ty v1 -> let v1 = v_ty v1 in ()
| Expr v1 -> let v1 = v_expr v1 in ()
| Pattern v1 -> let v1 = v_pattern v1 in ()
| Item v1 -> let v1 = v_item v1 in ()
| Toplevel v1 -> let v1 = v_toplevel v1 in ()
| Program v1 -> let v1 = v_program v1 in ()
| TypeDeclaration v1 -> let v1 = v_type_declaration v1 in ()
| TypeDefKind v1 -> let v1 = v_type_def_kind v1 in ()
| MatchCase v1 -> let v1 = v_match_case v1 in ()
| FieldDeclaration v1 -> let v1 = v_label_declaration v1 in ()
| LetBinding v1 -> let v1 = v_let_binding v1 in ()
| Constant v1 -> let v1 = v_constant v1 in ()
| Argument v1 -> let v1 = v_argument v1 in ()
| Body v1 -> let v1 = v_seq_expr v1 in ()
| Info v1 -> let v1 = v_info v1 in ()
| InfoList v1 -> let v1 = Ocaml.v_list v_info v1 in ()
and all_functions x = v_any x
in
v_any
let do_visit_with_ref mk_hooks = fun any - >
let res = ref [ ] in
let hooks = mk_hooks res in
let vout = mk_visitor hooks in
vout any ;
List.rev !
let do_visit_with_ref mk_hooks = fun any ->
let res = ref [] in
let hooks = mk_hooks res in
let vout = mk_visitor hooks in
vout any;
List.rev !res
*)
|
b32d05acfd9aded5010c0919622635a315b4f0b1ae8e84a9ed1b4fcd77d25a0a | ocaml/ood | rss_types.ml | (******************************************************************************)
(* OCamlrss *)
(* *)
Copyright ( C ) 2004 - 2013 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 Lesser General Public License version *)
3 as published by the Free Software Foundation .
(* *)
(* 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: *)
(* *)
(* *)
(******************************************************************************)
(** *)
type category = { cat_name : string; cat_domain : Uri.t option }
type image = {
image_url : Uri.t;
image_title : string;
image_link : Uri.t;
image_height : int option;
image_width : int option;
image_desc : string option;
}
type text_input = {
ti_title : string;
(** The label of the Submit button in the text input area. *)
ti_desc : string; (** Explains the text input area. *)
ti_name : string; (** The name of the text object in the text input area. *)
ti_link : Uri.t;
(** The URL of the CGI script that processes text input requests. *)
}
type enclosure = {
encl_url : Uri.t; (** URL of the enclosure *)
encl_length : int; (** size in bytes *)
encl_type : string; (** MIME type *)
}
type cloud = {
cloud_domain : string;
cloud_port : int;
cloud_path : string;
cloud_register_procedure : string;
cloud_protocol : string;
}
(** See {{:#rsscloudInterface} specification} *)
type guid = Guid_permalink of Uri.t | Guid_name of string
type source = { src_name : string; src_url : Uri.t }
type 'a item_t = {
item_title : string option;
item_link : Uri.t option;
item_desc : string option;
item_pubdate : Ptime.t option;
item_author : string option;
item_categories : category list;
item_comments : Uri.t option;
item_enclosure : enclosure option;
item_guid : guid option;
item_source : source option;
item_content : string option;
item_data : 'a option;
}
type ('a, 'b) channel_t = {
ch_title : string;
ch_link : Uri.t;
ch_desc : string;
ch_language : string option;
ch_copyright : string option;
ch_managing_editor : string option;
ch_webmaster : string option;
ch_pubdate : Ptime.t option;
ch_last_build_date : Ptime.t option;
ch_categories : category list;
ch_generator : string option;
ch_cloud : cloud option;
ch_docs : Uri.t option;
ch_ttl : int option;
ch_image : image option;
ch_rating : string option;
ch_text_input : text_input option;
ch_skip_hours : int list option;
ch_skip_days : int list option;
ch_items : 'b item_t list;
ch_data : 'a option;
ch_namespaces : (string * string) list;
}
type item = unit item_t
type channel = (unit, unit) channel_t
let compare_opt ~f x y =
match (x, y) with
| Some _, None -> 1
| None, Some _ -> -1
| None, None -> 0
| Some x, Some y -> f x y
let compare_url_opt = compare_opt ~f:Uri.compare
let compare_list ~f =
let rec iter = function
| [], [] -> 0
| [], _ -> -1
| _, [] -> 1
| h1 :: q1, h2 :: q2 -> ( match f h1 h2 with 0 -> iter (q1, q2) | n -> n)
in
fun l1 l2 -> iter (l1, l2)
let compare_enclosure { encl_url = e1; _ } { encl_url = e2; _ } =
Uri.compare e1 e2
let compare_guid g1 g2 =
match (g1, g2) with
| Guid_permalink url1, Guid_permalink url2 -> Uri.compare url1 url2
| Guid_permalink _, Guid_name _ -> 1
| Guid_name _, Guid_permalink _ -> -1
| Guid_name s1, Guid_name s2 -> compare s1 s2
let compare_source s1 s2 =
match Uri.compare s1.src_url s2.src_url with
| 0 -> compare s1.src_name s2.src_name
| n -> n
let compare_category c1 c2 =
match compare_url_opt c1.cat_domain c2.cat_domain with
| 0 -> compare c1.cat_name c2.cat_name
| n -> n
let item_comp_funs =
[
(fun i1 i2 -> compare_url_opt i1.item_link i2.item_link);
(fun i1 i2 -> compare i1.item_title i2.item_title);
(fun i1 i2 -> compare i1.item_desc i2.item_desc);
(fun i1 i2 -> compare i1.item_pubdate i2.item_pubdate);
(fun i1 i2 -> compare i1.item_author i2.item_author);
(fun i1 i2 ->
compare_list ~f:compare_category i1.item_categories i2.item_categories);
(fun i1 i2 -> compare_url_opt i1.item_comments i2.item_comments);
(fun i1 i2 ->
compare_opt ~f:compare_enclosure i1.item_enclosure i2.item_enclosure);
(fun i1 i2 -> compare_opt ~f:compare_guid i1.item_guid i2.item_guid);
(fun i1 i2 -> compare_opt ~f:compare_source i1.item_source i2.item_source);
]
let rec apply_comp item1 item2 = function
| [] -> 0
| f :: q -> (
match f item1 item2 with 0 -> apply_comp item1 item2 q | n -> n)
let compare_item ?comp_data =
let comp_funs =
match comp_data with
| None -> item_comp_funs
| Some f ->
(fun i1 i2 -> compare_opt ~f i1.item_data i2.item_data)
:: item_comp_funs
in
fun item1 item2 -> apply_comp item1 item2 comp_funs
| null | https://raw.githubusercontent.com/ocaml/ood/75c4f85e9a8cbe26530301cc14df578f0fc5c494/src/ood-gen/vendor/ocamlrss/src/rss_types.ml | ocaml | ****************************************************************************
OCamlrss
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 Lesser General Public License 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.
License along with this program; if not, write to the Free Software
02111-1307 USA
Contact:
****************************************************************************
*
* The label of the Submit button in the text input area.
* Explains the text input area.
* The name of the text object in the text input area.
* The URL of the CGI script that processes text input requests.
* URL of the enclosure
* size in bytes
* MIME type
* See {{:#rsscloudInterface} specification} | Copyright ( C ) 2004 - 2013 Institut National de Recherche en Informatique
3 as published by the Free Software Foundation .
You should have received a copy of the GNU Library General Public
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA
type category = { cat_name : string; cat_domain : Uri.t option }
type image = {
image_url : Uri.t;
image_title : string;
image_link : Uri.t;
image_height : int option;
image_width : int option;
image_desc : string option;
}
type text_input = {
ti_title : string;
ti_link : Uri.t;
}
type enclosure = {
}
type cloud = {
cloud_domain : string;
cloud_port : int;
cloud_path : string;
cloud_register_procedure : string;
cloud_protocol : string;
}
type guid = Guid_permalink of Uri.t | Guid_name of string
type source = { src_name : string; src_url : Uri.t }
type 'a item_t = {
item_title : string option;
item_link : Uri.t option;
item_desc : string option;
item_pubdate : Ptime.t option;
item_author : string option;
item_categories : category list;
item_comments : Uri.t option;
item_enclosure : enclosure option;
item_guid : guid option;
item_source : source option;
item_content : string option;
item_data : 'a option;
}
type ('a, 'b) channel_t = {
ch_title : string;
ch_link : Uri.t;
ch_desc : string;
ch_language : string option;
ch_copyright : string option;
ch_managing_editor : string option;
ch_webmaster : string option;
ch_pubdate : Ptime.t option;
ch_last_build_date : Ptime.t option;
ch_categories : category list;
ch_generator : string option;
ch_cloud : cloud option;
ch_docs : Uri.t option;
ch_ttl : int option;
ch_image : image option;
ch_rating : string option;
ch_text_input : text_input option;
ch_skip_hours : int list option;
ch_skip_days : int list option;
ch_items : 'b item_t list;
ch_data : 'a option;
ch_namespaces : (string * string) list;
}
type item = unit item_t
type channel = (unit, unit) channel_t
let compare_opt ~f x y =
match (x, y) with
| Some _, None -> 1
| None, Some _ -> -1
| None, None -> 0
| Some x, Some y -> f x y
let compare_url_opt = compare_opt ~f:Uri.compare
let compare_list ~f =
let rec iter = function
| [], [] -> 0
| [], _ -> -1
| _, [] -> 1
| h1 :: q1, h2 :: q2 -> ( match f h1 h2 with 0 -> iter (q1, q2) | n -> n)
in
fun l1 l2 -> iter (l1, l2)
let compare_enclosure { encl_url = e1; _ } { encl_url = e2; _ } =
Uri.compare e1 e2
let compare_guid g1 g2 =
match (g1, g2) with
| Guid_permalink url1, Guid_permalink url2 -> Uri.compare url1 url2
| Guid_permalink _, Guid_name _ -> 1
| Guid_name _, Guid_permalink _ -> -1
| Guid_name s1, Guid_name s2 -> compare s1 s2
let compare_source s1 s2 =
match Uri.compare s1.src_url s2.src_url with
| 0 -> compare s1.src_name s2.src_name
| n -> n
let compare_category c1 c2 =
match compare_url_opt c1.cat_domain c2.cat_domain with
| 0 -> compare c1.cat_name c2.cat_name
| n -> n
let item_comp_funs =
[
(fun i1 i2 -> compare_url_opt i1.item_link i2.item_link);
(fun i1 i2 -> compare i1.item_title i2.item_title);
(fun i1 i2 -> compare i1.item_desc i2.item_desc);
(fun i1 i2 -> compare i1.item_pubdate i2.item_pubdate);
(fun i1 i2 -> compare i1.item_author i2.item_author);
(fun i1 i2 ->
compare_list ~f:compare_category i1.item_categories i2.item_categories);
(fun i1 i2 -> compare_url_opt i1.item_comments i2.item_comments);
(fun i1 i2 ->
compare_opt ~f:compare_enclosure i1.item_enclosure i2.item_enclosure);
(fun i1 i2 -> compare_opt ~f:compare_guid i1.item_guid i2.item_guid);
(fun i1 i2 -> compare_opt ~f:compare_source i1.item_source i2.item_source);
]
let rec apply_comp item1 item2 = function
| [] -> 0
| f :: q -> (
match f item1 item2 with 0 -> apply_comp item1 item2 q | n -> n)
let compare_item ?comp_data =
let comp_funs =
match comp_data with
| None -> item_comp_funs
| Some f ->
(fun i1 i2 -> compare_opt ~f i1.item_data i2.item_data)
:: item_comp_funs
in
fun item1 item2 -> apply_comp item1 item2 comp_funs
|
1cc9cf06ec2cb68a9ca5fbc9c91a568ae7ad878fc9132cf05a0a40764153e713 | xapi-project/xen-api | open_uri.ml |
* Copyright ( c ) 2012 Citrix Inc
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
*
* Copyright (c) 2012 Citrix Inc
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*)
open Xapi_stdext_pervasives.Pervasiveext
module D = Debug.Make (struct let name = "open_uri" end)
open D
let handle_socket f s = try f s with e -> Backtrace.is_important e ; raise e
let open_tcp f host port =
let host = Scanf.ksscanf host (fun _ _ -> host) "[%s@]" Fun.id in
let sockaddr =
match Unix.getaddrinfo host (string_of_int port) [] with
| [] ->
error "No addrinfo found for host: %s on port: %d" host port ;
raise Not_found
| addrinfo :: _ ->
addrinfo.Unix.ai_addr
in
let family = Unix.domain_of_sockaddr sockaddr in
let s = Unix.socket family Unix.SOCK_STREAM 0 in
finally
(fun () -> Unix.connect s sockaddr ; handle_socket f s)
(fun () -> Unix.close s)
let with_open_uri ?verify_cert uri f =
match Uri.scheme uri with
| Some "http" -> (
match (Uri.host uri, Uri.port uri) with
| Some host, Some port ->
open_tcp f host port
| Some host, None ->
open_tcp f host 80
| _, _ ->
failwith
(Printf.sprintf "Failed to parse host and port from URI: %s"
(Uri.to_string uri)
)
)
| Some "https" -> (
let verify_cert =
Option.value ~default:(Stunnel_client.pool ()) verify_cert
in
match (Uri.host uri, Uri.port uri) with
| Some host, Some port ->
Stunnel.with_connect ~verify_cert host port (fun s ->
f Safe_resources.Unixfd.(!(s.Stunnel.fd))
)
| Some host, None ->
Stunnel.with_connect ~verify_cert host !Constants.https_port (fun s ->
f Safe_resources.Unixfd.(!(s.Stunnel.fd))
)
| _, _ ->
failwith
(Printf.sprintf "Failed to parse host and port from URI: %s"
(Uri.to_string uri)
)
)
| Some "file" ->
let filename = Uri.path_and_query uri in
let sockaddr = Unix.ADDR_UNIX filename in
let s = Unix.socket Unix.PF_UNIX Unix.SOCK_STREAM 0 in
finally
(fun () -> Unix.connect s sockaddr ; handle_socket f s)
(fun () -> Unix.close s)
| Some x ->
failwith (Printf.sprintf "Unsupported URI scheme: %s" x)
| None ->
failwith (Printf.sprintf "Failed to parse URI: %s" (Uri.to_string uri))
| null | https://raw.githubusercontent.com/xapi-project/xen-api/48cc1489fff0e344246ecf19fc1ebed6f09c7471/ocaml/libs/open-uri/open_uri.ml | ocaml |
* Copyright ( c ) 2012 Citrix Inc
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
*
* Copyright (c) 2012 Citrix Inc
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*)
open Xapi_stdext_pervasives.Pervasiveext
module D = Debug.Make (struct let name = "open_uri" end)
open D
let handle_socket f s = try f s with e -> Backtrace.is_important e ; raise e
let open_tcp f host port =
let host = Scanf.ksscanf host (fun _ _ -> host) "[%s@]" Fun.id in
let sockaddr =
match Unix.getaddrinfo host (string_of_int port) [] with
| [] ->
error "No addrinfo found for host: %s on port: %d" host port ;
raise Not_found
| addrinfo :: _ ->
addrinfo.Unix.ai_addr
in
let family = Unix.domain_of_sockaddr sockaddr in
let s = Unix.socket family Unix.SOCK_STREAM 0 in
finally
(fun () -> Unix.connect s sockaddr ; handle_socket f s)
(fun () -> Unix.close s)
let with_open_uri ?verify_cert uri f =
match Uri.scheme uri with
| Some "http" -> (
match (Uri.host uri, Uri.port uri) with
| Some host, Some port ->
open_tcp f host port
| Some host, None ->
open_tcp f host 80
| _, _ ->
failwith
(Printf.sprintf "Failed to parse host and port from URI: %s"
(Uri.to_string uri)
)
)
| Some "https" -> (
let verify_cert =
Option.value ~default:(Stunnel_client.pool ()) verify_cert
in
match (Uri.host uri, Uri.port uri) with
| Some host, Some port ->
Stunnel.with_connect ~verify_cert host port (fun s ->
f Safe_resources.Unixfd.(!(s.Stunnel.fd))
)
| Some host, None ->
Stunnel.with_connect ~verify_cert host !Constants.https_port (fun s ->
f Safe_resources.Unixfd.(!(s.Stunnel.fd))
)
| _, _ ->
failwith
(Printf.sprintf "Failed to parse host and port from URI: %s"
(Uri.to_string uri)
)
)
| Some "file" ->
let filename = Uri.path_and_query uri in
let sockaddr = Unix.ADDR_UNIX filename in
let s = Unix.socket Unix.PF_UNIX Unix.SOCK_STREAM 0 in
finally
(fun () -> Unix.connect s sockaddr ; handle_socket f s)
(fun () -> Unix.close s)
| Some x ->
failwith (Printf.sprintf "Unsupported URI scheme: %s" x)
| None ->
failwith (Printf.sprintf "Failed to parse URI: %s" (Uri.to_string uri))
| |
98e7d012ca6f099de14b28ebec7d45d2565cdee98ce5197a84aa44e32119ad7c | ayazhafiz/plts | a.ml | open Util
type iflag = Init | Uninit
type ty =
| TName of string
| TInt
| TFn of { typarams : string list; params : ty list }
| TTup of (ty * iflag) list
| TExist of string * ty
type annot_val = Annot of value * ty
and value =
| VVar of string
| VInt of int
| VTyApp of annot_val * ty
| VPack of ty * annot_val * ty
(** pack [t1, v] as ∃a.t2 (t1 is the true a) *)
and heap_value =
| HCode of {
typarams : string list;
params : (string * ty) list;
body : term;
}
| HTup of annot_val list
and decl =
| DeclVal of string * annot_val (** x = v *)
* x =
| DeclOp of string * op * annot_val * annot_val (** x = v R v *)
| DeclUnpack of string * string * annot_val (** [a, x] = unpack v *)
| DeclTupMalloc of string * ty list
| DeclTupInit of string * annot_val * int * annot_val
(* x = v1[i] <- v2 *)
and term =
| Let of decl * term (** let d in e *)
| App of annot_val * annot_val list (** v<ts>(vs) *)
| If0 of annot_val * term * term
| Halt of ty * annot_val
and program = Prog of (string * heap_value) list (* letrecs *) * term
let tyaeq t1 t2 =
let nexti =
let i = ref 0 in
fun () ->
incr i;
!i
in
let rec go s1 s2 = function
| TName x1, TName x2 -> (
match (List.assoc_opt x1 s1, List.assoc_opt x2 s2) with
| Some n1, Some n2 -> n1 = n2
| None, None -> x1 = x2
| _ -> false)
| TInt, TInt -> true
| TFn { typarams = tp1; params = p1 }, TFn { typarams = tp2; params = p2 }
->
if
List.length tp1 <> List.length tp2 || List.length p1 <> List.length p2
then false
else
let tp_maps = List.map (fun _ -> nexti ()) tp1 in
let s1' = List.combine tp1 tp_maps @ s1 in
let s2' = List.combine tp2 tp_maps @ s2 in
List.for_all (go s1' s2') (List.combine p1 p2)
| TTup t1, TTup t2 ->
List.length t1 = List.length t2
&& List.for_all2
(fun (t1, i1) (t2, i2) -> i1 = i2 && go s1 s2 (t1, t2))
t1 t2
| TExist (a1, t1), TExist (a2, t2) ->
let ti = nexti () in
go ((a1, ti) :: s1) ((a2, ti) :: s2) (t1, t2)
| _ -> false
in
go [] [] (t1, t2)
(*** Print ***)
let pp_ty f =
let open Format in
let rec go = function
| TInt -> fprintf f "int"
| TName a -> pp_print_string f a
| TFn { typarams; params } ->
fprintf f "@[<hov 2>(";
if List.length typarams <> 0 then (
fprintf f "∀<";
let lasti = List.length typarams - 1 in
List.iteri
(fun i t ->
go (TName t);
if i <> lasti then fprintf f ",@ ")
typarams;
fprintf f ">.@,");
fprintf f "(";
let lasti = List.length params - 1 in
List.iteri
(fun i t ->
go t;
if i <> lasti then fprintf f ",@ ")
params;
fprintf f ")@ -> void)@]"
| TTup ts ->
fprintf f "@[<hov 2>(";
let lasti = List.length ts - 1 in
List.iteri
(fun i (t, iflag) ->
if iflag = Uninit then fprintf f "!";
go t;
if i <> lasti then fprintf f ",@ ")
ts;
fprintf f ")@]"
| TExist (a, t) ->
fprintf f "@[<hov 2>(∃%s.@," a;
go t;
fprintf f ")@]"
in
go
let rec pp_annot f (Annot (v, _)) = pp_value f v
and pp_value f =
let open Format in
let go = function
| VVar x -> pp_print_string f x
| VInt i -> pp_print_int f i
| VTyApp (v, t) ->
fprintf f "@[<hov 2>";
pp_annot f v;
fprintf f "<@,";
pp_ty f t;
fprintf f ">@]"
| VPack (t1, v, t2) ->
fprintf f "@[<hov 2>(pack [";
pp_ty f t1;
fprintf f ",@ ";
pp_annot f v;
fprintf f "]@ as ";
pp_ty f t2;
fprintf f ")@]"
in
go
and pp_heap_value f =
let open Format in
function
| HCode { typarams; params; body } ->
fprintf f "@[<hov 2>(code";
if List.length typarams <> 0 then (
fprintf f "<";
let lasti = List.length typarams - 1 in
List.iteri
(fun i t ->
pp_print_string f t;
if i <> lasti then fprintf f ",@ ")
typarams;
fprintf f ">.@,");
fprintf f "(";
let lasti = List.length params - 1 in
List.iteri
(fun i (p, t) ->
fprintf f "@[<hov 2>%s:@ " p;
pp_ty f t;
fprintf f "@]";
if i <> lasti then fprintf f ",@ ")
params;
fprintf f ").@ ";
pp_term f body;
fprintf f ")@]"
| HTup vs ->
fprintf f "@[<hov 2>(";
let lasti = List.length vs - 1 in
List.iteri
(fun i e ->
pp_annot f e;
if i <> lasti then fprintf f ",@ ")
vs;
fprintf f ")@]"
and pp_decl f =
let open Format in
function
| DeclVal (s, v) ->
fprintf f "@[<hov 2>%s =@ " s;
pp_annot f v;
fprintf f "@]"
| DeclProj (s, v, i) ->
fprintf f "@[<hov 2>%s =@ " s;
pp_annot f v;
fprintf f ".%d@]" i
| DeclOp (s, op, v1, v2) ->
fprintf f "@[<hov 2>%s =@ @[<hov 2>" s;
pp_annot f v1;
fprintf f " ";
pp_op f op;
fprintf f "@ ";
pp_annot f v2;
fprintf f "@]@]"
| DeclUnpack (a, x, v) ->
fprintf f "@[<hov 2>[%s, %s] =@ @[<hov 2>unpack@ " a x;
pp_annot f v;
fprintf f "@]@]"
| DeclTupMalloc (x, ts) ->
fprintf f "@[<hov 2>%s =@ malloc@[<hov 2><" x;
let lasti = List.length ts - 1 in
List.iteri
(fun i t ->
pp_ty f t;
if i <> lasti then fprintf f ",@ ")
ts;
fprintf f ">@]@]"
| DeclTupInit (x, v1, i, v2) ->
fprintf f "@[<hov 2>%s =@ " x;
pp_annot f v1;
fprintf f ".%d <- " i;
pp_annot f v2;
fprintf f "@]"
and pp_term f =
let open Format in
let rec go = function
| Let (d, e) ->
fprintf f "@[<hov>(let@;<1 2>@[";
pp_decl f d;
fprintf f "@]@ in@;<1 2>@[";
go e;
fprintf f "@])@]"
| App (v, params) ->
fprintf f "@[<hov 2>(";
pp_annot f v;
fprintf f "(";
let lasti = List.length params - 1 in
List.iteri
(fun i p ->
pp_annot f p;
if i <> lasti then fprintf f ",@ ")
params;
fprintf f "))@]"
| If0 (test, then', else') ->
fprintf f "@[<hov>(if0@;<1 2>@[";
pp_annot f test;
fprintf f "@]@ then@;<1 2>@[";
go then';
fprintf f "@]@ else@;<1 2>@[";
go else';
fprintf f "@])@]"
| Halt (t, v) ->
fprintf f "@[<hov 2>halt<@,";
pp_ty f t;
fprintf f ">@,";
pp_annot f v;
fprintf f "@]"
in
go
and pp_program f =
let open Format in
function
| Prog (defs, e) ->
fprintf f "@[<hov>letrec@;<1 2>@[<v>";
List.iter
(fun (n, hv) ->
fprintf f "@[<hov 2>%s ->@ " n;
pp_heap_value f hv;
fprintf f "@]@,")
defs;
fprintf f "@]@ in@;<1 2>@[";
pp_term f e;
fprintf f "@]@]"
let string_of_annot e = with_buffer (fun f -> pp_annot f e) 80
let string_of_value e = with_buffer (fun f -> pp_value f e) 80
let string_of_heap_value e = with_buffer (fun f -> pp_heap_value f e) 80
let string_of_term e = with_buffer (fun f -> pp_term f e) 80
let string_of_ty t = with_buffer (fun f -> pp_ty f t) 80
let string_of_program p = with_buffer (fun f -> pp_program f p) 80
* * * *
let tyerr what = raise (TyErr ("H type error: " ^ what))
let rec ftv = function
| TInt -> SSet.empty
| TName a -> SSet.singleton a
| TTup ts ->
List.map fst ts |> List.map ftv |> List.fold_left SSet.union SSet.empty
| TFn { typarams; params } ->
let ftvs = SSet.(List.fold_left union empty (List.map ftv params)) in
SSet.(diff ftvs (of_list typarams))
| TExist (a, t) -> SSet.remove a (ftv t)
let tysub a ta t =
let rec go subs = function
| TInt -> TInt
| TName a -> (
match List.assoc_opt a subs with Some t -> t | None -> TName a)
| TTup ts -> TTup (List.map (fun (t, i) -> (go subs t, i)) ts)
| TFn { typarams; params } ->
if List.mem a typarams then TFn { typarams; params }
else if List.exists (fun a' -> SSet.mem a' (ftv ta)) typarams then
(* Something like (∀(a', b'). a)[a/a']. Naive substitution would result in (∀a'. a'),
transforming the constant quanitifier at a' in the outer scope to the identity.
Find a fresh name a'->a'' inside the binder. *)
let ftv_ta = ftv ta in
let ftv_body =
SSet.(List.fold_left union empty (List.map ftv params))
in
let used_vars = SSet.union ftv_ta ftv_body in
let typarams', newsubs =
List.map
(fun a' ->
if SSet.mem a' ftv_ta then
let a'' = freshen a' used_vars in
(a'', Some (a', TName a''))
else (a', None))
typarams
|> List.split
in
let newsubs = List.filter_map Fun.id newsubs in
TFn
{
typarams = typarams';
params = List.map (go (newsubs @ subs)) params;
}
else TFn { typarams; params = List.map (go subs) params }
| TExist (a', t) ->
if a = a' then TExist (a', t)
else if SSet.mem a' (ftv ta) then
let a'' = freshen a' (SSet.union (ftv ta) (ftv t)) in
TExist (a'', go ((a', TName a'') :: subs) t)
else TExist (a', go subs t)
in
go [ (a, ta) ] t
let sa = string_of_annot
let sv = string_of_value
let sh = string_of_heap_value
let se = string_of_term
let st = string_of_ty
let sprintf = Printf.sprintf
let ty_wf t tctx =
if not (SSet.subset (ftv t) (SSet.of_list tctx)) then
tyerr (Printf.sprintf "%s is malformed" (string_of_ty t))
let rec tyof_annot tctx vctx (Annot (v, t)) =
let vty = tyof tctx vctx v in
if tyaeq vty t then t
else tyerr (sprintf "%s checks as %s not %s" (sv v) (st vty) (st t))
and tyof tctx vctx = function
| VVar x -> (
match List.assoc_opt x vctx with
| Some t -> t
| None -> tyerr (sprintf "undeclared variable %s" x))
| VInt _ -> TInt
| VTyApp (v, o) -> (
ty_wf o tctx;
match tyof_annot tctx vctx v with
| TFn { typarams = a :: bs; params = ts } ->
TFn { typarams = bs; params = List.map (fun t -> tysub a o t) ts }
| TFn _ ->
tyerr
(sprintf "type application target %s has no type parameters" (sa v))
| _ ->
tyerr (sprintf "type application target %s is not a function" (sa v)))
| VPack (t1, v, TExist (a, t2)) ->
ty_wf t1 tctx;
let v_reifyty = tyof_annot tctx vctx v in
let v_expectty = tysub a t1 t2 in
if tyaeq v_expectty v_reifyty then TExist (a, t2)
else
tyerr
(sprintf "declared package type %s does not match checked type %s"
(st v_expectty) (st v_reifyty))
| VPack _ -> tyerr "package must be an existential type"
and tyof_heap_val vctx = function
| HCode { typarams; params; body } ->
(* well-formedness of types of parameters should be closed under this fn *)
List.iter (fun (_, t) -> ty_wf t typarams) params;
let fn_ty = TFn { typarams; params = List.map snd params } in
let vctx' = params @ vctx in
term_wf typarams vctx' body;
fn_ty
| HTup vs -> TTup (List.map (fun v -> (tyof_annot [] vctx v, Init)) vs)
and term_wf tctx vctx = function
| Let (DeclVal (x, v), e) ->
let vty = tyof_annot tctx vctx v in
term_wf tctx ((x, vty) :: vctx) e
| Let (DeclProj (x, v, i), e) -> (
match tyof_annot tctx vctx v with
| TTup ts -> (
match List.nth_opt ts (i - 1) with
| Some (ti, Init) -> term_wf tctx ((x, ti) :: vctx) e
| Some (_, Uninit) ->
tyerr (sprintf "tuple %s is not initialized at index %d" (sa v) i)
| None ->
tyerr
(sprintf "tuple type of %s cannot be indexed at \"%d\"" (sa v) i)
)
| _ -> tyerr (sprintf "projection target %s is not a tuple" (sa v)))
| Let (DeclOp (x, _, v1, v2), e) -> (
match (tyof_annot tctx vctx v1, tyof_annot tctx vctx v2) with
| TInt, TInt -> term_wf tctx ((x, TInt) :: vctx) e
| _ ->
tyerr
(sprintf "both arguments %s, %s of operation must be ints" (sa v1)
(sa v2)))
| Let (DeclUnpack (a, x, v), e) -> (
match tyof_annot tctx vctx v with
| TExist (a', t') ->
let t = if a = a' then t' else tysub a' (TName a) t' in
term_wf (a :: tctx) ((x, t) :: vctx) e
| _ ->
tyerr
(sprintf
"%s cannot be unpacked because it is not an existential type"
(sa v)))
| Let (DeclTupMalloc (x, ts), e) ->
List.iter (fun t -> ty_wf t tctx) ts;
let tupty = TTup (List.map (fun t -> (t, Uninit)) ts) in
term_wf tctx ((x, tupty) :: vctx) e
| Let (DeclTupInit (x, v1, i, v2), e) -> (
match tyof_annot tctx vctx v1 with
| TTup ts -> (
match List.nth_opt ts (i - 1) with
| Some (t, _) ->
if tyaeq t (tyof_annot tctx vctx v2) then
let fields' =
List.mapi
(fun j (t, iflag) ->
if j = i - 1 then (t, Init) else (t, iflag))
ts
in
term_wf tctx ((x, TTup fields') :: vctx) e
else
tyerr
(sprintf "%s cannot initialize %s.%d, which expects type %s"
(sa v2) (sa v1) i (st t))
| None ->
tyerr (sprintf "%d is out of range of the tuple %s" i (sa v1)))
| _ ->
tyerr
(sprintf "%s cannot be projected because it is not a tuple" (sa v1))
)
| App (fn, vargs) -> (
match tyof_annot tctx vctx fn with
| TFn { typarams = []; params } ->
if List.length params <> List.length vargs then
tyerr
(sprintf "expected %d formal arguments in application to %s"
(List.length params) (sa fn));
List.iter2
(fun arg param_ty ->
let arg_ty = tyof_annot tctx vctx arg in
if not (tyaeq arg_ty param_ty) then
tyerr
(sprintf
"in application to %s, expected argument %s to be of type \
%s (found type %s)"
(sa fn) (sa arg) (st param_ty) (st arg_ty)))
vargs params
| TFn _ as fnty ->
tyerr
(sprintf "application to %s (%s) must have no free type variables"
(sa fn) (st fnty))
| _ -> tyerr (sprintf "application target %s is not a function" (sa fn)))
| If0 (test, then', else') ->
if not (tyaeq (tyof_annot tctx vctx test) TInt) then
tyerr (sprintf "if0 test %s must be an int" (sa test));
term_wf tctx vctx then';
term_wf tctx vctx else'
| Halt (t, v) ->
if not (tyaeq (tyof_annot tctx vctx v) t) then
tyerr (sprintf "halting value %s is not of type %s" (sa v) (st t))
and check_program (Prog (defs, e)) =
let assume_ctx =
List.filter_map
(function
| f, HCode { typarams; params; body = _ } ->
Some (f, TFn { typarams; params = List.map snd params })
| _, HTup _ -> None)
defs
in
if SSet.of_list (List.map fst defs) |> SSet.cardinal <> List.length defs then
tyerr "duplicate letrec definitions in program";
List.iter (fun (_, ty) -> ty_wf ty []) assume_ctx;
List.iter2
(fun (_, code) (f, ty) ->
let infer = tyof_heap_val assume_ctx code in
if not (tyaeq infer ty) then
tyerr
(sprintf "%s expected to have type %s, found %s" f (st ty) (st infer)))
defs assume_ctx;
term_wf [] assume_ctx e
(*** Eval ***)
let rec fvs_a (Annot (v, _)) = fvs_v v
and fvs_v =
let open SSet in
let go = function
| VVar x -> singleton x
| VInt _ -> empty
| VPack (_, v, _) -> fvs_a v
| VTyApp (v, _) -> fvs_a v
in
go
and fvs_hv =
let open SSet in
function
| HCode { typarams = _; params; body } ->
let bound = of_list (List.map fst params) in
diff (fvs_t body) bound
| HTup vs -> List.fold_left union empty (List.map fvs_a vs)
and fvs_t =
let open SSet in
let rec go = function
| Let (DeclVal (x, v), e) -> union (fvs_a v) (remove x (go e))
| Let (DeclProj (x, v, _), e) -> union (fvs_a v) (remove x (go e))
| Let (DeclOp (x, _, v1, v2), e) ->
union (fvs_a v1) (fvs_a v2) |> union (remove x (go e))
| Let (DeclUnpack (_, x, v), e) -> union (fvs_a v) (remove x (go e))
| Let (DeclTupMalloc (x, _), e) -> remove x (go e)
| Let (DeclTupInit (x, v1, _, v2), e) ->
union (fvs_a v1) (fvs_a v2) |> union (remove x (go e))
| App (v, vs) -> List.fold_left union empty (List.map fvs_a (v :: vs))
| If0 (v1, t2, t3) -> fvs_a v1 |> union (go t2) |> union (go t3)
| Halt (_, v) -> fvs_a v
in
go
let subst x e =
let rec go_a subs (Annot (v, t)) = Annot (go_v subs v, t)
and go_v subs tm =
match tm with
| VVar y -> (
match List.assoc_opt y subs with Some e -> e | None -> VVar y)
| VInt _ -> tm
| VTyApp (v, t) -> VTyApp (go_a subs v, t)
| VPack (t1, v, t2) -> VPack (t1, go_a subs v, t2)
and go_t subs tm =
let do_let y body create_let =
if x = y then tm
else if SSet.mem y (fvs_v e) then
let y' = freshen y (SSet.union (fvs_v e) (fvs_t body)) in
create_let y' (go_t ((y, VVar y') :: subs) body)
else create_let y (go_t subs body)
in
match tm with
| Let (DeclVal (y, v), body) ->
do_let y body (fun y' body' -> Let (DeclVal (y', go_a subs v), body'))
| Let (DeclProj (y, v, i), body) ->
do_let y body (fun y' body' ->
Let (DeclProj (y', go_a subs v, i), body'))
| Let (DeclOp (y, op, e1, e2), body) ->
do_let y body (fun y' body' ->
Let (DeclOp (y', op, go_a subs e1, go_a subs e2), body'))
| Let (DeclUnpack (a, y, v), body) ->
do_let y body (fun y' body' ->
Let (DeclUnpack (a, y', go_a subs v), body'))
| Let (DeclTupMalloc (y, ts), body) ->
do_let y body (fun y' body' -> Let (DeclTupMalloc (y', ts), body'))
| Let (DeclTupInit (y, v1, i, v2), body) ->
do_let y body (fun y' body' ->
Let (DeclTupInit (y', go_a subs v1, i, go_a subs v2), body'))
| App (v, vs) -> App (go_a subs v, List.map (go_a subs) vs)
| If0 (v, t1, t2) -> If0 (go_a subs v, go_t subs t1, go_t subs t2)
| Halt (t, v) -> Halt (t, go_a subs v)
in
go_t [ (x, e) ]
let subst_v x e v =
match subst x e (App (Annot (v, TName "dummy"), [])) with
| App (Annot (v', TName "dummy"), _) -> v'
| _ -> failwith "bad subst"
let evalerr what = raise (EvalErr ("H eval error: " ^ what))
let unwrap_value = function
| VVar x -> evalerr ("unresolved variable " ^ x)
| v -> v
type rt_heap_val = RTup of value IntMap.t
let print_val = function
| RTup fields ->
let fields =
IntMap.to_seq fields |> List.of_seq
|> List.map (fun (i, v) -> sprintf "%d: %s" i (sv v))
in
sprintf "(%s)" (String.concat ", " fields)
type rt_heap = (string * rt_heap_val) list
let heap_subst x v heap =
List.map
(fun (n, hv) ->
let n' = match v with VVar v when n = x -> v | _ -> n in
let hv' = match hv with RTup vs -> RTup (IntMap.map (subst_v x v) vs) in
(n', hv'))
heap
let print_heap h =
String.concat "; "
(List.map (fun (x, hv) -> sprintf "%s => %s" x (print_val hv)) h)
let heapfind x heap hint =
match List.assoc_opt x heap with
| Some v -> v
| None ->
evalerr
(sprintf "%s not found in heap %s (in %s)" x (print_heap heap) hint)
let step defs heap = function
| Let (DeclVal (x, Annot (v, _)), body) ->
(subst x v body, heap_subst x v heap)
| Let (DeclProj (x, Annot (VVar tup, _), i), body) as dec -> (
let (RTup fields) = heapfind tup heap (se dec) in
match IntMap.find_opt i fields with
| Some vi -> (subst x vi body, heap_subst x vi heap)
| None ->
evalerr
(sprintf "field %d does not exist on %s" i (print_val (RTup fields)))
)
| Let (DeclOp (x, op, Annot (VInt i, _), Annot (VInt j, _)), body) ->
let v = VInt (do_op op i j) in
(subst x v body, heap_subst x v heap)
| Let (DeclUnpack (_, x, Annot (VPack (_, Annot (v, _), _), _)), body) ->
(subst x v body, heap_subst x v heap)
| Let (DeclTupMalloc (x, _), body) ->
let heap' = (x, RTup IntMap.empty) :: heap in
(body, heap')
| Let (DeclTupInit (x, Annot (VVar tup, _), i, Annot (v, _)), body) ->
let (RTup fields) = List.assoc tup heap in
let x_tup = RTup (IntMap.add i v fields) in
let heap' = (x, x_tup) :: heap in
(body, heap')
| App (Annot (VVar f, _), args) -> (
match List.assoc f defs with
| HCode { params; body; _ } ->
let body', heap' =
List.fold_left2
(fun (body, heap) (p, _) (Annot (rawv, _)) ->
(subst p rawv body, heap_subst p rawv heap))
(body, heap) params args
in
(body', heap')
| hv -> evalerr (sprintf "cannot call %s" (sh hv)))
| If0 (Annot (VInt 0, _), t2, _) -> (t2, heap)
| If0 (Annot (VInt _, _), _, t3) -> (t3, heap)
| t -> evalerr (sprintf "term %s is stuck" (se t))
let rec eval defs heap i = function
| Halt (_, Annot (v, _)) -> unwrap_value v
| e ->
if i = 2015 then failwith (sprintf "stuck at %s\n\n" (se e))
else
let e', heap' = step defs heap e in
eval defs heap' (i + 1) e'
let eval_top (Prog (defs, body)) = eval defs [] 0 body
(*** Translation from C ***)
let rec trans_ty = function
| H.TName x -> TName x
| H.TInt -> TInt
| H.TFn { typarams; params } ->
TFn { typarams; params = List.map trans_ty params }
| H.TTup tys -> TTup (List.map (fun t -> (trans_ty t, Init)) tys)
| H.TExist (a, t) -> TExist (a, trans_ty t)
let seq_decls = List.fold_right (fun d e -> Let (d, e))
let rec trans_aval fresh = function
| H.Annot (H.VVar x, t) -> ([], Annot (VVar x, trans_ty t))
| H.Annot (H.VInt i, t) -> ([], Annot (VInt i, trans_ty t))
| H.Annot (H.VTyApp (v, o), t) ->
let d, v' = trans_aval fresh v in
(d, Annot (VTyApp (v', trans_ty o), trans_ty t))
| H.Annot (H.VPack (t, v, t'), t'') ->
let d, v' = trans_aval fresh v in
(d, Annot (VPack (trans_ty t, v', trans_ty t'), trans_ty t''))
| H.Annot (H.VTup us, t) ->
let ts = List.map (fun (H.Annot (_, t)) -> trans_ty t) us in
let dss, vs = List.map (trans_aval fresh) us |> List.split in
let ds1 = List.concat dss in
let y0 = fresh "y" in
let ttup0 = TTup (List.map (fun t -> (t, Uninit)) ts) in
let malloc = DeclTupMalloc (y0, ts) in
let rec goinit i yi_1 ttupi_1 = function
| vi :: vrest ->
let yi = fresh "y" in
let ttupi =
TTup
(List.mapi
(fun j t -> if j + 1 <= i then (t, Init) else (t, Uninit))
ts)
in
let dec_i = DeclTupInit (yi, Annot (VVar yi_1, ttupi_1), i, vi) in
if vrest = [] then ([ dec_i ], yi)
else
let dec_rest, yn = goinit (i + 1) yi ttupi vrest in
(dec_i :: dec_rest, yn)
| [] -> (* empty tuple type *) ([], y0)
in
let ds2, yn = goinit 1 y0 ttup0 vs in
let ds = ds1 @ [ malloc ] @ ds2 in
(ds, Annot (VVar yn, trans_ty t))
and trans_heap fresh = function
| H.Code { typarams; params; body } ->
let params' = List.map (fun (p, t) -> (p, trans_ty t)) params in
let body' = trans_term fresh body in
HCode { typarams; params = params'; body = body' }
and trans_decl fresh = function
| H.DeclVal (x, v) ->
let d, v' = trans_aval fresh v in
d @ [ DeclVal (x, v') ]
| H.DeclProj (x, v, i) ->
let d, v' = trans_aval fresh v in
d @ [ DeclProj (x, v', i) ]
| H.DeclOp (x, op, v1, v2) ->
let d1, v1' = trans_aval fresh v1 in
let d2, v2' = trans_aval fresh v2 in
d1 @ d2 @ [ DeclOp (x, op, v1', v2') ]
| H.DeclUnpack (a, x, v) ->
let d, v' = trans_aval fresh v in
d @ [ DeclUnpack (a, x, v') ]
and trans_term fresh = function
| H.Let (d, e) -> seq_decls (trans_decl fresh d) (trans_term fresh e)
| H.App (v, vs) ->
let d, v' = trans_aval fresh v in
let ds, vs' = List.map (trans_aval fresh) vs |> List.split in
seq_decls (List.concat (d :: ds)) (App (v', vs'))
| H.If0 (v, t1, t2) ->
let d, v' = trans_aval fresh v in
seq_decls d (If0 (v', trans_term fresh t1, trans_term fresh t2))
| H.Halt (t, v) ->
let d, v' = trans_aval fresh v in
seq_decls d (Halt (trans_ty t, v'))
let all_names =
let open H in
let open SSet in
let rec goa = function Annot (v, t) -> union (gov v) (goty t)
and gov = function
| VVar x -> singleton x
| VInt _ -> empty
| VTup ts -> List.fold_left union empty (List.map goa ts)
| VTyApp (v, t) -> union (goa v) (goty t)
| VPack (t1, v, t2) -> union (goty t1) (goty t2) |> union (goa v)
and goh = function
| Code { typarams; params; body } ->
of_list typarams
|> union (of_list (List.map fst params))
|> union (got body)
and goprog = function
| Prog (defs, e) ->
let defs_names = List.map (fun (f, heap) -> add f (goh heap)) defs in
List.fold_left union empty defs_names |> union (got e)
and god = function
| DeclVal (x, v) | DeclProj (x, v, _) -> add x (goa v)
| DeclOp (x, _, v1, v2) -> union (goa v1) (goa v2) |> add x
| DeclUnpack (a, x, v) -> goa v |> add a |> add x
and got = function
| Let (d, t) -> union (god d) (got t)
| App (v, vs) -> List.fold_left union (goa v) (List.map goa vs)
| If0 (v, t1, t2) -> union (got t1) (got t2) |> union (goa v)
| Halt (t, v) -> union (goty t) (goa v)
and goty = function
| TInt -> empty
| TName x -> singleton x
| TFn { typarams; params } ->
union (of_list typarams)
(List.fold_left union empty (List.map goty params))
| TTup ts -> List.fold_left union empty (List.map goty ts)
| TExist (a, t) -> add a (goty t)
in
goprog
let trans_top (H.Prog (defs, e) as u) =
let fresh = fresh_generator (all_names u) in
let defs' = List.map (fun (x, h) -> (x, trans_heap fresh h)) defs in
let e' = trans_term fresh e in
Prog (defs', e')
| null | https://raw.githubusercontent.com/ayazhafiz/plts/725b7fd0d4bd65e15f12cc1fec80fa7402dec167/TAL/a.ml | ocaml | * pack [t1, v] as ∃a.t2 (t1 is the true a)
* x = v
* x = v R v
* [a, x] = unpack v
x = v1[i] <- v2
* let d in e
* v<ts>(vs)
letrecs
** Print **
Something like (∀(a', b'). a)[a/a']. Naive substitution would result in (∀a'. a'),
transforming the constant quanitifier at a' in the outer scope to the identity.
Find a fresh name a'->a'' inside the binder.
well-formedness of types of parameters should be closed under this fn
** Eval **
** Translation from C **
empty tuple type | open Util
type iflag = Init | Uninit
type ty =
| TName of string
| TInt
| TFn of { typarams : string list; params : ty list }
| TTup of (ty * iflag) list
| TExist of string * ty
type annot_val = Annot of value * ty
and value =
| VVar of string
| VInt of int
| VTyApp of annot_val * ty
| VPack of ty * annot_val * ty
and heap_value =
| HCode of {
typarams : string list;
params : (string * ty) list;
body : term;
}
| HTup of annot_val list
and decl =
* x =
| DeclTupMalloc of string * ty list
| DeclTupInit of string * annot_val * int * annot_val
and term =
| If0 of annot_val * term * term
| Halt of ty * annot_val
let tyaeq t1 t2 =
let nexti =
let i = ref 0 in
fun () ->
incr i;
!i
in
let rec go s1 s2 = function
| TName x1, TName x2 -> (
match (List.assoc_opt x1 s1, List.assoc_opt x2 s2) with
| Some n1, Some n2 -> n1 = n2
| None, None -> x1 = x2
| _ -> false)
| TInt, TInt -> true
| TFn { typarams = tp1; params = p1 }, TFn { typarams = tp2; params = p2 }
->
if
List.length tp1 <> List.length tp2 || List.length p1 <> List.length p2
then false
else
let tp_maps = List.map (fun _ -> nexti ()) tp1 in
let s1' = List.combine tp1 tp_maps @ s1 in
let s2' = List.combine tp2 tp_maps @ s2 in
List.for_all (go s1' s2') (List.combine p1 p2)
| TTup t1, TTup t2 ->
List.length t1 = List.length t2
&& List.for_all2
(fun (t1, i1) (t2, i2) -> i1 = i2 && go s1 s2 (t1, t2))
t1 t2
| TExist (a1, t1), TExist (a2, t2) ->
let ti = nexti () in
go ((a1, ti) :: s1) ((a2, ti) :: s2) (t1, t2)
| _ -> false
in
go [] [] (t1, t2)
let pp_ty f =
let open Format in
let rec go = function
| TInt -> fprintf f "int"
| TName a -> pp_print_string f a
| TFn { typarams; params } ->
fprintf f "@[<hov 2>(";
if List.length typarams <> 0 then (
fprintf f "∀<";
let lasti = List.length typarams - 1 in
List.iteri
(fun i t ->
go (TName t);
if i <> lasti then fprintf f ",@ ")
typarams;
fprintf f ">.@,");
fprintf f "(";
let lasti = List.length params - 1 in
List.iteri
(fun i t ->
go t;
if i <> lasti then fprintf f ",@ ")
params;
fprintf f ")@ -> void)@]"
| TTup ts ->
fprintf f "@[<hov 2>(";
let lasti = List.length ts - 1 in
List.iteri
(fun i (t, iflag) ->
if iflag = Uninit then fprintf f "!";
go t;
if i <> lasti then fprintf f ",@ ")
ts;
fprintf f ")@]"
| TExist (a, t) ->
fprintf f "@[<hov 2>(∃%s.@," a;
go t;
fprintf f ")@]"
in
go
let rec pp_annot f (Annot (v, _)) = pp_value f v
and pp_value f =
let open Format in
let go = function
| VVar x -> pp_print_string f x
| VInt i -> pp_print_int f i
| VTyApp (v, t) ->
fprintf f "@[<hov 2>";
pp_annot f v;
fprintf f "<@,";
pp_ty f t;
fprintf f ">@]"
| VPack (t1, v, t2) ->
fprintf f "@[<hov 2>(pack [";
pp_ty f t1;
fprintf f ",@ ";
pp_annot f v;
fprintf f "]@ as ";
pp_ty f t2;
fprintf f ")@]"
in
go
and pp_heap_value f =
let open Format in
function
| HCode { typarams; params; body } ->
fprintf f "@[<hov 2>(code";
if List.length typarams <> 0 then (
fprintf f "<";
let lasti = List.length typarams - 1 in
List.iteri
(fun i t ->
pp_print_string f t;
if i <> lasti then fprintf f ",@ ")
typarams;
fprintf f ">.@,");
fprintf f "(";
let lasti = List.length params - 1 in
List.iteri
(fun i (p, t) ->
fprintf f "@[<hov 2>%s:@ " p;
pp_ty f t;
fprintf f "@]";
if i <> lasti then fprintf f ",@ ")
params;
fprintf f ").@ ";
pp_term f body;
fprintf f ")@]"
| HTup vs ->
fprintf f "@[<hov 2>(";
let lasti = List.length vs - 1 in
List.iteri
(fun i e ->
pp_annot f e;
if i <> lasti then fprintf f ",@ ")
vs;
fprintf f ")@]"
and pp_decl f =
let open Format in
function
| DeclVal (s, v) ->
fprintf f "@[<hov 2>%s =@ " s;
pp_annot f v;
fprintf f "@]"
| DeclProj (s, v, i) ->
fprintf f "@[<hov 2>%s =@ " s;
pp_annot f v;
fprintf f ".%d@]" i
| DeclOp (s, op, v1, v2) ->
fprintf f "@[<hov 2>%s =@ @[<hov 2>" s;
pp_annot f v1;
fprintf f " ";
pp_op f op;
fprintf f "@ ";
pp_annot f v2;
fprintf f "@]@]"
| DeclUnpack (a, x, v) ->
fprintf f "@[<hov 2>[%s, %s] =@ @[<hov 2>unpack@ " a x;
pp_annot f v;
fprintf f "@]@]"
| DeclTupMalloc (x, ts) ->
fprintf f "@[<hov 2>%s =@ malloc@[<hov 2><" x;
let lasti = List.length ts - 1 in
List.iteri
(fun i t ->
pp_ty f t;
if i <> lasti then fprintf f ",@ ")
ts;
fprintf f ">@]@]"
| DeclTupInit (x, v1, i, v2) ->
fprintf f "@[<hov 2>%s =@ " x;
pp_annot f v1;
fprintf f ".%d <- " i;
pp_annot f v2;
fprintf f "@]"
and pp_term f =
let open Format in
let rec go = function
| Let (d, e) ->
fprintf f "@[<hov>(let@;<1 2>@[";
pp_decl f d;
fprintf f "@]@ in@;<1 2>@[";
go e;
fprintf f "@])@]"
| App (v, params) ->
fprintf f "@[<hov 2>(";
pp_annot f v;
fprintf f "(";
let lasti = List.length params - 1 in
List.iteri
(fun i p ->
pp_annot f p;
if i <> lasti then fprintf f ",@ ")
params;
fprintf f "))@]"
| If0 (test, then', else') ->
fprintf f "@[<hov>(if0@;<1 2>@[";
pp_annot f test;
fprintf f "@]@ then@;<1 2>@[";
go then';
fprintf f "@]@ else@;<1 2>@[";
go else';
fprintf f "@])@]"
| Halt (t, v) ->
fprintf f "@[<hov 2>halt<@,";
pp_ty f t;
fprintf f ">@,";
pp_annot f v;
fprintf f "@]"
in
go
and pp_program f =
let open Format in
function
| Prog (defs, e) ->
fprintf f "@[<hov>letrec@;<1 2>@[<v>";
List.iter
(fun (n, hv) ->
fprintf f "@[<hov 2>%s ->@ " n;
pp_heap_value f hv;
fprintf f "@]@,")
defs;
fprintf f "@]@ in@;<1 2>@[";
pp_term f e;
fprintf f "@]@]"
let string_of_annot e = with_buffer (fun f -> pp_annot f e) 80
let string_of_value e = with_buffer (fun f -> pp_value f e) 80
let string_of_heap_value e = with_buffer (fun f -> pp_heap_value f e) 80
let string_of_term e = with_buffer (fun f -> pp_term f e) 80
let string_of_ty t = with_buffer (fun f -> pp_ty f t) 80
let string_of_program p = with_buffer (fun f -> pp_program f p) 80
* * * *
let tyerr what = raise (TyErr ("H type error: " ^ what))
let rec ftv = function
| TInt -> SSet.empty
| TName a -> SSet.singleton a
| TTup ts ->
List.map fst ts |> List.map ftv |> List.fold_left SSet.union SSet.empty
| TFn { typarams; params } ->
let ftvs = SSet.(List.fold_left union empty (List.map ftv params)) in
SSet.(diff ftvs (of_list typarams))
| TExist (a, t) -> SSet.remove a (ftv t)
let tysub a ta t =
let rec go subs = function
| TInt -> TInt
| TName a -> (
match List.assoc_opt a subs with Some t -> t | None -> TName a)
| TTup ts -> TTup (List.map (fun (t, i) -> (go subs t, i)) ts)
| TFn { typarams; params } ->
if List.mem a typarams then TFn { typarams; params }
else if List.exists (fun a' -> SSet.mem a' (ftv ta)) typarams then
let ftv_ta = ftv ta in
let ftv_body =
SSet.(List.fold_left union empty (List.map ftv params))
in
let used_vars = SSet.union ftv_ta ftv_body in
let typarams', newsubs =
List.map
(fun a' ->
if SSet.mem a' ftv_ta then
let a'' = freshen a' used_vars in
(a'', Some (a', TName a''))
else (a', None))
typarams
|> List.split
in
let newsubs = List.filter_map Fun.id newsubs in
TFn
{
typarams = typarams';
params = List.map (go (newsubs @ subs)) params;
}
else TFn { typarams; params = List.map (go subs) params }
| TExist (a', t) ->
if a = a' then TExist (a', t)
else if SSet.mem a' (ftv ta) then
let a'' = freshen a' (SSet.union (ftv ta) (ftv t)) in
TExist (a'', go ((a', TName a'') :: subs) t)
else TExist (a', go subs t)
in
go [ (a, ta) ] t
let sa = string_of_annot
let sv = string_of_value
let sh = string_of_heap_value
let se = string_of_term
let st = string_of_ty
let sprintf = Printf.sprintf
let ty_wf t tctx =
if not (SSet.subset (ftv t) (SSet.of_list tctx)) then
tyerr (Printf.sprintf "%s is malformed" (string_of_ty t))
let rec tyof_annot tctx vctx (Annot (v, t)) =
let vty = tyof tctx vctx v in
if tyaeq vty t then t
else tyerr (sprintf "%s checks as %s not %s" (sv v) (st vty) (st t))
and tyof tctx vctx = function
| VVar x -> (
match List.assoc_opt x vctx with
| Some t -> t
| None -> tyerr (sprintf "undeclared variable %s" x))
| VInt _ -> TInt
| VTyApp (v, o) -> (
ty_wf o tctx;
match tyof_annot tctx vctx v with
| TFn { typarams = a :: bs; params = ts } ->
TFn { typarams = bs; params = List.map (fun t -> tysub a o t) ts }
| TFn _ ->
tyerr
(sprintf "type application target %s has no type parameters" (sa v))
| _ ->
tyerr (sprintf "type application target %s is not a function" (sa v)))
| VPack (t1, v, TExist (a, t2)) ->
ty_wf t1 tctx;
let v_reifyty = tyof_annot tctx vctx v in
let v_expectty = tysub a t1 t2 in
if tyaeq v_expectty v_reifyty then TExist (a, t2)
else
tyerr
(sprintf "declared package type %s does not match checked type %s"
(st v_expectty) (st v_reifyty))
| VPack _ -> tyerr "package must be an existential type"
and tyof_heap_val vctx = function
| HCode { typarams; params; body } ->
List.iter (fun (_, t) -> ty_wf t typarams) params;
let fn_ty = TFn { typarams; params = List.map snd params } in
let vctx' = params @ vctx in
term_wf typarams vctx' body;
fn_ty
| HTup vs -> TTup (List.map (fun v -> (tyof_annot [] vctx v, Init)) vs)
and term_wf tctx vctx = function
| Let (DeclVal (x, v), e) ->
let vty = tyof_annot tctx vctx v in
term_wf tctx ((x, vty) :: vctx) e
| Let (DeclProj (x, v, i), e) -> (
match tyof_annot tctx vctx v with
| TTup ts -> (
match List.nth_opt ts (i - 1) with
| Some (ti, Init) -> term_wf tctx ((x, ti) :: vctx) e
| Some (_, Uninit) ->
tyerr (sprintf "tuple %s is not initialized at index %d" (sa v) i)
| None ->
tyerr
(sprintf "tuple type of %s cannot be indexed at \"%d\"" (sa v) i)
)
| _ -> tyerr (sprintf "projection target %s is not a tuple" (sa v)))
| Let (DeclOp (x, _, v1, v2), e) -> (
match (tyof_annot tctx vctx v1, tyof_annot tctx vctx v2) with
| TInt, TInt -> term_wf tctx ((x, TInt) :: vctx) e
| _ ->
tyerr
(sprintf "both arguments %s, %s of operation must be ints" (sa v1)
(sa v2)))
| Let (DeclUnpack (a, x, v), e) -> (
match tyof_annot tctx vctx v with
| TExist (a', t') ->
let t = if a = a' then t' else tysub a' (TName a) t' in
term_wf (a :: tctx) ((x, t) :: vctx) e
| _ ->
tyerr
(sprintf
"%s cannot be unpacked because it is not an existential type"
(sa v)))
| Let (DeclTupMalloc (x, ts), e) ->
List.iter (fun t -> ty_wf t tctx) ts;
let tupty = TTup (List.map (fun t -> (t, Uninit)) ts) in
term_wf tctx ((x, tupty) :: vctx) e
| Let (DeclTupInit (x, v1, i, v2), e) -> (
match tyof_annot tctx vctx v1 with
| TTup ts -> (
match List.nth_opt ts (i - 1) with
| Some (t, _) ->
if tyaeq t (tyof_annot tctx vctx v2) then
let fields' =
List.mapi
(fun j (t, iflag) ->
if j = i - 1 then (t, Init) else (t, iflag))
ts
in
term_wf tctx ((x, TTup fields') :: vctx) e
else
tyerr
(sprintf "%s cannot initialize %s.%d, which expects type %s"
(sa v2) (sa v1) i (st t))
| None ->
tyerr (sprintf "%d is out of range of the tuple %s" i (sa v1)))
| _ ->
tyerr
(sprintf "%s cannot be projected because it is not a tuple" (sa v1))
)
| App (fn, vargs) -> (
match tyof_annot tctx vctx fn with
| TFn { typarams = []; params } ->
if List.length params <> List.length vargs then
tyerr
(sprintf "expected %d formal arguments in application to %s"
(List.length params) (sa fn));
List.iter2
(fun arg param_ty ->
let arg_ty = tyof_annot tctx vctx arg in
if not (tyaeq arg_ty param_ty) then
tyerr
(sprintf
"in application to %s, expected argument %s to be of type \
%s (found type %s)"
(sa fn) (sa arg) (st param_ty) (st arg_ty)))
vargs params
| TFn _ as fnty ->
tyerr
(sprintf "application to %s (%s) must have no free type variables"
(sa fn) (st fnty))
| _ -> tyerr (sprintf "application target %s is not a function" (sa fn)))
| If0 (test, then', else') ->
if not (tyaeq (tyof_annot tctx vctx test) TInt) then
tyerr (sprintf "if0 test %s must be an int" (sa test));
term_wf tctx vctx then';
term_wf tctx vctx else'
| Halt (t, v) ->
if not (tyaeq (tyof_annot tctx vctx v) t) then
tyerr (sprintf "halting value %s is not of type %s" (sa v) (st t))
and check_program (Prog (defs, e)) =
let assume_ctx =
List.filter_map
(function
| f, HCode { typarams; params; body = _ } ->
Some (f, TFn { typarams; params = List.map snd params })
| _, HTup _ -> None)
defs
in
if SSet.of_list (List.map fst defs) |> SSet.cardinal <> List.length defs then
tyerr "duplicate letrec definitions in program";
List.iter (fun (_, ty) -> ty_wf ty []) assume_ctx;
List.iter2
(fun (_, code) (f, ty) ->
let infer = tyof_heap_val assume_ctx code in
if not (tyaeq infer ty) then
tyerr
(sprintf "%s expected to have type %s, found %s" f (st ty) (st infer)))
defs assume_ctx;
term_wf [] assume_ctx e
let rec fvs_a (Annot (v, _)) = fvs_v v
and fvs_v =
let open SSet in
let go = function
| VVar x -> singleton x
| VInt _ -> empty
| VPack (_, v, _) -> fvs_a v
| VTyApp (v, _) -> fvs_a v
in
go
and fvs_hv =
let open SSet in
function
| HCode { typarams = _; params; body } ->
let bound = of_list (List.map fst params) in
diff (fvs_t body) bound
| HTup vs -> List.fold_left union empty (List.map fvs_a vs)
and fvs_t =
let open SSet in
let rec go = function
| Let (DeclVal (x, v), e) -> union (fvs_a v) (remove x (go e))
| Let (DeclProj (x, v, _), e) -> union (fvs_a v) (remove x (go e))
| Let (DeclOp (x, _, v1, v2), e) ->
union (fvs_a v1) (fvs_a v2) |> union (remove x (go e))
| Let (DeclUnpack (_, x, v), e) -> union (fvs_a v) (remove x (go e))
| Let (DeclTupMalloc (x, _), e) -> remove x (go e)
| Let (DeclTupInit (x, v1, _, v2), e) ->
union (fvs_a v1) (fvs_a v2) |> union (remove x (go e))
| App (v, vs) -> List.fold_left union empty (List.map fvs_a (v :: vs))
| If0 (v1, t2, t3) -> fvs_a v1 |> union (go t2) |> union (go t3)
| Halt (_, v) -> fvs_a v
in
go
let subst x e =
let rec go_a subs (Annot (v, t)) = Annot (go_v subs v, t)
and go_v subs tm =
match tm with
| VVar y -> (
match List.assoc_opt y subs with Some e -> e | None -> VVar y)
| VInt _ -> tm
| VTyApp (v, t) -> VTyApp (go_a subs v, t)
| VPack (t1, v, t2) -> VPack (t1, go_a subs v, t2)
and go_t subs tm =
let do_let y body create_let =
if x = y then tm
else if SSet.mem y (fvs_v e) then
let y' = freshen y (SSet.union (fvs_v e) (fvs_t body)) in
create_let y' (go_t ((y, VVar y') :: subs) body)
else create_let y (go_t subs body)
in
match tm with
| Let (DeclVal (y, v), body) ->
do_let y body (fun y' body' -> Let (DeclVal (y', go_a subs v), body'))
| Let (DeclProj (y, v, i), body) ->
do_let y body (fun y' body' ->
Let (DeclProj (y', go_a subs v, i), body'))
| Let (DeclOp (y, op, e1, e2), body) ->
do_let y body (fun y' body' ->
Let (DeclOp (y', op, go_a subs e1, go_a subs e2), body'))
| Let (DeclUnpack (a, y, v), body) ->
do_let y body (fun y' body' ->
Let (DeclUnpack (a, y', go_a subs v), body'))
| Let (DeclTupMalloc (y, ts), body) ->
do_let y body (fun y' body' -> Let (DeclTupMalloc (y', ts), body'))
| Let (DeclTupInit (y, v1, i, v2), body) ->
do_let y body (fun y' body' ->
Let (DeclTupInit (y', go_a subs v1, i, go_a subs v2), body'))
| App (v, vs) -> App (go_a subs v, List.map (go_a subs) vs)
| If0 (v, t1, t2) -> If0 (go_a subs v, go_t subs t1, go_t subs t2)
| Halt (t, v) -> Halt (t, go_a subs v)
in
go_t [ (x, e) ]
let subst_v x e v =
match subst x e (App (Annot (v, TName "dummy"), [])) with
| App (Annot (v', TName "dummy"), _) -> v'
| _ -> failwith "bad subst"
let evalerr what = raise (EvalErr ("H eval error: " ^ what))
let unwrap_value = function
| VVar x -> evalerr ("unresolved variable " ^ x)
| v -> v
type rt_heap_val = RTup of value IntMap.t
let print_val = function
| RTup fields ->
let fields =
IntMap.to_seq fields |> List.of_seq
|> List.map (fun (i, v) -> sprintf "%d: %s" i (sv v))
in
sprintf "(%s)" (String.concat ", " fields)
type rt_heap = (string * rt_heap_val) list
let heap_subst x v heap =
List.map
(fun (n, hv) ->
let n' = match v with VVar v when n = x -> v | _ -> n in
let hv' = match hv with RTup vs -> RTup (IntMap.map (subst_v x v) vs) in
(n', hv'))
heap
let print_heap h =
String.concat "; "
(List.map (fun (x, hv) -> sprintf "%s => %s" x (print_val hv)) h)
let heapfind x heap hint =
match List.assoc_opt x heap with
| Some v -> v
| None ->
evalerr
(sprintf "%s not found in heap %s (in %s)" x (print_heap heap) hint)
let step defs heap = function
| Let (DeclVal (x, Annot (v, _)), body) ->
(subst x v body, heap_subst x v heap)
| Let (DeclProj (x, Annot (VVar tup, _), i), body) as dec -> (
let (RTup fields) = heapfind tup heap (se dec) in
match IntMap.find_opt i fields with
| Some vi -> (subst x vi body, heap_subst x vi heap)
| None ->
evalerr
(sprintf "field %d does not exist on %s" i (print_val (RTup fields)))
)
| Let (DeclOp (x, op, Annot (VInt i, _), Annot (VInt j, _)), body) ->
let v = VInt (do_op op i j) in
(subst x v body, heap_subst x v heap)
| Let (DeclUnpack (_, x, Annot (VPack (_, Annot (v, _), _), _)), body) ->
(subst x v body, heap_subst x v heap)
| Let (DeclTupMalloc (x, _), body) ->
let heap' = (x, RTup IntMap.empty) :: heap in
(body, heap')
| Let (DeclTupInit (x, Annot (VVar tup, _), i, Annot (v, _)), body) ->
let (RTup fields) = List.assoc tup heap in
let x_tup = RTup (IntMap.add i v fields) in
let heap' = (x, x_tup) :: heap in
(body, heap')
| App (Annot (VVar f, _), args) -> (
match List.assoc f defs with
| HCode { params; body; _ } ->
let body', heap' =
List.fold_left2
(fun (body, heap) (p, _) (Annot (rawv, _)) ->
(subst p rawv body, heap_subst p rawv heap))
(body, heap) params args
in
(body', heap')
| hv -> evalerr (sprintf "cannot call %s" (sh hv)))
| If0 (Annot (VInt 0, _), t2, _) -> (t2, heap)
| If0 (Annot (VInt _, _), _, t3) -> (t3, heap)
| t -> evalerr (sprintf "term %s is stuck" (se t))
let rec eval defs heap i = function
| Halt (_, Annot (v, _)) -> unwrap_value v
| e ->
if i = 2015 then failwith (sprintf "stuck at %s\n\n" (se e))
else
let e', heap' = step defs heap e in
eval defs heap' (i + 1) e'
let eval_top (Prog (defs, body)) = eval defs [] 0 body
let rec trans_ty = function
| H.TName x -> TName x
| H.TInt -> TInt
| H.TFn { typarams; params } ->
TFn { typarams; params = List.map trans_ty params }
| H.TTup tys -> TTup (List.map (fun t -> (trans_ty t, Init)) tys)
| H.TExist (a, t) -> TExist (a, trans_ty t)
let seq_decls = List.fold_right (fun d e -> Let (d, e))
let rec trans_aval fresh = function
| H.Annot (H.VVar x, t) -> ([], Annot (VVar x, trans_ty t))
| H.Annot (H.VInt i, t) -> ([], Annot (VInt i, trans_ty t))
| H.Annot (H.VTyApp (v, o), t) ->
let d, v' = trans_aval fresh v in
(d, Annot (VTyApp (v', trans_ty o), trans_ty t))
| H.Annot (H.VPack (t, v, t'), t'') ->
let d, v' = trans_aval fresh v in
(d, Annot (VPack (trans_ty t, v', trans_ty t'), trans_ty t''))
| H.Annot (H.VTup us, t) ->
let ts = List.map (fun (H.Annot (_, t)) -> trans_ty t) us in
let dss, vs = List.map (trans_aval fresh) us |> List.split in
let ds1 = List.concat dss in
let y0 = fresh "y" in
let ttup0 = TTup (List.map (fun t -> (t, Uninit)) ts) in
let malloc = DeclTupMalloc (y0, ts) in
let rec goinit i yi_1 ttupi_1 = function
| vi :: vrest ->
let yi = fresh "y" in
let ttupi =
TTup
(List.mapi
(fun j t -> if j + 1 <= i then (t, Init) else (t, Uninit))
ts)
in
let dec_i = DeclTupInit (yi, Annot (VVar yi_1, ttupi_1), i, vi) in
if vrest = [] then ([ dec_i ], yi)
else
let dec_rest, yn = goinit (i + 1) yi ttupi vrest in
(dec_i :: dec_rest, yn)
in
let ds2, yn = goinit 1 y0 ttup0 vs in
let ds = ds1 @ [ malloc ] @ ds2 in
(ds, Annot (VVar yn, trans_ty t))
and trans_heap fresh = function
| H.Code { typarams; params; body } ->
let params' = List.map (fun (p, t) -> (p, trans_ty t)) params in
let body' = trans_term fresh body in
HCode { typarams; params = params'; body = body' }
and trans_decl fresh = function
| H.DeclVal (x, v) ->
let d, v' = trans_aval fresh v in
d @ [ DeclVal (x, v') ]
| H.DeclProj (x, v, i) ->
let d, v' = trans_aval fresh v in
d @ [ DeclProj (x, v', i) ]
| H.DeclOp (x, op, v1, v2) ->
let d1, v1' = trans_aval fresh v1 in
let d2, v2' = trans_aval fresh v2 in
d1 @ d2 @ [ DeclOp (x, op, v1', v2') ]
| H.DeclUnpack (a, x, v) ->
let d, v' = trans_aval fresh v in
d @ [ DeclUnpack (a, x, v') ]
and trans_term fresh = function
| H.Let (d, e) -> seq_decls (trans_decl fresh d) (trans_term fresh e)
| H.App (v, vs) ->
let d, v' = trans_aval fresh v in
let ds, vs' = List.map (trans_aval fresh) vs |> List.split in
seq_decls (List.concat (d :: ds)) (App (v', vs'))
| H.If0 (v, t1, t2) ->
let d, v' = trans_aval fresh v in
seq_decls d (If0 (v', trans_term fresh t1, trans_term fresh t2))
| H.Halt (t, v) ->
let d, v' = trans_aval fresh v in
seq_decls d (Halt (trans_ty t, v'))
let all_names =
let open H in
let open SSet in
let rec goa = function Annot (v, t) -> union (gov v) (goty t)
and gov = function
| VVar x -> singleton x
| VInt _ -> empty
| VTup ts -> List.fold_left union empty (List.map goa ts)
| VTyApp (v, t) -> union (goa v) (goty t)
| VPack (t1, v, t2) -> union (goty t1) (goty t2) |> union (goa v)
and goh = function
| Code { typarams; params; body } ->
of_list typarams
|> union (of_list (List.map fst params))
|> union (got body)
and goprog = function
| Prog (defs, e) ->
let defs_names = List.map (fun (f, heap) -> add f (goh heap)) defs in
List.fold_left union empty defs_names |> union (got e)
and god = function
| DeclVal (x, v) | DeclProj (x, v, _) -> add x (goa v)
| DeclOp (x, _, v1, v2) -> union (goa v1) (goa v2) |> add x
| DeclUnpack (a, x, v) -> goa v |> add a |> add x
and got = function
| Let (d, t) -> union (god d) (got t)
| App (v, vs) -> List.fold_left union (goa v) (List.map goa vs)
| If0 (v, t1, t2) -> union (got t1) (got t2) |> union (goa v)
| Halt (t, v) -> union (goty t) (goa v)
and goty = function
| TInt -> empty
| TName x -> singleton x
| TFn { typarams; params } ->
union (of_list typarams)
(List.fold_left union empty (List.map goty params))
| TTup ts -> List.fold_left union empty (List.map goty ts)
| TExist (a, t) -> add a (goty t)
in
goprog
let trans_top (H.Prog (defs, e) as u) =
let fresh = fresh_generator (all_names u) in
let defs' = List.map (fun (x, h) -> (x, trans_heap fresh h)) defs in
let e' = trans_term fresh e in
Prog (defs', e')
|
22bd672e6dc808ef17f27aa2f48e07a5303a152ab125fe3ab35fbbb58f70179d | ocaml-obuild/obuild | p2.ml | open Uri
open Printf
let () =
let u = Uri.make ~scheme:"http" ~host:"foo!.com" () in
printf "%s\n" (Uri.to_string u)
| null | https://raw.githubusercontent.com/ocaml-obuild/obuild/28252e8cee836448e85bfbc9e09a44e7674dae39/tests/full/dep-uri/p2.ml | ocaml | open Uri
open Printf
let () =
let u = Uri.make ~scheme:"http" ~host:"foo!.com" () in
printf "%s\n" (Uri.to_string u)
| |
67fa82c0ca0a00076f500d8e6f953b60f8932f7c900b2fbf6528b2fc972525ba | exercism/common-lisp | exercises.lisp | (in-package :test-exercises)
(defun slurp-exercise-config (dir)
(let ((config-file (merge-pathnames ".meta/config.json" dir)))
(with-open-file (input config-file :direction :input :if-does-not-exist :error)
(yason:parse input :object-key-fn #'keywordize :object-as :alist))))
(defun gather-exercise-data (dir)
(destructuring-bind (type slug)
(mapcar #'keywordize (last (pathname-directory dir) 2))
(let ((config (slurp-exercise-config dir)))
(pairlis '(:directory :type :slug :files)
(list dir type slug (aget :files config))))))
(defun load-exercise-file (exercise file)
(let ((*default-pathname-defaults* (aget :directory exercise))
(*load-verbose* t))
(handler-bind ((style-warning #'muffle-warning))
(load file))))
(defun missing-exercise-package-error-report (condition stream)
(format stream
"Could not find package ~S (perhaps exercise slug and code do not match?)"
(package-error-package condition)))
(define-condition missing-exercise-package-error (package-error) ()
(:documentation "Error to signal if exercise package (or exercise test package) cannot be found")
(:report missing-exercise-package-error-report))
(defun find-exercise-package (exercise &key (test nil))
(let* ((slug (symbol-name (aget :slug exercise)))
(package-name (string-upcase (format nil "~A~@[-TEST~]" slug test)))
(package (find-package package-name)))
(if (not package)
(error 'missing-exercise-package-error :package package-name)
package)))
| null | https://raw.githubusercontent.com/exercism/common-lisp/0e10dc22d5599c48272c811869bf2d5a674df266/src/test-exercises/exercises.lisp | lisp | (in-package :test-exercises)
(defun slurp-exercise-config (dir)
(let ((config-file (merge-pathnames ".meta/config.json" dir)))
(with-open-file (input config-file :direction :input :if-does-not-exist :error)
(yason:parse input :object-key-fn #'keywordize :object-as :alist))))
(defun gather-exercise-data (dir)
(destructuring-bind (type slug)
(mapcar #'keywordize (last (pathname-directory dir) 2))
(let ((config (slurp-exercise-config dir)))
(pairlis '(:directory :type :slug :files)
(list dir type slug (aget :files config))))))
(defun load-exercise-file (exercise file)
(let ((*default-pathname-defaults* (aget :directory exercise))
(*load-verbose* t))
(handler-bind ((style-warning #'muffle-warning))
(load file))))
(defun missing-exercise-package-error-report (condition stream)
(format stream
"Could not find package ~S (perhaps exercise slug and code do not match?)"
(package-error-package condition)))
(define-condition missing-exercise-package-error (package-error) ()
(:documentation "Error to signal if exercise package (or exercise test package) cannot be found")
(:report missing-exercise-package-error-report))
(defun find-exercise-package (exercise &key (test nil))
(let* ((slug (symbol-name (aget :slug exercise)))
(package-name (string-upcase (format nil "~A~@[-TEST~]" slug test)))
(package (find-package package-name)))
(if (not package)
(error 'missing-exercise-package-error :package package-name)
package)))
| |
755e96ebda27eb1f3521809f039d40b7d17c844ccaa0b84c24a52b9b888fb435 | janestreet/universe | address_config.ml | module Stable = struct
open! Core_kernel.Core_kernel_stable
module V2 = struct
type t =
{ max_open_connections : int
; cleanup_idle_connection_after : Time_ns.Span.V2.t
; max_connections_per_address : int
; max_connection_reuse : int
; close_idle_connections_when_at_limit : bool
}
[@@deriving bin_io, sexp]
let%expect_test _ =
print_endline [%bin_digest: t];
[%expect {| c8122cfd57d06e0d9201489d1d070af5 |}]
;;
end
module V1 = struct
type t =
{ max_open_connections : int
; cleanup_idle_connection_after : Time_ns.Span.V2.t
; max_connections_per_address : int
; max_connection_reuse : int
}
[@@deriving
bin_io
, sexp
, stable_record ~version:V2.t ~add:[ close_idle_connections_when_at_limit ]]
let of_v2 = of_V2_t
let to_v2 = to_V2_t ~close_idle_connections_when_at_limit:false
let%expect_test _ =
print_endline [%bin_digest: t];
[%expect {| f6909d04e51fd189259fe7dbe513e5a5 |}]
;;
end
end
open! Core_kernel
open! Async_kernel
open! Import
type t = Stable.V2.t =
{ max_open_connections : int
; cleanup_idle_connection_after : Time_ns.Span.t
; max_connections_per_address : int
; max_connection_reuse : int
; close_idle_connections_when_at_limit : bool
}
[@@deriving compare, fields, sexp_of]
let create = Fields.create
let default =
{ max_open_connections = 500
; cleanup_idle_connection_after = Time_ns.Span.of_sec 5.
; max_connections_per_address = 10
; max_connection_reuse = 10
; close_idle_connections_when_at_limit = false
}
;;
let to_cache_config t =
Config.create
~max_resources:t.max_open_connections
~idle_cleanup_after:t.cleanup_idle_connection_after
~max_resources_per_id:t.max_connections_per_address
~max_resource_reuse:t.max_connection_reuse
~close_idle_resources_when_at_limit:t.close_idle_connections_when_at_limit
;;
let of_cache_config (cache_config : Config.t) =
create
~max_open_connections:cache_config.max_resources
~cleanup_idle_connection_after:cache_config.idle_cleanup_after
~max_connections_per_address:cache_config.max_resources_per_id
~max_connection_reuse:cache_config.max_resource_reuse
~close_idle_connections_when_at_limit:cache_config.close_idle_resources_when_at_limit
;;
| null | https://raw.githubusercontent.com/janestreet/universe/b6cb56fdae83f5d55f9c809f1c2a2b50ea213126/resource_cache/src/address_config.ml | ocaml | module Stable = struct
open! Core_kernel.Core_kernel_stable
module V2 = struct
type t =
{ max_open_connections : int
; cleanup_idle_connection_after : Time_ns.Span.V2.t
; max_connections_per_address : int
; max_connection_reuse : int
; close_idle_connections_when_at_limit : bool
}
[@@deriving bin_io, sexp]
let%expect_test _ =
print_endline [%bin_digest: t];
[%expect {| c8122cfd57d06e0d9201489d1d070af5 |}]
;;
end
module V1 = struct
type t =
{ max_open_connections : int
; cleanup_idle_connection_after : Time_ns.Span.V2.t
; max_connections_per_address : int
; max_connection_reuse : int
}
[@@deriving
bin_io
, sexp
, stable_record ~version:V2.t ~add:[ close_idle_connections_when_at_limit ]]
let of_v2 = of_V2_t
let to_v2 = to_V2_t ~close_idle_connections_when_at_limit:false
let%expect_test _ =
print_endline [%bin_digest: t];
[%expect {| f6909d04e51fd189259fe7dbe513e5a5 |}]
;;
end
end
open! Core_kernel
open! Async_kernel
open! Import
type t = Stable.V2.t =
{ max_open_connections : int
; cleanup_idle_connection_after : Time_ns.Span.t
; max_connections_per_address : int
; max_connection_reuse : int
; close_idle_connections_when_at_limit : bool
}
[@@deriving compare, fields, sexp_of]
let create = Fields.create
let default =
{ max_open_connections = 500
; cleanup_idle_connection_after = Time_ns.Span.of_sec 5.
; max_connections_per_address = 10
; max_connection_reuse = 10
; close_idle_connections_when_at_limit = false
}
;;
let to_cache_config t =
Config.create
~max_resources:t.max_open_connections
~idle_cleanup_after:t.cleanup_idle_connection_after
~max_resources_per_id:t.max_connections_per_address
~max_resource_reuse:t.max_connection_reuse
~close_idle_resources_when_at_limit:t.close_idle_connections_when_at_limit
;;
let of_cache_config (cache_config : Config.t) =
create
~max_open_connections:cache_config.max_resources
~cleanup_idle_connection_after:cache_config.idle_cleanup_after
~max_connections_per_address:cache_config.max_resources_per_id
~max_connection_reuse:cache_config.max_resource_reuse
~close_idle_connections_when_at_limit:cache_config.close_idle_resources_when_at_limit
;;
| |
3ad71341c490bab7aa280d76a9332de84950073d4f9eda9f647d53c8c39b394e | quicklisp/quicklisp-client | fetch-gzipped.lisp | ;;;; fetch-gzipped.lisp
(in-package #:quicklisp-client)
(defun gzipped-url (url)
(check-type url string)
(concatenate 'string url ".gz"))
(defun fetch-gzipped-version (url file &key quietly)
(let ((gzipped (gzipped-url url))
(gzipped-temp (merge-pathnames "gzipped.tmp" file)))
(fetch gzipped gzipped-temp :quietly quietly)
(gunzip gzipped-temp file)
(delete-file-if-exists gzipped-temp)
(probe-file file)))
(defun url-not-suitable-error-p (condition)
(<= 400 (unexpected-http-status-code condition) 499))
(defun maybe-fetch-gzipped (url file &key quietly)
(handler-case
(fetch-gzipped-version url file :quietly quietly)
(unexpected-http-status (condition)
(cond ((url-not-suitable-error-p condition)
(fetch url file :quietly quietly)
(probe-file file))
(t
(error condition))))))
| null | https://raw.githubusercontent.com/quicklisp/quicklisp-client/8b63e00b3a2b3f96e24c113d7601dd03a128ce94/quicklisp/fetch-gzipped.lisp | lisp | fetch-gzipped.lisp |
(in-package #:quicklisp-client)
(defun gzipped-url (url)
(check-type url string)
(concatenate 'string url ".gz"))
(defun fetch-gzipped-version (url file &key quietly)
(let ((gzipped (gzipped-url url))
(gzipped-temp (merge-pathnames "gzipped.tmp" file)))
(fetch gzipped gzipped-temp :quietly quietly)
(gunzip gzipped-temp file)
(delete-file-if-exists gzipped-temp)
(probe-file file)))
(defun url-not-suitable-error-p (condition)
(<= 400 (unexpected-http-status-code condition) 499))
(defun maybe-fetch-gzipped (url file &key quietly)
(handler-case
(fetch-gzipped-version url file :quietly quietly)
(unexpected-http-status (condition)
(cond ((url-not-suitable-error-p condition)
(fetch url file :quietly quietly)
(probe-file file))
(t
(error condition))))))
|
8e2ee47b9ae7cd7ffe120d8aa09bb7bec52d681491f042cf45e92d57c670581b | arttuka/reagent-material-ui | tire_repair_outlined.cljs | (ns reagent-mui.icons.tire-repair-outlined
"Imports @mui/icons-material/TireRepairOutlined as a Reagent component."
(:require-macros [reagent-mui.util :refer [create-svg-icon e]])
(:require [react :as react]
["@mui/material/SvgIcon" :as SvgIcon]
[reagent-mui.util]))
(def tire-repair-outlined (create-svg-icon (e "path" #js {"d" "M19 8c-.55 0-1-.45-1-1 0-.28.11-.53.29-.71.4-.4 2.46-1.04 2.46-1.04s-.64 2.06-1.04 2.46c-.18.18-.43.29-.71.29zm1 5v5c0 1.65-1.35 3-3 3s-3-1.35-3-3v-2c0-.55-.45-1-1-1s-1 .45-1 1v3c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V5c0-1.1.9-2 2-2h6c1.1 0 2 .9 2 2v8.17c.31-.11.65-.17 1-.17 1.65 0 3 1.35 3 3v2c0 .55.45 1 1 1s1-.45 1-1v-5h-1v-1.42c-1.77-.77-3-2.53-3-4.58 0-2.76 2.24-5 5-5s5 2.24 5 5c0 2.05-1.23 3.81-3 4.58V13h-1zm2-6c0-1.66-1.34-3-3-3s-3 1.34-3 3 1.34 3 3 3 3-1.34 3-3zM10 7 8 9V6.17L9.17 5H4.83L6 6.17V9L4 7v2.17l2 2V14l-2-2v2.17l2 2V19l-2-2v2h6v-2l-2 2v-2.83l2-2V12l-2 2v-2.83l2-2V7z"})
"TireRepairOutlined"))
| null | https://raw.githubusercontent.com/arttuka/reagent-material-ui/c7cd0d7c661ab9df5b0aed0213a6653a9a3f28ea/src/icons/reagent_mui/icons/tire_repair_outlined.cljs | clojure | (ns reagent-mui.icons.tire-repair-outlined
"Imports @mui/icons-material/TireRepairOutlined as a Reagent component."
(:require-macros [reagent-mui.util :refer [create-svg-icon e]])
(:require [react :as react]
["@mui/material/SvgIcon" :as SvgIcon]
[reagent-mui.util]))
(def tire-repair-outlined (create-svg-icon (e "path" #js {"d" "M19 8c-.55 0-1-.45-1-1 0-.28.11-.53.29-.71.4-.4 2.46-1.04 2.46-1.04s-.64 2.06-1.04 2.46c-.18.18-.43.29-.71.29zm1 5v5c0 1.65-1.35 3-3 3s-3-1.35-3-3v-2c0-.55-.45-1-1-1s-1 .45-1 1v3c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V5c0-1.1.9-2 2-2h6c1.1 0 2 .9 2 2v8.17c.31-.11.65-.17 1-.17 1.65 0 3 1.35 3 3v2c0 .55.45 1 1 1s1-.45 1-1v-5h-1v-1.42c-1.77-.77-3-2.53-3-4.58 0-2.76 2.24-5 5-5s5 2.24 5 5c0 2.05-1.23 3.81-3 4.58V13h-1zm2-6c0-1.66-1.34-3-3-3s-3 1.34-3 3 1.34 3 3 3 3-1.34 3-3zM10 7 8 9V6.17L9.17 5H4.83L6 6.17V9L4 7v2.17l2 2V14l-2-2v2.17l2 2V19l-2-2v2h6v-2l-2 2v-2.83l2-2V12l-2 2v-2.83l2-2V7z"})
"TireRepairOutlined"))
| |
3a78a600ffec3817c13aaf7fe65b55e50af02e057d4f6a48fb0333798dcc9e2b | gja/pwa-clojure | main.clj | (ns pwa-clojure.main
(:gen-class)
(:require [ring.adapter.jetty :as jetty]
[pwa-clojure.app :as app]))
(defn -main []
(jetty/run-jetty app/app {:port 3000}))
| null | https://raw.githubusercontent.com/gja/pwa-clojure/a06450747c6ead439d1a74653a34afe415d8ef02/src-clj/pwa_clojure/main.clj | clojure | (ns pwa-clojure.main
(:gen-class)
(:require [ring.adapter.jetty :as jetty]
[pwa-clojure.app :as app]))
(defn -main []
(jetty/run-jetty app/app {:port 3000}))
| |
683bdb5d2db2363cc19cf8e4a7ac682888aa10e9816affb3dc1cfdcc1b3db036 | sicmutils/sicmutils | curvature.cljc | #_"SPDX-License-Identifier: GPL-3.0"
(ns sicmutils.calculus.curvature
(:require [sicmutils.calculus.basis :as b]
[sicmutils.calculus.form-field :as ff]
[sicmutils.calculus.indexed :as ci]
[sicmutils.calculus.manifold :as m]
[sicmutils.calculus.vector-field :as vf]
[sicmutils.generic :as g]
[sicmutils.operator :as o]
[sicmutils.structure :as s]))
;; Riemann curvature "tensor" is pretty easy
Hawking and equation 2.18 , page 35 .
(defn Riemann-curvature [nabla]
(fn [u v]
(g/- (o/commutator (nabla u) (nabla v))
(nabla (o/commutator u v)))))
The traditional Riemann tensor R^i_jkl :
(defn Riemann [nabla]
(letfn [(Riemann-tensor [w x u v]
(w (((Riemann-curvature nabla) u v) x)))]
(ci/with-argument-types
Riemann-tensor
[::ff/oneform-field
::vf/vector-field
::vf/vector-field
::vf/vector-field])))
(defn Ricci [nabla basis]
(letfn [(Ricci-tensor [u v]
(b/contract
(fn [ei wi]
((Riemann nabla) wi u ei v))
basis))]
(ci/with-argument-types
Ricci-tensor
[::vf/vector-field
::vf/vector-field])))
Hawking and page 34 .
(defn torsion-vector [nabla]
(fn [X Y]
(g/+ ((nabla X) Y)
(g/* -1 ((nabla Y) X))
(g/* -1 (o/commutator X Y)))))
;; The torsion tensor T^i_jk
(defn torsion [nabla]
(letfn [(the-torsion [w x y]
(w ((torsion-vector nabla) x y)))]
(ci/with-argument-types
the-torsion
[::ff/oneform-field
::vf/vector-field
::vf/vector-field])))
Components of the curvature tensor R^i_{jkl }
(defn curvature-components [nabla coord-sys]
(let [d:dxs (vf/coordinate-system->vector-basis coord-sys)
dxs (ff/coordinate-system->oneform-basis coord-sys)
point ((m/point coord-sys) (s/up 'x 'y 'z))]
((s/mapr
(fn [dx]
(s/mapr
(fn [d:dx]
(s/mapr
(fn [d:dy]
(s/mapr
(fn [d:dz]
(dx (((Riemann-curvature nabla) d:dy d:dz)
d:dx)))
d:dxs))
d:dxs))
d:dxs))
dxs)
point)))
| null | https://raw.githubusercontent.com/sicmutils/sicmutils/ce763b31153eb9253f165bd5b4e4e6a6087bf730/src/sicmutils/calculus/curvature.cljc | clojure | Riemann curvature "tensor" is pretty easy
The torsion tensor T^i_jk | #_"SPDX-License-Identifier: GPL-3.0"
(ns sicmutils.calculus.curvature
(:require [sicmutils.calculus.basis :as b]
[sicmutils.calculus.form-field :as ff]
[sicmutils.calculus.indexed :as ci]
[sicmutils.calculus.manifold :as m]
[sicmutils.calculus.vector-field :as vf]
[sicmutils.generic :as g]
[sicmutils.operator :as o]
[sicmutils.structure :as s]))
Hawking and equation 2.18 , page 35 .
(defn Riemann-curvature [nabla]
(fn [u v]
(g/- (o/commutator (nabla u) (nabla v))
(nabla (o/commutator u v)))))
The traditional Riemann tensor R^i_jkl :
(defn Riemann [nabla]
(letfn [(Riemann-tensor [w x u v]
(w (((Riemann-curvature nabla) u v) x)))]
(ci/with-argument-types
Riemann-tensor
[::ff/oneform-field
::vf/vector-field
::vf/vector-field
::vf/vector-field])))
(defn Ricci [nabla basis]
(letfn [(Ricci-tensor [u v]
(b/contract
(fn [ei wi]
((Riemann nabla) wi u ei v))
basis))]
(ci/with-argument-types
Ricci-tensor
[::vf/vector-field
::vf/vector-field])))
Hawking and page 34 .
(defn torsion-vector [nabla]
(fn [X Y]
(g/+ ((nabla X) Y)
(g/* -1 ((nabla Y) X))
(g/* -1 (o/commutator X Y)))))
(defn torsion [nabla]
(letfn [(the-torsion [w x y]
(w ((torsion-vector nabla) x y)))]
(ci/with-argument-types
the-torsion
[::ff/oneform-field
::vf/vector-field
::vf/vector-field])))
Components of the curvature tensor R^i_{jkl }
(defn curvature-components [nabla coord-sys]
(let [d:dxs (vf/coordinate-system->vector-basis coord-sys)
dxs (ff/coordinate-system->oneform-basis coord-sys)
point ((m/point coord-sys) (s/up 'x 'y 'z))]
((s/mapr
(fn [dx]
(s/mapr
(fn [d:dx]
(s/mapr
(fn [d:dy]
(s/mapr
(fn [d:dz]
(dx (((Riemann-curvature nabla) d:dy d:dz)
d:dx)))
d:dxs))
d:dxs))
d:dxs))
dxs)
point)))
|
00b733dc6a89e6e3b5237c491272382e878121c2f2eba59ace81f72423a57cf2 | david-vanderson/warp | warp.rkt | #lang racket/base
(require "defs.rkt"
"utils.rkt"
racket/class
mode-lambda
"draw-utils.rkt")
(provide (all-defined-out))
(define (dmg-warp tool)
(cond
((null? (tool-dmgs tool))
(list (chadd (dmg (next-id) "offline" DMG_SIZE 0 DMG_FIX?) (ob-id tool))))
(else
#f)))
;; client/server
(define (warp-speed w)
(car (tool-val w)))
(define (warp-threshold w)
(cadr (tool-val w)))
(define (warp-energy w)
(caddr (tool-val w)))
(define (warp-charging? space ship)
(define w (ship-tool ship 'warp))
(and w
((warp-energy w) . < . (warp-threshold w))
((tool-count space w ship) . > . 0)))
(define (warping? ship)
(define w (ship-tool ship 'warp))
(and w
((warp-energy w) . = . (warp-threshold w))))
(define (cancel-warp! space ship)
(define w (ship-tool ship 'warp))
(when w
(set-tool-val! w (list (warp-speed w)
(warp-threshold w)
0.0))
(for ((p (in-list (ship-players space ship))))
(set-player-commands! p (remove* '(warp) (player-commands p))))))
; return list of buttons
(define (draw-warp-ui! csd center scale space ship t stack send-commands)
(define buttons '())
(define spr '())
(define vals (tool-val t))
(define totalwarp (cadr vals))
(define warp (caddr vals))
(define w 160.0)
(define h 40.0)
(define x (+ (left) 8.0 (/ w 2.0)))
(define y (- (bottom) 124.0))
(define z (clamp 0.0 1.0 (/ warp totalwarp)))
(define p (car stack))
(define pid (ob-id p))
(define cmdlevel (player-cmdlevel p))
; fill
(append! spr (sprite x y (sprite-idx csd '100x100) #:layer LAYER_UI
#:mx (/ (* w z) 100.0)
#:my (/ h 100.0)
#:r 200))
; we always want the button on the screen so that the mouse cursor looks right
; only have the button-f function do something when allowed
; always have the holdbutton-frelease function because holding? can be overwritten
; - player presses and holds the shortcut key
; - player clicks the button with the mouse (overwrites holding?)
; this means you can get multiple holdbutton-frelease calls
(define b (holdbutton 'outline #\s #f x y w h "Charge Warp [s]"
(lambda (x y) (void))
(lambda ()
(send-commands (command pid cmdlevel (tool-name t) #f)))))
(cond
((warping? ship)
(set-button-label! b "Stop Warp [s]")
(set-button-f! b (lambda (x y)
(send-commands (command pid cmdlevel (tool-name t) 'stop)))))
(else
(when (player-using-tool? p t)
(set-button-label! b "Charging Warp [s]"))
(set-button-f! b (lambda (x y)
(send-commands (command pid cmdlevel (tool-name t) #t))))))
(when (or (not (ship-flying? ship))
(and (warping? ship) (not (tool-while-warping? t))))
(set-button-draw! b 'disabled))
(append! buttons b)
(button-set-dmg! t b)
(values buttons spr))
| null | https://raw.githubusercontent.com/david-vanderson/warp/cdc1d0bd942780fb5360dc6a34a2a06cf9518408/warp.rkt | racket | client/server
return list of buttons
fill
we always want the button on the screen so that the mouse cursor looks right
only have the button-f function do something when allowed
always have the holdbutton-frelease function because holding? can be overwritten
- player presses and holds the shortcut key
- player clicks the button with the mouse (overwrites holding?)
this means you can get multiple holdbutton-frelease calls | #lang racket/base
(require "defs.rkt"
"utils.rkt"
racket/class
mode-lambda
"draw-utils.rkt")
(provide (all-defined-out))
(define (dmg-warp tool)
(cond
((null? (tool-dmgs tool))
(list (chadd (dmg (next-id) "offline" DMG_SIZE 0 DMG_FIX?) (ob-id tool))))
(else
#f)))
(define (warp-speed w)
(car (tool-val w)))
(define (warp-threshold w)
(cadr (tool-val w)))
(define (warp-energy w)
(caddr (tool-val w)))
(define (warp-charging? space ship)
(define w (ship-tool ship 'warp))
(and w
((warp-energy w) . < . (warp-threshold w))
((tool-count space w ship) . > . 0)))
(define (warping? ship)
(define w (ship-tool ship 'warp))
(and w
((warp-energy w) . = . (warp-threshold w))))
(define (cancel-warp! space ship)
(define w (ship-tool ship 'warp))
(when w
(set-tool-val! w (list (warp-speed w)
(warp-threshold w)
0.0))
(for ((p (in-list (ship-players space ship))))
(set-player-commands! p (remove* '(warp) (player-commands p))))))
(define (draw-warp-ui! csd center scale space ship t stack send-commands)
(define buttons '())
(define spr '())
(define vals (tool-val t))
(define totalwarp (cadr vals))
(define warp (caddr vals))
(define w 160.0)
(define h 40.0)
(define x (+ (left) 8.0 (/ w 2.0)))
(define y (- (bottom) 124.0))
(define z (clamp 0.0 1.0 (/ warp totalwarp)))
(define p (car stack))
(define pid (ob-id p))
(define cmdlevel (player-cmdlevel p))
(append! spr (sprite x y (sprite-idx csd '100x100) #:layer LAYER_UI
#:mx (/ (* w z) 100.0)
#:my (/ h 100.0)
#:r 200))
(define b (holdbutton 'outline #\s #f x y w h "Charge Warp [s]"
(lambda (x y) (void))
(lambda ()
(send-commands (command pid cmdlevel (tool-name t) #f)))))
(cond
((warping? ship)
(set-button-label! b "Stop Warp [s]")
(set-button-f! b (lambda (x y)
(send-commands (command pid cmdlevel (tool-name t) 'stop)))))
(else
(when (player-using-tool? p t)
(set-button-label! b "Charging Warp [s]"))
(set-button-f! b (lambda (x y)
(send-commands (command pid cmdlevel (tool-name t) #t))))))
(when (or (not (ship-flying? ship))
(and (warping? ship) (not (tool-while-warping? t))))
(set-button-draw! b 'disabled))
(append! buttons b)
(button-set-dmg! t b)
(values buttons spr))
|
3da1605490c3d67ef7907dd200f7b6e1f58c86fb0a0e89dfdd1ead6e9df0b047 | letmaik/monadiccp | Util.hs |
- Monadic Constraint Programming
- /~toms/MCP/
-
- Monadic Constraint Programming
- /~toms/MCP/
- Pieter Wuille
-}
# LANGUAGE StandaloneDeriving #
module Data.Expr.Util (
Expr(), BoolExpr(), ColExpr(),
transform, colTransform, boolTransform,
transformEx, colTransformEx, boolTransformEx,
property, colProperty, boolProperty,
propertyEx, colPropertyEx, boolPropertyEx,
collapse, colCollapse, boolCollapse,
simplify, colSimplify, boolSimplify,
WalkPhase(..), WalkResult(..), walk, colWalk, boolWalk,
) where
import Data.Expr.Data
-------------------------
-- | Helper functions |--
-------------------------
relCheck :: Integer -> ExprRel -> Integer -> Bool
relCheck a EREqual b = a==b
relCheck a ERDiff b = a/=b
relCheck a ERLess b = a<b
-------------------------------------------------------------------------
| Transform expressions over one type to expressions over another | --
-------------------------------------------------------------------------
transform :: (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f) => (a->b,c->d,e->f,b->a,d->c,f->e) -> Expr a c e -> Expr b d f
transform (f,fc,fb,fi,fic,fib) = transformEx (Term . f, ColTerm . fc, BoolTerm . fb, Term . fi, ColTerm . fic, BoolTerm . fib)
transformEx :: (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f) => ((a -> Expr b d f),(c -> ColExpr b d f),(e -> BoolExpr b d f),(b -> Expr a c e),(d -> ColExpr a c e),(f -> BoolExpr a c e)) -> Expr a c e -> Expr b d f
transformEx (f,_,_,_,_,_) (Term v) = f v
transformEx f (Const i) = Const i
transformEx f (ExprHole i) = ExprHole i
transformEx f (Plus a b) = simplify $ Plus (transformEx f a) (transformEx f b)
transformEx f (Minus a b) = simplify $ Minus (transformEx f a) (transformEx f b)
transformEx f (Mult a b) = simplify $ Mult (transformEx f a) (transformEx f b)
transformEx f (Div a b) = simplify $ Div (transformEx f a) (transformEx f b)
transformEx f (Mod a b) = simplify $ Mod (transformEx f a) (transformEx f b)
transformEx f (Abs a) = simplify $ Abs (transformEx f a)
transformEx f (At c a) = simplify $ At (colTransformEx f c) (transformEx f a)
transformEx f (ColSize c) = simplify $ ColSize $ colTransformEx f c
transformEx f (Channel a) = simplify $ Channel $ boolTransformEx f a
transformEx f (Cond c t e) = simplify $ Cond (boolTransformEx f c) (transformEx f t) (transformEx f e)
transformEx t@(f,fc,fb,fi,fic,fib) (Fold m i c) = simplify $ Fold (\a b -> transformEx t (m (transformEx (fi,fic,fib,f,fc,fb) a) (transformEx (fi,fic,fib,f,fc,fb) b))) (transformEx t i) (colTransformEx t c)
colTransform :: (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f) => (a->b,c->d,e->f,b->a,d->c,f->e) -> ColExpr a c e -> ColExpr b d f
colTransform (f,fc,fb,fi,fic,fib) = colTransformEx (Term . f, ColTerm . fc, BoolTerm . fb, Term . fi, ColTerm . fic, BoolTerm . fib)
colTransformEx :: (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f) => ((a -> Expr b d f),(c -> ColExpr b d f),(e -> BoolExpr b d f),(b -> Expr a c e),(d -> ColExpr a c e),f -> BoolExpr a c e) -> ColExpr a c e -> ColExpr b d f
colTransformEx (_,f,_,_,_,_) (ColTerm c) = f c
colTransformEx f (ColList l) = colSimplify $ ColList $ map (transformEx f) l
colTransformEx t@(f,fc,fb,fi,fic,fib) (ColMap m c) = colSimplify $ ColMap (\a -> transformEx t (m (transformEx (fi,fic,fib,f,fc,fb) a))) (colTransformEx t c)
colTransformEx t@(f,fc,fb,fi,fic,fib) (ColSlice p l c) = colSimplify $ ColSlice (\a -> transformEx t (p (transformEx (fi,fic,fib,f,fc,fb) a))) (transformEx t l) (colTransformEx t c)
colTransformEx f (ColCat a b) = colSimplify $ ColCat (colTransformEx f a) (colTransformEx f b)
colTransformEx f (ColRange a b) = colSimplify $ ColRange (transformEx f a) (transformEx f b)
boolTransform :: (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f) => (a->b,c->d,e->f,b->a,d->c,f->e) -> BoolExpr a c e -> BoolExpr b d f
boolTransform (f,fc,fb,fi,fic,fib) = boolTransformEx (Term . f, ColTerm . fc, BoolTerm . fb, Term . fi, ColTerm . fic, BoolTerm . fib)
boolTransformEx :: (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f) => ((a -> Expr b d f),(c -> ColExpr b d f),(e -> BoolExpr b d f),(b -> Expr a c e),(d -> ColExpr a c e),f -> BoolExpr a c e) -> BoolExpr a c e -> BoolExpr b d f
boolTransformEx (_,_,f,_,_,_) (BoolTerm v) = f v
boolTransformEx f (BoolConst c) = BoolConst c
boolTransformEx f (BoolAnd a b) = boolSimplify $ BoolAnd (boolTransformEx f a) (boolTransformEx f b)
boolTransformEx f (BoolOr a b) = boolSimplify $ BoolOr (boolTransformEx f a) (boolTransformEx f b)
boolTransformEx f (BoolEqual a b) = boolSimplify $ BoolEqual (boolTransformEx f a) (boolTransformEx f b)
boolTransformEx f (BoolNot a) = boolSimplify $ BoolNot (boolTransformEx f a)
boolTransformEx f (Rel a r b) = boolSimplify $ Rel (transformEx f a) r (transformEx f b)
boolTransformEx t@(f,fc,fb,fi,fic,fib) (BoolAll m c) = boolSimplify $ BoolAll (\a -> boolTransformEx t (m (transformEx (fi,fic,fib,f,fc,fb) a))) (colTransformEx t c)
boolTransformEx t@(f,fc,fb,fi,fic,fib) (BoolAny m c) = boolSimplify $ BoolAny (\a -> boolTransformEx t (m (transformEx (fi,fic,fib,f,fc,fb) a))) (colTransformEx t c)
boolTransformEx f (ColEqual a b) = boolSimplify $ ColEqual (colTransformEx f a) (colTransformEx f b)
boolTransformEx f (Sorted b c) = boolSimplify $ Sorted b (colTransformEx f c)
boolTransformEx f (AllDiff b c) = boolSimplify $ AllDiff b (colTransformEx f c)
boolTransformEx f (BoolCond c t e) = boolSimplify $ BoolCond (boolTransformEx f c) (boolTransformEx f t) (boolTransformEx f e)
boolTransformEx f (Dom i c) = boolSimplify $ Dom (transformEx f i) (colTransformEx f c)
------------------------------------------------------------------------------------------
-- | Check whether an expression is possibly referring to terms with a given property | --
------------------------------------------------------------------------------------------
propertyEx :: (Expr a b c -> Maybe Bool, ColExpr a b c -> Maybe Bool, BoolExpr a b c -> Maybe Bool) -> Expr a b c -> Bool
propertyEx f@(fi,fc,fb) t = case fi t of
Just a -> a
Nothing -> case t of
Plus a b -> propertyEx f a || propertyEx f b
Minus a b -> propertyEx f a || propertyEx f b
Mult a b -> propertyEx f a || propertyEx f b
Div a b -> propertyEx f a || propertyEx f b
Mod a b -> propertyEx f a || propertyEx f b
Abs a -> propertyEx f a
At a b -> propertyEx f b || colPropertyEx f a
ColSize a -> colPropertyEx f a
Fold _ _ _ -> True
Channel b -> boolPropertyEx f b
Cond c t e -> boolPropertyEx f c || propertyEx f t || propertyEx f e
_ -> False
colPropertyEx :: (Expr a b c -> Maybe Bool, ColExpr a b c -> Maybe Bool, BoolExpr a b c -> Maybe Bool) -> ColExpr a b c -> Bool
colPropertyEx f@(fi,fc,fb) t = case fc t of
Just a -> a
Nothing -> case t of
ColList l -> any (propertyEx f) l
ColMap _ _ -> True
ColSlice p l c -> propertyEx f (p (ExprHole (-1))) || propertyEx f l || colPropertyEx f c
ColRange l h -> propertyEx f l || propertyEx f h
ColCat a b -> colPropertyEx f a || colPropertyEx f b
_ -> False
boolPropertyEx :: (Expr a b c -> Maybe Bool, ColExpr a b c -> Maybe Bool, BoolExpr a b c -> Maybe Bool) -> BoolExpr a b c -> Bool
boolPropertyEx f@(fi,fc,fb) t = case fb t of
Just a -> a
Nothing -> case t of
BoolAnd a b -> boolPropertyEx f a || boolPropertyEx f b
BoolOr a b -> boolPropertyEx f a || boolPropertyEx f b
BoolNot a -> boolPropertyEx f a
BoolEqual a b -> boolPropertyEx f a || boolPropertyEx f b
Rel a _ b -> propertyEx f a || propertyEx f b
BoolAll _ _ -> True
BoolAny _ _ -> True
ColEqual a b -> colPropertyEx f a || colPropertyEx f b
AllDiff _ c -> colPropertyEx f c
Sorted _ c -> colPropertyEx f c
BoolCond c t e -> boolPropertyEx f c || boolPropertyEx f t || boolPropertyEx f e
Dom i c -> propertyEx f i || colPropertyEx f c
_ -> False
property :: (a -> Bool) -> (b -> Bool) -> (c -> Bool) -> Expr a b c -> Bool
property fit fct fbt = propertyEx (propInt fit, propCol fct, propBool fbt)
colProperty :: (a -> Bool) -> (b -> Bool) -> (c -> Bool) -> ColExpr a b c -> Bool
colProperty fit fct fbt = colPropertyEx (propInt fit, propCol fct, propBool fbt)
boolProperty :: (a -> Bool) -> (b -> Bool) -> (c -> Bool) -> BoolExpr a b c -> Bool
boolProperty fit fct fbt = boolPropertyEx (propInt fit, propCol fct, propBool fbt)
propInt :: (a -> Bool) -> Expr a b c -> Maybe Bool
propInt ft t = case t of
Term x -> Just $ ft x
_ -> Nothing
propCol :: (b -> Bool) -> ColExpr a b c -> Maybe Bool
propCol ft t = case t of
ColTerm x -> Just $ ft x
_ -> Nothing
propBool :: (c -> Bool) -> BoolExpr a b c -> Maybe Bool
propBool ft t = case t of
BoolTerm x -> Just $ ft x
_ -> Nothing
-------------------------------------------------------------------
-- | Count how many references to terms an expression contains | --
-------------------------------------------------------------------
varrefs :: Expr a b c -> Int
varrefs (Term _) = 1
varrefs (Const _) = 0
varrefs (ExprHole _) = 0
varrefs (Plus a b) = varrefs a + varrefs b
varrefs (Minus a b) = varrefs a + varrefs b
varrefs (Mult a b) = varrefs a + varrefs b
varrefs (Div a b) = varrefs a + varrefs b
varrefs (Mod a b) = varrefs a + varrefs b
varrefs (Abs a) = varrefs a
varrefs (At c i) = varrefs i + colVarrefs c
varrefs (ColSize c) = colVarrefs c
varrefs (Fold f i c) = varrefs i + colVarrefs c + varrefs (f (ExprHole 0) (ExprHole 1))
varrefs (Channel b) = boolVarrefs b
varrefs (Cond c t e) = boolVarrefs c + varrefs t + varrefs e
colVarrefs :: ColExpr a b c -> Int
colVarrefs (ColTerm _) = 1
colVarrefs (ColList lst) = sum $ map varrefs lst
colVarrefs (ColMap m c) = colVarrefs c + varrefs (m (ExprHole 0))
colVarrefs (ColSlice p l c) = varrefs (p (ExprHole 0)) + varrefs l + colVarrefs c
colVarrefs (ColCat a b) = colVarrefs a + colVarrefs b
colVarrefs (ColRange a b) = varrefs a + varrefs b
boolVarrefs :: BoolExpr a b c -> Int
boolVarrefs (BoolTerm _) = 1
boolVarrefs (BoolConst _) = 0
boolVarrefs (BoolAnd a b) = boolVarrefs a + boolVarrefs b
boolVarrefs (BoolOr a b) = boolVarrefs a + boolVarrefs b
boolVarrefs (BoolEqual a b) = boolVarrefs a + boolVarrefs b
boolVarrefs (BoolNot a) = boolVarrefs a
boolVarrefs (BoolAll f c) = boolVarrefs (f $ ExprHole 0) + colVarrefs c
boolVarrefs (BoolAny f c) = boolVarrefs (f $ ExprHole 0) + colVarrefs c
boolVarrefs (Rel a _ b) = varrefs a + varrefs b
boolVarrefs (ColEqual a b) = colVarrefs a + colVarrefs b
boolVarrefs (Sorted _ c) = colVarrefs c
boolVarrefs (AllDiff _ c) = colVarrefs c
boolVarrefs (BoolCond c t e) = boolVarrefs c + boolVarrefs t + boolVarrefs e
boolVarrefs (Dom i c) = varrefs i + colVarrefs c
------------------------------
-- | Simplify expressions | --
------------------------------
simplify :: (Eq s, Eq c, Eq b) => Expr s c b -> Expr s c b
-- dropout rules (things that won't ever be changed)
simplify a@(Const _) = a
simplify a@(Term _) = a
simplify a@(ExprHole _) = a
simplification rules ( either decrease # of variable references , or leave that equal and decrease # of tree nodes )
--- level 0 (result in a final expression)
simplify (Mult a@(Const 0) _) = a
simplify (Div a@(Const 0) _) = a
simplify (Mod a@(Const 0) _) = a
simplify (Mod _ (Const 1)) = Const 0
simplify (Mod _ (Const (-1))) = Const 0
simplify (Mod (Mult (Const a) b) (Const c)) | (a `mod` c)==0 = Const 0
simplify (Minus a b) | a==b = Const 0
simplify (Plus (Const a) (Const b)) = Const (a+b)
simplify (Minus (Const a) (Const b)) = Const (a-b)
simplify (Mult (Const a) (Const b)) = Const (a*b)
simplify (Div (Const a) (Const b)) = Const $ (a `div` b)
simplify (Abs (Const a)) = Const (abs a)
simplify (Mod (Const a) (Const b)) = Const $ (a `mod` b)
simplify (Plus (Const 0) a) = a
simplify (Mult (Const 1) a) = a
simplify (Div a (Const 1)) = a
simplify (At (ColList l) (Const c)) = l!!(fromInteger c)
simplify (ColSize (ColList l)) = Const $ toInteger $ length l
simplify (ColSize (ColSlice _ l _)) = l
simplify (Channel (BoolConst False)) = Const 0
simplify (Channel (BoolConst True)) = Const 1
simplify (Cond (BoolConst True) t _) = t
simplify (Cond (BoolConst False) _ f) = f
- level 1 ( result in one recursive call to simplify )
simplify (Plus a b) | a==b = simplify $ Mult (Const 2) a
simplify (Div a (Const (-1))) = simplify $ Minus (Const 0) a
simplify (Plus (Const c) (Plus (Const a) b)) = simplify $ Plus (Const $ c+a) b
simplify (Plus (Const c) (Minus (Const a) b)) = simplify $ Minus (Const $ c+a) b
simplify (Minus (Const c) (Plus (Const a) b)) = simplify $ Minus (Const $ c-a) b
simplify (Minus (Const c) (Minus (Const a) b)) = simplify $ Plus (Const $ c-a) b
simplify (Mult (Const c) (Mult (Const a) b)) = simplify $ Mult (Const $ a*c) b
simplify (Div (Mult (Const a) b) (Const c)) | (a `mod` c)==0 = simplify $ Mult (Const (a `div` c)) b
simplify (ColSize (ColMap _ c)) = simplify $ ColSize c
simplify (Fold f1 i (ColMap f2 c)) = simplify $ Fold (\a b -> f1 a (f2 b)) i c
simplify (At (ColRange l h) p) = simplify $ Plus l p
simplify (Cond (BoolNot c) t f) = simplify $ Cond c f t
- level 2 ( result in two recursive calls to simplify )
simplify (Plus a (Mult b c)) | a==b && ((varrefs a)>0) = simplify $ Mult (simplify $ Plus c (Const 1)) a
simplify (Plus a (Mult b c)) | a==c && ((varrefs a)>0) = simplify $ Mult (simplify $ Plus b (Const 1)) a
simplify (Plus (Mult b c) a) | a==b && ((varrefs a)>0) = simplify $ Mult (simplify $ Plus c (Const 1)) a
simplify (Plus (Mult b c) a) | a==c && ((varrefs a)>0) = simplify $ Mult (simplify $ Plus b (Const 1)) a
simplify (Plus (Mult a b) (Mult c d)) | a==c = simplify $ Mult (simplify $ Plus b d) a
simplify (Plus (Mult a b) (Mult c d)) | a==d = simplify $ Mult (simplify $ Plus b c) a
simplify (Plus (Mult a b) (Mult c d)) | b==c = simplify $ Mult (simplify $ Plus a d) b
simplify (Plus (Mult a b) (Mult c d)) | b==d = simplify $ Mult (simplify $ Plus a c) b
simplify (Minus a (Mult b c)) | a==b && ((varrefs a)>0) = simplify $ Mult (simplify $ Minus (Const 1) c) a
simplify (Minus a (Mult b c)) | a==c && ((varrefs a)>0) = simplify $ Mult (simplify $ Minus (Const 1) b) a
simplify (Minus (Mult b c) a) | a==b && ((varrefs a)>0) = simplify $ Mult (simplify $ Minus c (Const 1)) a
simplify (Minus (Mult b c) a) | a==c && ((varrefs a)>0) = simplify $ Mult (simplify $ Minus b (Const 1)) a
simplify (Minus (Mult a b) (Mult c d)) | a==c = simplify $ Mult (simplify $ Minus b d) a
simplify (Minus (Mult a b) (Mult c d)) | a==d = simplify $ Mult (simplify $ Minus b c) a
simplify (Minus (Mult a b) (Mult c d)) | b==c = simplify $ Mult (simplify $ Minus a d) b
simplify (Minus (Mult a b) (Mult c d)) | b==d = simplify $ Mult (simplify $ Minus a c) b
simplify (Mult (Abs a) (Abs b)) = simplify $ Abs (simplify $ Mult a b)
simplify (Div (Abs a) (Abs b)) = simplify $ Abs (simplify $ Div a b)
simplify (ColSize (ColRange l h)) = simplify $ Plus (Const 1) $ simplify $ Minus h l
simplify (At (ColSlice f _ c) i) = simplify $ At c (f i)
simplify (At (ColMap m c) i) = simplify $ m $ simplify $ At c i
simplify t@(At (ColCat c1 c2) c@(Const p)) = case simplify (ColSize c1) of
Const l | p<l -> simplify $ At c1 c
Const l | p>=l -> simplify $ At c2 (Const $ p-l)
_ -> t {- no further (At _ _) rules may follow after this -}
- level 3 ( results in three recursive calls to simplify )
simplify (ColSize (ColCat a b)) = simplify $ Plus (simplify $ ColSize a) (simplify $ ColSize b)
reordering rules ( do not decrease # of variables or # of tree nodes , but normalize an expression in such a way that the same normalization can not be applied anymore - possibly because that can only occur in a case already matched by a simplification rule above )
- level 1
simplify (Plus a (Const c)) = simplify $ Plus (Const c) a
simplify (Minus a (Const c)) = simplify $ Plus (Const (-c)) a
simplify (Mult a (Const c)) = simplify $ Mult (Const c) a
simplify (Mult (Const (-1)) a) = simplify $ Minus (Const 0) a
- level 2
simplify (Mult t@(Const c) (Plus (Const a) b)) = simplify $ Plus (Const (a*c)) (simplify $ Mult t b)
simplify (Mult t@(Const c) (Minus (Const a) b)) = simplify $ Minus (Const (a*c)) (simplify $ Mult t b)
simplify (Plus a (Plus t@(Const b) c)) = simplify $ Plus t (simplify $ Plus a c)
simplify (Plus a (Minus t@(Const b) c)) = simplify $ Plus t (simplify $ Minus a c)
simplify (Minus a (Plus (Const b) c)) = simplify $ Plus (Const (-b)) (simplify $ Minus a c)
simplify (Minus a (Minus (Const b) c)) = simplify $ Plus (Const (-b)) (simplify $ Plus a c)
simplify (Mult a (Mult t@(Const b) c)) = simplify $ Mult t (simplify $ Mult a c)
simplify (Plus (Plus t@(Const a) b) c) = simplify $ Plus t (simplify $ Plus b c)
simplify (Plus (Minus t@(Const a) b) c) = simplify $ Plus t (simplify $ Minus c b)
simplify (Minus (Plus t@(Const a) b) c) = simplify $ Plus t (simplify $ Minus b c)
simplify (Minus (Minus t@(Const a) b) c) = simplify $ Minus t (simplify $ Plus b c)
simplify (Mult (Mult t@(Const a) b) c) = simplify $ Mult t (simplify $ Mult b c)
simplify (Mult a (Minus t@(Const 0) b)) = simplify $ Minus t (simplify $ Mult a b)
simplify (Mult (Minus t@(Const 0) b) a) = simplify $ Minus t (simplify $ Mult a b)
simplify (Div (Minus t@(Const 0) a) b) = simplify $ Minus t (simplify $ Div a b)
simplify (Div a (Minus t@(Const 0) b)) = simplify $ Minus t (simplify $ Div a b)
-- fallback rule
simplify a = a
colSimplify :: (Eq s, Eq c, Eq b) => ColExpr s c b -> ColExpr s c b
-- dropout rules
colSimplify t@(ColTerm _) = t
-- simplify rules
- level 1
colSimplify (ColMap f1 (ColMap f2 c)) = colSimplify $ ColMap (f1.f2) c
colSimplify (ColMap f (ColList l)) = colSimplify $ ColList (map f l)
- level 2
colSimplify (ColSlice p1 l1 (ColSlice p2 l2 c)) = colSimplify $ ColSlice (p1 . p2) l1 c
-- reordering rules
- level 2
colSimplify (ColCat (ColCat c1 c2) c3) = colSimplify $ ColCat c1 (colSimplify $ ColCat c2 c3)
colSimplify (ColSlice p l (ColMap f c)) = colSimplify $ ColMap f $ colSimplify $ ColSlice p l c
-- fallback rule
colSimplify x = x
boolSimplify :: (Eq s, Eq c, Eq b) => BoolExpr s c b -> BoolExpr s c b
-- dropout rules
boolSimplify t@(BoolTerm _) = t
boolSimplify t@(BoolConst _) = t
-- simplify rules
--- level 0
boolSimplify (BoolAnd (BoolConst False) _) = BoolConst False
boolSimplify (BoolAnd (BoolConst True) a) = a
boolSimplify (BoolAnd _ (BoolConst False)) = BoolConst False
boolSimplify (BoolAnd a (BoolConst True)) = a
boolSimplify (BoolOr (BoolConst True) _) = BoolConst True
boolSimplify (BoolOr (BoolConst False) a) = a
boolSimplify (BoolOr _ (BoolConst True)) = BoolConst True
boolSimplify (BoolOr a (BoolConst False)) = a
boolSimplify (BoolNot (BoolConst a)) = BoolConst (not a)
boolSimplify (BoolEqual (BoolConst True) a) = a
boolSimplify (BoolEqual a (BoolConst True)) = a
boolSimplify (BoolNot (BoolNot a)) = a
boolSimplify (BoolOr a b) | a==b = a
boolSimplify (BoolAnd a b) | a==b = a
boolSimplify (BoolEqual a b) | a==b = BoolConst False
boolSimplify (Rel (Const a) r (Const b)) = BoolConst $ relCheck a r b
boolSimplify (BoolAll f (ColList [])) = BoolConst True
boolSimplify (BoolAny f (ColList [])) = BoolConst False
boolSimplify (BoolAll f (ColList [a])) = f a
boolSimplify (BoolAny f (ColList [a])) = f a
boolSimplify (ColEqual (ColList []) (ColList [])) = BoolConst True
boolSimplify (ColEqual (ColList []) (ColList _)) = BoolConst False
boolSimplify (ColEqual (ColList _) (ColList [])) = BoolConst False
boolSimplify (BoolCond (BoolConst True) t _) = t
boolSimplify (BoolCond (BoolConst False) _ f) = f
- level 1
boolSimplify (BoolEqual (BoolNot a) (BoolNot b)) = boolSimplify $ BoolEqual a b
boolSimplify (BoolEqual (BoolConst False) a) = boolSimplify $ BoolNot a
boolSimplify (BoolEqual a (BoolConst False)) = boolSimplify $ BoolNot a
boolSimplify (BoolNot (Rel a EREqual b)) = boolSimplify $ Rel a ERDiff b
boolSimplify (BoolNot (Rel a ERDiff b)) = boolSimplify $ Rel a EREqual b
boolSimplify (BoolAll f (ColList [a,b])) = boolSimplify $ f a `BoolAnd` f b
boolSimplify (BoolAny f (ColList [a,b])) = boolSimplify $ f a `BoolOr` f b
boolSimplify (ColEqual (ColList [a]) (ColList [b])) = boolSimplify $ Rel a EREqual b
boolSimplify (Rel (Channel a) EREqual (Channel b)) = boolSimplify $ BoolEqual a b
boolSimplify (BoolCond (BoolNot c) t f) = boolSimplify $ BoolCond c f t
- level 2
boolSimplify (BoolAnd (BoolNot a) (BoolNot b)) = boolSimplify $ BoolNot $ boolSimplify $ BoolOr a b
boolSimplify (BoolOr (BoolNot a) (BoolNot b)) = boolSimplify $ BoolNot $ boolSimplify $ BoolAnd a b
boolSimplify (Rel (Channel a) ERDiff (Channel b)) = boolSimplify $ BoolNot $ boolSimplify $ BoolEqual a b
boolSimplify (Rel (Channel a) ERLess (Channel b)) = boolSimplify $ BoolAnd b $ boolSimplify $ BoolNot a -- int(b1) < int(b2) <=> !b1 && b2
-- fallback
boolSimplify a = a
-------------------------------------------------------------------
-- | Turn expressions over expressions into simply expressions | --
-------------------------------------------------------------------
collapse :: (Eq t, Eq c, Eq b) => Expr (Expr t c b) (ColExpr t c b) (BoolExpr t c b) -> Expr t c b
collapse (Term t) = t
collapse (Const i) = Const i
collapse (Plus a b) = simplify $ Plus (collapse a) (collapse b)
collapse (Minus a b) = simplify $ Minus (collapse a) (collapse b)
collapse (Mult a b) = simplify $ Mult (collapse a) (collapse b)
collapse (Div a b) = simplify $ Div (collapse a) (collapse b)
collapse (Mod a b) = simplify $ Mod (collapse a) (collapse b)
collapse (Abs a) = simplify $ Abs (collapse a)
collapse (At c a) = simplify $ At (colCollapse c) (collapse a)
collapse (ColSize c) = simplify $ ColSize (colCollapse c)
collapse (Fold f i c) = simplify $ Fold (\a b -> collapse $ f (Term a) (Term b)) (collapse i) (colCollapse c)
collapse (Channel b) = simplify $ Channel (boolCollapse b)
collapse (Cond c t e) = simplify $ Cond (boolCollapse c) (collapse t) (collapse e)
colCollapse :: (Eq t, Eq c, Eq b) => ColExpr (Expr t c b) (ColExpr t c b) (BoolExpr t c b) -> ColExpr t c b
colCollapse (ColTerm t) = t
colCollapse (ColList l) = colSimplify $ ColList $ map collapse l
colCollapse (ColMap f c) = colSimplify $ ColMap (\a -> collapse $ f (Term a)) (colCollapse c)
colCollapse (ColSlice p l c) = colSimplify $ ColSlice (\x -> collapse $ p (Term x)) (collapse l) (colCollapse c)
colCollapse (ColCat a b) = colSimplify $ ColCat (colCollapse a) (colCollapse b)
colCollapse (ColRange a b) = colSimplify $ ColRange (collapse a) (collapse b)
boolCollapse :: (Eq t, Eq c, Eq b) => BoolExpr (Expr t c b) (ColExpr t c b) (BoolExpr t c b) -> BoolExpr t c b
boolCollapse (BoolTerm t) = t
boolCollapse (BoolConst c) = BoolConst c
boolCollapse (BoolAnd a b) = boolSimplify $ BoolAnd (boolCollapse a) (boolCollapse b)
boolCollapse (BoolOr a b) = boolSimplify $ BoolOr (boolCollapse a) (boolCollapse b)
boolCollapse (BoolEqual a b) = boolSimplify $ BoolEqual (boolCollapse a) (boolCollapse b)
boolCollapse (BoolNot a) = boolSimplify $ BoolNot (boolCollapse a)
boolCollapse (Rel a r b) = boolSimplify $ Rel (collapse a) r (collapse b)
boolCollapse (BoolAll f c) = boolSimplify $ BoolAll (\a -> boolCollapse $ f (Term a)) (colCollapse c)
boolCollapse (BoolAny f c) = boolSimplify $ BoolAny (\a -> boolCollapse $ f (Term a)) (colCollapse c)
boolCollapse (ColEqual a b) = boolSimplify $ ColEqual (colCollapse a) (colCollapse b)
boolCollapse (Sorted b c) = boolSimplify $ Sorted b (colCollapse c)
boolCollapse (AllDiff b c) = boolSimplify $ AllDiff b (colCollapse c)
boolCollapse (BoolCond c t e) = boolSimplify $ BoolCond (boolCollapse c) (boolCollapse t) (boolCollapse e)
boolCollapse (Dom i c) = boolSimplify $ Dom (collapse i) (colCollapse c)
-----------------------------------------
-- | walk through expressions
-----------------------------------------
data WalkPhase = WalkPre | WalkSingle | WalkPost
deriving (Ord,Eq,Enum,Show)
data WalkResult = WalkSkip | WalkDescend
deriving (Ord,Eq,Enum,Show)
xwalker :: (Eq t, Eq c, Eq b, Monad m) => (WalkPhase -> m WalkResult) -> (Expr t c b -> WalkPhase -> m WalkResult, ColExpr t c b -> WalkPhase -> m WalkResult, BoolExpr t c b -> WalkPhase -> m WalkResult) -> ([Expr t c b],[ColExpr t c b],[BoolExpr t c b]) -> m ()
xwalker q f ([],[],[]) = do
q WalkSingle
return ()
xwalker q f (li,lc,lb) = do
r <- q WalkPre
case r of
WalkSkip -> return ()
WalkDescend -> do
mapM_ (\p -> walk p f) li
mapM_ (\p -> colWalk p f) lc
mapM_ (\p -> boolWalk p f) lb
q WalkPost
return ()
walker :: (Eq t, Eq c, Eq b, Monad m) => Expr t c b -> (Expr t c b -> WalkPhase -> m WalkResult, ColExpr t c b -> WalkPhase -> m WalkResult, BoolExpr t c b -> WalkPhase -> m WalkResult) -> ([Expr t c b],[ColExpr t c b],[BoolExpr t c b]) -> m ()
walker x f@(i,c,b) l = xwalker (i x) f l
colWalker :: (Eq t, Eq c, Eq b, Monad m) => ColExpr t c b -> (Expr t c b -> WalkPhase -> m WalkResult, ColExpr t c b -> WalkPhase -> m WalkResult, BoolExpr t c b -> WalkPhase -> m WalkResult) -> ([Expr t c b],[ColExpr t c b],[BoolExpr t c b]) -> m ()
colWalker x f@(i,c,b) l = xwalker (c x) f l
boolWalker :: (Eq t, Eq c, Eq b, Monad m) => BoolExpr t c b -> (Expr t c b -> WalkPhase -> m WalkResult, ColExpr t c b -> WalkPhase -> m WalkResult, BoolExpr t c b -> WalkPhase -> m WalkResult) -> ([Expr t c b],[ColExpr t c b],[BoolExpr t c b]) -> m ()
boolWalker x f@(i,c,b) l = xwalker (b x) f l
walk :: (Eq t, Eq c, Eq b, Monad m) => Expr t c b -> (Expr t c b -> WalkPhase -> m WalkResult, ColExpr t c b -> WalkPhase -> m WalkResult, BoolExpr t c b -> WalkPhase -> m WalkResult) -> m ()
walk x@(Term _) f = walker x f ([],[],[])
walk x@(Const _) f = walker x f ([],[],[])
walk x@(Plus a b) f = walker x f ([a,b],[],[])
walk x@(Minus a b) f = walker x f ([a,b],[],[])
walk x@(Mult a b) f = walker x f ([a,b],[],[])
walk x@(Div a b) f = walker x f ([a,b],[],[])
walk x@(Mod a b) f = walker x f ([a,b],[],[])
walk x@(Abs a) f = walker x f ([a],[],[])
walk x@(At c a) f = walker x f ([a],[c],[])
walk x@(ColSize c) f = walker x f ([],[c],[])
walk x@(Fold _ i c) f = walker x f ([i],[c],[])
walk x@(Channel b) f = walker x f ([],[],[b])
walk x@(Cond c t e) f = walker x f ([t,e],[],[c])
walk x@(ExprHole _) f = return ()
colWalk x@(ColTerm _) f = colWalker x f ([],[],[])
colWalk x@(ColList l) f = colWalker x f (l,[],[])
colWalk x@(ColMap _ c) f = colWalker x f ([],[c],[])
colWalk x@(ColSlice _ l c) f = colWalker x f ([l],[c],[])
colWalk x@(ColCat a b) f = colWalker x f ([],[a,b],[])
colWalk x@(ColRange a b) f = colWalker x f ([a,b],[],[])
boolWalk x@(BoolTerm _) f = boolWalker x f ([],[],[])
boolWalk x@(BoolConst _) f = boolWalker x f ([],[],[])
boolWalk x@(BoolAnd a b) f = boolWalker x f ([],[],[a,b])
boolWalk x@(BoolOr a b) f = boolWalker x f ([],[],[a,b])
boolWalk x@(BoolEqual a b) f = boolWalker x f ([],[],[a,b])
boolWalk x@(BoolNot a) f = boolWalker x f ([],[],[a])
boolWalk x@(Rel a _ b) f = boolWalker x f ([a,b],[],[])
boolWalk x@(BoolAll _ c) f = boolWalker x f ([],[c],[])
boolWalk x@(BoolAny _ c) f = boolWalker x f ([],[c],[])
boolWalk x@(ColEqual a b) f = boolWalker x f ([],[a,b],[])
boolWalk x@(Sorted _ c) f = boolWalker x f ([],[c],[])
boolWalk x@(AllDiff _ c) f = boolWalker x f ([],[c],[])
boolWalk x@(BoolCond c t e) f = boolWalker x f ([],[],[c,t,e])
boolWalk x@(Dom i c) f = boolWalker x f ([i],[c],[])
| null | https://raw.githubusercontent.com/letmaik/monadiccp/fe4498e46a7b9d9e387fd5e4ed5d0749a89d0188/src/Data/Expr/Util.hs | haskell | -----------------------
| Helper functions |--
-----------------------
-----------------------------------------------------------------------
-----------------------------------------------------------------------
----------------------------------------------------------------------------------------
| Check whether an expression is possibly referring to terms with a given property | --
----------------------------------------------------------------------------------------
-----------------------------------------------------------------
| Count how many references to terms an expression contains | --
-----------------------------------------------------------------
----------------------------
| Simplify expressions | --
----------------------------
dropout rules (things that won't ever be changed)
- level 0 (result in a final expression)
no further (At _ _) rules may follow after this
fallback rule
dropout rules
simplify rules
reordering rules
fallback rule
dropout rules
simplify rules
- level 0
int(b1) < int(b2) <=> !b1 && b2
fallback
-----------------------------------------------------------------
| Turn expressions over expressions into simply expressions | --
-----------------------------------------------------------------
---------------------------------------
| walk through expressions
--------------------------------------- |
- Monadic Constraint Programming
- /~toms/MCP/
-
- Monadic Constraint Programming
- /~toms/MCP/
- Pieter Wuille
-}
# LANGUAGE StandaloneDeriving #
module Data.Expr.Util (
Expr(), BoolExpr(), ColExpr(),
transform, colTransform, boolTransform,
transformEx, colTransformEx, boolTransformEx,
property, colProperty, boolProperty,
propertyEx, colPropertyEx, boolPropertyEx,
collapse, colCollapse, boolCollapse,
simplify, colSimplify, boolSimplify,
WalkPhase(..), WalkResult(..), walk, colWalk, boolWalk,
) where
import Data.Expr.Data
relCheck :: Integer -> ExprRel -> Integer -> Bool
relCheck a EREqual b = a==b
relCheck a ERDiff b = a/=b
relCheck a ERLess b = a<b
transform :: (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f) => (a->b,c->d,e->f,b->a,d->c,f->e) -> Expr a c e -> Expr b d f
transform (f,fc,fb,fi,fic,fib) = transformEx (Term . f, ColTerm . fc, BoolTerm . fb, Term . fi, ColTerm . fic, BoolTerm . fib)
transformEx :: (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f) => ((a -> Expr b d f),(c -> ColExpr b d f),(e -> BoolExpr b d f),(b -> Expr a c e),(d -> ColExpr a c e),(f -> BoolExpr a c e)) -> Expr a c e -> Expr b d f
transformEx (f,_,_,_,_,_) (Term v) = f v
transformEx f (Const i) = Const i
transformEx f (ExprHole i) = ExprHole i
transformEx f (Plus a b) = simplify $ Plus (transformEx f a) (transformEx f b)
transformEx f (Minus a b) = simplify $ Minus (transformEx f a) (transformEx f b)
transformEx f (Mult a b) = simplify $ Mult (transformEx f a) (transformEx f b)
transformEx f (Div a b) = simplify $ Div (transformEx f a) (transformEx f b)
transformEx f (Mod a b) = simplify $ Mod (transformEx f a) (transformEx f b)
transformEx f (Abs a) = simplify $ Abs (transformEx f a)
transformEx f (At c a) = simplify $ At (colTransformEx f c) (transformEx f a)
transformEx f (ColSize c) = simplify $ ColSize $ colTransformEx f c
transformEx f (Channel a) = simplify $ Channel $ boolTransformEx f a
transformEx f (Cond c t e) = simplify $ Cond (boolTransformEx f c) (transformEx f t) (transformEx f e)
transformEx t@(f,fc,fb,fi,fic,fib) (Fold m i c) = simplify $ Fold (\a b -> transformEx t (m (transformEx (fi,fic,fib,f,fc,fb) a) (transformEx (fi,fic,fib,f,fc,fb) b))) (transformEx t i) (colTransformEx t c)
colTransform :: (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f) => (a->b,c->d,e->f,b->a,d->c,f->e) -> ColExpr a c e -> ColExpr b d f
colTransform (f,fc,fb,fi,fic,fib) = colTransformEx (Term . f, ColTerm . fc, BoolTerm . fb, Term . fi, ColTerm . fic, BoolTerm . fib)
colTransformEx :: (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f) => ((a -> Expr b d f),(c -> ColExpr b d f),(e -> BoolExpr b d f),(b -> Expr a c e),(d -> ColExpr a c e),f -> BoolExpr a c e) -> ColExpr a c e -> ColExpr b d f
colTransformEx (_,f,_,_,_,_) (ColTerm c) = f c
colTransformEx f (ColList l) = colSimplify $ ColList $ map (transformEx f) l
colTransformEx t@(f,fc,fb,fi,fic,fib) (ColMap m c) = colSimplify $ ColMap (\a -> transformEx t (m (transformEx (fi,fic,fib,f,fc,fb) a))) (colTransformEx t c)
colTransformEx t@(f,fc,fb,fi,fic,fib) (ColSlice p l c) = colSimplify $ ColSlice (\a -> transformEx t (p (transformEx (fi,fic,fib,f,fc,fb) a))) (transformEx t l) (colTransformEx t c)
colTransformEx f (ColCat a b) = colSimplify $ ColCat (colTransformEx f a) (colTransformEx f b)
colTransformEx f (ColRange a b) = colSimplify $ ColRange (transformEx f a) (transformEx f b)
boolTransform :: (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f) => (a->b,c->d,e->f,b->a,d->c,f->e) -> BoolExpr a c e -> BoolExpr b d f
boolTransform (f,fc,fb,fi,fic,fib) = boolTransformEx (Term . f, ColTerm . fc, BoolTerm . fb, Term . fi, ColTerm . fic, BoolTerm . fib)
boolTransformEx :: (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f) => ((a -> Expr b d f),(c -> ColExpr b d f),(e -> BoolExpr b d f),(b -> Expr a c e),(d -> ColExpr a c e),f -> BoolExpr a c e) -> BoolExpr a c e -> BoolExpr b d f
boolTransformEx (_,_,f,_,_,_) (BoolTerm v) = f v
boolTransformEx f (BoolConst c) = BoolConst c
boolTransformEx f (BoolAnd a b) = boolSimplify $ BoolAnd (boolTransformEx f a) (boolTransformEx f b)
boolTransformEx f (BoolOr a b) = boolSimplify $ BoolOr (boolTransformEx f a) (boolTransformEx f b)
boolTransformEx f (BoolEqual a b) = boolSimplify $ BoolEqual (boolTransformEx f a) (boolTransformEx f b)
boolTransformEx f (BoolNot a) = boolSimplify $ BoolNot (boolTransformEx f a)
boolTransformEx f (Rel a r b) = boolSimplify $ Rel (transformEx f a) r (transformEx f b)
boolTransformEx t@(f,fc,fb,fi,fic,fib) (BoolAll m c) = boolSimplify $ BoolAll (\a -> boolTransformEx t (m (transformEx (fi,fic,fib,f,fc,fb) a))) (colTransformEx t c)
boolTransformEx t@(f,fc,fb,fi,fic,fib) (BoolAny m c) = boolSimplify $ BoolAny (\a -> boolTransformEx t (m (transformEx (fi,fic,fib,f,fc,fb) a))) (colTransformEx t c)
boolTransformEx f (ColEqual a b) = boolSimplify $ ColEqual (colTransformEx f a) (colTransformEx f b)
boolTransformEx f (Sorted b c) = boolSimplify $ Sorted b (colTransformEx f c)
boolTransformEx f (AllDiff b c) = boolSimplify $ AllDiff b (colTransformEx f c)
boolTransformEx f (BoolCond c t e) = boolSimplify $ BoolCond (boolTransformEx f c) (boolTransformEx f t) (boolTransformEx f e)
boolTransformEx f (Dom i c) = boolSimplify $ Dom (transformEx f i) (colTransformEx f c)
propertyEx :: (Expr a b c -> Maybe Bool, ColExpr a b c -> Maybe Bool, BoolExpr a b c -> Maybe Bool) -> Expr a b c -> Bool
propertyEx f@(fi,fc,fb) t = case fi t of
Just a -> a
Nothing -> case t of
Plus a b -> propertyEx f a || propertyEx f b
Minus a b -> propertyEx f a || propertyEx f b
Mult a b -> propertyEx f a || propertyEx f b
Div a b -> propertyEx f a || propertyEx f b
Mod a b -> propertyEx f a || propertyEx f b
Abs a -> propertyEx f a
At a b -> propertyEx f b || colPropertyEx f a
ColSize a -> colPropertyEx f a
Fold _ _ _ -> True
Channel b -> boolPropertyEx f b
Cond c t e -> boolPropertyEx f c || propertyEx f t || propertyEx f e
_ -> False
colPropertyEx :: (Expr a b c -> Maybe Bool, ColExpr a b c -> Maybe Bool, BoolExpr a b c -> Maybe Bool) -> ColExpr a b c -> Bool
colPropertyEx f@(fi,fc,fb) t = case fc t of
Just a -> a
Nothing -> case t of
ColList l -> any (propertyEx f) l
ColMap _ _ -> True
ColSlice p l c -> propertyEx f (p (ExprHole (-1))) || propertyEx f l || colPropertyEx f c
ColRange l h -> propertyEx f l || propertyEx f h
ColCat a b -> colPropertyEx f a || colPropertyEx f b
_ -> False
boolPropertyEx :: (Expr a b c -> Maybe Bool, ColExpr a b c -> Maybe Bool, BoolExpr a b c -> Maybe Bool) -> BoolExpr a b c -> Bool
boolPropertyEx f@(fi,fc,fb) t = case fb t of
Just a -> a
Nothing -> case t of
BoolAnd a b -> boolPropertyEx f a || boolPropertyEx f b
BoolOr a b -> boolPropertyEx f a || boolPropertyEx f b
BoolNot a -> boolPropertyEx f a
BoolEqual a b -> boolPropertyEx f a || boolPropertyEx f b
Rel a _ b -> propertyEx f a || propertyEx f b
BoolAll _ _ -> True
BoolAny _ _ -> True
ColEqual a b -> colPropertyEx f a || colPropertyEx f b
AllDiff _ c -> colPropertyEx f c
Sorted _ c -> colPropertyEx f c
BoolCond c t e -> boolPropertyEx f c || boolPropertyEx f t || boolPropertyEx f e
Dom i c -> propertyEx f i || colPropertyEx f c
_ -> False
property :: (a -> Bool) -> (b -> Bool) -> (c -> Bool) -> Expr a b c -> Bool
property fit fct fbt = propertyEx (propInt fit, propCol fct, propBool fbt)
colProperty :: (a -> Bool) -> (b -> Bool) -> (c -> Bool) -> ColExpr a b c -> Bool
colProperty fit fct fbt = colPropertyEx (propInt fit, propCol fct, propBool fbt)
boolProperty :: (a -> Bool) -> (b -> Bool) -> (c -> Bool) -> BoolExpr a b c -> Bool
boolProperty fit fct fbt = boolPropertyEx (propInt fit, propCol fct, propBool fbt)
propInt :: (a -> Bool) -> Expr a b c -> Maybe Bool
propInt ft t = case t of
Term x -> Just $ ft x
_ -> Nothing
propCol :: (b -> Bool) -> ColExpr a b c -> Maybe Bool
propCol ft t = case t of
ColTerm x -> Just $ ft x
_ -> Nothing
propBool :: (c -> Bool) -> BoolExpr a b c -> Maybe Bool
propBool ft t = case t of
BoolTerm x -> Just $ ft x
_ -> Nothing
varrefs :: Expr a b c -> Int
varrefs (Term _) = 1
varrefs (Const _) = 0
varrefs (ExprHole _) = 0
varrefs (Plus a b) = varrefs a + varrefs b
varrefs (Minus a b) = varrefs a + varrefs b
varrefs (Mult a b) = varrefs a + varrefs b
varrefs (Div a b) = varrefs a + varrefs b
varrefs (Mod a b) = varrefs a + varrefs b
varrefs (Abs a) = varrefs a
varrefs (At c i) = varrefs i + colVarrefs c
varrefs (ColSize c) = colVarrefs c
varrefs (Fold f i c) = varrefs i + colVarrefs c + varrefs (f (ExprHole 0) (ExprHole 1))
varrefs (Channel b) = boolVarrefs b
varrefs (Cond c t e) = boolVarrefs c + varrefs t + varrefs e
colVarrefs :: ColExpr a b c -> Int
colVarrefs (ColTerm _) = 1
colVarrefs (ColList lst) = sum $ map varrefs lst
colVarrefs (ColMap m c) = colVarrefs c + varrefs (m (ExprHole 0))
colVarrefs (ColSlice p l c) = varrefs (p (ExprHole 0)) + varrefs l + colVarrefs c
colVarrefs (ColCat a b) = colVarrefs a + colVarrefs b
colVarrefs (ColRange a b) = varrefs a + varrefs b
boolVarrefs :: BoolExpr a b c -> Int
boolVarrefs (BoolTerm _) = 1
boolVarrefs (BoolConst _) = 0
boolVarrefs (BoolAnd a b) = boolVarrefs a + boolVarrefs b
boolVarrefs (BoolOr a b) = boolVarrefs a + boolVarrefs b
boolVarrefs (BoolEqual a b) = boolVarrefs a + boolVarrefs b
boolVarrefs (BoolNot a) = boolVarrefs a
boolVarrefs (BoolAll f c) = boolVarrefs (f $ ExprHole 0) + colVarrefs c
boolVarrefs (BoolAny f c) = boolVarrefs (f $ ExprHole 0) + colVarrefs c
boolVarrefs (Rel a _ b) = varrefs a + varrefs b
boolVarrefs (ColEqual a b) = colVarrefs a + colVarrefs b
boolVarrefs (Sorted _ c) = colVarrefs c
boolVarrefs (AllDiff _ c) = colVarrefs c
boolVarrefs (BoolCond c t e) = boolVarrefs c + boolVarrefs t + boolVarrefs e
boolVarrefs (Dom i c) = varrefs i + colVarrefs c
simplify :: (Eq s, Eq c, Eq b) => Expr s c b -> Expr s c b
simplify a@(Const _) = a
simplify a@(Term _) = a
simplify a@(ExprHole _) = a
simplification rules ( either decrease # of variable references , or leave that equal and decrease # of tree nodes )
simplify (Mult a@(Const 0) _) = a
simplify (Div a@(Const 0) _) = a
simplify (Mod a@(Const 0) _) = a
simplify (Mod _ (Const 1)) = Const 0
simplify (Mod _ (Const (-1))) = Const 0
simplify (Mod (Mult (Const a) b) (Const c)) | (a `mod` c)==0 = Const 0
simplify (Minus a b) | a==b = Const 0
simplify (Plus (Const a) (Const b)) = Const (a+b)
simplify (Minus (Const a) (Const b)) = Const (a-b)
simplify (Mult (Const a) (Const b)) = Const (a*b)
simplify (Div (Const a) (Const b)) = Const $ (a `div` b)
simplify (Abs (Const a)) = Const (abs a)
simplify (Mod (Const a) (Const b)) = Const $ (a `mod` b)
simplify (Plus (Const 0) a) = a
simplify (Mult (Const 1) a) = a
simplify (Div a (Const 1)) = a
simplify (At (ColList l) (Const c)) = l!!(fromInteger c)
simplify (ColSize (ColList l)) = Const $ toInteger $ length l
simplify (ColSize (ColSlice _ l _)) = l
simplify (Channel (BoolConst False)) = Const 0
simplify (Channel (BoolConst True)) = Const 1
simplify (Cond (BoolConst True) t _) = t
simplify (Cond (BoolConst False) _ f) = f
- level 1 ( result in one recursive call to simplify )
simplify (Plus a b) | a==b = simplify $ Mult (Const 2) a
simplify (Div a (Const (-1))) = simplify $ Minus (Const 0) a
simplify (Plus (Const c) (Plus (Const a) b)) = simplify $ Plus (Const $ c+a) b
simplify (Plus (Const c) (Minus (Const a) b)) = simplify $ Minus (Const $ c+a) b
simplify (Minus (Const c) (Plus (Const a) b)) = simplify $ Minus (Const $ c-a) b
simplify (Minus (Const c) (Minus (Const a) b)) = simplify $ Plus (Const $ c-a) b
simplify (Mult (Const c) (Mult (Const a) b)) = simplify $ Mult (Const $ a*c) b
simplify (Div (Mult (Const a) b) (Const c)) | (a `mod` c)==0 = simplify $ Mult (Const (a `div` c)) b
simplify (ColSize (ColMap _ c)) = simplify $ ColSize c
simplify (Fold f1 i (ColMap f2 c)) = simplify $ Fold (\a b -> f1 a (f2 b)) i c
simplify (At (ColRange l h) p) = simplify $ Plus l p
simplify (Cond (BoolNot c) t f) = simplify $ Cond c f t
- level 2 ( result in two recursive calls to simplify )
simplify (Plus a (Mult b c)) | a==b && ((varrefs a)>0) = simplify $ Mult (simplify $ Plus c (Const 1)) a
simplify (Plus a (Mult b c)) | a==c && ((varrefs a)>0) = simplify $ Mult (simplify $ Plus b (Const 1)) a
simplify (Plus (Mult b c) a) | a==b && ((varrefs a)>0) = simplify $ Mult (simplify $ Plus c (Const 1)) a
simplify (Plus (Mult b c) a) | a==c && ((varrefs a)>0) = simplify $ Mult (simplify $ Plus b (Const 1)) a
simplify (Plus (Mult a b) (Mult c d)) | a==c = simplify $ Mult (simplify $ Plus b d) a
simplify (Plus (Mult a b) (Mult c d)) | a==d = simplify $ Mult (simplify $ Plus b c) a
simplify (Plus (Mult a b) (Mult c d)) | b==c = simplify $ Mult (simplify $ Plus a d) b
simplify (Plus (Mult a b) (Mult c d)) | b==d = simplify $ Mult (simplify $ Plus a c) b
simplify (Minus a (Mult b c)) | a==b && ((varrefs a)>0) = simplify $ Mult (simplify $ Minus (Const 1) c) a
simplify (Minus a (Mult b c)) | a==c && ((varrefs a)>0) = simplify $ Mult (simplify $ Minus (Const 1) b) a
simplify (Minus (Mult b c) a) | a==b && ((varrefs a)>0) = simplify $ Mult (simplify $ Minus c (Const 1)) a
simplify (Minus (Mult b c) a) | a==c && ((varrefs a)>0) = simplify $ Mult (simplify $ Minus b (Const 1)) a
simplify (Minus (Mult a b) (Mult c d)) | a==c = simplify $ Mult (simplify $ Minus b d) a
simplify (Minus (Mult a b) (Mult c d)) | a==d = simplify $ Mult (simplify $ Minus b c) a
simplify (Minus (Mult a b) (Mult c d)) | b==c = simplify $ Mult (simplify $ Minus a d) b
simplify (Minus (Mult a b) (Mult c d)) | b==d = simplify $ Mult (simplify $ Minus a c) b
simplify (Mult (Abs a) (Abs b)) = simplify $ Abs (simplify $ Mult a b)
simplify (Div (Abs a) (Abs b)) = simplify $ Abs (simplify $ Div a b)
simplify (ColSize (ColRange l h)) = simplify $ Plus (Const 1) $ simplify $ Minus h l
simplify (At (ColSlice f _ c) i) = simplify $ At c (f i)
simplify (At (ColMap m c) i) = simplify $ m $ simplify $ At c i
simplify t@(At (ColCat c1 c2) c@(Const p)) = case simplify (ColSize c1) of
Const l | p<l -> simplify $ At c1 c
Const l | p>=l -> simplify $ At c2 (Const $ p-l)
- level 3 ( results in three recursive calls to simplify )
simplify (ColSize (ColCat a b)) = simplify $ Plus (simplify $ ColSize a) (simplify $ ColSize b)
reordering rules ( do not decrease # of variables or # of tree nodes , but normalize an expression in such a way that the same normalization can not be applied anymore - possibly because that can only occur in a case already matched by a simplification rule above )
- level 1
simplify (Plus a (Const c)) = simplify $ Plus (Const c) a
simplify (Minus a (Const c)) = simplify $ Plus (Const (-c)) a
simplify (Mult a (Const c)) = simplify $ Mult (Const c) a
simplify (Mult (Const (-1)) a) = simplify $ Minus (Const 0) a
- level 2
simplify (Mult t@(Const c) (Plus (Const a) b)) = simplify $ Plus (Const (a*c)) (simplify $ Mult t b)
simplify (Mult t@(Const c) (Minus (Const a) b)) = simplify $ Minus (Const (a*c)) (simplify $ Mult t b)
simplify (Plus a (Plus t@(Const b) c)) = simplify $ Plus t (simplify $ Plus a c)
simplify (Plus a (Minus t@(Const b) c)) = simplify $ Plus t (simplify $ Minus a c)
simplify (Minus a (Plus (Const b) c)) = simplify $ Plus (Const (-b)) (simplify $ Minus a c)
simplify (Minus a (Minus (Const b) c)) = simplify $ Plus (Const (-b)) (simplify $ Plus a c)
simplify (Mult a (Mult t@(Const b) c)) = simplify $ Mult t (simplify $ Mult a c)
simplify (Plus (Plus t@(Const a) b) c) = simplify $ Plus t (simplify $ Plus b c)
simplify (Plus (Minus t@(Const a) b) c) = simplify $ Plus t (simplify $ Minus c b)
simplify (Minus (Plus t@(Const a) b) c) = simplify $ Plus t (simplify $ Minus b c)
simplify (Minus (Minus t@(Const a) b) c) = simplify $ Minus t (simplify $ Plus b c)
simplify (Mult (Mult t@(Const a) b) c) = simplify $ Mult t (simplify $ Mult b c)
simplify (Mult a (Minus t@(Const 0) b)) = simplify $ Minus t (simplify $ Mult a b)
simplify (Mult (Minus t@(Const 0) b) a) = simplify $ Minus t (simplify $ Mult a b)
simplify (Div (Minus t@(Const 0) a) b) = simplify $ Minus t (simplify $ Div a b)
simplify (Div a (Minus t@(Const 0) b)) = simplify $ Minus t (simplify $ Div a b)
simplify a = a
colSimplify :: (Eq s, Eq c, Eq b) => ColExpr s c b -> ColExpr s c b
colSimplify t@(ColTerm _) = t
- level 1
colSimplify (ColMap f1 (ColMap f2 c)) = colSimplify $ ColMap (f1.f2) c
colSimplify (ColMap f (ColList l)) = colSimplify $ ColList (map f l)
- level 2
colSimplify (ColSlice p1 l1 (ColSlice p2 l2 c)) = colSimplify $ ColSlice (p1 . p2) l1 c
- level 2
colSimplify (ColCat (ColCat c1 c2) c3) = colSimplify $ ColCat c1 (colSimplify $ ColCat c2 c3)
colSimplify (ColSlice p l (ColMap f c)) = colSimplify $ ColMap f $ colSimplify $ ColSlice p l c
colSimplify x = x
boolSimplify :: (Eq s, Eq c, Eq b) => BoolExpr s c b -> BoolExpr s c b
boolSimplify t@(BoolTerm _) = t
boolSimplify t@(BoolConst _) = t
boolSimplify (BoolAnd (BoolConst False) _) = BoolConst False
boolSimplify (BoolAnd (BoolConst True) a) = a
boolSimplify (BoolAnd _ (BoolConst False)) = BoolConst False
boolSimplify (BoolAnd a (BoolConst True)) = a
boolSimplify (BoolOr (BoolConst True) _) = BoolConst True
boolSimplify (BoolOr (BoolConst False) a) = a
boolSimplify (BoolOr _ (BoolConst True)) = BoolConst True
boolSimplify (BoolOr a (BoolConst False)) = a
boolSimplify (BoolNot (BoolConst a)) = BoolConst (not a)
boolSimplify (BoolEqual (BoolConst True) a) = a
boolSimplify (BoolEqual a (BoolConst True)) = a
boolSimplify (BoolNot (BoolNot a)) = a
boolSimplify (BoolOr a b) | a==b = a
boolSimplify (BoolAnd a b) | a==b = a
boolSimplify (BoolEqual a b) | a==b = BoolConst False
boolSimplify (Rel (Const a) r (Const b)) = BoolConst $ relCheck a r b
boolSimplify (BoolAll f (ColList [])) = BoolConst True
boolSimplify (BoolAny f (ColList [])) = BoolConst False
boolSimplify (BoolAll f (ColList [a])) = f a
boolSimplify (BoolAny f (ColList [a])) = f a
boolSimplify (ColEqual (ColList []) (ColList [])) = BoolConst True
boolSimplify (ColEqual (ColList []) (ColList _)) = BoolConst False
boolSimplify (ColEqual (ColList _) (ColList [])) = BoolConst False
boolSimplify (BoolCond (BoolConst True) t _) = t
boolSimplify (BoolCond (BoolConst False) _ f) = f
- level 1
boolSimplify (BoolEqual (BoolNot a) (BoolNot b)) = boolSimplify $ BoolEqual a b
boolSimplify (BoolEqual (BoolConst False) a) = boolSimplify $ BoolNot a
boolSimplify (BoolEqual a (BoolConst False)) = boolSimplify $ BoolNot a
boolSimplify (BoolNot (Rel a EREqual b)) = boolSimplify $ Rel a ERDiff b
boolSimplify (BoolNot (Rel a ERDiff b)) = boolSimplify $ Rel a EREqual b
boolSimplify (BoolAll f (ColList [a,b])) = boolSimplify $ f a `BoolAnd` f b
boolSimplify (BoolAny f (ColList [a,b])) = boolSimplify $ f a `BoolOr` f b
boolSimplify (ColEqual (ColList [a]) (ColList [b])) = boolSimplify $ Rel a EREqual b
boolSimplify (Rel (Channel a) EREqual (Channel b)) = boolSimplify $ BoolEqual a b
boolSimplify (BoolCond (BoolNot c) t f) = boolSimplify $ BoolCond c f t
- level 2
boolSimplify (BoolAnd (BoolNot a) (BoolNot b)) = boolSimplify $ BoolNot $ boolSimplify $ BoolOr a b
boolSimplify (BoolOr (BoolNot a) (BoolNot b)) = boolSimplify $ BoolNot $ boolSimplify $ BoolAnd a b
boolSimplify (Rel (Channel a) ERDiff (Channel b)) = boolSimplify $ BoolNot $ boolSimplify $ BoolEqual a b
boolSimplify a = a
collapse :: (Eq t, Eq c, Eq b) => Expr (Expr t c b) (ColExpr t c b) (BoolExpr t c b) -> Expr t c b
collapse (Term t) = t
collapse (Const i) = Const i
collapse (Plus a b) = simplify $ Plus (collapse a) (collapse b)
collapse (Minus a b) = simplify $ Minus (collapse a) (collapse b)
collapse (Mult a b) = simplify $ Mult (collapse a) (collapse b)
collapse (Div a b) = simplify $ Div (collapse a) (collapse b)
collapse (Mod a b) = simplify $ Mod (collapse a) (collapse b)
collapse (Abs a) = simplify $ Abs (collapse a)
collapse (At c a) = simplify $ At (colCollapse c) (collapse a)
collapse (ColSize c) = simplify $ ColSize (colCollapse c)
collapse (Fold f i c) = simplify $ Fold (\a b -> collapse $ f (Term a) (Term b)) (collapse i) (colCollapse c)
collapse (Channel b) = simplify $ Channel (boolCollapse b)
collapse (Cond c t e) = simplify $ Cond (boolCollapse c) (collapse t) (collapse e)
colCollapse :: (Eq t, Eq c, Eq b) => ColExpr (Expr t c b) (ColExpr t c b) (BoolExpr t c b) -> ColExpr t c b
colCollapse (ColTerm t) = t
colCollapse (ColList l) = colSimplify $ ColList $ map collapse l
colCollapse (ColMap f c) = colSimplify $ ColMap (\a -> collapse $ f (Term a)) (colCollapse c)
colCollapse (ColSlice p l c) = colSimplify $ ColSlice (\x -> collapse $ p (Term x)) (collapse l) (colCollapse c)
colCollapse (ColCat a b) = colSimplify $ ColCat (colCollapse a) (colCollapse b)
colCollapse (ColRange a b) = colSimplify $ ColRange (collapse a) (collapse b)
boolCollapse :: (Eq t, Eq c, Eq b) => BoolExpr (Expr t c b) (ColExpr t c b) (BoolExpr t c b) -> BoolExpr t c b
boolCollapse (BoolTerm t) = t
boolCollapse (BoolConst c) = BoolConst c
boolCollapse (BoolAnd a b) = boolSimplify $ BoolAnd (boolCollapse a) (boolCollapse b)
boolCollapse (BoolOr a b) = boolSimplify $ BoolOr (boolCollapse a) (boolCollapse b)
boolCollapse (BoolEqual a b) = boolSimplify $ BoolEqual (boolCollapse a) (boolCollapse b)
boolCollapse (BoolNot a) = boolSimplify $ BoolNot (boolCollapse a)
boolCollapse (Rel a r b) = boolSimplify $ Rel (collapse a) r (collapse b)
boolCollapse (BoolAll f c) = boolSimplify $ BoolAll (\a -> boolCollapse $ f (Term a)) (colCollapse c)
boolCollapse (BoolAny f c) = boolSimplify $ BoolAny (\a -> boolCollapse $ f (Term a)) (colCollapse c)
boolCollapse (ColEqual a b) = boolSimplify $ ColEqual (colCollapse a) (colCollapse b)
boolCollapse (Sorted b c) = boolSimplify $ Sorted b (colCollapse c)
boolCollapse (AllDiff b c) = boolSimplify $ AllDiff b (colCollapse c)
boolCollapse (BoolCond c t e) = boolSimplify $ BoolCond (boolCollapse c) (boolCollapse t) (boolCollapse e)
boolCollapse (Dom i c) = boolSimplify $ Dom (collapse i) (colCollapse c)
data WalkPhase = WalkPre | WalkSingle | WalkPost
deriving (Ord,Eq,Enum,Show)
data WalkResult = WalkSkip | WalkDescend
deriving (Ord,Eq,Enum,Show)
xwalker :: (Eq t, Eq c, Eq b, Monad m) => (WalkPhase -> m WalkResult) -> (Expr t c b -> WalkPhase -> m WalkResult, ColExpr t c b -> WalkPhase -> m WalkResult, BoolExpr t c b -> WalkPhase -> m WalkResult) -> ([Expr t c b],[ColExpr t c b],[BoolExpr t c b]) -> m ()
xwalker q f ([],[],[]) = do
q WalkSingle
return ()
xwalker q f (li,lc,lb) = do
r <- q WalkPre
case r of
WalkSkip -> return ()
WalkDescend -> do
mapM_ (\p -> walk p f) li
mapM_ (\p -> colWalk p f) lc
mapM_ (\p -> boolWalk p f) lb
q WalkPost
return ()
walker :: (Eq t, Eq c, Eq b, Monad m) => Expr t c b -> (Expr t c b -> WalkPhase -> m WalkResult, ColExpr t c b -> WalkPhase -> m WalkResult, BoolExpr t c b -> WalkPhase -> m WalkResult) -> ([Expr t c b],[ColExpr t c b],[BoolExpr t c b]) -> m ()
walker x f@(i,c,b) l = xwalker (i x) f l
colWalker :: (Eq t, Eq c, Eq b, Monad m) => ColExpr t c b -> (Expr t c b -> WalkPhase -> m WalkResult, ColExpr t c b -> WalkPhase -> m WalkResult, BoolExpr t c b -> WalkPhase -> m WalkResult) -> ([Expr t c b],[ColExpr t c b],[BoolExpr t c b]) -> m ()
colWalker x f@(i,c,b) l = xwalker (c x) f l
boolWalker :: (Eq t, Eq c, Eq b, Monad m) => BoolExpr t c b -> (Expr t c b -> WalkPhase -> m WalkResult, ColExpr t c b -> WalkPhase -> m WalkResult, BoolExpr t c b -> WalkPhase -> m WalkResult) -> ([Expr t c b],[ColExpr t c b],[BoolExpr t c b]) -> m ()
boolWalker x f@(i,c,b) l = xwalker (b x) f l
walk :: (Eq t, Eq c, Eq b, Monad m) => Expr t c b -> (Expr t c b -> WalkPhase -> m WalkResult, ColExpr t c b -> WalkPhase -> m WalkResult, BoolExpr t c b -> WalkPhase -> m WalkResult) -> m ()
walk x@(Term _) f = walker x f ([],[],[])
walk x@(Const _) f = walker x f ([],[],[])
walk x@(Plus a b) f = walker x f ([a,b],[],[])
walk x@(Minus a b) f = walker x f ([a,b],[],[])
walk x@(Mult a b) f = walker x f ([a,b],[],[])
walk x@(Div a b) f = walker x f ([a,b],[],[])
walk x@(Mod a b) f = walker x f ([a,b],[],[])
walk x@(Abs a) f = walker x f ([a],[],[])
walk x@(At c a) f = walker x f ([a],[c],[])
walk x@(ColSize c) f = walker x f ([],[c],[])
walk x@(Fold _ i c) f = walker x f ([i],[c],[])
walk x@(Channel b) f = walker x f ([],[],[b])
walk x@(Cond c t e) f = walker x f ([t,e],[],[c])
walk x@(ExprHole _) f = return ()
colWalk x@(ColTerm _) f = colWalker x f ([],[],[])
colWalk x@(ColList l) f = colWalker x f (l,[],[])
colWalk x@(ColMap _ c) f = colWalker x f ([],[c],[])
colWalk x@(ColSlice _ l c) f = colWalker x f ([l],[c],[])
colWalk x@(ColCat a b) f = colWalker x f ([],[a,b],[])
colWalk x@(ColRange a b) f = colWalker x f ([a,b],[],[])
boolWalk x@(BoolTerm _) f = boolWalker x f ([],[],[])
boolWalk x@(BoolConst _) f = boolWalker x f ([],[],[])
boolWalk x@(BoolAnd a b) f = boolWalker x f ([],[],[a,b])
boolWalk x@(BoolOr a b) f = boolWalker x f ([],[],[a,b])
boolWalk x@(BoolEqual a b) f = boolWalker x f ([],[],[a,b])
boolWalk x@(BoolNot a) f = boolWalker x f ([],[],[a])
boolWalk x@(Rel a _ b) f = boolWalker x f ([a,b],[],[])
boolWalk x@(BoolAll _ c) f = boolWalker x f ([],[c],[])
boolWalk x@(BoolAny _ c) f = boolWalker x f ([],[c],[])
boolWalk x@(ColEqual a b) f = boolWalker x f ([],[a,b],[])
boolWalk x@(Sorted _ c) f = boolWalker x f ([],[c],[])
boolWalk x@(AllDiff _ c) f = boolWalker x f ([],[c],[])
boolWalk x@(BoolCond c t e) f = boolWalker x f ([],[],[c,t,e])
boolWalk x@(Dom i c) f = boolWalker x f ([i],[c],[])
|
af026823a717eb2027585d738f3b1c286b4d7d59c99b08ce64c09b4455fe3a14 | achirkin/qua-kit | QuaViewSettings.hs | {-# OPTIONS_HADDOCK hide, prune #-}
# LANGUAGE CPP #
module Handler.QuaViewSettings
( getQuaViewEditorSettingsR
, getQuaViewExerciseSettingsR
) where
import Import
import qualified QuaTypes
import System.FilePath (takeDirectory)
import qualified Data.Text as Text
-- | If a user is not a student, use these generic settings
-- that give full access to qua-view functions
getQuaViewEditorSettingsR :: Handler Value
getQuaViewEditorSettingsR
= quaViewSettingsR QuaViewEditorR Nothing Nothing
QuaTypes.Permissions
{ canEditProperties = True
, canEraseReloadGeometry = True
, canAddDeleteGeometry = True
, canDownloadGeometry = True
, canModifyStaticObjects = True
, showHiddenProperties = True
, showShareButton = False
, isViewerOnly = False
}
-- | These settings are for students when we know their exercise id,
-- can save exercise submissions, write reviews, etc.
getQuaViewExerciseSettingsR :: ExerciseId -> UserId -> Handler Value
getQuaViewExerciseSettingsR exId uId = do
e <- runDB $ get404 exId
quaViewSettingsR (SubmissionR exId uId) (Just exId) (Just uId)
QuaTypes.Permissions
{ canEditProperties = exerciseCanEditProperties e
, canEraseReloadGeometry = False
, canAddDeleteGeometry = exerciseCanAddDeleteGeom e
, canDownloadGeometry = False
, canModifyStaticObjects = False
, showHiddenProperties = False
, showShareButton = True
, isViewerOnly = False
}
quaViewSettingsR :: Route App
-> Maybe ExerciseId
-> Maybe UserId
-> QuaTypes.Permissions
-> Handler Value
#if EXPO
quaViewSettingsR curRoute mcExId mAuthorId _ = do
app <- getYesod
req <- waiRequest
let appr = getApprootText guessApproot app req
routeUrl route = yesodRender app appr route []
showDemo = isNothing mcExId || isNothing mAuthorId
returnJson QuaTypes.Settings
{ loggingUrl = Nothing
, luciUrl = Nothing
, getSubmissionGeometryUrl =
if showDemo
then Just . routeUrl $ StaticR data_demo_scenario
else fmap routeUrl $ SubmissionGeometryR <$> mcExId <*> mAuthorId
, getSubmissionInfoUrl = fmap routeUrl $ SubmissionInfoR <$> mcExId <*> mAuthorId
, putSubmissionUrl = Nothing
, reviewSettingsUrl = fmap routeUrl $ QuaViewReviewSettingsR <$> mcExId <*> mAuthorId
, viewUrl = routeUrl curRoute
, jsRootUrl = Text.pack . takeDirectory . Text.unpack . routeUrl $ StaticR js_qua_view_js
, permissions = QuaTypes.Permissions
{ canEditProperties = showDemo
, canEraseReloadGeometry = showDemo
, canAddDeleteGeometry = showDemo
, canDownloadGeometry = True
, canModifyStaticObjects = False
, showHiddenProperties = False
, showShareButton = False
, isViewerOnly = not showDemo
}
}
#else
quaViewSettingsR curRoute mcExId mAuthorId perms' = do
app <- getYesod
req <- waiRequest
mUserId <- maybeAuthId
-- show a submission url iff authorId == userId
let filteredSubmissionR = case (==) <$> mUserId <*> mAuthorId of
Just True -> SubmissionR <$> mcExId <*> mAuthorId
Nothing -> Nothing
Just False -> Nothing
-- set viewer to not be able to do anything
perms = case (==) <$> mUserId <*> mAuthorId of
Just True -> perms'
Nothing -> perms'
Just False -> perms'
{ QuaTypes.canEditProperties = False
, QuaTypes.canEraseReloadGeometry = False
, QuaTypes.canAddDeleteGeometry = False
, QuaTypes.canDownloadGeometry = False
, QuaTypes.canModifyStaticObjects = False
, QuaTypes.isViewerOnly = True
}
let appr = getApprootText guessApproot app req
routeUrl route = yesodRender app appr route []
returnJson QuaTypes.Settings {
loggingUrl = Just $ "ws" <> drop 4 (routeUrl QVLoggingR)
, luciUrl = ("ws" <> drop 4 (routeUrl LuciR)) <$ mUserId
, getSubmissionGeometryUrl =
if isNothing mUserId && isNothing mcExId && isNothing mAuthorId
then Just . routeUrl $ StaticR data_demo_scenario
else fmap routeUrl $ SubmissionGeometryR <$> mcExId <*> mAuthorId
, getSubmissionInfoUrl = fmap routeUrl $ SubmissionInfoR <$> mcExId <*> mAuthorId
, putSubmissionUrl = routeUrl <$> filteredSubmissionR
, reviewSettingsUrl = fmap routeUrl $ QuaViewReviewSettingsR <$> mcExId <*> mAuthorId
, viewUrl = routeUrl curRoute
, jsRootUrl = Text.pack . takeDirectory . Text.unpack . routeUrl $ StaticR js_qua_view_js
, permissions = perms
}
#endif
| null | https://raw.githubusercontent.com/achirkin/qua-kit/9f859e2078d5f059fb87b2f6baabcde7170d4e95/apps/hs/qua-server/src/Handler/QuaViewSettings.hs | haskell | # OPTIONS_HADDOCK hide, prune #
| If a user is not a student, use these generic settings
that give full access to qua-view functions
| These settings are for students when we know their exercise id,
can save exercise submissions, write reviews, etc.
show a submission url iff authorId == userId
set viewer to not be able to do anything | # LANGUAGE CPP #
module Handler.QuaViewSettings
( getQuaViewEditorSettingsR
, getQuaViewExerciseSettingsR
) where
import Import
import qualified QuaTypes
import System.FilePath (takeDirectory)
import qualified Data.Text as Text
getQuaViewEditorSettingsR :: Handler Value
getQuaViewEditorSettingsR
= quaViewSettingsR QuaViewEditorR Nothing Nothing
QuaTypes.Permissions
{ canEditProperties = True
, canEraseReloadGeometry = True
, canAddDeleteGeometry = True
, canDownloadGeometry = True
, canModifyStaticObjects = True
, showHiddenProperties = True
, showShareButton = False
, isViewerOnly = False
}
getQuaViewExerciseSettingsR :: ExerciseId -> UserId -> Handler Value
getQuaViewExerciseSettingsR exId uId = do
e <- runDB $ get404 exId
quaViewSettingsR (SubmissionR exId uId) (Just exId) (Just uId)
QuaTypes.Permissions
{ canEditProperties = exerciseCanEditProperties e
, canEraseReloadGeometry = False
, canAddDeleteGeometry = exerciseCanAddDeleteGeom e
, canDownloadGeometry = False
, canModifyStaticObjects = False
, showHiddenProperties = False
, showShareButton = True
, isViewerOnly = False
}
quaViewSettingsR :: Route App
-> Maybe ExerciseId
-> Maybe UserId
-> QuaTypes.Permissions
-> Handler Value
#if EXPO
quaViewSettingsR curRoute mcExId mAuthorId _ = do
app <- getYesod
req <- waiRequest
let appr = getApprootText guessApproot app req
routeUrl route = yesodRender app appr route []
showDemo = isNothing mcExId || isNothing mAuthorId
returnJson QuaTypes.Settings
{ loggingUrl = Nothing
, luciUrl = Nothing
, getSubmissionGeometryUrl =
if showDemo
then Just . routeUrl $ StaticR data_demo_scenario
else fmap routeUrl $ SubmissionGeometryR <$> mcExId <*> mAuthorId
, getSubmissionInfoUrl = fmap routeUrl $ SubmissionInfoR <$> mcExId <*> mAuthorId
, putSubmissionUrl = Nothing
, reviewSettingsUrl = fmap routeUrl $ QuaViewReviewSettingsR <$> mcExId <*> mAuthorId
, viewUrl = routeUrl curRoute
, jsRootUrl = Text.pack . takeDirectory . Text.unpack . routeUrl $ StaticR js_qua_view_js
, permissions = QuaTypes.Permissions
{ canEditProperties = showDemo
, canEraseReloadGeometry = showDemo
, canAddDeleteGeometry = showDemo
, canDownloadGeometry = True
, canModifyStaticObjects = False
, showHiddenProperties = False
, showShareButton = False
, isViewerOnly = not showDemo
}
}
#else
quaViewSettingsR curRoute mcExId mAuthorId perms' = do
app <- getYesod
req <- waiRequest
mUserId <- maybeAuthId
let filteredSubmissionR = case (==) <$> mUserId <*> mAuthorId of
Just True -> SubmissionR <$> mcExId <*> mAuthorId
Nothing -> Nothing
Just False -> Nothing
perms = case (==) <$> mUserId <*> mAuthorId of
Just True -> perms'
Nothing -> perms'
Just False -> perms'
{ QuaTypes.canEditProperties = False
, QuaTypes.canEraseReloadGeometry = False
, QuaTypes.canAddDeleteGeometry = False
, QuaTypes.canDownloadGeometry = False
, QuaTypes.canModifyStaticObjects = False
, QuaTypes.isViewerOnly = True
}
let appr = getApprootText guessApproot app req
routeUrl route = yesodRender app appr route []
returnJson QuaTypes.Settings {
loggingUrl = Just $ "ws" <> drop 4 (routeUrl QVLoggingR)
, luciUrl = ("ws" <> drop 4 (routeUrl LuciR)) <$ mUserId
, getSubmissionGeometryUrl =
if isNothing mUserId && isNothing mcExId && isNothing mAuthorId
then Just . routeUrl $ StaticR data_demo_scenario
else fmap routeUrl $ SubmissionGeometryR <$> mcExId <*> mAuthorId
, getSubmissionInfoUrl = fmap routeUrl $ SubmissionInfoR <$> mcExId <*> mAuthorId
, putSubmissionUrl = routeUrl <$> filteredSubmissionR
, reviewSettingsUrl = fmap routeUrl $ QuaViewReviewSettingsR <$> mcExId <*> mAuthorId
, viewUrl = routeUrl curRoute
, jsRootUrl = Text.pack . takeDirectory . Text.unpack . routeUrl $ StaticR js_qua_view_js
, permissions = perms
}
#endif
|
484c39f41f0b32fc5dd66696a57f534bf6ed961f7e8e5ccf7e52a78c69a950a9 | simon-katz/lein-nomis-ns-graph | nomis_re_com_utils.cljs | (ns nomisdraw.utils.nomis-re-com-utils
(:require [reagent.core :as r]
[re-com.core :as re]))
;;; TODO: Doc.
;;; Including:
- The ` : need to be # ' -d for interactive development .
;;; (Hmmm, so don't use anonymous functions. Painful.)
TODO : Use a schema ( or a clojure.spec spec ) for options .
(defonce ^:private options-s-atom
(atom {}))
(defn ^:private options-&-uniquifier>selected-id-atom [options uniquifier]
(let [k [options uniquifier]]
(or (get @options-s-atom
k)
(let [a (r/atom (-> options
first
:id))]
(swap! options-s-atom
assoc
k
a)
a))))
(defn dropdown-and-chosen-item [& {:keys [options
uniquifier
outer-style
inner-style]
:or {:uniquifier ::default}}]
(let [selected-id-atom (options-&-uniquifier>selected-id-atom options
uniquifier)]
[re/v-box
:style outer-style
:width "700px"
:gap "10px"
:children [[re/h-box
:gap "10px"
:align :center
:children [[re/label :label "Select a demo"]
[re/single-dropdown
:choices options
:model selected-id-atom
:width "300px"
:on-change #(reset! selected-id-atom %)]]]
(re/box
:style inner-style
:child
(let [fun (->> options
(filter #(= @selected-id-atom
(:id %)))
first
:fun)]
[fun]))]]))
| null | https://raw.githubusercontent.com/simon-katz/lein-nomis-ns-graph/e30d8af3022ee1d9b1c49571847925c45617e66b/test-resources/example-projects/nomisdraw/src/cljs/nomisdraw/utils/nomis_re_com_utils.cljs | clojure | TODO: Doc.
Including:
(Hmmm, so don't use anonymous functions. Painful.) | (ns nomisdraw.utils.nomis-re-com-utils
(:require [reagent.core :as r]
[re-com.core :as re]))
- The ` : need to be # ' -d for interactive development .
TODO : Use a schema ( or a clojure.spec spec ) for options .
(defonce ^:private options-s-atom
(atom {}))
(defn ^:private options-&-uniquifier>selected-id-atom [options uniquifier]
(let [k [options uniquifier]]
(or (get @options-s-atom
k)
(let [a (r/atom (-> options
first
:id))]
(swap! options-s-atom
assoc
k
a)
a))))
(defn dropdown-and-chosen-item [& {:keys [options
uniquifier
outer-style
inner-style]
:or {:uniquifier ::default}}]
(let [selected-id-atom (options-&-uniquifier>selected-id-atom options
uniquifier)]
[re/v-box
:style outer-style
:width "700px"
:gap "10px"
:children [[re/h-box
:gap "10px"
:align :center
:children [[re/label :label "Select a demo"]
[re/single-dropdown
:choices options
:model selected-id-atom
:width "300px"
:on-change #(reset! selected-id-atom %)]]]
(re/box
:style inner-style
:child
(let [fun (->> options
(filter #(= @selected-id-atom
(:id %)))
first
:fun)]
[fun]))]]))
|
8e9ea56fe5404827f88332b0a5cde1165ae499cc509ab85bf05a0a19ed04fd15 | skanev/playground | 25.scm | SICP exercise 1.25
;
complains that we went to a lot of extra work in writing
; expmod. After all, she says, since we already know how to compute exponents,
; we could have simply written
;
( define ( expmod base exp m )
; (remainder (fast-expt base exp) m))
;
; Is she correct? Would this procedure serve as well for our fast prime tester?
; Explain.
; She is correct. We can define expmod that way and it would certainly return
; correct results. However, it will not deserve being called "fast-prime?",
; since it quickly becomes dramatically slower. Here is a comparison:
;
; +----------------+--------------------+
| exercise 24 | exercise 25 |
; +----------------+--------------------+
| 0.101074218750 | 0.751953125000 |
| 0.004150390625 | 0.282958984375 |
| 0.002929687500 | 0.229980468750 |
| 0.003173828125 | 7.984863281250 |
; | 0.004150390625 | 10.800781250000 |
| 0.003173828125 | 5.987060546875 |
| 0.077880859375 | 419.326904296875 |
| 0.024169921875 | 460.801025390625 |
; | 0.022949218750 | 401.984130859375 |
| 0.028076171875 | 12811.398193359375 |
; | 0.020019531250 | 15219.705078125000 |
; | 0.028076171870 | 18424.709228515620 |
; +----------------+--------------------+
;
; This happens, because we end up calculating exponents with very large numbers
Multiplication and division is particularly slow with those . Allysa 's expmod
; quickly starts multiplying them, while the one we wrote goes into great
; lengths of avoiding it.
(define (fast-expt base power)
(define (iter a b n)
(cond ((= n 0) a)
((even? n) (iter a (* b b) (/ n 2)))
(else (iter (* a b) b (- n 1)))))
(iter 1 base power))
(define (expmod base exp m)
(remainder (fast-expt base exp) m))
(define (square n)
(* n n))
(define (fermat-test n)
(define (try-it a)
(= (expmod a n n) a))
(try-it (+ 1 (random (- n 1)))))
(define (fast-prime? n times)
(cond ((= times 0) true)
((fermat-test n) (fast-prime? n (- times 1)))
(else false)))
(define (timed-prime-test n)
(newline)
(display n)
(start-prime-test n (runtime)))
(define (start-prime-test n start-time)
(if (fast-prime? n 1)
(report-prime (- (runtime) start-time))
(void)))
(define (runtime)
(current-inexact-milliseconds))
(define (report-prime elapsed-time)
(display " *** ")
(display elapsed-time))
(timed-prime-test 1009)
(timed-prime-test 1013)
(timed-prime-test 1019)
(timed-prime-test 10007)
(timed-prime-test 10009)
(timed-prime-test 10037)
(timed-prime-test 100003)
(timed-prime-test 100019)
(timed-prime-test 100043)
(timed-prime-test 1000003)
(timed-prime-test 1000033)
(timed-prime-test 1000037)
| null | https://raw.githubusercontent.com/skanev/playground/d88e53a7f277b35041c2f709771a0b96f993b310/scheme/sicp/01/25.scm | scheme |
expmod. After all, she says, since we already know how to compute exponents,
we could have simply written
(remainder (fast-expt base exp) m))
Is she correct? Would this procedure serve as well for our fast prime tester?
Explain.
She is correct. We can define expmod that way and it would certainly return
correct results. However, it will not deserve being called "fast-prime?",
since it quickly becomes dramatically slower. Here is a comparison:
+----------------+--------------------+
+----------------+--------------------+
| 0.004150390625 | 10.800781250000 |
| 0.022949218750 | 401.984130859375 |
| 0.020019531250 | 15219.705078125000 |
| 0.028076171870 | 18424.709228515620 |
+----------------+--------------------+
This happens, because we end up calculating exponents with very large numbers
quickly starts multiplying them, while the one we wrote goes into great
lengths of avoiding it. | SICP exercise 1.25
complains that we went to a lot of extra work in writing
( define ( expmod base exp m )
| exercise 24 | exercise 25 |
| 0.101074218750 | 0.751953125000 |
| 0.004150390625 | 0.282958984375 |
| 0.002929687500 | 0.229980468750 |
| 0.003173828125 | 7.984863281250 |
| 0.003173828125 | 5.987060546875 |
| 0.077880859375 | 419.326904296875 |
| 0.024169921875 | 460.801025390625 |
| 0.028076171875 | 12811.398193359375 |
Multiplication and division is particularly slow with those . Allysa 's expmod
(define (fast-expt base power)
(define (iter a b n)
(cond ((= n 0) a)
((even? n) (iter a (* b b) (/ n 2)))
(else (iter (* a b) b (- n 1)))))
(iter 1 base power))
(define (expmod base exp m)
(remainder (fast-expt base exp) m))
(define (square n)
(* n n))
(define (fermat-test n)
(define (try-it a)
(= (expmod a n n) a))
(try-it (+ 1 (random (- n 1)))))
(define (fast-prime? n times)
(cond ((= times 0) true)
((fermat-test n) (fast-prime? n (- times 1)))
(else false)))
(define (timed-prime-test n)
(newline)
(display n)
(start-prime-test n (runtime)))
(define (start-prime-test n start-time)
(if (fast-prime? n 1)
(report-prime (- (runtime) start-time))
(void)))
(define (runtime)
(current-inexact-milliseconds))
(define (report-prime elapsed-time)
(display " *** ")
(display elapsed-time))
(timed-prime-test 1009)
(timed-prime-test 1013)
(timed-prime-test 1019)
(timed-prime-test 10007)
(timed-prime-test 10009)
(timed-prime-test 10037)
(timed-prime-test 100003)
(timed-prime-test 100019)
(timed-prime-test 100043)
(timed-prime-test 1000003)
(timed-prime-test 1000033)
(timed-prime-test 1000037)
|
251417a7d12dbe5335734c09c082beb793539af72892fea53bf53bd470ae4c5f | ajnsit/wai-routes | RouteAttrs.hs | # LANGUAGE TemplateHaskell #
# LANGUAGE RecordWildCards #
module Routes.TH.RouteAttrs
( mkRouteAttrsInstance
) where
import Routes.TH.Types
import Routes.Class
import Language.Haskell.TH.Syntax
import Data.Set (fromList)
import Data.Text (pack)
mkRouteAttrsInstance :: Cxt -> Type -> [ResourceTree a] -> Q Dec
mkRouteAttrsInstance cxt typ ress = do
clauses <- mapM (goTree id) ress
return $ instanceD cxt (ConT ''RouteAttrs `AppT` typ)
[ FunD 'routeAttrs $ concat clauses
]
goTree :: (Pat -> Pat) -> ResourceTree a -> Q [Clause]
goTree front (ResourceLeaf res) = return <$> goRes front res
goTree front (ResourceParent name _check pieces trees) =
concat <$> mapM (goTree front') trees
where
ignored = (replicate toIgnore WildP ++) . return
toIgnore = length $ filter isDynamic pieces
isDynamic Dynamic{} = True
isDynamic Static{} = False
front' = front . ConP (mkName name) . ignored
goRes :: (Pat -> Pat) -> Resource a -> Q Clause
goRes front Resource {..} =
return $ Clause
[front $ RecP (mkName resourceName) []]
(NormalB $ VarE 'fromList `AppE` ListE (map toText resourceAttrs))
[]
where
toText s = VarE 'pack `AppE` LitE (StringL s)
instanceD :: Cxt -> Type -> [Dec] -> Dec
instanceD = InstanceD Nothing
| null | https://raw.githubusercontent.com/ajnsit/wai-routes/4d6b240af57a95353373ddba81c4905db0234459/src/Routes/TH/RouteAttrs.hs | haskell | # LANGUAGE TemplateHaskell #
# LANGUAGE RecordWildCards #
module Routes.TH.RouteAttrs
( mkRouteAttrsInstance
) where
import Routes.TH.Types
import Routes.Class
import Language.Haskell.TH.Syntax
import Data.Set (fromList)
import Data.Text (pack)
mkRouteAttrsInstance :: Cxt -> Type -> [ResourceTree a] -> Q Dec
mkRouteAttrsInstance cxt typ ress = do
clauses <- mapM (goTree id) ress
return $ instanceD cxt (ConT ''RouteAttrs `AppT` typ)
[ FunD 'routeAttrs $ concat clauses
]
goTree :: (Pat -> Pat) -> ResourceTree a -> Q [Clause]
goTree front (ResourceLeaf res) = return <$> goRes front res
goTree front (ResourceParent name _check pieces trees) =
concat <$> mapM (goTree front') trees
where
ignored = (replicate toIgnore WildP ++) . return
toIgnore = length $ filter isDynamic pieces
isDynamic Dynamic{} = True
isDynamic Static{} = False
front' = front . ConP (mkName name) . ignored
goRes :: (Pat -> Pat) -> Resource a -> Q Clause
goRes front Resource {..} =
return $ Clause
[front $ RecP (mkName resourceName) []]
(NormalB $ VarE 'fromList `AppE` ListE (map toText resourceAttrs))
[]
where
toText s = VarE 'pack `AppE` LitE (StringL s)
instanceD :: Cxt -> Type -> [Dec] -> Dec
instanceD = InstanceD Nothing
| |
efa6f3974db4e0a2bcef236661ebc11418bba9d45958094ba2caa3d16828f4a8 | G-Corp/kafe | kafe.erl | @author < >
@author < >
@author < >
2014 - 2015 Finexkap , 2015 G - Corp , 2015 - 2016 BotsUnit
@since 2014
% @doc
A client for Erlang
%
% This module only implement the <a href="+Guide+To+The+Kafka+Protocol">Kafak Protocol</a>.
% @end
-module(kafe).
-compile([{parse_transform, bristow_transform},
{parse_transform, lager_transform}]).
-include("../include/kafe.hrl").
-include_lib("kernel/include/inet.hrl").
% Public API
-export([
start/0,
brokers/0,
api_versions/0,
metadata/0,
metadata/1,
offset/0,
offset/1,
offset/2,
produce/1,
produce/2,
produce/3,
default_key_to_partition/2,
fetch/1,
fetch/2,
fetch/3,
list_groups/0,
list_groups/1,
group_coordinator/1,
join_group/1,
join_group/2,
sync_group/4,
heartbeat/3,
leave_group/2,
describe_group/1,
default_protocol/4,
offset_fetch/1,
offset_fetch/2,
offset_commit/2,
offset_commit/4,
offset_commit/5
]).
-export([
start_consumer/3,
stop_consumer/1,
consumer_infos/1,
consumer_groups/0,
offsets/2,
offsets/3
]).
% Internal API
-export([
number_of_brokers/0,
topics/0,
partitions/1,
max_offset/1,
max_offset/2,
partition_for_offset/2,
api_version/0,
api_version/1,
update_brokers/0
]).
-export_type([describe_group/0, group_commit_identifier/0]).
-type error_code() :: no_error
| unknown
| offset_out_of_range
| invalid_message
| unknown_topic_or_partition
| invalid_message_size
| leader_not_available
| not_leader_for_partition
| request_timed_out
| broker_not_available
| replica_not_available
| message_size_too_large
| stale_controller_epoch
| offset_metadata_too_large
| offsets_load_in_progress
| consumer_coordinator_not_available
| not_coordinator_for_consumer.
-type metadata() :: #{brokers => [#{host => binary(),
id => integer(),
port => port()}],
topics => [#{error_code => error_code(),
name => binary(),
partitions => [#{error_code => error_code(),
id => integer(),
isr => [integer()],
leader => integer(),
replicas => [integer()]}]}]}.
-type topic() :: binary().
-type key() :: term().
-type value() :: binary().
-type partition() :: integer().
-type topics() :: [topic()] | [{topic(), [{partition(), integer(), integer()}]}] | [{topic(), [{partition(), integer()}]}].
-type topic_partition_info() :: #{name => binary(),
partitions => [#{error_code => error_code(),
id => integer(),
offset => integer(),
timestamp => integer()}
| #{error_code => error_code(),
id => integer(),
offsets => [integer()]}]}.
-type produce_options() :: #{timeout => integer(),
required_acks => integer(),
partition => integer(),
key_to_partition => fun((binary(), term()) -> integer())}.
-type fetch_options() :: #{partition => integer(),
offset => integer(),
response_max_bytes => integer(),
max_bytes => integer(),
min_bytes => integer(),
max_wait_time => integer(),
retrieve => first | all}.
-type message_set() :: #{name => binary(),
partitions => [#{partition => integer(),
error_code => error_code(),
high_watermark_offset => integer(),
messages => [#{offset => integer(),
crc => integer(),
magic_byte => 0 | 1,
attributes => integer(),
timestamp => integer(),
key => binary(),
value => binary()}]}]}.
-type group_coordinator() :: #{error_code => error_code(),
coordinator_id => integer(),
coordinator_host => binary(),
coordinator_port => port()}.
-type offset_fetch_options() :: [binary()] | [{binary(), [integer()]}].
-type offset_fetch_set() :: #{name => binary(),
partitions_offset => [#{partition => integer(),
offset => integer(),
metadata_info => binary(),
error_code => error_code()}]}.
-type offset_commit_set() :: #{name => binary(),
partitions => [#{partition => integer(),
error_code => error_code()}]}.
-type offset_commit_topics() :: [{binary(), [{integer(), integer(), integer(), binary()}]}]
| [{binary(), [{integer(), integer(), binary()}]}]
| [{binary(), [{integer(), integer(), integer()}]}]
| [{binary(), [{integer(), integer()}]}].
-type offset_commit_topics_v1() :: [{binary(), [{integer(), integer(), integer(), binary()}]}].
-type broker_id() :: atom().
-type broker_name() :: string().
-type group() :: #{group_id => binary(), protocol_type => binary()}.
-type groups() :: #{error_code => error_code(),
groups => [group()]}.
-type groups_list() :: [#{broker => broker_name(),
groups => groups()}].
-type group_member() :: #{member_id => binary(),
member_metadata => binary()}.
-type group_join() :: #{error_code => error_code(),
generation_id => integer(),
protocol_group => binary(),
leader_id => binary(),
member_id => binary(),
members => [group_member()]}.
-type protocol() :: binary().
-type join_group_options() :: #{session_timeout => integer(),
rebalance_timeout => integer(),
member_id => binary(),
protocol_type => binary(),
protocols => [protocol()]}.
-type partition_assignment() :: #{topic => binary(),
partitions => [integer()]}.
-type member_assignment() :: #{version => integer(),
partition_assignment => [partition_assignment()],
user_data => binary()}.
-type group_assignment() :: #{member_id => binary(),
member_assignment => member_assignment()}.
-type sync_group() :: #{error_code => error_code(),
version => integer(),
partition_assignment => [partition_assignment()],
user_data => binary()}.
-type response_code() :: #{error_code => error_code()}.
-type group_member_ex() :: #{client_host => binary(),
client_id => binary(),
member_id => binary(),
member_metadata => binary(),
member_assignment => member_assignment()}.
-type describe_group() :: [#{error_code => error_code(),
group_id => binary(),
members => [group_member_ex()],
protocol => binary(),
protocol_type => binary(),
state => binary()}].
-type consumer_options() :: #{session_timeout => integer(),
member_id => binary(),
topics => [binary() | {binary(), [integer()]}],
fetch_interval => integer(),
fetch_size => integer(),
max_bytes => integer(),
min_bytes => integer(),
max_wait_time => integer(),
on_start_fetching => fun((binary()) -> any()) | {atom(), atom()} | undefined,
on_stop_fetching => fun((binary()) -> any()) | {atom(), atom()} | undefined,
on_assignment_change => fun((binary(), [{binary(), integer()}], [{binary(), integer()}]) -> any()) | {atom(), atom()} | undefined,
can_fetch => fun(() -> true | false) | {atom(), atom()} | undefined,
from_beginning => true | false,
commit => [commit()]}.
-type commit() :: processing() | {interval, integer()} | {message, integer()}.
-type processing() :: before_processing | after_processing.
-type group_commit_identifier() :: binary().
% @hidden
number_of_brokers() ->
kafe_brokers:size().
% @hidden
topics() ->
kafe_brokers:topics().
% @hidden
partitions(Topic) ->
kafe_brokers:partitions(Topic).
% @hidden
max_offset(TopicName) ->
case offset([TopicName]) of
{ok, [#{partitions := Partitions}]} ->
lists:foldl(fun
(#{id := P, offsets := [O|_]}, {_, Offset} = Acc) ->
if
O > Offset -> {P, O};
true -> Acc
end;
(#{id := P, offset := O}, {_, Offset} = Acc) ->
if
O > Offset -> {P, O};
true -> Acc
end
end, {?DEFAULT_OFFSET_PARTITION, 0}, Partitions);
{ok, _} ->
{?DEFAULT_OFFSET_PARTITION, 0}
end.
% @hidden
max_offset(TopicName, Partition) ->
case offset([{TopicName, [{Partition, ?DEFAULT_OFFSET_TIMESTAMP, ?DEFAULT_OFFSET_MAX_NUM_OFFSETS}]}]) of
{ok,
[#{partitions := [#{id := Partition,
offsets := [Offset|_]}]}]
} ->
{Partition, Offset};
{ok, _} ->
{Partition, 0}
end.
% @hidden
partition_for_offset(TopicName, Offset) ->
case offset([TopicName]) of
{ok, [#{partitions := Partitions}]} ->
lists:foldl(fun(#{id := P, offsets := [O|_]}, {_, Offset1} = Acc) ->
if
O >= Offset1 -> {P, Offset1};
true -> Acc
end
end, {0, Offset}, Partitions);
{ok, _} ->
{?DEFAULT_OFFSET_PARTITION, Offset}
end.
% @hidden
update_brokers() ->
kafe_brokers:update().
% @hidden
api_version() ->
kafe_brokers:api_version().
% @hidden
api_version(ApiKey) ->
kafe_brokers:api_version(ApiKey).
% -- Public APIs --
% @doc
% Start kafe application
% @end
start() ->
application:ensure_all_started(?MODULE).
% @doc
% Return the list of availables brokers
% @end
-spec brokers() -> [broker_name()].
brokers() ->
kafe_brokers:list().
% @doc
% Return the list of API versions for each api key
% @end
api_versions() ->
kafe_protocol_api_versions:run().
% @equiv metadata([])
metadata() ->
metadata([]).
% @doc
% Return metadata for the given topics
%
% Example:
% <pre>
% Metadata = kafe:metadata([<<"topic1">>, <<"topic2">>]).
% </pre>
%
% This example return all metadata for <tt>topic1</tt> and <tt>topic2</tt>
%
% For more informations, see the
< a href=" / confluence / display / / A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol - TopicMetadataRequest">Kafka protocol documentation</a > .
% @end
-spec metadata([binary()|string()|atom()]) -> {ok, metadata()} | {error, term()}.
metadata(Topics) when is_list(Topics) ->
kafe_protocol_metadata:run(Topics).
% @equiv offset(-1, [])
offset() ->
offset(-1, []).
% @equiv offset(-1, Topics)
offset(Topics) when is_list(Topics) ->
offset(-1, Topics).
% @doc
% Get offet for the given topics and replicat
%
% Example:
% <pre>
Offset = kafe : offet(-1 , [ & lt;<"topic1">> ; , { & lt;<"topic2">> ; , [ { 0 , -1 , 1 } , { 2 , -1 , 1 } ] } ] ) .
% </pre>
%
% For more informations, see the
< a href=" / confluence / display / / A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol - OffsetRequest">Kafka protocol documentation</a > .
% @end
-spec offset(integer(), topics()) -> {ok, [topic_partition_info()]} | {error, term()}.
offset(ReplicatID, Topics) when is_integer(ReplicatID), is_list(Topics) ->
kafe_protocol_offset:run(ReplicatID, Topics).
% @equiv produce(Messages, #{})
produce(Messages) ->
produce(Messages, #{}).
% @doc
% Send a message
%
% Options:
% <ul>
< li><tt > timeout : : > : This provides a maximum time in milliseconds the server can await the receipt of the number of acknowledgements in
RequiredAcks . The timeout is not an exact limit on the request time for a few reasons : ( 1 ) it does not include network latency , ( 2 ) the timer begins at the
beginning of the processing of this request so if many requests are queued due to server overload that wait time will not be included , ( 3 ) we will not
% terminate a local write so if the local write time exceeds this timeout it will not be respected. To get a hard timeout of this type the client should use the
socket timeout . ( default : 5000)</li >
< li><tt > required_acks : : > : This field indicates how many acknowledgements the servers should receive before responding to the request . If it is
% 0 the server will not send any response (this is the only case where the server will not reply to a request) and this function will return ok.
If it is 1 , the server will wait the data is written to the local log before sending a response . If it is -1 the server will block until the message is committed
by all in sync replicas before sending a response . For any number > 1 the server will block waiting for this number of acknowledgements to occur ( but the server
% will never wait for more acknowledgements than there are in-sync replicas). (default: -1)</li>
< li><tt > partition : : > : The partition that data is being published to .
% <i>This option exist for compatibility but it will be removed in the next major release.</i></li>
< li><tt > key_to_partition : : fun((binary ( ) , term ( ) ) -> ; integer())</tt > : Hash function to do partition assignment from the message key . ( default :
% kafe:default_key_to_partition/2)</li>
% </ul>
%
% If the partition is specified (option <tt>partition</tt>) and there is a message' key, the message will be produce on the specified partition. If no partition
% is specified, and there is a message key, the partition will be calculated using the <tt>key_to_partition</tt> function (or an internal function if this
% option is not specified). If there is no key and no partition specified, the partition will be choosen using a round robin algorithm.
%
% Example:
% <pre>
Response = kafe : product([{<<"topic">> ; , [ & lt;<"a simple message">> ; ] } ] , # { timeout = & gt ; 1000 } ) .
Response1 = kafe : ; , [ { & lt;<"key1">> ; , & lt;<"A simple message">> ; } ] } ,
{ & lt;<"topic2">> ; , [ { & lt;<"key2">> ; , & lt;<"Another simple message">> ; } ] } ] ) .
% </pre>
%
% For more informations, see the
< a href=" / confluence / display / / A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol - ProduceAPI">Kafka protocol documentation</a > .
% @end
-spec produce([{topic(), [{key(), value(), partition()}
| {value(), partition()}
| {key(), value()}
| value()]}], produce_options()) ->
{ok, #{throttle_time => integer(),
topics => [topic_partition_info()]}}
| {ok, [topic_partition_info()]}
| {error, term()}
| ok.
produce(Messages, Options) when is_list(Messages), is_map(Options) ->
kafe_protocol_produce:run(Messages, Options);
produce(Topic, Message) when is_binary(Topic),
(is_binary(Message) orelse is_tuple(Message)) ->
produce([{Topic, [Message]}], #{}).
% @equiv produce([{Topic, [Message]}], Options)
produce(Topic, Message, #{partition := Partition} = Options) when is_binary(Topic),
is_binary(Message) ->
produce([{Topic, [{Message, Partition}]}], Options);
produce(Topic, {Key, Value}, #{partition := Partition} = Options) when is_binary(Topic),
is_binary(Value) ->
produce([{Topic, [{Key, Value, Partition}]}], Options);
produce(Topic, Message, Options) when is_binary(Topic),
is_map(Options) ->
produce([{Topic, [Message]}], Options).
% @doc
% Default fonction used to do partition assignment from the message key.
% @end
-spec default_key_to_partition(Topic :: binary(), Key :: term()) -> integer().
default_key_to_partition(Topic, Key) ->
erlang:crc32(term_to_binary(Key)) rem erlang:length(kafe:partitions(Topic)).
% @equiv fetch(-1, Topics, #{})
-spec fetch(binary()
| [{Topic :: binary(), [{Partition :: integer(), Offset :: integer(), MaxBytes :: integer()}]}]
| [{Topic :: binary(), [{Partition :: integer(), Offset :: integer()}]}]
| [{Topic :: binary(), [Partition :: integer()]}]
| [{Topic :: binary(), Partition :: integer()}]
| [Topic :: binary()]) -> {ok, [message_set()]} | {ok, #{topics => [message_set()], throttle_time => integer()}} | {error, term()}.
fetch(Topics) when is_binary(Topics) orelse is_list(Topics) ->
fetch(-1, Topics, #{}).
@equiv fetch(ReplicatID , TopicName , # { } )
-spec fetch(integer()
| binary()
| [{Topic :: binary(), [{Partition :: integer(), Offset :: integer(), MaxBytes :: integer()}]}]
| [{Topic :: binary(), [{Partition :: integer(), Offset :: integer()}]}]
| [{Topic :: binary(), [Partition :: integer()]}]
| [{Topic :: binary(), Partition :: integer()}]
| [Topic :: binary()],
binary()
| [{Topic :: binary(), [{Partition :: integer(), Offset :: integer(), MaxBytes :: integer()}]}]
| [{Topic :: binary(), [{Partition :: integer(), Offset :: integer()}]}]
| [{Topic :: binary(), [Partition :: integer()]}]
| [{Topic :: binary(), Partition :: integer()}]
| [Topic :: binary()]
| fetch_options()) -> {ok, [message_set()]} | {ok, #{topics => [message_set()], throttle_time => integer()}} | {error, term()}.
fetch(ReplicatID, Topics) when is_integer(ReplicatID), (is_binary(Topics) orelse is_list(Topics)) ->
fetch(ReplicatID, Topics, #{});
% @equiv fetch(-1, Topics, Options)
fetch(Topics, Options) when is_map(Options), (is_binary(Topics) orelse is_list(Topics)) ->
fetch(-1, Topics, Options).
% @doc
% Fetch messages
%
% Options:
% <ul>
< li><tt > partition : : > : The i d of the partition to fetch , if not specified . < i > This option exist for compatibility but it will be removed
% in the next major release.</i></li>
< li><tt > offset : : > : The default offset to begin this fetch from , if not specified . < i > This option exist for compatibility but it will be removed
% in the next major release.</i></li>
< li><tt > response_max_bytes : : > : Maximum bytes to accumulate in the response . Note that this is not an absolute maximum , if the first message
in the first non - empty partition of the fetch is larger than this value , the message will still be returned to ensure that progress can be made .
% (default: sum of all max_bytes)</li>
< li><tt > max_bytes : : > : The maximum bytes to include in the message set for this partition . This helps bound the size of the response ( default :
1024 * 1024 ) < i > This option exist for compatibility but it will be removed in the next major release.</i></li >
< li><tt > min_bytes : : > : This is the minimum number of bytes of messages that must be available to give a response . If the client sets this to 0
% the server will always respond immediately, however if there is no new data since their last request they will just get back empty message sets. If this is
set to 1 , the server will respond as soon as at least one partition has at least 1 byte of data or the specified timeout occurs . By setting higher values in
% combination with the timeout the consumer can tune for throughput and trade a little additional latency for reading only large chunks of data (e.g. setting
MaxWaitTime to 100 ms and setting MinBytes to 64k would allow the server to wait up to to try to accumulate 64k of data before responding ) ( default :
% 1).</li>
< li><tt > max_wait_time : : > : The wait time is the maximum amount of time in milliseconds to block waiting if insufficient data is available
% at the time the request is issued (default : 100).</li>
% </ul>
%
ReplicatID must < b > always</b > be -1 .
%
% Examples:
% <pre>
% Response0 = kafe:fetch(<<"topic">>).
Response1 = kafe : fetch(<<"topic">> ; , # { offset = & gt ; 2 , partition = & gt ; 3 } ) .
Response2 = fetch(-1 , [ { Topic , [ { Partition , Offset , MaxBytes , Options ) .
% Response3 = fetch(-1, [{Topic, [{Partition, Offset}]}], Options).
% Response4 = fetch(-1, [{Topic, [Partition]}], Options).
Response5 = fetch(-1 , [ { Topic , Partition } ] , Options ) .
% Response6 = fetch(-1, [Topic, Options).
% </pre>
%
% For more informations, see the
< a href=" / confluence / display / / A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol - FetchAPI">Kafka protocol documentation</a > .
% @end
-spec fetch(integer(),
binary()
| [{Topic :: binary(), [{Partition :: integer(), Offset :: integer(), MaxBytes :: integer()}]}]
| [{Topic :: binary(), [{Partition :: integer(), Offset :: integer()}]}]
| [{Topic :: binary(), [Partition :: integer()]}]
| [{Topic :: binary(), Partition :: integer()}]
| [Topic :: binary()],
fetch_options()) -> {ok, [message_set()]} | {ok, #{topics => [message_set()], throttle_time => integer()}} | {error, term()}.
fetch(ReplicatID, TopicName, Options) when is_integer(ReplicatID), is_binary(TopicName), is_map(Options) ->
fetch(ReplicatID, [TopicName], Options);
fetch(ReplicatID, Topics, Options) when is_integer(ReplicatID), is_list(Topics), is_map(Options) ->
kafe_protocol_fetch:run(ReplicatID, Topics, Options).
% @doc
% Find groups managed by all brokers.
% @end
-spec list_groups() -> {ok, groups_list()} | {error, term()}.
list_groups() ->
{ok, lists:map(fun(BrokerName) ->
case list_groups(BrokerName) of
{ok, Groups} ->
#{broker => BrokerName,
groups => Groups};
_ ->
#{broker => BrokerName,
groups => #{error_code => broker_not_available,
groups => []}}
end
end, brokers())}.
% @doc
% Find groups managed by a broker.
%
% For more informations, see the
< a href=" / confluence / display / / A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol - ListGroupsRequest">Kafka protocol documentation</a >
% @end
-spec list_groups(BrokerIDOrName :: broker_id() | broker_name()) -> {ok, groups()} | {error, term()}.
list_groups(BrokerIDOrName) ->
kafe_protocol_list_groups:run(BrokerIDOrName).
% @doc
% Group coordinator Request
%
% For more informations, see the
< a href=" / confluence / display / / A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol - ConsumerMetadataRequest">Kafka protocol documentation</a > .
%
% For compatibility, this function as an alias : <tt>consumer_metadata</tt>.
% @end
-spec group_coordinator(binary()) -> {ok, group_coordinator()} | {error, term()}.
group_coordinator(ConsumerGroup) ->
kafe_protocol_group_coordinator:run(ConsumerGroup).
-alias consumer_metadata.
% @equiv join_group(GroupID, #{})
join_group(GroupID) ->
join_group(GroupID, #{}).
% @doc
Join Group
%
% Options:
% <ul>
< li><tt > session_timeout : : > : The coordinator considers the consumer dead if it receives no heartbeat after this timeout in ms . ( default : 10000)</li >
< li><tt > rebalance_timeout : : > : The maximum time that the coordinator will wait for each member to rejoin when rebalancing the group . ( default : 20000)</li >
< li><tt > member_id : : binary()</tt > : The assigned consumer i d or an empty string for a new consumer . When a member first joins the group , the memberID must be
empty ( i.e. & lt;<>> ; , default ) , but a rejoining member should use the same memberID from the previous generation.</li >
< li><tt > protocol_type : : binary()</tt > : Unique name for class of protocols implemented by group ( default & lt;<"consumer">>).</li >
< li><tt > protocols : : [ protocol()]</tt > : List of protocols.</li >
% </ul>
%
% For more informations, see the
< a href=" / confluence / display / / A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol - JoinGroupRequest">Kafka protocol documentation</a > .
% @end
-spec join_group(binary(), join_group_options()) -> {error, term()} | {ok, group_join()}.
join_group(GroupID, Options) ->
kafe_protocol_join_group:run(GroupID, Options).
% @doc
% Create a default protocol as defined in the <a
href=" / confluence / display / / A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol - JoinGroupRequest">Kafka Protocol Guide</a > .
% @end
-spec default_protocol(Name :: binary(), Version :: integer(), Topics :: topics(), UserData :: binary()) -> protocol().
default_protocol(Name, Version, Topics, UserData) when is_binary(Name),
is_integer(Version),
is_list(Topics),
is_binary(UserData) ->
EncodedTopics = lists:map(fun(E) ->
kafe_protocol:encode_string(bucs:to_binary(E))
end, Topics),
<<(kafe_protocol:encode_string(Name))/binary,
Version:16/signed,
(kafe_protocol:encode_array(EncodedTopics))/binary,
(kafe_protocol:encode_bytes(UserData))/binary>>.
% @doc
% The sync group request is used by the group leader to assign state (e.g. partition assignments) to all members of the current generation. All members send
SyncGroup immediately after joining the group , but only the leader provides the group 's assignment .
%
% Example:
%
% <pre>
kafe : sync_group(<<"my_group">> ; , 1 , & lt;<"kafka-6dbb08f4 - a0dc-4f4c - a0b9 - dccb4d03ff2c">> ; ,
[ # { member_id = & gt ; & lt;<"kafka-6dbb08f4 - a0dc-4f4c - a0b9 - dccb4d03ff2c">> ; ,
member_assignment = & gt ; # { version = & gt ; 0 ,
% user_data => <<"my user data">>,
partition_assignment = & gt ; [ # { topic = & gt ; & lt;<"topic0">> ; ,
partitions = & gt ; [ 0 , 1 , 2 ] } ,
# { topic = & gt ; & lt;<"topic1">> ; ,
partitions = & gt ; [ 0 , 1 , 2 ] } ] } } ,
# { member_id = & gt ; & lt;<"kafka-0b7e179d-3ff9 - 46d2 - b652 - e0d041e4264a">> ; ,
member_assignment = & gt ; # { version = & gt ; 0 ,
% user_data => <<"my user data">>,
partition_assignment = & gt ; [ # { topic = & gt ; & lt;<"topic0">> ; ,
partitions = & gt ; [ 0 , 1 , 2 ] } ,
# { topic = & gt ; & lt;<"topic1">> ; ,
partitions = & gt ; [ 0 , 1 , 2 ] } ] } } ] ) .
% </pre>
%
% For more informations, see the
< a href=" / confluence / display / / A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol - SyncGroupRequest">Kafka protocol documentation</a > .
% @end
-spec sync_group(binary(), integer(), binary(), [group_assignment()]) -> {error, term()} | {ok, sync_group()}.
sync_group(GroupID, GenerationID, MemberID, Assignments) ->
kafe_protocol_sync_group:run(GroupID, GenerationID, MemberID, Assignments).
% @doc
% Once a member has joined and synced, it will begin sending periodic heartbeats to keep itself in the group. If not heartbeat has been received by the
% coordinator with the configured session timeout, the member will be kicked out of the group.
%
% For more informations, see the
< a href=" / confluence / display / / A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol - HeartbeatRequest">Kafka protocol documentation</a > .
% @end
-spec heartbeat(binary(), integer(), binary()) -> {error, term()} | {ok, response_code()}.
heartbeat(GroupID, GenerationID, MemberID) ->
kafe_protocol_heartbeat:run(GroupID, GenerationID, MemberID).
% @doc
% To explicitly leave a group, the client can send a leave group request. This is preferred over letting the session timeout expire since it allows the group to
% rebalance faster, which for the consumer means that less time will elapse before partitions can be reassigned to an active member.
%
% For more informations, see the
< a href=" / confluence / display / / A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol - LeaveGroupRequest">Kafka protocol documentation</a > .
% @end
-spec leave_group(binary(), binary()) -> {error, term()} | {ok, response_code()}.
leave_group(GroupID, MemberID) ->
kafe_protocol_leave_group:run(GroupID, MemberID).
% @doc
% Return the description of the given consumer group.
%
% For more informations, see the
< a href=" / confluence / display / / A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol - DescribeGroupsRequest">Kafka protocol documentation</a > .
% @end
-spec describe_group(binary()) -> {error, term()} | {ok, describe_group()}.
describe_group(GroupID) when is_binary(GroupID) ->
kafe_protocol_describe_group:run(GroupID).
% @doc
% Offset commit v0
%
% For more informations, see the
< a href=" / confluence / display / / A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol - OffsetCommitRequest">Kafka protocol documentation</a > .
% @end
-spec offset_commit(binary(), offset_commit_topics()) -> {ok, [offset_commit_set()]} | {error, term()}.
offset_commit(ConsumerGroup, Topics) ->
kafe_protocol_consumer_offset_commit:run_v0(ConsumerGroup, Topics).
% @doc
% Offset commit v1
%
% For more informations, see the
< a href=" / confluence / display / / A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol - OffsetCommitRequest">Kafka protocol documentation</a > .
% @end
-spec offset_commit(binary(), integer(), binary(), offset_commit_topics_v1()) -> {ok, [offset_commit_set()]} | {error, term()}.
offset_commit(ConsumerGroup, ConsumerGroupGenerationID, ConsumerID, Topics) ->
kafe_protocol_consumer_offset_commit:run_v1(ConsumerGroup,
ConsumerGroupGenerationID,
ConsumerID,
Topics).
% @doc
% Offset commit v2
%
% For more informations, see the
< a href=" / confluence / display / / A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol - OffsetCommitRequest">Kafka protocol documentation</a > .
% @end
-spec offset_commit(binary(), integer(), binary(), integer(), offset_commit_topics()) -> {ok, [offset_commit_set()]} | {error, term()}.
offset_commit(ConsumerGroup, ConsumerGroupGenerationID, ConsumerID, RetentionTime, Topics) ->
kafe_protocol_consumer_offset_commit:run_v2(ConsumerGroup,
ConsumerGroupGenerationID,
ConsumerID,
RetentionTime,
Topics).
% @equiv offset_fetch(ConsumerGroup, [])
-spec offset_fetch(binary()) -> {ok, [offset_fetch_set()]}.
offset_fetch(ConsumerGroup) ->
offset_fetch(ConsumerGroup, []).
% @doc
% Offset fetch
%
% For more informations, see the
< a href=" / confluence / display / / A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol - OffsetFetchRequest">Kafka protocol documentation</a > .
% @end
-spec offset_fetch(binary(), offset_fetch_options()) -> {ok, [offset_fetch_set()]} | {error, term()}.
offset_fetch(ConsumerGroup, Options) when is_binary(ConsumerGroup), is_list(Options) ->
kafe_protocol_consumer_offset_fetch:run(ConsumerGroup, Options);
offset_fetch(ConsumerGroup, Options) when is_list(Options) ->
offset_fetch(bucs:to_binary(ConsumerGroup), Options).
% @doc
% Return the list of the next Nth unread offsets for a given topic and consumer group
% @end
-spec offsets(binary() | {binary(), [integer()]}, binary(), integer()) -> [{integer(), integer()}] | error.
offsets(TopicName, ConsumerGroup, Nth) when is_binary(TopicName) ->
offsets({TopicName, partitions(TopicName)}, ConsumerGroup, Nth);
offsets({TopicName, PartitionsList}, ConsumerGroup, Nth) ->
case offset([TopicName]) of
{ok, [#{name := TopicName, partitions := Partitions}]} ->
{Offsets, PartitionsID} = lists:foldl(fun
(#{id := PartitionID,
offsets := [Offset|_],
error_code := none},
{AccOffs, AccParts} = Acc) ->
case lists:member(PartitionID, PartitionsList) of
true ->
{[{PartitionID, Offset - 1}|AccOffs], [PartitionID|AccParts]};
false ->
Acc
end;
(_, Acc) ->
Acc
end, {[], []}, Partitions),
case offset_fetch(ConsumerGroup, [{TopicName, PartitionsID}]) of
{ok, [#{name := TopicName, partitions_offset := PartitionsOffset}]} ->
CurrentOffsets = lists:foldl(fun
(#{offset := Offset1,
partition := PartitionID1},
Acc1) ->
[{PartitionID1, Offset1 + 1}|Acc1];
(_, Acc1) ->
Acc1
end, [], PartitionsOffset),
CombinedOffsets = lists:foldl(fun({P, O}, Acc) ->
case lists:keyfind(P, 1, CurrentOffsets) of
{P, C} when C =< O -> [{P, O, C}|Acc];
_ -> Acc
end
end, [], Offsets),
lager:debug("Offsets = ~p / CurrentOffsets = ~p / CombinedOffsets = ~p", [Offsets, CurrentOffsets, CombinedOffsets]),
{NewOffsets, Result} = get_offsets_list(CombinedOffsets, [], [], Nth),
lists:foldl(fun({PartitionID, NewOffset}, Acc) ->
case offset_commit(ConsumerGroup,
[{TopicName, [{PartitionID, NewOffset, <<>>}]}]) of
{ok, [#{name := TopicName,
partitions := [#{partition := PartitionID,
error_code := none}]}]} ->
Acc;
_ ->
delete_offset_for_partition(PartitionID, Acc)
end
end, Result, NewOffsets);
_ ->
lager:error("Can't retrieve offsets for consumer group ~s on topic ~s", [ConsumerGroup, TopicName]),
error
end;
_ ->
lager:error("Can't retrieve offsets for topic ~s", [TopicName]),
error
end.
% @doc
% Return the list of all unread offsets for a given topic and consumer group
% @end
-spec offsets(binary(), binary()) -> [{integer(), integer()}] | error.
offsets(TopicName, ConsumerGroup) ->
offsets(TopicName, ConsumerGroup, -1).
get_offsets_list(Offsets, Result, Final, Nth) when Offsets =/= [], length(Result) =/= Nth ->
[{PartitionID, MaxOffset, CurrentOffset}|SortedOffsets] = lists:sort(fun({_, O1, C1}, {_, O2, C2}) -> (C1 < C2) and (O1 < O2) end, Offsets),
Offsets1 = if
CurrentOffset + 1 > MaxOffset -> SortedOffsets;
true -> [{PartitionID, MaxOffset, CurrentOffset + 1}|SortedOffsets]
end,
Final1 = lists:keystore(PartitionID, 1, Final, {PartitionID, CurrentOffset}),
get_offsets_list(Offsets1, [{PartitionID, CurrentOffset}|Result], Final1, Nth);
get_offsets_list(_, Result, Final, _) -> {Final, lists:reverse(Result)}.
delete_offset_for_partition(PartitionID, Offsets) ->
case lists:keyfind(PartitionID, 1, Offsets) of
false -> Offsets;
_ -> delete_offset_for_partition(PartitionID, lists:keydelete(PartitionID, 1, Offsets))
end.
% @doc
% Start a new consumer.
%
% Options:
% <ul>
< li><tt > session_timeout : : > : The coordinator considers the consumer dead if it receives no heartbeat after this timeout in ms . ( default : 10000)</li >
< li><tt > member_id : : binary()</tt > : The assigned consumer i d or an empty string for a new consumer . When a member first joins the group , the memberID must be
empty ( i.e. & lt;<>> ; , default ) , but a rejoining member should use the same memberID from the previous generation.</li >
% <li><tt>topics :: [binary() | {binary(), [integer()]}]</tt> : List or topics (and partitions).</li>
< li><tt > fetch_interval : : > : Fetch interval in ms ( default : 10)</li >
< li><tt > max_bytes : : > : The maximum bytes to include in the message set for this partition . This helps bound the size of the response ( default :
1024 * 1024)</li >
< li><tt > min_bytes : : > : This is the minimum number of bytes of messages that must be available to give a response . If the client sets this to 0
% the server will always respond immediately, however if there is no new data since their last request they will just get back empty message sets. If this is
set to 1 , the server will respond as soon as at least one partition has at least 1 byte of data or the specified timeout occurs . By setting higher values in
% combination with the timeout the consumer can tune for throughput and trade a little additional latency for reading only large chunks of data (e.g. setting
MaxWaitTime to 100 ms and setting MinBytes to 64k would allow the server to wait up to to try to accumulate 64k of data before responding ) ( default :
% 1).</li>
< li><tt > max_wait_time : : > : The wait time is the maximum amount of time in milliseconds to block waiting if insufficient data is available
% at the time the request is issued (default : 100).</li>
% <li><tt>commit :: commit()</tt> : Commit configuration (default: [after_processing, {interval, 1000}]).</li>
< li><tt > on_start_fetching : : fun((GroupID : : binary ( ) ) - > any ( ) ) | { atom ( ) , atom()}</tt > : Function called when the fetcher start / restart fetching . ( default : >
< li><tt > on_stop_fetching : : fun((GroupID : : binary ( ) ) - > any ( ) ) | { atom ( ) , atom()}</tt > : Function called when the fetcher stop fetching . ( default : >
% <li><tt>can_fetch :: fun(() -> true | false) | {atom(), atom()}</tt> : Messages are fetched, only if this function returns <tt>true</tt> or is undefined.
( default : >
% <li><tt>on_assignment_change :: fun((GroupID :: binary(), [{binary(), integer()}], [{binary(), integer()}]) -> any()) | {atom(), atom()}</tt> : Function called when the
partitions ' assignments change . The first parameter is the consumer group ID , the second is the list of { topic , partition } that were unassigned , the third
parameter is the list of { topic , partition } that were reassigned . ( default : >
% <li><tt>from_beginning :: true | false</tt> : Start consuming method. If it's set to <tt>true</tt>, the consumer will start to consume from the offset next to the
% last committed one. If it's set to <tt>false</tt>, the consumer will start to consume next to the last offset. (default: true).</li>
< li><tt > errors_actions : : map()</tt > : < /li >
% </ul>
% @end
-spec start_consumer(GroupID :: binary(),
Callback :: fun((GroupID :: binary(),
Topic :: binary(),
PartitionID :: integer(),
Offset :: integer(),
Key :: binary(),
Value :: binary()) -> ok | {error, term()})
| fun((Message :: kafe_consumer_subscriber:message()) -> ok | {error, term()})
| atom()
| {atom(), list(term())},
Options :: consumer_options()) -> {ok, GroupPID :: pid()} | {error, term()}.
start_consumer(GroupID, Callback, Options) when is_function(Callback, 6);
is_function(Callback, 1);
is_atom(Callback);
is_tuple(Callback) ->
kafe_consumer_sup:start_child(GroupID, Options#{callback => Callback}).
% @doc
% Stop the given consumer
% @end
-spec stop_consumer(GroupID :: binary()) -> ok | {error, not_found | simple_one_for_one | detached}.
stop_consumer(GroupID) ->
kafe_consumer_sup:stop_child(GroupID).
% @doc
% Return informations about a consumer
% @end
-spec consumer_infos(GroupID :: binary()) -> {ok, list()} | {error, term()}.
consumer_infos(GroupID) ->
case lists:member(GroupID, [bucs:to_binary(G) || G <- consumer_groups()]) of
true ->
{ok, [{Name, kafe_consumer_store:value(GroupID, Name)} || Name <- [generation_id, member_id, topics]]};
false ->
{error, group_does_not_exist}
end.
% @doc
% Return the list of availables consumers
% @end
-spec consumer_groups() -> [binary()].
consumer_groups() ->
kafe_consumer_sup:consumer_groups().
| null | https://raw.githubusercontent.com/G-Corp/kafe/78e014ae5b6d7e1077aa5cabf4adc21ed7abe203/src/kafe.erl | erlang | @doc
This module only implement the <a href="+Guide+To+The+Kafka+Protocol">Kafak Protocol</a>.
@end
Public API
Internal API
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
-- Public APIs --
@doc
Start kafe application
@end
@doc
Return the list of availables brokers
@end
@doc
Return the list of API versions for each api key
@end
@equiv metadata([])
@doc
Return metadata for the given topics
Example:
<pre>
Metadata = kafe:metadata([<<"topic1">>, <<"topic2">>]).
</pre>
This example return all metadata for <tt>topic1</tt> and <tt>topic2</tt>
For more informations, see the
@end
@equiv offset(-1, [])
@equiv offset(-1, Topics)
@doc
Get offet for the given topics and replicat
Example:
<pre>
</pre>
For more informations, see the
@end
@equiv produce(Messages, #{})
@doc
Send a message
Options:
<ul>
terminate a local write so if the local write time exceeds this timeout it will not be respected. To get a hard timeout of this type the client should use the
0 the server will not send any response (this is the only case where the server will not reply to a request) and this function will return ok.
will never wait for more acknowledgements than there are in-sync replicas). (default: -1)</li>
<i>This option exist for compatibility but it will be removed in the next major release.</i></li>
kafe:default_key_to_partition/2)</li>
</ul>
If the partition is specified (option <tt>partition</tt>) and there is a message' key, the message will be produce on the specified partition. If no partition
is specified, and there is a message key, the partition will be calculated using the <tt>key_to_partition</tt> function (or an internal function if this
option is not specified). If there is no key and no partition specified, the partition will be choosen using a round robin algorithm.
Example:
<pre>
</pre>
For more informations, see the
@end
@equiv produce([{Topic, [Message]}], Options)
@doc
Default fonction used to do partition assignment from the message key.
@end
@equiv fetch(-1, Topics, #{})
@equiv fetch(-1, Topics, Options)
@doc
Fetch messages
Options:
<ul>
in the next major release.</i></li>
in the next major release.</i></li>
(default: sum of all max_bytes)</li>
the server will always respond immediately, however if there is no new data since their last request they will just get back empty message sets. If this is
combination with the timeout the consumer can tune for throughput and trade a little additional latency for reading only large chunks of data (e.g. setting
1).</li>
at the time the request is issued (default : 100).</li>
</ul>
Examples:
<pre>
Response0 = kafe:fetch(<<"topic">>).
Response3 = fetch(-1, [{Topic, [{Partition, Offset}]}], Options).
Response4 = fetch(-1, [{Topic, [Partition]}], Options).
Response6 = fetch(-1, [Topic, Options).
</pre>
For more informations, see the
@end
@doc
Find groups managed by all brokers.
@end
@doc
Find groups managed by a broker.
For more informations, see the
@end
@doc
Group coordinator Request
For more informations, see the
For compatibility, this function as an alias : <tt>consumer_metadata</tt>.
@end
@equiv join_group(GroupID, #{})
@doc
Options:
<ul>
</ul>
For more informations, see the
@end
@doc
Create a default protocol as defined in the <a
@end
@doc
The sync group request is used by the group leader to assign state (e.g. partition assignments) to all members of the current generation. All members send
Example:
<pre>
user_data => <<"my user data">>,
user_data => <<"my user data">>,
</pre>
For more informations, see the
@end
@doc
Once a member has joined and synced, it will begin sending periodic heartbeats to keep itself in the group. If not heartbeat has been received by the
coordinator with the configured session timeout, the member will be kicked out of the group.
For more informations, see the
@end
@doc
To explicitly leave a group, the client can send a leave group request. This is preferred over letting the session timeout expire since it allows the group to
rebalance faster, which for the consumer means that less time will elapse before partitions can be reassigned to an active member.
For more informations, see the
@end
@doc
Return the description of the given consumer group.
For more informations, see the
@end
@doc
Offset commit v0
For more informations, see the
@end
@doc
Offset commit v1
For more informations, see the
@end
@doc
Offset commit v2
For more informations, see the
@end
@equiv offset_fetch(ConsumerGroup, [])
@doc
Offset fetch
For more informations, see the
@end
@doc
Return the list of the next Nth unread offsets for a given topic and consumer group
@end
@doc
Return the list of all unread offsets for a given topic and consumer group
@end
@doc
Start a new consumer.
Options:
<ul>
<li><tt>topics :: [binary() | {binary(), [integer()]}]</tt> : List or topics (and partitions).</li>
the server will always respond immediately, however if there is no new data since their last request they will just get back empty message sets. If this is
combination with the timeout the consumer can tune for throughput and trade a little additional latency for reading only large chunks of data (e.g. setting
1).</li>
at the time the request is issued (default : 100).</li>
<li><tt>commit :: commit()</tt> : Commit configuration (default: [after_processing, {interval, 1000}]).</li>
<li><tt>can_fetch :: fun(() -> true | false) | {atom(), atom()}</tt> : Messages are fetched, only if this function returns <tt>true</tt> or is undefined.
<li><tt>on_assignment_change :: fun((GroupID :: binary(), [{binary(), integer()}], [{binary(), integer()}]) -> any()) | {atom(), atom()}</tt> : Function called when the
<li><tt>from_beginning :: true | false</tt> : Start consuming method. If it's set to <tt>true</tt>, the consumer will start to consume from the offset next to the
last committed one. If it's set to <tt>false</tt>, the consumer will start to consume next to the last offset. (default: true).</li>
</ul>
@end
@doc
Stop the given consumer
@end
@doc
Return informations about a consumer
@end
@doc
Return the list of availables consumers
@end | @author < >
@author < >
@author < >
2014 - 2015 Finexkap , 2015 G - Corp , 2015 - 2016 BotsUnit
@since 2014
A client for Erlang
-module(kafe).
-compile([{parse_transform, bristow_transform},
{parse_transform, lager_transform}]).
-include("../include/kafe.hrl").
-include_lib("kernel/include/inet.hrl").
-export([
start/0,
brokers/0,
api_versions/0,
metadata/0,
metadata/1,
offset/0,
offset/1,
offset/2,
produce/1,
produce/2,
produce/3,
default_key_to_partition/2,
fetch/1,
fetch/2,
fetch/3,
list_groups/0,
list_groups/1,
group_coordinator/1,
join_group/1,
join_group/2,
sync_group/4,
heartbeat/3,
leave_group/2,
describe_group/1,
default_protocol/4,
offset_fetch/1,
offset_fetch/2,
offset_commit/2,
offset_commit/4,
offset_commit/5
]).
-export([
start_consumer/3,
stop_consumer/1,
consumer_infos/1,
consumer_groups/0,
offsets/2,
offsets/3
]).
-export([
number_of_brokers/0,
topics/0,
partitions/1,
max_offset/1,
max_offset/2,
partition_for_offset/2,
api_version/0,
api_version/1,
update_brokers/0
]).
-export_type([describe_group/0, group_commit_identifier/0]).
-type error_code() :: no_error
| unknown
| offset_out_of_range
| invalid_message
| unknown_topic_or_partition
| invalid_message_size
| leader_not_available
| not_leader_for_partition
| request_timed_out
| broker_not_available
| replica_not_available
| message_size_too_large
| stale_controller_epoch
| offset_metadata_too_large
| offsets_load_in_progress
| consumer_coordinator_not_available
| not_coordinator_for_consumer.
-type metadata() :: #{brokers => [#{host => binary(),
id => integer(),
port => port()}],
topics => [#{error_code => error_code(),
name => binary(),
partitions => [#{error_code => error_code(),
id => integer(),
isr => [integer()],
leader => integer(),
replicas => [integer()]}]}]}.
-type topic() :: binary().
-type key() :: term().
-type value() :: binary().
-type partition() :: integer().
-type topics() :: [topic()] | [{topic(), [{partition(), integer(), integer()}]}] | [{topic(), [{partition(), integer()}]}].
-type topic_partition_info() :: #{name => binary(),
partitions => [#{error_code => error_code(),
id => integer(),
offset => integer(),
timestamp => integer()}
| #{error_code => error_code(),
id => integer(),
offsets => [integer()]}]}.
-type produce_options() :: #{timeout => integer(),
required_acks => integer(),
partition => integer(),
key_to_partition => fun((binary(), term()) -> integer())}.
-type fetch_options() :: #{partition => integer(),
offset => integer(),
response_max_bytes => integer(),
max_bytes => integer(),
min_bytes => integer(),
max_wait_time => integer(),
retrieve => first | all}.
-type message_set() :: #{name => binary(),
partitions => [#{partition => integer(),
error_code => error_code(),
high_watermark_offset => integer(),
messages => [#{offset => integer(),
crc => integer(),
magic_byte => 0 | 1,
attributes => integer(),
timestamp => integer(),
key => binary(),
value => binary()}]}]}.
-type group_coordinator() :: #{error_code => error_code(),
coordinator_id => integer(),
coordinator_host => binary(),
coordinator_port => port()}.
-type offset_fetch_options() :: [binary()] | [{binary(), [integer()]}].
-type offset_fetch_set() :: #{name => binary(),
partitions_offset => [#{partition => integer(),
offset => integer(),
metadata_info => binary(),
error_code => error_code()}]}.
-type offset_commit_set() :: #{name => binary(),
partitions => [#{partition => integer(),
error_code => error_code()}]}.
-type offset_commit_topics() :: [{binary(), [{integer(), integer(), integer(), binary()}]}]
| [{binary(), [{integer(), integer(), binary()}]}]
| [{binary(), [{integer(), integer(), integer()}]}]
| [{binary(), [{integer(), integer()}]}].
-type offset_commit_topics_v1() :: [{binary(), [{integer(), integer(), integer(), binary()}]}].
-type broker_id() :: atom().
-type broker_name() :: string().
-type group() :: #{group_id => binary(), protocol_type => binary()}.
-type groups() :: #{error_code => error_code(),
groups => [group()]}.
-type groups_list() :: [#{broker => broker_name(),
groups => groups()}].
-type group_member() :: #{member_id => binary(),
member_metadata => binary()}.
-type group_join() :: #{error_code => error_code(),
generation_id => integer(),
protocol_group => binary(),
leader_id => binary(),
member_id => binary(),
members => [group_member()]}.
-type protocol() :: binary().
-type join_group_options() :: #{session_timeout => integer(),
rebalance_timeout => integer(),
member_id => binary(),
protocol_type => binary(),
protocols => [protocol()]}.
-type partition_assignment() :: #{topic => binary(),
partitions => [integer()]}.
-type member_assignment() :: #{version => integer(),
partition_assignment => [partition_assignment()],
user_data => binary()}.
-type group_assignment() :: #{member_id => binary(),
member_assignment => member_assignment()}.
-type sync_group() :: #{error_code => error_code(),
version => integer(),
partition_assignment => [partition_assignment()],
user_data => binary()}.
-type response_code() :: #{error_code => error_code()}.
-type group_member_ex() :: #{client_host => binary(),
client_id => binary(),
member_id => binary(),
member_metadata => binary(),
member_assignment => member_assignment()}.
-type describe_group() :: [#{error_code => error_code(),
group_id => binary(),
members => [group_member_ex()],
protocol => binary(),
protocol_type => binary(),
state => binary()}].
-type consumer_options() :: #{session_timeout => integer(),
member_id => binary(),
topics => [binary() | {binary(), [integer()]}],
fetch_interval => integer(),
fetch_size => integer(),
max_bytes => integer(),
min_bytes => integer(),
max_wait_time => integer(),
on_start_fetching => fun((binary()) -> any()) | {atom(), atom()} | undefined,
on_stop_fetching => fun((binary()) -> any()) | {atom(), atom()} | undefined,
on_assignment_change => fun((binary(), [{binary(), integer()}], [{binary(), integer()}]) -> any()) | {atom(), atom()} | undefined,
can_fetch => fun(() -> true | false) | {atom(), atom()} | undefined,
from_beginning => true | false,
commit => [commit()]}.
-type commit() :: processing() | {interval, integer()} | {message, integer()}.
-type processing() :: before_processing | after_processing.
-type group_commit_identifier() :: binary().
number_of_brokers() ->
kafe_brokers:size().
topics() ->
kafe_brokers:topics().
partitions(Topic) ->
kafe_brokers:partitions(Topic).
max_offset(TopicName) ->
case offset([TopicName]) of
{ok, [#{partitions := Partitions}]} ->
lists:foldl(fun
(#{id := P, offsets := [O|_]}, {_, Offset} = Acc) ->
if
O > Offset -> {P, O};
true -> Acc
end;
(#{id := P, offset := O}, {_, Offset} = Acc) ->
if
O > Offset -> {P, O};
true -> Acc
end
end, {?DEFAULT_OFFSET_PARTITION, 0}, Partitions);
{ok, _} ->
{?DEFAULT_OFFSET_PARTITION, 0}
end.
max_offset(TopicName, Partition) ->
case offset([{TopicName, [{Partition, ?DEFAULT_OFFSET_TIMESTAMP, ?DEFAULT_OFFSET_MAX_NUM_OFFSETS}]}]) of
{ok,
[#{partitions := [#{id := Partition,
offsets := [Offset|_]}]}]
} ->
{Partition, Offset};
{ok, _} ->
{Partition, 0}
end.
partition_for_offset(TopicName, Offset) ->
case offset([TopicName]) of
{ok, [#{partitions := Partitions}]} ->
lists:foldl(fun(#{id := P, offsets := [O|_]}, {_, Offset1} = Acc) ->
if
O >= Offset1 -> {P, Offset1};
true -> Acc
end
end, {0, Offset}, Partitions);
{ok, _} ->
{?DEFAULT_OFFSET_PARTITION, Offset}
end.
update_brokers() ->
kafe_brokers:update().
api_version() ->
kafe_brokers:api_version().
api_version(ApiKey) ->
kafe_brokers:api_version(ApiKey).
start() ->
application:ensure_all_started(?MODULE).
-spec brokers() -> [broker_name()].
brokers() ->
kafe_brokers:list().
api_versions() ->
kafe_protocol_api_versions:run().
metadata() ->
metadata([]).
< a href=" / confluence / display / / A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol - TopicMetadataRequest">Kafka protocol documentation</a > .
-spec metadata([binary()|string()|atom()]) -> {ok, metadata()} | {error, term()}.
metadata(Topics) when is_list(Topics) ->
kafe_protocol_metadata:run(Topics).
offset() ->
offset(-1, []).
offset(Topics) when is_list(Topics) ->
offset(-1, Topics).
Offset = kafe : offet(-1 , [ & lt;<"topic1">> ; , { & lt;<"topic2">> ; , [ { 0 , -1 , 1 } , { 2 , -1 , 1 } ] } ] ) .
< a href=" / confluence / display / / A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol - OffsetRequest">Kafka protocol documentation</a > .
-spec offset(integer(), topics()) -> {ok, [topic_partition_info()]} | {error, term()}.
offset(ReplicatID, Topics) when is_integer(ReplicatID), is_list(Topics) ->
kafe_protocol_offset:run(ReplicatID, Topics).
produce(Messages) ->
produce(Messages, #{}).
< li><tt > timeout : : > : This provides a maximum time in milliseconds the server can await the receipt of the number of acknowledgements in
RequiredAcks . The timeout is not an exact limit on the request time for a few reasons : ( 1 ) it does not include network latency , ( 2 ) the timer begins at the
beginning of the processing of this request so if many requests are queued due to server overload that wait time will not be included , ( 3 ) we will not
socket timeout . ( default : 5000)</li >
< li><tt > required_acks : : > : This field indicates how many acknowledgements the servers should receive before responding to the request . If it is
If it is 1 , the server will wait the data is written to the local log before sending a response . If it is -1 the server will block until the message is committed
by all in sync replicas before sending a response . For any number > 1 the server will block waiting for this number of acknowledgements to occur ( but the server
< li><tt > partition : : > : The partition that data is being published to .
< li><tt > key_to_partition : : fun((binary ( ) , term ( ) ) -> ; integer())</tt > : Hash function to do partition assignment from the message key . ( default :
Response = kafe : product([{<<"topic">> ; , [ & lt;<"a simple message">> ; ] } ] , # { timeout = & gt ; 1000 } ) .
Response1 = kafe : ; , [ { & lt;<"key1">> ; , & lt;<"A simple message">> ; } ] } ,
{ & lt;<"topic2">> ; , [ { & lt;<"key2">> ; , & lt;<"Another simple message">> ; } ] } ] ) .
< a href=" / confluence / display / / A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol - ProduceAPI">Kafka protocol documentation</a > .
-spec produce([{topic(), [{key(), value(), partition()}
| {value(), partition()}
| {key(), value()}
| value()]}], produce_options()) ->
{ok, #{throttle_time => integer(),
topics => [topic_partition_info()]}}
| {ok, [topic_partition_info()]}
| {error, term()}
| ok.
produce(Messages, Options) when is_list(Messages), is_map(Options) ->
kafe_protocol_produce:run(Messages, Options);
produce(Topic, Message) when is_binary(Topic),
(is_binary(Message) orelse is_tuple(Message)) ->
produce([{Topic, [Message]}], #{}).
produce(Topic, Message, #{partition := Partition} = Options) when is_binary(Topic),
is_binary(Message) ->
produce([{Topic, [{Message, Partition}]}], Options);
produce(Topic, {Key, Value}, #{partition := Partition} = Options) when is_binary(Topic),
is_binary(Value) ->
produce([{Topic, [{Key, Value, Partition}]}], Options);
produce(Topic, Message, Options) when is_binary(Topic),
is_map(Options) ->
produce([{Topic, [Message]}], Options).
-spec default_key_to_partition(Topic :: binary(), Key :: term()) -> integer().
default_key_to_partition(Topic, Key) ->
erlang:crc32(term_to_binary(Key)) rem erlang:length(kafe:partitions(Topic)).
-spec fetch(binary()
| [{Topic :: binary(), [{Partition :: integer(), Offset :: integer(), MaxBytes :: integer()}]}]
| [{Topic :: binary(), [{Partition :: integer(), Offset :: integer()}]}]
| [{Topic :: binary(), [Partition :: integer()]}]
| [{Topic :: binary(), Partition :: integer()}]
| [Topic :: binary()]) -> {ok, [message_set()]} | {ok, #{topics => [message_set()], throttle_time => integer()}} | {error, term()}.
fetch(Topics) when is_binary(Topics) orelse is_list(Topics) ->
fetch(-1, Topics, #{}).
@equiv fetch(ReplicatID , TopicName , # { } )
-spec fetch(integer()
| binary()
| [{Topic :: binary(), [{Partition :: integer(), Offset :: integer(), MaxBytes :: integer()}]}]
| [{Topic :: binary(), [{Partition :: integer(), Offset :: integer()}]}]
| [{Topic :: binary(), [Partition :: integer()]}]
| [{Topic :: binary(), Partition :: integer()}]
| [Topic :: binary()],
binary()
| [{Topic :: binary(), [{Partition :: integer(), Offset :: integer(), MaxBytes :: integer()}]}]
| [{Topic :: binary(), [{Partition :: integer(), Offset :: integer()}]}]
| [{Topic :: binary(), [Partition :: integer()]}]
| [{Topic :: binary(), Partition :: integer()}]
| [Topic :: binary()]
| fetch_options()) -> {ok, [message_set()]} | {ok, #{topics => [message_set()], throttle_time => integer()}} | {error, term()}.
fetch(ReplicatID, Topics) when is_integer(ReplicatID), (is_binary(Topics) orelse is_list(Topics)) ->
fetch(ReplicatID, Topics, #{});
fetch(Topics, Options) when is_map(Options), (is_binary(Topics) orelse is_list(Topics)) ->
fetch(-1, Topics, Options).
< li><tt > partition : : > : The i d of the partition to fetch , if not specified . < i > This option exist for compatibility but it will be removed
< li><tt > offset : : > : The default offset to begin this fetch from , if not specified . < i > This option exist for compatibility but it will be removed
< li><tt > response_max_bytes : : > : Maximum bytes to accumulate in the response . Note that this is not an absolute maximum , if the first message
in the first non - empty partition of the fetch is larger than this value , the message will still be returned to ensure that progress can be made .
< li><tt > max_bytes : : > : The maximum bytes to include in the message set for this partition . This helps bound the size of the response ( default :
1024 * 1024 ) < i > This option exist for compatibility but it will be removed in the next major release.</i></li >
< li><tt > min_bytes : : > : This is the minimum number of bytes of messages that must be available to give a response . If the client sets this to 0
set to 1 , the server will respond as soon as at least one partition has at least 1 byte of data or the specified timeout occurs . By setting higher values in
MaxWaitTime to 100 ms and setting MinBytes to 64k would allow the server to wait up to to try to accumulate 64k of data before responding ) ( default :
< li><tt > max_wait_time : : > : The wait time is the maximum amount of time in milliseconds to block waiting if insufficient data is available
ReplicatID must < b > always</b > be -1 .
Response1 = kafe : fetch(<<"topic">> ; , # { offset = & gt ; 2 , partition = & gt ; 3 } ) .
Response2 = fetch(-1 , [ { Topic , [ { Partition , Offset , MaxBytes , Options ) .
Response5 = fetch(-1 , [ { Topic , Partition } ] , Options ) .
< a href=" / confluence / display / / A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol - FetchAPI">Kafka protocol documentation</a > .
-spec fetch(integer(),
binary()
| [{Topic :: binary(), [{Partition :: integer(), Offset :: integer(), MaxBytes :: integer()}]}]
| [{Topic :: binary(), [{Partition :: integer(), Offset :: integer()}]}]
| [{Topic :: binary(), [Partition :: integer()]}]
| [{Topic :: binary(), Partition :: integer()}]
| [Topic :: binary()],
fetch_options()) -> {ok, [message_set()]} | {ok, #{topics => [message_set()], throttle_time => integer()}} | {error, term()}.
fetch(ReplicatID, TopicName, Options) when is_integer(ReplicatID), is_binary(TopicName), is_map(Options) ->
fetch(ReplicatID, [TopicName], Options);
fetch(ReplicatID, Topics, Options) when is_integer(ReplicatID), is_list(Topics), is_map(Options) ->
kafe_protocol_fetch:run(ReplicatID, Topics, Options).
-spec list_groups() -> {ok, groups_list()} | {error, term()}.
list_groups() ->
{ok, lists:map(fun(BrokerName) ->
case list_groups(BrokerName) of
{ok, Groups} ->
#{broker => BrokerName,
groups => Groups};
_ ->
#{broker => BrokerName,
groups => #{error_code => broker_not_available,
groups => []}}
end
end, brokers())}.
< a href=" / confluence / display / / A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol - ListGroupsRequest">Kafka protocol documentation</a >
-spec list_groups(BrokerIDOrName :: broker_id() | broker_name()) -> {ok, groups()} | {error, term()}.
list_groups(BrokerIDOrName) ->
kafe_protocol_list_groups:run(BrokerIDOrName).
< a href=" / confluence / display / / A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol - ConsumerMetadataRequest">Kafka protocol documentation</a > .
-spec group_coordinator(binary()) -> {ok, group_coordinator()} | {error, term()}.
group_coordinator(ConsumerGroup) ->
kafe_protocol_group_coordinator:run(ConsumerGroup).
-alias consumer_metadata.
join_group(GroupID) ->
join_group(GroupID, #{}).
Join Group
< li><tt > session_timeout : : > : The coordinator considers the consumer dead if it receives no heartbeat after this timeout in ms . ( default : 10000)</li >
< li><tt > rebalance_timeout : : > : The maximum time that the coordinator will wait for each member to rejoin when rebalancing the group . ( default : 20000)</li >
< li><tt > member_id : : binary()</tt > : The assigned consumer i d or an empty string for a new consumer . When a member first joins the group , the memberID must be
empty ( i.e. & lt;<>> ; , default ) , but a rejoining member should use the same memberID from the previous generation.</li >
< li><tt > protocol_type : : binary()</tt > : Unique name for class of protocols implemented by group ( default & lt;<"consumer">>).</li >
< li><tt > protocols : : [ protocol()]</tt > : List of protocols.</li >
< a href=" / confluence / display / / A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol - JoinGroupRequest">Kafka protocol documentation</a > .
-spec join_group(binary(), join_group_options()) -> {error, term()} | {ok, group_join()}.
join_group(GroupID, Options) ->
kafe_protocol_join_group:run(GroupID, Options).
href=" / confluence / display / / A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol - JoinGroupRequest">Kafka Protocol Guide</a > .
-spec default_protocol(Name :: binary(), Version :: integer(), Topics :: topics(), UserData :: binary()) -> protocol().
default_protocol(Name, Version, Topics, UserData) when is_binary(Name),
is_integer(Version),
is_list(Topics),
is_binary(UserData) ->
EncodedTopics = lists:map(fun(E) ->
kafe_protocol:encode_string(bucs:to_binary(E))
end, Topics),
<<(kafe_protocol:encode_string(Name))/binary,
Version:16/signed,
(kafe_protocol:encode_array(EncodedTopics))/binary,
(kafe_protocol:encode_bytes(UserData))/binary>>.
SyncGroup immediately after joining the group , but only the leader provides the group 's assignment .
kafe : sync_group(<<"my_group">> ; , 1 , & lt;<"kafka-6dbb08f4 - a0dc-4f4c - a0b9 - dccb4d03ff2c">> ; ,
[ # { member_id = & gt ; & lt;<"kafka-6dbb08f4 - a0dc-4f4c - a0b9 - dccb4d03ff2c">> ; ,
member_assignment = & gt ; # { version = & gt ; 0 ,
partition_assignment = & gt ; [ # { topic = & gt ; & lt;<"topic0">> ; ,
partitions = & gt ; [ 0 , 1 , 2 ] } ,
# { topic = & gt ; & lt;<"topic1">> ; ,
partitions = & gt ; [ 0 , 1 , 2 ] } ] } } ,
# { member_id = & gt ; & lt;<"kafka-0b7e179d-3ff9 - 46d2 - b652 - e0d041e4264a">> ; ,
member_assignment = & gt ; # { version = & gt ; 0 ,
partition_assignment = & gt ; [ # { topic = & gt ; & lt;<"topic0">> ; ,
partitions = & gt ; [ 0 , 1 , 2 ] } ,
# { topic = & gt ; & lt;<"topic1">> ; ,
partitions = & gt ; [ 0 , 1 , 2 ] } ] } } ] ) .
< a href=" / confluence / display / / A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol - SyncGroupRequest">Kafka protocol documentation</a > .
-spec sync_group(binary(), integer(), binary(), [group_assignment()]) -> {error, term()} | {ok, sync_group()}.
sync_group(GroupID, GenerationID, MemberID, Assignments) ->
kafe_protocol_sync_group:run(GroupID, GenerationID, MemberID, Assignments).
< a href=" / confluence / display / / A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol - HeartbeatRequest">Kafka protocol documentation</a > .
-spec heartbeat(binary(), integer(), binary()) -> {error, term()} | {ok, response_code()}.
heartbeat(GroupID, GenerationID, MemberID) ->
kafe_protocol_heartbeat:run(GroupID, GenerationID, MemberID).
< a href=" / confluence / display / / A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol - LeaveGroupRequest">Kafka protocol documentation</a > .
-spec leave_group(binary(), binary()) -> {error, term()} | {ok, response_code()}.
leave_group(GroupID, MemberID) ->
kafe_protocol_leave_group:run(GroupID, MemberID).
< a href=" / confluence / display / / A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol - DescribeGroupsRequest">Kafka protocol documentation</a > .
-spec describe_group(binary()) -> {error, term()} | {ok, describe_group()}.
describe_group(GroupID) when is_binary(GroupID) ->
kafe_protocol_describe_group:run(GroupID).
< a href=" / confluence / display / / A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol - OffsetCommitRequest">Kafka protocol documentation</a > .
-spec offset_commit(binary(), offset_commit_topics()) -> {ok, [offset_commit_set()]} | {error, term()}.
offset_commit(ConsumerGroup, Topics) ->
kafe_protocol_consumer_offset_commit:run_v0(ConsumerGroup, Topics).
< a href=" / confluence / display / / A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol - OffsetCommitRequest">Kafka protocol documentation</a > .
-spec offset_commit(binary(), integer(), binary(), offset_commit_topics_v1()) -> {ok, [offset_commit_set()]} | {error, term()}.
offset_commit(ConsumerGroup, ConsumerGroupGenerationID, ConsumerID, Topics) ->
kafe_protocol_consumer_offset_commit:run_v1(ConsumerGroup,
ConsumerGroupGenerationID,
ConsumerID,
Topics).
< a href=" / confluence / display / / A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol - OffsetCommitRequest">Kafka protocol documentation</a > .
-spec offset_commit(binary(), integer(), binary(), integer(), offset_commit_topics()) -> {ok, [offset_commit_set()]} | {error, term()}.
offset_commit(ConsumerGroup, ConsumerGroupGenerationID, ConsumerID, RetentionTime, Topics) ->
kafe_protocol_consumer_offset_commit:run_v2(ConsumerGroup,
ConsumerGroupGenerationID,
ConsumerID,
RetentionTime,
Topics).
-spec offset_fetch(binary()) -> {ok, [offset_fetch_set()]}.
offset_fetch(ConsumerGroup) ->
offset_fetch(ConsumerGroup, []).
< a href=" / confluence / display / / A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol - OffsetFetchRequest">Kafka protocol documentation</a > .
-spec offset_fetch(binary(), offset_fetch_options()) -> {ok, [offset_fetch_set()]} | {error, term()}.
offset_fetch(ConsumerGroup, Options) when is_binary(ConsumerGroup), is_list(Options) ->
kafe_protocol_consumer_offset_fetch:run(ConsumerGroup, Options);
offset_fetch(ConsumerGroup, Options) when is_list(Options) ->
offset_fetch(bucs:to_binary(ConsumerGroup), Options).
-spec offsets(binary() | {binary(), [integer()]}, binary(), integer()) -> [{integer(), integer()}] | error.
offsets(TopicName, ConsumerGroup, Nth) when is_binary(TopicName) ->
offsets({TopicName, partitions(TopicName)}, ConsumerGroup, Nth);
offsets({TopicName, PartitionsList}, ConsumerGroup, Nth) ->
case offset([TopicName]) of
{ok, [#{name := TopicName, partitions := Partitions}]} ->
{Offsets, PartitionsID} = lists:foldl(fun
(#{id := PartitionID,
offsets := [Offset|_],
error_code := none},
{AccOffs, AccParts} = Acc) ->
case lists:member(PartitionID, PartitionsList) of
true ->
{[{PartitionID, Offset - 1}|AccOffs], [PartitionID|AccParts]};
false ->
Acc
end;
(_, Acc) ->
Acc
end, {[], []}, Partitions),
case offset_fetch(ConsumerGroup, [{TopicName, PartitionsID}]) of
{ok, [#{name := TopicName, partitions_offset := PartitionsOffset}]} ->
CurrentOffsets = lists:foldl(fun
(#{offset := Offset1,
partition := PartitionID1},
Acc1) ->
[{PartitionID1, Offset1 + 1}|Acc1];
(_, Acc1) ->
Acc1
end, [], PartitionsOffset),
CombinedOffsets = lists:foldl(fun({P, O}, Acc) ->
case lists:keyfind(P, 1, CurrentOffsets) of
{P, C} when C =< O -> [{P, O, C}|Acc];
_ -> Acc
end
end, [], Offsets),
lager:debug("Offsets = ~p / CurrentOffsets = ~p / CombinedOffsets = ~p", [Offsets, CurrentOffsets, CombinedOffsets]),
{NewOffsets, Result} = get_offsets_list(CombinedOffsets, [], [], Nth),
lists:foldl(fun({PartitionID, NewOffset}, Acc) ->
case offset_commit(ConsumerGroup,
[{TopicName, [{PartitionID, NewOffset, <<>>}]}]) of
{ok, [#{name := TopicName,
partitions := [#{partition := PartitionID,
error_code := none}]}]} ->
Acc;
_ ->
delete_offset_for_partition(PartitionID, Acc)
end
end, Result, NewOffsets);
_ ->
lager:error("Can't retrieve offsets for consumer group ~s on topic ~s", [ConsumerGroup, TopicName]),
error
end;
_ ->
lager:error("Can't retrieve offsets for topic ~s", [TopicName]),
error
end.
-spec offsets(binary(), binary()) -> [{integer(), integer()}] | error.
offsets(TopicName, ConsumerGroup) ->
offsets(TopicName, ConsumerGroup, -1).
get_offsets_list(Offsets, Result, Final, Nth) when Offsets =/= [], length(Result) =/= Nth ->
[{PartitionID, MaxOffset, CurrentOffset}|SortedOffsets] = lists:sort(fun({_, O1, C1}, {_, O2, C2}) -> (C1 < C2) and (O1 < O2) end, Offsets),
Offsets1 = if
CurrentOffset + 1 > MaxOffset -> SortedOffsets;
true -> [{PartitionID, MaxOffset, CurrentOffset + 1}|SortedOffsets]
end,
Final1 = lists:keystore(PartitionID, 1, Final, {PartitionID, CurrentOffset}),
get_offsets_list(Offsets1, [{PartitionID, CurrentOffset}|Result], Final1, Nth);
get_offsets_list(_, Result, Final, _) -> {Final, lists:reverse(Result)}.
delete_offset_for_partition(PartitionID, Offsets) ->
case lists:keyfind(PartitionID, 1, Offsets) of
false -> Offsets;
_ -> delete_offset_for_partition(PartitionID, lists:keydelete(PartitionID, 1, Offsets))
end.
< li><tt > session_timeout : : > : The coordinator considers the consumer dead if it receives no heartbeat after this timeout in ms . ( default : 10000)</li >
< li><tt > member_id : : binary()</tt > : The assigned consumer i d or an empty string for a new consumer . When a member first joins the group , the memberID must be
empty ( i.e. & lt;<>> ; , default ) , but a rejoining member should use the same memberID from the previous generation.</li >
< li><tt > fetch_interval : : > : Fetch interval in ms ( default : 10)</li >
< li><tt > max_bytes : : > : The maximum bytes to include in the message set for this partition . This helps bound the size of the response ( default :
1024 * 1024)</li >
< li><tt > min_bytes : : > : This is the minimum number of bytes of messages that must be available to give a response . If the client sets this to 0
set to 1 , the server will respond as soon as at least one partition has at least 1 byte of data or the specified timeout occurs . By setting higher values in
MaxWaitTime to 100 ms and setting MinBytes to 64k would allow the server to wait up to to try to accumulate 64k of data before responding ) ( default :
< li><tt > max_wait_time : : > : The wait time is the maximum amount of time in milliseconds to block waiting if insufficient data is available
< li><tt > on_start_fetching : : fun((GroupID : : binary ( ) ) - > any ( ) ) | { atom ( ) , atom()}</tt > : Function called when the fetcher start / restart fetching . ( default : >
< li><tt > on_stop_fetching : : fun((GroupID : : binary ( ) ) - > any ( ) ) | { atom ( ) , atom()}</tt > : Function called when the fetcher stop fetching . ( default : >
( default : >
partitions ' assignments change . The first parameter is the consumer group ID , the second is the list of { topic , partition } that were unassigned , the third
parameter is the list of { topic , partition } that were reassigned . ( default : >
< li><tt > errors_actions : : map()</tt > : < /li >
-spec start_consumer(GroupID :: binary(),
Callback :: fun((GroupID :: binary(),
Topic :: binary(),
PartitionID :: integer(),
Offset :: integer(),
Key :: binary(),
Value :: binary()) -> ok | {error, term()})
| fun((Message :: kafe_consumer_subscriber:message()) -> ok | {error, term()})
| atom()
| {atom(), list(term())},
Options :: consumer_options()) -> {ok, GroupPID :: pid()} | {error, term()}.
start_consumer(GroupID, Callback, Options) when is_function(Callback, 6);
is_function(Callback, 1);
is_atom(Callback);
is_tuple(Callback) ->
kafe_consumer_sup:start_child(GroupID, Options#{callback => Callback}).
-spec stop_consumer(GroupID :: binary()) -> ok | {error, not_found | simple_one_for_one | detached}.
stop_consumer(GroupID) ->
kafe_consumer_sup:stop_child(GroupID).
-spec consumer_infos(GroupID :: binary()) -> {ok, list()} | {error, term()}.
consumer_infos(GroupID) ->
case lists:member(GroupID, [bucs:to_binary(G) || G <- consumer_groups()]) of
true ->
{ok, [{Name, kafe_consumer_store:value(GroupID, Name)} || Name <- [generation_id, member_id, topics]]};
false ->
{error, group_does_not_exist}
end.
-spec consumer_groups() -> [binary()].
consumer_groups() ->
kafe_consumer_sup:consumer_groups().
|
64aeba9c22aa7348d555f9ec0324d9125763477236bf0624175f11405fe96a41 | uim/sigscheme | test-values.scm | Filename : test-values.scm
;; About : unit tests for multiple values
;;
Copyright ( C ) 2006 YAMAMOTO Kengo < yamaken AT >
Copyright ( c ) 2007 - 2008 SigScheme Project < uim - en AT googlegroups.com >
;;
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
1 . Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
2 . Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in the
;; documentation and/or other materials provided with the distribution.
3 . Neither the name of authors nor the names of its contributors
;; may be used to endorse or promote products derived from this software
;; without specific prior written permission.
;;
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ` ` AS
;; IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
;; THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
;; PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
;; CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO ,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR
;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS
;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(require-extension (unittest))
(define tn test-name)
;;
;; values
;;
;; These tests use explicit equivalence predicates instead of assert-equal?, to
;; avoid being affected by multiple-values -specific behavior.
(tn "values invalid forms")
Normal continuations accept exactly one value only .
(assert-error (tn) (lambda () (eq? '() (values))))
(assert-error (tn) (lambda () (eq? '() (apply values '()))))
(assert-error (tn) (lambda () (eq? '() (values . 1))))
(assert-error (tn) (lambda () (eq? '() (values 1 2))))
(assert-error (tn) (lambda () (eq? '() (apply values '(1 2)))))
(assert-error (tn) (lambda () (eq? '() (values 1 . 2))))
(tn "values disallowed places")
;; top-level variable
(assert-error (tn) (lambda () (eval '(define foo (values 1 2 3))
(interaction-environment))))
(define foo 1)
(assert-error (tn) (lambda () (eval '(set! foo (values 1 2 3))
(interaction-environment))))
;; internal variable
(assert-error (tn) (lambda () (define bar (values 1 2 3))))
;; others
(assert-error (tn) (lambda () (let ((bar (values 1 2 3))) #t)))
(assert-error (tn) (lambda () (let* ((bar (values 1 2 3))) #t)))
(assert-error (tn) (lambda () (letrec ((bar (values 1 2 3))) #t)))
(assert-error (tn) (lambda () (if (values 1 2 3) #t)))
(assert-error (tn) (lambda () (and (values 1 2 3) #t)))
(assert-error (tn) (lambda () (or (values 1 2 3) #t)))
(assert-error (tn) (lambda () (cond ((values 1 2 3) #t) (else #t))))
(assert-error (tn) (lambda () (case (values 1 2 3) (else #t))))
(assert-error (tn) (lambda () (begin (values 1 2 3) #t)))
(assert-error (tn) (lambda () ((lambda () (values 1 2 3) #t))))
(tn "values")
Exactly one value .
(assert-true (tn) (eqv? 1 (values 1)))
(assert-true (tn) (eqv? 1 (apply values '(1))))
(assert-true (tn) (eq? '() (values '())))
(assert-true (tn) (eq? '() (apply values '(()))))
(assert-true (tn) (eq? #f (values #f)))
(assert-true (tn) (eq? #f (apply values '(#f))))
Returning multiple values in top - level is allowed ( SigScheme - specific ) .
;; These forms test whether evaluations are passed without blowing up.
(values)
(values 1 2 3)
(apply values '())
(apply values '(1 2 3))
(begin
(values))
(begin
(values 1 2 3))
(begin
(apply values '()))
(begin
(apply values '(1 2 3)))
;;
;; call-with-values
;;
(tn "call-with-values invalid forms")
(assert-error (tn) (lambda ()
(call-with-values)))
(assert-error (tn) (lambda ()
(call-with-values even?)))
(assert-error (tn) (lambda ()
(call-with-values even? #t)))
(assert-error (tn) (lambda ()
(call-with-values #t even?)))
(tn "call-with-values")
(assert-equal? (tn)
-1
(call-with-values * -))
(assert-equal? (tn)
'ok
(call-with-values
(lambda () (values))
(lambda () 'ok)))
(assert-equal? (tn)
'()
(call-with-values
(lambda () (values))
(lambda args args)))
(assert-equal? (tn)
'ok
(call-with-values
(lambda () (apply values '()))
(lambda () 'ok)))
(assert-equal? (tn)
'()
(call-with-values
(lambda () (apply values '()))
(lambda args args)))
(assert-equal? (tn)
1
(call-with-values
(lambda () (values 1))
(lambda (x) x)))
(assert-equal? (tn)
'(1)
(call-with-values
(lambda () (values 1))
(lambda args args)))
(assert-equal? (tn)
1
(call-with-values
(lambda () (apply values '(1)))
(lambda (x) x)))
(assert-equal? (tn)
'(1)
(call-with-values
(lambda () (apply values '(1)))
(lambda args args)))
(assert-equal? (tn)
'(1 2)
(call-with-values
(lambda () (values 1 2))
(lambda (x y) (list x y))))
(assert-equal? (tn)
'(1 2)
(call-with-values
(lambda () (values 1 2))
(lambda args args)))
(assert-equal? (tn)
'(1 2)
(call-with-values
(lambda () (apply values '(1 2)))
(lambda (x y) (list x y))))
(assert-equal? (tn)
'(1 2)
(call-with-values
(lambda () (apply values '(1 2)))
(lambda args args)))
(tn "call-with-values by apply")
(assert-equal? (tn)
-1
(apply call-with-values (list * -)))
(assert-equal? (tn)
'ok
(apply call-with-values
(list (lambda () (values))
(lambda () 'ok))))
(assert-equal? (tn)
'()
(apply call-with-values
(list (lambda () (values))
(lambda args args))))
(assert-equal? (tn)
'ok
(apply call-with-values
(list (lambda () (apply values '()))
(lambda () 'ok))))
(assert-equal? (tn)
'()
(apply call-with-values
(list (lambda () (apply values '()))
(lambda args args))))
(assert-equal? (tn)
1
(apply call-with-values
(list (lambda () (values 1))
(lambda (x) x))))
(assert-equal? (tn)
'(1)
(apply call-with-values
(list (lambda () (values 1))
(lambda args args))))
(assert-equal? (tn)
1
(apply call-with-values
(list (lambda () (apply values '(1)))
(lambda (x) x))))
(assert-equal? (tn)
'(1)
(apply call-with-values
(list (lambda () (apply values '(1)))
(lambda args args))))
(assert-equal? (tn)
'(1 2)
(apply call-with-values
(list (lambda () (values 1 2))
(lambda (x y) (list x y)))))
(assert-equal? (tn)
'(1 2)
(apply call-with-values
(list (lambda () (values 1 2))
(lambda args args))))
(assert-equal? (tn)
'(1 2)
(apply call-with-values
(list (lambda () (apply values '(1 2)))
(lambda (x y) (list x y)))))
(assert-equal? (tn)
'(1 2)
(apply call-with-values
(list (lambda () (apply values '(1 2)))
(lambda args args))))
(tn "call-with-values misc")
;; test whether the variable is properly bound
(assert-equal? (tn)
1
((lambda (n)
(call-with-values
(lambda () (values 2 3 n))
(lambda (dummy1 dummy2 n2)
n2)))
1))
(total-report)
| null | https://raw.githubusercontent.com/uim/sigscheme/ccf1f92d6c2a0f45c15d93da82e399c2a78fe5f3/test/test-values.scm | scheme | About : unit tests for multiple values
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
notice, this list of conditions and the following disclaimer.
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
may be used to endorse or promote products derived from this software
without specific prior written permission.
IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
LOSS OF USE , DATA , OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
values
These tests use explicit equivalence predicates instead of assert-equal?, to
avoid being affected by multiple-values -specific behavior.
top-level variable
internal variable
others
These forms test whether evaluations are passed without blowing up.
call-with-values
test whether the variable is properly bound | Filename : test-values.scm
Copyright ( C ) 2006 YAMAMOTO Kengo < yamaken AT >
Copyright ( c ) 2007 - 2008 SigScheme Project < uim - en AT googlegroups.com >
1 . Redistributions of source code must retain the above copyright
2 . Redistributions in binary form must reproduce the above copyright
3 . Neither the name of authors nor the names of its contributors
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ` ` AS
EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO ,
LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS
(require-extension (unittest))
(define tn test-name)
(tn "values invalid forms")
Normal continuations accept exactly one value only .
(assert-error (tn) (lambda () (eq? '() (values))))
(assert-error (tn) (lambda () (eq? '() (apply values '()))))
(assert-error (tn) (lambda () (eq? '() (values . 1))))
(assert-error (tn) (lambda () (eq? '() (values 1 2))))
(assert-error (tn) (lambda () (eq? '() (apply values '(1 2)))))
(assert-error (tn) (lambda () (eq? '() (values 1 . 2))))
(tn "values disallowed places")
(assert-error (tn) (lambda () (eval '(define foo (values 1 2 3))
(interaction-environment))))
(define foo 1)
(assert-error (tn) (lambda () (eval '(set! foo (values 1 2 3))
(interaction-environment))))
(assert-error (tn) (lambda () (define bar (values 1 2 3))))
(assert-error (tn) (lambda () (let ((bar (values 1 2 3))) #t)))
(assert-error (tn) (lambda () (let* ((bar (values 1 2 3))) #t)))
(assert-error (tn) (lambda () (letrec ((bar (values 1 2 3))) #t)))
(assert-error (tn) (lambda () (if (values 1 2 3) #t)))
(assert-error (tn) (lambda () (and (values 1 2 3) #t)))
(assert-error (tn) (lambda () (or (values 1 2 3) #t)))
(assert-error (tn) (lambda () (cond ((values 1 2 3) #t) (else #t))))
(assert-error (tn) (lambda () (case (values 1 2 3) (else #t))))
(assert-error (tn) (lambda () (begin (values 1 2 3) #t)))
(assert-error (tn) (lambda () ((lambda () (values 1 2 3) #t))))
(tn "values")
Exactly one value .
(assert-true (tn) (eqv? 1 (values 1)))
(assert-true (tn) (eqv? 1 (apply values '(1))))
(assert-true (tn) (eq? '() (values '())))
(assert-true (tn) (eq? '() (apply values '(()))))
(assert-true (tn) (eq? #f (values #f)))
(assert-true (tn) (eq? #f (apply values '(#f))))
Returning multiple values in top - level is allowed ( SigScheme - specific ) .
(values)
(values 1 2 3)
(apply values '())
(apply values '(1 2 3))
(begin
(values))
(begin
(values 1 2 3))
(begin
(apply values '()))
(begin
(apply values '(1 2 3)))
(tn "call-with-values invalid forms")
(assert-error (tn) (lambda ()
(call-with-values)))
(assert-error (tn) (lambda ()
(call-with-values even?)))
(assert-error (tn) (lambda ()
(call-with-values even? #t)))
(assert-error (tn) (lambda ()
(call-with-values #t even?)))
(tn "call-with-values")
(assert-equal? (tn)
-1
(call-with-values * -))
(assert-equal? (tn)
'ok
(call-with-values
(lambda () (values))
(lambda () 'ok)))
(assert-equal? (tn)
'()
(call-with-values
(lambda () (values))
(lambda args args)))
(assert-equal? (tn)
'ok
(call-with-values
(lambda () (apply values '()))
(lambda () 'ok)))
(assert-equal? (tn)
'()
(call-with-values
(lambda () (apply values '()))
(lambda args args)))
(assert-equal? (tn)
1
(call-with-values
(lambda () (values 1))
(lambda (x) x)))
(assert-equal? (tn)
'(1)
(call-with-values
(lambda () (values 1))
(lambda args args)))
(assert-equal? (tn)
1
(call-with-values
(lambda () (apply values '(1)))
(lambda (x) x)))
(assert-equal? (tn)
'(1)
(call-with-values
(lambda () (apply values '(1)))
(lambda args args)))
(assert-equal? (tn)
'(1 2)
(call-with-values
(lambda () (values 1 2))
(lambda (x y) (list x y))))
(assert-equal? (tn)
'(1 2)
(call-with-values
(lambda () (values 1 2))
(lambda args args)))
(assert-equal? (tn)
'(1 2)
(call-with-values
(lambda () (apply values '(1 2)))
(lambda (x y) (list x y))))
(assert-equal? (tn)
'(1 2)
(call-with-values
(lambda () (apply values '(1 2)))
(lambda args args)))
(tn "call-with-values by apply")
(assert-equal? (tn)
-1
(apply call-with-values (list * -)))
(assert-equal? (tn)
'ok
(apply call-with-values
(list (lambda () (values))
(lambda () 'ok))))
(assert-equal? (tn)
'()
(apply call-with-values
(list (lambda () (values))
(lambda args args))))
(assert-equal? (tn)
'ok
(apply call-with-values
(list (lambda () (apply values '()))
(lambda () 'ok))))
(assert-equal? (tn)
'()
(apply call-with-values
(list (lambda () (apply values '()))
(lambda args args))))
(assert-equal? (tn)
1
(apply call-with-values
(list (lambda () (values 1))
(lambda (x) x))))
(assert-equal? (tn)
'(1)
(apply call-with-values
(list (lambda () (values 1))
(lambda args args))))
(assert-equal? (tn)
1
(apply call-with-values
(list (lambda () (apply values '(1)))
(lambda (x) x))))
(assert-equal? (tn)
'(1)
(apply call-with-values
(list (lambda () (apply values '(1)))
(lambda args args))))
(assert-equal? (tn)
'(1 2)
(apply call-with-values
(list (lambda () (values 1 2))
(lambda (x y) (list x y)))))
(assert-equal? (tn)
'(1 2)
(apply call-with-values
(list (lambda () (values 1 2))
(lambda args args))))
(assert-equal? (tn)
'(1 2)
(apply call-with-values
(list (lambda () (apply values '(1 2)))
(lambda (x y) (list x y)))))
(assert-equal? (tn)
'(1 2)
(apply call-with-values
(list (lambda () (apply values '(1 2)))
(lambda args args))))
(tn "call-with-values misc")
(assert-equal? (tn)
1
((lambda (n)
(call-with-values
(lambda () (values 2 3 n))
(lambda (dummy1 dummy2 n2)
n2)))
1))
(total-report)
|
b246ef897246c280feb8714a457f73eccbae7bfcefd5b62defaf3ac847bbf4c6 | electric-sql/vaxine | antidote_crdt_map_rr.erl | %% -------------------------------------------------------------------
%%
Copyright < 2013 - 2018 > <
Technische Universität Kaiserslautern , Germany
, France
Universidade NOVA de Lisboa , Portugal
Université catholique de Louvain ( UCL ) , Belgique
, Portugal
%% >
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either expressed or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
List of the contributors to the development of Antidote : see file .
%% Description and complete License: see LICENSE file.
%% -------------------------------------------------------------------
%% @doc module antidote_crdt_map_rr - A CRDT map datatype with a reset functionality
%%
%% Inserting a new element in the map:
%% if element already there -> do nothing
%% if not create a map entry where value is initial state of the embedded
%% data type (a call to the create function of the embedded data type)
%%
Update operations on entries(embedded CRDTs ) are calls to the update functions of the entries .
%%
%% Deleting an entry in the map:
%% 1- calls the reset function of this entry (tries to reset entry to its initial state)
%% As reset only affects operations that are locally (where reset was invoked) seen
%% i.e. operations on the same entry that are concurrent to the reset operation are
%% not affected and their effect should be observable once delivered.
%%
%% if there were no operations concurrent to the reset (all operations where in the causal past of the reset),
%% then the state of the entry is bottom (the initial state of the entry)
%%
%% 2- checks if the state of the entry after the reset is bottom (its initial state)
%% if bottom, delete the entry from the map
%% if not bottom, keep the entry
%%
An entry exists in a map , if there is at least one update ( inserts included ) on the key , which is not followed by a remove
%%
%% Resetting the map means removing all the current entries
%%
-module(antidote_crdt_map_rr).
-behaviour(antidote_crdt).
%% API
-export([
new/0,
value/1,
update/2,
equal/2,
get/2,
to_binary/1,
from_binary/1,
is_operation/1,
downstream/2,
require_state_downstream/1,
is_bottom/1
]).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
-type typedKey() :: {Key :: term(), Type :: atom()}.
-type state() :: dict:dict(typedKey(), {NestedState :: term()}).
-type op() ::
{update, nested_op()}
| {update, [nested_op()]}
| {remove, typedKey()}
| {remove, [typedKey()]}
| {batch, {Updates :: [nested_op()], Removes :: [typedKey()]}}
| {reset, {}}.
-type nested_op() :: {typedKey(), Op :: term()}.
-type effect() ::
{Adds :: [nested_downstream()], Removed :: [nested_downstream()]}.
-type nested_downstream() :: {typedKey(), none | {ok, Effect :: term()}}.
-type value() :: orddict:orddict(typedKey(), term()).
-spec new() -> state().
new() ->
dict:new().
-spec value(state()) -> value().
value(Map) ->
lists:sort([
{{Key, Type}, antidote_crdt:value(Type, Value)}
|| {{Key, Type}, Value} <- dict:to_list(Map)
]).
% get a value from the map
% returns empty value if the key is not present in the map
-spec get(typedKey(), value()) -> term().
get({_K, Type} = Key, Map) ->
case orddict:find(Key, Map) of
{ok, Val} -> Val;
error -> antidote_crdt:value(Type, antidote_crdt:new(Type))
end.
-spec require_state_downstream(op()) -> boolean().
require_state_downstream(_Op) ->
true.
-spec downstream(op(), state()) -> {ok, effect()}.
downstream({update, {{Key, Type}, Op}}, CurrentMap) ->
downstream({update, [{{Key, Type}, Op}]}, CurrentMap);
downstream({update, NestedOps}, CurrentMap) ->
downstream({batch, {NestedOps, []}}, CurrentMap);
downstream({remove, {Key, Type}}, CurrentMap) ->
downstream({remove, [{Key, Type}]}, CurrentMap);
downstream({remove, Keys}, CurrentMap) ->
downstream({batch, {[], Keys}}, CurrentMap);
downstream({batch, {Updates, Removes}}, CurrentMap) ->
UpdateEffects = [generate_downstream_update(Op, CurrentMap) || Op <- Updates],
RemoveEffects = [generate_downstream_remove(Key, CurrentMap) || Key <- Removes],
{ok, {UpdateEffects, RemoveEffects}};
downstream({reset, {}}, CurrentMap) ->
% reset removes all keys
AllKeys = [Key || {Key, _Val} <- value(CurrentMap)],
downstream({remove, AllKeys}, CurrentMap).
-spec generate_downstream_update({typedKey(), Op :: term()}, state()) -> nested_downstream().
generate_downstream_update({{Key, Type}, Op}, CurrentMap) ->
CurrentState =
case dict:is_key({Key, Type}, CurrentMap) of
true -> dict:fetch({Key, Type}, CurrentMap);
false -> antidote_crdt:new(Type)
end,
{ok, DownstreamEffect} = antidote_crdt:downstream(Type, Op, CurrentState),
{{Key, Type}, {ok, DownstreamEffect}}.
-spec generate_downstream_remove(typedKey(), state()) -> nested_downstream().
generate_downstream_remove({Key, Type}, CurrentMap) ->
CurrentState =
case dict:is_key({Key, Type}, CurrentMap) of
true -> dict:fetch({Key, Type}, CurrentMap);
false -> antidote_crdt:new(Type)
end,
DownstreamEffect =
case antidote_crdt:is_operation(Type, {reset, {}}) of
true ->
{ok, _} = antidote_crdt:downstream(Type, {reset, {}}, CurrentState);
false ->
none
end,
{{Key, Type}, DownstreamEffect}.
-spec update(effect(), state()) -> {ok, state()}.
update({Updates, Removes}, State) ->
State2 = lists:foldl(fun(E, S) -> update_entry(E, S) end, State, Updates),
State3 = dict:fold(fun(K, V, S) -> remove_obsolete(K, V, S) end, new(), State2),
State4 = lists:foldl(fun(E, S) -> remove_entry(E, S) end, State3, Removes),
{ok, State4}.
update_entry({{Key, Type}, {ok, Op}}, Map) ->
case dict:find({Key, Type}, Map) of
{ok, State} ->
{ok, UpdatedState} = antidote_crdt:update(Type, Op, State),
dict:store({Key, Type}, UpdatedState, Map);
error ->
NewValue = antidote_crdt:new(Type),
{ok, NewValueUpdated} = antidote_crdt:update(Type, Op, NewValue),
dict:store({Key, Type}, NewValueUpdated, Map)
end.
remove_entry({{Key, Type}, {ok, Op}}, Map) ->
case dict:find({Key, Type}, Map) of
{ok, State} ->
{ok, UpdatedState} = antidote_crdt:update(Type, Op, State),
case is_bottom(Type, UpdatedState) of
true ->
dict:erase({Key, Type}, Map);
false ->
dict:store({Key, Type}, UpdatedState, Map)
end;
error ->
Map
end;
remove_entry({{_Key, _Type}, none}, Map) ->
Map.
remove_obsolete({Key, Type}, Val, Map) ->
case is_bottom(Type, Val) of
false ->
dict:store({Key, Type}, Val, Map);
true ->
Map
end.
is_bottom(Type, State) ->
T = antidote_crdt:alias(Type),
erlang:function_exported(T, is_bottom, 1) andalso T:is_bottom(State).
equal(Map1, Map2) ->
% TODO better implementation (recursive equals)
Map1 == Map2.
-define(TAG, 101).
-define(V1_VERS, 1).
to_binary(Policy) ->
<<?TAG:8/integer, ?V1_VERS:8/integer, (term_to_binary(Policy))/binary>>.
from_binary(<<?TAG:8/integer, ?V1_VERS:8/integer, Bin/binary>>) ->
{ok, binary_to_term(Bin)}.
is_operation(Operation) ->
case Operation of
{update, {{_Key, Type}, Op}} ->
antidote_crdt:is_type(Type) andalso antidote_crdt:is_operation(Type, Op);
{update, Ops} when is_list(Ops) ->
lists:all(fun(Op) -> is_operation({update, Op}) end, Ops);
{remove, {_Key, Type}} ->
antidote_crdt:is_type(Type);
{remove, Keys} when is_list(Keys) ->
lists:all(fun(Key) -> is_operation({remove, Key}) end, Keys);
{batch, {Updates, Removes}} ->
is_list(Updates) andalso
is_list(Removes) andalso
lists:all(fun(Key) -> is_operation({remove, Key}) end, Removes) andalso
lists:all(fun(Op) -> is_operation({update, Op}) end, Updates);
{reset, {}} ->
true;
is_bottom ->
true;
_ ->
false
end.
is_bottom(Map) ->
dict:is_empty(Map).
%% ===================================================================
EUnit tests
%% ===================================================================
-ifdef(TEST).
reset1_test() ->
Map0 = new(),
% DC1: a.incr
{ok, Incr1} = downstream({update, {{a, antidote_crdt_counter_fat}, {increment, 1}}}, Map0),
{ok, Map1a} = update(Incr1, Map0),
% DC1 reset
{ok, Reset1} = downstream({reset, {}}, Map1a),
{ok, Map1b} = update(Reset1, Map1a),
% DC2 a.remove
{ok, Remove1} = downstream({remove, {a, antidote_crdt_counter_fat}}, Map0),
{ok, Map2a} = update(Remove1, Map0),
% DC2 --> DC1
{ok, Map1c} = update(Remove1, Map1b),
% DC1 reset
{ok, Reset2} = downstream({reset, {}}, Map1c),
{ok, Map1d} = update(Reset2, Map1c),
% DC1: a.incr
{ok, Incr2} = downstream({update, {{a, antidote_crdt_counter_fat}, {increment, 2}}}, Map1d),
{ok, Map1e} = update(Incr2, Map1d),
io:format("Map0 = ~p~n", [Map0]),
io:format("Incr1 = ~p~n", [Incr1]),
io:format("Map1a = ~p~n", [Map1a]),
io:format("Reset1 = ~p~n", [Reset1]),
io:format("Map1b = ~p~n", [Map1b]),
io:format("Remove1 = ~p~n", [Remove1]),
io:format("Map2a = ~p~n", [Map2a]),
io:format("Map1c = ~p~n", [Map1c]),
io:format("Reset2 = ~p~n", [Reset2]),
io:format("Map1d = ~p~n", [Map1d]),
io:format("Incr2 = ~p~n", [Incr2]),
io:format("Map1e = ~p~n", [Map1e]),
?assertEqual([], value(Map0)),
?assertEqual([{{a, antidote_crdt_counter_fat}, 1}], value(Map1a)),
?assertEqual([], value(Map1b)),
?assertEqual([], value(Map2a)),
?assertEqual([], value(Map1c)),
?assertEqual([], value(Map1d)),
?assertEqual([{{a, antidote_crdt_counter_fat}, 2}], value(Map1e)).
reset2_test() ->
Map0 = new(),
% DC1: s.add
{ok, Add1} = downstream({update, {{s, antidote_crdt_set_rw}, {add, a}}}, Map0),
{ok, Map1a} = update(Add1, Map0),
% DC1 reset
{ok, Reset1} = downstream({reset, {}}, Map1a),
{ok, Map1b} = update(Reset1, Map1a),
% DC2 s.remove
{ok, Remove1} = downstream({remove, {s, antidote_crdt_set_rw}}, Map0),
{ok, Map2a} = update(Remove1, Map0),
% DC2 --> DC1
{ok, Map1c} = update(Remove1, Map1b),
% DC1 reset
{ok, Reset2} = downstream({reset, {}}, Map1c),
{ok, Map1d} = update(Reset2, Map1c),
% DC1: s.add
{ok, Add2} = downstream({update, {{s, antidote_crdt_set_rw}, {add, b}}}, Map1d),
{ok, Map1e} = update(Add2, Map1d),
io:format("Map0 = ~p~n", [value(Map0)]),
io:format("Add1 = ~p~n", [Add1]),
io:format("Map1a = ~p~n", [value(Map1a)]),
io:format("Reset1 = ~p~n", [Reset1]),
io:format("Map1b = ~p~n", [value(Map1b)]),
io:format("Remove1 = ~p~n", [Remove1]),
io:format("Map2a = ~p~n", [value(Map2a)]),
io:format("Map1c = ~p~n", [value(Map1c)]),
io:format("Reset2 = ~p~n", [Reset2]),
io:format("Map1d = ~p~n", [value(Map1d)]),
io:format("Add2 = ~p~n", [Add2]),
io:format("Map1e = ~p~n", [value(Map1e)]),
?assertEqual([], value(Map0)),
?assertEqual([{{s, antidote_crdt_set_rw}, [a]}], value(Map1a)),
?assertEqual([], value(Map1b)),
?assertEqual([], value(Map2a)),
?assertEqual([], value(Map1c)),
?assertEqual([], value(Map1d)),
?assertEqual([{{s, antidote_crdt_set_rw}, [b]}], value(Map1e)).
prop1_test() ->
Map0 = new(),
% DC1: s.add
{ok, Add1} = downstream(
{update, {{a, antidote_crdt_map_rr}, {update, {{a, antidote_crdt_set_rw}, {add, a}}}}}, Map0
),
{ok, Map1a} = update(Add1, Map0),
% DC1 reset
{ok, Reset1} = downstream({remove, {a, antidote_crdt_map_rr}}, Map1a),
{ok, Map1b} = update(Reset1, Map1a),
io:format("Map0 = ~p~n", [Map0]),
io:format("Add1 = ~p~n", [Add1]),
io:format("Map1a = ~p~n", [Map1a]),
io:format("Reset1 = ~p~n", [Reset1]),
io:format("Map1b = ~p~n", [Map1b]),
?assertEqual([], value(Map0)),
?assertEqual([{{a, antidote_crdt_map_rr}, [{{a, antidote_crdt_set_rw}, [a]}]}], value(Map1a)),
?assertEqual([], value(Map1b)).
prop2_test() ->
Map0 = new(),
% DC1: update remove
{ok, Add1} = downstream(
{update, [{{b, antidote_crdt_map_rr}, {remove, {a, antidote_crdt_set_rw}}}]}, Map0
),
{ok, Map1a} = update(Add1, Map0),
% DC2 remove
{ok, Remove2} = downstream({remove, {b, antidote_crdt_map_rr}}, Map0),
{ok, Map2a} = update(Remove2, Map0),
% pull DC2 -> DC1
{ok, Map1b} = update(Remove2, Map1a),
io:format("Map0 = ~p~n", [Map0]),
io:format("Add1 = ~p~n", [Add1]),
io:format("Map1a = ~p~n", [Map1a]),
io:format("Remove2 = ~p~n", [Remove2]),
io:format("Map1b = ~p~n", [Map1b]),
?assertEqual([], value(Map0)),
?assertEqual([], value(Map1a)),
?assertEqual([], value(Map2a)),
?assertEqual([], value(Map1b)).
upd(Update, State) ->
{ok, Downstream} = downstream(Update, State),
{ok, Res} = update(Downstream, State),
Res.
remove_test() ->
M1 = new(),
?assertEqual([], value(M1)),
?assertEqual(true, is_bottom(M1)),
M2 = upd(
{update, [
{{<<"a">>, antidote_crdt_set_aw}, {add, <<"1">>}},
{{<<"b">>, antidote_crdt_register_mv}, {assign, <<"2">>}},
{{<<"c">>, antidote_crdt_counter_fat}, {increment, 1}}
]},
M1
),
?assertEqual(
[
{{<<"a">>, antidote_crdt_set_aw}, [<<"1">>]},
{{<<"b">>, antidote_crdt_register_mv}, [<<"2">>]},
{{<<"c">>, antidote_crdt_counter_fat}, 1}
],
value(M2)
),
?assertEqual(false, is_bottom(M2)),
M3 = upd({reset, {}}, M2),
io:format("M3 state = ~p~n", [dict:to_list(M3)]),
?assertEqual([], value(M3)),
?assertEqual(true, is_bottom(M3)),
ok.
-endif.
| null | https://raw.githubusercontent.com/electric-sql/vaxine/83ec217b2f218c2da51ca7cd47accd31f51ec9ba/apps/antidote_crdt/src/antidote_crdt_map_rr.erl | erlang | -------------------------------------------------------------------
>
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either expressed or implied. See the License for the
specific language governing permissions and limitations
under the License.
Description and complete License: see LICENSE file.
-------------------------------------------------------------------
@doc module antidote_crdt_map_rr - A CRDT map datatype with a reset functionality
Inserting a new element in the map:
if element already there -> do nothing
if not create a map entry where value is initial state of the embedded
data type (a call to the create function of the embedded data type)
Deleting an entry in the map:
1- calls the reset function of this entry (tries to reset entry to its initial state)
As reset only affects operations that are locally (where reset was invoked) seen
i.e. operations on the same entry that are concurrent to the reset operation are
not affected and their effect should be observable once delivered.
if there were no operations concurrent to the reset (all operations where in the causal past of the reset),
then the state of the entry is bottom (the initial state of the entry)
2- checks if the state of the entry after the reset is bottom (its initial state)
if bottom, delete the entry from the map
if not bottom, keep the entry
Resetting the map means removing all the current entries
API
get a value from the map
returns empty value if the key is not present in the map
reset removes all keys
TODO better implementation (recursive equals)
===================================================================
===================================================================
DC1: a.incr
DC1 reset
DC2 a.remove
DC2 --> DC1
DC1 reset
DC1: a.incr
DC1: s.add
DC1 reset
DC2 s.remove
DC2 --> DC1
DC1 reset
DC1: s.add
DC1: s.add
DC1 reset
DC1: update remove
DC2 remove
pull DC2 -> DC1 | Copyright < 2013 - 2018 > <
Technische Universität Kaiserslautern , Germany
, France
Universidade NOVA de Lisboa , Portugal
Université catholique de Louvain ( UCL ) , Belgique
, Portugal
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
List of the contributors to the development of Antidote : see file .
Update operations on entries(embedded CRDTs ) are calls to the update functions of the entries .
An entry exists in a map , if there is at least one update ( inserts included ) on the key , which is not followed by a remove
-module(antidote_crdt_map_rr).
-behaviour(antidote_crdt).
-export([
new/0,
value/1,
update/2,
equal/2,
get/2,
to_binary/1,
from_binary/1,
is_operation/1,
downstream/2,
require_state_downstream/1,
is_bottom/1
]).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
-type typedKey() :: {Key :: term(), Type :: atom()}.
-type state() :: dict:dict(typedKey(), {NestedState :: term()}).
-type op() ::
{update, nested_op()}
| {update, [nested_op()]}
| {remove, typedKey()}
| {remove, [typedKey()]}
| {batch, {Updates :: [nested_op()], Removes :: [typedKey()]}}
| {reset, {}}.
-type nested_op() :: {typedKey(), Op :: term()}.
-type effect() ::
{Adds :: [nested_downstream()], Removed :: [nested_downstream()]}.
-type nested_downstream() :: {typedKey(), none | {ok, Effect :: term()}}.
-type value() :: orddict:orddict(typedKey(), term()).
-spec new() -> state().
new() ->
dict:new().
-spec value(state()) -> value().
value(Map) ->
lists:sort([
{{Key, Type}, antidote_crdt:value(Type, Value)}
|| {{Key, Type}, Value} <- dict:to_list(Map)
]).
-spec get(typedKey(), value()) -> term().
get({_K, Type} = Key, Map) ->
case orddict:find(Key, Map) of
{ok, Val} -> Val;
error -> antidote_crdt:value(Type, antidote_crdt:new(Type))
end.
-spec require_state_downstream(op()) -> boolean().
require_state_downstream(_Op) ->
true.
-spec downstream(op(), state()) -> {ok, effect()}.
downstream({update, {{Key, Type}, Op}}, CurrentMap) ->
downstream({update, [{{Key, Type}, Op}]}, CurrentMap);
downstream({update, NestedOps}, CurrentMap) ->
downstream({batch, {NestedOps, []}}, CurrentMap);
downstream({remove, {Key, Type}}, CurrentMap) ->
downstream({remove, [{Key, Type}]}, CurrentMap);
downstream({remove, Keys}, CurrentMap) ->
downstream({batch, {[], Keys}}, CurrentMap);
downstream({batch, {Updates, Removes}}, CurrentMap) ->
UpdateEffects = [generate_downstream_update(Op, CurrentMap) || Op <- Updates],
RemoveEffects = [generate_downstream_remove(Key, CurrentMap) || Key <- Removes],
{ok, {UpdateEffects, RemoveEffects}};
downstream({reset, {}}, CurrentMap) ->
AllKeys = [Key || {Key, _Val} <- value(CurrentMap)],
downstream({remove, AllKeys}, CurrentMap).
-spec generate_downstream_update({typedKey(), Op :: term()}, state()) -> nested_downstream().
generate_downstream_update({{Key, Type}, Op}, CurrentMap) ->
CurrentState =
case dict:is_key({Key, Type}, CurrentMap) of
true -> dict:fetch({Key, Type}, CurrentMap);
false -> antidote_crdt:new(Type)
end,
{ok, DownstreamEffect} = antidote_crdt:downstream(Type, Op, CurrentState),
{{Key, Type}, {ok, DownstreamEffect}}.
-spec generate_downstream_remove(typedKey(), state()) -> nested_downstream().
generate_downstream_remove({Key, Type}, CurrentMap) ->
CurrentState =
case dict:is_key({Key, Type}, CurrentMap) of
true -> dict:fetch({Key, Type}, CurrentMap);
false -> antidote_crdt:new(Type)
end,
DownstreamEffect =
case antidote_crdt:is_operation(Type, {reset, {}}) of
true ->
{ok, _} = antidote_crdt:downstream(Type, {reset, {}}, CurrentState);
false ->
none
end,
{{Key, Type}, DownstreamEffect}.
-spec update(effect(), state()) -> {ok, state()}.
update({Updates, Removes}, State) ->
State2 = lists:foldl(fun(E, S) -> update_entry(E, S) end, State, Updates),
State3 = dict:fold(fun(K, V, S) -> remove_obsolete(K, V, S) end, new(), State2),
State4 = lists:foldl(fun(E, S) -> remove_entry(E, S) end, State3, Removes),
{ok, State4}.
update_entry({{Key, Type}, {ok, Op}}, Map) ->
case dict:find({Key, Type}, Map) of
{ok, State} ->
{ok, UpdatedState} = antidote_crdt:update(Type, Op, State),
dict:store({Key, Type}, UpdatedState, Map);
error ->
NewValue = antidote_crdt:new(Type),
{ok, NewValueUpdated} = antidote_crdt:update(Type, Op, NewValue),
dict:store({Key, Type}, NewValueUpdated, Map)
end.
remove_entry({{Key, Type}, {ok, Op}}, Map) ->
case dict:find({Key, Type}, Map) of
{ok, State} ->
{ok, UpdatedState} = antidote_crdt:update(Type, Op, State),
case is_bottom(Type, UpdatedState) of
true ->
dict:erase({Key, Type}, Map);
false ->
dict:store({Key, Type}, UpdatedState, Map)
end;
error ->
Map
end;
remove_entry({{_Key, _Type}, none}, Map) ->
Map.
remove_obsolete({Key, Type}, Val, Map) ->
case is_bottom(Type, Val) of
false ->
dict:store({Key, Type}, Val, Map);
true ->
Map
end.
is_bottom(Type, State) ->
T = antidote_crdt:alias(Type),
erlang:function_exported(T, is_bottom, 1) andalso T:is_bottom(State).
equal(Map1, Map2) ->
Map1 == Map2.
-define(TAG, 101).
-define(V1_VERS, 1).
to_binary(Policy) ->
<<?TAG:8/integer, ?V1_VERS:8/integer, (term_to_binary(Policy))/binary>>.
from_binary(<<?TAG:8/integer, ?V1_VERS:8/integer, Bin/binary>>) ->
{ok, binary_to_term(Bin)}.
is_operation(Operation) ->
case Operation of
{update, {{_Key, Type}, Op}} ->
antidote_crdt:is_type(Type) andalso antidote_crdt:is_operation(Type, Op);
{update, Ops} when is_list(Ops) ->
lists:all(fun(Op) -> is_operation({update, Op}) end, Ops);
{remove, {_Key, Type}} ->
antidote_crdt:is_type(Type);
{remove, Keys} when is_list(Keys) ->
lists:all(fun(Key) -> is_operation({remove, Key}) end, Keys);
{batch, {Updates, Removes}} ->
is_list(Updates) andalso
is_list(Removes) andalso
lists:all(fun(Key) -> is_operation({remove, Key}) end, Removes) andalso
lists:all(fun(Op) -> is_operation({update, Op}) end, Updates);
{reset, {}} ->
true;
is_bottom ->
true;
_ ->
false
end.
is_bottom(Map) ->
dict:is_empty(Map).
EUnit tests
-ifdef(TEST).
reset1_test() ->
Map0 = new(),
{ok, Incr1} = downstream({update, {{a, antidote_crdt_counter_fat}, {increment, 1}}}, Map0),
{ok, Map1a} = update(Incr1, Map0),
{ok, Reset1} = downstream({reset, {}}, Map1a),
{ok, Map1b} = update(Reset1, Map1a),
{ok, Remove1} = downstream({remove, {a, antidote_crdt_counter_fat}}, Map0),
{ok, Map2a} = update(Remove1, Map0),
{ok, Map1c} = update(Remove1, Map1b),
{ok, Reset2} = downstream({reset, {}}, Map1c),
{ok, Map1d} = update(Reset2, Map1c),
{ok, Incr2} = downstream({update, {{a, antidote_crdt_counter_fat}, {increment, 2}}}, Map1d),
{ok, Map1e} = update(Incr2, Map1d),
io:format("Map0 = ~p~n", [Map0]),
io:format("Incr1 = ~p~n", [Incr1]),
io:format("Map1a = ~p~n", [Map1a]),
io:format("Reset1 = ~p~n", [Reset1]),
io:format("Map1b = ~p~n", [Map1b]),
io:format("Remove1 = ~p~n", [Remove1]),
io:format("Map2a = ~p~n", [Map2a]),
io:format("Map1c = ~p~n", [Map1c]),
io:format("Reset2 = ~p~n", [Reset2]),
io:format("Map1d = ~p~n", [Map1d]),
io:format("Incr2 = ~p~n", [Incr2]),
io:format("Map1e = ~p~n", [Map1e]),
?assertEqual([], value(Map0)),
?assertEqual([{{a, antidote_crdt_counter_fat}, 1}], value(Map1a)),
?assertEqual([], value(Map1b)),
?assertEqual([], value(Map2a)),
?assertEqual([], value(Map1c)),
?assertEqual([], value(Map1d)),
?assertEqual([{{a, antidote_crdt_counter_fat}, 2}], value(Map1e)).
reset2_test() ->
Map0 = new(),
{ok, Add1} = downstream({update, {{s, antidote_crdt_set_rw}, {add, a}}}, Map0),
{ok, Map1a} = update(Add1, Map0),
{ok, Reset1} = downstream({reset, {}}, Map1a),
{ok, Map1b} = update(Reset1, Map1a),
{ok, Remove1} = downstream({remove, {s, antidote_crdt_set_rw}}, Map0),
{ok, Map2a} = update(Remove1, Map0),
{ok, Map1c} = update(Remove1, Map1b),
{ok, Reset2} = downstream({reset, {}}, Map1c),
{ok, Map1d} = update(Reset2, Map1c),
{ok, Add2} = downstream({update, {{s, antidote_crdt_set_rw}, {add, b}}}, Map1d),
{ok, Map1e} = update(Add2, Map1d),
io:format("Map0 = ~p~n", [value(Map0)]),
io:format("Add1 = ~p~n", [Add1]),
io:format("Map1a = ~p~n", [value(Map1a)]),
io:format("Reset1 = ~p~n", [Reset1]),
io:format("Map1b = ~p~n", [value(Map1b)]),
io:format("Remove1 = ~p~n", [Remove1]),
io:format("Map2a = ~p~n", [value(Map2a)]),
io:format("Map1c = ~p~n", [value(Map1c)]),
io:format("Reset2 = ~p~n", [Reset2]),
io:format("Map1d = ~p~n", [value(Map1d)]),
io:format("Add2 = ~p~n", [Add2]),
io:format("Map1e = ~p~n", [value(Map1e)]),
?assertEqual([], value(Map0)),
?assertEqual([{{s, antidote_crdt_set_rw}, [a]}], value(Map1a)),
?assertEqual([], value(Map1b)),
?assertEqual([], value(Map2a)),
?assertEqual([], value(Map1c)),
?assertEqual([], value(Map1d)),
?assertEqual([{{s, antidote_crdt_set_rw}, [b]}], value(Map1e)).
prop1_test() ->
Map0 = new(),
{ok, Add1} = downstream(
{update, {{a, antidote_crdt_map_rr}, {update, {{a, antidote_crdt_set_rw}, {add, a}}}}}, Map0
),
{ok, Map1a} = update(Add1, Map0),
{ok, Reset1} = downstream({remove, {a, antidote_crdt_map_rr}}, Map1a),
{ok, Map1b} = update(Reset1, Map1a),
io:format("Map0 = ~p~n", [Map0]),
io:format("Add1 = ~p~n", [Add1]),
io:format("Map1a = ~p~n", [Map1a]),
io:format("Reset1 = ~p~n", [Reset1]),
io:format("Map1b = ~p~n", [Map1b]),
?assertEqual([], value(Map0)),
?assertEqual([{{a, antidote_crdt_map_rr}, [{{a, antidote_crdt_set_rw}, [a]}]}], value(Map1a)),
?assertEqual([], value(Map1b)).
prop2_test() ->
Map0 = new(),
{ok, Add1} = downstream(
{update, [{{b, antidote_crdt_map_rr}, {remove, {a, antidote_crdt_set_rw}}}]}, Map0
),
{ok, Map1a} = update(Add1, Map0),
{ok, Remove2} = downstream({remove, {b, antidote_crdt_map_rr}}, Map0),
{ok, Map2a} = update(Remove2, Map0),
{ok, Map1b} = update(Remove2, Map1a),
io:format("Map0 = ~p~n", [Map0]),
io:format("Add1 = ~p~n", [Add1]),
io:format("Map1a = ~p~n", [Map1a]),
io:format("Remove2 = ~p~n", [Remove2]),
io:format("Map1b = ~p~n", [Map1b]),
?assertEqual([], value(Map0)),
?assertEqual([], value(Map1a)),
?assertEqual([], value(Map2a)),
?assertEqual([], value(Map1b)).
upd(Update, State) ->
{ok, Downstream} = downstream(Update, State),
{ok, Res} = update(Downstream, State),
Res.
remove_test() ->
M1 = new(),
?assertEqual([], value(M1)),
?assertEqual(true, is_bottom(M1)),
M2 = upd(
{update, [
{{<<"a">>, antidote_crdt_set_aw}, {add, <<"1">>}},
{{<<"b">>, antidote_crdt_register_mv}, {assign, <<"2">>}},
{{<<"c">>, antidote_crdt_counter_fat}, {increment, 1}}
]},
M1
),
?assertEqual(
[
{{<<"a">>, antidote_crdt_set_aw}, [<<"1">>]},
{{<<"b">>, antidote_crdt_register_mv}, [<<"2">>]},
{{<<"c">>, antidote_crdt_counter_fat}, 1}
],
value(M2)
),
?assertEqual(false, is_bottom(M2)),
M3 = upd({reset, {}}, M2),
io:format("M3 state = ~p~n", [dict:to_list(M3)]),
?assertEqual([], value(M3)),
?assertEqual(true, is_bottom(M3)),
ok.
-endif.
|
b064a43dd8f1d73102001cf1899241d91122f38a608027e1ad5eb749f6de7fd1 | clj-holmes/clj-watson | vulnerability.clj | (ns clj-watson.controller.dependency-check.vulnerability
(:require
[clj-watson.diplomat.dependency :as diplomat.dependency]
[clj-watson.logic.dependency :as logic.dependency]
[clj-watson.logic.dependency-check.vulnerability :as logic.dc.vulnerability]
[clojure.string :as string]
[version-clj.core :as version])
(:import
(org.owasp.dependencycheck.dependency Dependency)))
(defn ^:private extract-vulnerabilities-information-from-dependency
[dependency dependency-current-version all-versions]
(->> (.getVulnerabilities dependency)
(pmap #(logic.dc.vulnerability/get-information dependency-current-version all-versions %))
(filterv identity)
(sort-by (comp :value first :identifiers :advisory))))
(defn ^:private safe-version-from-vulnerabilities [vulnerabilities]
(let [versions-map (->> vulnerabilities (map :safe-versions) (map last))
version-kind (first (transduce (map keys) (comp set concat) versions-map))
versions (transduce (map vals) concat versions-map)
version (last (version/version-sort versions))]
(when version
{version-kind version})))
(defn ^:private extract-from-dependency [project-dependencies repositories ^Dependency dependency]
(when-let [dependency-name (some-> dependency .getName (string/replace #":" "/") symbol)]
(let [dependency-map (first (filter #(= (:dependency %) dependency-name) project-dependencies))
dependency-current-version (logic.dependency/get-dependency-version dependency-map)
all-versions (diplomat.dependency/get-all-versions! dependency-name repositories)
vulnerabilities (extract-vulnerabilities-information-from-dependency dependency dependency-current-version all-versions)
safe-version (safe-version-from-vulnerabilities vulnerabilities)]
(when (seq vulnerabilities)
(-> dependency-map
(assoc :vulnerabilities vulnerabilities)
(assoc :secure-version safe-version)
(assoc :dependency dependency-name))))))
(defn extract [scanned-dependencies dependencies repositories]
(let [vulnerable-dependencies (->> scanned-dependencies
(map (partial extract-from-dependency dependencies repositories))
(filterv identity)
(sort-by :dependency-name))]
vulnerable-dependencies))
| null | https://raw.githubusercontent.com/clj-holmes/clj-watson/9972a334b49dd50bb9bb14314ce37e8ad566dc55/src/clj_watson/controller/dependency_check/vulnerability.clj | clojure | (ns clj-watson.controller.dependency-check.vulnerability
(:require
[clj-watson.diplomat.dependency :as diplomat.dependency]
[clj-watson.logic.dependency :as logic.dependency]
[clj-watson.logic.dependency-check.vulnerability :as logic.dc.vulnerability]
[clojure.string :as string]
[version-clj.core :as version])
(:import
(org.owasp.dependencycheck.dependency Dependency)))
(defn ^:private extract-vulnerabilities-information-from-dependency
[dependency dependency-current-version all-versions]
(->> (.getVulnerabilities dependency)
(pmap #(logic.dc.vulnerability/get-information dependency-current-version all-versions %))
(filterv identity)
(sort-by (comp :value first :identifiers :advisory))))
(defn ^:private safe-version-from-vulnerabilities [vulnerabilities]
(let [versions-map (->> vulnerabilities (map :safe-versions) (map last))
version-kind (first (transduce (map keys) (comp set concat) versions-map))
versions (transduce (map vals) concat versions-map)
version (last (version/version-sort versions))]
(when version
{version-kind version})))
(defn ^:private extract-from-dependency [project-dependencies repositories ^Dependency dependency]
(when-let [dependency-name (some-> dependency .getName (string/replace #":" "/") symbol)]
(let [dependency-map (first (filter #(= (:dependency %) dependency-name) project-dependencies))
dependency-current-version (logic.dependency/get-dependency-version dependency-map)
all-versions (diplomat.dependency/get-all-versions! dependency-name repositories)
vulnerabilities (extract-vulnerabilities-information-from-dependency dependency dependency-current-version all-versions)
safe-version (safe-version-from-vulnerabilities vulnerabilities)]
(when (seq vulnerabilities)
(-> dependency-map
(assoc :vulnerabilities vulnerabilities)
(assoc :secure-version safe-version)
(assoc :dependency dependency-name))))))
(defn extract [scanned-dependencies dependencies repositories]
(let [vulnerable-dependencies (->> scanned-dependencies
(map (partial extract-from-dependency dependencies repositories))
(filterv identity)
(sort-by :dependency-name))]
vulnerable-dependencies))
| |
f0ab4605e98ae5a797ef34a1b8e9765ca3dc45f86ed7b4e2168f7f447ff296c0 | mondemand/mondemand-server | mondemand_server.erl | -module (mondemand_server).
-include_lib ("lwes/include/lwes.hrl").
-behaviour (gen_server).
%% API
-export ([ start_link/2,
process_event/2 ]).
%% gen_server callbacks
-export ([ init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3
]).
-record (state, { listeners }).
-record (listener_state, { dispatchers }).
%%====================================================================
%% API
%%====================================================================
start_link (ListenerConfig, DispatchConfig) ->
gen_server:start_link ( { local, ?MODULE }, ?MODULE,
[ListenerConfig, DispatchConfig], []).
process_event (Event = {udp, P, SenderIp, SenderPort, Data},
State = #listener_state { dispatchers = Dispatchers }) ->
% TODO: move this into lwes library?
%
The lwes library will see if the second element of the udp packet is a
port or an integer and treat integer as the ReceiptTime . By setting the
% receipt time before we forward, this should ensure that backends all get
% the same receipt time, or don't end up with duplicate's because of delays
% and quick processing. This could probably be done in the lwes library
% since the port is normally not useful to consumers anyway.
NewEvent =
case is_port (P) of
true ->
{udp, mondemand_util:millis_since_epoch(), SenderIp, SenderPort, Data};
false ->
Event
end,
% just ignore errors, so the whole server doesn't crash
try mondemand_server_dispatcher_sup:dispatch (Dispatchers, NewEvent) of
DispatchersOut -> State#listener_state { dispatchers = DispatchersOut }
catch
E1:E2 ->
error_logger:error_msg ("Error dispatching : ~p:~p",[E1,E2]),
State
end.
%%====================================================================
%% gen_server callbacks
%%====================================================================
init ([ListenerConfig, DispatchConfig]) ->
% I want terminate to be called
process_flag (trap_exit, true),
% lwes listener config
case ListenerConfig of
undefined ->
{ stop, missing_listener_config };
L when is_list (L) ->
Channels = [ open_lwes_channel (Config, DispatchConfig) || Config <- L ],
{ ok, #state {listeners = Channels } };
Config ->
Channel = open_lwes_channel (Config, DispatchConfig),
{ ok, #state {listeners = [Channel] } }
end.
handle_call (Request, From, State) ->
error_logger:warning_msg ("~p : Unrecognized call ~p from ~p~n",
[?MODULE, Request, From]),
{ reply, ok, State }.
handle_cast (Request, State) ->
error_logger:warning_msg ("~p : Unrecognized cast ~p~n",
[?MODULE, Request]),
{ noreply, State }.
handle_info (Request, State) ->
error_logger:warning_msg ("~p : Unrecognized info ~p~n",
[?MODULE, Request]),
{noreply, State}.
terminate (_Reason, #state { listeners = Channels }) ->
[ lwes:close (Channel) || Channel <- Channels ],
ok.
code_change (_OldVsn, State, _Extra) ->
{ok, State}.
%%====================================================================
Internal functions
%%====================================================================
open_lwes_channel (LwesConfig, DispatchConfig) ->
{ok, Channel} = lwes:open (listener, LwesConfig),
ok = lwes:listen (
Channel,
fun process_event/2,
raw,
#listener_state{ dispatchers = DispatchConfig }
),
Channel.
%%====================================================================
%% Test functions
%%====================================================================
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
% include test code here
-endif.
| null | https://raw.githubusercontent.com/mondemand/mondemand-server/88e57ef8ece8a0069a747620f4585104cb560840/src/mondemand_server.erl | erlang | API
gen_server callbacks
====================================================================
API
====================================================================
TODO: move this into lwes library?
receipt time before we forward, this should ensure that backends all get
the same receipt time, or don't end up with duplicate's because of delays
and quick processing. This could probably be done in the lwes library
since the port is normally not useful to consumers anyway.
just ignore errors, so the whole server doesn't crash
====================================================================
gen_server callbacks
====================================================================
I want terminate to be called
lwes listener config
====================================================================
====================================================================
====================================================================
Test functions
====================================================================
include test code here | -module (mondemand_server).
-include_lib ("lwes/include/lwes.hrl").
-behaviour (gen_server).
-export ([ start_link/2,
process_event/2 ]).
-export ([ init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3
]).
-record (state, { listeners }).
-record (listener_state, { dispatchers }).
start_link (ListenerConfig, DispatchConfig) ->
gen_server:start_link ( { local, ?MODULE }, ?MODULE,
[ListenerConfig, DispatchConfig], []).
process_event (Event = {udp, P, SenderIp, SenderPort, Data},
State = #listener_state { dispatchers = Dispatchers }) ->
The lwes library will see if the second element of the udp packet is a
port or an integer and treat integer as the ReceiptTime . By setting the
NewEvent =
case is_port (P) of
true ->
{udp, mondemand_util:millis_since_epoch(), SenderIp, SenderPort, Data};
false ->
Event
end,
try mondemand_server_dispatcher_sup:dispatch (Dispatchers, NewEvent) of
DispatchersOut -> State#listener_state { dispatchers = DispatchersOut }
catch
E1:E2 ->
error_logger:error_msg ("Error dispatching : ~p:~p",[E1,E2]),
State
end.
init ([ListenerConfig, DispatchConfig]) ->
process_flag (trap_exit, true),
case ListenerConfig of
undefined ->
{ stop, missing_listener_config };
L when is_list (L) ->
Channels = [ open_lwes_channel (Config, DispatchConfig) || Config <- L ],
{ ok, #state {listeners = Channels } };
Config ->
Channel = open_lwes_channel (Config, DispatchConfig),
{ ok, #state {listeners = [Channel] } }
end.
handle_call (Request, From, State) ->
error_logger:warning_msg ("~p : Unrecognized call ~p from ~p~n",
[?MODULE, Request, From]),
{ reply, ok, State }.
handle_cast (Request, State) ->
error_logger:warning_msg ("~p : Unrecognized cast ~p~n",
[?MODULE, Request]),
{ noreply, State }.
handle_info (Request, State) ->
error_logger:warning_msg ("~p : Unrecognized info ~p~n",
[?MODULE, Request]),
{noreply, State}.
terminate (_Reason, #state { listeners = Channels }) ->
[ lwes:close (Channel) || Channel <- Channels ],
ok.
code_change (_OldVsn, State, _Extra) ->
{ok, State}.
Internal functions
open_lwes_channel (LwesConfig, DispatchConfig) ->
{ok, Channel} = lwes:open (listener, LwesConfig),
ok = lwes:listen (
Channel,
fun process_event/2,
raw,
#listener_state{ dispatchers = DispatchConfig }
),
Channel.
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
|
31cfa58a51193c6d70e99bb79e8605e275150d7ae5ed3cb4090357570ba16d63 | hipsleek/hipsleek | slsat.ml | #include "xdebug.cppo"
open VarGen
open Globals
open Others
open Gen
open Cformula
module CP = Cpure
: to implement
let check_sat_uo ante_uo conseq_uo=
let is_sat = true in
mk_cex is_sat
: to implement
let check_sat_with_uo ante conseq=
let is_sat = true in
mk_cex is_sat
: to implement
let check_sat_empty_rhs_with_uo_x es ante (conseq_p:CP.formula) matched_svl=
let ante_pos = ante.formula_base_pos in
let ante_w_fp = mkStar (Base ante) (formula_of_heap es.es_heap ante_pos) (Flow_combine) ante_pos in
let is_sat = match ante.formula_base_heap with
| HEmp -> true
| _ -> false (* to implement*)
in
let is_sat = false in
mk_cex is_sat
let check_sat_empty_rhs_with_uo es ante (conseq_p:CP.formula) matched_set=
let pr1 = !print_formula_base in
let pr2 = !CP.print_formula in
Debug.no_4 "check_sat_empty_rhs_with_uo" Cprinter.string_of_entail_state pr1 pr2 !CP.print_svl Cprinter.string_of_failure_cex
(fun _ _ _ _ -> check_sat_empty_rhs_with_uo_x es ante (conseq_p:CP.formula) matched_set)
es ante conseq_p matched_set
| null | https://raw.githubusercontent.com/hipsleek/hipsleek/596f7fa7f67444c8309da2ca86ba4c47d376618c/bef_indent/slsat.ml | ocaml | to implement | #include "xdebug.cppo"
open VarGen
open Globals
open Others
open Gen
open Cformula
module CP = Cpure
: to implement
let check_sat_uo ante_uo conseq_uo=
let is_sat = true in
mk_cex is_sat
: to implement
let check_sat_with_uo ante conseq=
let is_sat = true in
mk_cex is_sat
: to implement
let check_sat_empty_rhs_with_uo_x es ante (conseq_p:CP.formula) matched_svl=
let ante_pos = ante.formula_base_pos in
let ante_w_fp = mkStar (Base ante) (formula_of_heap es.es_heap ante_pos) (Flow_combine) ante_pos in
let is_sat = match ante.formula_base_heap with
| HEmp -> true
in
let is_sat = false in
mk_cex is_sat
let check_sat_empty_rhs_with_uo es ante (conseq_p:CP.formula) matched_set=
let pr1 = !print_formula_base in
let pr2 = !CP.print_formula in
Debug.no_4 "check_sat_empty_rhs_with_uo" Cprinter.string_of_entail_state pr1 pr2 !CP.print_svl Cprinter.string_of_failure_cex
(fun _ _ _ _ -> check_sat_empty_rhs_with_uo_x es ante (conseq_p:CP.formula) matched_set)
es ante conseq_p matched_set
|
ce041517fb6d91aa71020f0fc03badc834fbb829375a5b6e01097c2496b37824 | sapur/hexe | Options.hs | # LANGUAGE NoMonomorphismRestriction #
module Options (
Options (..),
Action (..),
parseOptions,
) where
import Data.Char
import Data.List
import Text.Printf
import Options.Applicative
import qualified Options.Applicative.Help as Doc
import Data.Version
data Options = Options
{ optAction :: Action
, optColumnWdt :: Maybe Int
, opt256Colors :: Maybe Bool
, optCursor :: Maybe Int
, optNamedMarks :: [(Int, String)]
, optMarks :: [Int]
, optCommands :: [String]
, optScripts :: [String]
}
deriving (Show, Read)
data Action
= Edit String
| ListKeymap
| ListBindings
deriving (Show, Read)
parseOptions version = customExecParser prefs
$ info (helper <*> infoOptions version <*> options)
$ fullDesc
<> header (printf "hexe %s - A Hex Editor " (showVersion version))
<> footerDoc description
where
prefs = defaultPrefs
{ prefDisambiguate = True
}
infoOptions version
= infoOption (versionText version) (mconcat
[ withshort 'V' "version"
, help "Print version number."
])
options = Options
<$> ( flag' ListKeymap (mconcat
[ long "list-keymap"
, help "List key bindings by input mode."
])
<|> flag' ListBindings (mconcat
[ long "list-bindings"
, help "List key bindings by category."
])
<|> argument (Edit <$> str) (mconcat
[ filevar
, help "File to open. Need not exist."
]))
<*> optional (option auto (mconcat
[ withshort 'w' "column-width"
, metavar "N"
, help "Set the initial column width to N."
]))
<*> optional (option boolReader (mconcat
[ withshort 'C' "256-colors"
, boolvar
, help "Switch between 16 [n] and 256 colors [y] palette."
]))
<*> optional (option auto (mconcat
[ withshort 'c' "cursor"
, metavar "OFFSET"
, help "Moves the cursor after opening the file."
]))
<*> many (option namedMarkReader (mconcat
[ withshort 'M' "mark"
, metavar "OFFSET[=TEXT]"
, help "Place a single mark with optional text."
]))
<*> option marksReader (mconcat
[ withshort 'm' "marks"
, defaultvar "MARKS" []
, help "List of offsets to mark. Format: 0,0x3"
])
<*> many (strOption (mconcat
[ noshort "cmd"
, metavar "CMD"
, help "Execute CMD on startup."
]))
<*> many (strOption (mconcat
[ noshort "script"
, filevar
, help "Load script from FILE and execute it."
]))
noshort l = hidden <> long l
withshort s l = hidden <> long l <> short s
defaultvar nm v = metavar nm <> value v
boolvar = metavar "Y/N" <> boolCompleter
filevar = metavar "FILE" <> action "file"
namedMarkReader = eitherReader $ \arg ->
let (offset, text) = break (== '=') arg
in case reads offset of
[(n, "")] -> return (n, drop 1 text)
_ -> Left $ printf "cannot parse mark '%s'" arg
marksReader = eitherReader $ \arg -> case reads ("[" ++ arg ++ "]") of
[(r, "")] -> return r
_ -> Left "cannot parse offset list"
trueVals = ["y", "yes", "t", "true" , "1", "on" ]
falseVals = ["n", "no" , "f", "false", "0", "off"]
boolReader = eitherReader $ \arg ->
let val = map toLower arg
in case () of
_ | val `elem` trueVals -> return True
_ | val `elem` falseVals -> return False
_ -> Left $ printf "expected 'y' or 'n', but got '%s'" arg
boolCompleter = completeWith $ trueVals ++ falseVals
description = Doc.unChunk $ Doc.vsepChunks
[ Doc.vcatChunks
[ Doc.paragraph "hexe can generate a bash completion script. To enable completion in the current shell, run:"
, Doc.stringChunk " "
, Doc.stringChunk " source <(hexe --bash-completion-script `command -v hexe`)"
]
, Doc.paragraph "Note: hexe will automatically detect how many colors the terminal supports from the environment variable TERM. However, for compatibility reasons, terminals often announce less features than they have. To enable full colors, either set TERM to a proper value, e.g. `xterm-256color', or force 256 color mode via command-line option `-C', by pressing capital `T' in the editor, or adding `256colors on' to the configuration file."
]
versionText version = intercalate "\n"
[ printf "hexe %s" (showVersion version)
]
| null | https://raw.githubusercontent.com/sapur/hexe/e01036a1f8213938f9e1c72afc6aff48ba7fb0fd/src/Options.hs | haskell | # LANGUAGE NoMonomorphismRestriction #
module Options (
Options (..),
Action (..),
parseOptions,
) where
import Data.Char
import Data.List
import Text.Printf
import Options.Applicative
import qualified Options.Applicative.Help as Doc
import Data.Version
data Options = Options
{ optAction :: Action
, optColumnWdt :: Maybe Int
, opt256Colors :: Maybe Bool
, optCursor :: Maybe Int
, optNamedMarks :: [(Int, String)]
, optMarks :: [Int]
, optCommands :: [String]
, optScripts :: [String]
}
deriving (Show, Read)
data Action
= Edit String
| ListKeymap
| ListBindings
deriving (Show, Read)
parseOptions version = customExecParser prefs
$ info (helper <*> infoOptions version <*> options)
$ fullDesc
<> header (printf "hexe %s - A Hex Editor " (showVersion version))
<> footerDoc description
where
prefs = defaultPrefs
{ prefDisambiguate = True
}
infoOptions version
= infoOption (versionText version) (mconcat
[ withshort 'V' "version"
, help "Print version number."
])
options = Options
<$> ( flag' ListKeymap (mconcat
[ long "list-keymap"
, help "List key bindings by input mode."
])
<|> flag' ListBindings (mconcat
[ long "list-bindings"
, help "List key bindings by category."
])
<|> argument (Edit <$> str) (mconcat
[ filevar
, help "File to open. Need not exist."
]))
<*> optional (option auto (mconcat
[ withshort 'w' "column-width"
, metavar "N"
, help "Set the initial column width to N."
]))
<*> optional (option boolReader (mconcat
[ withshort 'C' "256-colors"
, boolvar
, help "Switch between 16 [n] and 256 colors [y] palette."
]))
<*> optional (option auto (mconcat
[ withshort 'c' "cursor"
, metavar "OFFSET"
, help "Moves the cursor after opening the file."
]))
<*> many (option namedMarkReader (mconcat
[ withshort 'M' "mark"
, metavar "OFFSET[=TEXT]"
, help "Place a single mark with optional text."
]))
<*> option marksReader (mconcat
[ withshort 'm' "marks"
, defaultvar "MARKS" []
, help "List of offsets to mark. Format: 0,0x3"
])
<*> many (strOption (mconcat
[ noshort "cmd"
, metavar "CMD"
, help "Execute CMD on startup."
]))
<*> many (strOption (mconcat
[ noshort "script"
, filevar
, help "Load script from FILE and execute it."
]))
noshort l = hidden <> long l
withshort s l = hidden <> long l <> short s
defaultvar nm v = metavar nm <> value v
boolvar = metavar "Y/N" <> boolCompleter
filevar = metavar "FILE" <> action "file"
namedMarkReader = eitherReader $ \arg ->
let (offset, text) = break (== '=') arg
in case reads offset of
[(n, "")] -> return (n, drop 1 text)
_ -> Left $ printf "cannot parse mark '%s'" arg
marksReader = eitherReader $ \arg -> case reads ("[" ++ arg ++ "]") of
[(r, "")] -> return r
_ -> Left "cannot parse offset list"
trueVals = ["y", "yes", "t", "true" , "1", "on" ]
falseVals = ["n", "no" , "f", "false", "0", "off"]
boolReader = eitherReader $ \arg ->
let val = map toLower arg
in case () of
_ | val `elem` trueVals -> return True
_ | val `elem` falseVals -> return False
_ -> Left $ printf "expected 'y' or 'n', but got '%s'" arg
boolCompleter = completeWith $ trueVals ++ falseVals
description = Doc.unChunk $ Doc.vsepChunks
[ Doc.vcatChunks
[ Doc.paragraph "hexe can generate a bash completion script. To enable completion in the current shell, run:"
, Doc.stringChunk " "
, Doc.stringChunk " source <(hexe --bash-completion-script `command -v hexe`)"
]
, Doc.paragraph "Note: hexe will automatically detect how many colors the terminal supports from the environment variable TERM. However, for compatibility reasons, terminals often announce less features than they have. To enable full colors, either set TERM to a proper value, e.g. `xterm-256color', or force 256 color mode via command-line option `-C', by pressing capital `T' in the editor, or adding `256colors on' to the configuration file."
]
versionText version = intercalate "\n"
[ printf "hexe %s" (showVersion version)
]
| |
301e046ad81348b1ad85c65aecdb9f12e422192e71993edb73113e67292cab46 | fetburner/Coq2SML | modops.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2014
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
open Util
open Names
open Univ
open Term
open Environ
open Declarations
open Entries
open Mod_subst
(** Various operations on modules and module types *)
val module_body_of_type : module_path -> module_type_body -> module_body
val module_type_of_module : module_path option -> module_body ->
module_type_body
val destr_functor :
env -> struct_expr_body -> mod_bound_id * module_type_body * struct_expr_body
val subst_struct_expr : substitution -> struct_expr_body -> struct_expr_body
val subst_signature : substitution -> structure_body -> structure_body
val add_signature :
module_path -> structure_body -> delta_resolver -> env -> env
(** adds a module and its components, but not the constraints *)
val add_module : module_body -> env -> env
val check_modpath_equiv : env -> module_path -> module_path -> unit
val strengthen : module_type_body -> module_path -> module_type_body
val inline_delta_resolver :
env -> inline -> module_path -> mod_bound_id -> module_type_body ->
delta_resolver -> delta_resolver
val strengthen_and_subst_mb : module_body -> module_path -> bool -> module_body
val subst_modtype_and_resolver : module_type_body -> module_path ->
module_type_body
val clean_bounded_mod_expr : struct_expr_body -> struct_expr_body
(** Errors *)
type signature_mismatch_error =
| InductiveFieldExpected of mutual_inductive_body
| DefinitionFieldExpected
| ModuleFieldExpected
| ModuleTypeFieldExpected
| NotConvertibleInductiveField of identifier
| NotConvertibleConstructorField of identifier
| NotConvertibleBodyField
| NotConvertibleTypeField of env * types * types
| NotSameConstructorNamesField
| NotSameInductiveNameInBlockField
| FiniteInductiveFieldExpected of bool
| InductiveNumbersFieldExpected of int
| InductiveParamsNumberField of int
| RecordFieldExpected of bool
| RecordProjectionsExpected of name list
| NotEqualInductiveAliases
| NoTypeConstraintExpected
type module_typing_error =
| SignatureMismatch of label * structure_field_body * signature_mismatch_error
| LabelAlreadyDeclared of label
| ApplicationToNotPath of module_struct_entry
| NotAFunctor of struct_expr_body
| IncompatibleModuleTypes of module_type_body * module_type_body
| NotEqualModulePaths of module_path * module_path
| NoSuchLabel of label
| IncompatibleLabels of label * label
| SignatureExpected of struct_expr_body
| NoModuleToEnd
| NoModuleTypeToEnd
| NotAModule of string
| NotAModuleType of string
| NotAConstant of label
| IncorrectWithConstraint of label
| GenerativeModuleExpected of label
| NonEmptyLocalContect of label option
| LabelMissing of label * string
exception ModuleTypingError of module_typing_error
val error_existing_label : label -> 'a
val error_application_to_not_path : module_struct_entry -> 'a
val error_incompatible_modtypes :
module_type_body -> module_type_body -> 'a
val error_signature_mismatch :
label -> structure_field_body -> signature_mismatch_error -> 'a
val error_incompatible_labels : label -> label -> 'a
val error_no_such_label : label -> 'a
val error_signature_expected : struct_expr_body -> 'a
val error_no_module_to_end : unit -> 'a
val error_no_modtype_to_end : unit -> 'a
val error_not_a_module : string -> 'a
val error_not_a_constant : label -> 'a
val error_incorrect_with_constraint : label -> 'a
val error_generative_module_expected : label -> 'a
val error_non_empty_local_context : label option -> 'a
val error_no_such_label_sub : label->string->'a
| null | https://raw.githubusercontent.com/fetburner/Coq2SML/322d613619edbb62edafa999bff24b1993f37612/coq-8.4pl4/kernel/modops.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
* Various operations on modules and module types
* adds a module and its components, but not the constraints
* Errors | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2014
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Util
open Names
open Univ
open Term
open Environ
open Declarations
open Entries
open Mod_subst
val module_body_of_type : module_path -> module_type_body -> module_body
val module_type_of_module : module_path option -> module_body ->
module_type_body
val destr_functor :
env -> struct_expr_body -> mod_bound_id * module_type_body * struct_expr_body
val subst_struct_expr : substitution -> struct_expr_body -> struct_expr_body
val subst_signature : substitution -> structure_body -> structure_body
val add_signature :
module_path -> structure_body -> delta_resolver -> env -> env
val add_module : module_body -> env -> env
val check_modpath_equiv : env -> module_path -> module_path -> unit
val strengthen : module_type_body -> module_path -> module_type_body
val inline_delta_resolver :
env -> inline -> module_path -> mod_bound_id -> module_type_body ->
delta_resolver -> delta_resolver
val strengthen_and_subst_mb : module_body -> module_path -> bool -> module_body
val subst_modtype_and_resolver : module_type_body -> module_path ->
module_type_body
val clean_bounded_mod_expr : struct_expr_body -> struct_expr_body
type signature_mismatch_error =
| InductiveFieldExpected of mutual_inductive_body
| DefinitionFieldExpected
| ModuleFieldExpected
| ModuleTypeFieldExpected
| NotConvertibleInductiveField of identifier
| NotConvertibleConstructorField of identifier
| NotConvertibleBodyField
| NotConvertibleTypeField of env * types * types
| NotSameConstructorNamesField
| NotSameInductiveNameInBlockField
| FiniteInductiveFieldExpected of bool
| InductiveNumbersFieldExpected of int
| InductiveParamsNumberField of int
| RecordFieldExpected of bool
| RecordProjectionsExpected of name list
| NotEqualInductiveAliases
| NoTypeConstraintExpected
type module_typing_error =
| SignatureMismatch of label * structure_field_body * signature_mismatch_error
| LabelAlreadyDeclared of label
| ApplicationToNotPath of module_struct_entry
| NotAFunctor of struct_expr_body
| IncompatibleModuleTypes of module_type_body * module_type_body
| NotEqualModulePaths of module_path * module_path
| NoSuchLabel of label
| IncompatibleLabels of label * label
| SignatureExpected of struct_expr_body
| NoModuleToEnd
| NoModuleTypeToEnd
| NotAModule of string
| NotAModuleType of string
| NotAConstant of label
| IncorrectWithConstraint of label
| GenerativeModuleExpected of label
| NonEmptyLocalContect of label option
| LabelMissing of label * string
exception ModuleTypingError of module_typing_error
val error_existing_label : label -> 'a
val error_application_to_not_path : module_struct_entry -> 'a
val error_incompatible_modtypes :
module_type_body -> module_type_body -> 'a
val error_signature_mismatch :
label -> structure_field_body -> signature_mismatch_error -> 'a
val error_incompatible_labels : label -> label -> 'a
val error_no_such_label : label -> 'a
val error_signature_expected : struct_expr_body -> 'a
val error_no_module_to_end : unit -> 'a
val error_no_modtype_to_end : unit -> 'a
val error_not_a_module : string -> 'a
val error_not_a_constant : label -> 'a
val error_incorrect_with_constraint : label -> 'a
val error_generative_module_expected : label -> 'a
val error_non_empty_local_context : label option -> 'a
val error_no_such_label_sub : label->string->'a
|
89ed7edb6797a7c23c55fd8c574caa9b789c788f531dda85348cc37c23038b62 | cndreisbach/clojure-web-dev-workshop | handler.clj | (ns we-owe.handler
(:require [clojure.pprint :refer [pprint]]
[compojure.core :refer :all]
[compojure.route :as route]
[compojure.handler :as handler]
[we-owe.views :as views]))
(defn create-routes [db]
(routes
(GET "/" [] (views/index-page db))
(GET "/add-debt" [] (views/add-debt-page))
(POST "/add-debt" [from to amount] (views/add-debt-post db {:from from :to to :amount amount}))
(GET "/:person" [person] (views/person-page db person))
(route/resources "/")
(route/not-found "Page not found")))
(defn create-handler [db]
(-> (create-routes db)
handler/site))
(def ring-handler
(create-handler
(atom {:debts [{:from "clinton" :to "pete" :amount 3.50}
{:from "clinton" :to "diego" :amount 2.00}
{:from "pete" :to "clinton" :amount 1.25}
{:from "jill" :to "pete" :amount 10.00}]})))
| null | https://raw.githubusercontent.com/cndreisbach/clojure-web-dev-workshop/95d9fdf94b39f8a1e408b8bf75a81b92899ee7d9/code/03-hiccup/src/we_owe/handler.clj | clojure | (ns we-owe.handler
(:require [clojure.pprint :refer [pprint]]
[compojure.core :refer :all]
[compojure.route :as route]
[compojure.handler :as handler]
[we-owe.views :as views]))
(defn create-routes [db]
(routes
(GET "/" [] (views/index-page db))
(GET "/add-debt" [] (views/add-debt-page))
(POST "/add-debt" [from to amount] (views/add-debt-post db {:from from :to to :amount amount}))
(GET "/:person" [person] (views/person-page db person))
(route/resources "/")
(route/not-found "Page not found")))
(defn create-handler [db]
(-> (create-routes db)
handler/site))
(def ring-handler
(create-handler
(atom {:debts [{:from "clinton" :to "pete" :amount 3.50}
{:from "clinton" :to "diego" :amount 2.00}
{:from "pete" :to "clinton" :amount 1.25}
{:from "jill" :to "pete" :amount 10.00}]})))
| |
b5465e19c9cc6658f6e77653afcd8cfeeeee8e826b85f1dcb0bc9758e70dd637 | mhkoji/Senn | ex-dict-builder.lisp | (defpackage :hachee.kkc.impl.mirror.ex-dict-builder
(:use :cl)
(:export :item-pron
:item-form
:list-items
:build))
(in-package :hachee.kkc.impl.mirror.ex-dict-builder)
(defgeneric list-items (source))
(defgeneric item-pron (item))
(defgeneric item-form (item))
(defun list-items-in-dict-excluded (source in-dict)
(labels ((in-dict-contains-p (item)
(let ((form (item-form item))
(pron (item-pron item)))
(find form (hachee.kkc.impl.mirror.in-dict:list-entries
in-dict pron)
:test #'string=
:key #'hachee.kkc.impl.mirror.in-dict:entry-form))))
(remove-if #'in-dict-contains-p (list-items source))))
(defun build (source in-dict in-dict-prob char-based-cost-fn)
(let ((hash (make-hash-table :test #'equal)))
(let* ((items (list-items-in-dict-excluded source in-dict))
(each-added-probability (/ in-dict-prob (length items))))
(loop for item in items
for form = (item-form item)
for pron = (item-pron item)
for cost = (funcall char-based-cost-fn form)
for prob = (hachee.kkc.impl.mirror.cost:->probability cost)
for new-prob = (+ prob each-added-probability)
for new-cost = (hachee.kkc.impl.mirror.cost:<-probability
new-prob)
for entry = (hachee.kkc.impl.mirror.ex-dict:make-entry
:form form :cost new-cost)
do (progn (push entry (gethash pron hash)))))
(hachee.kkc.impl.mirror.ex-dict:make-ex-dict :hash hash)))
| null | https://raw.githubusercontent.com/mhkoji/Senn/0701d380f437aa4b48e2fba89bcd3d25587e4d0b/hachee/src/kkc/impl/mirror/ex-dict-builder.lisp | lisp | (defpackage :hachee.kkc.impl.mirror.ex-dict-builder
(:use :cl)
(:export :item-pron
:item-form
:list-items
:build))
(in-package :hachee.kkc.impl.mirror.ex-dict-builder)
(defgeneric list-items (source))
(defgeneric item-pron (item))
(defgeneric item-form (item))
(defun list-items-in-dict-excluded (source in-dict)
(labels ((in-dict-contains-p (item)
(let ((form (item-form item))
(pron (item-pron item)))
(find form (hachee.kkc.impl.mirror.in-dict:list-entries
in-dict pron)
:test #'string=
:key #'hachee.kkc.impl.mirror.in-dict:entry-form))))
(remove-if #'in-dict-contains-p (list-items source))))
(defun build (source in-dict in-dict-prob char-based-cost-fn)
(let ((hash (make-hash-table :test #'equal)))
(let* ((items (list-items-in-dict-excluded source in-dict))
(each-added-probability (/ in-dict-prob (length items))))
(loop for item in items
for form = (item-form item)
for pron = (item-pron item)
for cost = (funcall char-based-cost-fn form)
for prob = (hachee.kkc.impl.mirror.cost:->probability cost)
for new-prob = (+ prob each-added-probability)
for new-cost = (hachee.kkc.impl.mirror.cost:<-probability
new-prob)
for entry = (hachee.kkc.impl.mirror.ex-dict:make-entry
:form form :cost new-cost)
do (progn (push entry (gethash pron hash)))))
(hachee.kkc.impl.mirror.ex-dict:make-ex-dict :hash hash)))
| |
58e7829ef7a78795a39faabb3b8848bcc082e2baa96cb61a54747c1f73602ab7 | mpenet/tape | queue.clj | (ns qbits.tape.queue
(:require [qbits.commons.enum :as enum]
[qbits.commons.jvm :as jvm]
[clojure.tools.logging :as log]
[clojure.core.protocols :as p]
[qbits.tape.cycle-listener :as cycle-listener]
[qbits.tape.codec.fressian :as fressian.codec])
(:import (net.openhft.chronicle.queue ChronicleQueue
RollCycles
ExcerptTailer)
(net.openhft.chronicle.queue.impl.single SingleChronicleQueueBuilder
SingleChronicleQueue)))
(set! *warn-on-reflection* true)
(def ->roll-cycle (enum/enum->fn RollCycles))
(defprotocol IQueue
(codec [q] "Returns codec to be used with queue instance")
(close! [q] "Closes the queue")
(closed? [q] "Returns true if the queue is closed")
(underlying-queue ^net.openhft.chronicle.queue.impl.single.SingleChronicleQueue [q]
"Returns the underlying chronicle-queue instance"))
(defn ^java.io.Closeable make
"Return a queue instance that will create/bind to a directory
* `roll-cycle` roll-cycle determines how often you create a new
Chronicle Queue data file. Can be `:minutely`, `:daily`,
`:test4-daily`, `:test-hourly`, `:hourly`, `:test-secondly`,
`:huge-daily-xsparse`, `:test-daily`, `:large-hourly-xsparse`,
`:large-daily`, `:test2-daily`, `:xlarge-daily`, `:huge-daily`,
`:large-hourly`, `:small-daily`, `:large-hourly-sparse`
* `autoclose-on-jvm-exit?` wheter to cleanly close the queue on jvm
exit (defaults to true)
* `cycle-release-tasks` Tasks to run on queue release. See
qbits.tape.cycle-listener
* `cycle-acquire-tasks` Tasks to run on queue acquisition. See
qbits.tape.cycle-listener
* `codec` qbits.tape.codec/ICodec instance that will be used to
encode/decode messages. Default to qbits.tape.codec.fressian/default"
([dir]
(make dir nil))
([dir {:keys [roll-cycle autoclose-on-jvm-exit?
cycle-release-tasks
cycle-acquire-tasks
codec
block-size]
:or {roll-cycle :small-daily
autoclose-on-jvm-exit? true
codec fressian.codec/default}}]
(let [^SingleChronicleQueue queue
(cond-> (ChronicleQueue/singleBuilder ^String dir)
roll-cycle
(.rollCycle (->roll-cycle roll-cycle))
(or (seq cycle-release-tasks)
(seq cycle-acquire-tasks))
(.storeFileListener (cycle-listener/make dir
(->roll-cycle roll-cycle)
{:release-tasks cycle-release-tasks
:acquire-tasks cycle-acquire-tasks}))
(number? block-size)
(.blockSize (long block-size))
:then (.build))
q (reify
IQueue
(closed? [this]
(.isClosed queue))
(close! [this]
(.close queue))
(codec [this]
codec)
(underlying-queue [this] queue)
java.io.Closeable
(close [this] (.close queue))
p/Datafiable
(datafy [this]
#::{:source-id (.sourceId queue)
:last-acknowledged-index-replicated (.lastAcknowledgedIndexReplicated queue)
:last-index-replicated (.lastIndexReplicated queue)
:file (.fileAbsolutePath queue)
:index-count (.indexCount queue)
:index-spacing (.indexSpacing queue)
:roll-cycle (.rollCycle queue)
:delta-checkpoint-interval (.deltaCheckpointInterval queue)
:buffered (.buffered queue)
:cycle (.cycle queue)
:closed? (.isClosed queue)}))]
(when autoclose-on-jvm-exit?
(jvm/add-shutdown-hook!
(fn []
(when-not (closed? q)
(log/infof "JVM exit handler triggered for open Queue: %s"
q)
(close! q)
(log/infof "Closed Queue: %s"
q)))))
q)))
| null | https://raw.githubusercontent.com/mpenet/tape/615293e2d9eeaac36b5024f9ca1efc80169ac75c/src/qbits/tape/queue.clj | clojure | (ns qbits.tape.queue
(:require [qbits.commons.enum :as enum]
[qbits.commons.jvm :as jvm]
[clojure.tools.logging :as log]
[clojure.core.protocols :as p]
[qbits.tape.cycle-listener :as cycle-listener]
[qbits.tape.codec.fressian :as fressian.codec])
(:import (net.openhft.chronicle.queue ChronicleQueue
RollCycles
ExcerptTailer)
(net.openhft.chronicle.queue.impl.single SingleChronicleQueueBuilder
SingleChronicleQueue)))
(set! *warn-on-reflection* true)
(def ->roll-cycle (enum/enum->fn RollCycles))
(defprotocol IQueue
(codec [q] "Returns codec to be used with queue instance")
(close! [q] "Closes the queue")
(closed? [q] "Returns true if the queue is closed")
(underlying-queue ^net.openhft.chronicle.queue.impl.single.SingleChronicleQueue [q]
"Returns the underlying chronicle-queue instance"))
(defn ^java.io.Closeable make
"Return a queue instance that will create/bind to a directory
* `roll-cycle` roll-cycle determines how often you create a new
Chronicle Queue data file. Can be `:minutely`, `:daily`,
`:test4-daily`, `:test-hourly`, `:hourly`, `:test-secondly`,
`:huge-daily-xsparse`, `:test-daily`, `:large-hourly-xsparse`,
`:large-daily`, `:test2-daily`, `:xlarge-daily`, `:huge-daily`,
`:large-hourly`, `:small-daily`, `:large-hourly-sparse`
* `autoclose-on-jvm-exit?` wheter to cleanly close the queue on jvm
exit (defaults to true)
* `cycle-release-tasks` Tasks to run on queue release. See
qbits.tape.cycle-listener
* `cycle-acquire-tasks` Tasks to run on queue acquisition. See
qbits.tape.cycle-listener
* `codec` qbits.tape.codec/ICodec instance that will be used to
encode/decode messages. Default to qbits.tape.codec.fressian/default"
([dir]
(make dir nil))
([dir {:keys [roll-cycle autoclose-on-jvm-exit?
cycle-release-tasks
cycle-acquire-tasks
codec
block-size]
:or {roll-cycle :small-daily
autoclose-on-jvm-exit? true
codec fressian.codec/default}}]
(let [^SingleChronicleQueue queue
(cond-> (ChronicleQueue/singleBuilder ^String dir)
roll-cycle
(.rollCycle (->roll-cycle roll-cycle))
(or (seq cycle-release-tasks)
(seq cycle-acquire-tasks))
(.storeFileListener (cycle-listener/make dir
(->roll-cycle roll-cycle)
{:release-tasks cycle-release-tasks
:acquire-tasks cycle-acquire-tasks}))
(number? block-size)
(.blockSize (long block-size))
:then (.build))
q (reify
IQueue
(closed? [this]
(.isClosed queue))
(close! [this]
(.close queue))
(codec [this]
codec)
(underlying-queue [this] queue)
java.io.Closeable
(close [this] (.close queue))
p/Datafiable
(datafy [this]
#::{:source-id (.sourceId queue)
:last-acknowledged-index-replicated (.lastAcknowledgedIndexReplicated queue)
:last-index-replicated (.lastIndexReplicated queue)
:file (.fileAbsolutePath queue)
:index-count (.indexCount queue)
:index-spacing (.indexSpacing queue)
:roll-cycle (.rollCycle queue)
:delta-checkpoint-interval (.deltaCheckpointInterval queue)
:buffered (.buffered queue)
:cycle (.cycle queue)
:closed? (.isClosed queue)}))]
(when autoclose-on-jvm-exit?
(jvm/add-shutdown-hook!
(fn []
(when-not (closed? q)
(log/infof "JVM exit handler triggered for open Queue: %s"
q)
(close! q)
(log/infof "Closed Queue: %s"
q)))))
q)))
| |
dd985f15095d01b6fe79774ec4d8f05defc20afb4984d7f390d7c60c6db502b0 | d-cent/objective8 | questions_test.clj | (ns objective8.unit.questions-test
(:require [midje.sweet :refer :all]
[objective8.back-end.domain.questions :as questions]
[objective8.back-end.domain.objectives :as objectives]
[objective8.back-end.storage.storage :as storage]
[objective8.config :as config]))
(def USER_ID 1)
(def OBJECTIVE_ID 234)
(fact "Postgresql exceptions are not caught"
(questions/store-question! {:question "something"}) => (throws org.postgresql.util.PSQLException)
(provided
(storage/pg-store! {:entity :question :question "something"}) =throws=> (org.postgresql.util.PSQLException.
(org.postgresql.util.ServerErrorMessage. "" 0))))
| null | https://raw.githubusercontent.com/d-cent/objective8/db8344ba4425ca0b38a31c99a3b282d7c8ddaef0/test/objective8/unit/questions_test.clj | clojure | (ns objective8.unit.questions-test
(:require [midje.sweet :refer :all]
[objective8.back-end.domain.questions :as questions]
[objective8.back-end.domain.objectives :as objectives]
[objective8.back-end.storage.storage :as storage]
[objective8.config :as config]))
(def USER_ID 1)
(def OBJECTIVE_ID 234)
(fact "Postgresql exceptions are not caught"
(questions/store-question! {:question "something"}) => (throws org.postgresql.util.PSQLException)
(provided
(storage/pg-store! {:entity :question :question "something"}) =throws=> (org.postgresql.util.PSQLException.
(org.postgresql.util.ServerErrorMessage. "" 0))))
| |
3c56749696dd4806ea88731b4413e2c42424da5c1cef226def64af02b3859845 | CodyReichert/qi | dstate.lisp | ;;;; dstate.lisp -- common bits for decompression state
(in-package :chipz)
;;; This structure is never meant to be instantiated. It exists only to
;;; provide common framework for other decompressors.
(defstruct (decompression-state
(:constructor)
(:conc-name dstate-))
(state nil :type (or null function))
(done nil)
(input (make-array 1 :element-type '(unsigned-byte 8))
:type simple-octet-vector)
(input-start 0 :type (and fixnum (integer 0 *)))
(input-index 0 :type (and fixnum (integer 0 *)))
(input-end 0 :type (and fixnum (integer 0 *)))
(output (make-array 1 :element-type '(unsigned-byte 8))
:type simple-octet-vector)
(output-start 0 :type (and fixnum (integer 0 *)))
(output-index 0 :type (and fixnum (integer 0 *)))
(output-end 0 :type (and fixnum (integer 0 *)))
Checksums of various sorts .
(checksum nil)
(update-checksum nil :type (or null function))
;; Bit buffer.
(bits 0 :type (unsigned-byte 32))
(n-bits 0 :type (integer 0 32)))
(defun make-dstate (format)
"Return a structure suitable for uncompressing data in DATA-FORMAT;
DATA-FORMAT should be:
:BZIP2 or CHIPZ:BZIP2 For decompressing data in the `bzip2' format;
:GZIP or CHIPZ:GZIP For decompressing data in the `gzip' format;
:ZLIB or CHIPZ:ZLIB For decompressing data in the `zlib' format;
:DEFLATE or CHIPZ:DEFLATE For decompressing data in the `deflate' format.
The usual value of DATA-FORMAT will be one of CHIPZ:BZIP2 or CHIPZ:GZIP."
(case format
((:deflate :zlib :gzip
deflate zlib gzip)
(make-inflate-state format))
((:bzip2 bzip2)
(make-bzip2-state))
(t
(error 'invalid-format-error :format format))))
(defun finish-dstate (state)
(unless (dstate-done state)
(error 'premature-end-of-stream))
t)
| null | https://raw.githubusercontent.com/CodyReichert/qi/9cf6d31f40e19f4a7f60891ef7c8c0381ccac66f/dependencies/chipz-master/dstate.lisp | lisp | dstate.lisp -- common bits for decompression state
This structure is never meant to be instantiated. It exists only to
provide common framework for other decompressors.
Bit buffer.
|
(in-package :chipz)
(defstruct (decompression-state
(:constructor)
(:conc-name dstate-))
(state nil :type (or null function))
(done nil)
(input (make-array 1 :element-type '(unsigned-byte 8))
:type simple-octet-vector)
(input-start 0 :type (and fixnum (integer 0 *)))
(input-index 0 :type (and fixnum (integer 0 *)))
(input-end 0 :type (and fixnum (integer 0 *)))
(output (make-array 1 :element-type '(unsigned-byte 8))
:type simple-octet-vector)
(output-start 0 :type (and fixnum (integer 0 *)))
(output-index 0 :type (and fixnum (integer 0 *)))
(output-end 0 :type (and fixnum (integer 0 *)))
Checksums of various sorts .
(checksum nil)
(update-checksum nil :type (or null function))
(bits 0 :type (unsigned-byte 32))
(n-bits 0 :type (integer 0 32)))
(defun make-dstate (format)
DATA-FORMAT should be:
:DEFLATE or CHIPZ:DEFLATE For decompressing data in the `deflate' format.
The usual value of DATA-FORMAT will be one of CHIPZ:BZIP2 or CHIPZ:GZIP."
(case format
((:deflate :zlib :gzip
deflate zlib gzip)
(make-inflate-state format))
((:bzip2 bzip2)
(make-bzip2-state))
(t
(error 'invalid-format-error :format format))))
(defun finish-dstate (state)
(unless (dstate-done state)
(error 'premature-end-of-stream))
t)
|
2b09397c6d927b9c8c54c2a1085d7d8fc213b45095c1c359e7cf1070c423d8c1 | theodormoroianu/SecondYearCourses | HaskellChurchMonad_20210415160429.hs | module HaskellChurchMonad where
A boolean is any way to choose between two alternatives
newtype CBool t = CBool {cIf :: t -> t -> t}
toBool :: CBool Bool -> Bool
toBool b = cIf b True False
The boolean constant true always chooses the first alternative
cTrue :: CBool t
cTrue = CBool $ \t f -> t
The boolean constant false always chooses the second alternative
cFalse :: CBool t
cFalse = CBool $ \t f -> f
--The boolean negation switches the alternatives
cNot :: CBool t -> CBool t
cNot b = CBool $ \t f -> cIf b f t
--The boolean conjunction can be built as a conditional
(&&:) :: CBool t -> CBool t -> CBool t
b1 &&: b2 = CBool $ \t f -> cIf b1 (cIf b2 t f) f
infixr 3 &&:
--The boolean disjunction can be built as a conditional
(||:) :: CBool t -> CBool t -> CBool t
b1 ||: b2 = CBool $ \t f -> cIf b1 t (cIf b2 t f)
infixr 2 ||:
-- a pair is a way to compute something based on the values
-- contained within the pair.
newtype CPair a b t = CPair { cOn :: (a -> b -> t) -> t }
toPair :: CPair a b (a,b) -> (a,b)
toPair p = cOn p (,)
builds a pair out of two values as an object which , when given
--a function to be applied on the values, it will apply it on them.
cPair :: a -> b -> CPair a b t
cPair a b = CPair $ \f -> f a b
first projection uses the function selecting first component on a pair
cFst :: CPair a b a -> a
cFst p = cOn p (\f s -> f)
second projection
cSnd :: CPair a b b -> b
cSnd p = cOn p (\f s -> s)
-- A natural number is any way to iterate a function s a number of times
-- over an initial value z
newtype CNat t = CNat { cFor :: (t -> t) -> t -> t }
-- An instance to show CNats as regular natural numbers
toNat :: CNat Integer -> Integer
toNat n = cFor n (1 +) 0
--0 will iterate the function s 0 times over z, producing z
c0 :: CNat t
c0 = CNat $ \s z -> z
1 is the the function s iterated 1 times over z , that is , z
c1 :: CNat t
c1 = CNat $ \s z -> s z
--Successor n either
- applies s one more time in addition to what n does
-- - iterates s n times over (s z)
cS :: CNat t -> CNat t
cS n = CNat $ \s z -> s (cFor n s z)
--Addition of m and n is done by iterating s n times over m
(+:) :: CNat t -> CNat t -> CNat t
m +: n = CNat $ \s -> cFor n s . cFor m s
infixl 6 +:
--Multiplication of m and n can be done by composing n and m
(*:) :: CNat t -> CNat t -> CNat t
m *: n = CNat $ cFor n . cFor m
infixl 7 *:
--Exponentiation of m and n can be done by applying n to m
(^:) :: CNat -> CNat -> CNat
(^:) = \m n -> CNat $ cFor n (cFor m)
infixr 8 ^:
--Testing whether a value is 0 can be done through iteration
-- using a function constantly false and an initial value true
cIs0 : : CNat - > CBool
cIs0 = \n - > cFor n ( \ _ - > cFalse ) cTrue
--Predecessor ( evaluating to 0 for 0 ) can be defined iterating
--over pairs , starting from an initial value ( 0 , 0 )
cPred : : CNat - > CNat
cPred = undefined
--substraction from m n ( evaluating to 0 if m < n ) is repeated application
-- of the predeccesor function
(-: ) : : CNat - > CNat - > CNat
(-: ) = \m n - > cFor n cPred m
-- Transform a value into a CNat ( should yield c0 for nums < = 0 )
cNat : : ( Ord p , ) = > p - > CNat
cNat n = undefined
-- We can define an instance Num CNat which will allow us to see any
-- integer constant as a CNat ( e.g. 12 : : CNat ) and also use regular
-- arithmetic
instance Num CNat where
( + ) = ( + :)
( * ) = ( * :)
( - ) = (-: )
abs = i d
signum n = ( cIs0 n ) 0 1
fromInteger = cNat
-- m is less than ( or equal to ) n if when substracting n from m we get 0
( < = :) : : CNat - > CNat - > CBool
( < = :) = undefined
infix 4 < = :
( > = :) : : CNat - > CNat - > CBool
( > = :) = \m n - > n < = : m
infix 4 > = :
( < :) : : CNat - > CNat - > CBool
( < :) = \m n - > cNot ( m > = : n )
infix 4 < :
( > :) : : CNat - > CNat - > CBool
( > :) = \m n - > n < : m
infix 4 > :
-- equality on naturals can be defined my means of comparisons
(= = :) : : CNat - > CNat - > CBool
(= = :) = undefined
--Testing whether a value is 0 can be done through iteration
-- using a function constantly false and an initial value true
cIs0 :: CNat -> CBool
cIs0 = \n -> cFor n (\_ -> cFalse) cTrue
--Predecessor (evaluating to 0 for 0) can be defined iterating
--over pairs, starting from an initial value (0, 0)
cPred :: CNat -> CNat
cPred = undefined
--substraction from m n (evaluating to 0 if m < n) is repeated application
-- of the predeccesor function
(-:) :: CNat -> CNat -> CNat
(-:) = \m n -> cFor n cPred m
-- Transform a Num value into a CNat (should yield c0 for nums <= 0)
cNat :: (Ord p, Num p) => p -> CNat
cNat n = undefined
-- We can define an instance Num CNat which will allow us to see any
-- integer constant as a CNat (e.g. 12 :: CNat ) and also use regular
-- arithmetic
instance Num CNat where
(+) = (+:)
(*) = (*:)
(-) = (-:)
abs = id
signum n = cIf (cIs0 n) 0 1
fromInteger = cNat
-- m is less than (or equal to) n if when substracting n from m we get 0
(<=:) :: CNat -> CNat -> CBool
(<=:) = undefined
infix 4 <=:
(>=:) :: CNat -> CNat -> CBool
(>=:) = \m n -> n <=: m
infix 4 >=:
(<:) :: CNat -> CNat -> CBool
(<:) = \m n -> cNot (m >=: n)
infix 4 <:
(>:) :: CNat -> CNat -> CBool
(>:) = \m n -> n <: m
infix 4 >:
-- equality on naturals can be defined my means of comparisons
(==:) :: CNat -> CNat -> CBool
(==:) = undefined
-} | null | https://raw.githubusercontent.com/theodormoroianu/SecondYearCourses/5e359e6a7cf588a527d27209bf53b4ce6b8d5e83/FLP/Laboratoare/Lab%209/.history/HaskellChurchMonad_20210415160429.hs | haskell | The boolean negation switches the alternatives
The boolean conjunction can be built as a conditional
The boolean disjunction can be built as a conditional
a pair is a way to compute something based on the values
contained within the pair.
a function to be applied on the values, it will apply it on them.
A natural number is any way to iterate a function s a number of times
over an initial value z
An instance to show CNats as regular natural numbers
0 will iterate the function s 0 times over z, producing z
Successor n either
- iterates s n times over (s z)
Addition of m and n is done by iterating s n times over m
Multiplication of m and n can be done by composing n and m
Exponentiation of m and n can be done by applying n to m
Testing whether a value is 0 can be done through iteration
using a function constantly false and an initial value true
Predecessor ( evaluating to 0 for 0 ) can be defined iterating
over pairs , starting from an initial value ( 0 , 0 )
substraction from m n ( evaluating to 0 if m < n ) is repeated application
of the predeccesor function
Transform a value into a CNat ( should yield c0 for nums < = 0 )
We can define an instance Num CNat which will allow us to see any
integer constant as a CNat ( e.g. 12 : : CNat ) and also use regular
arithmetic
m is less than ( or equal to ) n if when substracting n from m we get 0
equality on naturals can be defined my means of comparisons
Testing whether a value is 0 can be done through iteration
using a function constantly false and an initial value true
Predecessor (evaluating to 0 for 0) can be defined iterating
over pairs, starting from an initial value (0, 0)
substraction from m n (evaluating to 0 if m < n) is repeated application
of the predeccesor function
Transform a Num value into a CNat (should yield c0 for nums <= 0)
We can define an instance Num CNat which will allow us to see any
integer constant as a CNat (e.g. 12 :: CNat ) and also use regular
arithmetic
m is less than (or equal to) n if when substracting n from m we get 0
equality on naturals can be defined my means of comparisons | module HaskellChurchMonad where
A boolean is any way to choose between two alternatives
newtype CBool t = CBool {cIf :: t -> t -> t}
toBool :: CBool Bool -> Bool
toBool b = cIf b True False
The boolean constant true always chooses the first alternative
cTrue :: CBool t
cTrue = CBool $ \t f -> t
The boolean constant false always chooses the second alternative
cFalse :: CBool t
cFalse = CBool $ \t f -> f
cNot :: CBool t -> CBool t
cNot b = CBool $ \t f -> cIf b f t
(&&:) :: CBool t -> CBool t -> CBool t
b1 &&: b2 = CBool $ \t f -> cIf b1 (cIf b2 t f) f
infixr 3 &&:
(||:) :: CBool t -> CBool t -> CBool t
b1 ||: b2 = CBool $ \t f -> cIf b1 t (cIf b2 t f)
infixr 2 ||:
newtype CPair a b t = CPair { cOn :: (a -> b -> t) -> t }
toPair :: CPair a b (a,b) -> (a,b)
toPair p = cOn p (,)
builds a pair out of two values as an object which , when given
cPair :: a -> b -> CPair a b t
cPair a b = CPair $ \f -> f a b
first projection uses the function selecting first component on a pair
cFst :: CPair a b a -> a
cFst p = cOn p (\f s -> f)
second projection
cSnd :: CPair a b b -> b
cSnd p = cOn p (\f s -> s)
newtype CNat t = CNat { cFor :: (t -> t) -> t -> t }
toNat :: CNat Integer -> Integer
toNat n = cFor n (1 +) 0
c0 :: CNat t
c0 = CNat $ \s z -> z
1 is the the function s iterated 1 times over z , that is , z
c1 :: CNat t
c1 = CNat $ \s z -> s z
- applies s one more time in addition to what n does
cS :: CNat t -> CNat t
cS n = CNat $ \s z -> s (cFor n s z)
(+:) :: CNat t -> CNat t -> CNat t
m +: n = CNat $ \s -> cFor n s . cFor m s
infixl 6 +:
(*:) :: CNat t -> CNat t -> CNat t
m *: n = CNat $ cFor n . cFor m
infixl 7 *:
(^:) :: CNat -> CNat -> CNat
(^:) = \m n -> CNat $ cFor n (cFor m)
infixr 8 ^:
cIs0 : : CNat - > CBool
cIs0 = \n - > cFor n ( \ _ - > cFalse ) cTrue
cPred : : CNat - > CNat
cPred = undefined
(-: ) : : CNat - > CNat - > CNat
(-: ) = \m n - > cFor n cPred m
cNat : : ( Ord p , ) = > p - > CNat
cNat n = undefined
instance Num CNat where
( + ) = ( + :)
( * ) = ( * :)
( - ) = (-: )
abs = i d
signum n = ( cIs0 n ) 0 1
fromInteger = cNat
( < = :) : : CNat - > CNat - > CBool
( < = :) = undefined
infix 4 < = :
( > = :) : : CNat - > CNat - > CBool
( > = :) = \m n - > n < = : m
infix 4 > = :
( < :) : : CNat - > CNat - > CBool
( < :) = \m n - > cNot ( m > = : n )
infix 4 < :
( > :) : : CNat - > CNat - > CBool
( > :) = \m n - > n < : m
infix 4 > :
(= = :) : : CNat - > CNat - > CBool
(= = :) = undefined
cIs0 :: CNat -> CBool
cIs0 = \n -> cFor n (\_ -> cFalse) cTrue
cPred :: CNat -> CNat
cPred = undefined
(-:) :: CNat -> CNat -> CNat
(-:) = \m n -> cFor n cPred m
cNat :: (Ord p, Num p) => p -> CNat
cNat n = undefined
instance Num CNat where
(+) = (+:)
(*) = (*:)
(-) = (-:)
abs = id
signum n = cIf (cIs0 n) 0 1
fromInteger = cNat
(<=:) :: CNat -> CNat -> CBool
(<=:) = undefined
infix 4 <=:
(>=:) :: CNat -> CNat -> CBool
(>=:) = \m n -> n <=: m
infix 4 >=:
(<:) :: CNat -> CNat -> CBool
(<:) = \m n -> cNot (m >=: n)
infix 4 <:
(>:) :: CNat -> CNat -> CBool
(>:) = \m n -> n <: m
infix 4 >:
(==:) :: CNat -> CNat -> CBool
(==:) = undefined
-} |
3a4f11051ad3dc0b75e6193783138c4bf8e9953341f00ca2036f19fa62ad98c9 | coq/coq | haskell.ml | (************************************************************************)
(* * The Coq Proof Assistant / The Coq Development Team *)
v * Copyright INRIA , CNRS and contributors
< O _ _ _ , , * ( see version control and CREDITS file for authors & dates )
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
* GNU Lesser General Public License Version 2.1
(* * (see LICENSE file for the text of the license) *)
(************************************************************************)
(*s Production of Haskell syntax. *)
open Pp
open CErrors
open Util
open Names
open Table
open Miniml
open Mlutil
open Common
s renaming issues .
let pr_lower_id id = str (String.uncapitalize_ascii (Id.to_string id))
let pr_upper_id id = str (String.capitalize_ascii (Id.to_string id))
let keywords =
List.fold_right (fun s -> Id.Set.add (Id.of_string s))
[ "Any"; "case"; "class"; "data"; "default"; "deriving"; "do"; "else";
"family"; "forall"; "foreign"; "if"; "import"; "in"; "infix"; "infixl"; "infixr"; "instance";
"let"; "mdo"; "module"; "newtype"; "of"; "proc"; "rec"; "then"; "type"; "where"; "_"; "__";
"as"; "qualified"; "hiding" ; "unit" ; "unsafeCoerce" ]
Id.Set.empty
let pp_comment s = str "-- " ++ s ++ fnl ()
let pp_bracket_comment s = str"{- " ++ hov 0 s ++ str" -}"
(* Note: do not shorten [str "foo" ++ fnl ()] into [str "foo\n"],
the '\n' character interacts badly with the Format boxing mechanism *)
let preamble mod_name comment used_modules usf =
let pp_import mp = str ("import qualified "^ string_of_modfile mp) ++ fnl ()
in
(if not (usf.magic || usf.tunknown) then mt ()
else
str "{-# OPTIONS_GHC -cpp -XMagicHash #-}" ++ fnl () ++
str "{- For Hugs, use the option -F\"cpp -P -traditional\" -}" ++ fnl2 ())
++
(match comment with
| None -> mt ()
| Some com -> pp_bracket_comment com ++ fnl2 ())
++
str "module " ++ pr_upper_id mod_name ++ str " where" ++ fnl2 () ++
str "import qualified Prelude" ++ fnl () ++
prlist pp_import used_modules ++ fnl ()
++
(if not (usf.magic || usf.tunknown) then mt ()
else
str "#ifdef __GLASGOW_HASKELL__" ++ fnl () ++
str "import qualified GHC.Base" ++ fnl () ++
str "#if __GLASGOW_HASKELL__ >= 900" ++ fnl () ++
str "import qualified GHC.Exts" ++ fnl () ++
str "#endif" ++ fnl () ++
str "#else" ++ fnl () ++
str "-- HUGS" ++ fnl () ++
str "import qualified IOExts" ++ fnl () ++
str "#endif" ++ fnl2 ())
++
(if not usf.magic then mt ()
else
str "#ifdef __GLASGOW_HASKELL__" ++ fnl () ++
str "unsafeCoerce :: a -> b" ++ fnl () ++
str "#if __GLASGOW_HASKELL__ >= 900" ++ fnl () ++
str "unsafeCoerce = GHC.Exts.unsafeCoerce#" ++ fnl () ++
str "#else" ++ fnl () ++
str "unsafeCoerce = GHC.Base.unsafeCoerce#" ++ fnl () ++
str "#endif" ++ fnl () ++
str "#else" ++ fnl () ++
str "-- HUGS" ++ fnl () ++
str "unsafeCoerce :: a -> b" ++ fnl () ++
str "unsafeCoerce = IOExts.unsafeCoerce" ++ fnl () ++
str "#endif" ++ fnl2 ())
++
(if not usf.tunknown then mt ()
else
str "#ifdef __GLASGOW_HASKELL__" ++ fnl () ++
str "type Any = GHC.Base.Any" ++ fnl () ++
str "#else" ++ fnl () ++
str "-- HUGS" ++ fnl () ++
str "type Any = ()" ++ fnl () ++
str "#endif" ++ fnl2 ())
++
(if not usf.mldummy then mt ()
else
str "__ :: any" ++ fnl () ++
str "__ = Prelude.error \"Logical or arity value used\"" ++ fnl2 ())
let pp_abst = function
| [] -> (mt ())
| l -> (str "\\" ++
prlist_with_sep (fun () -> (str " ")) Id.print l ++
str " ->" ++ spc ())
(*s The pretty-printer for haskell syntax *)
let pp_global k r =
if is_inline_custom r then str (find_custom r)
else str (Common.pp_global k r)
(*s Pretty-printing of types. [par] is a boolean indicating whether parentheses
are needed or not. *)
let rec pp_type par vl t =
let rec pp_rec par = function
| Tmeta _ | Tvar' _ -> assert false
| Tvar i ->
(try Id.print (List.nth vl (pred i))
with Failure _ -> (str "a" ++ int i))
| Tglob (r,[]) -> pp_global Type r
| Tglob (gr,l)
when not (keep_singleton ()) && GlobRef.CanOrd.equal gr (sig_type_ref ()) ->
pp_type true vl (List.hd l)
| Tglob (r,l) ->
pp_par par
(pp_global Type r ++ spc () ++
prlist_with_sep spc (pp_type true vl) l)
| Tarr (t1,t2) ->
pp_par par
(pp_rec true t1 ++ spc () ++ str "->" ++ spc () ++ pp_rec false t2)
| Tdummy _ -> str "()"
| Tunknown -> str "Any"
| Taxiom -> str "() -- AXIOM TO BE REALIZED" ++ fnl ()
in
hov 0 (pp_rec par t)
s Pretty - printing of expressions . [ par ] indicates whether
parentheses are needed or not . [ env ] is the list of names for the
de Bruijn variables . [ args ] is the list of collected arguments
( already pretty - printed ) .
parentheses are needed or not. [env] is the list of names for the
de Bruijn variables. [args] is the list of collected arguments
(already pretty-printed). *)
let expr_needs_par = function
| MLlam _ -> true
| MLcase _ -> false (* now that we use the case ... of { ... } syntax *)
| _ -> false
let rec pp_expr par env args =
let apply st = pp_apply st par args
and apply2 st = pp_apply2 st par args in
function
| MLrel n ->
let id = get_db_name n env in
Try to survive to the occurrence of a Dummy rel .
TODO : we should get rid of this hack ( cf . BZ#592 )
TODO: we should get rid of this hack (cf. BZ#592) *)
let id = if Id.equal id dummy_name then Id.of_string "__" else id in
apply (Id.print id)
| MLapp (f,args') ->
let stl = List.map (pp_expr true env []) args' in
pp_expr par env (stl @ args) f
| MLlam _ as a ->
let fl,a' = collect_lams a in
let fl,env' = push_vars (List.map id_of_mlid fl) env in
let st = (pp_abst (List.rev fl) ++ pp_expr false env' [] a') in
apply2 st
| MLletin (id,a1,a2) ->
let i,env' = push_vars [id_of_mlid id] env in
let pp_id = Id.print (List.hd i)
and pp_a1 = pp_expr false env [] a1
and pp_a2 = pp_expr (not par && expr_needs_par a2) env' [] a2 in
let pp_def =
str "let {" ++ cut () ++
hov 1 (pp_id ++ str " = " ++ pp_a1 ++ str "}")
in
apply2 (hv 0 (hv 0 (hv 1 pp_def ++ spc () ++ str "in") ++
spc () ++ hov 0 pp_a2))
| MLglob r ->
apply (pp_global Term r)
| MLcons (_,r,a) as c ->
assert (List.is_empty args);
begin match a with
| _ when is_native_char c -> pp_native_char c
| _ when is_native_string c -> pp_native_string c
| [] -> pp_global Cons r
| [a] ->
pp_par par (pp_global Cons r ++ spc () ++ pp_expr true env [] a)
| _ ->
pp_par par (pp_global Cons r ++ spc () ++
prlist_with_sep spc (pp_expr true env []) a)
end
| MLtuple l ->
assert (List.is_empty args);
pp_boxed_tuple (pp_expr true env []) l
| MLcase (_,t, pv) when is_custom_match pv ->
if not (is_regular_match pv) then
user_err Pp.(str "Cannot mix yet user-given match and general patterns.");
let mkfun (ids,_,e) =
if not (List.is_empty ids) then named_lams (List.rev ids) e
else dummy_lams (ast_lift 1 e) 1
in
let pp_branch tr = pp_expr true env [] (mkfun tr) ++ fnl () in
let inner =
str (find_custom_match pv) ++ fnl () ++
prvect pp_branch pv ++
pp_expr true env [] t
in
apply2 (hov 2 inner)
| MLcase (typ,t,pv) ->
apply2
(v 0 (str "case " ++ pp_expr false env [] t ++ str " of {" ++
fnl () ++ pp_pat env pv))
| MLfix (i,ids,defs) ->
let ids',env' = push_vars (List.rev (Array.to_list ids)) env in
pp_fix par env' i (Array.of_list (List.rev ids'),defs) args
| MLexn s ->
An [ MLexn ] may be applied , but I do n't really care .
pp_par par (str "Prelude.error" ++ spc () ++ qs s)
| MLdummy k ->
(* An [MLdummy] may be applied, but I don't really care. *)
(match msg_of_implicit k with
| "" -> str "__"
| s -> str "__" ++ spc () ++ pp_bracket_comment (str s))
| MLmagic a ->
pp_apply (str "unsafeCoerce") par (pp_expr true env [] a :: args)
| MLaxiom -> pp_par par (str "Prelude.error \"AXIOM TO BE REALIZED\"")
| MLuint _ ->
pp_par par (str "Prelude.error \"EXTRACTION OF UINT NOT IMPLEMENTED\"")
| MLfloat _ ->
pp_par par (str "Prelude.error \"EXTRACTION OF FLOAT NOT IMPLEMENTED\"")
| MLparray _ ->
pp_par par (str "Prelude.error \"EXTRACTION OF ARRAY NOT IMPLEMENTED\"")
and pp_cons_pat par r ppl =
pp_par par
(pp_global Cons r ++ space_if (not (List.is_empty ppl)) ++ prlist_with_sep spc identity ppl)
and pp_gen_pat par ids env = function
| Pcons (r,l) -> pp_cons_pat par r (List.map (pp_gen_pat true ids env) l)
| Pusual r -> pp_cons_pat par r (List.map Id.print ids)
| Ptuple l -> pp_boxed_tuple (pp_gen_pat false ids env) l
| Pwild -> str "_"
| Prel n -> Id.print (get_db_name n env)
and pp_one_pat env (ids,p,t) =
let ids',env' = push_vars (List.rev_map id_of_mlid ids) env in
hov 2 (str " " ++
pp_gen_pat false (List.rev ids') env' p ++
str " ->" ++ spc () ++
pp_expr (expr_needs_par t) env' [] t)
and pp_pat env pv =
prvecti
(fun i x ->
pp_one_pat env pv.(i) ++
if Int.equal i (Array.length pv - 1) then str "}" else
(str ";" ++ fnl ()))
pv
(*s names of the functions ([ids]) are already pushed in [env],
and passed here just for convenience. *)
and pp_fix par env i (ids,bl) args =
pp_par par
(v 0
(v 1 (str "let {" ++ fnl () ++
prvect_with_sep (fun () -> str ";" ++ fnl ())
(fun (fi,ti) -> pp_function env (Id.print fi) ti)
(Array.map2 (fun a b -> a,b) ids bl) ++
str "}") ++
fnl () ++ str "in " ++ pp_apply (Id.print ids.(i)) false args))
and pp_function env f t =
let bl,t' = collect_lams t in
let bl,env' = push_vars (List.map id_of_mlid bl) env in
(f ++ pr_binding (List.rev bl) ++
str " =" ++ fnl () ++ str " " ++
hov 2 (pp_expr false env' [] t'))
(*s Pretty-printing of inductive types declaration. *)
let pp_logical_ind packet =
pp_comment (Id.print packet.ip_typename ++ str " : logical inductive") ++
pp_comment (str "with constructors : " ++
prvect_with_sep spc Id.print packet.ip_consnames)
let pp_singleton kn packet =
let name = pp_global Type (GlobRef.IndRef (kn,0)) in
let l = rename_tvars keywords packet.ip_vars in
hov 2 (str "type " ++ name ++ spc () ++
prlist_with_sep spc Id.print l ++
(if not (List.is_empty l) then str " " else mt ()) ++ str "=" ++ spc () ++
pp_type false l (List.hd packet.ip_types.(0)) ++ fnl () ++
pp_comment (str "singleton inductive, whose constructor was " ++
Id.print packet.ip_consnames.(0)))
let pp_one_ind ip pl cv =
let pl = rename_tvars keywords pl in
let pp_constructor (r,l) =
(pp_global Cons r ++
match l with
| [] -> (mt ())
| _ -> (str " " ++
prlist_with_sep
(fun () -> (str " ")) (pp_type true pl) l))
in
str (if Array.is_empty cv then "type " else "data ") ++
pp_global Type (GlobRef.IndRef ip) ++
prlist_strict (fun id -> str " " ++ pr_lower_id id) pl ++ str " =" ++
if Array.is_empty cv then str " () -- empty inductive"
else
(fnl () ++ str " " ++
v 0 (str " " ++
prvect_with_sep (fun () -> fnl () ++ str "| ") pp_constructor
(Array.mapi (fun i c -> GlobRef.ConstructRef (ip,i+1),c) cv)))
let rec pp_ind first kn i ind =
if i >= Array.length ind.ind_packets then
if first then mt () else fnl ()
else
let ip = (kn,i) in
let p = ind.ind_packets.(i) in
if is_custom (GlobRef.IndRef (kn,i)) then pp_ind first kn (i+1) ind
else
if p.ip_logical then
pp_logical_ind p ++ pp_ind first kn (i+1) ind
else
pp_one_ind ip p.ip_vars p.ip_types ++ fnl () ++
pp_ind false kn (i+1) ind
(*s Pretty-printing of a declaration. *)
let pp_decl = function
| Dind (kn,i) when i.ind_kind == Singleton ->
pp_singleton kn i.ind_packets.(0) ++ fnl ()
| Dind (kn,i) -> hov 0 (pp_ind true kn 0 i)
| Dtype (r, l, t) ->
if is_inline_custom r then mt ()
else
let l = rename_tvars keywords l in
let st =
try
let ids,s = find_type_custom r in
prlist (fun id -> str (id^" ")) ids ++ str "=" ++ spc () ++ str s
with Not_found ->
prlist (fun id -> Id.print id ++ str " ") l ++
if t == Taxiom then str "= () -- AXIOM TO BE REALIZED" ++ fnl ()
else str "=" ++ spc () ++ pp_type false l t
in
hov 2 (str "type " ++ pp_global Type r ++ spc () ++ st) ++ fnl2 ()
| Dfix (rv, defs, typs) ->
let names = Array.map
(fun r -> if is_inline_custom r then mt () else pp_global Term r) rv
in
prvecti
(fun i r ->
let void = is_inline_custom r ||
(not (is_custom r) &&
match defs.(i) with MLexn "UNUSED" -> true | _ -> false)
in
if void then mt ()
else
hov 2 (names.(i) ++ str " :: " ++ pp_type false [] typs.(i)) ++ fnl () ++
(if is_custom r then
(names.(i) ++ str " = " ++ str (find_custom r))
else
(pp_function (empty_env ()) names.(i) defs.(i)))
++ fnl2 ())
rv
| Dterm (r, a, t) ->
if is_inline_custom r then mt ()
else
let e = pp_global Term r in
hov 2 (e ++ str " :: " ++ pp_type false [] t) ++ fnl () ++
if is_custom r then
hov 0 (e ++ str " = " ++ str (find_custom r) ++ fnl2 ())
else
hov 0 (pp_function (empty_env ()) e a ++ fnl2 ())
let rec pp_structure_elem = function
| (l,SEdecl d) -> pp_decl d
| (l,SEmodule m) -> pp_module_expr m.ml_mod_expr
| (l,SEmodtype m) -> mt ()
(* for the moment we simply discard module type *)
and pp_module_expr = function
| MEstruct (mp,sel) -> prlist_strict pp_structure_elem sel
| MEfunctor _ -> mt ()
(* for the moment we simply discard unapplied functors *)
| MEident _ | MEapply _ -> assert false
(* should be expanded in extract_env *)
let pp_struct =
let pp_sel (mp,sel) =
push_visible mp [];
let p = prlist_strict pp_structure_elem sel in
pop_visible (); p
in
prlist_strict pp_sel
let haskell_descr = {
keywords = keywords;
file_suffix = ".hs";
file_naming = string_of_modfile;
preamble = preamble;
pp_struct = pp_struct;
sig_suffix = None;
sig_preamble = (fun _ _ _ _ -> mt ());
pp_sig = (fun _ -> mt ());
pp_decl = pp_decl;
}
| null | https://raw.githubusercontent.com/coq/coq/8f1590f7840d0dff71fa9b7a7bbc1ed01d779359/plugins/extraction/haskell.ml | ocaml | **********************************************************************
* The Coq Proof Assistant / The Coq Development Team
// * This file is distributed under the terms of the
* (see LICENSE file for the text of the license)
**********************************************************************
s Production of Haskell syntax.
Note: do not shorten [str "foo" ++ fnl ()] into [str "foo\n"],
the '\n' character interacts badly with the Format boxing mechanism
s The pretty-printer for haskell syntax
s Pretty-printing of types. [par] is a boolean indicating whether parentheses
are needed or not.
now that we use the case ... of { ... } syntax
An [MLdummy] may be applied, but I don't really care.
s names of the functions ([ids]) are already pushed in [env],
and passed here just for convenience.
s Pretty-printing of inductive types declaration.
s Pretty-printing of a declaration.
for the moment we simply discard module type
for the moment we simply discard unapplied functors
should be expanded in extract_env | v * Copyright INRIA , CNRS and contributors
< O _ _ _ , , * ( see version control and CREDITS file for authors & dates )
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* GNU Lesser General Public License Version 2.1
open Pp
open CErrors
open Util
open Names
open Table
open Miniml
open Mlutil
open Common
s renaming issues .
let pr_lower_id id = str (String.uncapitalize_ascii (Id.to_string id))
let pr_upper_id id = str (String.capitalize_ascii (Id.to_string id))
let keywords =
List.fold_right (fun s -> Id.Set.add (Id.of_string s))
[ "Any"; "case"; "class"; "data"; "default"; "deriving"; "do"; "else";
"family"; "forall"; "foreign"; "if"; "import"; "in"; "infix"; "infixl"; "infixr"; "instance";
"let"; "mdo"; "module"; "newtype"; "of"; "proc"; "rec"; "then"; "type"; "where"; "_"; "__";
"as"; "qualified"; "hiding" ; "unit" ; "unsafeCoerce" ]
Id.Set.empty
let pp_comment s = str "-- " ++ s ++ fnl ()
let pp_bracket_comment s = str"{- " ++ hov 0 s ++ str" -}"
let preamble mod_name comment used_modules usf =
let pp_import mp = str ("import qualified "^ string_of_modfile mp) ++ fnl ()
in
(if not (usf.magic || usf.tunknown) then mt ()
else
str "{-# OPTIONS_GHC -cpp -XMagicHash #-}" ++ fnl () ++
str "{- For Hugs, use the option -F\"cpp -P -traditional\" -}" ++ fnl2 ())
++
(match comment with
| None -> mt ()
| Some com -> pp_bracket_comment com ++ fnl2 ())
++
str "module " ++ pr_upper_id mod_name ++ str " where" ++ fnl2 () ++
str "import qualified Prelude" ++ fnl () ++
prlist pp_import used_modules ++ fnl ()
++
(if not (usf.magic || usf.tunknown) then mt ()
else
str "#ifdef __GLASGOW_HASKELL__" ++ fnl () ++
str "import qualified GHC.Base" ++ fnl () ++
str "#if __GLASGOW_HASKELL__ >= 900" ++ fnl () ++
str "import qualified GHC.Exts" ++ fnl () ++
str "#endif" ++ fnl () ++
str "#else" ++ fnl () ++
str "-- HUGS" ++ fnl () ++
str "import qualified IOExts" ++ fnl () ++
str "#endif" ++ fnl2 ())
++
(if not usf.magic then mt ()
else
str "#ifdef __GLASGOW_HASKELL__" ++ fnl () ++
str "unsafeCoerce :: a -> b" ++ fnl () ++
str "#if __GLASGOW_HASKELL__ >= 900" ++ fnl () ++
str "unsafeCoerce = GHC.Exts.unsafeCoerce#" ++ fnl () ++
str "#else" ++ fnl () ++
str "unsafeCoerce = GHC.Base.unsafeCoerce#" ++ fnl () ++
str "#endif" ++ fnl () ++
str "#else" ++ fnl () ++
str "-- HUGS" ++ fnl () ++
str "unsafeCoerce :: a -> b" ++ fnl () ++
str "unsafeCoerce = IOExts.unsafeCoerce" ++ fnl () ++
str "#endif" ++ fnl2 ())
++
(if not usf.tunknown then mt ()
else
str "#ifdef __GLASGOW_HASKELL__" ++ fnl () ++
str "type Any = GHC.Base.Any" ++ fnl () ++
str "#else" ++ fnl () ++
str "-- HUGS" ++ fnl () ++
str "type Any = ()" ++ fnl () ++
str "#endif" ++ fnl2 ())
++
(if not usf.mldummy then mt ()
else
str "__ :: any" ++ fnl () ++
str "__ = Prelude.error \"Logical or arity value used\"" ++ fnl2 ())
let pp_abst = function
| [] -> (mt ())
| l -> (str "\\" ++
prlist_with_sep (fun () -> (str " ")) Id.print l ++
str " ->" ++ spc ())
let pp_global k r =
if is_inline_custom r then str (find_custom r)
else str (Common.pp_global k r)
let rec pp_type par vl t =
let rec pp_rec par = function
| Tmeta _ | Tvar' _ -> assert false
| Tvar i ->
(try Id.print (List.nth vl (pred i))
with Failure _ -> (str "a" ++ int i))
| Tglob (r,[]) -> pp_global Type r
| Tglob (gr,l)
when not (keep_singleton ()) && GlobRef.CanOrd.equal gr (sig_type_ref ()) ->
pp_type true vl (List.hd l)
| Tglob (r,l) ->
pp_par par
(pp_global Type r ++ spc () ++
prlist_with_sep spc (pp_type true vl) l)
| Tarr (t1,t2) ->
pp_par par
(pp_rec true t1 ++ spc () ++ str "->" ++ spc () ++ pp_rec false t2)
| Tdummy _ -> str "()"
| Tunknown -> str "Any"
| Taxiom -> str "() -- AXIOM TO BE REALIZED" ++ fnl ()
in
hov 0 (pp_rec par t)
s Pretty - printing of expressions . [ par ] indicates whether
parentheses are needed or not . [ env ] is the list of names for the
de Bruijn variables . [ args ] is the list of collected arguments
( already pretty - printed ) .
parentheses are needed or not. [env] is the list of names for the
de Bruijn variables. [args] is the list of collected arguments
(already pretty-printed). *)
let expr_needs_par = function
| MLlam _ -> true
| _ -> false
let rec pp_expr par env args =
let apply st = pp_apply st par args
and apply2 st = pp_apply2 st par args in
function
| MLrel n ->
let id = get_db_name n env in
Try to survive to the occurrence of a Dummy rel .
TODO : we should get rid of this hack ( cf . BZ#592 )
TODO: we should get rid of this hack (cf. BZ#592) *)
let id = if Id.equal id dummy_name then Id.of_string "__" else id in
apply (Id.print id)
| MLapp (f,args') ->
let stl = List.map (pp_expr true env []) args' in
pp_expr par env (stl @ args) f
| MLlam _ as a ->
let fl,a' = collect_lams a in
let fl,env' = push_vars (List.map id_of_mlid fl) env in
let st = (pp_abst (List.rev fl) ++ pp_expr false env' [] a') in
apply2 st
| MLletin (id,a1,a2) ->
let i,env' = push_vars [id_of_mlid id] env in
let pp_id = Id.print (List.hd i)
and pp_a1 = pp_expr false env [] a1
and pp_a2 = pp_expr (not par && expr_needs_par a2) env' [] a2 in
let pp_def =
str "let {" ++ cut () ++
hov 1 (pp_id ++ str " = " ++ pp_a1 ++ str "}")
in
apply2 (hv 0 (hv 0 (hv 1 pp_def ++ spc () ++ str "in") ++
spc () ++ hov 0 pp_a2))
| MLglob r ->
apply (pp_global Term r)
| MLcons (_,r,a) as c ->
assert (List.is_empty args);
begin match a with
| _ when is_native_char c -> pp_native_char c
| _ when is_native_string c -> pp_native_string c
| [] -> pp_global Cons r
| [a] ->
pp_par par (pp_global Cons r ++ spc () ++ pp_expr true env [] a)
| _ ->
pp_par par (pp_global Cons r ++ spc () ++
prlist_with_sep spc (pp_expr true env []) a)
end
| MLtuple l ->
assert (List.is_empty args);
pp_boxed_tuple (pp_expr true env []) l
| MLcase (_,t, pv) when is_custom_match pv ->
if not (is_regular_match pv) then
user_err Pp.(str "Cannot mix yet user-given match and general patterns.");
let mkfun (ids,_,e) =
if not (List.is_empty ids) then named_lams (List.rev ids) e
else dummy_lams (ast_lift 1 e) 1
in
let pp_branch tr = pp_expr true env [] (mkfun tr) ++ fnl () in
let inner =
str (find_custom_match pv) ++ fnl () ++
prvect pp_branch pv ++
pp_expr true env [] t
in
apply2 (hov 2 inner)
| MLcase (typ,t,pv) ->
apply2
(v 0 (str "case " ++ pp_expr false env [] t ++ str " of {" ++
fnl () ++ pp_pat env pv))
| MLfix (i,ids,defs) ->
let ids',env' = push_vars (List.rev (Array.to_list ids)) env in
pp_fix par env' i (Array.of_list (List.rev ids'),defs) args
| MLexn s ->
An [ MLexn ] may be applied , but I do n't really care .
pp_par par (str "Prelude.error" ++ spc () ++ qs s)
| MLdummy k ->
(match msg_of_implicit k with
| "" -> str "__"
| s -> str "__" ++ spc () ++ pp_bracket_comment (str s))
| MLmagic a ->
pp_apply (str "unsafeCoerce") par (pp_expr true env [] a :: args)
| MLaxiom -> pp_par par (str "Prelude.error \"AXIOM TO BE REALIZED\"")
| MLuint _ ->
pp_par par (str "Prelude.error \"EXTRACTION OF UINT NOT IMPLEMENTED\"")
| MLfloat _ ->
pp_par par (str "Prelude.error \"EXTRACTION OF FLOAT NOT IMPLEMENTED\"")
| MLparray _ ->
pp_par par (str "Prelude.error \"EXTRACTION OF ARRAY NOT IMPLEMENTED\"")
and pp_cons_pat par r ppl =
pp_par par
(pp_global Cons r ++ space_if (not (List.is_empty ppl)) ++ prlist_with_sep spc identity ppl)
and pp_gen_pat par ids env = function
| Pcons (r,l) -> pp_cons_pat par r (List.map (pp_gen_pat true ids env) l)
| Pusual r -> pp_cons_pat par r (List.map Id.print ids)
| Ptuple l -> pp_boxed_tuple (pp_gen_pat false ids env) l
| Pwild -> str "_"
| Prel n -> Id.print (get_db_name n env)
and pp_one_pat env (ids,p,t) =
let ids',env' = push_vars (List.rev_map id_of_mlid ids) env in
hov 2 (str " " ++
pp_gen_pat false (List.rev ids') env' p ++
str " ->" ++ spc () ++
pp_expr (expr_needs_par t) env' [] t)
and pp_pat env pv =
prvecti
(fun i x ->
pp_one_pat env pv.(i) ++
if Int.equal i (Array.length pv - 1) then str "}" else
(str ";" ++ fnl ()))
pv
and pp_fix par env i (ids,bl) args =
pp_par par
(v 0
(v 1 (str "let {" ++ fnl () ++
prvect_with_sep (fun () -> str ";" ++ fnl ())
(fun (fi,ti) -> pp_function env (Id.print fi) ti)
(Array.map2 (fun a b -> a,b) ids bl) ++
str "}") ++
fnl () ++ str "in " ++ pp_apply (Id.print ids.(i)) false args))
and pp_function env f t =
let bl,t' = collect_lams t in
let bl,env' = push_vars (List.map id_of_mlid bl) env in
(f ++ pr_binding (List.rev bl) ++
str " =" ++ fnl () ++ str " " ++
hov 2 (pp_expr false env' [] t'))
let pp_logical_ind packet =
pp_comment (Id.print packet.ip_typename ++ str " : logical inductive") ++
pp_comment (str "with constructors : " ++
prvect_with_sep spc Id.print packet.ip_consnames)
let pp_singleton kn packet =
let name = pp_global Type (GlobRef.IndRef (kn,0)) in
let l = rename_tvars keywords packet.ip_vars in
hov 2 (str "type " ++ name ++ spc () ++
prlist_with_sep spc Id.print l ++
(if not (List.is_empty l) then str " " else mt ()) ++ str "=" ++ spc () ++
pp_type false l (List.hd packet.ip_types.(0)) ++ fnl () ++
pp_comment (str "singleton inductive, whose constructor was " ++
Id.print packet.ip_consnames.(0)))
let pp_one_ind ip pl cv =
let pl = rename_tvars keywords pl in
let pp_constructor (r,l) =
(pp_global Cons r ++
match l with
| [] -> (mt ())
| _ -> (str " " ++
prlist_with_sep
(fun () -> (str " ")) (pp_type true pl) l))
in
str (if Array.is_empty cv then "type " else "data ") ++
pp_global Type (GlobRef.IndRef ip) ++
prlist_strict (fun id -> str " " ++ pr_lower_id id) pl ++ str " =" ++
if Array.is_empty cv then str " () -- empty inductive"
else
(fnl () ++ str " " ++
v 0 (str " " ++
prvect_with_sep (fun () -> fnl () ++ str "| ") pp_constructor
(Array.mapi (fun i c -> GlobRef.ConstructRef (ip,i+1),c) cv)))
let rec pp_ind first kn i ind =
if i >= Array.length ind.ind_packets then
if first then mt () else fnl ()
else
let ip = (kn,i) in
let p = ind.ind_packets.(i) in
if is_custom (GlobRef.IndRef (kn,i)) then pp_ind first kn (i+1) ind
else
if p.ip_logical then
pp_logical_ind p ++ pp_ind first kn (i+1) ind
else
pp_one_ind ip p.ip_vars p.ip_types ++ fnl () ++
pp_ind false kn (i+1) ind
let pp_decl = function
| Dind (kn,i) when i.ind_kind == Singleton ->
pp_singleton kn i.ind_packets.(0) ++ fnl ()
| Dind (kn,i) -> hov 0 (pp_ind true kn 0 i)
| Dtype (r, l, t) ->
if is_inline_custom r then mt ()
else
let l = rename_tvars keywords l in
let st =
try
let ids,s = find_type_custom r in
prlist (fun id -> str (id^" ")) ids ++ str "=" ++ spc () ++ str s
with Not_found ->
prlist (fun id -> Id.print id ++ str " ") l ++
if t == Taxiom then str "= () -- AXIOM TO BE REALIZED" ++ fnl ()
else str "=" ++ spc () ++ pp_type false l t
in
hov 2 (str "type " ++ pp_global Type r ++ spc () ++ st) ++ fnl2 ()
| Dfix (rv, defs, typs) ->
let names = Array.map
(fun r -> if is_inline_custom r then mt () else pp_global Term r) rv
in
prvecti
(fun i r ->
let void = is_inline_custom r ||
(not (is_custom r) &&
match defs.(i) with MLexn "UNUSED" -> true | _ -> false)
in
if void then mt ()
else
hov 2 (names.(i) ++ str " :: " ++ pp_type false [] typs.(i)) ++ fnl () ++
(if is_custom r then
(names.(i) ++ str " = " ++ str (find_custom r))
else
(pp_function (empty_env ()) names.(i) defs.(i)))
++ fnl2 ())
rv
| Dterm (r, a, t) ->
if is_inline_custom r then mt ()
else
let e = pp_global Term r in
hov 2 (e ++ str " :: " ++ pp_type false [] t) ++ fnl () ++
if is_custom r then
hov 0 (e ++ str " = " ++ str (find_custom r) ++ fnl2 ())
else
hov 0 (pp_function (empty_env ()) e a ++ fnl2 ())
let rec pp_structure_elem = function
| (l,SEdecl d) -> pp_decl d
| (l,SEmodule m) -> pp_module_expr m.ml_mod_expr
| (l,SEmodtype m) -> mt ()
and pp_module_expr = function
| MEstruct (mp,sel) -> prlist_strict pp_structure_elem sel
| MEfunctor _ -> mt ()
| MEident _ | MEapply _ -> assert false
let pp_struct =
let pp_sel (mp,sel) =
push_visible mp [];
let p = prlist_strict pp_structure_elem sel in
pop_visible (); p
in
prlist_strict pp_sel
let haskell_descr = {
keywords = keywords;
file_suffix = ".hs";
file_naming = string_of_modfile;
preamble = preamble;
pp_struct = pp_struct;
sig_suffix = None;
sig_preamble = (fun _ _ _ _ -> mt ());
pp_sig = (fun _ -> mt ());
pp_decl = pp_decl;
}
|
1b2305d9505b0e11002d76e85ec4c8c7a6e7a398b2f5b7b569c00245f28709b8 | valmirjunior0088/curios | Ieee754.hs | module WebAssembly.Encode.Ieee754
( ieee754Single
, ieee754Double
)
where
This module assumes that GHC uses IEEE-754
-- floats (which it does) and reuses them
-- For completeness sake in the future this
module should house an actual IEEE-754 encoder
import Data.Word (Word32, Word64)
import GHC.Float (castFloatToWord32, castDoubleToWord64)
ieee754Single :: Float -> Word32
ieee754Single = castFloatToWord32
ieee754Double :: Double -> Word64
ieee754Double = castDoubleToWord64
| null | https://raw.githubusercontent.com/valmirjunior0088/curios/391bebe67d5e7a4c3d51c758da9ba96b38c11705/src/WebAssembly/Encode/Ieee754.hs | haskell | floats (which it does) and reuses them
For completeness sake in the future this | module WebAssembly.Encode.Ieee754
( ieee754Single
, ieee754Double
)
where
This module assumes that GHC uses IEEE-754
module should house an actual IEEE-754 encoder
import Data.Word (Word32, Word64)
import GHC.Float (castFloatToWord32, castDoubleToWord64)
ieee754Single :: Float -> Word32
ieee754Single = castFloatToWord32
ieee754Double :: Double -> Word64
ieee754Double = castDoubleToWord64
|
32e08b30a75160144fb3147e3427072b72b14d9b0d5bf876c0ceb8a4307b523e | PLTools/Lama | stdpath.ml | let path = "/home/db/.opam/4.14.0+flambda/share/Lama"
| null | https://raw.githubusercontent.com/PLTools/Lama/f47d872df1231fd5da8268cde119418d9db37ceb/src/stdpath.ml | ocaml | let path = "/home/db/.opam/4.14.0+flambda/share/Lama"
| |
17f6ecbef61293fde89c2af25fb3d79496cb82e689778517eac912eea8549c75 | haskell/play-haskell | Play.hs | # LANGUAGE DeriveGeneric #
# LANGUAGE LambdaCase #
# LANGUAGE NumericUnderscores #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TupleSections #
# LANGUAGE TypeApplications #
# LANGUAGE ViewPatterns #
module Play (playModule) where
import Control.Concurrent.STM
import Control.Monad (when, forM_)
import Control.Monad.IO.Class (liftIO)
import qualified Data.Aeson as J
import qualified Data.Aeson.Types as J
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as Char8
import qualified Data.ByteString.Lazy as BSL
import qualified Data.ByteString.Short as BSS
import Data.Char (chr)
import Data.Maybe (fromMaybe)
import qualified Data.Map.Strict as Map
import Data.String (fromString)
import Data.Text (Text)
import Data.Time (secondsToDiffTime)
import Data.Word (Word64)
import GHC.Generics (Generic)
import Snap.Core hiding (path, method, pass)
import System.Directory (listDirectory)
import System.FilePath (takeExtension, takeFileName, (</>))
import System.Random (StdGen, genByteString, newStdGen)
import DB (KeyType, Contents(..), ClientAddr)
import qualified DB
import Pages
import ServerModule
import Snap.Server.Utils
import Snap.Server.Utils.BasicAuth
import Snap.Server.Utils.Challenge
import Snap.Server.Utils.ExitEarly
import Snap.Server.Utils.Hex
import Snap.Server.Utils.SpamDetect
import qualified Play.WorkerPool as WP
import PlayHaskellTypes
import PlayHaskellTypes.Constants
import qualified PlayHaskellTypes.Sign as Sign
data ClientJobReq = ClientJobReq
{ cjrGivenKey :: Text
, cjrSource :: Text
, cjrVersion :: Version
, cjrOpt :: Optimisation }
deriving (Show)
instance J.FromJSON ClientJobReq where
parseJSON (J.Object v) =
ClientJobReq <$> v J..: fromString "challenge"
<*> v J..: fromString "source"
<*> v J..: fromString "version"
<*> (fromMaybe O1 <$> (v J..:? fromString "opt"))
parseJSON val = J.prependFailure "parsing ClientJobReq failed, " (J.typeMismatch "Object" val)
data ClientSubmitReq = ClientSubmitReq
{ csrCode :: Text
, csrVersion :: Version
, csrOpt :: Optimisation
, csrOutput :: Command }
deriving (Show)
instance J.FromJSON ClientSubmitReq where
parseJSON (J.Object v) =
ClientSubmitReq
<$> v J..: fromString "code"
<*> v J..: fromString "version"
<*> (fromMaybe O1 <$> (v J..:? fromString "opt"))
<*> v J..: fromString "output"
parseJSON val = J.prependFailure "parsing ClientSubmitReq failed, " (J.typeMismatch "Object" val)
saveKeyLength :: Int
saveKeyLength = 8
maxSaveFileSize :: Int
maxSaveFileSize = 128 * 1024
genKey :: StdGen -> (KeyType, StdGen)
genKey gen =
let (bs, gen') = genByteString saveKeyLength gen
intoAlphabet n = BS.index alphabet (fromIntegral n `rem` BS.length alphabet)
in (BS.map intoAlphabet bs, gen')
where
alphabet :: ByteString
alphabet = Char8.pack (['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'])
genKey' :: TVar StdGen -> IO KeyType
genKey' var = atomically $ do
gen <- readTVar var
let (key, gen') = genKey gen
writeTVar var gen'
return key
-- returns the generated key, or an error string
genStorePaste :: GlobalContext -> TVar StdGen -> ClientAddr -> Contents -> IO (Either String KeyType)
genStorePaste gctx stvar srcip contents =
let loop iter = do
key <- genKey' stvar
DB.storePaste (gcDb gctx) srcip key contents >>= \case
Nothing -> return (Right key)
Just DB.ErrExists
| iter < 5 -> loop (iter + 1) -- try again with a new key
| otherwise -> return (Left "Database full?")
Just DB.ErrFull ->
return (Left "Too many snippets saved, saving is temporarily disabled")
in loop (0 :: Int)
data Context = Context
{ ctxPool :: WP.WPool
, ctxChallengeKey :: ChallengeKey
, ctxRNG :: TVar StdGen }
data WhatRequest
= Index
| PostedIndex
| FromSaved ByteString
| Save
| Versions
| CurrentChallenge
| Submit
| AdminReq AdminReq
| LegacyRunGHC Command
| LegacyRedirect ByteString -- ^ to destination URL
deriving (Show)
data AdminReq
= ARDashboard
| ARStatus
| ARAddWorker
| ARRemoveWorker
| ARRefreshWorker
deriving (Show)
parseRequest :: Method -> [ByteString] -> Maybe WhatRequest
parseRequest method comps = case (method, comps) of
(GET, []) -> Just Index
(POST, []) -> Just PostedIndex
(GET, ["saved", key]) -> Just (FromSaved key)
(POST, ["save"]) -> Just Save
(GET, ["versions"]) -> Just Versions
(GET, ["challenge"]) -> Just CurrentChallenge
(POST, ["submit"]) -> Just Submit
(GET, ["admin"]) -> Just (AdminReq ARDashboard)
(GET, ["admin", "status"]) -> Just (AdminReq ARStatus)
(PUT, ["admin", "worker"]) -> Just (AdminReq ARAddWorker)
(DELETE, ["admin", "worker"]) -> Just (AdminReq ARRemoveWorker)
(POST, ["admin", "worker", "refresh"]) -> Just (AdminReq ARRefreshWorker)
(POST, ["compile", "run"]) -> Just (LegacyRunGHC CRun)
(POST, ["compile", "core"]) -> Just (LegacyRunGHC CCore)
(POST, ["compile", "asm"]) -> Just (LegacyRunGHC CAsm)
(GET, ["play"]) -> Just (LegacyRedirect "/")
(GET, ["play", "paste", key]) -> Just (LegacyRedirect ("/saved/" <> key))
(GET, ["play", "paste", key, _]) -> Just (LegacyRedirect ("/saved/" <> key))
_ -> Nothing
handleRequest :: GlobalContext -> Context -> WhatRequest -> Snap ()
handleRequest gctx ctx = \case
Index -> do
req <- getRequest
renderer <- liftIO $ getPageFromGCtx pPlay gctx
case Map.lookup "code" (rqQueryParams req) of
Just (source : _) -> writeHTML (renderer (Just source))
_ -> writeHTML (renderer Nothing)
PostedIndex -> do
req <- getRequest
case Map.lookup "code" (rqPostParams req) of
Just [source] -> do
renderer <- liftIO $ getPageFromGCtx pPlay gctx
writeHTML (renderer (Just source))
_ ->
httpError 400 "Invalid request"
FromSaved key -> do
res <- liftIO $ DB.getPaste (gcDb gctx) key
let buildPage contents = do
renderer <- liftIO $ getPageFromGCtx pPlay gctx
writeHTML (renderer (Just contents))
case res of
Just (_, Contents [] _ _) -> do
modifyResponse (setContentType (Char8.pack "text/plain"))
writeBS (Char8.pack "Save key not found (empty file list?)")
Just (_, Contents ((_, source) : _) _ _) ->
buildPage source
Nothing -> do
modifyResponse (setContentType (Char8.pack "text/plain"))
writeBS (Char8.pack "Save key not found")
Save -> do
req <- getRequest
isSpam <- liftIO $ recordCheckSpam PlaySave (gcSpam gctx) (rqClientAddr req)
if isSpam
then httpError 429 "Please slow down a bit, you're rate limited"
else do body <- readRequestBody (fromIntegral @Int @Word64 maxSaveFileSize)
let body' = BSL.toStrict body
let contents = Contents [(Nothing, body')] Nothing Nothing
srcip = Char8.unpack (rqClientAddr req)
mkey <- liftIO $ genStorePaste gctx (ctxRNG ctx) srcip contents
case mkey of
Right key -> do
modifyResponse (setContentType (Char8.pack "text/plain"))
writeBS key
Left err -> httpError 500 err
Versions -> do
modifyResponse (setContentType (Char8.pack "text/plain"))
versions <- liftIO (WP.getAvailableVersions (ctxPool ctx))
writeJSON versions
-- TODO: remove this. This is present only to let the upgrade to /submit go a bit more smoothly.
CurrentChallenge -> do
modifyResponse (setContentType (Char8.pack "text/plain"))
key <- liftIO $ servingChallenge (ctxChallengeKey ctx)
writeText key
Open a local exit - early block instead of using Snap 's early - exit
-- functionality, because this is more local.
Submit -> execExitEarlyT $ do
req <- lift getRequest
isSpam <- liftIO $ recordCheckSpam PlayRunStart (gcSpam gctx) (rqClientAddr req)
when isSpam $ do
lift (httpError 429 "Please slow down a bit, you're rate limited")
exitEarly ()
postdata <- getRequestBodyEarlyExit 1000_000 "Program too large"
csr <-
case J.decodeStrict' postdata of
Just request -> return request
_ -> do lift (httpError 400 "Invalid JSON")
exitEarly ()
handleSubmitRequest req csr
Open a local exit - early block instead of using Snap 's early - exit
-- functionality, because this is more local.
-- TODO: remove this. This is present only to let the upgrade to /submit go a bit more smoothly. Then also remove /challenge.
LegacyRunGHC runner -> execExitEarlyT $ do
req <- lift getRequest
isSpam <- liftIO $ recordCheckSpam PlayRunStart (gcSpam gctx) (rqClientAddr req)
when isSpam $ do
lift (httpError 429 "Please slow down a bit, you're rate limited")
exitEarly ()
postdata <- getRequestBodyEarlyExit 1000_000 "Program too large"
ClientJobReq {cjrGivenKey=givenKey, cjrSource=source, cjrVersion=version, cjrOpt=opt} <-
case J.decodeStrict' postdata of
Just request -> return request
_ -> do lift (httpError 400 "Invalid JSON")
exitEarly ()
liftIO (checkChallenge (ctxChallengeKey ctx) givenKey) >>= \case
True -> return ()
False -> do lift (httpError 400 "Invalid challenge, request again")
exitEarly ()
handleSubmitRequest req
ClientSubmitReq { csrCode = source
, csrVersion = version
, csrOpt = opt
, csrOutput = runner }
AdminReq adminreq -> do
getBasicAuthCredentials <$> getRequest >>= \case
Just (user, pass)
| user == "admin"
, Just pass == gcAdminPassword gctx
-> handleAdminRequest ctx adminreq
_ -> modifyResponse (requireBasicAuth "admin")
LegacyRedirect url -> redirect' url 301 -- moved permanently
where
handleSubmitRequest :: Request -> ClientSubmitReq -> ExitEarlyT () Snap ()
handleSubmitRequest req ClientSubmitReq {csrCode=source, csrVersion=version, csrOpt=opt, csrOutput=submitType} = do
let runreq = RunRequest { runreqCommand = submitType
, runreqSource = source
, runreqVersion = version
, runreqOpt = opt }
mresult <- liftIO $ WP.submitJob (ctxPool ctx) runreq
result <- case mresult of
Just r -> return r
Nothing -> do lift (httpError 503 "Service busy, please try again later")
exitEarly ()
-- Record the run as a spam-checking action, but don't actually act
-- on the return value yet; that will come on the next user action
let timeoutSecs = fromIntegral runTimeoutMicrosecs / 1e6
timeTakenSecs = case result of
RunResponseErr RETimeOut -> timeoutSecs
RunResponseErr REBackend -> timeoutSecs / 6 -- shrug
RunResponseOk{} -> runresTimeTakenSecs result
timeFraction = timeTakenSecs / timeoutSecs
_ <- liftIO $ recordCheckSpam (PlayRunTimeoutFraction timeFraction) (gcSpam gctx) (rqClientAddr req)
lift $ writeJSON result
data AddWorkerRequest = AddWorkerRequest
{ awreqHostname :: String
, awreqPubkey :: String }
deriving (Show, Generic)
instance J.FromJSON AddWorkerRequest where
parseJSON = J.genericParseJSON J.defaultOptions { J.fieldLabelModifier = J.camelTo2 '_' . drop 5 }
data RemoveWorkerRequest = RemoveWorkerRequest
{ rmwreqHostname :: String }
deriving (Show, Generic)
instance J.FromJSON RemoveWorkerRequest where
parseJSON = J.genericParseJSON J.defaultOptions { J.fieldLabelModifier = J.camelTo2 '_' . drop 6 }
data RefreshWorkerRequest = RefreshWorkerRequest
{ rfwreqHostname :: String }
deriving (Show, Generic)
instance J.FromJSON RefreshWorkerRequest where
parseJSON = J.genericParseJSON J.defaultOptions { J.fieldLabelModifier = J.camelTo2 '_' . drop 6 }
handleAdminRequest :: Context -> AdminReq -> Snap ()
handleAdminRequest ctx = \case
ARDashboard -> do
modifyResponse (setContentType (Char8.pack "text/html"))
sendFile "static/admin_dashboard.html"
ARStatus -> do
status <- liftIO $ WP.getPoolStatus (ctxPool ctx)
writeJSON status
ARAddWorker -> execExitEarlyT $ do
AddWorkerRequest host pkeyhex <- getRequestBodyEarlyExitJSON 1024 "request too large"
when (any (\b -> b <= chr 32 && b >= chr 127) (host ++ pkeyhex)) $ do
lift $ httpError 400 "Non-printable input"
exitEarly ()
pkey <- case Sign.readPublicKey . BSS.fromShort =<< hexDecode pkeyhex of
Just res -> return res
_ -> do lift $ httpError 400 "Invalid pubkey (must be 64 hex digits)"
exitEarly ()
liftIO $ WP.addWorker (ctxPool ctx) (Char8.pack host) pkey
lift $ putResponse $ setResponseCode 200 emptyResponse
ARRemoveWorker -> execExitEarlyT $ do
RemoveWorkerRequest host <- getRequestBodyEarlyExitJSON 1024 "request too large"
liftIO $ WP.removeWorker (ctxPool ctx) (Char8.pack host)
lift $ putResponse $ setResponseCode 200 emptyResponse
ARRefreshWorker -> execExitEarlyT $ do
RefreshWorkerRequest host <- getRequestBodyEarlyExitJSON 1024 "request too large"
liftIO $ WP.refreshWorker (ctxPool ctx) (Char8.pack host)
lift $ putResponse $ setResponseCode 200 emptyResponse
playModule :: IO ServerModule
playModule = do
let aceDir = "ace-builds/src-min-noconflict"
aceFiles <- map (\path -> StaticFile (aceDir </> path) ["ace-files", Char8.pack (takeFileName path)] "text/javascript")
. filter (\path -> takeExtension path == ".js")
<$> listDirectory ("static" </> aceDir)
return $ ServerModule
{ smMakeContext = \gctx _options k -> do
-- TODO: the max queue length is a completely arbitrary value
pool <- WP.newPool (gcServerSecretKey gctx) 10
challenge <- makeRefreshingChallenge (secondsToDiffTime (24 * 3600))
rng <- newStdGen >>= newTVarIO
forM_ (gcPreloadWorkers gctx) $ \(host, pubkey) ->
WP.addWorker pool host pubkey
k (Context { ctxPool = pool
, ctxChallengeKey = challenge
, ctxRNG = rng })
, smParseRequest = parseRequest
, smHandleRequest = handleRequest
, smStaticFiles = StaticFile "play-index.js" ["play-index.js"] "text/javascript"
: StaticFile "haskell-logo-tw.svg" ["haskell-logo-tw.svg"] "image/svg+xml"
: StaticFile "haskell-play-logo.png" ["haskell-play-logo.png"] "image/png"
: aceFiles
}
| null | https://raw.githubusercontent.com/haskell/play-haskell/a8ae8e62f9b6867b72ea94b47c837408b9a867f7/play-haskell-server/src/Play.hs | haskell | # LANGUAGE OverloadedStrings #
returns the generated key, or an error string
try again with a new key
^ to destination URL
TODO: remove this. This is present only to let the upgrade to /submit go a bit more smoothly.
functionality, because this is more local.
functionality, because this is more local.
TODO: remove this. This is present only to let the upgrade to /submit go a bit more smoothly. Then also remove /challenge.
moved permanently
Record the run as a spam-checking action, but don't actually act
on the return value yet; that will come on the next user action
shrug
TODO: the max queue length is a completely arbitrary value | # LANGUAGE DeriveGeneric #
# LANGUAGE LambdaCase #
# LANGUAGE NumericUnderscores #
# LANGUAGE TupleSections #
# LANGUAGE TypeApplications #
# LANGUAGE ViewPatterns #
module Play (playModule) where
import Control.Concurrent.STM
import Control.Monad (when, forM_)
import Control.Monad.IO.Class (liftIO)
import qualified Data.Aeson as J
import qualified Data.Aeson.Types as J
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as Char8
import qualified Data.ByteString.Lazy as BSL
import qualified Data.ByteString.Short as BSS
import Data.Char (chr)
import Data.Maybe (fromMaybe)
import qualified Data.Map.Strict as Map
import Data.String (fromString)
import Data.Text (Text)
import Data.Time (secondsToDiffTime)
import Data.Word (Word64)
import GHC.Generics (Generic)
import Snap.Core hiding (path, method, pass)
import System.Directory (listDirectory)
import System.FilePath (takeExtension, takeFileName, (</>))
import System.Random (StdGen, genByteString, newStdGen)
import DB (KeyType, Contents(..), ClientAddr)
import qualified DB
import Pages
import ServerModule
import Snap.Server.Utils
import Snap.Server.Utils.BasicAuth
import Snap.Server.Utils.Challenge
import Snap.Server.Utils.ExitEarly
import Snap.Server.Utils.Hex
import Snap.Server.Utils.SpamDetect
import qualified Play.WorkerPool as WP
import PlayHaskellTypes
import PlayHaskellTypes.Constants
import qualified PlayHaskellTypes.Sign as Sign
data ClientJobReq = ClientJobReq
{ cjrGivenKey :: Text
, cjrSource :: Text
, cjrVersion :: Version
, cjrOpt :: Optimisation }
deriving (Show)
instance J.FromJSON ClientJobReq where
parseJSON (J.Object v) =
ClientJobReq <$> v J..: fromString "challenge"
<*> v J..: fromString "source"
<*> v J..: fromString "version"
<*> (fromMaybe O1 <$> (v J..:? fromString "opt"))
parseJSON val = J.prependFailure "parsing ClientJobReq failed, " (J.typeMismatch "Object" val)
data ClientSubmitReq = ClientSubmitReq
{ csrCode :: Text
, csrVersion :: Version
, csrOpt :: Optimisation
, csrOutput :: Command }
deriving (Show)
instance J.FromJSON ClientSubmitReq where
parseJSON (J.Object v) =
ClientSubmitReq
<$> v J..: fromString "code"
<*> v J..: fromString "version"
<*> (fromMaybe O1 <$> (v J..:? fromString "opt"))
<*> v J..: fromString "output"
parseJSON val = J.prependFailure "parsing ClientSubmitReq failed, " (J.typeMismatch "Object" val)
saveKeyLength :: Int
saveKeyLength = 8
maxSaveFileSize :: Int
maxSaveFileSize = 128 * 1024
genKey :: StdGen -> (KeyType, StdGen)
genKey gen =
let (bs, gen') = genByteString saveKeyLength gen
intoAlphabet n = BS.index alphabet (fromIntegral n `rem` BS.length alphabet)
in (BS.map intoAlphabet bs, gen')
where
alphabet :: ByteString
alphabet = Char8.pack (['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'])
genKey' :: TVar StdGen -> IO KeyType
genKey' var = atomically $ do
gen <- readTVar var
let (key, gen') = genKey gen
writeTVar var gen'
return key
genStorePaste :: GlobalContext -> TVar StdGen -> ClientAddr -> Contents -> IO (Either String KeyType)
genStorePaste gctx stvar srcip contents =
let loop iter = do
key <- genKey' stvar
DB.storePaste (gcDb gctx) srcip key contents >>= \case
Nothing -> return (Right key)
Just DB.ErrExists
| otherwise -> return (Left "Database full?")
Just DB.ErrFull ->
return (Left "Too many snippets saved, saving is temporarily disabled")
in loop (0 :: Int)
data Context = Context
{ ctxPool :: WP.WPool
, ctxChallengeKey :: ChallengeKey
, ctxRNG :: TVar StdGen }
data WhatRequest
= Index
| PostedIndex
| FromSaved ByteString
| Save
| Versions
| CurrentChallenge
| Submit
| AdminReq AdminReq
| LegacyRunGHC Command
deriving (Show)
data AdminReq
= ARDashboard
| ARStatus
| ARAddWorker
| ARRemoveWorker
| ARRefreshWorker
deriving (Show)
parseRequest :: Method -> [ByteString] -> Maybe WhatRequest
parseRequest method comps = case (method, comps) of
(GET, []) -> Just Index
(POST, []) -> Just PostedIndex
(GET, ["saved", key]) -> Just (FromSaved key)
(POST, ["save"]) -> Just Save
(GET, ["versions"]) -> Just Versions
(GET, ["challenge"]) -> Just CurrentChallenge
(POST, ["submit"]) -> Just Submit
(GET, ["admin"]) -> Just (AdminReq ARDashboard)
(GET, ["admin", "status"]) -> Just (AdminReq ARStatus)
(PUT, ["admin", "worker"]) -> Just (AdminReq ARAddWorker)
(DELETE, ["admin", "worker"]) -> Just (AdminReq ARRemoveWorker)
(POST, ["admin", "worker", "refresh"]) -> Just (AdminReq ARRefreshWorker)
(POST, ["compile", "run"]) -> Just (LegacyRunGHC CRun)
(POST, ["compile", "core"]) -> Just (LegacyRunGHC CCore)
(POST, ["compile", "asm"]) -> Just (LegacyRunGHC CAsm)
(GET, ["play"]) -> Just (LegacyRedirect "/")
(GET, ["play", "paste", key]) -> Just (LegacyRedirect ("/saved/" <> key))
(GET, ["play", "paste", key, _]) -> Just (LegacyRedirect ("/saved/" <> key))
_ -> Nothing
handleRequest :: GlobalContext -> Context -> WhatRequest -> Snap ()
handleRequest gctx ctx = \case
Index -> do
req <- getRequest
renderer <- liftIO $ getPageFromGCtx pPlay gctx
case Map.lookup "code" (rqQueryParams req) of
Just (source : _) -> writeHTML (renderer (Just source))
_ -> writeHTML (renderer Nothing)
PostedIndex -> do
req <- getRequest
case Map.lookup "code" (rqPostParams req) of
Just [source] -> do
renderer <- liftIO $ getPageFromGCtx pPlay gctx
writeHTML (renderer (Just source))
_ ->
httpError 400 "Invalid request"
FromSaved key -> do
res <- liftIO $ DB.getPaste (gcDb gctx) key
let buildPage contents = do
renderer <- liftIO $ getPageFromGCtx pPlay gctx
writeHTML (renderer (Just contents))
case res of
Just (_, Contents [] _ _) -> do
modifyResponse (setContentType (Char8.pack "text/plain"))
writeBS (Char8.pack "Save key not found (empty file list?)")
Just (_, Contents ((_, source) : _) _ _) ->
buildPage source
Nothing -> do
modifyResponse (setContentType (Char8.pack "text/plain"))
writeBS (Char8.pack "Save key not found")
Save -> do
req <- getRequest
isSpam <- liftIO $ recordCheckSpam PlaySave (gcSpam gctx) (rqClientAddr req)
if isSpam
then httpError 429 "Please slow down a bit, you're rate limited"
else do body <- readRequestBody (fromIntegral @Int @Word64 maxSaveFileSize)
let body' = BSL.toStrict body
let contents = Contents [(Nothing, body')] Nothing Nothing
srcip = Char8.unpack (rqClientAddr req)
mkey <- liftIO $ genStorePaste gctx (ctxRNG ctx) srcip contents
case mkey of
Right key -> do
modifyResponse (setContentType (Char8.pack "text/plain"))
writeBS key
Left err -> httpError 500 err
Versions -> do
modifyResponse (setContentType (Char8.pack "text/plain"))
versions <- liftIO (WP.getAvailableVersions (ctxPool ctx))
writeJSON versions
CurrentChallenge -> do
modifyResponse (setContentType (Char8.pack "text/plain"))
key <- liftIO $ servingChallenge (ctxChallengeKey ctx)
writeText key
Open a local exit - early block instead of using Snap 's early - exit
Submit -> execExitEarlyT $ do
req <- lift getRequest
isSpam <- liftIO $ recordCheckSpam PlayRunStart (gcSpam gctx) (rqClientAddr req)
when isSpam $ do
lift (httpError 429 "Please slow down a bit, you're rate limited")
exitEarly ()
postdata <- getRequestBodyEarlyExit 1000_000 "Program too large"
csr <-
case J.decodeStrict' postdata of
Just request -> return request
_ -> do lift (httpError 400 "Invalid JSON")
exitEarly ()
handleSubmitRequest req csr
Open a local exit - early block instead of using Snap 's early - exit
LegacyRunGHC runner -> execExitEarlyT $ do
req <- lift getRequest
isSpam <- liftIO $ recordCheckSpam PlayRunStart (gcSpam gctx) (rqClientAddr req)
when isSpam $ do
lift (httpError 429 "Please slow down a bit, you're rate limited")
exitEarly ()
postdata <- getRequestBodyEarlyExit 1000_000 "Program too large"
ClientJobReq {cjrGivenKey=givenKey, cjrSource=source, cjrVersion=version, cjrOpt=opt} <-
case J.decodeStrict' postdata of
Just request -> return request
_ -> do lift (httpError 400 "Invalid JSON")
exitEarly ()
liftIO (checkChallenge (ctxChallengeKey ctx) givenKey) >>= \case
True -> return ()
False -> do lift (httpError 400 "Invalid challenge, request again")
exitEarly ()
handleSubmitRequest req
ClientSubmitReq { csrCode = source
, csrVersion = version
, csrOpt = opt
, csrOutput = runner }
AdminReq adminreq -> do
getBasicAuthCredentials <$> getRequest >>= \case
Just (user, pass)
| user == "admin"
, Just pass == gcAdminPassword gctx
-> handleAdminRequest ctx adminreq
_ -> modifyResponse (requireBasicAuth "admin")
where
handleSubmitRequest :: Request -> ClientSubmitReq -> ExitEarlyT () Snap ()
handleSubmitRequest req ClientSubmitReq {csrCode=source, csrVersion=version, csrOpt=opt, csrOutput=submitType} = do
let runreq = RunRequest { runreqCommand = submitType
, runreqSource = source
, runreqVersion = version
, runreqOpt = opt }
mresult <- liftIO $ WP.submitJob (ctxPool ctx) runreq
result <- case mresult of
Just r -> return r
Nothing -> do lift (httpError 503 "Service busy, please try again later")
exitEarly ()
let timeoutSecs = fromIntegral runTimeoutMicrosecs / 1e6
timeTakenSecs = case result of
RunResponseErr RETimeOut -> timeoutSecs
RunResponseOk{} -> runresTimeTakenSecs result
timeFraction = timeTakenSecs / timeoutSecs
_ <- liftIO $ recordCheckSpam (PlayRunTimeoutFraction timeFraction) (gcSpam gctx) (rqClientAddr req)
lift $ writeJSON result
data AddWorkerRequest = AddWorkerRequest
{ awreqHostname :: String
, awreqPubkey :: String }
deriving (Show, Generic)
instance J.FromJSON AddWorkerRequest where
parseJSON = J.genericParseJSON J.defaultOptions { J.fieldLabelModifier = J.camelTo2 '_' . drop 5 }
data RemoveWorkerRequest = RemoveWorkerRequest
{ rmwreqHostname :: String }
deriving (Show, Generic)
instance J.FromJSON RemoveWorkerRequest where
parseJSON = J.genericParseJSON J.defaultOptions { J.fieldLabelModifier = J.camelTo2 '_' . drop 6 }
data RefreshWorkerRequest = RefreshWorkerRequest
{ rfwreqHostname :: String }
deriving (Show, Generic)
instance J.FromJSON RefreshWorkerRequest where
parseJSON = J.genericParseJSON J.defaultOptions { J.fieldLabelModifier = J.camelTo2 '_' . drop 6 }
handleAdminRequest :: Context -> AdminReq -> Snap ()
handleAdminRequest ctx = \case
ARDashboard -> do
modifyResponse (setContentType (Char8.pack "text/html"))
sendFile "static/admin_dashboard.html"
ARStatus -> do
status <- liftIO $ WP.getPoolStatus (ctxPool ctx)
writeJSON status
ARAddWorker -> execExitEarlyT $ do
AddWorkerRequest host pkeyhex <- getRequestBodyEarlyExitJSON 1024 "request too large"
when (any (\b -> b <= chr 32 && b >= chr 127) (host ++ pkeyhex)) $ do
lift $ httpError 400 "Non-printable input"
exitEarly ()
pkey <- case Sign.readPublicKey . BSS.fromShort =<< hexDecode pkeyhex of
Just res -> return res
_ -> do lift $ httpError 400 "Invalid pubkey (must be 64 hex digits)"
exitEarly ()
liftIO $ WP.addWorker (ctxPool ctx) (Char8.pack host) pkey
lift $ putResponse $ setResponseCode 200 emptyResponse
ARRemoveWorker -> execExitEarlyT $ do
RemoveWorkerRequest host <- getRequestBodyEarlyExitJSON 1024 "request too large"
liftIO $ WP.removeWorker (ctxPool ctx) (Char8.pack host)
lift $ putResponse $ setResponseCode 200 emptyResponse
ARRefreshWorker -> execExitEarlyT $ do
RefreshWorkerRequest host <- getRequestBodyEarlyExitJSON 1024 "request too large"
liftIO $ WP.refreshWorker (ctxPool ctx) (Char8.pack host)
lift $ putResponse $ setResponseCode 200 emptyResponse
playModule :: IO ServerModule
playModule = do
let aceDir = "ace-builds/src-min-noconflict"
aceFiles <- map (\path -> StaticFile (aceDir </> path) ["ace-files", Char8.pack (takeFileName path)] "text/javascript")
. filter (\path -> takeExtension path == ".js")
<$> listDirectory ("static" </> aceDir)
return $ ServerModule
{ smMakeContext = \gctx _options k -> do
pool <- WP.newPool (gcServerSecretKey gctx) 10
challenge <- makeRefreshingChallenge (secondsToDiffTime (24 * 3600))
rng <- newStdGen >>= newTVarIO
forM_ (gcPreloadWorkers gctx) $ \(host, pubkey) ->
WP.addWorker pool host pubkey
k (Context { ctxPool = pool
, ctxChallengeKey = challenge
, ctxRNG = rng })
, smParseRequest = parseRequest
, smHandleRequest = handleRequest
, smStaticFiles = StaticFile "play-index.js" ["play-index.js"] "text/javascript"
: StaticFile "haskell-logo-tw.svg" ["haskell-logo-tw.svg"] "image/svg+xml"
: StaticFile "haskell-play-logo.png" ["haskell-play-logo.png"] "image/png"
: aceFiles
}
|
7bbf903e32cda8148b7808258c176b87dac20c75567f9a9e66a9e9416a69a852 | NorfairKing/smos | Gen.hs | # OPTIONS_GHC -fno - warn - orphans #
module Smos.Keys.Gen where
import Graphics.Vty.Input.Events
import Smos.Data.Gen ()
import Smos.Keys
import Smos.Report.OptParse.Gen ()
import TestImport
instance GenValid Key where
genValid = genValidStructurally
shrinkValid = shrinkValidStructurally
instance GenValid Modifier where
genValid = genValidStructurally
shrinkValid = shrinkValidStructurally
instance GenValid KeyPress where
genValid = genValidStructurally
shrinkValid = shrinkValidStructurally
instance GenValid MatcherConfig where
genValid = genValidStructurally
shrinkValid = shrinkValidStructurally
| null | https://raw.githubusercontent.com/NorfairKing/smos/f72b26c2e66ab4f3ec879a1bedc6c0e8eeb18a01/smos/test/Smos/Keys/Gen.hs | haskell | # OPTIONS_GHC -fno - warn - orphans #
module Smos.Keys.Gen where
import Graphics.Vty.Input.Events
import Smos.Data.Gen ()
import Smos.Keys
import Smos.Report.OptParse.Gen ()
import TestImport
instance GenValid Key where
genValid = genValidStructurally
shrinkValid = shrinkValidStructurally
instance GenValid Modifier where
genValid = genValidStructurally
shrinkValid = shrinkValidStructurally
instance GenValid KeyPress where
genValid = genValidStructurally
shrinkValid = shrinkValidStructurally
instance GenValid MatcherConfig where
genValid = genValidStructurally
shrinkValid = shrinkValidStructurally
| |
b02aa6b48055852b0e2a52af4ae9cbef90b500b2c9be8dec72138dd11ddae373 | DogLooksGood/holdem | panel.cljs | (ns poker.components.panel
"Player's status is displayed in panel.
Buttons are displayed depending on current state. "
(:require
[reagent.core :as reagent]
[re-frame.core :as re-frame]
[poker.components.message-box :refer [message-box]]
[poker.components.button :refer [raise-button
check-button
call-button
bet-button
fold-button
reveal-button
musk-button
join-bet-button
runner-times-button]]))
(defn get-buttons-set
[players current-player street-bet]
(when (= :player-status/in-action (:status current-player))
(let [{:keys [bets]} current-player
this-bet (last bets)]
(cond-> #{}
(and (nil? street-bet) (nil? this-bet))
(conj :check :bet)
(and street-bet (= this-bet street-bet))
(conj :check :raise)
(< this-bet street-bet)
(conj :fold :call)
(and (< this-bet street-bet)
(some (comp #{:player-status/acted :player-status/wait-for-action} :status) players))
(conj :raise)))))
(defn on-fold
[]
(re-frame/dispatch [:game/fold]))
(defn on-check
[]
(re-frame/dispatch [:game/check]))
(defn on-call
[]
(re-frame/dispatch [:game/call]))
(defn on-bet
[bet]
(re-frame/dispatch [:game/bet {:bet bet}]))
(defn on-raise
[raise]
(re-frame/dispatch [:game/raise {:raise raise}]))
(defn on-musk
[]
(re-frame/dispatch [:game/musk]))
(defn on-join-bet
[]
(re-frame/dispatch [:game/join-bet]))
(defn on-request-deal-times
[deal-times]
(re-frame/dispatch [:game/request-deal-times {:deal-times deal-times}]))
(defn bet-button-group
[{:keys [buttons-set bet pot-val stack street-bet min-raise opts]}]
(when buttons-set
[:div.w-full.h-full.flex.flex-col.justify-end.items-stretch
(when (:raise buttons-set)
[raise-button
{:min-raise min-raise,
:pot pot-val,
:sb (:sb opts),
:bb (:bb opts),
:stack stack,
:street-bet street-bet,
:bet bet,
:on-raise on-raise}])
(when (:bet buttons-set)
[bet-button
{:pot pot-val,
:stack stack,
:on-bet on-bet,
:bb (:bb opts)}])
[:div.flex.w-full
(when (:call buttons-set)
[call-button {:on-call on-call, :street-bet street-bet, :bet bet, :stack stack}])
(when (:fold buttons-set)
[fold-button {:on-fold on-fold}])
(when (:check buttons-set)
[check-button {:on-check on-check}])]]))
(defn runner-button-group
[]
(let [deal-times* (reagent/atom nil)]
(fn []
[:div.w-full.h-full.flex.flex-col.justify-end.items-stretch
[runner-times-button
{:on-click #(do (reset! deal-times* 1)
(on-request-deal-times 1)),
:text "Run ONCE!",
:selected? (= @deal-times*
1),
:disabled? (some? @deal-times*)}]
[runner-times-button
{:on-click #(do (reset! deal-times* 2)
(on-request-deal-times 2)),
:text "Run TWICE!",
:selected? (= @deal-times*
2),
:disabled? (some? @deal-times*)}]])))
(defn join-bet-button-group
[]
[:div.w-full.h-full.flex.flex-col.justify-end.items-stretch
[join-bet-button {:on-join-bet on-join-bet}]])
(defn showdown-button-group
[]
(let [choice* (reagent/atom false)]
(fn []
[:div.w-full.h-full.flex.flex-col.justify-end.items-stretch
[:div.flex-1
(when-not (= :musk @choice*)
[reveal-button
{:on-reveal #(reset! choice* :reveal),
:clicked @choice*}])]
[:div.flex-1
(when-not (= :reveal @choice*)
[musk-button
{:disabled @choice*,
:on-musk #(do (reset! choice* :musk)
(on-musk))}])]])))
(defn panel
[{:keys [current-player pots street-bet opts players messages], game-status :status, :as props}]
(let [{:keys [status stack]} current-player
buttons-set (get-buttons-set players current-player street-bet)
pot-val (transduce (map :value) + 0 pots)]
;; container
[:div.bg-gray-900.md:bg-transparent.md:pointer-events-none.md:absolute.md:left-0.md:bottom-0.md:right-0.flex.justify-end.items-stretch.h-36.self-stretch
;; right part
[:div.w-full.sm:w-72.lg:w-96.md:max-w-full.flex.flex-col.justify-end.items-stretch
;; message box
[:div.flex-1.relative
[:div.absolute.bottom-0.left-0.right-0.p-1.pointer-events-auto
[message-box messages]]]
[:div.h-24.pointer-events-auto
(cond
(= :player-status/off-seat status)
[:div.text-md.flex.justify-center.items-center.h-24.text-gray-500
"Pick a seat to join"]
(= game-status :game-status/showdown-prepare)
(when (#{:player-status/acted} status)
[showdown-button-group])
(= game-status :game-status/runner-prepare)
(when (#{:player-status/acted :player-status/all-in} status)
[runner-button-group])
(seq buttons-set)
[bet-button-group
{:pot-val (or pot-val 0),
:opts opts,
:bet (or (last (:bets current-player)) 0),
:street-bet (or street-bet 0),
:buttons-set buttons-set,
:stack stack}]
(= :player-status/wait-for-bb (:status current-player))
[join-bet-button-group]
(= :player-status/wait-for-start (:status current-player))
[:div.text-md.flex.justify-center.items-center.h-24.text-gray-500
"Waiting for game start"])]]]))
| null | https://raw.githubusercontent.com/DogLooksGood/holdem/949b25361fd59d8b6f444215f279a5206e200043/src/cljs/poker/components/panel.cljs | clojure | container
right part
message box | (ns poker.components.panel
"Player's status is displayed in panel.
Buttons are displayed depending on current state. "
(:require
[reagent.core :as reagent]
[re-frame.core :as re-frame]
[poker.components.message-box :refer [message-box]]
[poker.components.button :refer [raise-button
check-button
call-button
bet-button
fold-button
reveal-button
musk-button
join-bet-button
runner-times-button]]))
(defn get-buttons-set
[players current-player street-bet]
(when (= :player-status/in-action (:status current-player))
(let [{:keys [bets]} current-player
this-bet (last bets)]
(cond-> #{}
(and (nil? street-bet) (nil? this-bet))
(conj :check :bet)
(and street-bet (= this-bet street-bet))
(conj :check :raise)
(< this-bet street-bet)
(conj :fold :call)
(and (< this-bet street-bet)
(some (comp #{:player-status/acted :player-status/wait-for-action} :status) players))
(conj :raise)))))
(defn on-fold
[]
(re-frame/dispatch [:game/fold]))
(defn on-check
[]
(re-frame/dispatch [:game/check]))
(defn on-call
[]
(re-frame/dispatch [:game/call]))
(defn on-bet
[bet]
(re-frame/dispatch [:game/bet {:bet bet}]))
(defn on-raise
[raise]
(re-frame/dispatch [:game/raise {:raise raise}]))
(defn on-musk
[]
(re-frame/dispatch [:game/musk]))
(defn on-join-bet
[]
(re-frame/dispatch [:game/join-bet]))
(defn on-request-deal-times
[deal-times]
(re-frame/dispatch [:game/request-deal-times {:deal-times deal-times}]))
(defn bet-button-group
[{:keys [buttons-set bet pot-val stack street-bet min-raise opts]}]
(when buttons-set
[:div.w-full.h-full.flex.flex-col.justify-end.items-stretch
(when (:raise buttons-set)
[raise-button
{:min-raise min-raise,
:pot pot-val,
:sb (:sb opts),
:bb (:bb opts),
:stack stack,
:street-bet street-bet,
:bet bet,
:on-raise on-raise}])
(when (:bet buttons-set)
[bet-button
{:pot pot-val,
:stack stack,
:on-bet on-bet,
:bb (:bb opts)}])
[:div.flex.w-full
(when (:call buttons-set)
[call-button {:on-call on-call, :street-bet street-bet, :bet bet, :stack stack}])
(when (:fold buttons-set)
[fold-button {:on-fold on-fold}])
(when (:check buttons-set)
[check-button {:on-check on-check}])]]))
(defn runner-button-group
[]
(let [deal-times* (reagent/atom nil)]
(fn []
[:div.w-full.h-full.flex.flex-col.justify-end.items-stretch
[runner-times-button
{:on-click #(do (reset! deal-times* 1)
(on-request-deal-times 1)),
:text "Run ONCE!",
:selected? (= @deal-times*
1),
:disabled? (some? @deal-times*)}]
[runner-times-button
{:on-click #(do (reset! deal-times* 2)
(on-request-deal-times 2)),
:text "Run TWICE!",
:selected? (= @deal-times*
2),
:disabled? (some? @deal-times*)}]])))
(defn join-bet-button-group
[]
[:div.w-full.h-full.flex.flex-col.justify-end.items-stretch
[join-bet-button {:on-join-bet on-join-bet}]])
(defn showdown-button-group
[]
(let [choice* (reagent/atom false)]
(fn []
[:div.w-full.h-full.flex.flex-col.justify-end.items-stretch
[:div.flex-1
(when-not (= :musk @choice*)
[reveal-button
{:on-reveal #(reset! choice* :reveal),
:clicked @choice*}])]
[:div.flex-1
(when-not (= :reveal @choice*)
[musk-button
{:disabled @choice*,
:on-musk #(do (reset! choice* :musk)
(on-musk))}])]])))
(defn panel
[{:keys [current-player pots street-bet opts players messages], game-status :status, :as props}]
(let [{:keys [status stack]} current-player
buttons-set (get-buttons-set players current-player street-bet)
pot-val (transduce (map :value) + 0 pots)]
[:div.bg-gray-900.md:bg-transparent.md:pointer-events-none.md:absolute.md:left-0.md:bottom-0.md:right-0.flex.justify-end.items-stretch.h-36.self-stretch
[:div.w-full.sm:w-72.lg:w-96.md:max-w-full.flex.flex-col.justify-end.items-stretch
[:div.flex-1.relative
[:div.absolute.bottom-0.left-0.right-0.p-1.pointer-events-auto
[message-box messages]]]
[:div.h-24.pointer-events-auto
(cond
(= :player-status/off-seat status)
[:div.text-md.flex.justify-center.items-center.h-24.text-gray-500
"Pick a seat to join"]
(= game-status :game-status/showdown-prepare)
(when (#{:player-status/acted} status)
[showdown-button-group])
(= game-status :game-status/runner-prepare)
(when (#{:player-status/acted :player-status/all-in} status)
[runner-button-group])
(seq buttons-set)
[bet-button-group
{:pot-val (or pot-val 0),
:opts opts,
:bet (or (last (:bets current-player)) 0),
:street-bet (or street-bet 0),
:buttons-set buttons-set,
:stack stack}]
(= :player-status/wait-for-bb (:status current-player))
[join-bet-button-group]
(= :player-status/wait-for-start (:status current-player))
[:div.text-md.flex.justify-center.items-center.h-24.text-gray-500
"Waiting for game start"])]]]))
|
4eb0667ed3e5c618ad943f20a041f2c1ee112cbec7381218a0b2fe2d57486268 | karimarttila/clojure | core.clj | (ns simpleserver.core
(:require
[clojure.tools.logging :as log]
[clojure.pprint]
[clojure.java.io :as io]
[ring.adapter.jetty :as jetty]
[nrepl.server :as nrepl]
[integrant.repl :as ig-repl]
[integrant.core :as ig]
[aero.core :as aero]
[hikari-cp.core :as hikari-cp]
[datomic.api :as d]
[simpleserver.service.service :as ss-service]
[simpleserver.webserver.server :as ss-webserver]
[simpleserver.service.dynamodb-config :as ddb-config]
[simpleserver.service.domain.domain-csv-db-loader :as csv-db-loader]
[clojure.tools.reader.edn :as edn]
[potpuri.core :as p]))
(defn env-value [key default]
(some-> (or (System/getenv (name key)) default)))
(defmethod aero/reader 'ig/ref [_ _ value] (ig/ref value))
(defmethod ig/init-key :backend/profile [_ profile]
profile)
(defmethod ig/init-key :backend/active-db [_ active-db]
(log/debug (str "ENTER ig/init-key :backend/active-db:") active-db)
(keyword active-db))
(defmethod ig/init-key :backend/csv [_ {:keys [profile active-db data-dir]}]
(log/debug "ENTER ig/init-key :backend/csv")
; We simulate this data store using atom.
; We initialize the "db" from :data-dir.
(if (= active-db :csv)
(let [csv-data
{:data-dir data-dir
:db (atom {:domain {}
:session #{}
:user {}})}]
; Let's keep the test database empty.
(if (not= profile :test)
(csv-db-loader/load-csv-db csv-data))
(:db csv-data))))
(defmethod ig/init-key :backend/ddb [_ {:keys [active-db ss-table-prefix ss-env endpoint aws-profile]}]
(log/debug "ENTER ig/init-key :backend/ddb")
(if (= active-db :ddb)
(ddb-config/get-dynamodb-config ss-table-prefix ss-env endpoint aws-profile)))
(defmethod ig/init-key :backend/postgres [_ opts]
(log/debug "ENTER ig/init-key :backend/postgres")
(if (= (:active-db opts) :postgres)
{:datasource (hikari-cp/make-datasource (dissoc opts :active-db)) :active-db (:active-db opts)}))
(defmethod ig/halt-key! :backend/postgres [_ this]
(log/debug "ENTER ig/halt-key! :backend/postgres")
(if (= (:active-db this) :postgres)
(hikari-cp/close-datasource (:datasource this))))
(defmethod ig/init-key :backend/datomic [_ {:keys [active-db uri]}]
(log/debug "ENTER ig/init-key :backend/datomic")
(if (= active-db :datomic)
{:conn (d/connect uri)}))
(defmethod ig/halt-key! :backend/datomic [_ this]
(log/debug "ENTER ig/halt-key! :backend/datomic")
(if (= (:active-db this) :datomic)
(d/release (:conn this))))
(defmethod ig/init-key :backend/service [_ {:keys [active-db csv ddb postgres datomic]}]
(log/debug "ENTER ig/init-key :backend/service")
(ss-service/get-service-config {:active-db active-db :csv csv :ddb ddb :postgres postgres :datomic datomic}))
(defmethod ig/init-key :backend/env [_ env]
env)
(defmethod ig/init-key :backend/jetty [_ {:keys [port join? env]}]
(log/debug "ENTER ig/init-key :backend/jetty")
(-> (ss-webserver/handler (ss-webserver/routes env))
(jetty/run-jetty {:port port :join? join?})))
(defmethod ig/halt-key! :backend/jetty [_ server]
(log/debug "ENTER ig/halt-key! :backend/jetty")
(.stop server))
(defmethod ig/init-key :backend/options [_ options]
(log/debug "ENTER ig/init-key :backend/options")
options)
(defmethod ig/init-key :backend/nrepl [_ {:keys [bind port]}]
(log/debug "ENTER ig/init-key :backend/nrepl")
(if (and bind port)
(nrepl/start-server :bind bind :port port)
nil))
(defmethod ig/halt-key! :backend/nrepl [_ this]
(log/debug "ENTER ig/halt-key! :backend/nrepl")
(if this
(nrepl/stop-server this)))
(defmethod ig/suspend-key! :backend/nrepl [_ this]
(log/debug "ENTER ig/suspend-key! :backend/nrepl")
this)
(defmethod ig/resume-key :backend/nrepl [_ _ _ old-impl]
(log/debug "ENTER ig/resume-key :backend/nrepl")
old-impl)
; Profile is if you want to test in real AWS env:
; you can add to the container script PROFILE=prod
(defn read-config [profile]
(let [local-config (let [file (io/file "config-local.edn")]
(if (.exists file) (edn/read-string (slurp file))))]
(cond-> (aero/read-config (io/resource "config.edn") {:profile profile})
local-config (p/deep-merge local-config))))
(defn system-config [myprofile]
(let [profile (or myprofile (some-> (System/getenv "PROFILE") keyword) :dev)
_ (log/info "Using profile " profile)
config (read-config profile)]
config))
(defn system-config-start []
(system-config nil))
(defn -main []
(log/info "System starting...")
(let [config (system-config-start)
_ (log/info "Config: " config)]
(ig-repl/set-prep! (constantly config))
(ig-repl/go)))
(comment
(ig-repl/reset)
)
| null | https://raw.githubusercontent.com/karimarttila/clojure/3e23d3755d8f555e94d77d104dd9401edc7e8cc9/webstore-demo/re-frame-demo/src/clj/simpleserver/core.clj | clojure | We simulate this data store using atom.
We initialize the "db" from :data-dir.
Let's keep the test database empty.
Profile is if you want to test in real AWS env:
you can add to the container script PROFILE=prod | (ns simpleserver.core
(:require
[clojure.tools.logging :as log]
[clojure.pprint]
[clojure.java.io :as io]
[ring.adapter.jetty :as jetty]
[nrepl.server :as nrepl]
[integrant.repl :as ig-repl]
[integrant.core :as ig]
[aero.core :as aero]
[hikari-cp.core :as hikari-cp]
[datomic.api :as d]
[simpleserver.service.service :as ss-service]
[simpleserver.webserver.server :as ss-webserver]
[simpleserver.service.dynamodb-config :as ddb-config]
[simpleserver.service.domain.domain-csv-db-loader :as csv-db-loader]
[clojure.tools.reader.edn :as edn]
[potpuri.core :as p]))
(defn env-value [key default]
(some-> (or (System/getenv (name key)) default)))
(defmethod aero/reader 'ig/ref [_ _ value] (ig/ref value))
(defmethod ig/init-key :backend/profile [_ profile]
profile)
(defmethod ig/init-key :backend/active-db [_ active-db]
(log/debug (str "ENTER ig/init-key :backend/active-db:") active-db)
(keyword active-db))
(defmethod ig/init-key :backend/csv [_ {:keys [profile active-db data-dir]}]
(log/debug "ENTER ig/init-key :backend/csv")
(if (= active-db :csv)
(let [csv-data
{:data-dir data-dir
:db (atom {:domain {}
:session #{}
:user {}})}]
(if (not= profile :test)
(csv-db-loader/load-csv-db csv-data))
(:db csv-data))))
(defmethod ig/init-key :backend/ddb [_ {:keys [active-db ss-table-prefix ss-env endpoint aws-profile]}]
(log/debug "ENTER ig/init-key :backend/ddb")
(if (= active-db :ddb)
(ddb-config/get-dynamodb-config ss-table-prefix ss-env endpoint aws-profile)))
(defmethod ig/init-key :backend/postgres [_ opts]
(log/debug "ENTER ig/init-key :backend/postgres")
(if (= (:active-db opts) :postgres)
{:datasource (hikari-cp/make-datasource (dissoc opts :active-db)) :active-db (:active-db opts)}))
(defmethod ig/halt-key! :backend/postgres [_ this]
(log/debug "ENTER ig/halt-key! :backend/postgres")
(if (= (:active-db this) :postgres)
(hikari-cp/close-datasource (:datasource this))))
(defmethod ig/init-key :backend/datomic [_ {:keys [active-db uri]}]
(log/debug "ENTER ig/init-key :backend/datomic")
(if (= active-db :datomic)
{:conn (d/connect uri)}))
(defmethod ig/halt-key! :backend/datomic [_ this]
(log/debug "ENTER ig/halt-key! :backend/datomic")
(if (= (:active-db this) :datomic)
(d/release (:conn this))))
(defmethod ig/init-key :backend/service [_ {:keys [active-db csv ddb postgres datomic]}]
(log/debug "ENTER ig/init-key :backend/service")
(ss-service/get-service-config {:active-db active-db :csv csv :ddb ddb :postgres postgres :datomic datomic}))
(defmethod ig/init-key :backend/env [_ env]
env)
(defmethod ig/init-key :backend/jetty [_ {:keys [port join? env]}]
(log/debug "ENTER ig/init-key :backend/jetty")
(-> (ss-webserver/handler (ss-webserver/routes env))
(jetty/run-jetty {:port port :join? join?})))
(defmethod ig/halt-key! :backend/jetty [_ server]
(log/debug "ENTER ig/halt-key! :backend/jetty")
(.stop server))
(defmethod ig/init-key :backend/options [_ options]
(log/debug "ENTER ig/init-key :backend/options")
options)
(defmethod ig/init-key :backend/nrepl [_ {:keys [bind port]}]
(log/debug "ENTER ig/init-key :backend/nrepl")
(if (and bind port)
(nrepl/start-server :bind bind :port port)
nil))
(defmethod ig/halt-key! :backend/nrepl [_ this]
(log/debug "ENTER ig/halt-key! :backend/nrepl")
(if this
(nrepl/stop-server this)))
(defmethod ig/suspend-key! :backend/nrepl [_ this]
(log/debug "ENTER ig/suspend-key! :backend/nrepl")
this)
(defmethod ig/resume-key :backend/nrepl [_ _ _ old-impl]
(log/debug "ENTER ig/resume-key :backend/nrepl")
old-impl)
(defn read-config [profile]
(let [local-config (let [file (io/file "config-local.edn")]
(if (.exists file) (edn/read-string (slurp file))))]
(cond-> (aero/read-config (io/resource "config.edn") {:profile profile})
local-config (p/deep-merge local-config))))
(defn system-config [myprofile]
(let [profile (or myprofile (some-> (System/getenv "PROFILE") keyword) :dev)
_ (log/info "Using profile " profile)
config (read-config profile)]
config))
(defn system-config-start []
(system-config nil))
(defn -main []
(log/info "System starting...")
(let [config (system-config-start)
_ (log/info "Config: " config)]
(ig-repl/set-prep! (constantly config))
(ig-repl/go)))
(comment
(ig-repl/reset)
)
|
a60e5dee0bb3374d76d62d13397e369e9d690b635b6c3ea073cfc226a4cb51e3 | MinaProtocol/mina | vesta_constraint_system.mli | include
Intf.Full
with type fp := Kimchi_pasta_basic.Fp.t
and type gates := Kimchi_bindings.Protocol.Gates.Vector.Fp.t
| null | https://raw.githubusercontent.com/MinaProtocol/mina/a40d965ae6b39ca93d9eed17efcbf77e0778de0a/src/lib/crypto/kimchi_backend/pasta/constraint_system/vesta_constraint_system.mli | ocaml | include
Intf.Full
with type fp := Kimchi_pasta_basic.Fp.t
and type gates := Kimchi_bindings.Protocol.Gates.Vector.Fp.t
| |
5e0ecd16f49cbb4cf38ba9f2b13d291e70a183565fdbd7814783b2a65f2607a0 | GaloisInc/saw-script | IDESupport.hs | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
{-# LANGUAGE GADTs #-}
# LANGUAGE KindSignatures #
# LANGUAGE LambdaCase #
# LANGUAGE QuasiQuotes #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeOperators #
# LANGUAGE UndecidableInstances #
# LANGUAGE ViewPatterns #
# LANGUAGE PolyKinds #
module Verifier.SAW.Heapster.IDESupport where
import Control.Monad.Reader
( MonadReader (ask, local),
ReaderT (..),
)
import Data.Aeson (ToJSON, Value, encodeFile)
import Data.Binding.Hobbits
( Liftable (..),
Mb,
NuMatching (..),
RList,
mbMatch,
nuMP,
nuMultiWithElim1,
unsafeMbTypeRepr,
Name,
)
import Data.Maybe (catMaybes, listToMaybe, mapMaybe)
import Data.Parameterized.Some (Some (..))
import qualified Data.Text as T
import qualified Data.Type.RList as RL
import GHC.Generics (Generic)
import Lang.Crucible.FunctionHandle
import Lang.Crucible.Types (CrucibleType)
import What4.FunctionName (FunctionName (functionName))
import What4.ProgramLoc
( Position (BinaryPos, InternalPos, OtherPos, SourcePos),
ProgramLoc (..),
)
import Verifier.SAW.Heapster.CruUtil
import Verifier.SAW.Heapster.Permissions
import Verifier.SAW.Heapster.Implication
import Verifier.SAW.Heapster.TypedCrucible
import Verifier.SAW.Heapster.SAWTranslation (SomeTypedCFG (..))
import Verifier.SAW.Heapster.JSONExport(ppToJson)
import Data.Type.RList (mapRAssign)
import Data.Functor.Constant
import Control.Monad.Writer
import Data.Binding.Hobbits.NameMap (NameMap)
import qualified Data.Binding.Hobbits.NameMap as NameMap
import Verifier.SAW.Heapster.NamedMb
| The entry point for dumping a environment to a file for IDE
-- consumption.
printIDEInfo :: PermEnv -> [Some SomeTypedCFG] -> FilePath -> PPInfo -> IO ()
printIDEInfo _penv tcfgs file ppinfo =
encodeFile file $ IDELog (runWithLoc ppinfo tcfgs)
type ExtractionM = ReaderT (PPInfo, ProgramLoc, String) (Writer [LogEntry])
emit :: LogEntry -> ExtractionM ()
emit entry = tell [entry]
gather :: ExtractionM () -> ExtractionM [LogEntry]
gather m = snd <$> listen m
-- | A single entry in the IDE info dump log. At a bare minimum, this must
-- include a location and corresponding permission. Once the basics are
-- working, we can enrich the information we log.
data LogEntry
= LogEntry
{ leLocation :: String
, leEntryId :: LogEntryID
, leCallers :: [LogEntryID]
, leFunctionName :: String
, lePermissions :: [(String, String, Value)]
}
| LogError
{ lerrLocation :: String
, lerrError :: String
, lerrFunctionName :: String
}
| LogImpl
{ limplLocation :: String
, limplExport :: Value
, limplFunctionName :: String
}
deriving (Generic, Show)
instance ToJSON LogEntry
instance NuMatching LogEntry where
nuMatchingProof = unsafeMbTypeRepr
instance Liftable LogEntry where
mbLift mb = case mbMatch mb of
[nuMP| LogEntry v w x y z |] ->
LogEntry (mbLift v) (mbLift w) (mbLift x) (mbLift y) (mbLift z)
[nuMP| LogError x y z |] ->
LogError (mbLift x) (mbLift y) (mbLift z)
[nuMP| LogImpl x y z |] ->
LogImpl (mbLift x) (mbLift y) (mbLift z)
data LogEntryID = LogEntryID
{ leIdBlock :: Int
, leIdHeapster :: Int
}
deriving (Generic, Show)
instance ToJSON LogEntryID
instance NuMatching LogEntryID where
nuMatchingProof = unsafeMbTypeRepr
instance Liftable LogEntryID where
mbLift mb = case mbMatch mb of
[nuMP| LogEntryID x y |] -> LogEntryID (mbLift x) (mbLift y)
-- | A complete IDE info dump log, which is just a sequence of entries. Once
-- the basics are working, we can enrich the information we log.
newtype IDELog = IDELog {
lmfEntries :: [LogEntry]
} deriving (Generic, Show)
instance ToJSON IDELog
class ExtractLogEntries a where
extractLogEntries :: a -> ExtractionM ()
instance (PermCheckExtC ext extExpr)
=> ExtractLogEntries
(TypedEntry TransPhase ext blocks tops ret args ghosts) where
extractLogEntries te = do
let loc = mbLiftNamed $ fmap getFirstProgramLocTS (typedEntryBody te)
withLoc loc (mb'ExtractLogEntries (typedEntryBody te))
let entryId = mkLogEntryID $ typedEntryID te
let callers = callerIDs $ typedEntryCallers te
(ppi, _, fname) <- ask
let loc' = snd (ppLoc loc)
let debugNames = _mbNames (typedEntryBody te)
let insertNames ::
RL.RAssign Name (x :: RList CrucibleType) ->
RL.RAssign StringF x ->
NameMap (StringF :: CrucibleType -> *)->
NameMap (StringF :: CrucibleType -> *)
insertNames RL.MNil RL.MNil m = m
insertNames (ns RL.:>: n) (xs RL.:>: StringF name) m =
insertNames ns xs (NameMap.insert n (StringF name) m)
inputs = mbLift
$ flip nuMultiWithElim1 (typedEntryPermsIn te)
$ \ns body ->
let ppi' = ppi { ppExprNames = insertNames ns debugNames (ppExprNames ppi) }
f ::
(Pair StringF ValuePerm) x ->
Constant (String, String, Value) x
f (Pair (StringF name) vp) = Constant (name, permPrettyString ppi' vp, ppToJson ppi' vp)
in RL.toList (mapRAssign f (zipRAssign debugNames body))
tell [LogEntry loc' entryId callers fname inputs]
mkLogEntryID :: TypedEntryID blocks args -> LogEntryID
mkLogEntryID = uncurry LogEntryID . entryIDIndices
callerIDs :: [Some (TypedCallSite phase blocks tops args ghosts)] -> [LogEntryID]
callerIDs = map $ \(Some tcs) -> case typedCallSiteID tcs of
TypedCallSiteID tei _ _ _ -> mkLogEntryID tei
data Pair f g x = Pair (f x) (g x)
zipRAssign :: RL.RAssign f x -> RL.RAssign g x -> RL.RAssign (Pair f g) x
zipRAssign RL.MNil RL.MNil = RL.MNil
zipRAssign (xs RL.:>: x) (ys RL.:>: y) = zipRAssign xs ys RL.:>: Pair x y
instance ExtractLogEntries (TypedStmtSeq ext blocks tops ret ps_in) where
extractLogEntries (TypedImplStmt (AnnotPermImpl _str pimpl)) =
fmap ( setErrorMsg str ) < $ > extractLogEntries pimpl
extractLogEntries pimpl
extractLogEntries (TypedConsStmt loc _ _ rest) = do
withLoc loc $ mb'ExtractLogEntries rest
extractLogEntries (TypedTermStmt _ _) = pure ()
instance ExtractLogEntries
(PermImpl (TypedStmtSeq ext blocks tops ret) ps_in) where
extractLogEntries (PermImpl_Step pi1 mbpis) = do
pi1Entries <- extractLogEntries pi1
pisEntries <- extractLogEntries mbpis
return $ pi1Entries <> pisEntries
extractLogEntries (PermImpl_Done stmts) = extractLogEntries stmts
instance ExtractLogEntries (PermImpl1 ps_in ps_outs) where
extractLogEntries (Impl1_Fail err) =
do (_, loc, fname) <- ask
emit (LogError (snd (ppLoc loc)) (ppError err) fname)
-- The error message is available further up the stack, so we just leave it
extractLogEntries impl =
do (ppi, loc, fname) <- ask
emit (LogImpl (snd (ppLoc loc)) (ppToJson ppi impl) fname)
instance ExtractLogEntries
(MbPermImpls (TypedStmtSeq ext blocks tops ret) ps_outs) where
extractLogEntries (MbPermImpls_Cons ctx mbpis pis) = do
mbExtractLogEntries ctx pis
extractLogEntries mbpis
extractLogEntries MbPermImpls_Nil = pure ()
instance (PermCheckExtC ext extExpr)
=> ExtractLogEntries (TypedCFG ext blocks ghosts inits gouts ret) where
extractLogEntries tcfg = extractLogEntries $ tpcfgBlockMap tcfg
instance (PermCheckExtC ext extExpr)
=> ExtractLogEntries (TypedBlockMap TransPhase ext blocks tops ret) where
extractLogEntries tbm =
sequence_ $ RL.mapToList extractLogEntries tbm
instance (PermCheckExtC ext extExpr)
=> ExtractLogEntries (TypedBlock TransPhase ext blocks tops ret args) where
extractLogEntries tb =
mapM_ (\(Some te) -> extractLogEntries te) $ _typedBlockEntries tb
mbExtractLogEntries
:: ExtractLogEntries a => CruCtx ctx -> Mb (ctx :: RList CrucibleType) a -> ExtractionM ()
mbExtractLogEntries ctx mb_a =
ReaderT $ \(ppi, loc, fname) ->
tell $ mbLift $ flip nuMultiWithElim1 mb_a $ \ns x ->
let ppi' = ppInfoAddTypedExprNames ctx ns ppi in
execWriter $ runReaderT (extractLogEntries x) (ppi', loc, fname)
mb'ExtractLogEntries
:: ExtractLogEntries a => NamedMb (ctx :: RList CrucibleType) a -> ExtractionM ()
mb'ExtractLogEntries mb_a =
ReaderT $ \(ppi, loc, fname) ->
tell $ mbLift $ flip nuMultiWithElim1 (_mbBinding mb_a) $ \ns x ->
let ppi' = ppInfoApplyAllocation ns (_mbNames mb_a) ppi in
execWriter $ runReaderT (extractLogEntries x) (ppi', loc, fname)
typedStmtOutCtx :: TypedStmt ext rets ps_in ps_next -> CruCtx rets
typedStmtOutCtx = error "FIXME: write typedStmtOutCtx"
withLoc :: ProgramLoc -> ExtractionM a -> ExtractionM a
withLoc loc = local (\(ppinfo, _, fname) -> (ppinfo, loc, fname))
setErrorMsg :: String -> LogEntry -> LogEntry
setErrorMsg msg le@LogError {} = le { lerrError = msg }
setErrorMsg msg le@LogImpl {} =
LogError { lerrError = msg
, lerrLocation = limplLocation le
, lerrFunctionName = limplFunctionName le}
setErrorMsg msg le@LogEntry {} =
LogError { lerrError = msg
, lerrLocation = leLocation le
, lerrFunctionName = leFunctionName le
}
runWithLoc :: PPInfo -> [Some SomeTypedCFG] -> [LogEntry]
runWithLoc ppi =
concatMap (runWithLocHelper ppi)
where
runWithLocHelper :: PPInfo -> Some SomeTypedCFG -> [LogEntry]
runWithLocHelper ppi' sstcfg = case sstcfg of
Some (SomeTypedCFG _ _ tcfg) -> do
let env = (ppi', getFirstProgramLoc tcfg, getFunctionName tcfg)
execWriter (runReaderT (extractLogEntries tcfg) env)
getFunctionName :: TypedCFG ext blocks ghosts inits gouts ret -> String
getFunctionName tcfg = case tpcfgHandle tcfg of
TypedFnHandle _ _ handle -> show $ handleName handle
getFirstProgramLoc
:: PermCheckExtC ext extExpr
=> TypedCFG ext blocks ghosts inits gouts ret -> ProgramLoc
getFirstProgramLoc tcfg =
case listToMaybe $ catMaybes $
RL.mapToList getFirstProgramLocBM $ tpcfgBlockMap tcfg of
Just pl -> pl
_ -> error "Unable to get initial program location"
getFirstProgramLocBM
:: PermCheckExtC ext extExpr
=> TypedBlock TransPhase ext blocks tops ret ctx
-> Maybe ProgramLoc
getFirstProgramLocBM block =
listToMaybe $ mapMaybe helper (_typedBlockEntries block)
where
helper
:: PermCheckExtC ext extExpr
=> Some (TypedEntry TransPhase ext blocks tops ret ctx)
-> Maybe ProgramLoc
helper ste = case ste of
Some TypedEntry { typedEntryBody = stmts } ->
Just $ mbLiftNamed $ fmap getFirstProgramLocTS stmts
| From the sequence , get the first program location we encounter , which
-- should correspond to the permissions for the entry point we want to log
getFirstProgramLocTS :: PermCheckExtC ext extExpr
=> TypedStmtSeq ext blocks tops ret ctx
-> ProgramLoc
getFirstProgramLocTS (TypedImplStmt (AnnotPermImpl _ pis)) =
getFirstProgramLocPI pis
getFirstProgramLocTS (TypedConsStmt loc _ _ _) = loc
getFirstProgramLocTS (TypedTermStmt loc _) = loc
getFirstProgramLocPI
:: PermCheckExtC ext extExpr
=> PermImpl (TypedStmtSeq ext blocks tops ret) ctx
-> ProgramLoc
getFirstProgramLocPI (PermImpl_Done stmts) = getFirstProgramLocTS stmts
getFirstProgramLocPI (PermImpl_Step _ mbps) = getFirstProgramLocMBPI mbps
getFirstProgramLocMBPI
:: PermCheckExtC ext extExpr
=> MbPermImpls (TypedStmtSeq ext blocks tops ret) ctx
-> ProgramLoc
getFirstProgramLocMBPI MbPermImpls_Nil =
error "Error finding program location for IDE log"
getFirstProgramLocMBPI (MbPermImpls_Cons _ _ pis) =
mbLift $ fmap getFirstProgramLocPI pis
| Print a ` ProgramLoc ` in a way that is useful for an IDE , i.e. , machine
-- readable
ppLoc :: ProgramLoc -> (String, String)
ppLoc pl =
let fnName = T.unpack $ functionName $ plFunction pl
locStr = ppPos $ plSourceLoc pl
ppPos (SourcePos file line column) =
T.unpack file <> ":" <> show line <> ":" <> show column
ppPos (BinaryPos _ _) = "<unknown binary pos>"
ppPos (OtherPos _) = "<unknown other pos>"
ppPos InternalPos = "<unknown internal pos>"
in (fnName, locStr)
| null | https://raw.githubusercontent.com/GaloisInc/saw-script/9d66afc87e2afe70fbea40033f7f887c6a02558a/heapster-saw/src/Verifier/SAW/Heapster/IDESupport.hs | haskell | # LANGUAGE GADTs #
consumption.
| A single entry in the IDE info dump log. At a bare minimum, this must
include a location and corresponding permission. Once the basics are
working, we can enrich the information we log.
| A complete IDE info dump log, which is just a sequence of entries. Once
the basics are working, we can enrich the information we log.
The error message is available further up the stack, so we just leave it
should correspond to the permissions for the entry point we want to log
readable | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE KindSignatures #
# LANGUAGE LambdaCase #
# LANGUAGE QuasiQuotes #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeOperators #
# LANGUAGE UndecidableInstances #
# LANGUAGE ViewPatterns #
# LANGUAGE PolyKinds #
module Verifier.SAW.Heapster.IDESupport where
import Control.Monad.Reader
( MonadReader (ask, local),
ReaderT (..),
)
import Data.Aeson (ToJSON, Value, encodeFile)
import Data.Binding.Hobbits
( Liftable (..),
Mb,
NuMatching (..),
RList,
mbMatch,
nuMP,
nuMultiWithElim1,
unsafeMbTypeRepr,
Name,
)
import Data.Maybe (catMaybes, listToMaybe, mapMaybe)
import Data.Parameterized.Some (Some (..))
import qualified Data.Text as T
import qualified Data.Type.RList as RL
import GHC.Generics (Generic)
import Lang.Crucible.FunctionHandle
import Lang.Crucible.Types (CrucibleType)
import What4.FunctionName (FunctionName (functionName))
import What4.ProgramLoc
( Position (BinaryPos, InternalPos, OtherPos, SourcePos),
ProgramLoc (..),
)
import Verifier.SAW.Heapster.CruUtil
import Verifier.SAW.Heapster.Permissions
import Verifier.SAW.Heapster.Implication
import Verifier.SAW.Heapster.TypedCrucible
import Verifier.SAW.Heapster.SAWTranslation (SomeTypedCFG (..))
import Verifier.SAW.Heapster.JSONExport(ppToJson)
import Data.Type.RList (mapRAssign)
import Data.Functor.Constant
import Control.Monad.Writer
import Data.Binding.Hobbits.NameMap (NameMap)
import qualified Data.Binding.Hobbits.NameMap as NameMap
import Verifier.SAW.Heapster.NamedMb
| The entry point for dumping a environment to a file for IDE
printIDEInfo :: PermEnv -> [Some SomeTypedCFG] -> FilePath -> PPInfo -> IO ()
printIDEInfo _penv tcfgs file ppinfo =
encodeFile file $ IDELog (runWithLoc ppinfo tcfgs)
type ExtractionM = ReaderT (PPInfo, ProgramLoc, String) (Writer [LogEntry])
emit :: LogEntry -> ExtractionM ()
emit entry = tell [entry]
gather :: ExtractionM () -> ExtractionM [LogEntry]
gather m = snd <$> listen m
data LogEntry
= LogEntry
{ leLocation :: String
, leEntryId :: LogEntryID
, leCallers :: [LogEntryID]
, leFunctionName :: String
, lePermissions :: [(String, String, Value)]
}
| LogError
{ lerrLocation :: String
, lerrError :: String
, lerrFunctionName :: String
}
| LogImpl
{ limplLocation :: String
, limplExport :: Value
, limplFunctionName :: String
}
deriving (Generic, Show)
instance ToJSON LogEntry
instance NuMatching LogEntry where
nuMatchingProof = unsafeMbTypeRepr
instance Liftable LogEntry where
mbLift mb = case mbMatch mb of
[nuMP| LogEntry v w x y z |] ->
LogEntry (mbLift v) (mbLift w) (mbLift x) (mbLift y) (mbLift z)
[nuMP| LogError x y z |] ->
LogError (mbLift x) (mbLift y) (mbLift z)
[nuMP| LogImpl x y z |] ->
LogImpl (mbLift x) (mbLift y) (mbLift z)
data LogEntryID = LogEntryID
{ leIdBlock :: Int
, leIdHeapster :: Int
}
deriving (Generic, Show)
instance ToJSON LogEntryID
instance NuMatching LogEntryID where
nuMatchingProof = unsafeMbTypeRepr
instance Liftable LogEntryID where
mbLift mb = case mbMatch mb of
[nuMP| LogEntryID x y |] -> LogEntryID (mbLift x) (mbLift y)
newtype IDELog = IDELog {
lmfEntries :: [LogEntry]
} deriving (Generic, Show)
instance ToJSON IDELog
class ExtractLogEntries a where
extractLogEntries :: a -> ExtractionM ()
instance (PermCheckExtC ext extExpr)
=> ExtractLogEntries
(TypedEntry TransPhase ext blocks tops ret args ghosts) where
extractLogEntries te = do
let loc = mbLiftNamed $ fmap getFirstProgramLocTS (typedEntryBody te)
withLoc loc (mb'ExtractLogEntries (typedEntryBody te))
let entryId = mkLogEntryID $ typedEntryID te
let callers = callerIDs $ typedEntryCallers te
(ppi, _, fname) <- ask
let loc' = snd (ppLoc loc)
let debugNames = _mbNames (typedEntryBody te)
let insertNames ::
RL.RAssign Name (x :: RList CrucibleType) ->
RL.RAssign StringF x ->
NameMap (StringF :: CrucibleType -> *)->
NameMap (StringF :: CrucibleType -> *)
insertNames RL.MNil RL.MNil m = m
insertNames (ns RL.:>: n) (xs RL.:>: StringF name) m =
insertNames ns xs (NameMap.insert n (StringF name) m)
inputs = mbLift
$ flip nuMultiWithElim1 (typedEntryPermsIn te)
$ \ns body ->
let ppi' = ppi { ppExprNames = insertNames ns debugNames (ppExprNames ppi) }
f ::
(Pair StringF ValuePerm) x ->
Constant (String, String, Value) x
f (Pair (StringF name) vp) = Constant (name, permPrettyString ppi' vp, ppToJson ppi' vp)
in RL.toList (mapRAssign f (zipRAssign debugNames body))
tell [LogEntry loc' entryId callers fname inputs]
mkLogEntryID :: TypedEntryID blocks args -> LogEntryID
mkLogEntryID = uncurry LogEntryID . entryIDIndices
callerIDs :: [Some (TypedCallSite phase blocks tops args ghosts)] -> [LogEntryID]
callerIDs = map $ \(Some tcs) -> case typedCallSiteID tcs of
TypedCallSiteID tei _ _ _ -> mkLogEntryID tei
data Pair f g x = Pair (f x) (g x)
zipRAssign :: RL.RAssign f x -> RL.RAssign g x -> RL.RAssign (Pair f g) x
zipRAssign RL.MNil RL.MNil = RL.MNil
zipRAssign (xs RL.:>: x) (ys RL.:>: y) = zipRAssign xs ys RL.:>: Pair x y
instance ExtractLogEntries (TypedStmtSeq ext blocks tops ret ps_in) where
extractLogEntries (TypedImplStmt (AnnotPermImpl _str pimpl)) =
fmap ( setErrorMsg str ) < $ > extractLogEntries pimpl
extractLogEntries pimpl
extractLogEntries (TypedConsStmt loc _ _ rest) = do
withLoc loc $ mb'ExtractLogEntries rest
extractLogEntries (TypedTermStmt _ _) = pure ()
instance ExtractLogEntries
(PermImpl (TypedStmtSeq ext blocks tops ret) ps_in) where
extractLogEntries (PermImpl_Step pi1 mbpis) = do
pi1Entries <- extractLogEntries pi1
pisEntries <- extractLogEntries mbpis
return $ pi1Entries <> pisEntries
extractLogEntries (PermImpl_Done stmts) = extractLogEntries stmts
instance ExtractLogEntries (PermImpl1 ps_in ps_outs) where
extractLogEntries (Impl1_Fail err) =
do (_, loc, fname) <- ask
emit (LogError (snd (ppLoc loc)) (ppError err) fname)
extractLogEntries impl =
do (ppi, loc, fname) <- ask
emit (LogImpl (snd (ppLoc loc)) (ppToJson ppi impl) fname)
instance ExtractLogEntries
(MbPermImpls (TypedStmtSeq ext blocks tops ret) ps_outs) where
extractLogEntries (MbPermImpls_Cons ctx mbpis pis) = do
mbExtractLogEntries ctx pis
extractLogEntries mbpis
extractLogEntries MbPermImpls_Nil = pure ()
instance (PermCheckExtC ext extExpr)
=> ExtractLogEntries (TypedCFG ext blocks ghosts inits gouts ret) where
extractLogEntries tcfg = extractLogEntries $ tpcfgBlockMap tcfg
instance (PermCheckExtC ext extExpr)
=> ExtractLogEntries (TypedBlockMap TransPhase ext blocks tops ret) where
extractLogEntries tbm =
sequence_ $ RL.mapToList extractLogEntries tbm
instance (PermCheckExtC ext extExpr)
=> ExtractLogEntries (TypedBlock TransPhase ext blocks tops ret args) where
extractLogEntries tb =
mapM_ (\(Some te) -> extractLogEntries te) $ _typedBlockEntries tb
mbExtractLogEntries
:: ExtractLogEntries a => CruCtx ctx -> Mb (ctx :: RList CrucibleType) a -> ExtractionM ()
mbExtractLogEntries ctx mb_a =
ReaderT $ \(ppi, loc, fname) ->
tell $ mbLift $ flip nuMultiWithElim1 mb_a $ \ns x ->
let ppi' = ppInfoAddTypedExprNames ctx ns ppi in
execWriter $ runReaderT (extractLogEntries x) (ppi', loc, fname)
mb'ExtractLogEntries
:: ExtractLogEntries a => NamedMb (ctx :: RList CrucibleType) a -> ExtractionM ()
mb'ExtractLogEntries mb_a =
ReaderT $ \(ppi, loc, fname) ->
tell $ mbLift $ flip nuMultiWithElim1 (_mbBinding mb_a) $ \ns x ->
let ppi' = ppInfoApplyAllocation ns (_mbNames mb_a) ppi in
execWriter $ runReaderT (extractLogEntries x) (ppi', loc, fname)
typedStmtOutCtx :: TypedStmt ext rets ps_in ps_next -> CruCtx rets
typedStmtOutCtx = error "FIXME: write typedStmtOutCtx"
withLoc :: ProgramLoc -> ExtractionM a -> ExtractionM a
withLoc loc = local (\(ppinfo, _, fname) -> (ppinfo, loc, fname))
setErrorMsg :: String -> LogEntry -> LogEntry
setErrorMsg msg le@LogError {} = le { lerrError = msg }
setErrorMsg msg le@LogImpl {} =
LogError { lerrError = msg
, lerrLocation = limplLocation le
, lerrFunctionName = limplFunctionName le}
setErrorMsg msg le@LogEntry {} =
LogError { lerrError = msg
, lerrLocation = leLocation le
, lerrFunctionName = leFunctionName le
}
runWithLoc :: PPInfo -> [Some SomeTypedCFG] -> [LogEntry]
runWithLoc ppi =
concatMap (runWithLocHelper ppi)
where
runWithLocHelper :: PPInfo -> Some SomeTypedCFG -> [LogEntry]
runWithLocHelper ppi' sstcfg = case sstcfg of
Some (SomeTypedCFG _ _ tcfg) -> do
let env = (ppi', getFirstProgramLoc tcfg, getFunctionName tcfg)
execWriter (runReaderT (extractLogEntries tcfg) env)
getFunctionName :: TypedCFG ext blocks ghosts inits gouts ret -> String
getFunctionName tcfg = case tpcfgHandle tcfg of
TypedFnHandle _ _ handle -> show $ handleName handle
getFirstProgramLoc
:: PermCheckExtC ext extExpr
=> TypedCFG ext blocks ghosts inits gouts ret -> ProgramLoc
getFirstProgramLoc tcfg =
case listToMaybe $ catMaybes $
RL.mapToList getFirstProgramLocBM $ tpcfgBlockMap tcfg of
Just pl -> pl
_ -> error "Unable to get initial program location"
getFirstProgramLocBM
:: PermCheckExtC ext extExpr
=> TypedBlock TransPhase ext blocks tops ret ctx
-> Maybe ProgramLoc
getFirstProgramLocBM block =
listToMaybe $ mapMaybe helper (_typedBlockEntries block)
where
helper
:: PermCheckExtC ext extExpr
=> Some (TypedEntry TransPhase ext blocks tops ret ctx)
-> Maybe ProgramLoc
helper ste = case ste of
Some TypedEntry { typedEntryBody = stmts } ->
Just $ mbLiftNamed $ fmap getFirstProgramLocTS stmts
| From the sequence , get the first program location we encounter , which
getFirstProgramLocTS :: PermCheckExtC ext extExpr
=> TypedStmtSeq ext blocks tops ret ctx
-> ProgramLoc
getFirstProgramLocTS (TypedImplStmt (AnnotPermImpl _ pis)) =
getFirstProgramLocPI pis
getFirstProgramLocTS (TypedConsStmt loc _ _ _) = loc
getFirstProgramLocTS (TypedTermStmt loc _) = loc
getFirstProgramLocPI
:: PermCheckExtC ext extExpr
=> PermImpl (TypedStmtSeq ext blocks tops ret) ctx
-> ProgramLoc
getFirstProgramLocPI (PermImpl_Done stmts) = getFirstProgramLocTS stmts
getFirstProgramLocPI (PermImpl_Step _ mbps) = getFirstProgramLocMBPI mbps
getFirstProgramLocMBPI
:: PermCheckExtC ext extExpr
=> MbPermImpls (TypedStmtSeq ext blocks tops ret) ctx
-> ProgramLoc
getFirstProgramLocMBPI MbPermImpls_Nil =
error "Error finding program location for IDE log"
getFirstProgramLocMBPI (MbPermImpls_Cons _ _ pis) =
mbLift $ fmap getFirstProgramLocPI pis
| Print a ` ProgramLoc ` in a way that is useful for an IDE , i.e. , machine
ppLoc :: ProgramLoc -> (String, String)
ppLoc pl =
let fnName = T.unpack $ functionName $ plFunction pl
locStr = ppPos $ plSourceLoc pl
ppPos (SourcePos file line column) =
T.unpack file <> ":" <> show line <> ":" <> show column
ppPos (BinaryPos _ _) = "<unknown binary pos>"
ppPos (OtherPos _) = "<unknown other pos>"
ppPos InternalPos = "<unknown internal pos>"
in (fnName, locStr)
|
43d3a7062771b8ace1bf8caf99cf69e5c8477df852519b070fb6f230f39af7f0 | evdubs/renegade-way | price-analysis.rkt | #lang racket/base
(require gregor
math/statistics
racket/list
racket/string
racket/vector
"db-queries.rkt"
"structs.rkt"
"technical-indicators.rkt"
"pattern/ascending-triangle.rkt"
"pattern/bull-pullback.rkt"
"pattern/bear-rally.rkt"
"pattern/descending-triangle.rkt"
"pattern/high-base.rkt"
"pattern/low-base.rkt"
"pattern/range-rally.rkt"
"pattern/range-pullback.rkt")
(provide price-analysis-hash
price-analysis-list
run-price-analysis
test-hash)
(define (vector-first v)
(vector-ref v 0))
(define (vector-last v)
(vector-ref v (- (vector-length v) 1)))
;; Rating for market/sector/industry
;; Looks at price relative to moving averages
Scales from -3 to 3
(define (msi-rating symbol end-date-str)
(let* ([end-date (iso8601->date end-date-str)]
[start-date (-months end-date 15)]
[dohlc (list->vector (get-date-ohlc symbol (date->iso8601 start-date) (date->iso8601 end-date)))]
[sma-20 (simple-moving-average dohlc 20)]
[sma-50 (simple-moving-average dohlc 50)]
[sma-20-distance (* 1/2 (statistics-stddev
(foldl (λ (d s r)
(update-statistics r (/ (dohlc-close d) (dv-value s))))
empty-statistics
(vector->list (vector-drop dohlc (- (vector-length dohlc)
(vector-length sma-20))))
(vector->list sma-20))))]
[sma-50-distance (* 1/2 (statistics-stddev
(foldl (λ (d s r)
(update-statistics r (/ (dohlc-close d) (dv-value s))))
empty-statistics
(vector->list (vector-drop dohlc (- (vector-length dohlc)
(vector-length sma-50))))
(vector->list sma-50))))])
(+ (cond [(> (/ (dohlc-close (vector-last dohlc)) (dv-value (vector-last sma-20)))
(+ 1 sma-20-distance)) 1]
[(< (/ (dohlc-close (vector-last dohlc)) (dv-value (vector-last sma-20)))
(- 1 sma-20-distance)) -1]
[else 0])
(cond [(> (/ (dohlc-close (vector-last dohlc)) (dv-value (vector-last sma-50)))
(+ 1 sma-50-distance)) 1]
[(< (/ (dohlc-close (vector-last dohlc)) (dv-value (vector-last sma-50)))
(- 1 sma-50-distance)) -1]
[else 0])
(cond [(> (dv-value (vector-ref sma-20 (- (vector-length sma-20) 2)))
(dv-value (vector-ref sma-20 (- (vector-length sma-20) 1)))) -1/2]
[else 1/2])
(cond [(> (dv-value (vector-ref sma-50 (- (vector-length sma-50) 2)))
(dv-value (vector-ref sma-50 (- (vector-length sma-50) 1)))) -1/2]
[else 1/2]))))
(define (stock-patterns symbol start-date end-date)
(let* ([dohlc-list (get-date-ohlc symbol start-date end-date)])
(if (< (length dohlc-list) 60) ""
(string-join (filter (λ (p) (not (equal? "" p)))
(map (λ (p)
(define tests (filter (λ (t) (<= (dohlc-date (list-ref dohlc-list (- (length dohlc-list) 2))) (dv-date t)))
(history-test ((second p) dohlc-list))))
(cond [(not (empty? tests))
(hash-set! test-hash symbol (dv-value (last tests)))
(first p)]
[else ""]))
(list (list "AT" ascending-triangle-entry)
(list "BP" bull-pullback-entry)
(list "BR" bear-rally-entry)
(list "DT" descending-triangle-entry)
(list "HB" high-base-entry)
(list "LB" low-base-entry)
(list "RR" range-rally-entry)
(list "RP" range-pullback-entry))))
" "))))
(define price-analysis-list (list))
(define price-analysis-hash (make-hash))
(define test-hash (make-hash))
(define (run-price-analysis market sector start-date end-date)
(let ([new-price-analysis-list (get-price-analysis market sector start-date end-date)]
[new-price-analysis-hash (make-hash)])
; this lets us avoid calling (msi-rating) with an empty symbol
(hash-set! new-price-analysis-hash "" 0)
(for-each (λ (pa)
(cond [(not (hash-has-key? new-price-analysis-hash (price-analysis-market pa)))
(hash-set! new-price-analysis-hash (price-analysis-market pa) (msi-rating (price-analysis-market pa) end-date))])
(cond [(not (hash-has-key? new-price-analysis-hash (price-analysis-sector pa)))
(hash-set! new-price-analysis-hash (price-analysis-sector pa) (msi-rating (price-analysis-sector pa) end-date))])
(cond [(not (hash-has-key? new-price-analysis-hash (price-analysis-industry pa)))
(hash-set! new-price-analysis-hash (price-analysis-industry pa) (msi-rating (price-analysis-industry pa) end-date))])
(hash-set! new-price-analysis-hash (price-analysis-stock pa) (stock-patterns (price-analysis-stock pa) start-date end-date)))
new-price-analysis-list)
(set! price-analysis-list new-price-analysis-list)
(set! price-analysis-hash new-price-analysis-hash)))
| null | https://raw.githubusercontent.com/evdubs/renegade-way/c4d7af2d33f2f628a93794064c41d37a2a7e8231/price-analysis.rkt | racket | Rating for market/sector/industry
Looks at price relative to moving averages
this lets us avoid calling (msi-rating) with an empty symbol | #lang racket/base
(require gregor
math/statistics
racket/list
racket/string
racket/vector
"db-queries.rkt"
"structs.rkt"
"technical-indicators.rkt"
"pattern/ascending-triangle.rkt"
"pattern/bull-pullback.rkt"
"pattern/bear-rally.rkt"
"pattern/descending-triangle.rkt"
"pattern/high-base.rkt"
"pattern/low-base.rkt"
"pattern/range-rally.rkt"
"pattern/range-pullback.rkt")
(provide price-analysis-hash
price-analysis-list
run-price-analysis
test-hash)
(define (vector-first v)
(vector-ref v 0))
(define (vector-last v)
(vector-ref v (- (vector-length v) 1)))
Scales from -3 to 3
(define (msi-rating symbol end-date-str)
(let* ([end-date (iso8601->date end-date-str)]
[start-date (-months end-date 15)]
[dohlc (list->vector (get-date-ohlc symbol (date->iso8601 start-date) (date->iso8601 end-date)))]
[sma-20 (simple-moving-average dohlc 20)]
[sma-50 (simple-moving-average dohlc 50)]
[sma-20-distance (* 1/2 (statistics-stddev
(foldl (λ (d s r)
(update-statistics r (/ (dohlc-close d) (dv-value s))))
empty-statistics
(vector->list (vector-drop dohlc (- (vector-length dohlc)
(vector-length sma-20))))
(vector->list sma-20))))]
[sma-50-distance (* 1/2 (statistics-stddev
(foldl (λ (d s r)
(update-statistics r (/ (dohlc-close d) (dv-value s))))
empty-statistics
(vector->list (vector-drop dohlc (- (vector-length dohlc)
(vector-length sma-50))))
(vector->list sma-50))))])
(+ (cond [(> (/ (dohlc-close (vector-last dohlc)) (dv-value (vector-last sma-20)))
(+ 1 sma-20-distance)) 1]
[(< (/ (dohlc-close (vector-last dohlc)) (dv-value (vector-last sma-20)))
(- 1 sma-20-distance)) -1]
[else 0])
(cond [(> (/ (dohlc-close (vector-last dohlc)) (dv-value (vector-last sma-50)))
(+ 1 sma-50-distance)) 1]
[(< (/ (dohlc-close (vector-last dohlc)) (dv-value (vector-last sma-50)))
(- 1 sma-50-distance)) -1]
[else 0])
(cond [(> (dv-value (vector-ref sma-20 (- (vector-length sma-20) 2)))
(dv-value (vector-ref sma-20 (- (vector-length sma-20) 1)))) -1/2]
[else 1/2])
(cond [(> (dv-value (vector-ref sma-50 (- (vector-length sma-50) 2)))
(dv-value (vector-ref sma-50 (- (vector-length sma-50) 1)))) -1/2]
[else 1/2]))))
(define (stock-patterns symbol start-date end-date)
(let* ([dohlc-list (get-date-ohlc symbol start-date end-date)])
(if (< (length dohlc-list) 60) ""
(string-join (filter (λ (p) (not (equal? "" p)))
(map (λ (p)
(define tests (filter (λ (t) (<= (dohlc-date (list-ref dohlc-list (- (length dohlc-list) 2))) (dv-date t)))
(history-test ((second p) dohlc-list))))
(cond [(not (empty? tests))
(hash-set! test-hash symbol (dv-value (last tests)))
(first p)]
[else ""]))
(list (list "AT" ascending-triangle-entry)
(list "BP" bull-pullback-entry)
(list "BR" bear-rally-entry)
(list "DT" descending-triangle-entry)
(list "HB" high-base-entry)
(list "LB" low-base-entry)
(list "RR" range-rally-entry)
(list "RP" range-pullback-entry))))
" "))))
(define price-analysis-list (list))
(define price-analysis-hash (make-hash))
(define test-hash (make-hash))
(define (run-price-analysis market sector start-date end-date)
(let ([new-price-analysis-list (get-price-analysis market sector start-date end-date)]
[new-price-analysis-hash (make-hash)])
(hash-set! new-price-analysis-hash "" 0)
(for-each (λ (pa)
(cond [(not (hash-has-key? new-price-analysis-hash (price-analysis-market pa)))
(hash-set! new-price-analysis-hash (price-analysis-market pa) (msi-rating (price-analysis-market pa) end-date))])
(cond [(not (hash-has-key? new-price-analysis-hash (price-analysis-sector pa)))
(hash-set! new-price-analysis-hash (price-analysis-sector pa) (msi-rating (price-analysis-sector pa) end-date))])
(cond [(not (hash-has-key? new-price-analysis-hash (price-analysis-industry pa)))
(hash-set! new-price-analysis-hash (price-analysis-industry pa) (msi-rating (price-analysis-industry pa) end-date))])
(hash-set! new-price-analysis-hash (price-analysis-stock pa) (stock-patterns (price-analysis-stock pa) start-date end-date)))
new-price-analysis-list)
(set! price-analysis-list new-price-analysis-list)
(set! price-analysis-hash new-price-analysis-hash)))
|
d120c9c54b5b8a7e0df8e932ee6893a6929cdafca460855754547c89b5bc4696 | well-typed/optics | Optics.hs | # LANGUAGE DataKinds #
# LANGUAGE PolyKinds #
| This module defines optics for working with the types in @generics - sop@.
--
module Generics.SOP.Optics
( rep
, sop
, nsSingleton
, _I
, _K
, productRep
, npHead
, npTail
, npSingleton
, _Z
, _S
)
where
import Generics.SOP
import Optics.Core hiding (to)
| between a generic type and its representation .
rep :: (Generic a, Generic b) => Iso a b (Rep a) (Rep b)
rep = iso from to
| induced by the ' SOP ' newtype .
sop :: Iso (SOP f xss) (SOP g yss) (NS (NP f) xss) (NS (NP g) yss)
sop = iso unSOP SOP
| between a one - element sum and its contents .
nsSingleton :: Iso (NS f '[ x ]) (NS g '[ y ]) (f x) (g y)
nsSingleton = iso unZ Z
| induced by the ' I ' newtype .
_I :: Iso (I x) (I y) x y
_I = iso unI I
| induced by the ' K ' newtype .
_K :: Iso (K a b) (K c d) a c
_K = iso unK K
| between a generic product type and its product representation .
productRep :: (IsProductType a xs, IsProductType b ys) => Iso a b (NP I xs) (NP I ys)
productRep = rep % sop % nsSingleton
| Lens accessing the head of an ' NP ' .
npHead :: Lens (NP f (x ': xs)) (NP f (y ': xs)) (f x) (f y)
npHead = lensVL (\ f (x :* xs) -> (:* xs) <$> f x)
| Lens accessing the tail of an ' NP ' .
npTail :: Lens (NP f (x ': xs)) (NP f (x ': ys)) (NP f xs) (NP f ys)
npTail = lensVL (\ f (x :* xs) -> (x :*) <$> f xs)
| between a single - element ' NP ' and its contents .
npSingleton :: Iso (NP f '[ x ]) (NP g '[ y ]) (f x) (g y)
npSingleton = iso hd (:* Nil)
| Prism for the first option in an ' NS ' .
_Z :: Prism (NS f (x ': xs)) (NS f (y ': xs)) (f x) (f y)
_Z = prism Z $ \ ns -> case ns of
Z x -> Right x
S y -> Left (S y)
| Prism for the other options in an ' NS ' .
_S :: Prism (NS f (x ': xs)) (NS f (x ': ys)) (NS f xs) (NS f ys)
_S = prism S $ \ ns -> case ns of
Z y -> Left (Z y)
S x -> Right x
| null | https://raw.githubusercontent.com/well-typed/optics/ba3c5a4d2f110c82238bc2fe7bb187023ab516f5/optics-sop/src/Generics/SOP/Optics.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE PolyKinds #
| This module defines optics for working with the types in @generics - sop@.
module Generics.SOP.Optics
( rep
, sop
, nsSingleton
, _I
, _K
, productRep
, npHead
, npTail
, npSingleton
, _Z
, _S
)
where
import Generics.SOP
import Optics.Core hiding (to)
| between a generic type and its representation .
rep :: (Generic a, Generic b) => Iso a b (Rep a) (Rep b)
rep = iso from to
| induced by the ' SOP ' newtype .
sop :: Iso (SOP f xss) (SOP g yss) (NS (NP f) xss) (NS (NP g) yss)
sop = iso unSOP SOP
| between a one - element sum and its contents .
nsSingleton :: Iso (NS f '[ x ]) (NS g '[ y ]) (f x) (g y)
nsSingleton = iso unZ Z
| induced by the ' I ' newtype .
_I :: Iso (I x) (I y) x y
_I = iso unI I
| induced by the ' K ' newtype .
_K :: Iso (K a b) (K c d) a c
_K = iso unK K
| between a generic product type and its product representation .
productRep :: (IsProductType a xs, IsProductType b ys) => Iso a b (NP I xs) (NP I ys)
productRep = rep % sop % nsSingleton
| Lens accessing the head of an ' NP ' .
npHead :: Lens (NP f (x ': xs)) (NP f (y ': xs)) (f x) (f y)
npHead = lensVL (\ f (x :* xs) -> (:* xs) <$> f x)
| Lens accessing the tail of an ' NP ' .
npTail :: Lens (NP f (x ': xs)) (NP f (x ': ys)) (NP f xs) (NP f ys)
npTail = lensVL (\ f (x :* xs) -> (x :*) <$> f xs)
| between a single - element ' NP ' and its contents .
npSingleton :: Iso (NP f '[ x ]) (NP g '[ y ]) (f x) (g y)
npSingleton = iso hd (:* Nil)
| Prism for the first option in an ' NS ' .
_Z :: Prism (NS f (x ': xs)) (NS f (y ': xs)) (f x) (f y)
_Z = prism Z $ \ ns -> case ns of
Z x -> Right x
S y -> Left (S y)
| Prism for the other options in an ' NS ' .
_S :: Prism (NS f (x ': xs)) (NS f (x ': ys)) (NS f xs) (NS f ys)
_S = prism S $ \ ns -> case ns of
Z y -> Left (Z y)
S x -> Right x
| |
8649eef3a5c090642dae0aa1ba41729ee705172b8be63c134cda213165f323c2 | OlafChitil/hat | List.hs | module Hat.List
(gelemIndex, aelemIndex, helemIndex, gelemIndices,
aelemIndices, helemIndices, gfind, afind, hfind,
gfindIndex, afindIndex, hfindIndex, gfindIndices,
afindIndices, hfindIndices, gnub, gnubBy, anubBy,
hnubBy, gdelete, gdeleteBy, adeleteBy, hdeleteBy,
(!\\), gdeleteFirstsBy, adeleteFirstsBy,
hdeleteFirstsBy, gunion, gunionBy, aunionBy,
hunionBy, gintersect, gintersectBy, aintersectBy,
hintersectBy, gintersperse, aintersperse,
hintersperse, gtranspose, atranspose, htranspose,
gpartition, apartition, hpartition, ggroup, ggroupBy,
agroupBy, hgroupBy, ginits, ainits, hinits, gtails,
atails, htails, gisPrefixOf, aisPrefixOf,
hisPrefixOf, gisSuffixOf, aisSuffixOf, hisSuffixOf,
gmapAccumL, amapAccumL, hmapAccumL, gmapAccumR,
amapAccumR, hmapAccumR, gsort, gsortBy, asortBy,
hsortBy, ginsert, ginsertBy, ainsertBy, hinsertBy,
gmaximumBy, amaximumBy, hmaximumBy, gminimumBy,
aminimumBy, hminimumBy, ggenericLength,
agenericLength, hgenericLength, ggenericTake,
agenericTake, hgenericTake, ggenericDrop,
agenericDrop, hgenericDrop, ggenericSplitAt,
agenericSplitAt, hgenericSplitAt, ggenericIndex,
agenericIndex, hgenericIndex, ggenericReplicate,
agenericReplicate, hgenericReplicate, gzip4, gzip5,
gzip6, gzip7, gzipWith4, azipWith4, hzipWith4,
gzipWith5, azipWith5, hzipWith5, gzipWith6,
azipWith6, hzipWith6, gzipWith7, azipWith7,
hzipWith7, gunzip4, gunzip5, gunzip6, gunzip7,
gunfoldr, aunfoldr, hunfoldr, gmap, amap, hmap,
(!++), (+++), (*++), gconcat, aconcat, hconcat,
gfilter, afilter, hfilter, ghead, ahead, hhead,
glast, alast, hlast, gtail, atail, htail, ginit,
ainit, hinit, gnull, anull, hnull, glength, alength,
hlength, (!!!), (+!!), (*!!), gfoldl, afoldl, hfoldl,
gfoldl1, afoldl1, hfoldl1, gscanl, ascanl, hscanl,
gscanl1, ascanl1, hscanl1, gfoldr, afoldr, hfoldr,
gfoldr1, afoldr1, hfoldr1, gscanr, ascanr, hscanr,
gscanr1, ascanr1, hscanr1, giterate, aiterate,
hiterate, grepeat, arepeat, hrepeat, greplicate,
areplicate, hreplicate, gcycle, acycle, hcycle,
gtake, atake, htake, gdrop, adrop, hdrop, gsplitAt,
asplitAt, hsplitAt, gtakeWhile, atakeWhile,
htakeWhile, gdropWhile, adropWhile, hdropWhile,
gspan, aspan, hspan, gbreak, abreak, hbreak, glines,
alines, hlines, gwords, awords, hwords, gunlines,
gunwords, aunwords, hunwords, greverse, gand, gor,
gany, aany, hany, gall, aall, hall, gelem, aelem,
helem, gnotElem, anotElem, hnotElem, glookup,
alookup, hlookup, gsum, gproduct, gmaximum, amaximum,
hmaximum, gminimum, aminimum, hminimum, gconcatMap,
aconcatMap, hconcatMap, gzip, gzip3, gzipWith,
azipWith, hzipWith, gzipWith3, azipWith3, hzipWith3,
gunzip, gunzip3)
where
import qualified Prelude
import qualified Hat.Hat as T
import qualified Hat.PreludeBasic
import qualified Hat.PreludeBuiltinTypes
import Hat.Prelude
import Hat.Maybe
(glistToMaybe, alistToMaybe, hlistToMaybe)
gelemIndex ::
(Eq a) =>
T.RefSrcPos ->
T.RefExp ->
T.R (T.Fun a (T.Fun (T.List a) (Maybe Int)))
helemIndex ::
(Eq a) =>
T.R a ->
T.RefExp -> T.R (T.Fun (T.List a) (Maybe Int))
gelemIndex pelemIndex p
= T.ufun1 aelemIndex pelemIndex p helemIndex
helemIndex fx p
= T.uwrapForward p
(hfindIndex
(T.uap1 T.mkNoSrcPos p ((!==) T.mkNoSrcPos p) fx)
p)
gelemIndices ::
(Eq a) =>
T.RefSrcPos ->
T.RefExp ->
T.R (T.Fun a (T.Fun (T.List a) (T.List Int)))
helemIndices ::
(Eq a) =>
T.R a ->
T.RefExp -> T.R (T.Fun (T.List a) (T.List Int))
gelemIndices pelemIndices p
= T.ufun1 aelemIndices pelemIndices p helemIndices
helemIndices fx p
= T.uap1 T.mkNoSrcPos p (gfindIndices T.mkNoSrcPos p)
(T.uap1 T.mkNoSrcPos p ((!==) T.mkNoSrcPos p) fx)
gfind ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.Fun a Bool) (T.Fun (T.List a) (Maybe a)))
hfind ::
T.R (T.Fun a Bool) ->
T.RefExp -> T.R (T.Fun (T.List a) (Maybe a))
gfind pfind p = T.ufun1 afind pfind p hfind
hfind fp p
= T.uap2 T.mkNoSrcPos p ((!.) T.mkNoSrcPos p)
(glistToMaybe T.mkNoSrcPos p)
(T.uap1 T.mkNoSrcPos p (gfilter T.mkNoSrcPos p) fp)
gfindIndex ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.Fun a Bool) (T.Fun (T.List a) (Maybe Int)))
hfindIndex ::
T.R (T.Fun a Bool) ->
T.RefExp -> T.R (T.Fun (T.List a) (Maybe Int))
gfindIndex pfindIndex p
= T.ufun1 afindIndex pfindIndex p hfindIndex
hfindIndex fp p
= T.uap2 T.mkNoSrcPos p ((!.) T.mkNoSrcPos p)
(glistToMaybe T.mkNoSrcPos p)
(T.uap1 T.mkNoSrcPos p (gfindIndices T.mkNoSrcPos p)
fp)
gfindIndices ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.Fun a Bool)
(T.Fun (T.List a) (T.List Int)))
hfindIndices ::
T.R (T.Fun a Bool) ->
T.R (T.List a) -> T.RefExp -> T.R (T.List Int)
gfindIndices pfindIndices p
= T.ufun2 afindIndices pfindIndices p hfindIndices
hfindIndices fp fxs p
= T.uap2 T.mkNoSrcPos p
((Hat.PreludeBasic.!>>=) T.mkNoSrcPos p)
(T.uap2 T.mkNoSrcPos p (gzip T.mkNoSrcPos p) fxs
(T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.genumFrom T.mkNoSrcPos p)
(T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.gfromInteger T.mkNoSrcPos p)
(T.conInteger T.mkNoSrcPos p (0)))))
(T.ufun1 T.mkDoLambda T.mkNoSrcPos p
(\ (T.R (T.Tuple2 fx fi) _) p ->
T.uap2 T.mkNoSrcPos p
((Hat.PreludeBasic.!>>) T.mkNoSrcPos p)
(T.uwrapForward p
(Hat.PreludeBasic.hguard
(T.uap1 T.mkNoSrcPos p fp fx)
p))
(T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.greturn T.mkNoSrcPos p)
fi)))
gnub ::
(Eq a) =>
T.RefSrcPos ->
T.RefExp -> T.R (T.Fun (T.List a) (T.List a))
snub :: (Eq a) => T.R (T.Fun (T.List a) (T.List a))
gnub pnub p = T.uconstUse pnub p snub
snub
= T.uconstDef p anub
(\ p ->
T.uap1 T.mkNoSrcPos p (gnubBy T.mkNoSrcPos p)
((!==) T.mkNoSrcPos p))
gnubBy ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.Fun a (T.Fun a Bool))
(T.Fun (T.List a) (T.List a)))
hnubBy ::
T.R (T.Fun a (T.Fun a Bool)) ->
T.R (T.List a) -> T.RefExp -> T.R (T.List a)
gnubBy pnubBy p = T.ufun2 anubBy pnubBy p hnubBy
hnubBy feq (T.R T.Nil _) p
= T.con0 T.mkNoSrcPos p T.Nil T.aNil
hnubBy feq (T.R (T.Cons fx fxs) _) p
= T.con2 T.mkNoSrcPos p T.Cons T.aCons fx
(T.uwrapForward p
(hnubBy feq
(T.uwrapForward p
(hfilter
(T.ufun1 T.mkLambda T.mkNoSrcPos p
(\ fy p ->
T.uwrapForward p
(hnot (T.uap2 T.mkNoSrcPos p feq fx fy) p)))
fxs
p))
p))
hnubBy _ _ p = T.fatal p
gdelete ::
(Eq a) =>
T.RefSrcPos ->
T.RefExp ->
T.R (T.Fun a (T.Fun (T.List a) (T.List a)))
sdelete ::
(Eq a) => T.R (T.Fun a (T.Fun (T.List a) (T.List a)))
gdelete pdelete p = T.uconstUse pdelete p sdelete
sdelete
= T.uconstDef p adelete
(\ p ->
T.uap1 T.mkNoSrcPos p (gdeleteBy T.mkNoSrcPos p)
((!==) T.mkNoSrcPos p))
gdeleteBy ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.Fun a (T.Fun a Bool))
(T.Fun a (T.Fun (T.List a) (T.List a))))
hdeleteBy ::
T.R (T.Fun a (T.Fun a Bool)) ->
T.R a -> T.R (T.List a) -> T.RefExp -> T.R (T.List a)
gdeleteBy pdeleteBy p
= T.ufun3 adeleteBy pdeleteBy p hdeleteBy
hdeleteBy feq fx (T.R T.Nil _) p
= T.con0 T.mkNoSrcPos p T.Nil T.aNil
hdeleteBy feq fx (T.R (T.Cons fy fys) _) p
= T.ucif p (T.uap2 T.mkNoSrcPos p feq fx fy)
(T.projection T.mkNoSrcPos p fys)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fy
(T.uwrapForward p (hdeleteBy feq fx fys p)))
hdeleteBy _ _ _ p = T.fatal p
(!\\) ::
(Eq a) =>
T.RefSrcPos ->
T.RefExp ->
T.R (T.Fun (T.List a) (T.Fun (T.List a) (T.List a)))
(|\\) ::
(Eq a) =>
T.R (T.Fun (T.List a) (T.Fun (T.List a) (T.List a)))
(%\\) !\\ p = T.uconstUse (%\\) p (|\\)
(|\\)
= T.uconstDef p (+\\)
(\ p ->
T.uap1 T.mkNoSrcPos p (gfoldl T.mkNoSrcPos p)
(T.uap1 T.mkNoSrcPos p (gflip T.mkNoSrcPos p)
(gdelete T.mkNoSrcPos p)))
gdeleteFirstsBy ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.Fun a (T.Fun a Bool))
(T.Fun (T.List a) (T.Fun (T.List a) (T.List a))))
hdeleteFirstsBy ::
T.R (T.Fun a (T.Fun a Bool)) ->
T.RefExp ->
T.R (T.Fun (T.List a) (T.Fun (T.List a) (T.List a)))
gdeleteFirstsBy pdeleteFirstsBy p
= T.ufun1 adeleteFirstsBy pdeleteFirstsBy p
hdeleteFirstsBy
hdeleteFirstsBy feq p
= T.uap1 T.mkNoSrcPos p (gfoldl T.mkNoSrcPos p)
(T.uap1 T.mkNoSrcPos p (gflip T.mkNoSrcPos p)
(T.uap1 T.mkNoSrcPos p (gdeleteBy T.mkNoSrcPos p)
feq))
gunion ::
(Eq a) =>
T.RefSrcPos ->
T.RefExp ->
T.R (T.Fun (T.List a) (T.Fun (T.List a) (T.List a)))
sunion ::
(Eq a) =>
T.R (T.Fun (T.List a) (T.Fun (T.List a) (T.List a)))
gunion punion p = T.uconstUse punion p sunion
sunion
= T.uconstDef p aunion
(\ p ->
T.uap1 T.mkNoSrcPos p (gunionBy T.mkNoSrcPos p)
((!==) T.mkNoSrcPos p))
gunionBy ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.Fun a (T.Fun a Bool))
(T.Fun (T.List a) (T.Fun (T.List a) (T.List a))))
hunionBy ::
T.R (T.Fun a (T.Fun a Bool)) ->
T.R (T.List a) ->
T.R (T.List a) -> T.RefExp -> T.R (T.List a)
gunionBy punionBy p
= T.ufun3 aunionBy punionBy p hunionBy
hunionBy feq fxs fys p
= T.uwrapForward p
((*++) fxs
(T.uap2 T.mkNoSrcPos p
(T.uwrapForward p (hdeleteFirstsBy feq p))
(T.uwrapForward p (hnubBy feq fys p))
fxs)
p)
gintersect ::
(Eq a) =>
T.RefSrcPos ->
T.RefExp ->
T.R (T.Fun (T.List a) (T.Fun (T.List a) (T.List a)))
sintersect ::
(Eq a) =>
T.R (T.Fun (T.List a) (T.Fun (T.List a) (T.List a)))
gintersect pintersect p
= T.uconstUse pintersect p sintersect
sintersect
= T.uconstDef p aintersect
(\ p ->
T.uap1 T.mkNoSrcPos p (gintersectBy T.mkNoSrcPos p)
((!==) T.mkNoSrcPos p))
gintersectBy ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.Fun a (T.Fun a Bool))
(T.Fun (T.List a) (T.Fun (T.List a) (T.List a))))
hintersectBy ::
T.R (T.Fun a (T.Fun a Bool)) ->
T.R (T.List a) ->
T.R (T.List a) -> T.RefExp -> T.R (T.List a)
gintersectBy pintersectBy p
= T.ufun3 aintersectBy pintersectBy p hintersectBy
hintersectBy feq fxs fys p
= T.uap2 T.mkNoSrcPos p
((Hat.PreludeBasic.!>>=) T.mkNoSrcPos p)
fxs
(T.ufun1 T.mkDoLambda T.mkNoSrcPos p
(\ fx p ->
T.uap2 T.mkNoSrcPos p
((Hat.PreludeBasic.!>>) T.mkNoSrcPos p)
(T.uwrapForward p
(Hat.PreludeBasic.hguard
(T.uap1 T.mkNoSrcPos p
(T.uwrapForward p
(hany (T.uap1 T.mkNoSrcPos p feq fx) p))
fys)
p))
(T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.greturn T.mkNoSrcPos p)
fx)))
gintersperse ::
T.RefSrcPos ->
T.RefExp ->
T.R (T.Fun a (T.Fun (T.List a) (T.List a)))
hintersperse ::
T.R a -> T.R (T.List a) -> T.RefExp -> T.R (T.List a)
gintersperse pintersperse p
= T.ufun2 aintersperse pintersperse p hintersperse
hintersperse fsep (T.R T.Nil _) p
= T.con0 T.mkNoSrcPos p T.Nil T.aNil
hintersperse fsep (T.R (T.Cons fx (T.R T.Nil _)) _) p
= T.fromExpList T.mkNoSrcPos p [fx]
hintersperse fsep (T.R (T.Cons fx fxs) _) p
= T.con2 T.mkNoSrcPos p T.Cons T.aCons fx
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fsep
(T.uwrapForward p (hintersperse fsep fxs p)))
hintersperse _ _ p = T.fatal p
gtranspose ::
T.RefSrcPos ->
T.RefExp ->
T.R (T.Fun (T.List (T.List a)) (T.List (T.List a)))
htranspose ::
T.R (T.List (T.List a)) ->
T.RefExp -> T.R (T.List (T.List a))
gtranspose ptranspose p
= T.ufun1 atranspose ptranspose p htranspose
htranspose (T.R T.Nil _) p
= T.con0 T.mkNoSrcPos p T.Nil T.aNil
htranspose (T.R (T.Cons (T.R T.Nil _) fxss) _) p
= T.uwrapForward p (htranspose fxss p)
htranspose
(T.R (T.Cons (T.R (T.Cons fx fxs) _) fxss) _) p
= T.con2 T.mkNoSrcPos p T.Cons T.aCons
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fx
(T.uap2 T.mkNoSrcPos p
((Hat.PreludeBasic.!>>=) T.mkNoSrcPos p)
fxss
(T.ufun1 T.mkDoLambda T.mkNoSrcPos p
(\ fv93v38v93v45v1 p ->
T.uccase T.mkNoSrcPos p
(let v93v38v93v45v1 (T.R (T.Cons fh ft) _) p
= T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.greturn T.mkNoSrcPos p)
fh
v93v38v93v45v1 _ p
= T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.gfail T.mkNoSrcPos p)
(T.fromLitString T.mkNoSrcPos p
"pattern-match failure in do-expression")
in v93v38v93v45v1)
fv93v38v93v45v1))))
(T.uwrapForward p
(htranspose
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fxs
(T.uap2 T.mkNoSrcPos p
((Hat.PreludeBasic.!>>=) T.mkNoSrcPos p)
fxss
(T.ufun1 T.mkDoLambda T.mkNoSrcPos p
(\ fv94v49v94v56v1 p ->
T.uccase T.mkNoSrcPos p
(let v94v49v94v56v1 (T.R (T.Cons fh ft) _) p
= T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.greturn T.mkNoSrcPos p)
ft
v94v49v94v56v1 _ p
= T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.gfail T.mkNoSrcPos p)
(T.fromLitString T.mkNoSrcPos p
"pattern-match failure in do-expression")
in v94v49v94v56v1)
fv94v49v94v56v1))))
p))
htranspose _ p = T.fatal p
gpartition ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.Fun a Bool)
(T.Fun (T.List a) (T.Tuple2 (T.List a) (T.List a))))
hpartition ::
T.R (T.Fun a Bool) ->
T.R (T.List a) ->
T.RefExp -> T.R (T.Tuple2 (T.List a) (T.List a))
gpartition ppartition p
= T.ufun2 apartition ppartition p hpartition
hpartition fp fxs p
= T.con2 T.mkNoSrcPos p T.Tuple2 T.aTuple2
(T.uwrapForward p (hfilter fp fxs p))
(T.uwrapForward p
(hfilter
(T.uap2 T.mkNoSrcPos p ((!.) T.mkNoSrcPos p)
(gnot T.mkNoSrcPos p)
fp)
fxs
p))
ggroup ::
(Eq a) =>
T.RefSrcPos ->
T.RefExp ->
T.R (T.Fun (T.List a) (T.List (T.List a)))
sgroup ::
(Eq a) => T.R (T.Fun (T.List a) (T.List (T.List a)))
ggroup pgroup p = T.uconstUse pgroup p sgroup
sgroup
= T.uconstDef p agroup
(\ p ->
T.uap1 T.mkNoSrcPos p (ggroupBy T.mkNoSrcPos p)
((!==) T.mkNoSrcPos p))
ggroupBy ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.Fun a (T.Fun a Bool))
(T.Fun (T.List a) (T.List (T.List a))))
hgroupBy ::
T.R (T.Fun a (T.Fun a Bool)) ->
T.R (T.List a) -> T.RefExp -> T.R (T.List (T.List a))
ggroupBy pgroupBy p
= T.ufun2 agroupBy pgroupBy p hgroupBy
hgroupBy feq (T.R T.Nil _) p
= T.con0 T.mkNoSrcPos p T.Nil T.aNil
hgroupBy feq (T.R (T.Cons fx fxs) _) p
= T.con2 T.mkNoSrcPos p T.Cons T.aCons
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fx
(gys T.mkNoSrcPos p))
(T.uwrapForward p
(hgroupBy feq (gzs T.mkNoSrcPos p) p))
where gys pys p = T.uconstUse pys p sys
gzs pzs p = T.uconstUse pzs p szs
sys
= T.uconstDef p c108v34v108v57ys
(\ _ ->
case j108v34v108v57ys of
(kys, fys, fzs) -> fys)
szs
= T.uconstDef p c108v34v108v57zs
(\ _ ->
case j108v34v108v57ys of
(kys, fys, fzs) -> fzs)
j108v34v108v57ys
= case
T.uwrapForward p
(hspan (T.uap1 T.mkNoSrcPos p feq fx) fxs p)
of
T.R (T.Tuple2 fys fzs) kys -> (kys, fys, fzs)
_ -> T.fatal p
hgroupBy _ _ p = T.fatal p
ginits ::
T.RefSrcPos ->
T.RefExp ->
T.R (T.Fun (T.List a) (T.List (T.List a)))
hinits ::
T.R (T.List a) -> T.RefExp -> T.R (T.List (T.List a))
ginits pinits p = T.ufun1 ainits pinits p hinits
hinits (T.R T.Nil _) p
= T.fromExpList T.mkNoSrcPos p
[T.con0 T.mkNoSrcPos p T.Nil T.aNil]
hinits (T.R (T.Cons fx fxs) _) p
= T.uwrapForward p
((*++)
(T.fromExpList T.mkNoSrcPos p
[T.con0 T.mkNoSrcPos p T.Nil T.aNil])
(T.uwrapForward p
(hmap (T.pa1 T.Cons T.cn1 T.mkNoSrcPos p T.aCons fx)
(T.uwrapForward p (hinits fxs p))
p))
p)
hinits _ p = T.fatal p
gtails ::
T.RefSrcPos ->
T.RefExp ->
T.R (T.Fun (T.List a) (T.List (T.List a)))
htails ::
T.R (T.List a) -> T.RefExp -> T.R (T.List (T.List a))
gtails ptails p = T.ufun1 atails ptails p htails
htails (T.R T.Nil _) p
= T.fromExpList T.mkNoSrcPos p
[T.con0 T.mkNoSrcPos p T.Nil T.aNil]
htails fxxs@(T.R (T.Cons _ fxs) _) p
= T.con2 T.mkNoSrcPos p T.Cons T.aCons fxxs
(T.uwrapForward p (htails fxs p))
htails _ p = T.fatal p
gisPrefixOf ::
(Eq a) =>
T.RefSrcPos ->
T.RefExp ->
T.R (T.Fun (T.List a) (T.Fun (T.List a) Bool))
hisPrefixOf ::
(Eq a) =>
T.R (T.List a) ->
T.R (T.List a) -> T.RefExp -> T.R Bool
gisPrefixOf pisPrefixOf p
= T.ufun2 aisPrefixOf pisPrefixOf p hisPrefixOf
hisPrefixOf (T.R T.Nil _) _ p
= T.con0 T.mkNoSrcPos p True aTrue
hisPrefixOf _ (T.R T.Nil _) p
= T.con0 T.mkNoSrcPos p False aFalse
hisPrefixOf (T.R (T.Cons fx fxs) _)
(T.R (T.Cons fy fys) _) p
= T.uwrapForward p
((*&&)
(T.uap2 T.mkNoSrcPos p ((!==) T.mkNoSrcPos p) fx fy)
(T.uwrapForward p (hisPrefixOf fxs fys p))
p)
hisPrefixOf _ _ p = T.fatal p
gisSuffixOf ::
(Eq a) =>
T.RefSrcPos ->
T.RefExp ->
T.R (T.Fun (T.List a) (T.Fun (T.List a) Bool))
hisSuffixOf ::
(Eq a) =>
T.R (T.List a) ->
T.R (T.List a) -> T.RefExp -> T.R Bool
gisSuffixOf pisSuffixOf p
= T.ufun2 aisSuffixOf pisSuffixOf p hisSuffixOf
hisSuffixOf fx fy p
= T.uwrapForward p
(hisPrefixOf
(T.uap1 T.mkNoSrcPos p (greverse T.mkNoSrcPos p) fx)
(T.uap1 T.mkNoSrcPos p (greverse T.mkNoSrcPos p) fy)
p)
gmapAccumL ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.Fun a (T.Fun b (T.Tuple2 a c)))
(T.Fun a (T.Fun (T.List b) (T.Tuple2 a (T.List c)))))
hmapAccumL ::
T.R (T.Fun a (T.Fun b (T.Tuple2 a c))) ->
T.R a ->
T.R (T.List b) ->
T.RefExp -> T.R (T.Tuple2 a (T.List c))
gmapAccumL pmapAccumL p
= T.ufun3 amapAccumL pmapAccumL p hmapAccumL
hmapAccumL ff fs (T.R T.Nil _) p
= T.con2 T.mkNoSrcPos p T.Tuple2 T.aTuple2 fs
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
hmapAccumL ff fs (T.R (T.Cons fx fxs) _) p
= T.con2 T.mkNoSrcPos p T.Tuple2 T.aTuple2
(gs'' T.mkNoSrcPos p)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons
(gy T.mkNoSrcPos p)
(gys T.mkNoSrcPos p))
where gs' ps' p = T.uconstUse ps' p ss'
gy py p = T.uconstUse py p sy
ss'
= T.uconstDef p c133v34v133v49s'
(\ _ ->
case j133v34v133v49s' of
(ks', fs', fy) -> fs')
sy
= T.uconstDef p c133v34v133v49y
(\ _ ->
case j133v34v133v49s' of
(ks', fs', fy) -> fy)
j133v34v133v49s'
= case T.uap2 T.mkNoSrcPos p ff fs fx of
T.R (T.Tuple2 fs' fy) ks' -> (ks', fs', fy)
_ -> T.fatal p
gs'' ps'' p = T.uconstUse ps'' p ss''
gys pys p = T.uconstUse pys p sys
ss''
= T.uconstDef p c134v34v134v61s''
(\ _ ->
case j134v34v134v61s'' of
(ks'', fs'', fys) -> fs'')
sys
= T.uconstDef p c134v34v134v61ys
(\ _ ->
case j134v34v134v61s'' of
(ks'', fs'', fys) -> fys)
j134v34v134v61s''
= case
T.uwrapForward p
(hmapAccumL ff (gs' T.mkNoSrcPos p) fxs p)
of
T.R (T.Tuple2 fs'' fys) ks'' -> (ks'', fs'', fys)
_ -> T.fatal p
hmapAccumL _ _ _ p = T.fatal p
gmapAccumR ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.Fun a (T.Fun b (T.Tuple2 a c)))
(T.Fun a (T.Fun (T.List b) (T.Tuple2 a (T.List c)))))
hmapAccumR ::
T.R (T.Fun a (T.Fun b (T.Tuple2 a c))) ->
T.R a ->
T.R (T.List b) ->
T.RefExp -> T.R (T.Tuple2 a (T.List c))
gmapAccumR pmapAccumR p
= T.ufun3 amapAccumR pmapAccumR p hmapAccumR
hmapAccumR ff fs (T.R T.Nil _) p
= T.con2 T.mkNoSrcPos p T.Tuple2 T.aTuple2 fs
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
hmapAccumR ff fs (T.R (T.Cons fx fxs) _) p
= T.con2 T.mkNoSrcPos p T.Tuple2 T.aTuple2
(gs'' T.mkNoSrcPos p)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons
(gy T.mkNoSrcPos p)
(gys T.mkNoSrcPos p))
where gs'' ps'' p = T.uconstUse ps'' p ss''
gy py p = T.uconstUse py p sy
ss''
= T.uconstDef p c139v34v139v50s''
(\ _ ->
case j139v34v139v50s'' of
(ks'', fs'', fy) -> fs'')
sy
= T.uconstDef p c139v34v139v50y
(\ _ ->
case j139v34v139v50s'' of
(ks'', fs'', fy) -> fy)
j139v34v139v50s''
= case
T.uap2 T.mkNoSrcPos p ff (gs' T.mkNoSrcPos p) fx of
T.R (T.Tuple2 fs'' fy) ks'' -> (ks'', fs'', fy)
_ -> T.fatal p
gs' ps' p = T.uconstUse ps' p ss'
gys pys p = T.uconstUse pys p sys
ss'
= T.uconstDef p c140v34v140v60s'
(\ _ ->
case j140v34v140v60s' of
(ks', fs', fys) -> fs')
sys
= T.uconstDef p c140v34v140v60ys
(\ _ ->
case j140v34v140v60s' of
(ks', fs', fys) -> fys)
j140v34v140v60s'
= case T.uwrapForward p (hmapAccumR ff fs fxs p) of
T.R (T.Tuple2 fs' fys) ks' -> (ks', fs', fys)
_ -> T.fatal p
hmapAccumR _ _ _ p = T.fatal p
gunfoldr ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.Fun b (Maybe (T.Tuple2 a b)))
(T.Fun b (T.List a)))
hunfoldr ::
T.R (T.Fun b (Maybe (T.Tuple2 a b))) ->
T.R b -> T.RefExp -> T.R (T.List a)
gunfoldr punfoldr p
= T.ufun2 aunfoldr punfoldr p hunfoldr
hunfoldr ff fb p
= T.uccase T.mkNoSrcPos p
(let v143v27v147v0v1 (T.R Nothing _) p
= T.con0 T.mkNoSrcPos p T.Nil T.aNil
v143v27v147v0v1
(T.R (Just (T.R (T.Tuple2 fa fb) _)) _) p
= T.con2 T.mkNoSrcPos p T.Cons T.aCons fa
(T.uwrapForward p (hunfoldr ff fb p))
v143v27v147v0v1 _ p = T.fatal p
in v143v27v147v0v1)
(T.uap1 T.mkNoSrcPos p ff fb)
gsort ::
(Ord a) =>
T.RefSrcPos ->
T.RefExp -> T.R (T.Fun (T.List a) (T.List a))
ssort :: (Ord a) => T.R (T.Fun (T.List a) (T.List a))
gsort psort p = T.uconstUse psort p ssort
ssort
= T.uconstDef p asort
(\ p ->
T.uwrapForward p
(hsortBy (gcompare T.mkNoSrcPos p) p))
gsortBy ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.Fun a (T.Fun a Ordering))
(T.Fun (T.List a) (T.List a)))
hsortBy ::
T.R (T.Fun a (T.Fun a Ordering)) ->
T.RefExp -> T.R (T.Fun (T.List a) (T.List a))
gsortBy psortBy p = T.ufun1 asortBy psortBy p hsortBy
hsortBy fcmp p
= T.uap2 T.mkNoSrcPos p ((!.) T.mkNoSrcPos p)
(gmergeAll T.mkNoSrcPos p)
(gsequences T.mkNoSrcPos p)
where gsequences psequences p
= T.ufun1 c153v5v156v23sequences psequences p
hsequences
asequences = c153v5v156v23sequences
hsequences
(T.R (T.Cons fa (T.R (T.Cons fb fxs) _)) _) p
= T.ucguard
(T.uap2 T.mkNoSrcPos p ((!==) T.mkNoSrcPos p)
(T.uap2 T.mkNoSrcPos p fcmp fa fb)
(T.con0 T.mkNoSrcPos p GT aGT))
(T.uwrapForward p
(hdescending fb (T.fromExpList T.mkNoSrcPos p [fa])
fxs
p))
(T.ucguard (gotherwise T.mkNoSrcPos p)
(T.uwrapForward p
(hascending fb
(T.pa1 T.Cons T.cn1 T.mkNoSrcPos p T.aCons fa)
fxs
p))
(T.fatal p))
hsequences fxs p = T.fromExpList T.mkNoSrcPos p [fxs]
gdescending pdescending p
= T.ufun3 c158v5v160v46descending pdescending p
hdescending
adescending = c158v5v160v46descending
hdescending fa fas
z3descending@(T.R (T.Cons fb fbs) _) p
= T.ucguard
(T.uap2 T.mkNoSrcPos p ((!==) T.mkNoSrcPos p)
(T.uap2 T.mkNoSrcPos p fcmp fa fb)
(T.con0 T.mkNoSrcPos p GT aGT))
(T.uwrapForward p
(hdescending fb
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fa fas)
fbs
p))
(y1descending fa fas z3descending p)
hdescending fa fas z3descending p
= y1descending fa fas z3descending p
y1descending fa fas fbs p
= T.con2 T.mkNoSrcPos p T.Cons T.aCons
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fa fas)
(T.uwrapForward p (hsequences fbs p))
gascending pascending p
= T.ufun3 c162v5v164v46ascending pascending p
hascending
aascending = c162v5v164v46ascending
hascending fa fas z3ascending@(T.R (T.Cons fb fbs) _)
p
= T.ucguard
(T.uap2 T.mkNoSrcPos p ((!/=) T.mkNoSrcPos p)
(T.uap2 T.mkNoSrcPos p fcmp fa fb)
(T.con0 T.mkNoSrcPos p GT aGT))
(T.uwrapForward p
(hascending fb
(T.ufun1 T.mkLambda T.mkNoSrcPos p
(\ fys p ->
T.uap1 T.mkNoSrcPos p
(T.projection T.mkNoSrcPos p fas)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fa fys)))
fbs
p))
(y1ascending fa fas z3ascending p)
hascending fa fas z3ascending p
= y1ascending fa fas z3ascending p
y1ascending fa fas fbs p
= T.con2 T.mkNoSrcPos p T.Cons T.aCons
(T.uap1 T.mkNoSrcPos p fas
(T.fromExpList T.mkNoSrcPos p [fa]))
(T.uwrapForward p (hsequences fbs p))
gmergeAll pmergeAll p
= T.ufun1 c166v5v167v43mergeAll pmergeAll p hmergeAll
amergeAll = c166v5v167v43mergeAll
hmergeAll (T.R (T.Cons fx (T.R T.Nil _)) _) p
= T.projection T.mkNoSrcPos p fx
hmergeAll fxs p
= T.uwrapForward p
(hmergeAll (T.uwrapForward p (hmergePairs fxs p)) p)
gmergePairs pmergePairs p
= T.ufun1 c169v5v170v28mergePairs pmergePairs p
hmergePairs
amergePairs = c169v5v170v28mergePairs
hmergePairs
(T.R (T.Cons fa (T.R (T.Cons fb fxs) _)) _) p
= T.con2 T.mkNoSrcPos p T.Cons T.aCons
(T.uwrapForward p (hmerge fa fb p))
(T.uwrapForward p (hmergePairs fxs p))
hmergePairs fxs p = T.projection T.mkNoSrcPos p fxs
gmerge pmerge p
= T.ufun2 c172v5v176v28merge pmerge p hmerge
amerge = c172v5v176v28merge
hmerge fas@(T.R (T.Cons fa fas') _)
fbs@(T.R (T.Cons fb fbs') _) p
= T.ucguard
(T.uap2 T.mkNoSrcPos p ((!==) T.mkNoSrcPos p)
(T.uap2 T.mkNoSrcPos p fcmp fa fb)
(T.con0 T.mkNoSrcPos p GT aGT))
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fb
(T.uwrapForward p (hmerge fas fbs' p)))
(T.ucguard (gotherwise T.mkNoSrcPos p)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fa
(T.uwrapForward p (hmerge fas' fbs p)))
(T.fatal p))
hmerge (T.R T.Nil _) fbs p
= T.projection T.mkNoSrcPos p fbs
hmerge fas (T.R T.Nil _) p
= T.projection T.mkNoSrcPos p fas
hmerge _ _ p = T.fatal p
ginsert ::
(Ord a) =>
T.RefSrcPos ->
T.RefExp ->
T.R (T.Fun a (T.Fun (T.List a) (T.List a)))
sinsert ::
(Ord a) =>
T.R (T.Fun a (T.Fun (T.List a) (T.List a)))
ginsert pinsert p = T.uconstUse pinsert p sinsert
sinsert
= T.uconstDef p ainsert
(\ p ->
T.uap1 T.mkNoSrcPos p (ginsertBy T.mkNoSrcPos p)
(gcompare T.mkNoSrcPos p))
ginsertBy ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.Fun a (T.Fun a Ordering))
(T.Fun a (T.Fun (T.List a) (T.List a))))
hinsertBy ::
T.R (T.Fun a (T.Fun a Ordering)) ->
T.R a -> T.R (T.List a) -> T.RefExp -> T.R (T.List a)
ginsertBy pinsertBy p
= T.ufun3 ainsertBy pinsertBy p hinsertBy
hinsertBy fcmp fx (T.R T.Nil _) p
= T.fromExpList T.mkNoSrcPos p [fx]
hinsertBy fcmp fx fys@(T.R (T.Cons fy fys') _) p
= T.uccase T.mkNoSrcPos p
(let v184v28v188v0v1 (T.R GT _) p
= T.con2 T.mkNoSrcPos p T.Cons T.aCons fy
(T.uwrapForward p (hinsertBy fcmp fx fys' p))
v184v28v188v0v1 _ p
= T.con2 T.mkNoSrcPos p T.Cons T.aCons fx fys
in v184v28v188v0v1)
(T.uap2 T.mkNoSrcPos p fcmp fx fy)
hinsertBy _ _ _ p = T.fatal p
gmaximumBy ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.Fun a (T.Fun a Ordering))
(T.Fun (T.List a) a))
hmaximumBy ::
T.R (T.Fun a (T.Fun a Ordering)) ->
T.R (T.List a) -> T.RefExp -> T.R a
gmaximumBy pmaximumBy p
= T.ufun2 amaximumBy pmaximumBy p hmaximumBy
hmaximumBy fcmp (T.R T.Nil _) p
= T.uwrapForward p
(herror
(T.fromLitString T.mkNoSrcPos p
"List.maximumBy: empty list")
p)
hmaximumBy fcmp fxs p
= T.uwrapForward p
(hfoldl1 (gmax T.mkNoSrcPos p) fxs p)
where gmax pmax p
= T.ufun2 c192v28v196v0max pmax p hmax
amax = c192v28v196v0max
hmax fx fy p
= T.uccase T.mkNoSrcPos p
(let v192v38v196v0v1 (T.R GT _) p
= T.projection T.mkNoSrcPos p fx
v192v38v196v0v1 _ p = T.projection T.mkNoSrcPos p fy
in v192v38v196v0v1)
(T.uap2 T.mkNoSrcPos p fcmp fx fy)
gminimumBy ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.Fun a (T.Fun a Ordering))
(T.Fun (T.List a) a))
hminimumBy ::
T.R (T.Fun a (T.Fun a Ordering)) ->
T.R (T.List a) -> T.RefExp -> T.R a
gminimumBy pminimumBy p
= T.ufun2 aminimumBy pminimumBy p hminimumBy
hminimumBy fcmp (T.R T.Nil _) p
= T.uwrapForward p
(herror
(T.fromLitString T.mkNoSrcPos p
"List.minimumBy: empty list")
p)
hminimumBy fcmp fxs p
= T.uwrapForward p
(hfoldl1 (gmin T.mkNoSrcPos p) fxs p)
where gmin pmin p
= T.ufun2 c200v28v204v0min pmin p hmin
amin = c200v28v204v0min
hmin fx fy p
= T.uccase T.mkNoSrcPos p
(let v200v38v204v0v1 (T.R GT _) p
= T.projection T.mkNoSrcPos p fy
v200v38v204v0v1 _ p = T.projection T.mkNoSrcPos p fx
in v200v38v204v0v1)
(T.uap2 T.mkNoSrcPos p fcmp fx fy)
ggenericLength ::
(Integral a) =>
T.RefSrcPos -> T.RefExp -> T.R (T.Fun (T.List b) a)
hgenericLength ::
(Integral a) => T.R (T.List b) -> T.RefExp -> T.R a
ggenericLength pgenericLength p
= T.ufun1 agenericLength pgenericLength p
hgenericLength
hgenericLength (T.R T.Nil _) p
= T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.gfromInteger T.mkNoSrcPos p)
(T.conInteger T.mkNoSrcPos p (0))
hgenericLength (T.R (T.Cons fx fxs) _) p
= T.uap2 T.mkNoSrcPos p ((!+) T.mkNoSrcPos p)
(T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.gfromInteger T.mkNoSrcPos p)
(T.conInteger T.mkNoSrcPos p (1)))
(T.uwrapForward p (hgenericLength fxs p))
hgenericLength _ p = T.fatal p
ggenericTake ::
(Integral a) =>
T.RefSrcPos ->
T.RefExp ->
T.R (T.Fun a (T.Fun (T.List b) (T.List b)))
hgenericTake ::
(Integral a) =>
T.R a -> T.R (T.List b) -> T.RefExp -> T.R (T.List b)
ggenericTake pgenericTake p
= T.ufun2 agenericTake pgenericTake p hgenericTake
hgenericTake _ (T.R T.Nil _) p
= T.con0 T.mkNoSrcPos p T.Nil T.aNil
hgenericTake fv210v13v210v13n v210v15v210v15n p
= T.ucguard
(T.uap2 T.mkNoSrcPos p
((Hat.PreludeBasic.!==) T.mkNoSrcPos p)
fv210v13v210v13n
(T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.gfromInteger T.mkNoSrcPos p)
(T.conInteger T.mkNoSrcPos p (0))))
(h210v1v210v29n v210v15v210v15n p)
(y1genericTake fv210v13v210v13n v210v15v210v15n p)
where h210v1v210v29n _ p
= T.con0 T.mkNoSrcPos p T.Nil T.aNil
h210v1v210v29n _ p
= y1genericTake fv210v13v210v13n v210v15v210v15n p
hgenericTake fv210v13v210v13n v210v15v210v15n p
= y1genericTake fv210v13v210v13n v210v15v210v15n p
y1genericTake fn (T.R (T.Cons fx fxs) _) p
= T.ucguard
(T.uap2 T.mkNoSrcPos p ((!>) T.mkNoSrcPos p) fn
(T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.gfromInteger T.mkNoSrcPos p)
(T.conInteger T.mkNoSrcPos p (0))))
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fx
(T.uwrapForward p
(hgenericTake
(T.uap2 T.mkNoSrcPos p ((!-) T.mkNoSrcPos p) fn
(T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.gfromInteger T.mkNoSrcPos p)
(T.conInteger T.mkNoSrcPos p (1))))
fxs
p)))
(T.ucguard (gotherwise T.mkNoSrcPos p)
(T.uwrapForward p
(herror
(T.fromLitString T.mkNoSrcPos p
"List.genericTake: negative argument")
p))
(T.fatal p))
y1genericTake _ _ p = T.fatal p
ggenericDrop ::
(Integral a) =>
T.RefSrcPos ->
T.RefExp ->
T.R (T.Fun a (T.Fun (T.List b) (T.List b)))
hgenericDrop ::
(Integral a) =>
T.R a -> T.R (T.List b) -> T.RefExp -> T.R (T.List b)
ggenericDrop pgenericDrop p
= T.ufun2 agenericDrop pgenericDrop p hgenericDrop
hgenericDrop fv216v13v216v13n fxs p
= T.ucguard
(T.uap2 T.mkNoSrcPos p
((Hat.PreludeBasic.!==) T.mkNoSrcPos p)
fv216v13v216v13n
(T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.gfromInteger T.mkNoSrcPos p)
(T.conInteger T.mkNoSrcPos p (0))))
(h216v1v216v29n fxs p)
(y1genericDrop fv216v13v216v13n fxs p)
where h216v1v216v29n fxs p
= T.projection T.mkNoSrcPos p fxs
h216v1v216v29n _ p
= y1genericDrop fv216v13v216v13n fxs p
hgenericDrop fv216v13v216v13n fxs p
= y1genericDrop fv216v13v216v13n fxs p
y1genericDrop _ (T.R T.Nil _) p
= T.con0 T.mkNoSrcPos p T.Nil T.aNil
y1genericDrop fn (T.R (T.Cons _ fxs) _) p
= T.ucguard
(T.uap2 T.mkNoSrcPos p ((!>) T.mkNoSrcPos p) fn
(T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.gfromInteger T.mkNoSrcPos p)
(T.conInteger T.mkNoSrcPos p (0))))
(T.uwrapForward p
(hgenericDrop
(T.uap2 T.mkNoSrcPos p ((!-) T.mkNoSrcPos p) fn
(T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.gfromInteger T.mkNoSrcPos p)
(T.conInteger T.mkNoSrcPos p (1))))
fxs
p))
(T.ucguard (gotherwise T.mkNoSrcPos p)
(T.uwrapForward p
(herror
(T.fromLitString T.mkNoSrcPos p
"List.genericDrop: negative argument")
p))
(T.fatal p))
y1genericDrop _ _ p = T.fatal p
ggenericSplitAt ::
(Integral a) =>
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun a
(T.Fun (T.List b) (T.Tuple2 (T.List b) (T.List b))))
hgenericSplitAt ::
(Integral a) =>
T.R a ->
T.R (T.List b) ->
T.RefExp -> T.R (T.Tuple2 (T.List b) (T.List b))
ggenericSplitAt pgenericSplitAt p
= T.ufun2 agenericSplitAt pgenericSplitAt p
hgenericSplitAt
hgenericSplitAt fv223v16v223v16n fxs p
= T.ucguard
(T.uap2 T.mkNoSrcPos p
((Hat.PreludeBasic.!==) T.mkNoSrcPos p)
fv223v16v223v16n
(T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.gfromInteger T.mkNoSrcPos p)
(T.conInteger T.mkNoSrcPos p (0))))
(h223v1v223v34n fxs p)
(y1genericSplitAt fv223v16v223v16n fxs p)
where h223v1v223v34n fxs p
= T.con2 T.mkNoSrcPos p T.Tuple2 T.aTuple2
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
fxs
h223v1v223v34n _ p
= y1genericSplitAt fv223v16v223v16n fxs p
hgenericSplitAt fv223v16v223v16n fxs p
= y1genericSplitAt fv223v16v223v16n fxs p
y1genericSplitAt _ (T.R T.Nil _) p
= T.con2 T.mkNoSrcPos p T.Tuple2 T.aTuple2
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
y1genericSplitAt fn (T.R (T.Cons fx fxs) _) p
= T.ucguard
(T.uap2 T.mkNoSrcPos p ((!>) T.mkNoSrcPos p) fn
(T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.gfromInteger T.mkNoSrcPos p)
(T.conInteger T.mkNoSrcPos p (0))))
(T.con2 T.mkNoSrcPos p T.Tuple2 T.aTuple2
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fx
(gxs' T.mkNoSrcPos p))
(gxs'' T.mkNoSrcPos p))
(T.ucguard (gotherwise T.mkNoSrcPos p)
(T.uwrapForward p
(herror
(T.fromLitString T.mkNoSrcPos p
"List.genericSplitAt: negative argument")
p))
(T.fatal p))
where gxs' pxs' p = T.uconstUse pxs' p sxs'
gxs'' pxs'' p = T.uconstUse pxs'' p sxs''
sxs'
= T.uconstDef p c228v14v228v50xs'
(\ _ ->
case j228v14v228v50xs' of
(kxs', fxs', fxs'') -> fxs')
sxs''
= T.uconstDef p c228v14v228v50xs''
(\ _ ->
case j228v14v228v50xs' of
(kxs', fxs', fxs'') -> fxs'')
j228v14v228v50xs'
= case
T.uwrapForward p
(hgenericSplitAt
(T.uap2 T.mkNoSrcPos p ((!-) T.mkNoSrcPos p) fn
(T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.gfromInteger T.mkNoSrcPos p)
(T.conInteger T.mkNoSrcPos p (1))))
fxs
p)
of
T.R (T.Tuple2 fxs' fxs'') kxs' -> (kxs', fxs', fxs'')
_ -> T.fatal p
y1genericSplitAt _ _ p = T.fatal p
ggenericIndex ::
(Integral a) =>
T.RefSrcPos ->
T.RefExp -> T.R (T.Fun (T.List b) (T.Fun a b))
hgenericIndex ::
(Integral a) =>
T.R (T.List b) -> T.R a -> T.RefExp -> T.R b
ggenericIndex pgenericIndex p
= T.ufun2 agenericIndex pgenericIndex p hgenericIndex
hgenericIndex z1genericIndex@(T.R (T.Cons fx _) _)
fv231v21v231v21n p
= T.ucguard
(T.uap2 T.mkNoSrcPos p
((Hat.PreludeBasic.!==) T.mkNoSrcPos p)
fv231v21v231v21n
(T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.gfromInteger T.mkNoSrcPos p)
(T.conInteger T.mkNoSrcPos p (0))))
(h231v1v231v28n p)
(y1genericIndex z1genericIndex fv231v21v231v21n p)
where h231v1v231v28n p
= T.projection T.mkNoSrcPos p fx
h231v1v231v28n p
= y1genericIndex z1genericIndex fv231v21v231v21n p
hgenericIndex z1genericIndex fv231v21v231v21n p
= y1genericIndex z1genericIndex fv231v21v231v21n p
y1genericIndex (T.R (T.Cons _ fxs) _) fn p
= T.ucguard
(T.uap2 T.mkNoSrcPos p ((!>) T.mkNoSrcPos p) fn
(T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.gfromInteger T.mkNoSrcPos p)
(T.conInteger T.mkNoSrcPos p (0))))
(T.uwrapForward p
(hgenericIndex fxs
(T.uap2 T.mkNoSrcPos p ((!-) T.mkNoSrcPos p) fn
(T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.gfromInteger T.mkNoSrcPos p)
(T.conInteger T.mkNoSrcPos p (1))))
p))
(T.ucguard (gotherwise T.mkNoSrcPos p)
(T.uwrapForward p
(herror
(T.fromLitString T.mkNoSrcPos p
"List.genericIndex: negative argument")
p))
(T.fatal p))
y1genericIndex _ _ p
= T.uwrapForward p
(herror
(T.fromLitString T.mkNoSrcPos p
"List.genericIndex: index too large")
p)
ggenericReplicate ::
(Integral a) =>
T.RefSrcPos ->
T.RefExp -> T.R (T.Fun a (T.Fun b (T.List b)))
hgenericReplicate ::
(Integral a) =>
T.R a -> T.R b -> T.RefExp -> T.R (T.List b)
ggenericReplicate pgenericReplicate p
= T.ufun2 agenericReplicate pgenericReplicate p
hgenericReplicate
hgenericReplicate fn fx p
= T.uwrapForward p
(hgenericTake fn (T.uwrapForward p (hrepeat fx p)) p)
gzip4 ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.List a)
(T.Fun (T.List b)
(T.Fun (T.List c)
(T.Fun (T.List d) (T.List (T.Tuple4 a b c d))))))
szip4 ::
T.R
(T.Fun (T.List a)
(T.Fun (T.List b)
(T.Fun (T.List c)
(T.Fun (T.List d) (T.List (T.Tuple4 a b c d))))))
gzip4 pzip4 p = T.uconstUse pzip4 p szip4
szip4
= T.uconstDef p azip4
(\ p ->
T.uap1 T.mkNoSrcPos p (gzipWith4 T.mkNoSrcPos p)
(T.pa0 T.Tuple4 T.cn4 T.mkNoSrcPos p T.aTuple4))
gzip5 ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.List a)
(T.Fun (T.List b)
(T.Fun (T.List c)
(T.Fun (T.List d)
(T.Fun (T.List e) (T.List (T.Tuple5 a b c d e)))))))
szip5 ::
T.R
(T.Fun (T.List a)
(T.Fun (T.List b)
(T.Fun (T.List c)
(T.Fun (T.List d)
(T.Fun (T.List e) (T.List (T.Tuple5 a b c d e)))))))
gzip5 pzip5 p = T.uconstUse pzip5 p szip5
szip5
= T.uconstDef p azip5
(\ p ->
T.uap1 T.mkNoSrcPos p (gzipWith5 T.mkNoSrcPos p)
(T.pa0 T.Tuple5 T.cn5 T.mkNoSrcPos p T.aTuple5))
gzip6 ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.List a)
(T.Fun (T.List b)
(T.Fun (T.List c)
(T.Fun (T.List d)
(T.Fun (T.List e)
(T.Fun (T.List f)
(T.List (T.Tuple6 a b c d e f))))))))
szip6 ::
T.R
(T.Fun (T.List a)
(T.Fun (T.List b)
(T.Fun (T.List c)
(T.Fun (T.List d)
(T.Fun (T.List e)
(T.Fun (T.List f)
(T.List (T.Tuple6 a b c d e f))))))))
gzip6 pzip6 p = T.uconstUse pzip6 p szip6
szip6
= T.uconstDef p azip6
(\ p ->
T.uap1 T.mkNoSrcPos p (gzipWith6 T.mkNoSrcPos p)
(T.pa0 T.Tuple6 T.cn6 T.mkNoSrcPos p T.aTuple6))
gzip7 ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.List a)
(T.Fun (T.List b)
(T.Fun (T.List c)
(T.Fun (T.List d)
(T.Fun (T.List e)
(T.Fun (T.List f)
(T.Fun (T.List g)
(T.List (T.Tuple7 a b c d e f g)))))))))
szip7 ::
T.R
(T.Fun (T.List a)
(T.Fun (T.List b)
(T.Fun (T.List c)
(T.Fun (T.List d)
(T.Fun (T.List e)
(T.Fun (T.List f)
(T.Fun (T.List g)
(T.List (T.Tuple7 a b c d e f g)))))))))
gzip7 pzip7 p = T.uconstUse pzip7 p szip7
szip7
= T.uconstDef p azip7
(\ p ->
T.uap1 T.mkNoSrcPos p (gzipWith7 T.mkNoSrcPos p)
(T.pa0 T.Tuple7 T.cn7 T.mkNoSrcPos p T.aTuple7))
gzipWith4 ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.Fun a (T.Fun b (T.Fun c (T.Fun d e))))
(T.Fun (T.List a)
(T.Fun (T.List b)
(T.Fun (T.List c) (T.Fun (T.List d) (T.List e))))))
hzipWith4 ::
T.R (T.Fun a (T.Fun b (T.Fun c (T.Fun d e)))) ->
T.R (T.List a) ->
T.R (T.List b) ->
T.R (T.List c) ->
T.R (T.List d) -> T.RefExp -> T.R (T.List e)
gzipWith4 pzipWith4 p
= T.ufun5 azipWith4 pzipWith4 p hzipWith4
hzipWith4 fz (T.R (T.Cons fa fas) _)
(T.R (T.Cons fb fbs) _) (T.R (T.Cons fc fcs) _)
(T.R (T.Cons fd fds) _) p
= T.con2 T.mkNoSrcPos p T.Cons T.aCons
(T.uap4 T.mkNoSrcPos p fz fa fb fc fd)
(T.uwrapForward p (hzipWith4 fz fas fbs fcs fds p))
hzipWith4 _ _ _ _ _ p
= T.con0 T.mkNoSrcPos p T.Nil T.aNil
gzipWith5 ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun
(T.Fun a (T.Fun b (T.Fun c (T.Fun d (T.Fun e f)))))
(T.Fun (T.List a)
(T.Fun (T.List b)
(T.Fun (T.List c)
(T.Fun (T.List d) (T.Fun (T.List e) (T.List f)))))))
hzipWith5 ::
T.R
(T.Fun a (T.Fun b (T.Fun c (T.Fun d (T.Fun e f)))))
->
T.R (T.List a) ->
T.R (T.List b) ->
T.R (T.List c) ->
T.R (T.List d) ->
T.R (T.List e) -> T.RefExp -> T.R (T.List f)
gzipWith5 pzipWith5 p
= T.ufun6 azipWith5 pzipWith5 p hzipWith5
hzipWith5 fz (T.R (T.Cons fa fas) _)
(T.R (T.Cons fb fbs) _) (T.R (T.Cons fc fcs) _)
(T.R (T.Cons fd fds) _) (T.R (T.Cons fe fes) _) p
= T.con2 T.mkNoSrcPos p T.Cons T.aCons
(T.uap5 T.mkNoSrcPos p fz fa fb fc fd fe)
(T.uap6 T.mkNoSrcPos p (gzipWith5 T.mkNoSrcPos p) fz
fas
fbs
fcs
fds
fes)
hzipWith5 _ _ _ _ _ _ p
= T.con0 T.mkNoSrcPos p T.Nil T.aNil
gzipWith6 ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun
(T.Fun a
(T.Fun b (T.Fun c (T.Fun d (T.Fun e (T.Fun f g))))))
(T.Fun (T.List a)
(T.Fun (T.List b)
(T.Fun (T.List c)
(T.Fun (T.List d)
(T.Fun (T.List e)
(T.Fun (T.List f) (T.List g))))))))
hzipWith6 ::
T.R
(T.Fun a
(T.Fun b (T.Fun c (T.Fun d (T.Fun e (T.Fun f g))))))
->
T.R (T.List a) ->
T.R (T.List b) ->
T.R (T.List c) ->
T.R (T.List d) ->
T.R (T.List e) ->
T.R (T.List f) -> T.RefExp -> T.R (T.List g)
gzipWith6 pzipWith6 p
= T.ufun7 azipWith6 pzipWith6 p hzipWith6
hzipWith6 fz (T.R (T.Cons fa fas) _)
(T.R (T.Cons fb fbs) _) (T.R (T.Cons fc fcs) _)
(T.R (T.Cons fd fds) _) (T.R (T.Cons fe fes) _)
(T.R (T.Cons ff ffs) _) p
= T.con2 T.mkNoSrcPos p T.Cons T.aCons
(T.uap6 T.mkNoSrcPos p fz fa fb fc fd fe ff)
(T.uap7 T.mkNoSrcPos p (gzipWith6 T.mkNoSrcPos p) fz
fas
fbs
fcs
fds
fes
ffs)
hzipWith6 _ _ _ _ _ _ _ p
= T.con0 T.mkNoSrcPos p T.Nil T.aNil
gzipWith7 ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun
(T.Fun a
(T.Fun b
(T.Fun c (T.Fun d (T.Fun e (T.Fun f (T.Fun g h)))))))
(T.Fun (T.List a)
(T.Fun (T.List b)
(T.Fun (T.List c)
(T.Fun (T.List d)
(T.Fun (T.List e)
(T.Fun (T.List f)
(T.Fun (T.List g) (T.List h)))))))))
hzipWith7 ::
T.R
(T.Fun a
(T.Fun b
(T.Fun c (T.Fun d (T.Fun e (T.Fun f (T.Fun g h)))))))
->
T.R (T.List a) ->
T.R (T.List b) ->
T.R (T.List c) ->
T.R (T.List d) ->
T.R (T.List e) ->
T.R (T.List f) ->
T.R (T.List g) -> T.RefExp -> T.R (T.List h)
gzipWith7 pzipWith7 p
= T.ufun8 azipWith7 pzipWith7 p hzipWith7
hzipWith7 fz (T.R (T.Cons fa fas) _)
(T.R (T.Cons fb fbs) _) (T.R (T.Cons fc fcs) _)
(T.R (T.Cons fd fds) _) (T.R (T.Cons fe fes) _)
(T.R (T.Cons ff ffs) _) (T.R (T.Cons fg fgs) _) p
= T.con2 T.mkNoSrcPos p T.Cons T.aCons
(T.uap7 T.mkNoSrcPos p fz fa fb fc fd fe ff fg)
(T.uap8 T.mkNoSrcPos p (gzipWith7 T.mkNoSrcPos p) fz
fas
fbs
fcs
fds
fes
ffs
fgs)
hzipWith7 _ _ _ _ _ _ _ _ p
= T.con0 T.mkNoSrcPos p T.Nil T.aNil
gunzip4 ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.List (T.Tuple4 a b c d))
(T.Tuple4 (T.List a) (T.List b) (T.List c)
(T.List d)))
sunzip4 ::
T.R
(T.Fun (T.List (T.Tuple4 a b c d))
(T.Tuple4 (T.List a) (T.List b) (T.List c)
(T.List d)))
gunzip4 punzip4 p = T.uconstUse punzip4 p sunzip4
sunzip4
= T.uconstDef p aunzip4
(\ p ->
T.uap2 T.mkNoSrcPos p (gfoldr T.mkNoSrcPos p)
(T.ufun2 T.mkLambda T.mkNoSrcPos p
(\ (T.R (T.Tuple4 fa fb fc fd) _)
(T.R ~(T.Tuple4 fas fbs fcs fds) _) p ->
T.con4 T.mkNoSrcPos p T.Tuple4 T.aTuple4
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fa fas)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fb fbs)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fc fcs)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fd fds)))
(T.con4 T.mkNoSrcPos p T.Tuple4 T.aTuple4
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)))
gunzip5 ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.List (T.Tuple5 a b c d e))
(T.Tuple5 (T.List a) (T.List b) (T.List c) (T.List d)
(T.List e)))
sunzip5 ::
T.R
(T.Fun (T.List (T.Tuple5 a b c d e))
(T.Tuple5 (T.List a) (T.List b) (T.List c) (T.List d)
(T.List e)))
gunzip5 punzip5 p = T.uconstUse punzip5 p sunzip5
sunzip5
= T.uconstDef p aunzip5
(\ p ->
T.uap2 T.mkNoSrcPos p (gfoldr T.mkNoSrcPos p)
(T.ufun2 T.mkLambda T.mkNoSrcPos p
(\ (T.R (T.Tuple5 fa fb fc fd fe) _)
(T.R ~(T.Tuple5 fas fbs fcs fds fes) _) p ->
T.con5 T.mkNoSrcPos p T.Tuple5 T.aTuple5
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fa fas)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fb fbs)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fc fcs)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fd fds)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fe fes)))
(T.con5 T.mkNoSrcPos p T.Tuple5 T.aTuple5
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)))
gunzip6 ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.List (T.Tuple6 a b c d e f))
(T.Tuple6 (T.List a) (T.List b) (T.List c) (T.List d)
(T.List e)
(T.List f)))
sunzip6 ::
T.R
(T.Fun (T.List (T.Tuple6 a b c d e f))
(T.Tuple6 (T.List a) (T.List b) (T.List c) (T.List d)
(T.List e)
(T.List f)))
gunzip6 punzip6 p = T.uconstUse punzip6 p sunzip6
sunzip6
= T.uconstDef p aunzip6
(\ p ->
T.uap2 T.mkNoSrcPos p (gfoldr T.mkNoSrcPos p)
(T.ufun2 T.mkLambda T.mkNoSrcPos p
(\ (T.R (T.Tuple6 fa fb fc fd fe ff) _)
(T.R ~(T.Tuple6 fas fbs fcs fds fes ffs) _) p ->
T.con6 T.mkNoSrcPos p T.Tuple6 T.aTuple6
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fa fas)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fb fbs)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fc fcs)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fd fds)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fe fes)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons ff ffs)))
(T.con6 T.mkNoSrcPos p T.Tuple6 T.aTuple6
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)))
gunzip7 ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.List (T.Tuple7 a b c d e f g))
(T.Tuple7 (T.List a) (T.List b) (T.List c) (T.List d)
(T.List e)
(T.List f)
(T.List g)))
sunzip7 ::
T.R
(T.Fun (T.List (T.Tuple7 a b c d e f g))
(T.Tuple7 (T.List a) (T.List b) (T.List c) (T.List d)
(T.List e)
(T.List f)
(T.List g)))
gunzip7 punzip7 p = T.uconstUse punzip7 p sunzip7
sunzip7
= T.uconstDef p aunzip7
(\ p ->
T.uap2 T.mkNoSrcPos p (gfoldr T.mkNoSrcPos p)
(T.ufun2 T.mkLambda T.mkNoSrcPos p
(\ (T.R (T.Tuple7 fa fb fc fd fe ff fg) _)
(T.R ~(T.Tuple7 fas fbs fcs fds fes ffs fgs) _) p ->
T.con7 T.mkNoSrcPos p T.Tuple7 T.aTuple7
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fa fas)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fb fbs)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fc fcs)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fd fds)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fe fes)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons ff ffs)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fg fgs)))
(T.con7 T.mkNoSrcPos p T.Tuple7 T.aTuple7
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)))
adelete
= T.mkVariable tList 560001 560040 3 (0) "delete"
Prelude.False
adeleteBy
= T.mkVariable tList 590001 600071 3 (3) "deleteBy"
Prelude.False
adeleteFirstsBy
= T.mkVariable tList 660001 660053 3 (1)
"deleteFirstsBy"
Prelude.False
aelemIndex
= T.mkVariable tList 340001 340043 3 (1) "elemIndex"
Prelude.False
aelemIndices
= T.mkVariable tList 370001 370045 3 (1)
"elemIndices"
Prelude.False
afind
= T.mkVariable tList 400001 400049 3 (1) "find"
Prelude.False
afindIndex
= T.mkVariable tList 430001 430054 3 (1) "findIndex"
Prelude.False
afindIndices
= T.mkVariable tList 460001 460061 3 (2)
"findIndices"
Prelude.False
agenericDrop
= T.mkVariable tList 2160001 2200070 3 (2)
"genericDrop"
Prelude.False
agenericIndex
= T.mkVariable tList 2310001 2350069 3 (2)
"genericIndex"
Prelude.False
agenericLength
= T.mkVariable tList 2050001 2060047 3 (1)
"genericLength"
Prelude.False
agenericReplicate
= T.mkVariable tList 2380001 2380051 3 (2)
"genericReplicate"
Prelude.False
agenericSplitAt
= T.mkVariable tList 2230001 2300000 3 (2)
"genericSplitAt"
Prelude.False
agenericTake
= T.mkVariable tList 2090001 2130070 3 (2)
"genericTake"
Prelude.False
agroup
= T.mkVariable tList 1030001 1030039 3 (0) "group"
Prelude.False
agroupBy
= T.mkVariable tList 1060001 1120000 3 (2) "groupBy"
Prelude.False
ainits
= T.mkVariable tList 1130001 1140054 3 (1) "inits"
Prelude.False
ainsert
= T.mkVariable tList 1790001 1790042 3 (0) "insert"
Prelude.False
ainsertBy
= T.mkVariable tList 1820001 1880000 3 (3) "insertBy"
Prelude.False
aintersect
= T.mkVariable tList 750001 750043 3 (0) "intersect"
Prelude.False
aintersectBy
= T.mkVariable tList 780001 780055 3 (3)
"intersectBy"
Prelude.False
aintersperse
= T.mkVariable tList 810001 830055 3 (2)
"intersperse"
Prelude.False
aisPrefixOf
= T.mkVariable tList 1230001 1250054 3 (2)
"isPrefixOf"
Prelude.False
aisSuffixOf
= T.mkVariable tList 1280001 1280059 3 (2)
"isSuffixOf"
Prelude.False
amapAccumL
= T.mkVariable tList 1310001 1360000 3 (3)
"mapAccumL"
Prelude.False
amapAccumR
= T.mkVariable tList 1370001 1420000 3 (3)
"mapAccumR"
Prelude.False
amaximumBy
= T.mkVariable tList 1890001 1960000 3 (2)
"maximumBy"
Prelude.False
aminimumBy
= T.mkVariable tList 1970001 2040000 3 (2)
"minimumBy"
Prelude.False
anub
= T.mkVariable tList 490001 490037 3 (0) "nub"
Prelude.False
anubBy
= T.mkVariable tList 520001 530072 3 (2) "nubBy"
Prelude.False
apartition
= T.mkVariable tList 970001 970061 3 (2) "partition"
Prelude.False
asort
= T.mkVariable tList 1480001 1480041 3 (0) "sort"
Prelude.False
asortBy
= T.mkVariable tList 1510001 1520007 3 (1) "sortBy"
Prelude.False
atails
= T.mkVariable tList 1190001 1200041 3 (1) "tails"
Prelude.False
atranspose
= T.mkVariable tList 910001 940062 3 (1) "transpose"
Prelude.False
aunfoldr
= T.mkVariable tList 1430001 1470000 3 (2) "unfoldr"
Prelude.False
aunion
= T.mkVariable tList 690001 690039 3 (0) "union"
Prelude.False
aunionBy
= T.mkVariable tList 720001 720067 3 (3) "unionBy"
Prelude.False
aunzip4
= T.mkVariable tList 2780001 2800046 3 (0) "unzip4"
Prelude.False
aunzip5
= T.mkVariable tList 2830001 2850049 3 (0) "unzip5"
Prelude.False
aunzip6
= T.mkVariable tList 2880001 2900052 3 (0) "unzip6"
Prelude.False
aunzip7
= T.mkVariable tList 2930001 2950047 3 (0) "unzip7"
Prelude.False
azip4
= T.mkVariable tList 2410001 2410041 3 (0) "zip4"
Prelude.False
azip5
= T.mkVariable tList 2440001 2440042 3 (0) "zip5"
Prelude.False
azip6
= T.mkVariable tList 2480001 2480043 3 (0) "zip6"
Prelude.False
azip7
= T.mkVariable tList 2520001 2520044 3 (0) "zip7"
Prelude.False
azipWith4
= T.mkVariable tList 2550001 2570029 3 (5) "zipWith4"
Prelude.False
azipWith5
= T.mkVariable tList 2610001 2630029 3 (6) "zipWith5"
Prelude.False
azipWith6
= T.mkVariable tList 2670001 2690029 3 (7) "zipWith6"
Prelude.False
azipWith7
= T.mkVariable tList 2730001 2750029 3 (8) "zipWith7"
Prelude.False
(+\\)
= T.mkVariable tList 630001 630046 20 (0) "\\\\"
Prelude.False
c108v34v108v57ys
= T.mkVariable tList 1080034 1080057 3 (0) "ys"
Prelude.True
c108v34v108v57zs
= T.mkVariable tList 1080034 1080057 3 (0) "zs"
Prelude.True
c133v34v133v49s'
= T.mkVariable tList 1330034 1330049 3 (0) "s'"
Prelude.True
c134v34v134v61s''
= T.mkVariable tList 1340034 1340061 3 (0) "s''"
Prelude.True
c133v34v133v49y
= T.mkVariable tList 1330034 1330049 3 (0) "y"
Prelude.True
c134v34v134v61ys
= T.mkVariable tList 1340034 1340061 3 (0) "ys"
Prelude.True
c140v34v140v60s'
= T.mkVariable tList 1400034 1400060 3 (0) "s'"
Prelude.True
c139v34v139v50s''
= T.mkVariable tList 1390034 1390050 3 (0) "s''"
Prelude.True
c139v34v139v50y
= T.mkVariable tList 1390034 1390050 3 (0) "y"
Prelude.True
c140v34v140v60ys
= T.mkVariable tList 1400034 1400060 3 (0) "ys"
Prelude.True
c162v5v164v46ascending
= T.mkVariable tList 1620005 1640046 3 (3)
"ascending"
Prelude.True
c158v5v160v46descending
= T.mkVariable tList 1580005 1600046 3 (3)
"descending"
Prelude.True
c172v5v176v28merge
= T.mkVariable tList 1720005 1760028 3 (2) "merge"
Prelude.True
c166v5v167v43mergeAll
= T.mkVariable tList 1660005 1670043 3 (1) "mergeAll"
Prelude.True
c169v5v170v28mergePairs
= T.mkVariable tList 1690005 1700028 3 (1)
"mergePairs"
Prelude.True
c153v5v156v23sequences
= T.mkVariable tList 1530005 1560023 3 (1)
"sequences"
Prelude.True
c192v28v196v0max
= T.mkVariable tList 1920028 1960000 3 (2) "max"
Prelude.True
c200v28v204v0min
= T.mkVariable tList 2000028 2040000 3 (2) "min"
Prelude.True
c228v14v228v50xs'
= T.mkVariable tList 2280014 2280050 3 (0) "xs'"
Prelude.True
c228v14v228v50xs''
= T.mkVariable tList 2280014 2280050 3 (0) "xs''"
Prelude.True
p = T.mkRoot
tList = T.mkModule "List" "List.hs" Prelude.False | null | https://raw.githubusercontent.com/OlafChitil/hat/8840a480c076f9f01e58ce24b346850169498be2/Hat/List.hs | haskell | module Hat.List
(gelemIndex, aelemIndex, helemIndex, gelemIndices,
aelemIndices, helemIndices, gfind, afind, hfind,
gfindIndex, afindIndex, hfindIndex, gfindIndices,
afindIndices, hfindIndices, gnub, gnubBy, anubBy,
hnubBy, gdelete, gdeleteBy, adeleteBy, hdeleteBy,
(!\\), gdeleteFirstsBy, adeleteFirstsBy,
hdeleteFirstsBy, gunion, gunionBy, aunionBy,
hunionBy, gintersect, gintersectBy, aintersectBy,
hintersectBy, gintersperse, aintersperse,
hintersperse, gtranspose, atranspose, htranspose,
gpartition, apartition, hpartition, ggroup, ggroupBy,
agroupBy, hgroupBy, ginits, ainits, hinits, gtails,
atails, htails, gisPrefixOf, aisPrefixOf,
hisPrefixOf, gisSuffixOf, aisSuffixOf, hisSuffixOf,
gmapAccumL, amapAccumL, hmapAccumL, gmapAccumR,
amapAccumR, hmapAccumR, gsort, gsortBy, asortBy,
hsortBy, ginsert, ginsertBy, ainsertBy, hinsertBy,
gmaximumBy, amaximumBy, hmaximumBy, gminimumBy,
aminimumBy, hminimumBy, ggenericLength,
agenericLength, hgenericLength, ggenericTake,
agenericTake, hgenericTake, ggenericDrop,
agenericDrop, hgenericDrop, ggenericSplitAt,
agenericSplitAt, hgenericSplitAt, ggenericIndex,
agenericIndex, hgenericIndex, ggenericReplicate,
agenericReplicate, hgenericReplicate, gzip4, gzip5,
gzip6, gzip7, gzipWith4, azipWith4, hzipWith4,
gzipWith5, azipWith5, hzipWith5, gzipWith6,
azipWith6, hzipWith6, gzipWith7, azipWith7,
hzipWith7, gunzip4, gunzip5, gunzip6, gunzip7,
gunfoldr, aunfoldr, hunfoldr, gmap, amap, hmap,
(!++), (+++), (*++), gconcat, aconcat, hconcat,
gfilter, afilter, hfilter, ghead, ahead, hhead,
glast, alast, hlast, gtail, atail, htail, ginit,
ainit, hinit, gnull, anull, hnull, glength, alength,
hlength, (!!!), (+!!), (*!!), gfoldl, afoldl, hfoldl,
gfoldl1, afoldl1, hfoldl1, gscanl, ascanl, hscanl,
gscanl1, ascanl1, hscanl1, gfoldr, afoldr, hfoldr,
gfoldr1, afoldr1, hfoldr1, gscanr, ascanr, hscanr,
gscanr1, ascanr1, hscanr1, giterate, aiterate,
hiterate, grepeat, arepeat, hrepeat, greplicate,
areplicate, hreplicate, gcycle, acycle, hcycle,
gtake, atake, htake, gdrop, adrop, hdrop, gsplitAt,
asplitAt, hsplitAt, gtakeWhile, atakeWhile,
htakeWhile, gdropWhile, adropWhile, hdropWhile,
gspan, aspan, hspan, gbreak, abreak, hbreak, glines,
alines, hlines, gwords, awords, hwords, gunlines,
gunwords, aunwords, hunwords, greverse, gand, gor,
gany, aany, hany, gall, aall, hall, gelem, aelem,
helem, gnotElem, anotElem, hnotElem, glookup,
alookup, hlookup, gsum, gproduct, gmaximum, amaximum,
hmaximum, gminimum, aminimum, hminimum, gconcatMap,
aconcatMap, hconcatMap, gzip, gzip3, gzipWith,
azipWith, hzipWith, gzipWith3, azipWith3, hzipWith3,
gunzip, gunzip3)
where
import qualified Prelude
import qualified Hat.Hat as T
import qualified Hat.PreludeBasic
import qualified Hat.PreludeBuiltinTypes
import Hat.Prelude
import Hat.Maybe
(glistToMaybe, alistToMaybe, hlistToMaybe)
gelemIndex ::
(Eq a) =>
T.RefSrcPos ->
T.RefExp ->
T.R (T.Fun a (T.Fun (T.List a) (Maybe Int)))
helemIndex ::
(Eq a) =>
T.R a ->
T.RefExp -> T.R (T.Fun (T.List a) (Maybe Int))
gelemIndex pelemIndex p
= T.ufun1 aelemIndex pelemIndex p helemIndex
helemIndex fx p
= T.uwrapForward p
(hfindIndex
(T.uap1 T.mkNoSrcPos p ((!==) T.mkNoSrcPos p) fx)
p)
gelemIndices ::
(Eq a) =>
T.RefSrcPos ->
T.RefExp ->
T.R (T.Fun a (T.Fun (T.List a) (T.List Int)))
helemIndices ::
(Eq a) =>
T.R a ->
T.RefExp -> T.R (T.Fun (T.List a) (T.List Int))
gelemIndices pelemIndices p
= T.ufun1 aelemIndices pelemIndices p helemIndices
helemIndices fx p
= T.uap1 T.mkNoSrcPos p (gfindIndices T.mkNoSrcPos p)
(T.uap1 T.mkNoSrcPos p ((!==) T.mkNoSrcPos p) fx)
gfind ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.Fun a Bool) (T.Fun (T.List a) (Maybe a)))
hfind ::
T.R (T.Fun a Bool) ->
T.RefExp -> T.R (T.Fun (T.List a) (Maybe a))
gfind pfind p = T.ufun1 afind pfind p hfind
hfind fp p
= T.uap2 T.mkNoSrcPos p ((!.) T.mkNoSrcPos p)
(glistToMaybe T.mkNoSrcPos p)
(T.uap1 T.mkNoSrcPos p (gfilter T.mkNoSrcPos p) fp)
gfindIndex ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.Fun a Bool) (T.Fun (T.List a) (Maybe Int)))
hfindIndex ::
T.R (T.Fun a Bool) ->
T.RefExp -> T.R (T.Fun (T.List a) (Maybe Int))
gfindIndex pfindIndex p
= T.ufun1 afindIndex pfindIndex p hfindIndex
hfindIndex fp p
= T.uap2 T.mkNoSrcPos p ((!.) T.mkNoSrcPos p)
(glistToMaybe T.mkNoSrcPos p)
(T.uap1 T.mkNoSrcPos p (gfindIndices T.mkNoSrcPos p)
fp)
gfindIndices ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.Fun a Bool)
(T.Fun (T.List a) (T.List Int)))
hfindIndices ::
T.R (T.Fun a Bool) ->
T.R (T.List a) -> T.RefExp -> T.R (T.List Int)
gfindIndices pfindIndices p
= T.ufun2 afindIndices pfindIndices p hfindIndices
hfindIndices fp fxs p
= T.uap2 T.mkNoSrcPos p
((Hat.PreludeBasic.!>>=) T.mkNoSrcPos p)
(T.uap2 T.mkNoSrcPos p (gzip T.mkNoSrcPos p) fxs
(T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.genumFrom T.mkNoSrcPos p)
(T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.gfromInteger T.mkNoSrcPos p)
(T.conInteger T.mkNoSrcPos p (0)))))
(T.ufun1 T.mkDoLambda T.mkNoSrcPos p
(\ (T.R (T.Tuple2 fx fi) _) p ->
T.uap2 T.mkNoSrcPos p
((Hat.PreludeBasic.!>>) T.mkNoSrcPos p)
(T.uwrapForward p
(Hat.PreludeBasic.hguard
(T.uap1 T.mkNoSrcPos p fp fx)
p))
(T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.greturn T.mkNoSrcPos p)
fi)))
gnub ::
(Eq a) =>
T.RefSrcPos ->
T.RefExp -> T.R (T.Fun (T.List a) (T.List a))
snub :: (Eq a) => T.R (T.Fun (T.List a) (T.List a))
gnub pnub p = T.uconstUse pnub p snub
snub
= T.uconstDef p anub
(\ p ->
T.uap1 T.mkNoSrcPos p (gnubBy T.mkNoSrcPos p)
((!==) T.mkNoSrcPos p))
gnubBy ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.Fun a (T.Fun a Bool))
(T.Fun (T.List a) (T.List a)))
hnubBy ::
T.R (T.Fun a (T.Fun a Bool)) ->
T.R (T.List a) -> T.RefExp -> T.R (T.List a)
gnubBy pnubBy p = T.ufun2 anubBy pnubBy p hnubBy
hnubBy feq (T.R T.Nil _) p
= T.con0 T.mkNoSrcPos p T.Nil T.aNil
hnubBy feq (T.R (T.Cons fx fxs) _) p
= T.con2 T.mkNoSrcPos p T.Cons T.aCons fx
(T.uwrapForward p
(hnubBy feq
(T.uwrapForward p
(hfilter
(T.ufun1 T.mkLambda T.mkNoSrcPos p
(\ fy p ->
T.uwrapForward p
(hnot (T.uap2 T.mkNoSrcPos p feq fx fy) p)))
fxs
p))
p))
hnubBy _ _ p = T.fatal p
gdelete ::
(Eq a) =>
T.RefSrcPos ->
T.RefExp ->
T.R (T.Fun a (T.Fun (T.List a) (T.List a)))
sdelete ::
(Eq a) => T.R (T.Fun a (T.Fun (T.List a) (T.List a)))
gdelete pdelete p = T.uconstUse pdelete p sdelete
sdelete
= T.uconstDef p adelete
(\ p ->
T.uap1 T.mkNoSrcPos p (gdeleteBy T.mkNoSrcPos p)
((!==) T.mkNoSrcPos p))
gdeleteBy ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.Fun a (T.Fun a Bool))
(T.Fun a (T.Fun (T.List a) (T.List a))))
hdeleteBy ::
T.R (T.Fun a (T.Fun a Bool)) ->
T.R a -> T.R (T.List a) -> T.RefExp -> T.R (T.List a)
gdeleteBy pdeleteBy p
= T.ufun3 adeleteBy pdeleteBy p hdeleteBy
hdeleteBy feq fx (T.R T.Nil _) p
= T.con0 T.mkNoSrcPos p T.Nil T.aNil
hdeleteBy feq fx (T.R (T.Cons fy fys) _) p
= T.ucif p (T.uap2 T.mkNoSrcPos p feq fx fy)
(T.projection T.mkNoSrcPos p fys)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fy
(T.uwrapForward p (hdeleteBy feq fx fys p)))
hdeleteBy _ _ _ p = T.fatal p
(!\\) ::
(Eq a) =>
T.RefSrcPos ->
T.RefExp ->
T.R (T.Fun (T.List a) (T.Fun (T.List a) (T.List a)))
(|\\) ::
(Eq a) =>
T.R (T.Fun (T.List a) (T.Fun (T.List a) (T.List a)))
(%\\) !\\ p = T.uconstUse (%\\) p (|\\)
(|\\)
= T.uconstDef p (+\\)
(\ p ->
T.uap1 T.mkNoSrcPos p (gfoldl T.mkNoSrcPos p)
(T.uap1 T.mkNoSrcPos p (gflip T.mkNoSrcPos p)
(gdelete T.mkNoSrcPos p)))
gdeleteFirstsBy ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.Fun a (T.Fun a Bool))
(T.Fun (T.List a) (T.Fun (T.List a) (T.List a))))
hdeleteFirstsBy ::
T.R (T.Fun a (T.Fun a Bool)) ->
T.RefExp ->
T.R (T.Fun (T.List a) (T.Fun (T.List a) (T.List a)))
gdeleteFirstsBy pdeleteFirstsBy p
= T.ufun1 adeleteFirstsBy pdeleteFirstsBy p
hdeleteFirstsBy
hdeleteFirstsBy feq p
= T.uap1 T.mkNoSrcPos p (gfoldl T.mkNoSrcPos p)
(T.uap1 T.mkNoSrcPos p (gflip T.mkNoSrcPos p)
(T.uap1 T.mkNoSrcPos p (gdeleteBy T.mkNoSrcPos p)
feq))
gunion ::
(Eq a) =>
T.RefSrcPos ->
T.RefExp ->
T.R (T.Fun (T.List a) (T.Fun (T.List a) (T.List a)))
sunion ::
(Eq a) =>
T.R (T.Fun (T.List a) (T.Fun (T.List a) (T.List a)))
gunion punion p = T.uconstUse punion p sunion
sunion
= T.uconstDef p aunion
(\ p ->
T.uap1 T.mkNoSrcPos p (gunionBy T.mkNoSrcPos p)
((!==) T.mkNoSrcPos p))
gunionBy ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.Fun a (T.Fun a Bool))
(T.Fun (T.List a) (T.Fun (T.List a) (T.List a))))
hunionBy ::
T.R (T.Fun a (T.Fun a Bool)) ->
T.R (T.List a) ->
T.R (T.List a) -> T.RefExp -> T.R (T.List a)
gunionBy punionBy p
= T.ufun3 aunionBy punionBy p hunionBy
hunionBy feq fxs fys p
= T.uwrapForward p
((*++) fxs
(T.uap2 T.mkNoSrcPos p
(T.uwrapForward p (hdeleteFirstsBy feq p))
(T.uwrapForward p (hnubBy feq fys p))
fxs)
p)
gintersect ::
(Eq a) =>
T.RefSrcPos ->
T.RefExp ->
T.R (T.Fun (T.List a) (T.Fun (T.List a) (T.List a)))
sintersect ::
(Eq a) =>
T.R (T.Fun (T.List a) (T.Fun (T.List a) (T.List a)))
gintersect pintersect p
= T.uconstUse pintersect p sintersect
sintersect
= T.uconstDef p aintersect
(\ p ->
T.uap1 T.mkNoSrcPos p (gintersectBy T.mkNoSrcPos p)
((!==) T.mkNoSrcPos p))
gintersectBy ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.Fun a (T.Fun a Bool))
(T.Fun (T.List a) (T.Fun (T.List a) (T.List a))))
hintersectBy ::
T.R (T.Fun a (T.Fun a Bool)) ->
T.R (T.List a) ->
T.R (T.List a) -> T.RefExp -> T.R (T.List a)
gintersectBy pintersectBy p
= T.ufun3 aintersectBy pintersectBy p hintersectBy
hintersectBy feq fxs fys p
= T.uap2 T.mkNoSrcPos p
((Hat.PreludeBasic.!>>=) T.mkNoSrcPos p)
fxs
(T.ufun1 T.mkDoLambda T.mkNoSrcPos p
(\ fx p ->
T.uap2 T.mkNoSrcPos p
((Hat.PreludeBasic.!>>) T.mkNoSrcPos p)
(T.uwrapForward p
(Hat.PreludeBasic.hguard
(T.uap1 T.mkNoSrcPos p
(T.uwrapForward p
(hany (T.uap1 T.mkNoSrcPos p feq fx) p))
fys)
p))
(T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.greturn T.mkNoSrcPos p)
fx)))
gintersperse ::
T.RefSrcPos ->
T.RefExp ->
T.R (T.Fun a (T.Fun (T.List a) (T.List a)))
hintersperse ::
T.R a -> T.R (T.List a) -> T.RefExp -> T.R (T.List a)
gintersperse pintersperse p
= T.ufun2 aintersperse pintersperse p hintersperse
hintersperse fsep (T.R T.Nil _) p
= T.con0 T.mkNoSrcPos p T.Nil T.aNil
hintersperse fsep (T.R (T.Cons fx (T.R T.Nil _)) _) p
= T.fromExpList T.mkNoSrcPos p [fx]
hintersperse fsep (T.R (T.Cons fx fxs) _) p
= T.con2 T.mkNoSrcPos p T.Cons T.aCons fx
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fsep
(T.uwrapForward p (hintersperse fsep fxs p)))
hintersperse _ _ p = T.fatal p
gtranspose ::
T.RefSrcPos ->
T.RefExp ->
T.R (T.Fun (T.List (T.List a)) (T.List (T.List a)))
htranspose ::
T.R (T.List (T.List a)) ->
T.RefExp -> T.R (T.List (T.List a))
gtranspose ptranspose p
= T.ufun1 atranspose ptranspose p htranspose
htranspose (T.R T.Nil _) p
= T.con0 T.mkNoSrcPos p T.Nil T.aNil
htranspose (T.R (T.Cons (T.R T.Nil _) fxss) _) p
= T.uwrapForward p (htranspose fxss p)
htranspose
(T.R (T.Cons (T.R (T.Cons fx fxs) _) fxss) _) p
= T.con2 T.mkNoSrcPos p T.Cons T.aCons
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fx
(T.uap2 T.mkNoSrcPos p
((Hat.PreludeBasic.!>>=) T.mkNoSrcPos p)
fxss
(T.ufun1 T.mkDoLambda T.mkNoSrcPos p
(\ fv93v38v93v45v1 p ->
T.uccase T.mkNoSrcPos p
(let v93v38v93v45v1 (T.R (T.Cons fh ft) _) p
= T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.greturn T.mkNoSrcPos p)
fh
v93v38v93v45v1 _ p
= T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.gfail T.mkNoSrcPos p)
(T.fromLitString T.mkNoSrcPos p
"pattern-match failure in do-expression")
in v93v38v93v45v1)
fv93v38v93v45v1))))
(T.uwrapForward p
(htranspose
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fxs
(T.uap2 T.mkNoSrcPos p
((Hat.PreludeBasic.!>>=) T.mkNoSrcPos p)
fxss
(T.ufun1 T.mkDoLambda T.mkNoSrcPos p
(\ fv94v49v94v56v1 p ->
T.uccase T.mkNoSrcPos p
(let v94v49v94v56v1 (T.R (T.Cons fh ft) _) p
= T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.greturn T.mkNoSrcPos p)
ft
v94v49v94v56v1 _ p
= T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.gfail T.mkNoSrcPos p)
(T.fromLitString T.mkNoSrcPos p
"pattern-match failure in do-expression")
in v94v49v94v56v1)
fv94v49v94v56v1))))
p))
htranspose _ p = T.fatal p
gpartition ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.Fun a Bool)
(T.Fun (T.List a) (T.Tuple2 (T.List a) (T.List a))))
hpartition ::
T.R (T.Fun a Bool) ->
T.R (T.List a) ->
T.RefExp -> T.R (T.Tuple2 (T.List a) (T.List a))
gpartition ppartition p
= T.ufun2 apartition ppartition p hpartition
hpartition fp fxs p
= T.con2 T.mkNoSrcPos p T.Tuple2 T.aTuple2
(T.uwrapForward p (hfilter fp fxs p))
(T.uwrapForward p
(hfilter
(T.uap2 T.mkNoSrcPos p ((!.) T.mkNoSrcPos p)
(gnot T.mkNoSrcPos p)
fp)
fxs
p))
ggroup ::
(Eq a) =>
T.RefSrcPos ->
T.RefExp ->
T.R (T.Fun (T.List a) (T.List (T.List a)))
sgroup ::
(Eq a) => T.R (T.Fun (T.List a) (T.List (T.List a)))
ggroup pgroup p = T.uconstUse pgroup p sgroup
sgroup
= T.uconstDef p agroup
(\ p ->
T.uap1 T.mkNoSrcPos p (ggroupBy T.mkNoSrcPos p)
((!==) T.mkNoSrcPos p))
ggroupBy ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.Fun a (T.Fun a Bool))
(T.Fun (T.List a) (T.List (T.List a))))
hgroupBy ::
T.R (T.Fun a (T.Fun a Bool)) ->
T.R (T.List a) -> T.RefExp -> T.R (T.List (T.List a))
ggroupBy pgroupBy p
= T.ufun2 agroupBy pgroupBy p hgroupBy
hgroupBy feq (T.R T.Nil _) p
= T.con0 T.mkNoSrcPos p T.Nil T.aNil
hgroupBy feq (T.R (T.Cons fx fxs) _) p
= T.con2 T.mkNoSrcPos p T.Cons T.aCons
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fx
(gys T.mkNoSrcPos p))
(T.uwrapForward p
(hgroupBy feq (gzs T.mkNoSrcPos p) p))
where gys pys p = T.uconstUse pys p sys
gzs pzs p = T.uconstUse pzs p szs
sys
= T.uconstDef p c108v34v108v57ys
(\ _ ->
case j108v34v108v57ys of
(kys, fys, fzs) -> fys)
szs
= T.uconstDef p c108v34v108v57zs
(\ _ ->
case j108v34v108v57ys of
(kys, fys, fzs) -> fzs)
j108v34v108v57ys
= case
T.uwrapForward p
(hspan (T.uap1 T.mkNoSrcPos p feq fx) fxs p)
of
T.R (T.Tuple2 fys fzs) kys -> (kys, fys, fzs)
_ -> T.fatal p
hgroupBy _ _ p = T.fatal p
ginits ::
T.RefSrcPos ->
T.RefExp ->
T.R (T.Fun (T.List a) (T.List (T.List a)))
hinits ::
T.R (T.List a) -> T.RefExp -> T.R (T.List (T.List a))
ginits pinits p = T.ufun1 ainits pinits p hinits
hinits (T.R T.Nil _) p
= T.fromExpList T.mkNoSrcPos p
[T.con0 T.mkNoSrcPos p T.Nil T.aNil]
hinits (T.R (T.Cons fx fxs) _) p
= T.uwrapForward p
((*++)
(T.fromExpList T.mkNoSrcPos p
[T.con0 T.mkNoSrcPos p T.Nil T.aNil])
(T.uwrapForward p
(hmap (T.pa1 T.Cons T.cn1 T.mkNoSrcPos p T.aCons fx)
(T.uwrapForward p (hinits fxs p))
p))
p)
hinits _ p = T.fatal p
gtails ::
T.RefSrcPos ->
T.RefExp ->
T.R (T.Fun (T.List a) (T.List (T.List a)))
htails ::
T.R (T.List a) -> T.RefExp -> T.R (T.List (T.List a))
gtails ptails p = T.ufun1 atails ptails p htails
htails (T.R T.Nil _) p
= T.fromExpList T.mkNoSrcPos p
[T.con0 T.mkNoSrcPos p T.Nil T.aNil]
htails fxxs@(T.R (T.Cons _ fxs) _) p
= T.con2 T.mkNoSrcPos p T.Cons T.aCons fxxs
(T.uwrapForward p (htails fxs p))
htails _ p = T.fatal p
gisPrefixOf ::
(Eq a) =>
T.RefSrcPos ->
T.RefExp ->
T.R (T.Fun (T.List a) (T.Fun (T.List a) Bool))
hisPrefixOf ::
(Eq a) =>
T.R (T.List a) ->
T.R (T.List a) -> T.RefExp -> T.R Bool
gisPrefixOf pisPrefixOf p
= T.ufun2 aisPrefixOf pisPrefixOf p hisPrefixOf
hisPrefixOf (T.R T.Nil _) _ p
= T.con0 T.mkNoSrcPos p True aTrue
hisPrefixOf _ (T.R T.Nil _) p
= T.con0 T.mkNoSrcPos p False aFalse
hisPrefixOf (T.R (T.Cons fx fxs) _)
(T.R (T.Cons fy fys) _) p
= T.uwrapForward p
((*&&)
(T.uap2 T.mkNoSrcPos p ((!==) T.mkNoSrcPos p) fx fy)
(T.uwrapForward p (hisPrefixOf fxs fys p))
p)
hisPrefixOf _ _ p = T.fatal p
gisSuffixOf ::
(Eq a) =>
T.RefSrcPos ->
T.RefExp ->
T.R (T.Fun (T.List a) (T.Fun (T.List a) Bool))
hisSuffixOf ::
(Eq a) =>
T.R (T.List a) ->
T.R (T.List a) -> T.RefExp -> T.R Bool
gisSuffixOf pisSuffixOf p
= T.ufun2 aisSuffixOf pisSuffixOf p hisSuffixOf
hisSuffixOf fx fy p
= T.uwrapForward p
(hisPrefixOf
(T.uap1 T.mkNoSrcPos p (greverse T.mkNoSrcPos p) fx)
(T.uap1 T.mkNoSrcPos p (greverse T.mkNoSrcPos p) fy)
p)
gmapAccumL ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.Fun a (T.Fun b (T.Tuple2 a c)))
(T.Fun a (T.Fun (T.List b) (T.Tuple2 a (T.List c)))))
hmapAccumL ::
T.R (T.Fun a (T.Fun b (T.Tuple2 a c))) ->
T.R a ->
T.R (T.List b) ->
T.RefExp -> T.R (T.Tuple2 a (T.List c))
gmapAccumL pmapAccumL p
= T.ufun3 amapAccumL pmapAccumL p hmapAccumL
hmapAccumL ff fs (T.R T.Nil _) p
= T.con2 T.mkNoSrcPos p T.Tuple2 T.aTuple2 fs
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
hmapAccumL ff fs (T.R (T.Cons fx fxs) _) p
= T.con2 T.mkNoSrcPos p T.Tuple2 T.aTuple2
(gs'' T.mkNoSrcPos p)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons
(gy T.mkNoSrcPos p)
(gys T.mkNoSrcPos p))
where gs' ps' p = T.uconstUse ps' p ss'
gy py p = T.uconstUse py p sy
ss'
= T.uconstDef p c133v34v133v49s'
(\ _ ->
case j133v34v133v49s' of
(ks', fs', fy) -> fs')
sy
= T.uconstDef p c133v34v133v49y
(\ _ ->
case j133v34v133v49s' of
(ks', fs', fy) -> fy)
j133v34v133v49s'
= case T.uap2 T.mkNoSrcPos p ff fs fx of
T.R (T.Tuple2 fs' fy) ks' -> (ks', fs', fy)
_ -> T.fatal p
gs'' ps'' p = T.uconstUse ps'' p ss''
gys pys p = T.uconstUse pys p sys
ss''
= T.uconstDef p c134v34v134v61s''
(\ _ ->
case j134v34v134v61s'' of
(ks'', fs'', fys) -> fs'')
sys
= T.uconstDef p c134v34v134v61ys
(\ _ ->
case j134v34v134v61s'' of
(ks'', fs'', fys) -> fys)
j134v34v134v61s''
= case
T.uwrapForward p
(hmapAccumL ff (gs' T.mkNoSrcPos p) fxs p)
of
T.R (T.Tuple2 fs'' fys) ks'' -> (ks'', fs'', fys)
_ -> T.fatal p
hmapAccumL _ _ _ p = T.fatal p
gmapAccumR ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.Fun a (T.Fun b (T.Tuple2 a c)))
(T.Fun a (T.Fun (T.List b) (T.Tuple2 a (T.List c)))))
hmapAccumR ::
T.R (T.Fun a (T.Fun b (T.Tuple2 a c))) ->
T.R a ->
T.R (T.List b) ->
T.RefExp -> T.R (T.Tuple2 a (T.List c))
gmapAccumR pmapAccumR p
= T.ufun3 amapAccumR pmapAccumR p hmapAccumR
hmapAccumR ff fs (T.R T.Nil _) p
= T.con2 T.mkNoSrcPos p T.Tuple2 T.aTuple2 fs
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
hmapAccumR ff fs (T.R (T.Cons fx fxs) _) p
= T.con2 T.mkNoSrcPos p T.Tuple2 T.aTuple2
(gs'' T.mkNoSrcPos p)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons
(gy T.mkNoSrcPos p)
(gys T.mkNoSrcPos p))
where gs'' ps'' p = T.uconstUse ps'' p ss''
gy py p = T.uconstUse py p sy
ss''
= T.uconstDef p c139v34v139v50s''
(\ _ ->
case j139v34v139v50s'' of
(ks'', fs'', fy) -> fs'')
sy
= T.uconstDef p c139v34v139v50y
(\ _ ->
case j139v34v139v50s'' of
(ks'', fs'', fy) -> fy)
j139v34v139v50s''
= case
T.uap2 T.mkNoSrcPos p ff (gs' T.mkNoSrcPos p) fx of
T.R (T.Tuple2 fs'' fy) ks'' -> (ks'', fs'', fy)
_ -> T.fatal p
gs' ps' p = T.uconstUse ps' p ss'
gys pys p = T.uconstUse pys p sys
ss'
= T.uconstDef p c140v34v140v60s'
(\ _ ->
case j140v34v140v60s' of
(ks', fs', fys) -> fs')
sys
= T.uconstDef p c140v34v140v60ys
(\ _ ->
case j140v34v140v60s' of
(ks', fs', fys) -> fys)
j140v34v140v60s'
= case T.uwrapForward p (hmapAccumR ff fs fxs p) of
T.R (T.Tuple2 fs' fys) ks' -> (ks', fs', fys)
_ -> T.fatal p
hmapAccumR _ _ _ p = T.fatal p
gunfoldr ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.Fun b (Maybe (T.Tuple2 a b)))
(T.Fun b (T.List a)))
hunfoldr ::
T.R (T.Fun b (Maybe (T.Tuple2 a b))) ->
T.R b -> T.RefExp -> T.R (T.List a)
gunfoldr punfoldr p
= T.ufun2 aunfoldr punfoldr p hunfoldr
hunfoldr ff fb p
= T.uccase T.mkNoSrcPos p
(let v143v27v147v0v1 (T.R Nothing _) p
= T.con0 T.mkNoSrcPos p T.Nil T.aNil
v143v27v147v0v1
(T.R (Just (T.R (T.Tuple2 fa fb) _)) _) p
= T.con2 T.mkNoSrcPos p T.Cons T.aCons fa
(T.uwrapForward p (hunfoldr ff fb p))
v143v27v147v0v1 _ p = T.fatal p
in v143v27v147v0v1)
(T.uap1 T.mkNoSrcPos p ff fb)
gsort ::
(Ord a) =>
T.RefSrcPos ->
T.RefExp -> T.R (T.Fun (T.List a) (T.List a))
ssort :: (Ord a) => T.R (T.Fun (T.List a) (T.List a))
gsort psort p = T.uconstUse psort p ssort
ssort
= T.uconstDef p asort
(\ p ->
T.uwrapForward p
(hsortBy (gcompare T.mkNoSrcPos p) p))
gsortBy ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.Fun a (T.Fun a Ordering))
(T.Fun (T.List a) (T.List a)))
hsortBy ::
T.R (T.Fun a (T.Fun a Ordering)) ->
T.RefExp -> T.R (T.Fun (T.List a) (T.List a))
gsortBy psortBy p = T.ufun1 asortBy psortBy p hsortBy
hsortBy fcmp p
= T.uap2 T.mkNoSrcPos p ((!.) T.mkNoSrcPos p)
(gmergeAll T.mkNoSrcPos p)
(gsequences T.mkNoSrcPos p)
where gsequences psequences p
= T.ufun1 c153v5v156v23sequences psequences p
hsequences
asequences = c153v5v156v23sequences
hsequences
(T.R (T.Cons fa (T.R (T.Cons fb fxs) _)) _) p
= T.ucguard
(T.uap2 T.mkNoSrcPos p ((!==) T.mkNoSrcPos p)
(T.uap2 T.mkNoSrcPos p fcmp fa fb)
(T.con0 T.mkNoSrcPos p GT aGT))
(T.uwrapForward p
(hdescending fb (T.fromExpList T.mkNoSrcPos p [fa])
fxs
p))
(T.ucguard (gotherwise T.mkNoSrcPos p)
(T.uwrapForward p
(hascending fb
(T.pa1 T.Cons T.cn1 T.mkNoSrcPos p T.aCons fa)
fxs
p))
(T.fatal p))
hsequences fxs p = T.fromExpList T.mkNoSrcPos p [fxs]
gdescending pdescending p
= T.ufun3 c158v5v160v46descending pdescending p
hdescending
adescending = c158v5v160v46descending
hdescending fa fas
z3descending@(T.R (T.Cons fb fbs) _) p
= T.ucguard
(T.uap2 T.mkNoSrcPos p ((!==) T.mkNoSrcPos p)
(T.uap2 T.mkNoSrcPos p fcmp fa fb)
(T.con0 T.mkNoSrcPos p GT aGT))
(T.uwrapForward p
(hdescending fb
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fa fas)
fbs
p))
(y1descending fa fas z3descending p)
hdescending fa fas z3descending p
= y1descending fa fas z3descending p
y1descending fa fas fbs p
= T.con2 T.mkNoSrcPos p T.Cons T.aCons
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fa fas)
(T.uwrapForward p (hsequences fbs p))
gascending pascending p
= T.ufun3 c162v5v164v46ascending pascending p
hascending
aascending = c162v5v164v46ascending
hascending fa fas z3ascending@(T.R (T.Cons fb fbs) _)
p
= T.ucguard
(T.uap2 T.mkNoSrcPos p ((!/=) T.mkNoSrcPos p)
(T.uap2 T.mkNoSrcPos p fcmp fa fb)
(T.con0 T.mkNoSrcPos p GT aGT))
(T.uwrapForward p
(hascending fb
(T.ufun1 T.mkLambda T.mkNoSrcPos p
(\ fys p ->
T.uap1 T.mkNoSrcPos p
(T.projection T.mkNoSrcPos p fas)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fa fys)))
fbs
p))
(y1ascending fa fas z3ascending p)
hascending fa fas z3ascending p
= y1ascending fa fas z3ascending p
y1ascending fa fas fbs p
= T.con2 T.mkNoSrcPos p T.Cons T.aCons
(T.uap1 T.mkNoSrcPos p fas
(T.fromExpList T.mkNoSrcPos p [fa]))
(T.uwrapForward p (hsequences fbs p))
gmergeAll pmergeAll p
= T.ufun1 c166v5v167v43mergeAll pmergeAll p hmergeAll
amergeAll = c166v5v167v43mergeAll
hmergeAll (T.R (T.Cons fx (T.R T.Nil _)) _) p
= T.projection T.mkNoSrcPos p fx
hmergeAll fxs p
= T.uwrapForward p
(hmergeAll (T.uwrapForward p (hmergePairs fxs p)) p)
gmergePairs pmergePairs p
= T.ufun1 c169v5v170v28mergePairs pmergePairs p
hmergePairs
amergePairs = c169v5v170v28mergePairs
hmergePairs
(T.R (T.Cons fa (T.R (T.Cons fb fxs) _)) _) p
= T.con2 T.mkNoSrcPos p T.Cons T.aCons
(T.uwrapForward p (hmerge fa fb p))
(T.uwrapForward p (hmergePairs fxs p))
hmergePairs fxs p = T.projection T.mkNoSrcPos p fxs
gmerge pmerge p
= T.ufun2 c172v5v176v28merge pmerge p hmerge
amerge = c172v5v176v28merge
hmerge fas@(T.R (T.Cons fa fas') _)
fbs@(T.R (T.Cons fb fbs') _) p
= T.ucguard
(T.uap2 T.mkNoSrcPos p ((!==) T.mkNoSrcPos p)
(T.uap2 T.mkNoSrcPos p fcmp fa fb)
(T.con0 T.mkNoSrcPos p GT aGT))
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fb
(T.uwrapForward p (hmerge fas fbs' p)))
(T.ucguard (gotherwise T.mkNoSrcPos p)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fa
(T.uwrapForward p (hmerge fas' fbs p)))
(T.fatal p))
hmerge (T.R T.Nil _) fbs p
= T.projection T.mkNoSrcPos p fbs
hmerge fas (T.R T.Nil _) p
= T.projection T.mkNoSrcPos p fas
hmerge _ _ p = T.fatal p
ginsert ::
(Ord a) =>
T.RefSrcPos ->
T.RefExp ->
T.R (T.Fun a (T.Fun (T.List a) (T.List a)))
sinsert ::
(Ord a) =>
T.R (T.Fun a (T.Fun (T.List a) (T.List a)))
ginsert pinsert p = T.uconstUse pinsert p sinsert
sinsert
= T.uconstDef p ainsert
(\ p ->
T.uap1 T.mkNoSrcPos p (ginsertBy T.mkNoSrcPos p)
(gcompare T.mkNoSrcPos p))
ginsertBy ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.Fun a (T.Fun a Ordering))
(T.Fun a (T.Fun (T.List a) (T.List a))))
hinsertBy ::
T.R (T.Fun a (T.Fun a Ordering)) ->
T.R a -> T.R (T.List a) -> T.RefExp -> T.R (T.List a)
ginsertBy pinsertBy p
= T.ufun3 ainsertBy pinsertBy p hinsertBy
hinsertBy fcmp fx (T.R T.Nil _) p
= T.fromExpList T.mkNoSrcPos p [fx]
hinsertBy fcmp fx fys@(T.R (T.Cons fy fys') _) p
= T.uccase T.mkNoSrcPos p
(let v184v28v188v0v1 (T.R GT _) p
= T.con2 T.mkNoSrcPos p T.Cons T.aCons fy
(T.uwrapForward p (hinsertBy fcmp fx fys' p))
v184v28v188v0v1 _ p
= T.con2 T.mkNoSrcPos p T.Cons T.aCons fx fys
in v184v28v188v0v1)
(T.uap2 T.mkNoSrcPos p fcmp fx fy)
hinsertBy _ _ _ p = T.fatal p
gmaximumBy ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.Fun a (T.Fun a Ordering))
(T.Fun (T.List a) a))
hmaximumBy ::
T.R (T.Fun a (T.Fun a Ordering)) ->
T.R (T.List a) -> T.RefExp -> T.R a
gmaximumBy pmaximumBy p
= T.ufun2 amaximumBy pmaximumBy p hmaximumBy
hmaximumBy fcmp (T.R T.Nil _) p
= T.uwrapForward p
(herror
(T.fromLitString T.mkNoSrcPos p
"List.maximumBy: empty list")
p)
hmaximumBy fcmp fxs p
= T.uwrapForward p
(hfoldl1 (gmax T.mkNoSrcPos p) fxs p)
where gmax pmax p
= T.ufun2 c192v28v196v0max pmax p hmax
amax = c192v28v196v0max
hmax fx fy p
= T.uccase T.mkNoSrcPos p
(let v192v38v196v0v1 (T.R GT _) p
= T.projection T.mkNoSrcPos p fx
v192v38v196v0v1 _ p = T.projection T.mkNoSrcPos p fy
in v192v38v196v0v1)
(T.uap2 T.mkNoSrcPos p fcmp fx fy)
gminimumBy ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.Fun a (T.Fun a Ordering))
(T.Fun (T.List a) a))
hminimumBy ::
T.R (T.Fun a (T.Fun a Ordering)) ->
T.R (T.List a) -> T.RefExp -> T.R a
gminimumBy pminimumBy p
= T.ufun2 aminimumBy pminimumBy p hminimumBy
hminimumBy fcmp (T.R T.Nil _) p
= T.uwrapForward p
(herror
(T.fromLitString T.mkNoSrcPos p
"List.minimumBy: empty list")
p)
hminimumBy fcmp fxs p
= T.uwrapForward p
(hfoldl1 (gmin T.mkNoSrcPos p) fxs p)
where gmin pmin p
= T.ufun2 c200v28v204v0min pmin p hmin
amin = c200v28v204v0min
hmin fx fy p
= T.uccase T.mkNoSrcPos p
(let v200v38v204v0v1 (T.R GT _) p
= T.projection T.mkNoSrcPos p fy
v200v38v204v0v1 _ p = T.projection T.mkNoSrcPos p fx
in v200v38v204v0v1)
(T.uap2 T.mkNoSrcPos p fcmp fx fy)
ggenericLength ::
(Integral a) =>
T.RefSrcPos -> T.RefExp -> T.R (T.Fun (T.List b) a)
hgenericLength ::
(Integral a) => T.R (T.List b) -> T.RefExp -> T.R a
ggenericLength pgenericLength p
= T.ufun1 agenericLength pgenericLength p
hgenericLength
hgenericLength (T.R T.Nil _) p
= T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.gfromInteger T.mkNoSrcPos p)
(T.conInteger T.mkNoSrcPos p (0))
hgenericLength (T.R (T.Cons fx fxs) _) p
= T.uap2 T.mkNoSrcPos p ((!+) T.mkNoSrcPos p)
(T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.gfromInteger T.mkNoSrcPos p)
(T.conInteger T.mkNoSrcPos p (1)))
(T.uwrapForward p (hgenericLength fxs p))
hgenericLength _ p = T.fatal p
ggenericTake ::
(Integral a) =>
T.RefSrcPos ->
T.RefExp ->
T.R (T.Fun a (T.Fun (T.List b) (T.List b)))
hgenericTake ::
(Integral a) =>
T.R a -> T.R (T.List b) -> T.RefExp -> T.R (T.List b)
ggenericTake pgenericTake p
= T.ufun2 agenericTake pgenericTake p hgenericTake
hgenericTake _ (T.R T.Nil _) p
= T.con0 T.mkNoSrcPos p T.Nil T.aNil
hgenericTake fv210v13v210v13n v210v15v210v15n p
= T.ucguard
(T.uap2 T.mkNoSrcPos p
((Hat.PreludeBasic.!==) T.mkNoSrcPos p)
fv210v13v210v13n
(T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.gfromInteger T.mkNoSrcPos p)
(T.conInteger T.mkNoSrcPos p (0))))
(h210v1v210v29n v210v15v210v15n p)
(y1genericTake fv210v13v210v13n v210v15v210v15n p)
where h210v1v210v29n _ p
= T.con0 T.mkNoSrcPos p T.Nil T.aNil
h210v1v210v29n _ p
= y1genericTake fv210v13v210v13n v210v15v210v15n p
hgenericTake fv210v13v210v13n v210v15v210v15n p
= y1genericTake fv210v13v210v13n v210v15v210v15n p
y1genericTake fn (T.R (T.Cons fx fxs) _) p
= T.ucguard
(T.uap2 T.mkNoSrcPos p ((!>) T.mkNoSrcPos p) fn
(T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.gfromInteger T.mkNoSrcPos p)
(T.conInteger T.mkNoSrcPos p (0))))
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fx
(T.uwrapForward p
(hgenericTake
(T.uap2 T.mkNoSrcPos p ((!-) T.mkNoSrcPos p) fn
(T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.gfromInteger T.mkNoSrcPos p)
(T.conInteger T.mkNoSrcPos p (1))))
fxs
p)))
(T.ucguard (gotherwise T.mkNoSrcPos p)
(T.uwrapForward p
(herror
(T.fromLitString T.mkNoSrcPos p
"List.genericTake: negative argument")
p))
(T.fatal p))
y1genericTake _ _ p = T.fatal p
ggenericDrop ::
(Integral a) =>
T.RefSrcPos ->
T.RefExp ->
T.R (T.Fun a (T.Fun (T.List b) (T.List b)))
hgenericDrop ::
(Integral a) =>
T.R a -> T.R (T.List b) -> T.RefExp -> T.R (T.List b)
ggenericDrop pgenericDrop p
= T.ufun2 agenericDrop pgenericDrop p hgenericDrop
hgenericDrop fv216v13v216v13n fxs p
= T.ucguard
(T.uap2 T.mkNoSrcPos p
((Hat.PreludeBasic.!==) T.mkNoSrcPos p)
fv216v13v216v13n
(T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.gfromInteger T.mkNoSrcPos p)
(T.conInteger T.mkNoSrcPos p (0))))
(h216v1v216v29n fxs p)
(y1genericDrop fv216v13v216v13n fxs p)
where h216v1v216v29n fxs p
= T.projection T.mkNoSrcPos p fxs
h216v1v216v29n _ p
= y1genericDrop fv216v13v216v13n fxs p
hgenericDrop fv216v13v216v13n fxs p
= y1genericDrop fv216v13v216v13n fxs p
y1genericDrop _ (T.R T.Nil _) p
= T.con0 T.mkNoSrcPos p T.Nil T.aNil
y1genericDrop fn (T.R (T.Cons _ fxs) _) p
= T.ucguard
(T.uap2 T.mkNoSrcPos p ((!>) T.mkNoSrcPos p) fn
(T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.gfromInteger T.mkNoSrcPos p)
(T.conInteger T.mkNoSrcPos p (0))))
(T.uwrapForward p
(hgenericDrop
(T.uap2 T.mkNoSrcPos p ((!-) T.mkNoSrcPos p) fn
(T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.gfromInteger T.mkNoSrcPos p)
(T.conInteger T.mkNoSrcPos p (1))))
fxs
p))
(T.ucguard (gotherwise T.mkNoSrcPos p)
(T.uwrapForward p
(herror
(T.fromLitString T.mkNoSrcPos p
"List.genericDrop: negative argument")
p))
(T.fatal p))
y1genericDrop _ _ p = T.fatal p
ggenericSplitAt ::
(Integral a) =>
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun a
(T.Fun (T.List b) (T.Tuple2 (T.List b) (T.List b))))
hgenericSplitAt ::
(Integral a) =>
T.R a ->
T.R (T.List b) ->
T.RefExp -> T.R (T.Tuple2 (T.List b) (T.List b))
ggenericSplitAt pgenericSplitAt p
= T.ufun2 agenericSplitAt pgenericSplitAt p
hgenericSplitAt
hgenericSplitAt fv223v16v223v16n fxs p
= T.ucguard
(T.uap2 T.mkNoSrcPos p
((Hat.PreludeBasic.!==) T.mkNoSrcPos p)
fv223v16v223v16n
(T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.gfromInteger T.mkNoSrcPos p)
(T.conInteger T.mkNoSrcPos p (0))))
(h223v1v223v34n fxs p)
(y1genericSplitAt fv223v16v223v16n fxs p)
where h223v1v223v34n fxs p
= T.con2 T.mkNoSrcPos p T.Tuple2 T.aTuple2
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
fxs
h223v1v223v34n _ p
= y1genericSplitAt fv223v16v223v16n fxs p
hgenericSplitAt fv223v16v223v16n fxs p
= y1genericSplitAt fv223v16v223v16n fxs p
y1genericSplitAt _ (T.R T.Nil _) p
= T.con2 T.mkNoSrcPos p T.Tuple2 T.aTuple2
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
y1genericSplitAt fn (T.R (T.Cons fx fxs) _) p
= T.ucguard
(T.uap2 T.mkNoSrcPos p ((!>) T.mkNoSrcPos p) fn
(T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.gfromInteger T.mkNoSrcPos p)
(T.conInteger T.mkNoSrcPos p (0))))
(T.con2 T.mkNoSrcPos p T.Tuple2 T.aTuple2
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fx
(gxs' T.mkNoSrcPos p))
(gxs'' T.mkNoSrcPos p))
(T.ucguard (gotherwise T.mkNoSrcPos p)
(T.uwrapForward p
(herror
(T.fromLitString T.mkNoSrcPos p
"List.genericSplitAt: negative argument")
p))
(T.fatal p))
where gxs' pxs' p = T.uconstUse pxs' p sxs'
gxs'' pxs'' p = T.uconstUse pxs'' p sxs''
sxs'
= T.uconstDef p c228v14v228v50xs'
(\ _ ->
case j228v14v228v50xs' of
(kxs', fxs', fxs'') -> fxs')
sxs''
= T.uconstDef p c228v14v228v50xs''
(\ _ ->
case j228v14v228v50xs' of
(kxs', fxs', fxs'') -> fxs'')
j228v14v228v50xs'
= case
T.uwrapForward p
(hgenericSplitAt
(T.uap2 T.mkNoSrcPos p ((!-) T.mkNoSrcPos p) fn
(T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.gfromInteger T.mkNoSrcPos p)
(T.conInteger T.mkNoSrcPos p (1))))
fxs
p)
of
T.R (T.Tuple2 fxs' fxs'') kxs' -> (kxs', fxs', fxs'')
_ -> T.fatal p
y1genericSplitAt _ _ p = T.fatal p
ggenericIndex ::
(Integral a) =>
T.RefSrcPos ->
T.RefExp -> T.R (T.Fun (T.List b) (T.Fun a b))
hgenericIndex ::
(Integral a) =>
T.R (T.List b) -> T.R a -> T.RefExp -> T.R b
ggenericIndex pgenericIndex p
= T.ufun2 agenericIndex pgenericIndex p hgenericIndex
hgenericIndex z1genericIndex@(T.R (T.Cons fx _) _)
fv231v21v231v21n p
= T.ucguard
(T.uap2 T.mkNoSrcPos p
((Hat.PreludeBasic.!==) T.mkNoSrcPos p)
fv231v21v231v21n
(T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.gfromInteger T.mkNoSrcPos p)
(T.conInteger T.mkNoSrcPos p (0))))
(h231v1v231v28n p)
(y1genericIndex z1genericIndex fv231v21v231v21n p)
where h231v1v231v28n p
= T.projection T.mkNoSrcPos p fx
h231v1v231v28n p
= y1genericIndex z1genericIndex fv231v21v231v21n p
hgenericIndex z1genericIndex fv231v21v231v21n p
= y1genericIndex z1genericIndex fv231v21v231v21n p
y1genericIndex (T.R (T.Cons _ fxs) _) fn p
= T.ucguard
(T.uap2 T.mkNoSrcPos p ((!>) T.mkNoSrcPos p) fn
(T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.gfromInteger T.mkNoSrcPos p)
(T.conInteger T.mkNoSrcPos p (0))))
(T.uwrapForward p
(hgenericIndex fxs
(T.uap2 T.mkNoSrcPos p ((!-) T.mkNoSrcPos p) fn
(T.uap1 T.mkNoSrcPos p
(Hat.PreludeBasic.gfromInteger T.mkNoSrcPos p)
(T.conInteger T.mkNoSrcPos p (1))))
p))
(T.ucguard (gotherwise T.mkNoSrcPos p)
(T.uwrapForward p
(herror
(T.fromLitString T.mkNoSrcPos p
"List.genericIndex: negative argument")
p))
(T.fatal p))
y1genericIndex _ _ p
= T.uwrapForward p
(herror
(T.fromLitString T.mkNoSrcPos p
"List.genericIndex: index too large")
p)
ggenericReplicate ::
(Integral a) =>
T.RefSrcPos ->
T.RefExp -> T.R (T.Fun a (T.Fun b (T.List b)))
hgenericReplicate ::
(Integral a) =>
T.R a -> T.R b -> T.RefExp -> T.R (T.List b)
ggenericReplicate pgenericReplicate p
= T.ufun2 agenericReplicate pgenericReplicate p
hgenericReplicate
hgenericReplicate fn fx p
= T.uwrapForward p
(hgenericTake fn (T.uwrapForward p (hrepeat fx p)) p)
gzip4 ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.List a)
(T.Fun (T.List b)
(T.Fun (T.List c)
(T.Fun (T.List d) (T.List (T.Tuple4 a b c d))))))
szip4 ::
T.R
(T.Fun (T.List a)
(T.Fun (T.List b)
(T.Fun (T.List c)
(T.Fun (T.List d) (T.List (T.Tuple4 a b c d))))))
gzip4 pzip4 p = T.uconstUse pzip4 p szip4
szip4
= T.uconstDef p azip4
(\ p ->
T.uap1 T.mkNoSrcPos p (gzipWith4 T.mkNoSrcPos p)
(T.pa0 T.Tuple4 T.cn4 T.mkNoSrcPos p T.aTuple4))
gzip5 ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.List a)
(T.Fun (T.List b)
(T.Fun (T.List c)
(T.Fun (T.List d)
(T.Fun (T.List e) (T.List (T.Tuple5 a b c d e)))))))
szip5 ::
T.R
(T.Fun (T.List a)
(T.Fun (T.List b)
(T.Fun (T.List c)
(T.Fun (T.List d)
(T.Fun (T.List e) (T.List (T.Tuple5 a b c d e)))))))
gzip5 pzip5 p = T.uconstUse pzip5 p szip5
szip5
= T.uconstDef p azip5
(\ p ->
T.uap1 T.mkNoSrcPos p (gzipWith5 T.mkNoSrcPos p)
(T.pa0 T.Tuple5 T.cn5 T.mkNoSrcPos p T.aTuple5))
gzip6 ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.List a)
(T.Fun (T.List b)
(T.Fun (T.List c)
(T.Fun (T.List d)
(T.Fun (T.List e)
(T.Fun (T.List f)
(T.List (T.Tuple6 a b c d e f))))))))
szip6 ::
T.R
(T.Fun (T.List a)
(T.Fun (T.List b)
(T.Fun (T.List c)
(T.Fun (T.List d)
(T.Fun (T.List e)
(T.Fun (T.List f)
(T.List (T.Tuple6 a b c d e f))))))))
gzip6 pzip6 p = T.uconstUse pzip6 p szip6
szip6
= T.uconstDef p azip6
(\ p ->
T.uap1 T.mkNoSrcPos p (gzipWith6 T.mkNoSrcPos p)
(T.pa0 T.Tuple6 T.cn6 T.mkNoSrcPos p T.aTuple6))
gzip7 ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.List a)
(T.Fun (T.List b)
(T.Fun (T.List c)
(T.Fun (T.List d)
(T.Fun (T.List e)
(T.Fun (T.List f)
(T.Fun (T.List g)
(T.List (T.Tuple7 a b c d e f g)))))))))
szip7 ::
T.R
(T.Fun (T.List a)
(T.Fun (T.List b)
(T.Fun (T.List c)
(T.Fun (T.List d)
(T.Fun (T.List e)
(T.Fun (T.List f)
(T.Fun (T.List g)
(T.List (T.Tuple7 a b c d e f g)))))))))
gzip7 pzip7 p = T.uconstUse pzip7 p szip7
szip7
= T.uconstDef p azip7
(\ p ->
T.uap1 T.mkNoSrcPos p (gzipWith7 T.mkNoSrcPos p)
(T.pa0 T.Tuple7 T.cn7 T.mkNoSrcPos p T.aTuple7))
gzipWith4 ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.Fun a (T.Fun b (T.Fun c (T.Fun d e))))
(T.Fun (T.List a)
(T.Fun (T.List b)
(T.Fun (T.List c) (T.Fun (T.List d) (T.List e))))))
hzipWith4 ::
T.R (T.Fun a (T.Fun b (T.Fun c (T.Fun d e)))) ->
T.R (T.List a) ->
T.R (T.List b) ->
T.R (T.List c) ->
T.R (T.List d) -> T.RefExp -> T.R (T.List e)
gzipWith4 pzipWith4 p
= T.ufun5 azipWith4 pzipWith4 p hzipWith4
hzipWith4 fz (T.R (T.Cons fa fas) _)
(T.R (T.Cons fb fbs) _) (T.R (T.Cons fc fcs) _)
(T.R (T.Cons fd fds) _) p
= T.con2 T.mkNoSrcPos p T.Cons T.aCons
(T.uap4 T.mkNoSrcPos p fz fa fb fc fd)
(T.uwrapForward p (hzipWith4 fz fas fbs fcs fds p))
hzipWith4 _ _ _ _ _ p
= T.con0 T.mkNoSrcPos p T.Nil T.aNil
gzipWith5 ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun
(T.Fun a (T.Fun b (T.Fun c (T.Fun d (T.Fun e f)))))
(T.Fun (T.List a)
(T.Fun (T.List b)
(T.Fun (T.List c)
(T.Fun (T.List d) (T.Fun (T.List e) (T.List f)))))))
hzipWith5 ::
T.R
(T.Fun a (T.Fun b (T.Fun c (T.Fun d (T.Fun e f)))))
->
T.R (T.List a) ->
T.R (T.List b) ->
T.R (T.List c) ->
T.R (T.List d) ->
T.R (T.List e) -> T.RefExp -> T.R (T.List f)
gzipWith5 pzipWith5 p
= T.ufun6 azipWith5 pzipWith5 p hzipWith5
hzipWith5 fz (T.R (T.Cons fa fas) _)
(T.R (T.Cons fb fbs) _) (T.R (T.Cons fc fcs) _)
(T.R (T.Cons fd fds) _) (T.R (T.Cons fe fes) _) p
= T.con2 T.mkNoSrcPos p T.Cons T.aCons
(T.uap5 T.mkNoSrcPos p fz fa fb fc fd fe)
(T.uap6 T.mkNoSrcPos p (gzipWith5 T.mkNoSrcPos p) fz
fas
fbs
fcs
fds
fes)
hzipWith5 _ _ _ _ _ _ p
= T.con0 T.mkNoSrcPos p T.Nil T.aNil
gzipWith6 ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun
(T.Fun a
(T.Fun b (T.Fun c (T.Fun d (T.Fun e (T.Fun f g))))))
(T.Fun (T.List a)
(T.Fun (T.List b)
(T.Fun (T.List c)
(T.Fun (T.List d)
(T.Fun (T.List e)
(T.Fun (T.List f) (T.List g))))))))
hzipWith6 ::
T.R
(T.Fun a
(T.Fun b (T.Fun c (T.Fun d (T.Fun e (T.Fun f g))))))
->
T.R (T.List a) ->
T.R (T.List b) ->
T.R (T.List c) ->
T.R (T.List d) ->
T.R (T.List e) ->
T.R (T.List f) -> T.RefExp -> T.R (T.List g)
gzipWith6 pzipWith6 p
= T.ufun7 azipWith6 pzipWith6 p hzipWith6
hzipWith6 fz (T.R (T.Cons fa fas) _)
(T.R (T.Cons fb fbs) _) (T.R (T.Cons fc fcs) _)
(T.R (T.Cons fd fds) _) (T.R (T.Cons fe fes) _)
(T.R (T.Cons ff ffs) _) p
= T.con2 T.mkNoSrcPos p T.Cons T.aCons
(T.uap6 T.mkNoSrcPos p fz fa fb fc fd fe ff)
(T.uap7 T.mkNoSrcPos p (gzipWith6 T.mkNoSrcPos p) fz
fas
fbs
fcs
fds
fes
ffs)
hzipWith6 _ _ _ _ _ _ _ p
= T.con0 T.mkNoSrcPos p T.Nil T.aNil
gzipWith7 ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun
(T.Fun a
(T.Fun b
(T.Fun c (T.Fun d (T.Fun e (T.Fun f (T.Fun g h)))))))
(T.Fun (T.List a)
(T.Fun (T.List b)
(T.Fun (T.List c)
(T.Fun (T.List d)
(T.Fun (T.List e)
(T.Fun (T.List f)
(T.Fun (T.List g) (T.List h)))))))))
hzipWith7 ::
T.R
(T.Fun a
(T.Fun b
(T.Fun c (T.Fun d (T.Fun e (T.Fun f (T.Fun g h)))))))
->
T.R (T.List a) ->
T.R (T.List b) ->
T.R (T.List c) ->
T.R (T.List d) ->
T.R (T.List e) ->
T.R (T.List f) ->
T.R (T.List g) -> T.RefExp -> T.R (T.List h)
gzipWith7 pzipWith7 p
= T.ufun8 azipWith7 pzipWith7 p hzipWith7
hzipWith7 fz (T.R (T.Cons fa fas) _)
(T.R (T.Cons fb fbs) _) (T.R (T.Cons fc fcs) _)
(T.R (T.Cons fd fds) _) (T.R (T.Cons fe fes) _)
(T.R (T.Cons ff ffs) _) (T.R (T.Cons fg fgs) _) p
= T.con2 T.mkNoSrcPos p T.Cons T.aCons
(T.uap7 T.mkNoSrcPos p fz fa fb fc fd fe ff fg)
(T.uap8 T.mkNoSrcPos p (gzipWith7 T.mkNoSrcPos p) fz
fas
fbs
fcs
fds
fes
ffs
fgs)
hzipWith7 _ _ _ _ _ _ _ _ p
= T.con0 T.mkNoSrcPos p T.Nil T.aNil
gunzip4 ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.List (T.Tuple4 a b c d))
(T.Tuple4 (T.List a) (T.List b) (T.List c)
(T.List d)))
sunzip4 ::
T.R
(T.Fun (T.List (T.Tuple4 a b c d))
(T.Tuple4 (T.List a) (T.List b) (T.List c)
(T.List d)))
gunzip4 punzip4 p = T.uconstUse punzip4 p sunzip4
sunzip4
= T.uconstDef p aunzip4
(\ p ->
T.uap2 T.mkNoSrcPos p (gfoldr T.mkNoSrcPos p)
(T.ufun2 T.mkLambda T.mkNoSrcPos p
(\ (T.R (T.Tuple4 fa fb fc fd) _)
(T.R ~(T.Tuple4 fas fbs fcs fds) _) p ->
T.con4 T.mkNoSrcPos p T.Tuple4 T.aTuple4
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fa fas)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fb fbs)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fc fcs)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fd fds)))
(T.con4 T.mkNoSrcPos p T.Tuple4 T.aTuple4
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)))
gunzip5 ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.List (T.Tuple5 a b c d e))
(T.Tuple5 (T.List a) (T.List b) (T.List c) (T.List d)
(T.List e)))
sunzip5 ::
T.R
(T.Fun (T.List (T.Tuple5 a b c d e))
(T.Tuple5 (T.List a) (T.List b) (T.List c) (T.List d)
(T.List e)))
gunzip5 punzip5 p = T.uconstUse punzip5 p sunzip5
sunzip5
= T.uconstDef p aunzip5
(\ p ->
T.uap2 T.mkNoSrcPos p (gfoldr T.mkNoSrcPos p)
(T.ufun2 T.mkLambda T.mkNoSrcPos p
(\ (T.R (T.Tuple5 fa fb fc fd fe) _)
(T.R ~(T.Tuple5 fas fbs fcs fds fes) _) p ->
T.con5 T.mkNoSrcPos p T.Tuple5 T.aTuple5
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fa fas)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fb fbs)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fc fcs)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fd fds)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fe fes)))
(T.con5 T.mkNoSrcPos p T.Tuple5 T.aTuple5
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)))
gunzip6 ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.List (T.Tuple6 a b c d e f))
(T.Tuple6 (T.List a) (T.List b) (T.List c) (T.List d)
(T.List e)
(T.List f)))
sunzip6 ::
T.R
(T.Fun (T.List (T.Tuple6 a b c d e f))
(T.Tuple6 (T.List a) (T.List b) (T.List c) (T.List d)
(T.List e)
(T.List f)))
gunzip6 punzip6 p = T.uconstUse punzip6 p sunzip6
sunzip6
= T.uconstDef p aunzip6
(\ p ->
T.uap2 T.mkNoSrcPos p (gfoldr T.mkNoSrcPos p)
(T.ufun2 T.mkLambda T.mkNoSrcPos p
(\ (T.R (T.Tuple6 fa fb fc fd fe ff) _)
(T.R ~(T.Tuple6 fas fbs fcs fds fes ffs) _) p ->
T.con6 T.mkNoSrcPos p T.Tuple6 T.aTuple6
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fa fas)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fb fbs)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fc fcs)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fd fds)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fe fes)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons ff ffs)))
(T.con6 T.mkNoSrcPos p T.Tuple6 T.aTuple6
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)))
gunzip7 ::
T.RefSrcPos ->
T.RefExp ->
T.R
(T.Fun (T.List (T.Tuple7 a b c d e f g))
(T.Tuple7 (T.List a) (T.List b) (T.List c) (T.List d)
(T.List e)
(T.List f)
(T.List g)))
sunzip7 ::
T.R
(T.Fun (T.List (T.Tuple7 a b c d e f g))
(T.Tuple7 (T.List a) (T.List b) (T.List c) (T.List d)
(T.List e)
(T.List f)
(T.List g)))
gunzip7 punzip7 p = T.uconstUse punzip7 p sunzip7
sunzip7
= T.uconstDef p aunzip7
(\ p ->
T.uap2 T.mkNoSrcPos p (gfoldr T.mkNoSrcPos p)
(T.ufun2 T.mkLambda T.mkNoSrcPos p
(\ (T.R (T.Tuple7 fa fb fc fd fe ff fg) _)
(T.R ~(T.Tuple7 fas fbs fcs fds fes ffs fgs) _) p ->
T.con7 T.mkNoSrcPos p T.Tuple7 T.aTuple7
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fa fas)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fb fbs)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fc fcs)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fd fds)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fe fes)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons ff ffs)
(T.con2 T.mkNoSrcPos p T.Cons T.aCons fg fgs)))
(T.con7 T.mkNoSrcPos p T.Tuple7 T.aTuple7
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)
(T.con0 T.mkNoSrcPos p T.Nil T.aNil)))
adelete
= T.mkVariable tList 560001 560040 3 (0) "delete"
Prelude.False
adeleteBy
= T.mkVariable tList 590001 600071 3 (3) "deleteBy"
Prelude.False
adeleteFirstsBy
= T.mkVariable tList 660001 660053 3 (1)
"deleteFirstsBy"
Prelude.False
aelemIndex
= T.mkVariable tList 340001 340043 3 (1) "elemIndex"
Prelude.False
aelemIndices
= T.mkVariable tList 370001 370045 3 (1)
"elemIndices"
Prelude.False
afind
= T.mkVariable tList 400001 400049 3 (1) "find"
Prelude.False
afindIndex
= T.mkVariable tList 430001 430054 3 (1) "findIndex"
Prelude.False
afindIndices
= T.mkVariable tList 460001 460061 3 (2)
"findIndices"
Prelude.False
agenericDrop
= T.mkVariable tList 2160001 2200070 3 (2)
"genericDrop"
Prelude.False
agenericIndex
= T.mkVariable tList 2310001 2350069 3 (2)
"genericIndex"
Prelude.False
agenericLength
= T.mkVariable tList 2050001 2060047 3 (1)
"genericLength"
Prelude.False
agenericReplicate
= T.mkVariable tList 2380001 2380051 3 (2)
"genericReplicate"
Prelude.False
agenericSplitAt
= T.mkVariable tList 2230001 2300000 3 (2)
"genericSplitAt"
Prelude.False
agenericTake
= T.mkVariable tList 2090001 2130070 3 (2)
"genericTake"
Prelude.False
agroup
= T.mkVariable tList 1030001 1030039 3 (0) "group"
Prelude.False
agroupBy
= T.mkVariable tList 1060001 1120000 3 (2) "groupBy"
Prelude.False
ainits
= T.mkVariable tList 1130001 1140054 3 (1) "inits"
Prelude.False
ainsert
= T.mkVariable tList 1790001 1790042 3 (0) "insert"
Prelude.False
ainsertBy
= T.mkVariable tList 1820001 1880000 3 (3) "insertBy"
Prelude.False
aintersect
= T.mkVariable tList 750001 750043 3 (0) "intersect"
Prelude.False
aintersectBy
= T.mkVariable tList 780001 780055 3 (3)
"intersectBy"
Prelude.False
aintersperse
= T.mkVariable tList 810001 830055 3 (2)
"intersperse"
Prelude.False
aisPrefixOf
= T.mkVariable tList 1230001 1250054 3 (2)
"isPrefixOf"
Prelude.False
aisSuffixOf
= T.mkVariable tList 1280001 1280059 3 (2)
"isSuffixOf"
Prelude.False
amapAccumL
= T.mkVariable tList 1310001 1360000 3 (3)
"mapAccumL"
Prelude.False
amapAccumR
= T.mkVariable tList 1370001 1420000 3 (3)
"mapAccumR"
Prelude.False
amaximumBy
= T.mkVariable tList 1890001 1960000 3 (2)
"maximumBy"
Prelude.False
aminimumBy
= T.mkVariable tList 1970001 2040000 3 (2)
"minimumBy"
Prelude.False
anub
= T.mkVariable tList 490001 490037 3 (0) "nub"
Prelude.False
anubBy
= T.mkVariable tList 520001 530072 3 (2) "nubBy"
Prelude.False
apartition
= T.mkVariable tList 970001 970061 3 (2) "partition"
Prelude.False
asort
= T.mkVariable tList 1480001 1480041 3 (0) "sort"
Prelude.False
asortBy
= T.mkVariable tList 1510001 1520007 3 (1) "sortBy"
Prelude.False
atails
= T.mkVariable tList 1190001 1200041 3 (1) "tails"
Prelude.False
atranspose
= T.mkVariable tList 910001 940062 3 (1) "transpose"
Prelude.False
aunfoldr
= T.mkVariable tList 1430001 1470000 3 (2) "unfoldr"
Prelude.False
aunion
= T.mkVariable tList 690001 690039 3 (0) "union"
Prelude.False
aunionBy
= T.mkVariable tList 720001 720067 3 (3) "unionBy"
Prelude.False
aunzip4
= T.mkVariable tList 2780001 2800046 3 (0) "unzip4"
Prelude.False
aunzip5
= T.mkVariable tList 2830001 2850049 3 (0) "unzip5"
Prelude.False
aunzip6
= T.mkVariable tList 2880001 2900052 3 (0) "unzip6"
Prelude.False
aunzip7
= T.mkVariable tList 2930001 2950047 3 (0) "unzip7"
Prelude.False
azip4
= T.mkVariable tList 2410001 2410041 3 (0) "zip4"
Prelude.False
azip5
= T.mkVariable tList 2440001 2440042 3 (0) "zip5"
Prelude.False
azip6
= T.mkVariable tList 2480001 2480043 3 (0) "zip6"
Prelude.False
azip7
= T.mkVariable tList 2520001 2520044 3 (0) "zip7"
Prelude.False
azipWith4
= T.mkVariable tList 2550001 2570029 3 (5) "zipWith4"
Prelude.False
azipWith5
= T.mkVariable tList 2610001 2630029 3 (6) "zipWith5"
Prelude.False
azipWith6
= T.mkVariable tList 2670001 2690029 3 (7) "zipWith6"
Prelude.False
azipWith7
= T.mkVariable tList 2730001 2750029 3 (8) "zipWith7"
Prelude.False
(+\\)
= T.mkVariable tList 630001 630046 20 (0) "\\\\"
Prelude.False
c108v34v108v57ys
= T.mkVariable tList 1080034 1080057 3 (0) "ys"
Prelude.True
c108v34v108v57zs
= T.mkVariable tList 1080034 1080057 3 (0) "zs"
Prelude.True
c133v34v133v49s'
= T.mkVariable tList 1330034 1330049 3 (0) "s'"
Prelude.True
c134v34v134v61s''
= T.mkVariable tList 1340034 1340061 3 (0) "s''"
Prelude.True
c133v34v133v49y
= T.mkVariable tList 1330034 1330049 3 (0) "y"
Prelude.True
c134v34v134v61ys
= T.mkVariable tList 1340034 1340061 3 (0) "ys"
Prelude.True
c140v34v140v60s'
= T.mkVariable tList 1400034 1400060 3 (0) "s'"
Prelude.True
c139v34v139v50s''
= T.mkVariable tList 1390034 1390050 3 (0) "s''"
Prelude.True
c139v34v139v50y
= T.mkVariable tList 1390034 1390050 3 (0) "y"
Prelude.True
c140v34v140v60ys
= T.mkVariable tList 1400034 1400060 3 (0) "ys"
Prelude.True
c162v5v164v46ascending
= T.mkVariable tList 1620005 1640046 3 (3)
"ascending"
Prelude.True
c158v5v160v46descending
= T.mkVariable tList 1580005 1600046 3 (3)
"descending"
Prelude.True
c172v5v176v28merge
= T.mkVariable tList 1720005 1760028 3 (2) "merge"
Prelude.True
c166v5v167v43mergeAll
= T.mkVariable tList 1660005 1670043 3 (1) "mergeAll"
Prelude.True
c169v5v170v28mergePairs
= T.mkVariable tList 1690005 1700028 3 (1)
"mergePairs"
Prelude.True
c153v5v156v23sequences
= T.mkVariable tList 1530005 1560023 3 (1)
"sequences"
Prelude.True
c192v28v196v0max
= T.mkVariable tList 1920028 1960000 3 (2) "max"
Prelude.True
c200v28v204v0min
= T.mkVariable tList 2000028 2040000 3 (2) "min"
Prelude.True
c228v14v228v50xs'
= T.mkVariable tList 2280014 2280050 3 (0) "xs'"
Prelude.True
c228v14v228v50xs''
= T.mkVariable tList 2280014 2280050 3 (0) "xs''"
Prelude.True
p = T.mkRoot
tList = T.mkModule "List" "List.hs" Prelude.False | |
0a1f0bef2cad7a87a8df3d07965d244b24e51688ed21cbb5208e76cbafd76677 | biegunka/biegunka | HStringTemplate.hs | # LANGUAGE ExistentialQuantification #
| HStringTemplate support as TemplateSystem
module Control.Biegunka.Templates.HStringTemplate
( HStringTemplate
, hStringTemplate
) where
import qualified Data.Text as T
import Text.StringTemplate (ToSElem, newSTMP, render, setAttribute)
import Text.StringTemplate.GenericStandard ()
import Control.Biegunka.Templates
-- | HStringTemplate templates
data HStringTemplate = forall t. ToSElem t => HStringTemplate t
instance TemplateSystem HStringTemplate where
templating (HStringTemplate b) = render . setAttribute "template" b . newSTMP . T.unpack
# INLINE templating #
| Use any stuff with ' ToSElem ' instance as templates
hStringTemplate :: ToSElem a => a -> Templates
hStringTemplate = Templates . HStringTemplate
# INLINE hStringTemplate #
| null | https://raw.githubusercontent.com/biegunka/biegunka/74fc93326d5f29761125d7047d5418899fa2469d/src/Control/Biegunka/Templates/HStringTemplate.hs | haskell | | HStringTemplate templates | # LANGUAGE ExistentialQuantification #
| HStringTemplate support as TemplateSystem
module Control.Biegunka.Templates.HStringTemplate
( HStringTemplate
, hStringTemplate
) where
import qualified Data.Text as T
import Text.StringTemplate (ToSElem, newSTMP, render, setAttribute)
import Text.StringTemplate.GenericStandard ()
import Control.Biegunka.Templates
data HStringTemplate = forall t. ToSElem t => HStringTemplate t
instance TemplateSystem HStringTemplate where
templating (HStringTemplate b) = render . setAttribute "template" b . newSTMP . T.unpack
# INLINE templating #
| Use any stuff with ' ToSElem ' instance as templates
hStringTemplate :: ToSElem a => a -> Templates
hStringTemplate = Templates . HStringTemplate
# INLINE hStringTemplate #
|
3165721e73d2b1226b4c6024362712da0c8b99cf0cb6ad20d22cbf86ee3ef144 | jackfirth/rebellion | mutable-red-black-tree-batch-insertion.rkt | #lang racket/base
(require racket/contract/base)
(provide
(contract-out
[mutable-rb-tree-put-all! (-> mutable-rb-tree? (sequence/c entry?) #:who interned-symbol? void?)]))
(require racket/match
racket/sequence
rebellion/base/option
rebellion/base/symbol
rebellion/collection/entry
rebellion/collection/private/mutable-red-black-tree-base
rebellion/collection/private/mutable-red-black-tree-insertion
rebellion/collection/private/mutable-red-black-tree-iteration
rebellion/collection/private/mutable-red-black-tree-search)
;@----------------------------------------------------------------------------------------------------
(define (mutable-rb-tree-put-all! tree entries #:who who)
(define unique-entries (make-mutable-rb-tree (mutable-rb-tree-key-comparator tree)))
(for ([e entries])
(match-define (entry key value) e)
(match (mutable-rb-tree-get-option unique-entries key)
[(present first-value)
(raise-arguments-error
who
"cannot batch insert entries, entry batch contain duplicate keys"
"key" key
"first value" first-value
"duplicate value" value)]
[(== absent)
(mutable-rb-tree-put! unique-entries key value)]))
This could be much faster since we 're combining two red - black trees and there exist efficient
;; algorithms for that. But that's complicated and the naive approach is obviously correct. Future
;; work may optimize this but the simple and correct approach is fine for now.
(for ([e (in-mutable-rb-tree unique-entries)])
(mutable-rb-tree-put! tree (entry-key e) (entry-value e))))
| null | https://raw.githubusercontent.com/jackfirth/rebellion/206ced365b07d1c6da5dcbe93f892fbb9bd7ba72/collection/private/mutable-red-black-tree-batch-insertion.rkt | racket | @----------------------------------------------------------------------------------------------------
algorithms for that. But that's complicated and the naive approach is obviously correct. Future
work may optimize this but the simple and correct approach is fine for now. | #lang racket/base
(require racket/contract/base)
(provide
(contract-out
[mutable-rb-tree-put-all! (-> mutable-rb-tree? (sequence/c entry?) #:who interned-symbol? void?)]))
(require racket/match
racket/sequence
rebellion/base/option
rebellion/base/symbol
rebellion/collection/entry
rebellion/collection/private/mutable-red-black-tree-base
rebellion/collection/private/mutable-red-black-tree-insertion
rebellion/collection/private/mutable-red-black-tree-iteration
rebellion/collection/private/mutable-red-black-tree-search)
(define (mutable-rb-tree-put-all! tree entries #:who who)
(define unique-entries (make-mutable-rb-tree (mutable-rb-tree-key-comparator tree)))
(for ([e entries])
(match-define (entry key value) e)
(match (mutable-rb-tree-get-option unique-entries key)
[(present first-value)
(raise-arguments-error
who
"cannot batch insert entries, entry batch contain duplicate keys"
"key" key
"first value" first-value
"duplicate value" value)]
[(== absent)
(mutable-rb-tree-put! unique-entries key value)]))
This could be much faster since we 're combining two red - black trees and there exist efficient
(for ([e (in-mutable-rb-tree unique-entries)])
(mutable-rb-tree-put! tree (entry-key e) (entry-value e))))
|
475f00d7054e176c712b1db0dce2ddfa6f0260ea87089a538e20b7fe785ece27 | masateruk/micro-caml | assoc.ml | (* flatten let-bindings (just for prettier printing) *)
open KNormal
let rec f' (e, t) = (* ネストしたletの簡約 (caml2html: assoc_f) *)
let e' =
match e with
| If(e, e1, e2) -> If(e, f' e1, f' e2)
| Let(xt, e1, e2) -> (* letの場合 (caml2html: assoc_let) *)
let rec insert (e, t) =
let e' =
match e with
| Let(yt, e3, e4) -> Let(yt, e3, insert e4)
| LetRec(fundefs, e) -> LetRec(fundefs, insert e)
| e -> Let(xt, (e, t), f' e2) in
(e', t) in
fst (insert (f' e1))
| LetRec({ name = xt; args = yts; body = e1 }, e2) ->
LetRec({ name = xt; args = yts; body = f' e1 }, f' e2)
| e -> e in
(e', t)
let f = List.map
(function
| TypeDef(x, t) -> TypeDef(x, t)
| VarDef(xt, e) -> VarDef(xt, f' e)
| RecDef({ name = (x, t); args = yts; body = e1 }) -> RecDef({ name = (x, t); args = yts; body = f' e1 }))
| null | https://raw.githubusercontent.com/masateruk/micro-caml/0c0bd066b87cf54ce33709355c422993a85a86a1/assoc.ml | ocaml | flatten let-bindings (just for prettier printing)
ネストしたletの簡約 (caml2html: assoc_f)
letの場合 (caml2html: assoc_let) |
open KNormal
let e' =
match e with
| If(e, e1, e2) -> If(e, f' e1, f' e2)
let rec insert (e, t) =
let e' =
match e with
| Let(yt, e3, e4) -> Let(yt, e3, insert e4)
| LetRec(fundefs, e) -> LetRec(fundefs, insert e)
| e -> Let(xt, (e, t), f' e2) in
(e', t) in
fst (insert (f' e1))
| LetRec({ name = xt; args = yts; body = e1 }, e2) ->
LetRec({ name = xt; args = yts; body = f' e1 }, f' e2)
| e -> e in
(e', t)
let f = List.map
(function
| TypeDef(x, t) -> TypeDef(x, t)
| VarDef(xt, e) -> VarDef(xt, f' e)
| RecDef({ name = (x, t); args = yts; body = e1 }) -> RecDef({ name = (x, t); args = yts; body = f' e1 }))
|
2a24d0ffa42598234bec1ada35d2a813d633e6ed2ba5d60bc89d7570d6160770 | karimarttila/clojure | domain_single_node.clj | (ns simpleserver.domain.domain-single-node
(:require
[clojure.data.csv :as csv]
[clojure.java.io :as io]
[clojure.string :as str]
[clojure.tools.logging :as log]
[simpleserver.util.config :as ss-config]
[simpleserver.domain.domain-interface :as ss-domain-i]
))
(def my-domain-atom
"Stores all domain objects into this cache once read from csv files.
Used for development purposes only."
(atom {}))
(defn -get-raw-products
"Gets raw products for a product group, returns the whole product information for each product."
[pg-id]
(log/debug (str "ENTER get-raw-products, pg-id: " pg-id))
(let [my-key (str "pg-" pg-id "-raw-products")]
(if-let [raw-products (@my-domain-atom my-key)]
raw-products
(let [data-dir (get-in ss-config/config [:single-node-data :data-dir])
raw-products-from-file
(try
(with-open [reader (io/reader (str data-dir "/pg-" pg-id "-products.csv"))]
(doall
(csv/read-csv reader :separator \tab)))
(catch java.io.FileNotFoundException _ nil))]
(if raw-products-from-file
(do
(swap! my-domain-atom assoc my-key raw-products-from-file)
raw-products-from-file)
nil)))))
(defrecord SingleNodeR []
ss-domain-i/DomainInterface
(get-product-groups
[this]
(log/debug "ENTER get-product-groups")
(if-let [product-groups (@my-domain-atom :product-groups)]
product-groups
(let [data-dir (get-in ss-config/config [:single-node-data :data-dir])
raw (with-open [reader (io/reader (str data-dir "/product-groups.csv"))]
(doall
(csv/read-csv reader)))
product-groups-from-file (into {}
(map
(fn [[item]]
(str/split item #"\t"))
raw))]
(swap! my-domain-atom assoc :product-groups product-groups-from-file)
product-groups-from-file)))
(get-products
[this pg-id]
(log/debug (str "ENTER get-products, pg-id: " pg-id))
(let [my-key (str "pg-" pg-id "-products")]
(if-let [products (@my-domain-atom my-key)]
products
(let [raw (-get-raw-products pg-id)
products-from-file (and raw
(map
(fn [item]
(take 4 item)) raw))]
(if products-from-file
(do
(swap! my-domain-atom assoc my-key products-from-file)
products-from-file)
nil)))))
(get-product
[this pg-id p-id]
(log/debug (str "ENTER get-product, pg-id: " pg-id ", p-id: " p-id))
(let [products (-get-raw-products pg-id)]
(first (filter (fn [item]
(let [id (first item)]
(= id (str p-id))))
products)))))
;; ****************************************************************
;; Rich comment.
(comment
(-get-raw-products 1)
(= 1 1)
)
| null | https://raw.githubusercontent.com/karimarttila/clojure/ee1261b9a8e6be92cb47aeb325f82a278f2c1ed3/webstore-demo/simple-server/src/simpleserver/domain/domain_single_node.clj | clojure | ****************************************************************
Rich comment. | (ns simpleserver.domain.domain-single-node
(:require
[clojure.data.csv :as csv]
[clojure.java.io :as io]
[clojure.string :as str]
[clojure.tools.logging :as log]
[simpleserver.util.config :as ss-config]
[simpleserver.domain.domain-interface :as ss-domain-i]
))
(def my-domain-atom
"Stores all domain objects into this cache once read from csv files.
Used for development purposes only."
(atom {}))
(defn -get-raw-products
"Gets raw products for a product group, returns the whole product information for each product."
[pg-id]
(log/debug (str "ENTER get-raw-products, pg-id: " pg-id))
(let [my-key (str "pg-" pg-id "-raw-products")]
(if-let [raw-products (@my-domain-atom my-key)]
raw-products
(let [data-dir (get-in ss-config/config [:single-node-data :data-dir])
raw-products-from-file
(try
(with-open [reader (io/reader (str data-dir "/pg-" pg-id "-products.csv"))]
(doall
(csv/read-csv reader :separator \tab)))
(catch java.io.FileNotFoundException _ nil))]
(if raw-products-from-file
(do
(swap! my-domain-atom assoc my-key raw-products-from-file)
raw-products-from-file)
nil)))))
(defrecord SingleNodeR []
ss-domain-i/DomainInterface
(get-product-groups
[this]
(log/debug "ENTER get-product-groups")
(if-let [product-groups (@my-domain-atom :product-groups)]
product-groups
(let [data-dir (get-in ss-config/config [:single-node-data :data-dir])
raw (with-open [reader (io/reader (str data-dir "/product-groups.csv"))]
(doall
(csv/read-csv reader)))
product-groups-from-file (into {}
(map
(fn [[item]]
(str/split item #"\t"))
raw))]
(swap! my-domain-atom assoc :product-groups product-groups-from-file)
product-groups-from-file)))
(get-products
[this pg-id]
(log/debug (str "ENTER get-products, pg-id: " pg-id))
(let [my-key (str "pg-" pg-id "-products")]
(if-let [products (@my-domain-atom my-key)]
products
(let [raw (-get-raw-products pg-id)
products-from-file (and raw
(map
(fn [item]
(take 4 item)) raw))]
(if products-from-file
(do
(swap! my-domain-atom assoc my-key products-from-file)
products-from-file)
nil)))))
(get-product
[this pg-id p-id]
(log/debug (str "ENTER get-product, pg-id: " pg-id ", p-id: " p-id))
(let [products (-get-raw-products pg-id)]
(first (filter (fn [item]
(let [id (first item)]
(= id (str p-id))))
products)))))
(comment
(-get-raw-products 1)
(= 1 1)
)
|
bdebad7f470074f8864f032fb0f79d4afba405d6be10b0ff14e8af1e763dc64d | tenpureto/tenpureto | Graph.hs | module Tenpureto.Graph
( Graph
, overlay
, compose
, vertex
, vertices
, edge
, edges
, path
, mapVertices
, filterVertices
, filterMapVertices
, graphRoots
, foldTopologically
, GraphSubsetDecision(..)
, graphSubset
, graphAncestors
) where
import qualified Algebra.Graph as G
import Algebra.Graph.AdjacencyMap.Algorithm
( scc )
import qualified Algebra.Graph.NonEmpty.AdjacencyMap
as NAM
import Algebra.Graph.ToGraph ( ToGraph
, ToVertex
, adjacencyMap
, dfs
, toAdjacencyMap
, toAdjacencyMapTranspose
, toGraph
)
import Control.Monad.Memo
import Data.Functor
import Data.Functor.Identity
import Data.List.NonEmpty ( NonEmpty(..)
, nonEmpty
)
import qualified Data.Map as Map
import Data.Maybe
import Data.Semigroup.Foldable
import qualified Data.Set as Set
data Graph a = Graph
{ unGraph :: G.Graph a
, graphNormalized :: G.Graph a
}
instance Show a => Show (Graph a) where
showsPrec i g = showParen
(i >= 11)
(showString "Graph " . showsPrec 11 (graphNormalized g))
instance Ord a => Eq (Graph a) where
x == y = toGraph x == toGraph y
instance Ord a => ToGraph (Graph a) where
type ToVertex (Graph a) = a
toGraph = graphNormalized
graph :: Ord a => G.Graph a -> Graph a
graph a = Graph a (normalize a)
overlay :: Ord a => Graph a -> Graph a -> Graph a
overlay x y = graph $ G.overlay (unGraph x) (unGraph y)
compose :: Ord a => Graph a -> Graph a -> Graph a
compose x y = graph $ G.compose (unGraph x) (unGraph y)
vertex :: Ord a => a -> Graph a
vertex = graph . G.vertex
vertices :: Ord a => [a] -> Graph a
vertices = graph . G.vertices
edge :: Ord a => a -> a -> Graph a
edge x y = graph $ G.edge x y
edges :: Ord a => [(a, a)] -> Graph a
edges = graph . G.edges
path :: Ord a => [a] -> Graph a
path = graph . G.path
mapVertices :: (Ord a, Ord b) => (a -> b) -> Graph a -> Graph b
mapVertices f = graph . fmap f . unGraph
filterVertices :: Ord a => (a -> Bool) -> Graph a -> Graph a
filterVertices f = filterMapVertices (\x -> if f x then Just x else Nothing)
filterMapVertices :: (Ord a, Ord b) => (a -> Maybe b) -> Graph a -> Graph b
filterMapVertices f x =
graph $ (=<<) (maybe G.empty G.vertex . snd) $ filterEmptyVertices $ fmap
zipf
(unGraph x)
where
zipf z = (z, f z)
removeIfEmpty ( _, Just _ ) acc = acc
removeIfEmpty v@(_, Nothing) acc = removeVertexConnecting v acc
filterEmptyVertices
:: (Ord a, Ord b) => G.Graph (a, Maybe b) -> G.Graph (a, Maybe b)
filterEmptyVertices g = foldr removeIfEmpty g (G.vertexList g)
removeVertexConnecting v g =
let ctx = G.context (v ==) g
cct c = G.connect (G.vertices (G.inputs c))
(G.vertices (G.outputs c))
g' = G.removeVertex v g
in maybe g' (G.overlay g' . cct) ctx
graphLeaves :: Ord a => Graph a -> [a]
graphLeaves =
Set.toList
. Map.keysSet
. Map.filter Set.null
. adjacencyMap
. toAdjacencyMap
graphRoots :: Ord a => Graph a -> [a]
graphRoots =
Set.toList
. Map.keysSet
. Map.filter Set.null
. adjacencyMap
. toAdjacencyMapTranspose
graphAncestors :: Ord a => Graph a -> [a] -> [a]
graphAncestors g vs =
let transposed = toAdjacencyMapTranspose g in dfs vs transposed
foldTopologically
:: (Ord a, Monad m)
=> (a -> [b] -> m b)
-> (NonEmpty b -> m c)
-> Graph a
-> m (Maybe c)
foldTopologically vcombine hcombine g =
let leaves = graphLeaves g
parents = adjacencyMap (toAdjacencyMapTranspose g)
parent = maybe mempty Set.toList . flip Map.lookup parents
foldVertex v = do
pbs <- traverse (memo foldVertex) (parent v)
lift $ vcombine v pbs
in startEvalMemoT (traverse (memo foldVertex) leaves)
>>= (mapM hcombine . nonEmpty)
data GraphSubsetDecision = MustDrop | PreferDrop | PreferKeep | MustKeep
deriving (Show, Eq, Ord, Enum, Bounded)
graphSubset :: Ord a => (a -> GraphSubsetDecision) -> Graph a -> Graph a
graphSubset f g = runIdentity $ do
(must, _) <-
fromMaybe (mempty, Nothing)
<$> foldTopologically vcombine (return . fold1) g
return $ filterVertices (`Set.member` must) g
where
vcombine c ps =
let must = foldMap fst ps
may = fmap mconcat (traverse snd ps)
in return $ case f c of
MustDrop -> (must, Nothing)
PreferDrop -> (must, fmap (Set.insert c) may)
PreferKeep ->
(must <> maybe mempty (Set.insert c) may, may $> mempty)
MustKeep ->
(Set.insert c must <> fromMaybe mempty may, Just mempty)
Internal
filterEdges :: Ord a => ((a, a) -> Bool) -> G.Graph a -> G.Graph a
filterEdges predicate x = G.overlay
(G.vertices $ G.vertexList x)
(G.edges $ filter predicate (G.edgeList x))
removeLoops :: Ord a => G.Graph a -> G.Graph a
removeLoops = filterEdges (uncurry (/=))
subtractEdges :: Ord a => G.Graph a -> G.Graph a -> G.Graph a
subtractEdges x y =
let yEdges = G.edgeSet y
yhasEdge = flip Set.member yEdges
in filterEdges (not . yhasEdge) x
removeTransitiveEdges :: Ord a => G.Graph a -> G.Graph a
removeTransitiveEdges g = g `subtractEdges` (recCompose (g `G.compose` g))
where
recCompose x =
let y = G.overlay x (x `G.compose` g)
in if y == x then y else recCompose y
dropCycles :: Ord a => G.Graph a -> G.Graph a
dropCycles = (>>= vertexOrEmpty) . toGraph . scc . toAdjacencyMap
where
vertexOrEmpty cc = case NAM.vertexList1 cc of
v :| [] -> G.vertex v
_ -> G.empty
normalize :: Ord a => G.Graph a -> G.Graph a
normalize = removeTransitiveEdges . dropCycles . removeLoops
| null | https://raw.githubusercontent.com/tenpureto/tenpureto/886df860200e1a6f44ce07c24a5e7597009f71ef/src/Tenpureto/Graph.hs | haskell | module Tenpureto.Graph
( Graph
, overlay
, compose
, vertex
, vertices
, edge
, edges
, path
, mapVertices
, filterVertices
, filterMapVertices
, graphRoots
, foldTopologically
, GraphSubsetDecision(..)
, graphSubset
, graphAncestors
) where
import qualified Algebra.Graph as G
import Algebra.Graph.AdjacencyMap.Algorithm
( scc )
import qualified Algebra.Graph.NonEmpty.AdjacencyMap
as NAM
import Algebra.Graph.ToGraph ( ToGraph
, ToVertex
, adjacencyMap
, dfs
, toAdjacencyMap
, toAdjacencyMapTranspose
, toGraph
)
import Control.Monad.Memo
import Data.Functor
import Data.Functor.Identity
import Data.List.NonEmpty ( NonEmpty(..)
, nonEmpty
)
import qualified Data.Map as Map
import Data.Maybe
import Data.Semigroup.Foldable
import qualified Data.Set as Set
data Graph a = Graph
{ unGraph :: G.Graph a
, graphNormalized :: G.Graph a
}
instance Show a => Show (Graph a) where
showsPrec i g = showParen
(i >= 11)
(showString "Graph " . showsPrec 11 (graphNormalized g))
instance Ord a => Eq (Graph a) where
x == y = toGraph x == toGraph y
instance Ord a => ToGraph (Graph a) where
type ToVertex (Graph a) = a
toGraph = graphNormalized
graph :: Ord a => G.Graph a -> Graph a
graph a = Graph a (normalize a)
overlay :: Ord a => Graph a -> Graph a -> Graph a
overlay x y = graph $ G.overlay (unGraph x) (unGraph y)
compose :: Ord a => Graph a -> Graph a -> Graph a
compose x y = graph $ G.compose (unGraph x) (unGraph y)
vertex :: Ord a => a -> Graph a
vertex = graph . G.vertex
vertices :: Ord a => [a] -> Graph a
vertices = graph . G.vertices
edge :: Ord a => a -> a -> Graph a
edge x y = graph $ G.edge x y
edges :: Ord a => [(a, a)] -> Graph a
edges = graph . G.edges
path :: Ord a => [a] -> Graph a
path = graph . G.path
mapVertices :: (Ord a, Ord b) => (a -> b) -> Graph a -> Graph b
mapVertices f = graph . fmap f . unGraph
filterVertices :: Ord a => (a -> Bool) -> Graph a -> Graph a
filterVertices f = filterMapVertices (\x -> if f x then Just x else Nothing)
filterMapVertices :: (Ord a, Ord b) => (a -> Maybe b) -> Graph a -> Graph b
filterMapVertices f x =
graph $ (=<<) (maybe G.empty G.vertex . snd) $ filterEmptyVertices $ fmap
zipf
(unGraph x)
where
zipf z = (z, f z)
removeIfEmpty ( _, Just _ ) acc = acc
removeIfEmpty v@(_, Nothing) acc = removeVertexConnecting v acc
filterEmptyVertices
:: (Ord a, Ord b) => G.Graph (a, Maybe b) -> G.Graph (a, Maybe b)
filterEmptyVertices g = foldr removeIfEmpty g (G.vertexList g)
removeVertexConnecting v g =
let ctx = G.context (v ==) g
cct c = G.connect (G.vertices (G.inputs c))
(G.vertices (G.outputs c))
g' = G.removeVertex v g
in maybe g' (G.overlay g' . cct) ctx
graphLeaves :: Ord a => Graph a -> [a]
graphLeaves =
Set.toList
. Map.keysSet
. Map.filter Set.null
. adjacencyMap
. toAdjacencyMap
graphRoots :: Ord a => Graph a -> [a]
graphRoots =
Set.toList
. Map.keysSet
. Map.filter Set.null
. adjacencyMap
. toAdjacencyMapTranspose
graphAncestors :: Ord a => Graph a -> [a] -> [a]
graphAncestors g vs =
let transposed = toAdjacencyMapTranspose g in dfs vs transposed
foldTopologically
:: (Ord a, Monad m)
=> (a -> [b] -> m b)
-> (NonEmpty b -> m c)
-> Graph a
-> m (Maybe c)
foldTopologically vcombine hcombine g =
let leaves = graphLeaves g
parents = adjacencyMap (toAdjacencyMapTranspose g)
parent = maybe mempty Set.toList . flip Map.lookup parents
foldVertex v = do
pbs <- traverse (memo foldVertex) (parent v)
lift $ vcombine v pbs
in startEvalMemoT (traverse (memo foldVertex) leaves)
>>= (mapM hcombine . nonEmpty)
data GraphSubsetDecision = MustDrop | PreferDrop | PreferKeep | MustKeep
deriving (Show, Eq, Ord, Enum, Bounded)
graphSubset :: Ord a => (a -> GraphSubsetDecision) -> Graph a -> Graph a
graphSubset f g = runIdentity $ do
(must, _) <-
fromMaybe (mempty, Nothing)
<$> foldTopologically vcombine (return . fold1) g
return $ filterVertices (`Set.member` must) g
where
vcombine c ps =
let must = foldMap fst ps
may = fmap mconcat (traverse snd ps)
in return $ case f c of
MustDrop -> (must, Nothing)
PreferDrop -> (must, fmap (Set.insert c) may)
PreferKeep ->
(must <> maybe mempty (Set.insert c) may, may $> mempty)
MustKeep ->
(Set.insert c must <> fromMaybe mempty may, Just mempty)
Internal
filterEdges :: Ord a => ((a, a) -> Bool) -> G.Graph a -> G.Graph a
filterEdges predicate x = G.overlay
(G.vertices $ G.vertexList x)
(G.edges $ filter predicate (G.edgeList x))
removeLoops :: Ord a => G.Graph a -> G.Graph a
removeLoops = filterEdges (uncurry (/=))
subtractEdges :: Ord a => G.Graph a -> G.Graph a -> G.Graph a
subtractEdges x y =
let yEdges = G.edgeSet y
yhasEdge = flip Set.member yEdges
in filterEdges (not . yhasEdge) x
removeTransitiveEdges :: Ord a => G.Graph a -> G.Graph a
removeTransitiveEdges g = g `subtractEdges` (recCompose (g `G.compose` g))
where
recCompose x =
let y = G.overlay x (x `G.compose` g)
in if y == x then y else recCompose y
dropCycles :: Ord a => G.Graph a -> G.Graph a
dropCycles = (>>= vertexOrEmpty) . toGraph . scc . toAdjacencyMap
where
vertexOrEmpty cc = case NAM.vertexList1 cc of
v :| [] -> G.vertex v
_ -> G.empty
normalize :: Ord a => G.Graph a -> G.Graph a
normalize = removeTransitiveEdges . dropCycles . removeLoops
| |
0e76d8925054fa092a8cd9029ffca0f259e7a525b2addeb0485c60dff04246b6 | someteam/acha | swears.clj | (ns acha.swears)
(def table #{"ahole" "anus" "ash0le" "ash0les" "asholes" "ass" "assface"
"assh0le" "assh0lez" "asshole" "assholes" "assholz" "asswipe" "azzhole" "bassterds"
"bastard" "bastards" "bastardz" "basterds" "basterdz" "biatch" "bitch" "bitches"
"boffing" "butthole" "buttwipe" "c0ck" "c0cks" "c0k" "carpet"
"cawk" "cawks" "clit" "cnts" "cntz" "cock" "cockhead" "cock-head"
"cocks" "cocksucker" "cock-sucker" "crap" "cum" "cunt" "cunts" "cuntz"
"dick" "dild0" "dild0s" "dildo" "dildos" "dilld0" "dilld0s" "dominatricks"
"dominatrics" "dominatrix" "dyke" "enema" "fag" "fag1t"
"faget" "fagg1t" "faggit" "faggot" "fagit" "fags" "fagz" "faig"
"faigs" "fart" "flipping" "fuck" "fucker" "fuckin" "fucking" "fucks"
"fudge" "fuk" "fukah" "fuken" "fuker" "fukin" "fukk" "fukkah"
"fukken" "fukker" "fukkin" "g00k" "gay" "gayboy" "gaygirl" "gays"
"gayz" "god-damned" "h00r" "h0ar" "h0re" "hells" "hoar" "hoor"
"hoore" "jackoff" "jap" "japs" "jerk-off" "jisim" "jiss" "jizm"
"jizz" "knobz" "kunt" "kunts" "kuntz" "lesbian"
"lezzian" "lipshits" "lipshitz" "masochist" "masokist" "massterbait" "masstrbait" "masstrbate"
"masterbaiter" "masterbate" "masterbates" "mother-fucker"
"n1gr" "nastt" "nigger;" "nigur;" "niiger;" "niigr;"
"orafis" "orgasim;" "orgasm" "orgasum" "oriface" "orifice" "orifiss" "packi"
"packie" "packy" "paki" "pakie" "paky" "pecker" "peeenus" "peeenusss"
"peenus" "peinus" "pen1s" "penas" "penis" "penis-breath" "penus" "penuus"
"phuc" "phuck" "phuk" "phuker" "phukker" "polac" "polack" "polak"
"poonani" "pr1c" "pr1ck" "pr1k" "pusse" "pussee" "pussy" "puuke"
"puuker" "queer" "queers" "queerz" "qweers" "qweerz" "qweir" "recktum"
"rectum" "retard" "sadist" "scank" "schlong" "screwing" "semen"
"sh!t" "sh1t" "sh1ter" "sh1ts" "sh1tter" "sh1tz" "shit"
"shits" "shitter" "shitty" "shity" "shitz" "shyt" "shyte" "shytty"
"shyty" "skanck" "skank" "skankee" "skankey" "skanks" "skanky" "slut"
"sluts" "slutty" "slutz" "son-of-a-bitch" "tit" "turd" "va1jina" "vag1na"
"vagiina" "vagina" "vaj1na" "vajina" "vullva" "vulva" "w0p" "wh00r"
"wh0re" "whore" "xrated" "b!+ch" "blowjob"
"arschloch" "b!tch" "b17ch" "b1tch"
"bi+ch" "boiolas" "buceta" "chink" "cipa"
"clits" "dirsa" "ejakulate" "fatass"
"fcuk" "fux0r" "hoer" "hore" "jism" "kawk" "l3itch"
"l3i+ch" "masterbat" "masterbat3" "s.o.b." "mofo"
"nazi" "nigga" "nigger" "nutsack" "pimpis"
"scrotum" "shemale" "shi+" "sh!+" "smut" "teets"
"tits" "boobs" "b00bs" "teez" "testical" "testicle" "titt" "w00se"
"wank" "whoar" "damn" "@$$" "amcik" "andskota" "arse" "assrammer" "ayir" "bi7ch"
"bollock" "breasts" "butt-pirate" "cabron" "cazzo" "chraa" "chuj"
"d4mn" "daygo" "dego" "dike" "dupa" "dziwka"
"ejackulate" "ekrem" "ekto" "enculer" "faen" "fanculo" "fanny"
"feces" "feg" "felcher" "ficken" "fitt" "flikker" "foreskin" "fotze"
"fu(" "futkretzn" "gook" "guiena" "h0r" "h4x0r"
"hell" "helvete" "honkey" "huevon" "hui" "injun"
"kanker" "kike" "klootzak" "kraut" "knulle" "kuk" "kuksuger" "kurac"
"kurwa" "kusi" "kyrpa" "lesbo" "mamhoon" "masturbat" "merd" "mibun"
"monkleigh" "mouliewop" "muie" "mulkku" "muschi" "nazis" "nepesaurio"
"orospu" "paska" "perse" "picka" "pierdol" "pillu" "pimmel" "piss"
"pizda" "poontsee" "poop" "porn" "p0rn" "pr0n" "preteen" "pula"
"pule" "puta" "puto" "qahbeh" "queef" "rautenberg" "schaffer" "scheiss"
"schlampe" "schmuck" "screw" "sharmuta" "sharmute" "shipal" "shiz"
"skribz" "skurwysyn" "sphencter" "spic" "spierdalaj" "splooge" "suka" "b00b"
"twat" "vittu" "wetback" "wichser" "wop"
"yed" "zabourah"})
| null | https://raw.githubusercontent.com/someteam/acha/6b957f6cb6773f4fc184d094b40de79039bb58cc/src-clj/acha/swears.clj | clojure | (ns acha.swears)
(def table #{"ahole" "anus" "ash0le" "ash0les" "asholes" "ass" "assface"
"assh0le" "assh0lez" "asshole" "assholes" "assholz" "asswipe" "azzhole" "bassterds"
"bastard" "bastards" "bastardz" "basterds" "basterdz" "biatch" "bitch" "bitches"
"boffing" "butthole" "buttwipe" "c0ck" "c0cks" "c0k" "carpet"
"cawk" "cawks" "clit" "cnts" "cntz" "cock" "cockhead" "cock-head"
"cocks" "cocksucker" "cock-sucker" "crap" "cum" "cunt" "cunts" "cuntz"
"dick" "dild0" "dild0s" "dildo" "dildos" "dilld0" "dilld0s" "dominatricks"
"dominatrics" "dominatrix" "dyke" "enema" "fag" "fag1t"
"faget" "fagg1t" "faggit" "faggot" "fagit" "fags" "fagz" "faig"
"faigs" "fart" "flipping" "fuck" "fucker" "fuckin" "fucking" "fucks"
"fudge" "fuk" "fukah" "fuken" "fuker" "fukin" "fukk" "fukkah"
"fukken" "fukker" "fukkin" "g00k" "gay" "gayboy" "gaygirl" "gays"
"gayz" "god-damned" "h00r" "h0ar" "h0re" "hells" "hoar" "hoor"
"hoore" "jackoff" "jap" "japs" "jerk-off" "jisim" "jiss" "jizm"
"jizz" "knobz" "kunt" "kunts" "kuntz" "lesbian"
"lezzian" "lipshits" "lipshitz" "masochist" "masokist" "massterbait" "masstrbait" "masstrbate"
"masterbaiter" "masterbate" "masterbates" "mother-fucker"
"n1gr" "nastt" "nigger;" "nigur;" "niiger;" "niigr;"
"orafis" "orgasim;" "orgasm" "orgasum" "oriface" "orifice" "orifiss" "packi"
"packie" "packy" "paki" "pakie" "paky" "pecker" "peeenus" "peeenusss"
"peenus" "peinus" "pen1s" "penas" "penis" "penis-breath" "penus" "penuus"
"phuc" "phuck" "phuk" "phuker" "phukker" "polac" "polack" "polak"
"poonani" "pr1c" "pr1ck" "pr1k" "pusse" "pussee" "pussy" "puuke"
"puuker" "queer" "queers" "queerz" "qweers" "qweerz" "qweir" "recktum"
"rectum" "retard" "sadist" "scank" "schlong" "screwing" "semen"
"sh!t" "sh1t" "sh1ter" "sh1ts" "sh1tter" "sh1tz" "shit"
"shits" "shitter" "shitty" "shity" "shitz" "shyt" "shyte" "shytty"
"shyty" "skanck" "skank" "skankee" "skankey" "skanks" "skanky" "slut"
"sluts" "slutty" "slutz" "son-of-a-bitch" "tit" "turd" "va1jina" "vag1na"
"vagiina" "vagina" "vaj1na" "vajina" "vullva" "vulva" "w0p" "wh00r"
"wh0re" "whore" "xrated" "b!+ch" "blowjob"
"arschloch" "b!tch" "b17ch" "b1tch"
"bi+ch" "boiolas" "buceta" "chink" "cipa"
"clits" "dirsa" "ejakulate" "fatass"
"fcuk" "fux0r" "hoer" "hore" "jism" "kawk" "l3itch"
"l3i+ch" "masterbat" "masterbat3" "s.o.b." "mofo"
"nazi" "nigga" "nigger" "nutsack" "pimpis"
"scrotum" "shemale" "shi+" "sh!+" "smut" "teets"
"tits" "boobs" "b00bs" "teez" "testical" "testicle" "titt" "w00se"
"wank" "whoar" "damn" "@$$" "amcik" "andskota" "arse" "assrammer" "ayir" "bi7ch"
"bollock" "breasts" "butt-pirate" "cabron" "cazzo" "chraa" "chuj"
"d4mn" "daygo" "dego" "dike" "dupa" "dziwka"
"ejackulate" "ekrem" "ekto" "enculer" "faen" "fanculo" "fanny"
"feces" "feg" "felcher" "ficken" "fitt" "flikker" "foreskin" "fotze"
"fu(" "futkretzn" "gook" "guiena" "h0r" "h4x0r"
"hell" "helvete" "honkey" "huevon" "hui" "injun"
"kanker" "kike" "klootzak" "kraut" "knulle" "kuk" "kuksuger" "kurac"
"kurwa" "kusi" "kyrpa" "lesbo" "mamhoon" "masturbat" "merd" "mibun"
"monkleigh" "mouliewop" "muie" "mulkku" "muschi" "nazis" "nepesaurio"
"orospu" "paska" "perse" "picka" "pierdol" "pillu" "pimmel" "piss"
"pizda" "poontsee" "poop" "porn" "p0rn" "pr0n" "preteen" "pula"
"pule" "puta" "puto" "qahbeh" "queef" "rautenberg" "schaffer" "scheiss"
"schlampe" "schmuck" "screw" "sharmuta" "sharmute" "shipal" "shiz"
"skribz" "skurwysyn" "sphencter" "spic" "spierdalaj" "splooge" "suka" "b00b"
"twat" "vittu" "wetback" "wichser" "wop"
"yed" "zabourah"})
| |
f76e9dec82c174da87a0344e8727e68f6bd5d34b90c589fb0dbebab6ba3a3c87 | mfikes/tubular | project.clj | (defproject tubular "1.4.0"
:description "Clojure Socket REPL client"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.8.0"]
[org.clojure/tools.cli "0.3.7"]])
| null | https://raw.githubusercontent.com/mfikes/tubular/e526405448077db438e20d95d7778e32a7434328/project.clj | clojure | (defproject tubular "1.4.0"
:description "Clojure Socket REPL client"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.8.0"]
[org.clojure/tools.cli "0.3.7"]])
| |
2ba47fec2677a2b5ced67e90c69e8217b06a738e786a49b4776a3839ab72be4a | tact-lang/tact-obsolete | immediacy_check.ml | module Config = struct
include Tact.Located.Disabled
end
module Syntax = Tact.Syntax.Make (Config)
module Parser = Tact.Parser.Make (Config)
module Lang = Tact.Lang.Make (Config)
module Show = Tact.Show.Make (Config)
module Interpreter = Tact.Interpreter.Make (Config)
module Errors = Tact.Errors
module Zint = Tact.Zint
module C = Tact.Compiler
module Codegen = Tact.Codegen_func
module Func = Tact.Func
include Core
type error = [Lang.error | Interpreter.error] [@@deriving sexp_of]
let make_errors e = new Errors.errors e
let parse_program s = Parser.parse s
let strip_if_exists_in_other o1 o2 ~equal =
List.filter o1 ~f:(fun o1_item -> not @@ List.exists o2 ~f:(equal o1_item))
let strip : program:Lang.program -> previous:Lang.program -> Lang.program =
fun ~program ~previous ->
{ program with
bindings =
strip_if_exists_in_other program.bindings previous.bindings
~equal:(fun (x1, _) (y1, _) -> Config.equal_located equal_string x1 y1);
structs =
strip_if_exists_in_other program.structs previous.structs
~equal:(fun (id1, _) (id2, _) -> equal_int id1 id2);
unions =
strip_if_exists_in_other program.unions previous.unions
~equal:(fun (id1, _) (id2, _) -> equal_int id1 id2);
interfaces =
strip_if_exists_in_other program.interfaces previous.interfaces
~equal:(fun (id1, _) (id2, _) -> equal_int id1 id2);
struct_signs =
Lang.Arena.strip_if_exists program.struct_signs previous.struct_signs;
union_signs =
Lang.Arena.strip_if_exists program.union_signs previous.struct_signs }
let compile_pass p prev_program errors =
let c = new Lang.constructor ~program:prev_program errors in
let p' = c#visit_program Lang.default_ctx p in
p'
let build_program ?(errors = make_errors Show.show_error)
?(strip_defaults = true) ~codegen p =
let p' = compile_pass p (Lang.default_program ()) errors in
let p'' =
if strip_defaults then strip ~program:p' ~previous:(Lang.default_program ())
else p'
in
errors#to_result p''
|> Result.map_error ~f:(fun errors ->
let errs = List.map errors ~f:(fun (_, err, _) -> err) in
(errs, p'') )
|> Result.map ~f:codegen
let rec pp_sexp = Sexplib.Sexp.pp_hum Caml.Format.std_formatter
and sexp_of_errors =
sexp_of_pair (List.sexp_of_t sexp_of_error) Lang.sexp_of_program
and print_sexp e =
pp_sexp (Result.sexp_of_t Lang.sexp_of_program sexp_of_errors e)
let compile ?(strip_defaults = true) s =
parse_program s |> build_program ~strip_defaults ~codegen:(fun x -> x)
let pp_compile ?(strip_defaults = true) s =
compile ~strip_defaults s |> print_sexp
open Lang
let%expect_test "Immediacy Checks Comptime Reference" =
let scope = [[make_comptime (bl "Test", bl @@ Value Void)]] in
let expr = bl @@ Reference (bl "Test", VoidType) in
pp_sexp @@ sexp_of_bool @@ is_immediate_expr scope (default_program ()) expr ;
[%expect {| true |}]
let%expect_test "Immediacy Checks Runtime Reference" =
let scope = [[make_runtime (bl "Test", VoidType)]] in
let expr = bl @@ Reference (bl "Test", VoidType) in
pp_sexp @@ sexp_of_bool @@ is_immediate_expr scope (default_program ()) expr ;
[%expect {| false |}]
let%expect_test "Immediacy Checks Primitive" =
let scope = [] in
let expr =
bl @@ Primitive (Prim {name = ""; exprs = []; out_ty = VoidType})
in
pp_sexp @@ sexp_of_bool @@ is_immediate_expr scope (default_program ()) expr ;
[%expect {| false |}]
let%expect_test "Immediacy Checks Empty Function" =
let scope = [] in
let expr =
bl
@@ Value
(Function
( bl
@@ { function_signature =
bl
@@ { function_attributes = [];
function_is_type = false;
function_params = [];
function_returns = VoidType };
function_impl = Fn (bl @@ Block []) } ) )
in
pp_sexp @@ sexp_of_bool @@ is_immediate_expr scope (default_program ()) expr ;
[%expect {| true |}]
let%expect_test "Immediacy Checks Function Argument" =
let scope = [] in
let expr =
bl
@@ Value
(Function
( bl
@@ { function_signature =
bl
@@ { function_attributes = [];
function_params = [(bl "arg", VoidType)];
function_is_type = false;
function_returns = VoidType };
function_impl =
Fn
( bl
@@ Block [bl @@ Expr (bl @@ Reference (bl "arg", VoidType))]
) } ) )
in
pp_sexp @@ sexp_of_bool @@ is_immediate_expr scope (default_program ()) expr ;
[%expect {| true |}]
let%expect_test "Immediacy Checks Let Argument" =
let scope = [] in
let expr =
bl
@@ Value
(Function
( bl
@@ { function_signature =
bl
@@ { function_attributes = [];
function_params = [];
function_is_type = false;
function_returns = VoidType };
function_impl =
Fn
( bl
@@ Block
[ bl @@ Let [(bl "arg", bl @@ Value Void)];
bl @@ Expr (bl @@ Reference (bl "arg", VoidType)) ]
) } ) )
in
pp_sexp @@ sexp_of_bool @@ is_immediate_expr scope (default_program ()) expr ;
[%expect {| true |}]
let%expect_test "Immediacy Checks Destructuring Let" =
let scope = [] in
let expr =
bl
@@ Value
(Function
( bl
@@ { function_signature =
bl
@@ { function_attributes = [];
function_params = [];
function_is_type = false;
function_returns = VoidType };
function_impl =
Fn
( bl
@@ Block
[ bl
@@ DestructuringLet
{ destructuring_let =
[(bl "a", bl "b"); (bl "c", bl "c")];
destructuring_let_rest = false;
destructuring_let_expr = bl @@ Value Void };
bl @@ Expr (bl @@ Reference (bl "b", VoidType));
bl @@ Expr (bl @@ Reference (bl "c", VoidType)) ] )
} ) )
in
pp_sexp @@ sexp_of_bool @@ is_immediate_expr scope (default_program ()) expr ;
[%expect {| true |}]
let%expect_test "Immediacy Checks Function Call WITHOUT Primitive" =
let scope = [] in
let expr =
bl
@@ FunctionCall
( bl
@@ Value
(Function
( bl
@@ { function_signature =
bl
@@ { function_attributes = [];
function_params = [];
function_is_type = false;
function_returns = VoidType };
function_impl =
Fn
( bl
@@ Block
[ bl @@ Let [(bl "arg", bl @@ Value Void)];
bl
@@ Expr (bl @@ Reference (bl "arg", VoidType))
] ) } ) ),
[],
false )
in
pp_sexp @@ sexp_of_bool @@ is_immediate_expr scope (default_program ()) expr ;
[%expect {| true |}]
let%expect_test "Immediacy Checks Function Call WITH Primitive" =
let scope = [] in
let expr =
bl
@@ FunctionCall
( bl
@@ Value
(Function
( bl
@@ { function_signature =
bl
@@ { function_attributes = [];
function_params = [];
function_is_type = false;
function_returns = VoidType };
function_impl =
Fn
( bl
@@ Block
[ bl
@@ Expr
( bl
@@ Primitive
(Prim
{ name = "";
exprs = [];
out_ty = VoidType } ) ) ] ) }
) ),
[],
false )
in
pp_sexp @@ sexp_of_bool @@ is_immediate_expr scope (default_program ()) expr ;
[%expect {| false |}]
let f_with_primitive =
bl
@@ Value
(Function
( bl
@@ { function_signature =
bl
@@ { function_attributes = [];
function_params = [];
function_is_type = false;
function_returns = VoidType };
function_impl =
Fn
( bl
@@ Block
[ bl
@@ Expr
( bl
@@ Primitive
(Prim
{name = ""; exprs = []; out_ty = VoidType}
) ) ] ) } ) )
let%expect_test "Immediacy Checks Function Call that contains function with \
primitive" =
let scope = [] in
let expr =
bl
@@ FunctionCall
( bl
@@ Value
(Function
( bl
@@ { function_signature =
bl
@@ { function_attributes = [];
function_is_type = false;
function_params = [];
function_returns = VoidType };
function_impl =
Fn
( bl
@@ Block [bl @@ Let [(bl "_", f_with_primitive)]] )
} ) ),
[],
false )
in
pp_sexp @@ sexp_of_bool @@ is_immediate_expr scope (default_program ()) expr ;
[%expect {| true |}]
let%expect_test "Immediacy Checks Function Call that Call function with \
primitive" =
let scope = [] in
let expr =
bl
@@ FunctionCall
( bl
@@ Value
(Function
( bl
@@ { function_signature =
bl
@@ { function_attributes = [];
function_is_type = false;
function_params = [];
function_returns = VoidType };
function_impl =
Fn
( bl
@@ Block
[ bl
@@ Expr
( bl
@@ FunctionCall
(f_with_primitive, [], false) ) ]
) } ) ),
[],
false )
in
pp_sexp @@ sexp_of_bool @@ is_immediate_expr scope (default_program ()) expr ;
[%expect {| false |}]
let%expect_test "Immediacy Checks Top Level Fn With Sign" =
let scope = [] in
let expr =
bl
@@ Value
(Function
( bl
@@ { function_signature =
bl
@@ { function_attributes = [];
function_is_type = false;
function_params = [];
function_returns = StructSig 0 };
function_impl = Fn (bl @@ Block []) } ) )
in
pp_sexp @@ sexp_of_bool @@ is_immediate_expr scope (default_program ()) expr ;
[%expect {| true |}]
let%expect_test "Immediacy Checks Struct Sig" =
let scope = [] in
let expr = bl @@ Value (Type (StructSig 0)) in
pp_sexp @@ sexp_of_bool @@ is_immediate_expr scope (default_program ()) expr ;
[%expect {| false |}]
let%expect_test "Immediacy Checks Self Type" =
let scope = [] in
let expr =
bl @@ FunctionCall (bl @@ Value Void, [bl @@ Value (Type SelfType)], false)
in
pp_sexp @@ sexp_of_bool @@ is_immediate_expr scope (default_program ()) expr ;
[%expect {| false |}]
let%expect_test " Immediacy Checks MyInt Type " =
let source =
{ |
struct Cell {
val c : builtin_Cell
}
struct Builder {
val b : builtin_Builder
fn serialize_int(self : Self , int : Integer , bits : Integer ) - > Self {
let b = builtin_store_int(self.b , int , bits ) ;
Self { b : b }
}
}
struct Slice {
s : builtin_Slice
fn load_int(self : Self , bits : Integer ) - > LoadResult(Integer ) {
let output = builtin_load_int(self.s , bits ) ;
let slice = Self { s : output.value1 } ;
let int = output.value2 ;
LoadResult(Integer ) { slice : slice , value : int }
}
}
struct MyInt[bits : Integer ] {
val value : Integer
impl {
fn deserialize(s : Slice ) - > LoadResult(Self ) {
let s.load_int(bits ) ;
LoadResult(Self ) {
slice : res.slice ,
value : Self { value : res.value }
}
}
}
}
| }
in
let p = Option.value_exn @@ Result.ok @@ compile source in
let res =
is_immediate_expr
[ List.map p.bindings ~f : ]
p
( bl
@@ FunctionCall
( List . Assoc.find_exn p.bindings ( bl @@ " MyInt " )
~equal:(Config.equal_located equal_string ) ,
[ bl @@ Value ( Integer ( Z.of_int 123 ) ) ] ) )
in
pp_sexp @@ sexp_of_bool res ;
[ % expect { | true | } ]
let source =
{|
struct Cell {
val c: builtin_Cell
}
struct Builder {
val b: builtin_Builder
fn serialize_int(self: Self, int: Integer, bits: Integer) -> Self {
let b = builtin_store_int(self.b, int, bits);
Self { b: b }
}
}
struct Slice {
val s: builtin_Slice
fn load_int(self: Self, bits: Integer) -> LoadResult(Integer) {
let output = builtin_load_int(self.s, bits);
let slice = Self { s: output.value1 };
let int = output.value2;
LoadResult(Integer) { slice: slice, value: int }
}
}
struct MyInt[bits: Integer] {
val value: Integer
impl Deserialize {
fn deserialize(s: Slice) -> LoadResult(Self) {
let res = s.load_int(bits);
LoadResult(Self) {
slice: res.slice,
value: Self { value: res.value }
}
}
}
}
|}
in
let p = Option.value_exn @@ Result.ok @@ compile source in
let res =
is_immediate_expr
[List.map p.bindings ~f:make_comptime]
p
( bl
@@ FunctionCall
( List.Assoc.find_exn p.bindings (bl @@ "MyInt")
~equal:(Config.equal_located equal_string),
[bl @@ Value (Integer (Z.of_int 123))] ) )
in
pp_sexp @@ sexp_of_bool res ;
[%expect {| true |}] *)
let%expect_test "Immediacy Checks Unions Functions" =
let source =
{|
union MsgAddressExt {
case Integer
fn serialize(self: Self) { }
}
|}
in
let _ = Option.value_exn @@ Result.ok @@ compile source in
pp_sexp @@ sexp_of_bool true ;
[%expect {| true |}]
let%expect_test "Immediacy Checks Unions Functions" =
let source =
{|
union MsgAddressExt {
case Integer
fn serialize(self: Self) { }
}
|}
in
let _ = Option.value_exn @@ Result.ok @@ compile source in
pp_sexp @@ sexp_of_bool true ;
[%expect {| true |}]
| null | https://raw.githubusercontent.com/tact-lang/tact-obsolete/deed43aa496676033f84fe4db9383d9e22b1d11d/test/immediacy_check.ml | ocaml | module Config = struct
include Tact.Located.Disabled
end
module Syntax = Tact.Syntax.Make (Config)
module Parser = Tact.Parser.Make (Config)
module Lang = Tact.Lang.Make (Config)
module Show = Tact.Show.Make (Config)
module Interpreter = Tact.Interpreter.Make (Config)
module Errors = Tact.Errors
module Zint = Tact.Zint
module C = Tact.Compiler
module Codegen = Tact.Codegen_func
module Func = Tact.Func
include Core
type error = [Lang.error | Interpreter.error] [@@deriving sexp_of]
let make_errors e = new Errors.errors e
let parse_program s = Parser.parse s
let strip_if_exists_in_other o1 o2 ~equal =
List.filter o1 ~f:(fun o1_item -> not @@ List.exists o2 ~f:(equal o1_item))
let strip : program:Lang.program -> previous:Lang.program -> Lang.program =
fun ~program ~previous ->
{ program with
bindings =
strip_if_exists_in_other program.bindings previous.bindings
~equal:(fun (x1, _) (y1, _) -> Config.equal_located equal_string x1 y1);
structs =
strip_if_exists_in_other program.structs previous.structs
~equal:(fun (id1, _) (id2, _) -> equal_int id1 id2);
unions =
strip_if_exists_in_other program.unions previous.unions
~equal:(fun (id1, _) (id2, _) -> equal_int id1 id2);
interfaces =
strip_if_exists_in_other program.interfaces previous.interfaces
~equal:(fun (id1, _) (id2, _) -> equal_int id1 id2);
struct_signs =
Lang.Arena.strip_if_exists program.struct_signs previous.struct_signs;
union_signs =
Lang.Arena.strip_if_exists program.union_signs previous.struct_signs }
let compile_pass p prev_program errors =
let c = new Lang.constructor ~program:prev_program errors in
let p' = c#visit_program Lang.default_ctx p in
p'
let build_program ?(errors = make_errors Show.show_error)
?(strip_defaults = true) ~codegen p =
let p' = compile_pass p (Lang.default_program ()) errors in
let p'' =
if strip_defaults then strip ~program:p' ~previous:(Lang.default_program ())
else p'
in
errors#to_result p''
|> Result.map_error ~f:(fun errors ->
let errs = List.map errors ~f:(fun (_, err, _) -> err) in
(errs, p'') )
|> Result.map ~f:codegen
let rec pp_sexp = Sexplib.Sexp.pp_hum Caml.Format.std_formatter
and sexp_of_errors =
sexp_of_pair (List.sexp_of_t sexp_of_error) Lang.sexp_of_program
and print_sexp e =
pp_sexp (Result.sexp_of_t Lang.sexp_of_program sexp_of_errors e)
let compile ?(strip_defaults = true) s =
parse_program s |> build_program ~strip_defaults ~codegen:(fun x -> x)
let pp_compile ?(strip_defaults = true) s =
compile ~strip_defaults s |> print_sexp
open Lang
let%expect_test "Immediacy Checks Comptime Reference" =
let scope = [[make_comptime (bl "Test", bl @@ Value Void)]] in
let expr = bl @@ Reference (bl "Test", VoidType) in
pp_sexp @@ sexp_of_bool @@ is_immediate_expr scope (default_program ()) expr ;
[%expect {| true |}]
let%expect_test "Immediacy Checks Runtime Reference" =
let scope = [[make_runtime (bl "Test", VoidType)]] in
let expr = bl @@ Reference (bl "Test", VoidType) in
pp_sexp @@ sexp_of_bool @@ is_immediate_expr scope (default_program ()) expr ;
[%expect {| false |}]
let%expect_test "Immediacy Checks Primitive" =
let scope = [] in
let expr =
bl @@ Primitive (Prim {name = ""; exprs = []; out_ty = VoidType})
in
pp_sexp @@ sexp_of_bool @@ is_immediate_expr scope (default_program ()) expr ;
[%expect {| false |}]
let%expect_test "Immediacy Checks Empty Function" =
let scope = [] in
let expr =
bl
@@ Value
(Function
( bl
@@ { function_signature =
bl
@@ { function_attributes = [];
function_is_type = false;
function_params = [];
function_returns = VoidType };
function_impl = Fn (bl @@ Block []) } ) )
in
pp_sexp @@ sexp_of_bool @@ is_immediate_expr scope (default_program ()) expr ;
[%expect {| true |}]
let%expect_test "Immediacy Checks Function Argument" =
let scope = [] in
let expr =
bl
@@ Value
(Function
( bl
@@ { function_signature =
bl
@@ { function_attributes = [];
function_params = [(bl "arg", VoidType)];
function_is_type = false;
function_returns = VoidType };
function_impl =
Fn
( bl
@@ Block [bl @@ Expr (bl @@ Reference (bl "arg", VoidType))]
) } ) )
in
pp_sexp @@ sexp_of_bool @@ is_immediate_expr scope (default_program ()) expr ;
[%expect {| true |}]
let%expect_test "Immediacy Checks Let Argument" =
let scope = [] in
let expr =
bl
@@ Value
(Function
( bl
@@ { function_signature =
bl
@@ { function_attributes = [];
function_params = [];
function_is_type = false;
function_returns = VoidType };
function_impl =
Fn
( bl
@@ Block
[ bl @@ Let [(bl "arg", bl @@ Value Void)];
bl @@ Expr (bl @@ Reference (bl "arg", VoidType)) ]
) } ) )
in
pp_sexp @@ sexp_of_bool @@ is_immediate_expr scope (default_program ()) expr ;
[%expect {| true |}]
let%expect_test "Immediacy Checks Destructuring Let" =
let scope = [] in
let expr =
bl
@@ Value
(Function
( bl
@@ { function_signature =
bl
@@ { function_attributes = [];
function_params = [];
function_is_type = false;
function_returns = VoidType };
function_impl =
Fn
( bl
@@ Block
[ bl
@@ DestructuringLet
{ destructuring_let =
[(bl "a", bl "b"); (bl "c", bl "c")];
destructuring_let_rest = false;
destructuring_let_expr = bl @@ Value Void };
bl @@ Expr (bl @@ Reference (bl "b", VoidType));
bl @@ Expr (bl @@ Reference (bl "c", VoidType)) ] )
} ) )
in
pp_sexp @@ sexp_of_bool @@ is_immediate_expr scope (default_program ()) expr ;
[%expect {| true |}]
let%expect_test "Immediacy Checks Function Call WITHOUT Primitive" =
let scope = [] in
let expr =
bl
@@ FunctionCall
( bl
@@ Value
(Function
( bl
@@ { function_signature =
bl
@@ { function_attributes = [];
function_params = [];
function_is_type = false;
function_returns = VoidType };
function_impl =
Fn
( bl
@@ Block
[ bl @@ Let [(bl "arg", bl @@ Value Void)];
bl
@@ Expr (bl @@ Reference (bl "arg", VoidType))
] ) } ) ),
[],
false )
in
pp_sexp @@ sexp_of_bool @@ is_immediate_expr scope (default_program ()) expr ;
[%expect {| true |}]
let%expect_test "Immediacy Checks Function Call WITH Primitive" =
let scope = [] in
let expr =
bl
@@ FunctionCall
( bl
@@ Value
(Function
( bl
@@ { function_signature =
bl
@@ { function_attributes = [];
function_params = [];
function_is_type = false;
function_returns = VoidType };
function_impl =
Fn
( bl
@@ Block
[ bl
@@ Expr
( bl
@@ Primitive
(Prim
{ name = "";
exprs = [];
out_ty = VoidType } ) ) ] ) }
) ),
[],
false )
in
pp_sexp @@ sexp_of_bool @@ is_immediate_expr scope (default_program ()) expr ;
[%expect {| false |}]
let f_with_primitive =
bl
@@ Value
(Function
( bl
@@ { function_signature =
bl
@@ { function_attributes = [];
function_params = [];
function_is_type = false;
function_returns = VoidType };
function_impl =
Fn
( bl
@@ Block
[ bl
@@ Expr
( bl
@@ Primitive
(Prim
{name = ""; exprs = []; out_ty = VoidType}
) ) ] ) } ) )
let%expect_test "Immediacy Checks Function Call that contains function with \
primitive" =
let scope = [] in
let expr =
bl
@@ FunctionCall
( bl
@@ Value
(Function
( bl
@@ { function_signature =
bl
@@ { function_attributes = [];
function_is_type = false;
function_params = [];
function_returns = VoidType };
function_impl =
Fn
( bl
@@ Block [bl @@ Let [(bl "_", f_with_primitive)]] )
} ) ),
[],
false )
in
pp_sexp @@ sexp_of_bool @@ is_immediate_expr scope (default_program ()) expr ;
[%expect {| true |}]
let%expect_test "Immediacy Checks Function Call that Call function with \
primitive" =
let scope = [] in
let expr =
bl
@@ FunctionCall
( bl
@@ Value
(Function
( bl
@@ { function_signature =
bl
@@ { function_attributes = [];
function_is_type = false;
function_params = [];
function_returns = VoidType };
function_impl =
Fn
( bl
@@ Block
[ bl
@@ Expr
( bl
@@ FunctionCall
(f_with_primitive, [], false) ) ]
) } ) ),
[],
false )
in
pp_sexp @@ sexp_of_bool @@ is_immediate_expr scope (default_program ()) expr ;
[%expect {| false |}]
let%expect_test "Immediacy Checks Top Level Fn With Sign" =
let scope = [] in
let expr =
bl
@@ Value
(Function
( bl
@@ { function_signature =
bl
@@ { function_attributes = [];
function_is_type = false;
function_params = [];
function_returns = StructSig 0 };
function_impl = Fn (bl @@ Block []) } ) )
in
pp_sexp @@ sexp_of_bool @@ is_immediate_expr scope (default_program ()) expr ;
[%expect {| true |}]
let%expect_test "Immediacy Checks Struct Sig" =
let scope = [] in
let expr = bl @@ Value (Type (StructSig 0)) in
pp_sexp @@ sexp_of_bool @@ is_immediate_expr scope (default_program ()) expr ;
[%expect {| false |}]
let%expect_test "Immediacy Checks Self Type" =
let scope = [] in
let expr =
bl @@ FunctionCall (bl @@ Value Void, [bl @@ Value (Type SelfType)], false)
in
pp_sexp @@ sexp_of_bool @@ is_immediate_expr scope (default_program ()) expr ;
[%expect {| false |}]
let%expect_test " Immediacy Checks MyInt Type " =
let source =
{ |
struct Cell {
val c : builtin_Cell
}
struct Builder {
val b : builtin_Builder
fn serialize_int(self : Self , int : Integer , bits : Integer ) - > Self {
let b = builtin_store_int(self.b , int , bits ) ;
Self { b : b }
}
}
struct Slice {
s : builtin_Slice
fn load_int(self : Self , bits : Integer ) - > LoadResult(Integer ) {
let output = builtin_load_int(self.s , bits ) ;
let slice = Self { s : output.value1 } ;
let int = output.value2 ;
LoadResult(Integer ) { slice : slice , value : int }
}
}
struct MyInt[bits : Integer ] {
val value : Integer
impl {
fn deserialize(s : Slice ) - > LoadResult(Self ) {
let s.load_int(bits ) ;
LoadResult(Self ) {
slice : res.slice ,
value : Self { value : res.value }
}
}
}
}
| }
in
let p = Option.value_exn @@ Result.ok @@ compile source in
let res =
is_immediate_expr
[ List.map p.bindings ~f : ]
p
( bl
@@ FunctionCall
( List . Assoc.find_exn p.bindings ( bl @@ " MyInt " )
~equal:(Config.equal_located equal_string ) ,
[ bl @@ Value ( Integer ( Z.of_int 123 ) ) ] ) )
in
pp_sexp @@ sexp_of_bool res ;
[ % expect { | true | } ]
let source =
{|
struct Cell {
val c: builtin_Cell
}
struct Builder {
val b: builtin_Builder
fn serialize_int(self: Self, int: Integer, bits: Integer) -> Self {
let b = builtin_store_int(self.b, int, bits);
Self { b: b }
}
}
struct Slice {
val s: builtin_Slice
fn load_int(self: Self, bits: Integer) -> LoadResult(Integer) {
let output = builtin_load_int(self.s, bits);
let slice = Self { s: output.value1 };
let int = output.value2;
LoadResult(Integer) { slice: slice, value: int }
}
}
struct MyInt[bits: Integer] {
val value: Integer
impl Deserialize {
fn deserialize(s: Slice) -> LoadResult(Self) {
let res = s.load_int(bits);
LoadResult(Self) {
slice: res.slice,
value: Self { value: res.value }
}
}
}
}
|}
in
let p = Option.value_exn @@ Result.ok @@ compile source in
let res =
is_immediate_expr
[List.map p.bindings ~f:make_comptime]
p
( bl
@@ FunctionCall
( List.Assoc.find_exn p.bindings (bl @@ "MyInt")
~equal:(Config.equal_located equal_string),
[bl @@ Value (Integer (Z.of_int 123))] ) )
in
pp_sexp @@ sexp_of_bool res ;
[%expect {| true |}] *)
let%expect_test "Immediacy Checks Unions Functions" =
let source =
{|
union MsgAddressExt {
case Integer
fn serialize(self: Self) { }
}
|}
in
let _ = Option.value_exn @@ Result.ok @@ compile source in
pp_sexp @@ sexp_of_bool true ;
[%expect {| true |}]
let%expect_test "Immediacy Checks Unions Functions" =
let source =
{|
union MsgAddressExt {
case Integer
fn serialize(self: Self) { }
}
|}
in
let _ = Option.value_exn @@ Result.ok @@ compile source in
pp_sexp @@ sexp_of_bool true ;
[%expect {| true |}]
| |
2a07e2a554ad11baffa2670bd9f90297dc31047d2dcd74831e977bab43eeba04 | pixlsus/registry.gimp.org_static | feurio-logo.scm | ; feurio logo
Copyright ( C ) 2002 - 2003
Copyright ( C ) 2004 - 2008
; This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
; (at your option) any later version.
;
; This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
; GNU General Public License for more details.
;
You should have received a copy of the GNU General Public License
; along with this program; if not, write to the Free Software
Foundation , Inc. , 675 Mass Ave , Cambridge , , USA .
;
; --------------------------------------------------------------------
version 1.0 by
version 2.0 by 2004/08/20
; - Support Gimp 2.0
version 2.1 by 2005/02/08
- problem with gimp 2.2
version 2.4 by
- Support Gimp 2.4
version 2.4.1 by 2008/10/28
; - do not rely on external def set-pt
version 2.4.2 by 2008/11/03
; - fix License
; - update script register
; --------------------------------------------------------------------
;
(define (script-fu-feurio-logo inText inFont inFontSize inTextColor inRed1 inRed2 inGreen1 inGreen2 inBlue1 inBlue2 inHeight inBlurRadius inAbsolute inImageWidth inImageHeight inFlatten)
(define (set-pt a index x y)
(begin
(aset a (* index 2) x)
(aset a (+ (* index 2) 1) y)
)
)
(let*
(
(img ( car (gimp-image-new 10 10 RGB) ) )
(theText)
(theTextWidth)
(theTextHeight)
(imgWidth)
(imgHeight)
(theBufferX)
(theBufferY)
(theSel)
(theLayer (car (gimp-layer-new img 10 10 RGB-IMAGE "Layer" 100 NORMAL) ) )
(theTextLayer (car (gimp-layer-new img 10 10 RGB-IMAGE "Text Layer" 100 NORMAL) ) )
(theFeurioLayer (car (gimp-layer-new img 10 10 RGB-IMAGE "Feurio Layer" 100 NORMAL) ) )
(theTextMask)
(theFeurioMask)
(old-fg (car (gimp-context-get-foreground) ) )
(old-bg (car (gimp-context-get-background) ) )
)
(define (splineRed)
(let* ((a (cons-array 6 'byte)))
(set-pt a 0 0 0)
(set-pt a 1 inRed1 inRed2)
(set-pt a 2 255 255)
a
)
)
(define (splineGreen)
(let* ((a (cons-array 6 'byte)))
(set-pt a 0 0 0)
(set-pt a 1 inGreen1 inGreen2)
(set-pt a 2 255 255)
a
)
)
(define (splineBlue)
(let* ((a (cons-array 6 'byte)))
(set-pt a 0 0 0)
(set-pt a 1 inBlue1 inBlue2)
(set-pt a 2 255 255)
a
)
)
(gimp-image-add-layer img theLayer 0)
(gimp-image-add-layer img theTextLayer 0)
(gimp-image-add-layer img theFeurioLayer 0)
(gimp-context-set-background '(0 0 0) )
(gimp-context-set-foreground '(255 255 255) )
(gimp-selection-all img)
(gimp-edit-clear theLayer)
(gimp-edit-clear theTextLayer)
(gimp-edit-clear theFeurioLayer)
(gimp-selection-none img)
(set! theText (car (gimp-text-fontname img theLayer 0 0 inText 0 TRUE inFontSize PIXELS inFont)))
(set! theTextWidth (car (gimp-drawable-width theText) ) )
(set! theTextHeight (car (gimp-drawable-height theText) ) )
(set! imgWidth inImageWidth )
(set! imgHeight inImageHeight )
(if (= inAbsolute FALSE)
(set! imgWidth (+ theTextWidth (* 3 inHeight) ) )
)
(if (= inAbsolute FALSE)
(set! imgHeight (+ theTextHeight (* 4 inHeight) ) )
)
(set! theBufferX (/ (- imgWidth theTextWidth) 2) )
(set! theBufferY (/ (- imgHeight theTextHeight) 2) )
(gimp-image-resize img imgWidth imgHeight 0 0)
(gimp-layer-resize theLayer imgWidth imgHeight 0 0)
(gimp-layer-resize theTextLayer imgWidth imgHeight 0 0)
(gimp-layer-resize theFeurioLayer imgWidth imgHeight 0 0)
(gimp-layer-set-offsets theText theBufferX theBufferY)
(gimp-floating-sel-anchor theText)
(gimp-context-set-foreground inTextColor )
(gimp-edit-bucket-fill theTextLayer FG-BUCKET-FILL NORMAL 100 0 FALSE 0 0)
(plug-in-bump-map 1 img theTextLayer theLayer 135.0 45.0 3 0 0 0 0 TRUE FALSE 2)
(gimp-layer-add-alpha theTextLayer)
(set! theTextMask (car (gimp-layer-create-mask theFeurioLayer WHITE-MASK)))
(gimp-layer-add-mask theTextLayer theTextMask)
(gimp-edit-copy theLayer)
(set! theSel (car (gimp-edit-paste theTextMask FALSE)))
(gimp-floating-sel-anchor theSel)
(gimp-layer-remove-mask theTextLayer APPLY)
(gimp-context-set-foreground '(255 255 255) )
(set! theSel (car (gimp-edit-paste theFeurioLayer FALSE)))
(gimp-floating-sel-anchor theSel)
(gimp-by-color-select theFeurioLayer '(255 255 255) 15 0 FALSE FALSE 10 FALSE)
(gimp-selection-grow img (/ inHeight 5))
(gimp-edit-bucket-fill theFeurioLayer FG-BUCKET-FILL NORMAL 100 0 FALSE 0 0)
(gimp-context-set-foreground '(128 128 128) )
(gimp-selection-shrink img (/ inHeight 5))
(gimp-edit-bucket-fill theFeurioLayer FG-BUCKET-FILL NORMAL 100 0 FALSE 0 0)
(gimp-selection-none img)
(gimp-context-set-foreground '(255 255 255) )
(plug-in-ripple 1 img theFeurioLayer inHeight inHeight 1 0 1 TRUE FALSE)
(plug-in-ripple 1 img theFeurioLayer (* 2 inHeight) (/ inHeight 3) 1 0 1 TRUE FALSE)
(plug-in-spread 1 img theFeurioLayer inHeight inHeight)
(gimp-layer-add-alpha theFeurioLayer)
(set! theFeurioMask (car (gimp-layer-create-mask theFeurioLayer WHITE-MASK)))
(gimp-layer-add-mask theFeurioLayer theFeurioMask)
(gimp-edit-blend theFeurioMask FG-BG-RGB NORMAL LINEAR 100 0 REPEAT-NONE FALSE 0 0 FALSE FALSE 0 theBufferY 0 (- imgHeight theBufferY))
(plug-in-gauss-iir 1 img theFeurioLayer inBlurRadius 1 1)
(gimp-curves-spline theFeurioLayer BLUE-LUT 6 (splineBlue))
(gimp-curves-spline theFeurioLayer GREEN-LUT 6 (splineGreen))
(gimp-curves-spline theFeurioLayer RED-LUT 6 (splineRed))
(gimp-layer-remove-mask theFeurioLayer APPLY)
(plug-in-gauss-iir 1 img theLayer inBlurRadius 1 1)
(gimp-curves-spline theLayer BLUE-LUT 6 (splineBlue))
(gimp-curves-spline theLayer GREEN-LUT 6 (splineGreen))
(gimp-curves-spline theLayer RED-LUT 6 (splineRed))
(if (= inFlatten TRUE)
(gimp-image-flatten img)
()
)
(gimp-context-set-background old-bg)
(gimp-context-set-foreground old-fg)
(gimp-display-new img)
(list img theLayer theText)
Bereinigen Dirty - Flag
(gimp-image-clean-all img)
)
)
(script-fu-register
"script-fu-feurio-logo"
"MS - Feurio..."
"Creates a burning text logo."
"Michael Schalla"
"Michael Schalla"
"October 2002"
""
SF-STRING "Text" "Feurio"
SF-FONT "Font" "-*-Arial Black-*-r-*-*-24-*-*-*-p-*-*-*"
SF-ADJUSTMENT "Font Size" '(100 2 1000 1 10 0 1)
SF-COLOR "Color" '(224 0 0)
SF-ADJUSTMENT "Red 1" '(64 0 255 1 1 0 1)
SF-ADJUSTMENT "Red 2" '(224 0 255 1 1 0 1)
SF-ADJUSTMENT "Green 1" '(128 0 255 1 1 0 1)
SF-ADJUSTMENT "Green 2" '(192 0 255 1 1 0 1)
SF-ADJUSTMENT "Blue 1" '(224 0 255 1 1 0 1)
SF-ADJUSTMENT "Blue 2" '(64 0 255 1 1 0 1)
SF-ADJUSTMENT "Flame Height" '(25 1 1000 1 1 1 1)
SF-ADJUSTMENT "Blur Radius" '(5 1 100 1 1 1 1)
SF-TOGGLE "Absolute Size?" FALSE
SF-VALUE "Image Width" "400"
SF-VALUE "Image Height" "150"
SF-TOGGLE "Flatten Layers?" FALSE
)
(script-fu-menu-register "script-fu-feurio-logo"
"<Toolbox>/Xtns/Logos")
| null | https://raw.githubusercontent.com/pixlsus/registry.gimp.org_static/ffcde7400f402728373ff6579947c6ffe87d1a5e/registry.gimp.org/files/feurio-logo.scm | scheme | feurio logo
This program is free software; you can redistribute it and/or modify
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
--------------------------------------------------------------------
- Support Gimp 2.0
- do not rely on external def set-pt
- fix License
- update script register
--------------------------------------------------------------------
| Copyright ( C ) 2002 - 2003
Copyright ( C ) 2004 - 2008
it under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
Foundation , Inc. , 675 Mass Ave , Cambridge , , USA .
version 1.0 by
version 2.0 by 2004/08/20
version 2.1 by 2005/02/08
- problem with gimp 2.2
version 2.4 by
- Support Gimp 2.4
version 2.4.1 by 2008/10/28
version 2.4.2 by 2008/11/03
(define (script-fu-feurio-logo inText inFont inFontSize inTextColor inRed1 inRed2 inGreen1 inGreen2 inBlue1 inBlue2 inHeight inBlurRadius inAbsolute inImageWidth inImageHeight inFlatten)
(define (set-pt a index x y)
(begin
(aset a (* index 2) x)
(aset a (+ (* index 2) 1) y)
)
)
(let*
(
(img ( car (gimp-image-new 10 10 RGB) ) )
(theText)
(theTextWidth)
(theTextHeight)
(imgWidth)
(imgHeight)
(theBufferX)
(theBufferY)
(theSel)
(theLayer (car (gimp-layer-new img 10 10 RGB-IMAGE "Layer" 100 NORMAL) ) )
(theTextLayer (car (gimp-layer-new img 10 10 RGB-IMAGE "Text Layer" 100 NORMAL) ) )
(theFeurioLayer (car (gimp-layer-new img 10 10 RGB-IMAGE "Feurio Layer" 100 NORMAL) ) )
(theTextMask)
(theFeurioMask)
(old-fg (car (gimp-context-get-foreground) ) )
(old-bg (car (gimp-context-get-background) ) )
)
(define (splineRed)
(let* ((a (cons-array 6 'byte)))
(set-pt a 0 0 0)
(set-pt a 1 inRed1 inRed2)
(set-pt a 2 255 255)
a
)
)
(define (splineGreen)
(let* ((a (cons-array 6 'byte)))
(set-pt a 0 0 0)
(set-pt a 1 inGreen1 inGreen2)
(set-pt a 2 255 255)
a
)
)
(define (splineBlue)
(let* ((a (cons-array 6 'byte)))
(set-pt a 0 0 0)
(set-pt a 1 inBlue1 inBlue2)
(set-pt a 2 255 255)
a
)
)
(gimp-image-add-layer img theLayer 0)
(gimp-image-add-layer img theTextLayer 0)
(gimp-image-add-layer img theFeurioLayer 0)
(gimp-context-set-background '(0 0 0) )
(gimp-context-set-foreground '(255 255 255) )
(gimp-selection-all img)
(gimp-edit-clear theLayer)
(gimp-edit-clear theTextLayer)
(gimp-edit-clear theFeurioLayer)
(gimp-selection-none img)
(set! theText (car (gimp-text-fontname img theLayer 0 0 inText 0 TRUE inFontSize PIXELS inFont)))
(set! theTextWidth (car (gimp-drawable-width theText) ) )
(set! theTextHeight (car (gimp-drawable-height theText) ) )
(set! imgWidth inImageWidth )
(set! imgHeight inImageHeight )
(if (= inAbsolute FALSE)
(set! imgWidth (+ theTextWidth (* 3 inHeight) ) )
)
(if (= inAbsolute FALSE)
(set! imgHeight (+ theTextHeight (* 4 inHeight) ) )
)
(set! theBufferX (/ (- imgWidth theTextWidth) 2) )
(set! theBufferY (/ (- imgHeight theTextHeight) 2) )
(gimp-image-resize img imgWidth imgHeight 0 0)
(gimp-layer-resize theLayer imgWidth imgHeight 0 0)
(gimp-layer-resize theTextLayer imgWidth imgHeight 0 0)
(gimp-layer-resize theFeurioLayer imgWidth imgHeight 0 0)
(gimp-layer-set-offsets theText theBufferX theBufferY)
(gimp-floating-sel-anchor theText)
(gimp-context-set-foreground inTextColor )
(gimp-edit-bucket-fill theTextLayer FG-BUCKET-FILL NORMAL 100 0 FALSE 0 0)
(plug-in-bump-map 1 img theTextLayer theLayer 135.0 45.0 3 0 0 0 0 TRUE FALSE 2)
(gimp-layer-add-alpha theTextLayer)
(set! theTextMask (car (gimp-layer-create-mask theFeurioLayer WHITE-MASK)))
(gimp-layer-add-mask theTextLayer theTextMask)
(gimp-edit-copy theLayer)
(set! theSel (car (gimp-edit-paste theTextMask FALSE)))
(gimp-floating-sel-anchor theSel)
(gimp-layer-remove-mask theTextLayer APPLY)
(gimp-context-set-foreground '(255 255 255) )
(set! theSel (car (gimp-edit-paste theFeurioLayer FALSE)))
(gimp-floating-sel-anchor theSel)
(gimp-by-color-select theFeurioLayer '(255 255 255) 15 0 FALSE FALSE 10 FALSE)
(gimp-selection-grow img (/ inHeight 5))
(gimp-edit-bucket-fill theFeurioLayer FG-BUCKET-FILL NORMAL 100 0 FALSE 0 0)
(gimp-context-set-foreground '(128 128 128) )
(gimp-selection-shrink img (/ inHeight 5))
(gimp-edit-bucket-fill theFeurioLayer FG-BUCKET-FILL NORMAL 100 0 FALSE 0 0)
(gimp-selection-none img)
(gimp-context-set-foreground '(255 255 255) )
(plug-in-ripple 1 img theFeurioLayer inHeight inHeight 1 0 1 TRUE FALSE)
(plug-in-ripple 1 img theFeurioLayer (* 2 inHeight) (/ inHeight 3) 1 0 1 TRUE FALSE)
(plug-in-spread 1 img theFeurioLayer inHeight inHeight)
(gimp-layer-add-alpha theFeurioLayer)
(set! theFeurioMask (car (gimp-layer-create-mask theFeurioLayer WHITE-MASK)))
(gimp-layer-add-mask theFeurioLayer theFeurioMask)
(gimp-edit-blend theFeurioMask FG-BG-RGB NORMAL LINEAR 100 0 REPEAT-NONE FALSE 0 0 FALSE FALSE 0 theBufferY 0 (- imgHeight theBufferY))
(plug-in-gauss-iir 1 img theFeurioLayer inBlurRadius 1 1)
(gimp-curves-spline theFeurioLayer BLUE-LUT 6 (splineBlue))
(gimp-curves-spline theFeurioLayer GREEN-LUT 6 (splineGreen))
(gimp-curves-spline theFeurioLayer RED-LUT 6 (splineRed))
(gimp-layer-remove-mask theFeurioLayer APPLY)
(plug-in-gauss-iir 1 img theLayer inBlurRadius 1 1)
(gimp-curves-spline theLayer BLUE-LUT 6 (splineBlue))
(gimp-curves-spline theLayer GREEN-LUT 6 (splineGreen))
(gimp-curves-spline theLayer RED-LUT 6 (splineRed))
(if (= inFlatten TRUE)
(gimp-image-flatten img)
()
)
(gimp-context-set-background old-bg)
(gimp-context-set-foreground old-fg)
(gimp-display-new img)
(list img theLayer theText)
Bereinigen Dirty - Flag
(gimp-image-clean-all img)
)
)
(script-fu-register
"script-fu-feurio-logo"
"MS - Feurio..."
"Creates a burning text logo."
"Michael Schalla"
"Michael Schalla"
"October 2002"
""
SF-STRING "Text" "Feurio"
SF-FONT "Font" "-*-Arial Black-*-r-*-*-24-*-*-*-p-*-*-*"
SF-ADJUSTMENT "Font Size" '(100 2 1000 1 10 0 1)
SF-COLOR "Color" '(224 0 0)
SF-ADJUSTMENT "Red 1" '(64 0 255 1 1 0 1)
SF-ADJUSTMENT "Red 2" '(224 0 255 1 1 0 1)
SF-ADJUSTMENT "Green 1" '(128 0 255 1 1 0 1)
SF-ADJUSTMENT "Green 2" '(192 0 255 1 1 0 1)
SF-ADJUSTMENT "Blue 1" '(224 0 255 1 1 0 1)
SF-ADJUSTMENT "Blue 2" '(64 0 255 1 1 0 1)
SF-ADJUSTMENT "Flame Height" '(25 1 1000 1 1 1 1)
SF-ADJUSTMENT "Blur Radius" '(5 1 100 1 1 1 1)
SF-TOGGLE "Absolute Size?" FALSE
SF-VALUE "Image Width" "400"
SF-VALUE "Image Height" "150"
SF-TOGGLE "Flatten Layers?" FALSE
)
(script-fu-menu-register "script-fu-feurio-logo"
"<Toolbox>/Xtns/Logos")
|
287b6eadcada7abcddbcf7f6dbde248f9d8bdcd2f9cd6911ae8d3cb3cbb38788 | Haskell-OpenAPI-Code-Generator/Stripe-Haskell-Library | TreasuryReceivedDebitsResourceLinkedFlows.hs | {-# LANGUAGE MultiWayIf #-}
CHANGE WITH CAUTION : This is a generated code file generated by -OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator .
{-# LANGUAGE OverloadedStrings #-}
-- | Contains the types generated from the schema TreasuryReceivedDebitsResourceLinkedFlows
module StripeAPI.Types.TreasuryReceivedDebitsResourceLinkedFlows where
import qualified Control.Monad.Fail
import qualified Data.Aeson
import qualified Data.Aeson as Data.Aeson.Encoding.Internal
import qualified Data.Aeson as Data.Aeson.Types
import qualified Data.Aeson as Data.Aeson.Types.FromJSON
import qualified Data.Aeson as Data.Aeson.Types.Internal
import qualified Data.Aeson as Data.Aeson.Types.ToJSON
import qualified Data.ByteString.Char8
import qualified Data.ByteString.Char8 as Data.ByteString.Internal
import qualified Data.Foldable
import qualified Data.Functor
import qualified Data.Maybe
import qualified Data.Scientific
import qualified Data.Text
import qualified Data.Text.Internal
import qualified Data.Time.Calendar as Data.Time.Calendar.Days
import qualified Data.Time.LocalTime as Data.Time.LocalTime.Internal.ZonedTime
import qualified GHC.Base
import qualified GHC.Classes
import qualified GHC.Int
import qualified GHC.Show
import qualified GHC.Types
import qualified StripeAPI.Common
import StripeAPI.TypeAlias
import qualified Prelude as GHC.Integer.Type
import qualified Prelude as GHC.Maybe
-- | Defines the object schema located at @components.schemas.treasury_received_debits_resource_linked_flows@ in the specification.
data TreasuryReceivedDebitsResourceLinkedFlows = TreasuryReceivedDebitsResourceLinkedFlows
| debit_reversal : The created as a result of this ReceivedDebit being reversed .
--
-- Constraints:
--
* Maximum length of 5000
treasuryReceivedDebitsResourceLinkedFlowsDebitReversal :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable Data.Text.Internal.Text)),
-- | inbound_transfer: Set if the ReceivedDebit is associated with an InboundTransfer\'s return of funds.
--
-- Constraints:
--
* Maximum length of 5000
treasuryReceivedDebitsResourceLinkedFlowsInboundTransfer :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable Data.Text.Internal.Text)),
-- | issuing_authorization: Set if the ReceivedDebit was created due to an [Issuing Authorization](https:\/\/stripe.com\/docs\/api\#issuing_authorizations) object.
--
-- Constraints:
--
* Maximum length of 5000
treasuryReceivedDebitsResourceLinkedFlowsIssuingAuthorization :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable Data.Text.Internal.Text)),
-- | issuing_transaction: Set if the ReceivedDebit is also viewable as an [Issuing Dispute](https:\/\/stripe.com\/docs\/api\#issuing_disputes) object.
--
-- Constraints:
--
* Maximum length of 5000
treasuryReceivedDebitsResourceLinkedFlowsIssuingTransaction :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable Data.Text.Internal.Text))
}
deriving
( GHC.Show.Show,
GHC.Classes.Eq
)
instance Data.Aeson.Types.ToJSON.ToJSON TreasuryReceivedDebitsResourceLinkedFlows where
toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("debit_reversal" Data.Aeson.Types.ToJSON..=)) (treasuryReceivedDebitsResourceLinkedFlowsDebitReversal obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("inbound_transfer" Data.Aeson.Types.ToJSON..=)) (treasuryReceivedDebitsResourceLinkedFlowsInboundTransfer obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("issuing_authorization" Data.Aeson.Types.ToJSON..=)) (treasuryReceivedDebitsResourceLinkedFlowsIssuingAuthorization obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("issuing_transaction" Data.Aeson.Types.ToJSON..=)) (treasuryReceivedDebitsResourceLinkedFlowsIssuingTransaction obj) : GHC.Base.mempty))
toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("debit_reversal" Data.Aeson.Types.ToJSON..=)) (treasuryReceivedDebitsResourceLinkedFlowsDebitReversal obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("inbound_transfer" Data.Aeson.Types.ToJSON..=)) (treasuryReceivedDebitsResourceLinkedFlowsInboundTransfer obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("issuing_authorization" Data.Aeson.Types.ToJSON..=)) (treasuryReceivedDebitsResourceLinkedFlowsIssuingAuthorization obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("issuing_transaction" Data.Aeson.Types.ToJSON..=)) (treasuryReceivedDebitsResourceLinkedFlowsIssuingTransaction obj) : GHC.Base.mempty)))
instance Data.Aeson.Types.FromJSON.FromJSON TreasuryReceivedDebitsResourceLinkedFlows where
parseJSON = Data.Aeson.Types.FromJSON.withObject "TreasuryReceivedDebitsResourceLinkedFlows" (\obj -> (((GHC.Base.pure TreasuryReceivedDebitsResourceLinkedFlows GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "debit_reversal")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "inbound_transfer")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "issuing_authorization")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "issuing_transaction"))
-- | Create a new 'TreasuryReceivedDebitsResourceLinkedFlows' with all required fields.
mkTreasuryReceivedDebitsResourceLinkedFlows :: TreasuryReceivedDebitsResourceLinkedFlows
mkTreasuryReceivedDebitsResourceLinkedFlows =
TreasuryReceivedDebitsResourceLinkedFlows
{ treasuryReceivedDebitsResourceLinkedFlowsDebitReversal = GHC.Maybe.Nothing,
treasuryReceivedDebitsResourceLinkedFlowsInboundTransfer = GHC.Maybe.Nothing,
treasuryReceivedDebitsResourceLinkedFlowsIssuingAuthorization = GHC.Maybe.Nothing,
treasuryReceivedDebitsResourceLinkedFlowsIssuingTransaction = GHC.Maybe.Nothing
}
| null | https://raw.githubusercontent.com/Haskell-OpenAPI-Code-Generator/Stripe-Haskell-Library/ba4401f083ff054f8da68c741f762407919de42f/src/StripeAPI/Types/TreasuryReceivedDebitsResourceLinkedFlows.hs | haskell | # LANGUAGE MultiWayIf #
# LANGUAGE OverloadedStrings #
| Contains the types generated from the schema TreasuryReceivedDebitsResourceLinkedFlows
| Defines the object schema located at @components.schemas.treasury_received_debits_resource_linked_flows@ in the specification.
Constraints:
| inbound_transfer: Set if the ReceivedDebit is associated with an InboundTransfer\'s return of funds.
Constraints:
| issuing_authorization: Set if the ReceivedDebit was created due to an [Issuing Authorization](https:\/\/stripe.com\/docs\/api\#issuing_authorizations) object.
Constraints:
| issuing_transaction: Set if the ReceivedDebit is also viewable as an [Issuing Dispute](https:\/\/stripe.com\/docs\/api\#issuing_disputes) object.
Constraints:
| Create a new 'TreasuryReceivedDebitsResourceLinkedFlows' with all required fields. | CHANGE WITH CAUTION : This is a generated code file generated by -OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator .
module StripeAPI.Types.TreasuryReceivedDebitsResourceLinkedFlows where
import qualified Control.Monad.Fail
import qualified Data.Aeson
import qualified Data.Aeson as Data.Aeson.Encoding.Internal
import qualified Data.Aeson as Data.Aeson.Types
import qualified Data.Aeson as Data.Aeson.Types.FromJSON
import qualified Data.Aeson as Data.Aeson.Types.Internal
import qualified Data.Aeson as Data.Aeson.Types.ToJSON
import qualified Data.ByteString.Char8
import qualified Data.ByteString.Char8 as Data.ByteString.Internal
import qualified Data.Foldable
import qualified Data.Functor
import qualified Data.Maybe
import qualified Data.Scientific
import qualified Data.Text
import qualified Data.Text.Internal
import qualified Data.Time.Calendar as Data.Time.Calendar.Days
import qualified Data.Time.LocalTime as Data.Time.LocalTime.Internal.ZonedTime
import qualified GHC.Base
import qualified GHC.Classes
import qualified GHC.Int
import qualified GHC.Show
import qualified GHC.Types
import qualified StripeAPI.Common
import StripeAPI.TypeAlias
import qualified Prelude as GHC.Integer.Type
import qualified Prelude as GHC.Maybe
data TreasuryReceivedDebitsResourceLinkedFlows = TreasuryReceivedDebitsResourceLinkedFlows
| debit_reversal : The created as a result of this ReceivedDebit being reversed .
* Maximum length of 5000
treasuryReceivedDebitsResourceLinkedFlowsDebitReversal :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable Data.Text.Internal.Text)),
* Maximum length of 5000
treasuryReceivedDebitsResourceLinkedFlowsInboundTransfer :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable Data.Text.Internal.Text)),
* Maximum length of 5000
treasuryReceivedDebitsResourceLinkedFlowsIssuingAuthorization :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable Data.Text.Internal.Text)),
* Maximum length of 5000
treasuryReceivedDebitsResourceLinkedFlowsIssuingTransaction :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable Data.Text.Internal.Text))
}
deriving
( GHC.Show.Show,
GHC.Classes.Eq
)
instance Data.Aeson.Types.ToJSON.ToJSON TreasuryReceivedDebitsResourceLinkedFlows where
toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("debit_reversal" Data.Aeson.Types.ToJSON..=)) (treasuryReceivedDebitsResourceLinkedFlowsDebitReversal obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("inbound_transfer" Data.Aeson.Types.ToJSON..=)) (treasuryReceivedDebitsResourceLinkedFlowsInboundTransfer obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("issuing_authorization" Data.Aeson.Types.ToJSON..=)) (treasuryReceivedDebitsResourceLinkedFlowsIssuingAuthorization obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("issuing_transaction" Data.Aeson.Types.ToJSON..=)) (treasuryReceivedDebitsResourceLinkedFlowsIssuingTransaction obj) : GHC.Base.mempty))
toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("debit_reversal" Data.Aeson.Types.ToJSON..=)) (treasuryReceivedDebitsResourceLinkedFlowsDebitReversal obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("inbound_transfer" Data.Aeson.Types.ToJSON..=)) (treasuryReceivedDebitsResourceLinkedFlowsInboundTransfer obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("issuing_authorization" Data.Aeson.Types.ToJSON..=)) (treasuryReceivedDebitsResourceLinkedFlowsIssuingAuthorization obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("issuing_transaction" Data.Aeson.Types.ToJSON..=)) (treasuryReceivedDebitsResourceLinkedFlowsIssuingTransaction obj) : GHC.Base.mempty)))
instance Data.Aeson.Types.FromJSON.FromJSON TreasuryReceivedDebitsResourceLinkedFlows where
parseJSON = Data.Aeson.Types.FromJSON.withObject "TreasuryReceivedDebitsResourceLinkedFlows" (\obj -> (((GHC.Base.pure TreasuryReceivedDebitsResourceLinkedFlows GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "debit_reversal")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "inbound_transfer")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "issuing_authorization")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "issuing_transaction"))
mkTreasuryReceivedDebitsResourceLinkedFlows :: TreasuryReceivedDebitsResourceLinkedFlows
mkTreasuryReceivedDebitsResourceLinkedFlows =
TreasuryReceivedDebitsResourceLinkedFlows
{ treasuryReceivedDebitsResourceLinkedFlowsDebitReversal = GHC.Maybe.Nothing,
treasuryReceivedDebitsResourceLinkedFlowsInboundTransfer = GHC.Maybe.Nothing,
treasuryReceivedDebitsResourceLinkedFlowsIssuingAuthorization = GHC.Maybe.Nothing,
treasuryReceivedDebitsResourceLinkedFlowsIssuingTransaction = GHC.Maybe.Nothing
}
|
43d40e2a636d347e948c058697a03cf93c4db1a1b8099800c620128e876b9b9a | yminsky/incremental-tutorial | server.ml | open! Core
open! Async
open! Import
let events_impl ~(make_stream:unit -> (unit -> (Time.t * Event.t)) Staged.t) ~stats =
Rpc.Pipe_rpc.implement Protocol.events (fun addr () ->
Log.Global.info !"Client connected on %{sexp:Socket.Address.Inet.t}" addr;
let next = unstage (make_stream ()) in
let (r,w) = Pipe.create () in
let log msg =
Log.Global.info
!"%{sexp:Socket.Address.Inet.t}: %s" addr msg
in
let started_at = Time_ns.now () in
let events_written = ref 0 in
begin
if stats then
Clock.every (Time.Span.of_sec 1.) ~stop:(Pipe.closed w)
(fun () ->
let sec_since_start =
Time_ns.diff (Time_ns.now ()) started_at
|> Time_ns.Span.to_sec
in
log (sprintf "Total-events: %d Events/sec %.3f%!"
!events_written
(Float.of_int !events_written /. sec_since_start)))
end;
let rec write () =
let (time,event) = next () in
if Pipe.is_closed w then (
log "Client disconnected!";
Deferred.unit
) else (
let%bind () = at time in
let%bind () = Pipe.write_if_open w event in
incr events_written;
write ()
)
in
don't_wait_for (write ());
return (Ok r))
let implementations ~make_stream ~stats =
Rpc.Implementations.create_exn
~implementations:[events_impl ~make_stream ~stats]
~on_unknown_rpc:`Raise
let serve ~make_stream ~port ~stats =
let%bind _tcp_server =
Tcp.Server.create
~on_handler_error:`Ignore
(Tcp.on_port port)
(fun addr r w ->
Rpc.Connection.server_with_close r w
~connection_state:(fun _ -> addr)
~on_handshake_error:`Raise
~implementations:(implementations ~make_stream ~stats)
)
in
Log.Global.info "Server started";
Deferred.unit
let go ~port ~num_hosts ~time_scale ~stats =
let make_stream =
let time = Time.now () in
let rs = Random.State.make_self_init () in
(fun () ->
Generator.stream
(Random.State.copy rs)
time
~num_hosts
~pct_initially_active:0.20
~time_scale
)
in
let%bind () = serve ~make_stream ~port ~stats in
Deferred.never ()
let command =
let open Command.Let_syntax in
Command.async'
~summary:"start server"
[%map_open
let port =
flag "port" (required int) ~doc:"PORT port to listen for clients"
and num_hosts =
flag "hosts" (optional_with_default 1000 int)
~doc:"N number of hosts to simulate"
and time_scale =
flag "time-scale" (optional_with_default (Time.Span.of_sec 0.01) time_span)
~doc:"maximum time to the next event"
and stats =
flag "print-stats" no_arg ~doc:" Print stats about event generation per client."
in
fun () ->
go ~port ~num_hosts ~time_scale ~stats
]
| null | https://raw.githubusercontent.com/yminsky/incremental-tutorial/756dfe36ec1b0a102128b3fa78a6c6762bdab90a/shared/server.ml | ocaml | open! Core
open! Async
open! Import
let events_impl ~(make_stream:unit -> (unit -> (Time.t * Event.t)) Staged.t) ~stats =
Rpc.Pipe_rpc.implement Protocol.events (fun addr () ->
Log.Global.info !"Client connected on %{sexp:Socket.Address.Inet.t}" addr;
let next = unstage (make_stream ()) in
let (r,w) = Pipe.create () in
let log msg =
Log.Global.info
!"%{sexp:Socket.Address.Inet.t}: %s" addr msg
in
let started_at = Time_ns.now () in
let events_written = ref 0 in
begin
if stats then
Clock.every (Time.Span.of_sec 1.) ~stop:(Pipe.closed w)
(fun () ->
let sec_since_start =
Time_ns.diff (Time_ns.now ()) started_at
|> Time_ns.Span.to_sec
in
log (sprintf "Total-events: %d Events/sec %.3f%!"
!events_written
(Float.of_int !events_written /. sec_since_start)))
end;
let rec write () =
let (time,event) = next () in
if Pipe.is_closed w then (
log "Client disconnected!";
Deferred.unit
) else (
let%bind () = at time in
let%bind () = Pipe.write_if_open w event in
incr events_written;
write ()
)
in
don't_wait_for (write ());
return (Ok r))
let implementations ~make_stream ~stats =
Rpc.Implementations.create_exn
~implementations:[events_impl ~make_stream ~stats]
~on_unknown_rpc:`Raise
let serve ~make_stream ~port ~stats =
let%bind _tcp_server =
Tcp.Server.create
~on_handler_error:`Ignore
(Tcp.on_port port)
(fun addr r w ->
Rpc.Connection.server_with_close r w
~connection_state:(fun _ -> addr)
~on_handshake_error:`Raise
~implementations:(implementations ~make_stream ~stats)
)
in
Log.Global.info "Server started";
Deferred.unit
let go ~port ~num_hosts ~time_scale ~stats =
let make_stream =
let time = Time.now () in
let rs = Random.State.make_self_init () in
(fun () ->
Generator.stream
(Random.State.copy rs)
time
~num_hosts
~pct_initially_active:0.20
~time_scale
)
in
let%bind () = serve ~make_stream ~port ~stats in
Deferred.never ()
let command =
let open Command.Let_syntax in
Command.async'
~summary:"start server"
[%map_open
let port =
flag "port" (required int) ~doc:"PORT port to listen for clients"
and num_hosts =
flag "hosts" (optional_with_default 1000 int)
~doc:"N number of hosts to simulate"
and time_scale =
flag "time-scale" (optional_with_default (Time.Span.of_sec 0.01) time_span)
~doc:"maximum time to the next event"
and stats =
flag "print-stats" no_arg ~doc:" Print stats about event generation per client."
in
fun () ->
go ~port ~num_hosts ~time_scale ~stats
]
| |
948b358a2e8f2d8eb0f1f5282b14b94b6d70d8087ab3fa31beeb6298d2effaef | sbcl/sbcl | dlisp.lisp | This software is part of the SBCL system . See the README file for
;;;; more information.
This software is derived from software originally released by Xerox
;;;; Corporation. Copyright and release statements follow. Later modifications
;;;; to the software are in the public domain and are provided with
;;;; absolutely no warranty. See the COPYING and CREDITS files for more
;;;; information.
copyright information from original PCL sources :
;;;;
Copyright ( c ) 1985 , 1986 , 1987 , 1988 , 1989 , 1990 Xerox Corporation .
;;;; All rights reserved.
;;;;
;;;; Use and copying of this software and preparation of derivative works based
;;;; upon this software are permitted. Any distribution of this software or
derivative works must comply with all applicable United States export
;;;; control laws.
;;;;
This software is made available AS IS , and Xerox Corporation makes no
;;;; warranty about the software, its performance or its conformity to any
;;;; specification.
(in-package "SB-PCL")
;;;; some support stuff for getting a hold of symbols that we need when
;;;; building the discriminator codes. It's OK for these to be interned
;;;; symbols because we don't capture any user code in the scope in which
;;;; these symbols are bound.
(declaim (list *dfun-arg-symbols*))
(define-load-time-global *dfun-arg-symbols* '(.ARG0. .ARG1. .ARG2. .ARG3.))
(defun dfun-arg-symbol (arg-number)
(or (nth arg-number *dfun-arg-symbols*)
(pcl-format-symbol ".ARG~A." arg-number)))
(declaim (list *slot-vector-symbols*))
(define-load-time-global *slot-vector-symbols* '(.SLOTS0. .SLOTS1. .SLOTS2. .SLOTS3.))
(defun slot-vector-symbol (arg-number)
(or (nth arg-number *slot-vector-symbols*)
(pcl-format-symbol ".SLOTS~A." arg-number)))
(declaim (inline make-dfun-required-args))
(defun make-dfun-required-args (count)
(declare (type index count))
N.B. : do n't PUSH and NREVERSE here . COLLECT will cons in the system TLAB ,
but NREVERSE wo n't because we do n't inline NREVERSE .
(collect ((result))
(dotimes (i count (result))
(result (dfun-arg-symbol i)))))
(defun make-dfun-lambda-list (nargs applyp)
(let ((required (make-dfun-required-args nargs)))
(if applyp
(nconc required
;; Use &MORE arguments to avoid consing up an &REST list
;; that we might not need at all. See MAKE-EMF-CALL and
INVOKE - EFFECTIVE - METHOD - FUNCTION for the other
;; pieces.
'(&more .dfun-more-context. .dfun-more-count.))
required)))
(defun make-dlap-lambda-list (nargs applyp)
(let ((required (make-dfun-required-args nargs)))
;; Return the full lambda list, the required arguments, a form
;; that will generate a rest-list, and a list of the &MORE
;; parameters used.
Beware of deep voodoo ! The DEFKNOWN for % LISTIFY - REST - ARGS says that its
second argument is INDEX , but the THE form below is " weaker " on account
of the vop operand restrictions or something that I do n't understand .
Which is to say , PCL compilation reliably broke when changed to INDEX .
(if applyp
(values (sb-impl::sys-tlab-append required '(&more .more-context. .more-count.))
required
'((sb-c:%listify-rest-args
.more-context. (the (and unsigned-byte fixnum)
.more-count.)))
'(.more-context. .more-count.))
(values required required nil nil))))
(defun make-emf-call (nargs applyp fn-variable &optional emf-type)
(let ((required (make-dfun-required-args nargs)))
`(,(if (eq emf-type 'fast-method-call)
'invoke-effective-method-function-fast
'invoke-effective-method-function)
,fn-variable
,applyp
:required-args ,required
INVOKE - EFFECTIVE - METHOD - FUNCTION will decide whether to use
;; the :REST-ARG version or the :MORE-ARG version depending on
;; the type of the EMF.
:rest-arg ,(if applyp
;; Creates a list from the &MORE arguments.
'((sb-c:%listify-rest-args ; See above re. voodoo
.dfun-more-context.
(the (and unsigned-byte fixnum)
.dfun-more-count.)))
nil)
:more-arg ,(when applyp
'(.dfun-more-context. .dfun-more-count.)))))
(defun make-fast-method-call-lambda-list (nargs applyp)
(list* '.pv. '.next-method-call. (make-dfun-lambda-list nargs applyp)))
;;; Emitting various accessors.
(defun emit-one-class-reader (class-slot-p)
(emit-reader/writer :reader 1 class-slot-p))
(defun emit-one-class-boundp (class-slot-p)
(emit-reader/writer :boundp 1 class-slot-p))
(defun emit-one-class-writer (class-slot-p)
(emit-reader/writer :writer 1 class-slot-p))
(defun emit-one-class-makunbound (class-slot-p)
(emit-reader/writer :makunbound 1 class-slot-p))
(defun emit-two-class-reader (class-slot-p)
(emit-reader/writer :reader 2 class-slot-p))
(defun emit-two-class-boundp (class-slot-p)
(emit-reader/writer :boundp 2 class-slot-p))
(defun emit-two-class-writer (class-slot-p)
(emit-reader/writer :writer 2 class-slot-p))
(defun emit-two-class-makunbound (class-slot-p)
(emit-reader/writer :makunbound 2 class-slot-p))
;;; --------------------------------
(defun emit-one-index-readers (class-slot-p)
(emit-one-or-n-index-reader/writer :reader nil class-slot-p))
(defun emit-one-index-boundps (class-slot-p)
(emit-one-or-n-index-reader/writer :boundp nil class-slot-p))
(defun emit-one-index-writers (class-slot-p)
(emit-one-or-n-index-reader/writer :writer nil class-slot-p))
(defun emit-one-index-makunbounds (class-slot-p)
(emit-one-or-n-index-reader/writer :makunbound nil class-slot-p))
(defun emit-n-n-readers ()
(emit-one-or-n-index-reader/writer :reader t nil))
(defun emit-n-n-boundps ()
(emit-one-or-n-index-reader/writer :boundp t nil))
(defun emit-n-n-writers ()
(emit-one-or-n-index-reader/writer :writer t nil))
(defun emit-n-n-makunbounds ()
(emit-one-or-n-index-reader/writer :makunbound t nil))
;;; --------------------------------
(defun emit-checking (metatypes applyp)
(emit-checking-or-caching nil nil metatypes applyp))
(defun emit-caching (metatypes applyp)
(emit-checking-or-caching t nil metatypes applyp))
(defun emit-in-checking-cache-p (metatypes)
(emit-checking-or-caching nil t metatypes nil))
(defun emit-constant-value (metatypes)
(emit-checking-or-caching t t metatypes nil))
;;; --------------------------------
;;; FIXME: What do these variables mean?
(defvar *precompiling-lap* nil)
(defun emit-default-only (metatypes applyp)
(multiple-value-bind (lambda-list args rest-arg more-arg)
(make-dlap-lambda-list (length metatypes) applyp)
(generating-lisp '(emf)
lambda-list
`(invoke-effective-method-function emf
,applyp
:required-args ,args
:more-arg ,more-arg
:rest-arg ,rest-arg))))
;;; --------------------------------
(defun generating-lisp (closure-variables args form)
(let ((lambda `(lambda ,closure-variables
,@(when (member 'miss-fn closure-variables)
`((declare (type function miss-fn))))
(declare (optimize (sb-c:store-source-form 0)))
(declare (optimize (sb-c::store-closure-debug-pointer 3)))
#'(lambda ,args
(let () ; What is this LET doing?
(declare #.*optimize-speed*)
,form)))))
(values (if *precompiling-lap*
`#',lambda
(pcl-compile lambda :safe))
nil)))
note on implementation for CMU 17 and later ( including SBCL ):
;;; Since STD-INSTANCE-P is weakened, that branch may run on non-PCL
;;; instances (structures). The result will be the non-wrapper layout
;;; for the structure, which will cause a miss. The "slots" will be
whatever the first slot is , but will be ignored . Similarly ,
;;; FSC-INSTANCE-P returns true on funcallable structures as well as
PCL fins .
(defun emit-reader/writer (reader/writer 1-or-2-class class-slot-p)
(let ((instance nil)
(arglist ())
(closure-variables ())
(read-form (emit-slot-read-form class-slot-p 'index 'slots)))
(ecase reader/writer
((:reader :boundp :makunbound)
(setq instance (dfun-arg-symbol 0)
arglist (list instance)))
(:writer (setq instance (dfun-arg-symbol 1)
arglist (list (dfun-arg-symbol 0) instance))))
(ecase 1-or-2-class
(1 (setq closure-variables '(wrapper-0 index miss-fn)))
(2 (setq closure-variables '(wrapper-0 wrapper-1 index miss-fn))))
(generating-lisp
closure-variables
arglist
`(let* (,@(unless class-slot-p `((slots nil)))
(wrapper (cond ((std-instance-p ,instance)
,@(unless class-slot-p
`((setq slots
(std-instance-slots ,instance))))
(%instance-wrapper ,instance))
((fsc-instance-p ,instance)
,@(unless class-slot-p
`((setq slots
(fsc-instance-slots ,instance))))
(%fun-wrapper ,instance)))))
(block access
(when (and wrapper
(not (zerop (wrapper-clos-hash wrapper)))
,@(if (eql 1 1-or-2-class)
`((eq wrapper wrapper-0))
`((or (eq wrapper wrapper-0)
(eq wrapper wrapper-1)))))
,@(ecase reader/writer
(:reader
`((let ((value ,read-form))
(unless (unbound-marker-p value)
(return-from access value)))))
(:boundp
`((let ((value ,read-form))
(return-from access (not (unbound-marker-p value))))))
(:makunbound
`(progn (setf ,read-form +slot-unbound+)
,instance))
(:writer
`((return-from access (setf ,read-form ,(car arglist)))))))
(funcall miss-fn ,@arglist))))))
(defun emit-slot-read-form (class-slot-p index slots)
(if class-slot-p
`(cdr ,index)
`(clos-slots-ref ,slots ,index)))
(defun emit-boundp-check (value-form miss-fn arglist)
`(let ((value ,value-form))
(if (unbound-marker-p value)
(funcall ,miss-fn ,@arglist)
value)))
(defun emit-slot-access (reader/writer class-slot-p slots
index miss-fn arglist)
(let ((read-form (emit-slot-read-form class-slot-p index slots)))
(ecase reader/writer
(:reader (emit-boundp-check read-form miss-fn arglist))
(:boundp `(not (unbound-marker-p ,read-form)))
(:makunbound `(progn (setf ,read-form +slot-unbound+) ,(car arglist)))
(:writer `(setf ,read-form ,(car arglist))))))
(defmacro emit-reader/writer-macro (reader/writer 1-or-2-class class-slot-p)
(let ((*precompiling-lap* t))
(values
(emit-reader/writer reader/writer 1-or-2-class class-slot-p))))
;; If CACHED-INDEX-P is false, then the slot location is a constant and
;; the cache holds layouts eligible to use that index.
;; If true, then the cache is a map of layout -> index.
(defun emit-one-or-n-index-reader/writer (reader/writer
cached-index-p
class-slot-p)
(multiple-value-bind (arglist metatypes)
(ecase reader/writer
((:reader :boundp :makunbound)
(values (list (dfun-arg-symbol 0))
'(standard-instance)))
(:writer (values (list (dfun-arg-symbol 0) (dfun-arg-symbol 1))
'(t standard-instance))))
(generating-lisp
`(cache ,@(unless cached-index-p '(index)) miss-fn)
arglist
`(let (,@(unless class-slot-p '(slots))
,@(when cached-index-p '(index)))
,(emit-dlap 'cache arglist metatypes
(emit-slot-access reader/writer class-slot-p
'slots 'index 'miss-fn arglist)
`(funcall miss-fn ,@arglist)
(when cached-index-p 'index)
(unless class-slot-p '(slots)))))))
(defmacro emit-one-or-n-index-reader/writer-macro
(reader/writer cached-index-p class-slot-p)
(let ((*precompiling-lap* t))
(values
(emit-one-or-n-index-reader/writer reader/writer
cached-index-p
class-slot-p))))
(defun emit-miss (miss-fn args applyp)
(if applyp
`(multiple-value-call ,miss-fn ,@args
(sb-c:%more-arg-values .more-context.
0
.more-count.))
`(funcall ,miss-fn ,@args)))
;; (cache-emf, return-value):
NIL / NIL : GF has a single EMF . Invoke it when layouts are in cache .
NIL / T : GF has a single EMF . Return T when layouts are in cache .
;; T / NIL : Look for the EMF for argument layouts. Invoke it when in cache.
;; T / T : Look for the EMF for argument layouts. Return it when in cache.
;;
METATYPES must be acceptable to EMIT - FETCH - WRAPPER .
APPLYP says whether there is a & MORE context .
(defun emit-checking-or-caching (cached-emf-p return-value-p metatypes applyp)
(multiple-value-bind (lambda-list args rest-arg more-arg)
(make-dlap-lambda-list (length metatypes) applyp)
(generating-lisp
`(cache ,@(unless cached-emf-p '(emf)) miss-fn)
lambda-list
`(let (,@(when cached-emf-p '(emf)))
,(emit-dlap 'cache args metatypes
(if return-value-p
(if cached-emf-p 'emf t)
`(invoke-effective-method-function
emf ,applyp
:required-args ,args
:more-arg ,more-arg
:rest-arg ,rest-arg))
(emit-miss 'miss-fn args applyp)
(when cached-emf-p 'emf))))))
(defmacro emit-checking-or-caching-macro (cached-emf-p
return-value-p
metatypes
applyp)
(let ((*precompiling-lap* t))
(values
(emit-checking-or-caching cached-emf-p return-value-p metatypes applyp))))
(defun emit-dlap (cache-var args metatypes hit-form miss-form value-var
&optional slot-vars)
(let* ((index -1)
(miss-tag (gensym "MISSED"))
(wrapper-bindings (mapcan (lambda (arg mt)
(unless (eq mt t)
(incf index)
`((,(pcl-format-symbol "WRAPPER-~D" index)
,(emit-fetch-wrapper
mt arg miss-tag (pop slot-vars))))))
args metatypes))
(wrapper-vars (mapcar #'car wrapper-bindings)))
(declare (fixnum index))
(unless wrapper-vars
(error "Every metatype is T."))
`(prog ()
(return
(let ,wrapper-bindings
,(emit-cache-lookup cache-var wrapper-vars miss-tag value-var)
,hit-form))
,miss-tag
(return ,miss-form))))
SLOTS - VAR , if supplied , is the variable to update with instance - slots
;; by side-effect of fetching the wrapper for ARGUMENT.
(defun emit-fetch-wrapper (metatype argument miss-tag &optional slots-var)
(ecase metatype
((standard-instance)
;; This branch may run on non-pcl instances (structures). The
;; result will be the non-wrapper layout for the structure, which
;; will cause a miss. Since refencing the structure is rather iffy
;; if it should have no slots, or only raw slots, we use FOR-STD-CLASS-P
;; to ensure that we have a wrapper.
;;
;; FIXME: If we unify layouts and wrappers we can use
;; instance-slots-layout instead of for-std-class-p, as if there
;; are no layouts there are no slots to worry about.
(with-unique-names (wrapper)
`(cond ((std-instance-p ,argument)
,(if slots-var
`(let ((,wrapper (%instance-wrapper ,argument)))
(when (layout-for-pcl-obj-p ,wrapper)
(setq ,slots-var (std-instance-slots ,argument)))
,wrapper)
`(%instance-wrapper ,argument)))
((fsc-instance-p ,argument)
,(if slots-var
`(let ((,wrapper (%fun-wrapper ,argument)))
(when (layout-for-pcl-obj-p ,wrapper)
(setq ,slots-var (fsc-instance-slots ,argument)))
,wrapper)
`(%fun-wrapper ,argument)))
(t (go ,miss-tag)))))
;; Sep92 PCL used to distinguish between some of these cases (and
spuriously exclude others ) . Since in SBCL
;; WRAPPER-OF/LAYOUT-OF/BUILT-IN-OR-STRUCTURE-WRAPPER are all
;; equivalent and inlined to each other, we can collapse some
;; spurious differences.
((class system-instance structure-instance condition-instance)
(when slots-var
(bug "SLOT requested for metatype ~S, but it isn't going to happen."
metatype))
`(wrapper-of ,argument))
a metatype of NIL should never be seen here , as NIL is only in
;; the metatypes before a generic function is fully initialized.
;; T should never be seen because we never need to get a wrapper
;; to do dispatch if all methods have T as the respective
;; specializer.
((t nil)
(bug "~@<metatype ~S seen in ~S.~@:>" metatype 'emit-fetch-wrapper))))
| null | https://raw.githubusercontent.com/sbcl/sbcl/cacbb24d03cbc1309447bfcd72a5cd17dd2d0e8b/src/pcl/dlisp.lisp | lisp | more information.
Corporation. Copyright and release statements follow. Later modifications
to the software are in the public domain and are provided with
absolutely no warranty. See the COPYING and CREDITS files for more
information.
All rights reserved.
Use and copying of this software and preparation of derivative works based
upon this software are permitted. Any distribution of this software or
control laws.
warranty about the software, its performance or its conformity to any
specification.
some support stuff for getting a hold of symbols that we need when
building the discriminator codes. It's OK for these to be interned
symbols because we don't capture any user code in the scope in which
these symbols are bound.
Use &MORE arguments to avoid consing up an &REST list
that we might not need at all. See MAKE-EMF-CALL and
pieces.
Return the full lambda list, the required arguments, a form
that will generate a rest-list, and a list of the &MORE
parameters used.
the :REST-ARG version or the :MORE-ARG version depending on
the type of the EMF.
Creates a list from the &MORE arguments.
See above re. voodoo
Emitting various accessors.
--------------------------------
--------------------------------
--------------------------------
FIXME: What do these variables mean?
--------------------------------
What is this LET doing?
Since STD-INSTANCE-P is weakened, that branch may run on non-PCL
instances (structures). The result will be the non-wrapper layout
for the structure, which will cause a miss. The "slots" will be
FSC-INSTANCE-P returns true on funcallable structures as well as
If CACHED-INDEX-P is false, then the slot location is a constant and
the cache holds layouts eligible to use that index.
If true, then the cache is a map of layout -> index.
(cache-emf, return-value):
T / NIL : Look for the EMF for argument layouts. Invoke it when in cache.
T / T : Look for the EMF for argument layouts. Return it when in cache.
by side-effect of fetching the wrapper for ARGUMENT.
This branch may run on non-pcl instances (structures). The
result will be the non-wrapper layout for the structure, which
will cause a miss. Since refencing the structure is rather iffy
if it should have no slots, or only raw slots, we use FOR-STD-CLASS-P
to ensure that we have a wrapper.
FIXME: If we unify layouts and wrappers we can use
instance-slots-layout instead of for-std-class-p, as if there
are no layouts there are no slots to worry about.
Sep92 PCL used to distinguish between some of these cases (and
WRAPPER-OF/LAYOUT-OF/BUILT-IN-OR-STRUCTURE-WRAPPER are all
equivalent and inlined to each other, we can collapse some
spurious differences.
the metatypes before a generic function is fully initialized.
T should never be seen because we never need to get a wrapper
to do dispatch if all methods have T as the respective
specializer. | This software is part of the SBCL system . See the README file for
This software is derived from software originally released by Xerox
copyright information from original PCL sources :
Copyright ( c ) 1985 , 1986 , 1987 , 1988 , 1989 , 1990 Xerox Corporation .
derivative works must comply with all applicable United States export
This software is made available AS IS , and Xerox Corporation makes no
(in-package "SB-PCL")
(declaim (list *dfun-arg-symbols*))
(define-load-time-global *dfun-arg-symbols* '(.ARG0. .ARG1. .ARG2. .ARG3.))
(defun dfun-arg-symbol (arg-number)
(or (nth arg-number *dfun-arg-symbols*)
(pcl-format-symbol ".ARG~A." arg-number)))
(declaim (list *slot-vector-symbols*))
(define-load-time-global *slot-vector-symbols* '(.SLOTS0. .SLOTS1. .SLOTS2. .SLOTS3.))
(defun slot-vector-symbol (arg-number)
(or (nth arg-number *slot-vector-symbols*)
(pcl-format-symbol ".SLOTS~A." arg-number)))
(declaim (inline make-dfun-required-args))
(defun make-dfun-required-args (count)
(declare (type index count))
N.B. : do n't PUSH and NREVERSE here . COLLECT will cons in the system TLAB ,
but NREVERSE wo n't because we do n't inline NREVERSE .
(collect ((result))
(dotimes (i count (result))
(result (dfun-arg-symbol i)))))
(defun make-dfun-lambda-list (nargs applyp)
(let ((required (make-dfun-required-args nargs)))
(if applyp
(nconc required
INVOKE - EFFECTIVE - METHOD - FUNCTION for the other
'(&more .dfun-more-context. .dfun-more-count.))
required)))
(defun make-dlap-lambda-list (nargs applyp)
(let ((required (make-dfun-required-args nargs)))
Beware of deep voodoo ! The DEFKNOWN for % LISTIFY - REST - ARGS says that its
second argument is INDEX , but the THE form below is " weaker " on account
of the vop operand restrictions or something that I do n't understand .
Which is to say , PCL compilation reliably broke when changed to INDEX .
(if applyp
(values (sb-impl::sys-tlab-append required '(&more .more-context. .more-count.))
required
'((sb-c:%listify-rest-args
.more-context. (the (and unsigned-byte fixnum)
.more-count.)))
'(.more-context. .more-count.))
(values required required nil nil))))
(defun make-emf-call (nargs applyp fn-variable &optional emf-type)
(let ((required (make-dfun-required-args nargs)))
`(,(if (eq emf-type 'fast-method-call)
'invoke-effective-method-function-fast
'invoke-effective-method-function)
,fn-variable
,applyp
:required-args ,required
INVOKE - EFFECTIVE - METHOD - FUNCTION will decide whether to use
:rest-arg ,(if applyp
.dfun-more-context.
(the (and unsigned-byte fixnum)
.dfun-more-count.)))
nil)
:more-arg ,(when applyp
'(.dfun-more-context. .dfun-more-count.)))))
(defun make-fast-method-call-lambda-list (nargs applyp)
(list* '.pv. '.next-method-call. (make-dfun-lambda-list nargs applyp)))
(defun emit-one-class-reader (class-slot-p)
(emit-reader/writer :reader 1 class-slot-p))
(defun emit-one-class-boundp (class-slot-p)
(emit-reader/writer :boundp 1 class-slot-p))
(defun emit-one-class-writer (class-slot-p)
(emit-reader/writer :writer 1 class-slot-p))
(defun emit-one-class-makunbound (class-slot-p)
(emit-reader/writer :makunbound 1 class-slot-p))
(defun emit-two-class-reader (class-slot-p)
(emit-reader/writer :reader 2 class-slot-p))
(defun emit-two-class-boundp (class-slot-p)
(emit-reader/writer :boundp 2 class-slot-p))
(defun emit-two-class-writer (class-slot-p)
(emit-reader/writer :writer 2 class-slot-p))
(defun emit-two-class-makunbound (class-slot-p)
(emit-reader/writer :makunbound 2 class-slot-p))
(defun emit-one-index-readers (class-slot-p)
(emit-one-or-n-index-reader/writer :reader nil class-slot-p))
(defun emit-one-index-boundps (class-slot-p)
(emit-one-or-n-index-reader/writer :boundp nil class-slot-p))
(defun emit-one-index-writers (class-slot-p)
(emit-one-or-n-index-reader/writer :writer nil class-slot-p))
(defun emit-one-index-makunbounds (class-slot-p)
(emit-one-or-n-index-reader/writer :makunbound nil class-slot-p))
(defun emit-n-n-readers ()
(emit-one-or-n-index-reader/writer :reader t nil))
(defun emit-n-n-boundps ()
(emit-one-or-n-index-reader/writer :boundp t nil))
(defun emit-n-n-writers ()
(emit-one-or-n-index-reader/writer :writer t nil))
(defun emit-n-n-makunbounds ()
(emit-one-or-n-index-reader/writer :makunbound t nil))
(defun emit-checking (metatypes applyp)
(emit-checking-or-caching nil nil metatypes applyp))
(defun emit-caching (metatypes applyp)
(emit-checking-or-caching t nil metatypes applyp))
(defun emit-in-checking-cache-p (metatypes)
(emit-checking-or-caching nil t metatypes nil))
(defun emit-constant-value (metatypes)
(emit-checking-or-caching t t metatypes nil))
(defvar *precompiling-lap* nil)
(defun emit-default-only (metatypes applyp)
(multiple-value-bind (lambda-list args rest-arg more-arg)
(make-dlap-lambda-list (length metatypes) applyp)
(generating-lisp '(emf)
lambda-list
`(invoke-effective-method-function emf
,applyp
:required-args ,args
:more-arg ,more-arg
:rest-arg ,rest-arg))))
(defun generating-lisp (closure-variables args form)
(let ((lambda `(lambda ,closure-variables
,@(when (member 'miss-fn closure-variables)
`((declare (type function miss-fn))))
(declare (optimize (sb-c:store-source-form 0)))
(declare (optimize (sb-c::store-closure-debug-pointer 3)))
#'(lambda ,args
(declare #.*optimize-speed*)
,form)))))
(values (if *precompiling-lap*
`#',lambda
(pcl-compile lambda :safe))
nil)))
note on implementation for CMU 17 and later ( including SBCL ):
whatever the first slot is , but will be ignored . Similarly ,
PCL fins .
(defun emit-reader/writer (reader/writer 1-or-2-class class-slot-p)
(let ((instance nil)
(arglist ())
(closure-variables ())
(read-form (emit-slot-read-form class-slot-p 'index 'slots)))
(ecase reader/writer
((:reader :boundp :makunbound)
(setq instance (dfun-arg-symbol 0)
arglist (list instance)))
(:writer (setq instance (dfun-arg-symbol 1)
arglist (list (dfun-arg-symbol 0) instance))))
(ecase 1-or-2-class
(1 (setq closure-variables '(wrapper-0 index miss-fn)))
(2 (setq closure-variables '(wrapper-0 wrapper-1 index miss-fn))))
(generating-lisp
closure-variables
arglist
`(let* (,@(unless class-slot-p `((slots nil)))
(wrapper (cond ((std-instance-p ,instance)
,@(unless class-slot-p
`((setq slots
(std-instance-slots ,instance))))
(%instance-wrapper ,instance))
((fsc-instance-p ,instance)
,@(unless class-slot-p
`((setq slots
(fsc-instance-slots ,instance))))
(%fun-wrapper ,instance)))))
(block access
(when (and wrapper
(not (zerop (wrapper-clos-hash wrapper)))
,@(if (eql 1 1-or-2-class)
`((eq wrapper wrapper-0))
`((or (eq wrapper wrapper-0)
(eq wrapper wrapper-1)))))
,@(ecase reader/writer
(:reader
`((let ((value ,read-form))
(unless (unbound-marker-p value)
(return-from access value)))))
(:boundp
`((let ((value ,read-form))
(return-from access (not (unbound-marker-p value))))))
(:makunbound
`(progn (setf ,read-form +slot-unbound+)
,instance))
(:writer
`((return-from access (setf ,read-form ,(car arglist)))))))
(funcall miss-fn ,@arglist))))))
(defun emit-slot-read-form (class-slot-p index slots)
(if class-slot-p
`(cdr ,index)
`(clos-slots-ref ,slots ,index)))
(defun emit-boundp-check (value-form miss-fn arglist)
`(let ((value ,value-form))
(if (unbound-marker-p value)
(funcall ,miss-fn ,@arglist)
value)))
(defun emit-slot-access (reader/writer class-slot-p slots
index miss-fn arglist)
(let ((read-form (emit-slot-read-form class-slot-p index slots)))
(ecase reader/writer
(:reader (emit-boundp-check read-form miss-fn arglist))
(:boundp `(not (unbound-marker-p ,read-form)))
(:makunbound `(progn (setf ,read-form +slot-unbound+) ,(car arglist)))
(:writer `(setf ,read-form ,(car arglist))))))
(defmacro emit-reader/writer-macro (reader/writer 1-or-2-class class-slot-p)
(let ((*precompiling-lap* t))
(values
(emit-reader/writer reader/writer 1-or-2-class class-slot-p))))
(defun emit-one-or-n-index-reader/writer (reader/writer
cached-index-p
class-slot-p)
(multiple-value-bind (arglist metatypes)
(ecase reader/writer
((:reader :boundp :makunbound)
(values (list (dfun-arg-symbol 0))
'(standard-instance)))
(:writer (values (list (dfun-arg-symbol 0) (dfun-arg-symbol 1))
'(t standard-instance))))
(generating-lisp
`(cache ,@(unless cached-index-p '(index)) miss-fn)
arglist
`(let (,@(unless class-slot-p '(slots))
,@(when cached-index-p '(index)))
,(emit-dlap 'cache arglist metatypes
(emit-slot-access reader/writer class-slot-p
'slots 'index 'miss-fn arglist)
`(funcall miss-fn ,@arglist)
(when cached-index-p 'index)
(unless class-slot-p '(slots)))))))
(defmacro emit-one-or-n-index-reader/writer-macro
(reader/writer cached-index-p class-slot-p)
(let ((*precompiling-lap* t))
(values
(emit-one-or-n-index-reader/writer reader/writer
cached-index-p
class-slot-p))))
(defun emit-miss (miss-fn args applyp)
(if applyp
`(multiple-value-call ,miss-fn ,@args
(sb-c:%more-arg-values .more-context.
0
.more-count.))
`(funcall ,miss-fn ,@args)))
NIL / NIL : GF has a single EMF . Invoke it when layouts are in cache .
NIL / T : GF has a single EMF . Return T when layouts are in cache .
METATYPES must be acceptable to EMIT - FETCH - WRAPPER .
APPLYP says whether there is a & MORE context .
(defun emit-checking-or-caching (cached-emf-p return-value-p metatypes applyp)
(multiple-value-bind (lambda-list args rest-arg more-arg)
(make-dlap-lambda-list (length metatypes) applyp)
(generating-lisp
`(cache ,@(unless cached-emf-p '(emf)) miss-fn)
lambda-list
`(let (,@(when cached-emf-p '(emf)))
,(emit-dlap 'cache args metatypes
(if return-value-p
(if cached-emf-p 'emf t)
`(invoke-effective-method-function
emf ,applyp
:required-args ,args
:more-arg ,more-arg
:rest-arg ,rest-arg))
(emit-miss 'miss-fn args applyp)
(when cached-emf-p 'emf))))))
(defmacro emit-checking-or-caching-macro (cached-emf-p
return-value-p
metatypes
applyp)
(let ((*precompiling-lap* t))
(values
(emit-checking-or-caching cached-emf-p return-value-p metatypes applyp))))
(defun emit-dlap (cache-var args metatypes hit-form miss-form value-var
&optional slot-vars)
(let* ((index -1)
(miss-tag (gensym "MISSED"))
(wrapper-bindings (mapcan (lambda (arg mt)
(unless (eq mt t)
(incf index)
`((,(pcl-format-symbol "WRAPPER-~D" index)
,(emit-fetch-wrapper
mt arg miss-tag (pop slot-vars))))))
args metatypes))
(wrapper-vars (mapcar #'car wrapper-bindings)))
(declare (fixnum index))
(unless wrapper-vars
(error "Every metatype is T."))
`(prog ()
(return
(let ,wrapper-bindings
,(emit-cache-lookup cache-var wrapper-vars miss-tag value-var)
,hit-form))
,miss-tag
(return ,miss-form))))
SLOTS - VAR , if supplied , is the variable to update with instance - slots
(defun emit-fetch-wrapper (metatype argument miss-tag &optional slots-var)
(ecase metatype
((standard-instance)
(with-unique-names (wrapper)
`(cond ((std-instance-p ,argument)
,(if slots-var
`(let ((,wrapper (%instance-wrapper ,argument)))
(when (layout-for-pcl-obj-p ,wrapper)
(setq ,slots-var (std-instance-slots ,argument)))
,wrapper)
`(%instance-wrapper ,argument)))
((fsc-instance-p ,argument)
,(if slots-var
`(let ((,wrapper (%fun-wrapper ,argument)))
(when (layout-for-pcl-obj-p ,wrapper)
(setq ,slots-var (fsc-instance-slots ,argument)))
,wrapper)
`(%fun-wrapper ,argument)))
(t (go ,miss-tag)))))
spuriously exclude others ) . Since in SBCL
((class system-instance structure-instance condition-instance)
(when slots-var
(bug "SLOT requested for metatype ~S, but it isn't going to happen."
metatype))
`(wrapper-of ,argument))
a metatype of NIL should never be seen here , as NIL is only in
((t nil)
(bug "~@<metatype ~S seen in ~S.~@:>" metatype 'emit-fetch-wrapper))))
|
3a1935e42ff029fb9402ebef45eabf9ec4acc86525772c9e6595507f452ce0eb | dpiponi/Moodler | audio_square.hs | do
plane <- currentPlane
(x, y) <- fmap (quantise2 quantum) mouse
panel <- container' "panel_3x1.png" (x, y) (Inside plane)
lab <- label' "audio_square" (x-25.0, y+75.0) (Inside plane)
parent panel lab
name <- new' "audio_square"
inp <- plugin' (name ++ ".freq") (x-21, y+50) (Inside plane)
setColour inp "#control"
parent panel inp
inp <- plugin' (name ++ ".pwm") (x-21, y) (Inside plane)
setColour inp "#control"
parent panel inp
inp <- plugin' (name ++ ".sync") (x-21, y-50) (Inside plane)
setColour inp "#sample"
parent panel inp
out <- plugout' (name ++ ".result") (x+20, y) (Inside plane)
setColour out "#sample"
parent panel out
recompile
return ()
| null | https://raw.githubusercontent.com/dpiponi/Moodler/a0c984c36abae52668d00f25eb3749e97e8936d3/Moodler/scripts/audio_square.hs | haskell | do
plane <- currentPlane
(x, y) <- fmap (quantise2 quantum) mouse
panel <- container' "panel_3x1.png" (x, y) (Inside plane)
lab <- label' "audio_square" (x-25.0, y+75.0) (Inside plane)
parent panel lab
name <- new' "audio_square"
inp <- plugin' (name ++ ".freq") (x-21, y+50) (Inside plane)
setColour inp "#control"
parent panel inp
inp <- plugin' (name ++ ".pwm") (x-21, y) (Inside plane)
setColour inp "#control"
parent panel inp
inp <- plugin' (name ++ ".sync") (x-21, y-50) (Inside plane)
setColour inp "#sample"
parent panel inp
out <- plugout' (name ++ ".result") (x+20, y) (Inside plane)
setColour out "#sample"
parent panel out
recompile
return ()
| |
418bc34c9478f8e78841ecbee806ca125c77e68d210d187c0574212bb394b8cf | fulcrologic/fulcro-rad | incrementally_loaded_report.cljc | (ns com.fulcrologic.rad.state-machines.incrementally-loaded-report
"A Report state machine that will load the data in pages to prevent network timeouts for large result
sets. This requires a resolver that can accept :report/offset and :report/limit parameters and that returns
```
{:report/next-offset n
:report/results data}
```
where `n` is the next offset to use to get the next page of data, and `data` is a vector
of the results in the current fetch.
See incrementally-loaded-report-options for supported additional report options.
"
(:require
[com.fulcrologic.fulcro.algorithms.merge :as merge]
[com.fulcrologic.fulcro.raw.application :as app]
[com.fulcrologic.fulcro.raw.components :as comp]
[com.fulcrologic.fulcro.ui-state-machines :as uism :refer [defstatemachine]]
[com.fulcrologic.rad.attributes :as attr]
[com.fulcrologic.rad.options-util :as opts :refer [?! debounce]]
[com.fulcrologic.rad.report :as report]
[com.fulcrologic.rad.routing :as rad-routing]
[com.fulcrologic.rad.routing.history :as history]
[com.fulcrologic.rad.type-support.date-time :as dt]
[taoensso.timbre :as log]))
(defn start-load [env]
(let [Report (uism/actor-class env :actor/report)
report-ident (uism/actor->ident env :actor/report)
{::report/keys [source-attribute load-options]
::keys [chunk-size]} (comp/component-options Report)
load-options (?! load-options env)
current-params (assoc (report/current-control-parameters env)
:report/offset 0
:report/limit (or chunk-size 100))
page-path (uism/resolve-alias env :loaded-page)]
(-> env
(uism/assoc-aliased :raw-rows [])
(uism/load source-attribute nil (merge
{:params current-params
::uism/ok-event :event/page-loaded
::uism/error-event :event/failed
:marker report-ident
:target page-path}
load-options))
(uism/activate :state/loading))))
(defn finalize-report [{::uism/keys [state-map] :as env}]
(let [Report (uism/actor-class env :actor/report)
{::report/keys [row-pk report-loaded]} (comp/component-options Report)
table-name (::attr/qualified-key row-pk)]
(-> env
(report/preprocess-raw-result)
(report/filter-rows)
(report/sort-rows)
(report/populate-current-page)
(uism/store :last-load-time (inst-ms (dt/now)))
(uism/store :raw-items-in-table (count (keys (get state-map table-name))))
(uism/activate :state/gathering-parameters)
(cond-> report-loaded report-loaded))))
(defn process-loaded-page [env]
(let [Report (uism/actor-class env :actor/report)
report-ident (uism/actor->ident env :actor/report)
{::report/keys [BodyItem source-attribute load-options]
::keys [chunk-size]} (comp/component-options Report)
load-options (?! load-options env)
{:report/keys [next-offset results]} (uism/alias-value env :loaded-page)
page-path (uism/resolve-alias env :loaded-page)
target-path (uism/resolve-alias env :raw-rows)
current-params (assoc
(report/current-control-parameters env)
:report/offset next-offset
:report/limit (or chunk-size 100))
more? (and (number? next-offset) (pos? next-offset))
append-results (fn [state-map]
(reduce
(fn [s item] (merge/merge-component s BodyItem item :append target-path))
state-map
results))]
(-> env
(uism/apply-action append-results)
(cond->
more? (uism/load source-attribute nil (merge
{:params current-params
::uism/ok-event :event/page-loaded
::uism/error-event :event/failed
:marker report-ident
:target page-path}
load-options))
(not more?) (uism/trigger report-ident :event/loaded)))))
(defn handle-resume-report
"Internal state machine implementation. Called on :event/resumt to do the steps to resume an already running report
that has just been re-mounted."
[{::uism/keys [state-map] :as env}]
(let [env (report/initialize-parameters env)
Report (uism/actor-class env :actor/report)
{::report/keys [load-cache-seconds
load-cache-expired?
row-pk]} (comp/component-options Report)
now-ms (inst-ms (dt/now))
last-load-time (uism/retrieve env :last-load-time)
last-table-count (uism/retrieve env :raw-items-in-table)
cache-expiration-ms (* 1000 (or load-cache-seconds 0))
table-name (::attr/qualified-key row-pk)
current-table-count (count (keys (get state-map table-name)))
cache-looks-stale? (or
(nil? last-load-time)
(not= current-table-count last-table-count)
(< last-load-time (- now-ms cache-expiration-ms)))
user-cache-expired? (?! load-cache-expired? env cache-looks-stale?)
cache-expired? (if (boolean user-cache-expired?)
user-cache-expired?
cache-looks-stale?)]
(if cache-expired?
(start-load env)
(report/handle-filter-event env))))
(defn start [env]
(let [{::uism/keys [fulcro-app event-data]} env
{::report/keys [run-on-mount?]} (report/report-options env)
page-path (report/route-params-path env ::current-page)
desired-page (-> (history/current-route fulcro-app)
:params
(get-in page-path))
run-now? (or desired-page run-on-mount?)]
(-> env
(uism/store :route-params (:route-params event-data))
(cond->
(nil? desired-page) (uism/assoc-aliased :current-page 1))
(report/initialize-parameters)
(cond->
run-now? (start-load)
(not run-now?) (uism/activate :state/gathering-parameters)))))
(defstatemachine incrementally-loaded-machine
(-> report/report-machine
(assoc-in [::uism/aliases :loaded-page] [:actor/report :ui/incremental-page])
(assoc-in [::uism/states :initial ::uism/handler] start)
(assoc-in [::uism/states :state/loading ::uism/events :event/page-loaded ::uism/handler] process-loaded-page)
(assoc-in [::uism/states :state/loading ::uism/events :event/loaded ::uism/handler] finalize-report)
(assoc-in [::uism/states :state/gathering-parameters ::uism/events :event/run ::uism/handler] start-load)
(assoc-in [::uism/states :state/gathering-parameters ::uism/events :event/resume ::uism/handler] handle-resume-report)))
(defn raw-loaded-item-count
"Returns the count of raw loaded items when given the props of the report. Can be used for progress reporting of
the load/refresh/"
[report-instance]
(let [state-map (app/current-state report-instance)
path (conj (comp/get-ident report-instance) :ui/loaded-data)]
(count (get-in state-map path))))
| null | https://raw.githubusercontent.com/fulcrologic/fulcro-rad/d2a40fdd7ca6ee0ec5fdb3897d5764bb6c5f7800/src/main/com/fulcrologic/rad/state_machines/incrementally_loaded_report.cljc | clojure | (ns com.fulcrologic.rad.state-machines.incrementally-loaded-report
"A Report state machine that will load the data in pages to prevent network timeouts for large result
sets. This requires a resolver that can accept :report/offset and :report/limit parameters and that returns
```
{:report/next-offset n
:report/results data}
```
where `n` is the next offset to use to get the next page of data, and `data` is a vector
of the results in the current fetch.
See incrementally-loaded-report-options for supported additional report options.
"
(:require
[com.fulcrologic.fulcro.algorithms.merge :as merge]
[com.fulcrologic.fulcro.raw.application :as app]
[com.fulcrologic.fulcro.raw.components :as comp]
[com.fulcrologic.fulcro.ui-state-machines :as uism :refer [defstatemachine]]
[com.fulcrologic.rad.attributes :as attr]
[com.fulcrologic.rad.options-util :as opts :refer [?! debounce]]
[com.fulcrologic.rad.report :as report]
[com.fulcrologic.rad.routing :as rad-routing]
[com.fulcrologic.rad.routing.history :as history]
[com.fulcrologic.rad.type-support.date-time :as dt]
[taoensso.timbre :as log]))
(defn start-load [env]
(let [Report (uism/actor-class env :actor/report)
report-ident (uism/actor->ident env :actor/report)
{::report/keys [source-attribute load-options]
::keys [chunk-size]} (comp/component-options Report)
load-options (?! load-options env)
current-params (assoc (report/current-control-parameters env)
:report/offset 0
:report/limit (or chunk-size 100))
page-path (uism/resolve-alias env :loaded-page)]
(-> env
(uism/assoc-aliased :raw-rows [])
(uism/load source-attribute nil (merge
{:params current-params
::uism/ok-event :event/page-loaded
::uism/error-event :event/failed
:marker report-ident
:target page-path}
load-options))
(uism/activate :state/loading))))
(defn finalize-report [{::uism/keys [state-map] :as env}]
(let [Report (uism/actor-class env :actor/report)
{::report/keys [row-pk report-loaded]} (comp/component-options Report)
table-name (::attr/qualified-key row-pk)]
(-> env
(report/preprocess-raw-result)
(report/filter-rows)
(report/sort-rows)
(report/populate-current-page)
(uism/store :last-load-time (inst-ms (dt/now)))
(uism/store :raw-items-in-table (count (keys (get state-map table-name))))
(uism/activate :state/gathering-parameters)
(cond-> report-loaded report-loaded))))
(defn process-loaded-page [env]
(let [Report (uism/actor-class env :actor/report)
report-ident (uism/actor->ident env :actor/report)
{::report/keys [BodyItem source-attribute load-options]
::keys [chunk-size]} (comp/component-options Report)
load-options (?! load-options env)
{:report/keys [next-offset results]} (uism/alias-value env :loaded-page)
page-path (uism/resolve-alias env :loaded-page)
target-path (uism/resolve-alias env :raw-rows)
current-params (assoc
(report/current-control-parameters env)
:report/offset next-offset
:report/limit (or chunk-size 100))
more? (and (number? next-offset) (pos? next-offset))
append-results (fn [state-map]
(reduce
(fn [s item] (merge/merge-component s BodyItem item :append target-path))
state-map
results))]
(-> env
(uism/apply-action append-results)
(cond->
more? (uism/load source-attribute nil (merge
{:params current-params
::uism/ok-event :event/page-loaded
::uism/error-event :event/failed
:marker report-ident
:target page-path}
load-options))
(not more?) (uism/trigger report-ident :event/loaded)))))
(defn handle-resume-report
"Internal state machine implementation. Called on :event/resumt to do the steps to resume an already running report
that has just been re-mounted."
[{::uism/keys [state-map] :as env}]
(let [env (report/initialize-parameters env)
Report (uism/actor-class env :actor/report)
{::report/keys [load-cache-seconds
load-cache-expired?
row-pk]} (comp/component-options Report)
now-ms (inst-ms (dt/now))
last-load-time (uism/retrieve env :last-load-time)
last-table-count (uism/retrieve env :raw-items-in-table)
cache-expiration-ms (* 1000 (or load-cache-seconds 0))
table-name (::attr/qualified-key row-pk)
current-table-count (count (keys (get state-map table-name)))
cache-looks-stale? (or
(nil? last-load-time)
(not= current-table-count last-table-count)
(< last-load-time (- now-ms cache-expiration-ms)))
user-cache-expired? (?! load-cache-expired? env cache-looks-stale?)
cache-expired? (if (boolean user-cache-expired?)
user-cache-expired?
cache-looks-stale?)]
(if cache-expired?
(start-load env)
(report/handle-filter-event env))))
(defn start [env]
(let [{::uism/keys [fulcro-app event-data]} env
{::report/keys [run-on-mount?]} (report/report-options env)
page-path (report/route-params-path env ::current-page)
desired-page (-> (history/current-route fulcro-app)
:params
(get-in page-path))
run-now? (or desired-page run-on-mount?)]
(-> env
(uism/store :route-params (:route-params event-data))
(cond->
(nil? desired-page) (uism/assoc-aliased :current-page 1))
(report/initialize-parameters)
(cond->
run-now? (start-load)
(not run-now?) (uism/activate :state/gathering-parameters)))))
(defstatemachine incrementally-loaded-machine
(-> report/report-machine
(assoc-in [::uism/aliases :loaded-page] [:actor/report :ui/incremental-page])
(assoc-in [::uism/states :initial ::uism/handler] start)
(assoc-in [::uism/states :state/loading ::uism/events :event/page-loaded ::uism/handler] process-loaded-page)
(assoc-in [::uism/states :state/loading ::uism/events :event/loaded ::uism/handler] finalize-report)
(assoc-in [::uism/states :state/gathering-parameters ::uism/events :event/run ::uism/handler] start-load)
(assoc-in [::uism/states :state/gathering-parameters ::uism/events :event/resume ::uism/handler] handle-resume-report)))
(defn raw-loaded-item-count
"Returns the count of raw loaded items when given the props of the report. Can be used for progress reporting of
the load/refresh/"
[report-instance]
(let [state-map (app/current-state report-instance)
path (conj (comp/get-ident report-instance) :ui/loaded-data)]
(count (get-in state-map path))))
| |
3cf18523c499c7ed6a0f9afcb1f5b97f194d16ce1921bcf362f3c719f7f2e371 | gethop-dev/hop-cli | env_vars.clj | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
;; file, You can obtain one at /
(ns hop-cli.aws.env-vars
(:require [babashka.fs :as fs]
[clojure.pprint :as pprint]
[clojure.string :as str]
[hop-cli.aws.api.eb :as api.eb]
[hop-cli.aws.api.ssm :as api.ssm]
[hop-cli.util.thread-transactions :as tht]
[malli.core :as m])
(:import (java.util Date)))
(def string-env-vars-schema
[:sequential
[:and
[:string {:min 1}]
[:re #"^[A-Z_0-9]+=.+$"]]])
(def ^:const last-ssm-script-update-env-var
"LAST_SSM_SCRIPT_ENV_UPDATE")
(defn- string-env-var->env-var
[s]
(zipmap [:name :value] (str/split s #"=" 2)))
(defn- env-var->string-env-var
[{:keys [name value]}]
(format "%s=%s" name value))
(defn- get-env-var-diff
[ssm-env-vars file-env-vars]
(let [all-env-var-names (distinct (map :name (concat ssm-env-vars file-env-vars)))]
(reduce
(fn [r name]
(let [in-ssm (some #(when (= name (:name %)) %) ssm-env-vars)
in-file (some #(when (= name (:name %)) %) file-env-vars)]
(cond
(and in-file (not in-ssm))
(update r :to-create conj in-file)
(and in-ssm (not in-file))
(update r :to-delete conj in-ssm)
(and in-file in-ssm (not= (:value in-ssm) (:value in-file)))
(update r :to-update conj in-file)
:else
r)))
{:to-update []
:to-create []
:to-delete []}
all-env-var-names)))
(defn- sync-env-vars*
[config {:keys [to-update to-create to-delete]}]
(->
[{:txn-fn
(fn txn-1 [_]
(let [result (api.ssm/put-parameters config {:new? true} to-create)]
(if (:success? result)
{:success? true}
{:success? false
:reason :could-not-create-env-vars
:error-details result})))
:rollback-fn
(fn rollback-1 [prv-result]
(let [result (api.ssm/delete-parameters config to-create)]
(when-not (:success? result)
(prn "Create parameters rollback failed"))
prv-result))}
{:txn-fn
(fn txn-2 [_]
(let [result (api.ssm/put-parameters config {} to-update)]
(if (:success? result)
{:success? true}
{:success? false
:reason :could-not-update-env-vars
:error-details result})))
:rollback-fn
(fn rollback-2 [prv-result]
(prn "Missing rollback for updated parameters: " to-update)
prv-result)}
{:txn-fn
(fn txn-2 [_]
(let [result (api.ssm/delete-parameters config to-delete)]
(if (:success? result)
{:success? true}
{:success? false
:reason :could-not-delete-env-vars
:error-details result})))}]
(tht/thread-transactions {})))
(defn- non-env-var-line?
[line]
(or
;; Empty lines or with just whitespace
(re-matches #"^\s*$" line)
;; Comment lines with optional initial whitespace
(re-matches #"^\s*#.*$" line)))
(defn sync-env-vars
[{:keys [file] :as config}]
(let [string-env-vars (->>
(fs/file file)
(fs/read-all-lines)
(remove non-env-var-line?))]
(if-not (m/validate string-env-vars-schema string-env-vars)
(do
(prn "File contains invalid environment variable format: ")
(pprint/pprint (m/explain string-env-vars-schema string-env-vars)))
(let [result (api.ssm/get-parameters config)]
(if-not (:success? result)
{:success? false
:reason :could-not-get-ssm-env-vars
:error-details result}
(let [ssm-env-vars (:params result)
file-env-vars (map string-env-var->env-var string-env-vars)
env-var-diff (get-env-var-diff ssm-env-vars file-env-vars)
result (sync-env-vars* config env-var-diff)]
(assoc result :sync-details env-var-diff)))))))
(defn download-env-vars
[{:keys [file] :as config}]
(let [result (api.ssm/get-parameters config)]
(if-not (:success? result)
{:success? false
:reason :could-not-get-ssm-env-vars
:error-details result}
(let [result (->> (:params result)
(map env-var->string-env-var)
sort
(fs/write-lines file))]
{:success? (boolean result)}))))
(defn apply-env-var-changes
[opts]
(api.eb/update-env-variable (merge opts {:name last-ssm-script-update-env-var
:value (.toString (Date.))})))
| null | https://raw.githubusercontent.com/gethop-dev/hop-cli/48e697115fb91290827d40ecd1f782a9d022b375/src/hop_cli/aws/env_vars.clj | clojure | file, You can obtain one at /
Empty lines or with just whitespace
Comment lines with optional initial whitespace | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
(ns hop-cli.aws.env-vars
(:require [babashka.fs :as fs]
[clojure.pprint :as pprint]
[clojure.string :as str]
[hop-cli.aws.api.eb :as api.eb]
[hop-cli.aws.api.ssm :as api.ssm]
[hop-cli.util.thread-transactions :as tht]
[malli.core :as m])
(:import (java.util Date)))
(def string-env-vars-schema
[:sequential
[:and
[:string {:min 1}]
[:re #"^[A-Z_0-9]+=.+$"]]])
(def ^:const last-ssm-script-update-env-var
"LAST_SSM_SCRIPT_ENV_UPDATE")
(defn- string-env-var->env-var
[s]
(zipmap [:name :value] (str/split s #"=" 2)))
(defn- env-var->string-env-var
[{:keys [name value]}]
(format "%s=%s" name value))
(defn- get-env-var-diff
[ssm-env-vars file-env-vars]
(let [all-env-var-names (distinct (map :name (concat ssm-env-vars file-env-vars)))]
(reduce
(fn [r name]
(let [in-ssm (some #(when (= name (:name %)) %) ssm-env-vars)
in-file (some #(when (= name (:name %)) %) file-env-vars)]
(cond
(and in-file (not in-ssm))
(update r :to-create conj in-file)
(and in-ssm (not in-file))
(update r :to-delete conj in-ssm)
(and in-file in-ssm (not= (:value in-ssm) (:value in-file)))
(update r :to-update conj in-file)
:else
r)))
{:to-update []
:to-create []
:to-delete []}
all-env-var-names)))
(defn- sync-env-vars*
[config {:keys [to-update to-create to-delete]}]
(->
[{:txn-fn
(fn txn-1 [_]
(let [result (api.ssm/put-parameters config {:new? true} to-create)]
(if (:success? result)
{:success? true}
{:success? false
:reason :could-not-create-env-vars
:error-details result})))
:rollback-fn
(fn rollback-1 [prv-result]
(let [result (api.ssm/delete-parameters config to-create)]
(when-not (:success? result)
(prn "Create parameters rollback failed"))
prv-result))}
{:txn-fn
(fn txn-2 [_]
(let [result (api.ssm/put-parameters config {} to-update)]
(if (:success? result)
{:success? true}
{:success? false
:reason :could-not-update-env-vars
:error-details result})))
:rollback-fn
(fn rollback-2 [prv-result]
(prn "Missing rollback for updated parameters: " to-update)
prv-result)}
{:txn-fn
(fn txn-2 [_]
(let [result (api.ssm/delete-parameters config to-delete)]
(if (:success? result)
{:success? true}
{:success? false
:reason :could-not-delete-env-vars
:error-details result})))}]
(tht/thread-transactions {})))
(defn- non-env-var-line?
[line]
(or
(re-matches #"^\s*$" line)
(re-matches #"^\s*#.*$" line)))
(defn sync-env-vars
[{:keys [file] :as config}]
(let [string-env-vars (->>
(fs/file file)
(fs/read-all-lines)
(remove non-env-var-line?))]
(if-not (m/validate string-env-vars-schema string-env-vars)
(do
(prn "File contains invalid environment variable format: ")
(pprint/pprint (m/explain string-env-vars-schema string-env-vars)))
(let [result (api.ssm/get-parameters config)]
(if-not (:success? result)
{:success? false
:reason :could-not-get-ssm-env-vars
:error-details result}
(let [ssm-env-vars (:params result)
file-env-vars (map string-env-var->env-var string-env-vars)
env-var-diff (get-env-var-diff ssm-env-vars file-env-vars)
result (sync-env-vars* config env-var-diff)]
(assoc result :sync-details env-var-diff)))))))
(defn download-env-vars
[{:keys [file] :as config}]
(let [result (api.ssm/get-parameters config)]
(if-not (:success? result)
{:success? false
:reason :could-not-get-ssm-env-vars
:error-details result}
(let [result (->> (:params result)
(map env-var->string-env-var)
sort
(fs/write-lines file))]
{:success? (boolean result)}))))
(defn apply-env-var-changes
[opts]
(api.eb/update-env-variable (merge opts {:name last-ssm-script-update-env-var
:value (.toString (Date.))})))
|
363f1052e1dd247e92c5356ddfedb819cbb2fddc35b3220a6642e3ffb52992d1 | jumarko/clojure-experiments | day-03.clj | (ns advent-of-clojure.advent-2017.day-03
"Day 3 of Advent of Clojure 2017 - Spiral Memory:
Part I:
------------------------------------------------------------------------------
You come across an experimental new kind of memory stored on an infinite two-dimensional grid.
Each square on the grid is allocated in a spiral pattern starting at a location marked 1
and then counting up while spiraling outward. For example, the first few squares are allocated like this:
17 16 15 14 13
18 5 4 3 12
19 6 1 2 11
20 7 8 9 10
21 22 23---> ...
While this is very space-efficient (no squares are skipped), requested data must be carried back
to square 1 (the location of the only access port for this memory system)
by programs that can only move up, down, left, or right.
They always take the shortest path: the Manhattan Distance between the location of the data and square 1.
For example:
Data from square 1 is carried 0 steps, since it's at the access port.
Data from square 12 is carried 3 steps, such as: down, left, left.
Data from square 23 is carried only 2 steps: up twice.
Data from square 1024 must be carried 31 steps.
How many steps are required to carry the data from the square identified in your puzzle input
all the way to the access port?
Your puzzle input is 325489.
Part II:
------------------------------------------------------------------------------
")
;; PART I:
;; The key idea here is to understand that the count of numbers is equal to the squares:
1 ^ 2 , 3 ^ 2 , 5 ^ 2 , 7 ^ 2 , 9 ^ 2 .
;; So we can easily determine to which "layer" the given input number belongs.
;; The number of layer gives us the distance automatically.
;; To find the number of layer we just need to use square root.
(defn- layer-number
"Returns the number of 'layer' to which given number belongs.
If `x` is the layer number, then the final distance is in interval <x; 2x>."
[input-square-number]
(-> input-square-number
Math/sqrt
Math/ceil
int
;; finally we have a square root and we need to get number of layer
this is done by dividing by 2 because all numbers up to 3 ^ 2 belong to the first layer
all numbers up to 5 ^ 2 belong to the second layer , all numbers up to 7 ^ 2 belong to the third layer , etc .
(quot 2)))
(defn spiral-memory-steps-count
[input-square-number]
(let [layer-num (layer-number input-square-number)
layer-width (* 2 layer-num)
max-num-in-layer (* (inc layer-width) (inc layer-width))
max-num-diff (- max-num-in-layer input-square-number)
max-num-diff-mod (mod max-num-diff layer-width)]
(if (zero? max-num-diff-mod)
layer-width
(max layer-num max-num-diff-mod))))
(spiral-memory-steps-count 325489)
| null | https://raw.githubusercontent.com/jumarko/clojure-experiments/f0f9c091959e7f54c3fb13d0585a793ebb09e4f9/src/clojure_experiments/advent_of_code/advent_2017/day-03.clj | clojure | PART I:
The key idea here is to understand that the count of numbers is equal to the squares:
So we can easily determine to which "layer" the given input number belongs.
The number of layer gives us the distance automatically.
To find the number of layer we just need to use square root.
2x>."
finally we have a square root and we need to get number of layer | (ns advent-of-clojure.advent-2017.day-03
"Day 3 of Advent of Clojure 2017 - Spiral Memory:
Part I:
------------------------------------------------------------------------------
You come across an experimental new kind of memory stored on an infinite two-dimensional grid.
Each square on the grid is allocated in a spiral pattern starting at a location marked 1
and then counting up while spiraling outward. For example, the first few squares are allocated like this:
17 16 15 14 13
18 5 4 3 12
19 6 1 2 11
20 7 8 9 10
21 22 23---> ...
While this is very space-efficient (no squares are skipped), requested data must be carried back
to square 1 (the location of the only access port for this memory system)
by programs that can only move up, down, left, or right.
They always take the shortest path: the Manhattan Distance between the location of the data and square 1.
For example:
Data from square 1 is carried 0 steps, since it's at the access port.
Data from square 12 is carried 3 steps, such as: down, left, left.
Data from square 23 is carried only 2 steps: up twice.
Data from square 1024 must be carried 31 steps.
How many steps are required to carry the data from the square identified in your puzzle input
all the way to the access port?
Your puzzle input is 325489.
Part II:
------------------------------------------------------------------------------
")
1 ^ 2 , 3 ^ 2 , 5 ^ 2 , 7 ^ 2 , 9 ^ 2 .
(defn- layer-number
"Returns the number of 'layer' to which given number belongs.
[input-square-number]
(-> input-square-number
Math/sqrt
Math/ceil
int
this is done by dividing by 2 because all numbers up to 3 ^ 2 belong to the first layer
all numbers up to 5 ^ 2 belong to the second layer , all numbers up to 7 ^ 2 belong to the third layer , etc .
(quot 2)))
(defn spiral-memory-steps-count
[input-square-number]
(let [layer-num (layer-number input-square-number)
layer-width (* 2 layer-num)
max-num-in-layer (* (inc layer-width) (inc layer-width))
max-num-diff (- max-num-in-layer input-square-number)
max-num-diff-mod (mod max-num-diff layer-width)]
(if (zero? max-num-diff-mod)
layer-width
(max layer-num max-num-diff-mod))))
(spiral-memory-steps-count 325489)
|
6516ac862341e56aac13d3099391b7805769dbac657b16471746be85f4cffbba | MLstate/opalang | qmljsPasses.ml |
Copyright © 2011 , 2012 MLstate
This file is part of .
is free software : you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License , version 3 , as published by
the Free Software Foundation .
is distributed in the hope that it will be useful , but WITHOUT ANY
WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE . See the GNU Affero General Public License for
more details .
You should have received a copy of the GNU Affero General Public License
along with . If not , see < / > .
Copyright © 2011, 2012 MLstate
This file is part of Opa.
Opa is free software: you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License, version 3, as published by
the Free Software Foundation.
Opa is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
more details.
You should have received a copy of the GNU Affero General Public License
along with Opa. If not, see </>.
*)
module O = OpaEnv
module P = Passes
module PH = PassHandler
module List = BaseList
type env_JsCompilation = {
env_js_input : Qml2jsOptions.env_js_input;
jsoptions : Qml2jsOptions.t;
env_bsl : BslLib.env_bsl;
loaded_bsl : Qml2js.loaded_bsl;
is_distant : JsIdent.t -> bool;
client_depends : StringSet.t;
depends : string list;
}
let pass_ServerJavascriptCompilation =
PassHandler.make_pass
(fun e ->
let options = e.PH.options in
let env = e.PH.env in
let module JsBackend = (val (options.OpaEnv.js_back_end) : Qml2jsOptions.JsBackend) in
let compilation_directory =
match ObjectFiles.compilation_mode () with
| `compilation -> Option.get (ObjectFiles.get_compilation_directory ())
| `init | `linking -> "_build"
| `prelude -> assert false
in
let jsoptions =
let argv_options = Qml2jsOptions.Argv.default () in
{ argv_options with Qml2jsOptions.
cps = options.OpaEnv.cps;
cps_toplevel_concurrency = options.OpaEnv.cps_toplevel_concurrency ;
qml_closure = options.OpaEnv.closure;
extra_lib = options.OpaEnv.extrajs;
alpha_renaming = options.OpaEnv.js_local_renaming;
check_bsl_types = options.OpaEnv.js_check_bsl_types;
cleanup = options.OpaEnv.js_cleanup;
inlining = options.OpaEnv.js_local_inlining;
global_inlining = options.OpaEnv.js_global_inlining;
no_assert = options.OpaEnv.no_assert;
target = options.OpaEnv.target;
compilation_directory;
package_version = options.OpaEnv.package_version;
lang = `node;
} in
let jsoptions =
match options.OpaEnv.run_server_options with
| None -> jsoptions
| Some exe_argv ->
{ jsoptions with Qml2jsOptions. exe_argv; exe_run = true }
in
let env_bsl = env.Passes.newFinalCompile_bsl in
let loaded_bsl =
Qml2js.JsTreat.js_bslfilesloading jsoptions env_bsl in
let is_distant, renaming =
let other = env.P.newFinalCompile_renaming_client in
let here = env.P.newFinalCompile_renaming_server in
S3Passes.EnvUtils.jsutils_from_renamings ~here ~other
in
let exported = env.Passes.newFinalCompile_exported in
let env_js_input = JsBackend.compile
~runtime_ast:false
~bsl:loaded_bsl.Qml2js.generated_ast
~val_:OpaMapToIdent.val_
~closure_map:env.Passes.newFinalCompile_closure_map
~is_distant
~renaming
~bsl_lang:BslLanguage.nodejs
~exported
jsoptions
env_bsl
env.Passes.newFinalCompile_qml_milkshake.QmlBlender.env
env.Passes.newFinalCompile_qml_milkshake.QmlBlender.code
in
let is_distant ident =
match ident with
| JsIdent.ExprIdent i ->
(try
ignore
(QmlRenamingMap.new_from_original
env.P.newFinalCompile_renaming_client
i);
true
with Not_found -> false)
| _ -> false
in
PH.make_env options {
env_js_input;
jsoptions;
env_bsl;
loaded_bsl;
is_distant;
client_depends = env.Passes.newFinalCompile_client_deps;
depends = [];
}
)
let pass_ServerJavascriptOptimization =
PassHandler.make_pass
(fun e ->
let env = e.PH.env in
let options = e.PH.options in
let exported = env.env_js_input.Qml2jsOptions.exported in
let is_exported i = JsIdentSet.mem i exported || env.is_distant i in
let depends, js_code =
Pass_ServerJavascriptOptimization.process_code
~client_deps:env.client_depends
options.O.extrajs
env.env_bsl
is_exported
env.env_js_input.Qml2jsOptions.js_code
in
let js_init_contents =
List.map
(fun (x, c) -> x,
match c with
| `string _ -> assert false
| `ast proj -> `ast
(List.map
(fun (i, e) ->
(i, Pass_ServerJavascriptOptimization.process_code_elt
is_exported e))
proj)
) env.env_js_input.Qml2jsOptions.js_init_contents
in
PH.make_env options
{ env with
depends;
env_js_input =
{ env.env_js_input with Qml2jsOptions. js_code; js_init_contents }
}
)
let pass_ServerJavascriptGeneration =
PassHandler.make_pass
(fun e ->
let env = e.PH.env in
let jsoptions = env.jsoptions in
let env_bsl = env.env_bsl in
let loaded_bsl = env.loaded_bsl in
let env_js_output =
Qml2js.JsTreat.js_generation ~depends:env.depends jsoptions env_bsl
loaded_bsl env.env_js_input
in
let code = Qml2js.JsTreat.js_treat jsoptions env_js_output in
PH.make_env e.PH.options code
)
| null | https://raw.githubusercontent.com/MLstate/opalang/424b369160ce693406cece6ac033d75d85f5df4f/compiler/js_passes/qmljsPasses.ml | ocaml |
Copyright © 2011 , 2012 MLstate
This file is part of .
is free software : you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License , version 3 , as published by
the Free Software Foundation .
is distributed in the hope that it will be useful , but WITHOUT ANY
WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE . See the GNU Affero General Public License for
more details .
You should have received a copy of the GNU Affero General Public License
along with . If not , see < / > .
Copyright © 2011, 2012 MLstate
This file is part of Opa.
Opa is free software: you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License, version 3, as published by
the Free Software Foundation.
Opa is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
more details.
You should have received a copy of the GNU Affero General Public License
along with Opa. If not, see </>.
*)
module O = OpaEnv
module P = Passes
module PH = PassHandler
module List = BaseList
type env_JsCompilation = {
env_js_input : Qml2jsOptions.env_js_input;
jsoptions : Qml2jsOptions.t;
env_bsl : BslLib.env_bsl;
loaded_bsl : Qml2js.loaded_bsl;
is_distant : JsIdent.t -> bool;
client_depends : StringSet.t;
depends : string list;
}
let pass_ServerJavascriptCompilation =
PassHandler.make_pass
(fun e ->
let options = e.PH.options in
let env = e.PH.env in
let module JsBackend = (val (options.OpaEnv.js_back_end) : Qml2jsOptions.JsBackend) in
let compilation_directory =
match ObjectFiles.compilation_mode () with
| `compilation -> Option.get (ObjectFiles.get_compilation_directory ())
| `init | `linking -> "_build"
| `prelude -> assert false
in
let jsoptions =
let argv_options = Qml2jsOptions.Argv.default () in
{ argv_options with Qml2jsOptions.
cps = options.OpaEnv.cps;
cps_toplevel_concurrency = options.OpaEnv.cps_toplevel_concurrency ;
qml_closure = options.OpaEnv.closure;
extra_lib = options.OpaEnv.extrajs;
alpha_renaming = options.OpaEnv.js_local_renaming;
check_bsl_types = options.OpaEnv.js_check_bsl_types;
cleanup = options.OpaEnv.js_cleanup;
inlining = options.OpaEnv.js_local_inlining;
global_inlining = options.OpaEnv.js_global_inlining;
no_assert = options.OpaEnv.no_assert;
target = options.OpaEnv.target;
compilation_directory;
package_version = options.OpaEnv.package_version;
lang = `node;
} in
let jsoptions =
match options.OpaEnv.run_server_options with
| None -> jsoptions
| Some exe_argv ->
{ jsoptions with Qml2jsOptions. exe_argv; exe_run = true }
in
let env_bsl = env.Passes.newFinalCompile_bsl in
let loaded_bsl =
Qml2js.JsTreat.js_bslfilesloading jsoptions env_bsl in
let is_distant, renaming =
let other = env.P.newFinalCompile_renaming_client in
let here = env.P.newFinalCompile_renaming_server in
S3Passes.EnvUtils.jsutils_from_renamings ~here ~other
in
let exported = env.Passes.newFinalCompile_exported in
let env_js_input = JsBackend.compile
~runtime_ast:false
~bsl:loaded_bsl.Qml2js.generated_ast
~val_:OpaMapToIdent.val_
~closure_map:env.Passes.newFinalCompile_closure_map
~is_distant
~renaming
~bsl_lang:BslLanguage.nodejs
~exported
jsoptions
env_bsl
env.Passes.newFinalCompile_qml_milkshake.QmlBlender.env
env.Passes.newFinalCompile_qml_milkshake.QmlBlender.code
in
let is_distant ident =
match ident with
| JsIdent.ExprIdent i ->
(try
ignore
(QmlRenamingMap.new_from_original
env.P.newFinalCompile_renaming_client
i);
true
with Not_found -> false)
| _ -> false
in
PH.make_env options {
env_js_input;
jsoptions;
env_bsl;
loaded_bsl;
is_distant;
client_depends = env.Passes.newFinalCompile_client_deps;
depends = [];
}
)
let pass_ServerJavascriptOptimization =
PassHandler.make_pass
(fun e ->
let env = e.PH.env in
let options = e.PH.options in
let exported = env.env_js_input.Qml2jsOptions.exported in
let is_exported i = JsIdentSet.mem i exported || env.is_distant i in
let depends, js_code =
Pass_ServerJavascriptOptimization.process_code
~client_deps:env.client_depends
options.O.extrajs
env.env_bsl
is_exported
env.env_js_input.Qml2jsOptions.js_code
in
let js_init_contents =
List.map
(fun (x, c) -> x,
match c with
| `string _ -> assert false
| `ast proj -> `ast
(List.map
(fun (i, e) ->
(i, Pass_ServerJavascriptOptimization.process_code_elt
is_exported e))
proj)
) env.env_js_input.Qml2jsOptions.js_init_contents
in
PH.make_env options
{ env with
depends;
env_js_input =
{ env.env_js_input with Qml2jsOptions. js_code; js_init_contents }
}
)
let pass_ServerJavascriptGeneration =
PassHandler.make_pass
(fun e ->
let env = e.PH.env in
let jsoptions = env.jsoptions in
let env_bsl = env.env_bsl in
let loaded_bsl = env.loaded_bsl in
let env_js_output =
Qml2js.JsTreat.js_generation ~depends:env.depends jsoptions env_bsl
loaded_bsl env.env_js_input
in
let code = Qml2js.JsTreat.js_treat jsoptions env_js_output in
PH.make_env e.PH.options code
)
| |
2eb3e9985bebb0568af1ec090bd5173af983483299b55ad2b1338b5eed789e35 | andrewthad/quickcheck-classes | Num.hs | # LANGUAGE ScopedTypeVariables #
# OPTIONS_GHC -Wall #
module Test.QuickCheck.Classes.Num
( numLaws
) where
import Data.Proxy (Proxy)
import Test.QuickCheck hiding ((.&.))
import Test.QuickCheck.Classes.Internal (Laws(..), myForAllShrink)
-- | Tests the following properties:
--
-- [/Additive Commutativity/]
-- @a + b ≡ b + a@
-- [/Additive Left Identity/]
-- @0 + a ≡ a@
-- [/Additive Right Identity/]
@a + 0 ≡ a@
-- [/Multiplicative Associativity/]
-- @a * (b * c) ≡ (a * b) * c@
-- [/Multiplicative Left Identity/]
-- @1 * a ≡ a@
-- [/Multiplicative Right Identity/]
@a * 1 ≡ a@
-- [/Multiplication Left Distributes Over Addition/]
@a * ( b + c ) ≡ ( a * b ) + ( a *
-- [/Multiplication Right Distributes Over Addition/]
@(a + b ) * c ≡ ( a * c ) + ( b *
-- [/Multiplicative Left Annihilation/]
@0 * a ≡ 0@
-- [/Multiplicative Right Annihilation/]
-- @a * 0 ≡ 0@
-- [/Additive Inverse/]
@'negate ' a ' + ' a ≡ 0@
-- [/Subtraction/]
@a ' + ' ' negate ' b ≡ a ' - ' b@
-- [/Abs Is Idempotent/]
-- @'abs' ('abs' a) ≡ 'abs' a
-- [/Signum Is Idempotent/]
@'signum ' ( ' signum ' a ) ≡ ' signum ' a
-- [/Product Of Abs And Signum Is Id/]
-- @'abs' a * 'signum' a ≡ a@
numLaws :: (Num a, Eq a, Arbitrary a, Show a) => Proxy a -> Laws
numLaws p = Laws "Num"
[ ("Additive Commutativity", numCommutativePlus p)
, ("Additive Left Identity", numLeftIdentityPlus p)
, ("Additive Right Identity", numRightIdentityPlus p)
, ("Multiplicative Associativity", numAssociativeTimes p)
, ("Multiplicative Left Identity", numLeftIdentityTimes p)
, ("Multiplicative Right Identity", numRightIdentityTimes p)
, ("Multiplication Left Distributes Over Addition", numLeftMultiplicationDistributes p)
, ("Multiplication Right Distributes Over Addition", numRightMultiplicationDistributes p)
, ("Multiplicative Left Annihilation", numLeftAnnihilation p)
, ("Multiplicative Right Annihilation", numRightAnnihilation p)
, ("Additive Inverse", numAdditiveInverse p)
, ("Subtraction", numSubtraction p)
, ("Abs Is Idempotent", absIdempotence p)
, ("Signum Is Idempotent", signumIdempotence p)
, ("Product Of Abs And Signum Is Id", absSignumId p)
]
numLeftMultiplicationDistributes :: forall a. (Num a, Eq a, Arbitrary a, Show a) => Proxy a -> Property
numLeftMultiplicationDistributes _ = myForAllShrink True (const True)
(\(a :: a,b,c) -> ["a = " ++ show a, "b = " ++ show b, "c = " ++ show c])
"a * (b + c)"
(\(a,b,c) -> a * (b + c))
"(a * b) + (a * c)"
(\(a,b,c) -> (a * b) + (a * c))
numRightMultiplicationDistributes :: forall a. (Num a, Eq a, Arbitrary a, Show a) => Proxy a -> Property
numRightMultiplicationDistributes _ = myForAllShrink True (const True)
(\(a :: a,b,c) -> ["a = " ++ show a, "b = " ++ show b, "c = " ++ show c])
"(a + b) * c"
(\(a,b,c) -> (a + b) * c)
"(a * c) + (b * c)"
(\(a,b,c) -> (a * c) + (b * c))
numLeftIdentityPlus :: forall a. (Num a, Eq a, Arbitrary a, Show a) => Proxy a -> Property
numLeftIdentityPlus _ = myForAllShrink False (const True)
(\(a :: a) -> ["a = " ++ show a])
"0 + a"
(\a -> 0 + a)
"a"
(\a -> a)
numRightIdentityPlus :: forall a. (Num a, Eq a, Arbitrary a, Show a) => Proxy a -> Property
numRightIdentityPlus _ = myForAllShrink False (const True)
(\(a :: a) -> ["a = " ++ show a])
"a + 0"
(\a -> a + 0)
"a"
(\a -> a)
numRightIdentityTimes :: forall a. (Num a, Eq a, Arbitrary a, Show a) => Proxy a -> Property
numRightIdentityTimes _ = myForAllShrink False (const True)
(\(a :: a) -> ["a = " ++ show a])
"a * 1"
(\a -> a * 1)
"a"
(\a -> a)
numLeftIdentityTimes :: forall a. (Num a, Eq a, Arbitrary a, Show a) => Proxy a -> Property
numLeftIdentityTimes _ = myForAllShrink False (const True)
(\(a :: a) -> ["a = " ++ show a])
"1 * a"
(\a -> 1 * a)
"a"
(\a -> a)
numLeftAnnihilation :: forall a. (Num a, Eq a, Arbitrary a, Show a) => Proxy a -> Property
numLeftAnnihilation _ = myForAllShrink False (const True)
(\(a :: a) -> ["a = " ++ show a])
"0 * a"
(\a -> 0 * a)
"0"
(\_ -> 0)
numRightAnnihilation :: forall a. (Num a, Eq a, Arbitrary a, Show a) => Proxy a -> Property
numRightAnnihilation _ = myForAllShrink False (const True)
(\(a :: a) -> ["a = " ++ show a])
"a * 0"
(\a -> a * 0)
"0"
(\_ -> 0)
numCommutativePlus :: forall a. (Num a, Eq a, Arbitrary a, Show a) => Proxy a -> Property
numCommutativePlus _ = myForAllShrink True (const True)
(\(a :: a,b) -> ["a = " ++ show a, "b = " ++ show b])
"a + b"
(\(a,b) -> a + b)
"b + a"
(\(a,b) -> b + a)
numAssociativeTimes :: forall a. (Num a, Eq a, Arbitrary a, Show a) => Proxy a -> Property
numAssociativeTimes _ = myForAllShrink True (const True)
(\(a :: a,b,c) -> ["a = " ++ show a, "b = " ++ show b, "c = " ++ show c])
"a * (b * c)"
(\(a,b,c) -> a * (b * c))
"(a * b) * c"
(\(a,b,c) -> (a * b) * c)
numAdditiveInverse :: forall a. (Num a, Eq a, Arbitrary a, Show a) => Proxy a -> Property
numAdditiveInverse _ = myForAllShrink True (const True)
(\(a :: a) -> ["a = " ++ show a])
"negate a + a"
(\a -> (-a) + a)
"0"
(const 0)
numSubtraction :: forall a. (Num a, Eq a, Arbitrary a, Show a) => Proxy a -> Property
numSubtraction _ = myForAllShrink True (const True)
(\(a :: a, b :: a) -> ["a = " ++ show a, "b = " ++ show b])
"a + negate b"
(\(a,b) -> a + negate b)
"a - b"
(\(a,b) -> a - b)
absIdempotence :: forall a. (Num a, Eq a, Arbitrary a, Show a) => Proxy a -> Property
absIdempotence _ = myForAllShrink True (const True)
(\(a :: a) -> ["a = " ++ show a])
"abs (abs a)"
(abs . abs)
"abs a"
abs
signumIdempotence :: forall a. (Num a, Eq a, Arbitrary a, Show a) => Proxy a -> Property
signumIdempotence _ = myForAllShrink True (const True)
(\(a :: a) -> ["a = " ++ show a])
"signum (signum a)"
(signum . signum)
"signum a"
signum
absSignumId :: forall a. (Num a, Eq a, Arbitrary a, Show a) => Proxy a -> Property
absSignumId _ = myForAllShrink True (const True)
(\(a :: a) -> ["a = " ++ show a])
"abs a * signum a"
(\a -> abs a * signum a)
"a"
id
| null | https://raw.githubusercontent.com/andrewthad/quickcheck-classes/0fc6c0602bc6875cdbde34cbdbcf229a175af62f/quickcheck-classes-base/src/Test/QuickCheck/Classes/Num.hs | haskell | | Tests the following properties:
[/Additive Commutativity/]
@a + b ≡ b + a@
[/Additive Left Identity/]
@0 + a ≡ a@
[/Additive Right Identity/]
[/Multiplicative Associativity/]
@a * (b * c) ≡ (a * b) * c@
[/Multiplicative Left Identity/]
@1 * a ≡ a@
[/Multiplicative Right Identity/]
[/Multiplication Left Distributes Over Addition/]
[/Multiplication Right Distributes Over Addition/]
[/Multiplicative Left Annihilation/]
[/Multiplicative Right Annihilation/]
@a * 0 ≡ 0@
[/Additive Inverse/]
[/Subtraction/]
[/Abs Is Idempotent/]
@'abs' ('abs' a) ≡ 'abs' a
[/Signum Is Idempotent/]
[/Product Of Abs And Signum Is Id/]
@'abs' a * 'signum' a ≡ a@ | # LANGUAGE ScopedTypeVariables #
# OPTIONS_GHC -Wall #
module Test.QuickCheck.Classes.Num
( numLaws
) where
import Data.Proxy (Proxy)
import Test.QuickCheck hiding ((.&.))
import Test.QuickCheck.Classes.Internal (Laws(..), myForAllShrink)
@a + 0 ≡ a@
@a * 1 ≡ a@
@a * ( b + c ) ≡ ( a * b ) + ( a *
@(a + b ) * c ≡ ( a * c ) + ( b *
@0 * a ≡ 0@
@'negate ' a ' + ' a ≡ 0@
@a ' + ' ' negate ' b ≡ a ' - ' b@
@'signum ' ( ' signum ' a ) ≡ ' signum ' a
numLaws :: (Num a, Eq a, Arbitrary a, Show a) => Proxy a -> Laws
numLaws p = Laws "Num"
[ ("Additive Commutativity", numCommutativePlus p)
, ("Additive Left Identity", numLeftIdentityPlus p)
, ("Additive Right Identity", numRightIdentityPlus p)
, ("Multiplicative Associativity", numAssociativeTimes p)
, ("Multiplicative Left Identity", numLeftIdentityTimes p)
, ("Multiplicative Right Identity", numRightIdentityTimes p)
, ("Multiplication Left Distributes Over Addition", numLeftMultiplicationDistributes p)
, ("Multiplication Right Distributes Over Addition", numRightMultiplicationDistributes p)
, ("Multiplicative Left Annihilation", numLeftAnnihilation p)
, ("Multiplicative Right Annihilation", numRightAnnihilation p)
, ("Additive Inverse", numAdditiveInverse p)
, ("Subtraction", numSubtraction p)
, ("Abs Is Idempotent", absIdempotence p)
, ("Signum Is Idempotent", signumIdempotence p)
, ("Product Of Abs And Signum Is Id", absSignumId p)
]
numLeftMultiplicationDistributes :: forall a. (Num a, Eq a, Arbitrary a, Show a) => Proxy a -> Property
numLeftMultiplicationDistributes _ = myForAllShrink True (const True)
(\(a :: a,b,c) -> ["a = " ++ show a, "b = " ++ show b, "c = " ++ show c])
"a * (b + c)"
(\(a,b,c) -> a * (b + c))
"(a * b) + (a * c)"
(\(a,b,c) -> (a * b) + (a * c))
numRightMultiplicationDistributes :: forall a. (Num a, Eq a, Arbitrary a, Show a) => Proxy a -> Property
numRightMultiplicationDistributes _ = myForAllShrink True (const True)
(\(a :: a,b,c) -> ["a = " ++ show a, "b = " ++ show b, "c = " ++ show c])
"(a + b) * c"
(\(a,b,c) -> (a + b) * c)
"(a * c) + (b * c)"
(\(a,b,c) -> (a * c) + (b * c))
numLeftIdentityPlus :: forall a. (Num a, Eq a, Arbitrary a, Show a) => Proxy a -> Property
numLeftIdentityPlus _ = myForAllShrink False (const True)
(\(a :: a) -> ["a = " ++ show a])
"0 + a"
(\a -> 0 + a)
"a"
(\a -> a)
numRightIdentityPlus :: forall a. (Num a, Eq a, Arbitrary a, Show a) => Proxy a -> Property
numRightIdentityPlus _ = myForAllShrink False (const True)
(\(a :: a) -> ["a = " ++ show a])
"a + 0"
(\a -> a + 0)
"a"
(\a -> a)
numRightIdentityTimes :: forall a. (Num a, Eq a, Arbitrary a, Show a) => Proxy a -> Property
numRightIdentityTimes _ = myForAllShrink False (const True)
(\(a :: a) -> ["a = " ++ show a])
"a * 1"
(\a -> a * 1)
"a"
(\a -> a)
numLeftIdentityTimes :: forall a. (Num a, Eq a, Arbitrary a, Show a) => Proxy a -> Property
numLeftIdentityTimes _ = myForAllShrink False (const True)
(\(a :: a) -> ["a = " ++ show a])
"1 * a"
(\a -> 1 * a)
"a"
(\a -> a)
numLeftAnnihilation :: forall a. (Num a, Eq a, Arbitrary a, Show a) => Proxy a -> Property
numLeftAnnihilation _ = myForAllShrink False (const True)
(\(a :: a) -> ["a = " ++ show a])
"0 * a"
(\a -> 0 * a)
"0"
(\_ -> 0)
numRightAnnihilation :: forall a. (Num a, Eq a, Arbitrary a, Show a) => Proxy a -> Property
numRightAnnihilation _ = myForAllShrink False (const True)
(\(a :: a) -> ["a = " ++ show a])
"a * 0"
(\a -> a * 0)
"0"
(\_ -> 0)
numCommutativePlus :: forall a. (Num a, Eq a, Arbitrary a, Show a) => Proxy a -> Property
numCommutativePlus _ = myForAllShrink True (const True)
(\(a :: a,b) -> ["a = " ++ show a, "b = " ++ show b])
"a + b"
(\(a,b) -> a + b)
"b + a"
(\(a,b) -> b + a)
numAssociativeTimes :: forall a. (Num a, Eq a, Arbitrary a, Show a) => Proxy a -> Property
numAssociativeTimes _ = myForAllShrink True (const True)
(\(a :: a,b,c) -> ["a = " ++ show a, "b = " ++ show b, "c = " ++ show c])
"a * (b * c)"
(\(a,b,c) -> a * (b * c))
"(a * b) * c"
(\(a,b,c) -> (a * b) * c)
numAdditiveInverse :: forall a. (Num a, Eq a, Arbitrary a, Show a) => Proxy a -> Property
numAdditiveInverse _ = myForAllShrink True (const True)
(\(a :: a) -> ["a = " ++ show a])
"negate a + a"
(\a -> (-a) + a)
"0"
(const 0)
numSubtraction :: forall a. (Num a, Eq a, Arbitrary a, Show a) => Proxy a -> Property
numSubtraction _ = myForAllShrink True (const True)
(\(a :: a, b :: a) -> ["a = " ++ show a, "b = " ++ show b])
"a + negate b"
(\(a,b) -> a + negate b)
"a - b"
(\(a,b) -> a - b)
absIdempotence :: forall a. (Num a, Eq a, Arbitrary a, Show a) => Proxy a -> Property
absIdempotence _ = myForAllShrink True (const True)
(\(a :: a) -> ["a = " ++ show a])
"abs (abs a)"
(abs . abs)
"abs a"
abs
signumIdempotence :: forall a. (Num a, Eq a, Arbitrary a, Show a) => Proxy a -> Property
signumIdempotence _ = myForAllShrink True (const True)
(\(a :: a) -> ["a = " ++ show a])
"signum (signum a)"
(signum . signum)
"signum a"
signum
absSignumId :: forall a. (Num a, Eq a, Arbitrary a, Show a) => Proxy a -> Property
absSignumId _ = myForAllShrink True (const True)
(\(a :: a) -> ["a = " ++ show a])
"abs a * signum a"
(\a -> abs a * signum a)
"a"
id
|
02684a667eadf63e8210d240026f4df8b0b7f114905a2b285b021099119322f0 | mfikes/fifth-postulate | ns216.cljs | (ns fifth-postulate.ns216)
(defn solve-for01 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for02 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for03 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for04 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for05 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for06 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for07 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for08 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for09 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for10 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for11 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for12 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for13 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for14 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for15 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for16 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for17 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for18 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for19 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
| null | https://raw.githubusercontent.com/mfikes/fifth-postulate/22cfd5f8c2b4a2dead1c15a96295bfeb4dba235e/src/fifth_postulate/ns216.cljs | clojure | (ns fifth-postulate.ns216)
(defn solve-for01 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for02 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for03 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for04 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for05 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for06 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for07 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for08 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for09 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for10 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for11 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for12 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for13 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for14 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for15 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for16 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for17 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for18 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for19 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
| |
aec9d064d2f61c224aef539812d466f0b3ce89c3b12f13ea2c2499adac4ad287 | mpickering/plugin-constraint | Main.hs | module Main(main) where
printMe = ()
main = print ()
| null | https://raw.githubusercontent.com/mpickering/plugin-constraint/71104d7a1f48f6e42701f5398bb17566cdc34564/test/src/Main.hs | haskell | module Main(main) where
printMe = ()
main = print ()
| |
e368efa84f446a27a8500a784c8ab2f957eeec1c4bc4039c4ab0b840f2add83e | zenhack/mule | tsort_t.ml | type 'n comparator = (module Comparator.S with type t = 'n)
type 'n edge = {
to_: 'n;
from: 'n;
}
type 'n result =
[ `Single of 'n | `Cycle of ('n * 'n list) ] list
| null | https://raw.githubusercontent.com/zenhack/mule/f3e23342906d834abb9659c72a67c1405c936a00/src/tsort/tsort_t.ml | ocaml | type 'n comparator = (module Comparator.S with type t = 'n)
type 'n edge = {
to_: 'n;
from: 'n;
}
type 'n result =
[ `Single of 'n | `Cycle of ('n * 'n list) ] list
| |
6a691e4f829aaebdea123e2aa3edc25a2c7b2c2a0c067f48d95ced072f10785b | shentufoundation/deepsea | StmtClocal.mli | open AST
open Ctypes
open Datatypes
open ExpMiniC
open Globalenvs
open Integers
type statement =
| Sskip
| Smassign of expr * expr
| Ssassign of expr * expr
| Sset of ident * expr
| Scall of ident option * label * expr list
| Ssequence of statement * statement
| Sifthenelse of expr * statement * statement
| Sloop of statement
| Sbreak
| Sreturn of ident option
| Shash of expr * expr * expr option
| Stransfer of expr * expr
| Scallmethod of expr * ident list * Int.int * expr * expr option * expr list
| Slog of expr list * expr list
| Srevert
type coq_function = { fn_return : coq_type;
fn_params : (ident, coq_type) prod list;
fn_temps : (ident, coq_type) prod list;
fn_locals : (ident, coq_type) prod list;
fn_body : statement }
val fn_return : coq_function -> coq_type
val fn_params : coq_function -> (ident, coq_type) prod list
val fn_temps : coq_function -> (ident, coq_type) prod list
val fn_locals : coq_function -> (ident, coq_type) prod list
val fn_body : coq_function -> statement
type genv = (coq_function, coq_type) Genv.t
| null | https://raw.githubusercontent.com/shentufoundation/deepsea/970576a97c8992655ed2f173f576502d73b827e1/src/backend/extraction/StmtClocal.mli | ocaml | open AST
open Ctypes
open Datatypes
open ExpMiniC
open Globalenvs
open Integers
type statement =
| Sskip
| Smassign of expr * expr
| Ssassign of expr * expr
| Sset of ident * expr
| Scall of ident option * label * expr list
| Ssequence of statement * statement
| Sifthenelse of expr * statement * statement
| Sloop of statement
| Sbreak
| Sreturn of ident option
| Shash of expr * expr * expr option
| Stransfer of expr * expr
| Scallmethod of expr * ident list * Int.int * expr * expr option * expr list
| Slog of expr list * expr list
| Srevert
type coq_function = { fn_return : coq_type;
fn_params : (ident, coq_type) prod list;
fn_temps : (ident, coq_type) prod list;
fn_locals : (ident, coq_type) prod list;
fn_body : statement }
val fn_return : coq_function -> coq_type
val fn_params : coq_function -> (ident, coq_type) prod list
val fn_temps : coq_function -> (ident, coq_type) prod list
val fn_locals : coq_function -> (ident, coq_type) prod list
val fn_body : coq_function -> statement
type genv = (coq_function, coq_type) Genv.t
| |
b2002c4543ab14b40238d404830cce18f4dfdd0bab8caa77e6d188bc2349db72 | buntine/Simply-Scheme-Exercises | 9-11.scm | Write a procedure unabbrev that takes two sentences as arguments . It should
return a sentence that ’s the same as the first sentence , except that any numbers in the
original sentence should be replaced with words from the second sentence . A number 2
in the first sentence should be replaced with the second word of the second sentence , a
6 with the sixth word , and so on .
;
> ( unabbrev ’ ( ) ’ ( bill hank kermit ) )
; (JOHN BILL WAYNE FRED JOEY)
;
> ( unabbrev ’ ( i 3 4 tell 2 ) ’ ( do you want to know a secret ? ) )
; (I WANT TO TELL YOU)
(define (unabbrev senta sentb)
(every
(lambda (wd) (if (number? wd) (item wd sentb) wd))
senta))
| null | https://raw.githubusercontent.com/buntine/Simply-Scheme-Exercises/c6cbf0bd60d6385b506b8df94c348ac5edc7f646/09-lambda/9-11.scm | scheme |
(JOHN BILL WAYNE FRED JOEY)
(I WANT TO TELL YOU) | Write a procedure unabbrev that takes two sentences as arguments . It should
return a sentence that ’s the same as the first sentence , except that any numbers in the
original sentence should be replaced with words from the second sentence . A number 2
in the first sentence should be replaced with the second word of the second sentence , a
6 with the sixth word , and so on .
> ( unabbrev ’ ( ) ’ ( bill hank kermit ) )
> ( unabbrev ’ ( i 3 4 tell 2 ) ’ ( do you want to know a secret ? ) )
(define (unabbrev senta sentb)
(every
(lambda (wd) (if (number? wd) (item wd sentb) wd))
senta))
|
0c49a17cb9001f8e0b33b84d15ad42b5188102b6994be07c319232aa14a8f7c4 | clckwrks/clckwrks | API.hs | {-# LANGUAGE RecordWildCards, OverloadedStrings #-}
module Clckwrks.Authenticate.API
( Username(..)
, getEmail
, getUser
, getUsername
, insecureUpdateUser
, setCreateUserCallback
) where
import Clckwrks.Authenticate.Plugin (authenticatePlugin)
import Clckwrks.Authenticate.Monad (AuthenticatePluginState(..))
import Clckwrks.Monad (Clck, ClckPlugins, plugins)
import Control.Concurrent.STM (atomically)
import Control.Concurrent.STM.TVar (modifyTVar')
import Control.Monad (join)
import Control.Monad.State (get)
import Control.Monad.Trans (liftIO)
import Data.Acid as Acid (AcidState, query, update)
import Data.Maybe (maybe)
import Data.Monoid (mempty)
import Data.Text (Text)
import Data.UserId (UserId)
import Happstack.Authenticate.Core (AuthenticateConfig(_createUserCallback), GetUserByUserId(..), Email(..), UpdateUser(..), User(..), Username(..))
import Web.Plugins.Core (Plugin(..), When(Always), addCleanup, addHandler, addPluginState, getConfig, getPluginRouteFn, getPluginState, getPluginsSt, initPlugin, modifyPluginState')
getUser :: UserId -> Clck url (Maybe User)
getUser uid =
do p <- plugins <$> get
~(Just aps) <- getPluginState p (pluginName authenticatePlugin)
liftIO $ Acid.query (acidStateAuthenticate aps) (GetUserByUserId uid)
-- | Update an existing 'User'. Must already have a valid 'UserId'.
--
-- no security checks are performed to ensure that the caller is
-- authorized to change data for the 'User'.
insecureUpdateUser :: User -> Clck url ()
insecureUpdateUser user =
do p <- plugins <$> get
~(Just aps) <- getPluginState p (pluginName authenticatePlugin)
liftIO $ Acid.update (acidStateAuthenticate aps) (UpdateUser user)
getUsername :: UserId -> Clck url (Maybe Username)
getUsername uid =
do mUser <- getUser uid
pure $ _username <$> mUser
getEmail :: UserId -> Clck url (Maybe Email)
getEmail uid =
do mUser <- getUser uid
pure $ join $ _email <$> mUser
setCreateUserCallback :: ClckPlugins -> Maybe (User -> IO ()) -> IO ()
setCreateUserCallback p mcb =
do ~(Just aps) <- getPluginState p (pluginName authenticatePlugin)
liftIO $ atomically $ modifyTVar' (apsAuthenticateConfigTV aps) $ (\ac -> ac { _createUserCallback = mcb })
pure ()
| null | https://raw.githubusercontent.com/clckwrks/clckwrks/b72effd54adf34cf0807de61e91a7ea933685ccb/Clckwrks/Authenticate/API.hs | haskell | # LANGUAGE RecordWildCards, OverloadedStrings #
| Update an existing 'User'. Must already have a valid 'UserId'.
no security checks are performed to ensure that the caller is
authorized to change data for the 'User'. | module Clckwrks.Authenticate.API
( Username(..)
, getEmail
, getUser
, getUsername
, insecureUpdateUser
, setCreateUserCallback
) where
import Clckwrks.Authenticate.Plugin (authenticatePlugin)
import Clckwrks.Authenticate.Monad (AuthenticatePluginState(..))
import Clckwrks.Monad (Clck, ClckPlugins, plugins)
import Control.Concurrent.STM (atomically)
import Control.Concurrent.STM.TVar (modifyTVar')
import Control.Monad (join)
import Control.Monad.State (get)
import Control.Monad.Trans (liftIO)
import Data.Acid as Acid (AcidState, query, update)
import Data.Maybe (maybe)
import Data.Monoid (mempty)
import Data.Text (Text)
import Data.UserId (UserId)
import Happstack.Authenticate.Core (AuthenticateConfig(_createUserCallback), GetUserByUserId(..), Email(..), UpdateUser(..), User(..), Username(..))
import Web.Plugins.Core (Plugin(..), When(Always), addCleanup, addHandler, addPluginState, getConfig, getPluginRouteFn, getPluginState, getPluginsSt, initPlugin, modifyPluginState')
getUser :: UserId -> Clck url (Maybe User)
getUser uid =
do p <- plugins <$> get
~(Just aps) <- getPluginState p (pluginName authenticatePlugin)
liftIO $ Acid.query (acidStateAuthenticate aps) (GetUserByUserId uid)
insecureUpdateUser :: User -> Clck url ()
insecureUpdateUser user =
do p <- plugins <$> get
~(Just aps) <- getPluginState p (pluginName authenticatePlugin)
liftIO $ Acid.update (acidStateAuthenticate aps) (UpdateUser user)
getUsername :: UserId -> Clck url (Maybe Username)
getUsername uid =
do mUser <- getUser uid
pure $ _username <$> mUser
getEmail :: UserId -> Clck url (Maybe Email)
getEmail uid =
do mUser <- getUser uid
pure $ join $ _email <$> mUser
setCreateUserCallback :: ClckPlugins -> Maybe (User -> IO ()) -> IO ()
setCreateUserCallback p mcb =
do ~(Just aps) <- getPluginState p (pluginName authenticatePlugin)
liftIO $ atomically $ modifyTVar' (apsAuthenticateConfigTV aps) $ (\ac -> ac { _createUserCallback = mcb })
pure ()
|
92f264e4257624ba42baa65e8897989d2003fa67e8d914de889e5cf54d2af6c4 | bscarlet/llvm-general | CodeGenOpt.hs | | Code generation options , used in specifying TargetMachine
module LLVM.General.CodeGenOpt where
import LLVM.General.Prelude
-- | <>
data Level
= None
| Less
| Default
| Aggressive
deriving (Eq, Ord, Read, Show, Typeable, Data)
| null | https://raw.githubusercontent.com/bscarlet/llvm-general/61fd03639063283e7dc617698265cc883baf0eec/llvm-general/src/LLVM/General/CodeGenOpt.hs | haskell | | <> | | Code generation options , used in specifying TargetMachine
module LLVM.General.CodeGenOpt where
import LLVM.General.Prelude
data Level
= None
| Less
| Default
| Aggressive
deriving (Eq, Ord, Read, Show, Typeable, Data)
|
84f888810e4cfc253c8fc19897ea40ddf9725cce9266dbaed6fc91d430857fd6 | ghc/testsuite | T3731-short.hs | # LANGUAGE DeriveDataTypeable ,
FlexibleContexts , FlexibleInstances ,
MultiParamTypeClasses ,
OverlappingInstances , UndecidableInstances ,
Rank2Types , KindSignatures , EmptyDataDecls #
FlexibleContexts, FlexibleInstances,
MultiParamTypeClasses,
OverlappingInstances, UndecidableInstances,
Rank2Types, KindSignatures, EmptyDataDecls #-}
# OPTIONS_GHC -Wall #
module Main (main) where
class Sat a where
dict :: a -- Holds a default value
class Sat a => Data a where
gunfold :: (forall b r. Data b => (b -> r) -> r) -> a
instance (Sat [a], Data a) => Data [a] where
gunfold _ = []
class Data a => Default a where
defaultValue :: a
defaultValue = gunfold (\c -> c dict)
instance Default t => Sat t where
dict = defaultValue
instance Default a => Default [a] where
defaultValue = []
data Proposition = Prop Expression
data Expression = Conj [Expression]
instance Data Expression => Data Proposition where
gunfold k = k Prop
instance (Data [Expression],Sat Expression) => Data Expression where
-- DV: Notice what happens when we remove the Sat Expression above!
-- Everything starts working!
gunfold k = k Conj
instance Default Expression
instance Default Proposition
main :: IO ()
main = case (defaultValue :: Proposition) of
Prop exp -> case exp of
Conj _ -> putStrLn "Hurray2!"
Need Default Proposition
for which we have an instance
Instance
Default Proposition
needs superclass
Data Proposition
via instance dfun , needs
Data Expression
via instance dfun , needs
Sat Expression
via instance dfun , needs
Default Expression
for which we have an instance
Instance
d1 : Default Expression
needs superclass [ d1 = MkD d2 .. ]
d2 : Data Expression { superclass Sat Expression }
via instance dfun , [ d2 = dfun d3 d4 ] needs
d3 : Sat Expression ( and d4 : Data [ Expression ] )
via instance dfun , [ d3 = dfun d5 ] needs
d5 Default Expression
for which we have an instance [ d5 = d1 ]
d1 = MkD d2 ..
d2 = dfun d3 d4
d3 = dfun d1
Instance
d1 : Default Expression
needs superclass [ d1 = MkD d2 .. ]
d2 : Data Expression { superclass Sat Expression d2 ' = sc d2 }
via instance dfun , [ d2 = dfun d3 d4 ] needs
d3 : Sat Expression ( and d4 : Data [ Expression ] )
and we can solve : d3 = d2 ' ... no : recursion checker will reject
for which we have an instance
Instance
Default Proposition
needs superclass
Data Proposition
via instance dfun, needs
Data Expression
via instance dfun, needs
Sat Expression
via instance dfun, needs
Default Expression
for which we have an instance
Instance
d1: Default Expression
needs superclass [d1 = MkD d2 ..]
d2: Data Expression {superclass Sat Expression}
via instance dfun, [d2 = dfun d3 d4] needs
d3 : Sat Expression (and d4 : Data [Expression])
via instance dfun, [d3 = dfun d5] needs
d5 Default Expression
for which we have an instance [d5 = d1]
d1 = MkD d2 ..
d2 = dfun d3 d4
d3 = dfun d1
Instance
d1: Default Expression
needs superclass [d1 = MkD d2 ..]
d2: Data Expression {superclass Sat Expression d2' = sc d2 }
via instance dfun, [d2 = dfun d3 d4] needs
d3 : Sat Expression (and d4 : Data [Expression])
and we can solve: d3 = d2'... no: recursion checker will reject
-}
| null | https://raw.githubusercontent.com/ghc/testsuite/998a816ae89c4fd573f4abd7c6abb346cf7ee9af/tests/typecheck/should_run/T3731-short.hs | haskell | Holds a default value
DV: Notice what happens when we remove the Sat Expression above!
Everything starts working! | # LANGUAGE DeriveDataTypeable ,
FlexibleContexts , FlexibleInstances ,
MultiParamTypeClasses ,
OverlappingInstances , UndecidableInstances ,
Rank2Types , KindSignatures , EmptyDataDecls #
FlexibleContexts, FlexibleInstances,
MultiParamTypeClasses,
OverlappingInstances, UndecidableInstances,
Rank2Types, KindSignatures, EmptyDataDecls #-}
# OPTIONS_GHC -Wall #
module Main (main) where
class Sat a where
class Sat a => Data a where
gunfold :: (forall b r. Data b => (b -> r) -> r) -> a
instance (Sat [a], Data a) => Data [a] where
gunfold _ = []
class Data a => Default a where
defaultValue :: a
defaultValue = gunfold (\c -> c dict)
instance Default t => Sat t where
dict = defaultValue
instance Default a => Default [a] where
defaultValue = []
data Proposition = Prop Expression
data Expression = Conj [Expression]
instance Data Expression => Data Proposition where
gunfold k = k Prop
instance (Data [Expression],Sat Expression) => Data Expression where
gunfold k = k Conj
instance Default Expression
instance Default Proposition
main :: IO ()
main = case (defaultValue :: Proposition) of
Prop exp -> case exp of
Conj _ -> putStrLn "Hurray2!"
Need Default Proposition
for which we have an instance
Instance
Default Proposition
needs superclass
Data Proposition
via instance dfun , needs
Data Expression
via instance dfun , needs
Sat Expression
via instance dfun , needs
Default Expression
for which we have an instance
Instance
d1 : Default Expression
needs superclass [ d1 = MkD d2 .. ]
d2 : Data Expression { superclass Sat Expression }
via instance dfun , [ d2 = dfun d3 d4 ] needs
d3 : Sat Expression ( and d4 : Data [ Expression ] )
via instance dfun , [ d3 = dfun d5 ] needs
d5 Default Expression
for which we have an instance [ d5 = d1 ]
d1 = MkD d2 ..
d2 = dfun d3 d4
d3 = dfun d1
Instance
d1 : Default Expression
needs superclass [ d1 = MkD d2 .. ]
d2 : Data Expression { superclass Sat Expression d2 ' = sc d2 }
via instance dfun , [ d2 = dfun d3 d4 ] needs
d3 : Sat Expression ( and d4 : Data [ Expression ] )
and we can solve : d3 = d2 ' ... no : recursion checker will reject
for which we have an instance
Instance
Default Proposition
needs superclass
Data Proposition
via instance dfun, needs
Data Expression
via instance dfun, needs
Sat Expression
via instance dfun, needs
Default Expression
for which we have an instance
Instance
d1: Default Expression
needs superclass [d1 = MkD d2 ..]
d2: Data Expression {superclass Sat Expression}
via instance dfun, [d2 = dfun d3 d4] needs
d3 : Sat Expression (and d4 : Data [Expression])
via instance dfun, [d3 = dfun d5] needs
d5 Default Expression
for which we have an instance [d5 = d1]
d1 = MkD d2 ..
d2 = dfun d3 d4
d3 = dfun d1
Instance
d1: Default Expression
needs superclass [d1 = MkD d2 ..]
d2: Data Expression {superclass Sat Expression d2' = sc d2 }
via instance dfun, [d2 = dfun d3 d4] needs
d3 : Sat Expression (and d4 : Data [Expression])
and we can solve: d3 = d2'... no: recursion checker will reject
-}
|
d6fb2cb92e3b545ab29be8b82ea9dc414e8a35e2eabac09f5524eaf40bd6ff1c | namin/biohacker | demo-false-positive.lisp | biohacker / trunk / network - debugger / presentation / demo - false - positive.lisp
(experiment
false-positive
(a b f)
:growth? nil
:essential-compounds (a e)
:knock-outs (g1))
#|
Focusing on experiment FALSE-POSITIVE.
Experiment is not consistent with model. Needs:
( (NOT (GENE-ON G4)) )
|#
| null | https://raw.githubusercontent.com/namin/biohacker/6b5da4c51c9caa6b5e1a68b046af171708d1af64/network-debugger/presentation/demo-false-positive.lisp | lisp |
Focusing on experiment FALSE-POSITIVE.
Experiment is not consistent with model. Needs:
( (NOT (GENE-ON G4)) )
| biohacker / trunk / network - debugger / presentation / demo - false - positive.lisp
(experiment
false-positive
(a b f)
:growth? nil
:essential-compounds (a e)
:knock-outs (g1))
|
162b364966d3a21fb7757fc0d902612cf350018a04c285ef9d945e0437fa83f0 | wies/grasshopper | debug.ml | type level = NONE | FATAL | ERROR | WARN | NOTICE | INFO | DEBUG of int
let int_of_level = function
| NONE -> 0 | FATAL -> 1 | ERROR -> 2 | WARN -> 3
| NOTICE -> 4 | INFO -> 5 | DEBUG l -> 6 + l
let level_of_int = function
| 0 -> NONE | 1 -> FATAL | 2 -> ERROR | 3 -> WARN
| 4 -> NOTICE | 5 -> INFO | l when l > 5 -> DEBUG (l - 6)
| i -> failwith ("invalid level: " ^ string_of_int i)
let lv = ref (int_of_level NOTICE)
let set_level lvl =
lv := int_of_level lvl;
match lvl with
| DEBUG _ -> Printexc.record_backtrace true
| _ -> Printexc.record_backtrace false
let show lvl = !lv >= (int_of_level lvl)
let is_debug l = show (DEBUG l)
let is_info () = show INFO
let is_notice () = show NOTICE
let is_warn () = show WARN
let is_error () = show ERROR
let more_verbose () =
let nlv = match (level_of_int !lv) with
| DEBUG l -> DEBUG (l + 1)
| INFO -> DEBUG 0
| NOTICE -> INFO
| WARN -> NOTICE
| ERROR -> WARN
| FATAL -> ERROR
| NONE -> FATAL
in
set_level nlv
let less_verbose () =
let nlv = match (level_of_int !lv) with
| DEBUG 0 -> INFO
| DEBUG l -> DEBUG (l - 1)
| INFO -> NOTICE
| NOTICE -> WARN
| WARN -> ERROR
| ERROR -> FATAL
| FATAL -> NONE
| NONE -> NONE
in
set_level nlv
(** always print this message *)
let amsg s =
print_string s; flush_all ()
let debug s = if show (DEBUG 0) then amsg (s ())
let debugl l s = if show (DEBUG l) then amsg (s ())
let info s = if show INFO then amsg (s ())
let notice s = if show NOTICE then amsg (s ())
let warn s = if show WARN then amsg (s ())
let error s = if show ERROR then amsg (s ())
let phase s fn x =
debug (fun () -> s () ^ "...");
let res = fn x in
debug (fun () -> "done.\n");
res
| null | https://raw.githubusercontent.com/wies/grasshopper/108473b0a678f0d93fffec6da2ad6bcdce5bddb9/src/util/debug.ml | ocaml | * always print this message | type level = NONE | FATAL | ERROR | WARN | NOTICE | INFO | DEBUG of int
let int_of_level = function
| NONE -> 0 | FATAL -> 1 | ERROR -> 2 | WARN -> 3
| NOTICE -> 4 | INFO -> 5 | DEBUG l -> 6 + l
let level_of_int = function
| 0 -> NONE | 1 -> FATAL | 2 -> ERROR | 3 -> WARN
| 4 -> NOTICE | 5 -> INFO | l when l > 5 -> DEBUG (l - 6)
| i -> failwith ("invalid level: " ^ string_of_int i)
let lv = ref (int_of_level NOTICE)
let set_level lvl =
lv := int_of_level lvl;
match lvl with
| DEBUG _ -> Printexc.record_backtrace true
| _ -> Printexc.record_backtrace false
let show lvl = !lv >= (int_of_level lvl)
let is_debug l = show (DEBUG l)
let is_info () = show INFO
let is_notice () = show NOTICE
let is_warn () = show WARN
let is_error () = show ERROR
let more_verbose () =
let nlv = match (level_of_int !lv) with
| DEBUG l -> DEBUG (l + 1)
| INFO -> DEBUG 0
| NOTICE -> INFO
| WARN -> NOTICE
| ERROR -> WARN
| FATAL -> ERROR
| NONE -> FATAL
in
set_level nlv
let less_verbose () =
let nlv = match (level_of_int !lv) with
| DEBUG 0 -> INFO
| DEBUG l -> DEBUG (l - 1)
| INFO -> NOTICE
| NOTICE -> WARN
| WARN -> ERROR
| ERROR -> FATAL
| FATAL -> NONE
| NONE -> NONE
in
set_level nlv
let amsg s =
print_string s; flush_all ()
let debug s = if show (DEBUG 0) then amsg (s ())
let debugl l s = if show (DEBUG l) then amsg (s ())
let info s = if show INFO then amsg (s ())
let notice s = if show NOTICE then amsg (s ())
let warn s = if show WARN then amsg (s ())
let error s = if show ERROR then amsg (s ())
let phase s fn x =
debug (fun () -> s () ^ "...");
let res = fn x in
debug (fun () -> "done.\n");
res
|
c49fbc504fe2ac4e69f3ac9aa6cad939f5946f2dc10c4a3633d2df97079095f6 | Metaxal/rascas | derivative.rkt | #lang racket/base
(require "../derivative.rkt"
"../misc.rkt"
"../algorithmic.rkt"
"../arithmetic.rkt"
"../rackunit.rkt"
"../automatic-simplify.rkt"
"../distribute.rkt"
"../substitute.rkt"
"../trig-functions.rkt"
"../special-functions.rkt")
Tool to test the symbolic derivative value against the numeric one
f must be a procedure of 1 argument
(define (check-derivative f [xs (build-list 10 (λ (i) (/ (- (random) .5)
(random))))])
(define dfnum (numeric-derivative f))
(define dfsym (derivative/proc f))
(for ([v (in-list xs)])
(check-= (->inexact
(sqr (- (dfnum v)
(dfsym v))))
0.
0.001)))
(check-equal? (derivative (+ (* 3 (^ 'x 2)) (* 4 'x)) 'x)
(+ (* 6 'x) 4))
(check-equal? (derivative (/ 3 'x) 'x)
(/ -3 (sqr 'x)))
(check-equal? (derivative (exp (* 3 'x)) 'x)
'(* 3 (exp (* 3 x))))
(check-equal? (derivative (log (* 3 'x)) 'x)
'(^ x -1))
(check-equal? (derivative (sin (* 3 'x)) 'x)
'(* 3 (cos (* 3 x))))
(check-equal? (derivative (cos (* 3 'x)) 'x)
'(* -3 (sin (* 3 x))))
(check-equal? (derivative (tan (* 3 'x)) 'x)
'(* 3 (^ (cos (* 3 x)) -2)))
TODO : Check registering a derivative of 3 args
; Check that 'derivative is registered as a function
(check-equal? (automatic-simplify '(derivative (sqr x) x))
(* 2 'x))
;; Register a function /after/ it has been used for derivation.
;; Simplify the expression to obtain the correct derivative.
;; WARNING: Test disabled because it's risky when using substitute
;; (see test just below)
#;
(let ()
(define bad-deriv (derivative '(__unknown-deriv (* x 2)) 'x))
(check-equal? bad-deriv '(derivative (__unknown-deriv (* x 2)) x))
(register-function '__unknown-deriv (λ (x) (sqr x)))
(check-equal? (automatic-simplify bad-deriv)
(* 8 'x)))
(let ()
;; Simulate a known function without a known derivative
(define (floc x) (+ x 10))
(register-function 'floc floc)
(check-exn exn:fail? (λ () (substitute (derivative '(floc x) 'x) 'x 0))))
(check-derivative gamma (build-list 10 (λ (i) (* 10 (random)))))
;;; list
(check-equal? (derivative (_list 'x 'y 'x 'z) 'x)
'(list 1 0 1 0))
(check-equal? (derivative (_list (* 'x 2) (^ 'x 'a) (log 'x)) 'x)
'(list 2 (* a (^ x (+ -1 a))) (^ x -1)))
(check-equal? (derivative (_list (* 'x 2) (^ 'x 'a) (log 'x)) 'a)
'(list 0 (* (log x) (^ x a)) 0))
;;; let*
(check-equal? (derivative (_let* `([a ,(+ 'x 2)])
(* (+ 1 'a) (+ 2 'a))) 'x)
'(+ 3 (* 2 (+ 2 x))))
(check-equal? (derivative (expand-let* (_let* `([a ,(+ 'x 2)])
(* (+ 1 'a) (+ 2 'a)))) 'x)
'(+ 7 (* 2 x)))
; error: Cannot differentiate for a bound id (a)
(check-exn exn:fail?
(λ () (derivative (_let* `([a ,(+ 'x 2)]
[b ,(* 'a 2)])
(* (+ 1 'b) (+ 2 'a)))
'a)))
(check-equal? (derivative (_let* `([a (+ x 2)])
(* (+ 1 'a) (+ 2 'a))) 'y)
0)
(check-equal? (distribute-product
(expand-let*
(derivative (_let* `([b (* (+ 1 a) (+ 2 a))] [c (* (+ b 1) (+ b 2))] [d c])
(* (+ 'd 1) (+ 'd 2)))
'a)))
(distribute-product
(derivative (expand-let*
(_let* `([b (* (+ 1 a) (+ 2 a))] [c (* (+ b 1) (+ b 2))] [d c])
(* (+ 'd 1) (+ 'd 2))))
'a)))
(check-not-exn
(λ () (derivative
'(let* ((_u0 (+ (* _w_0_0_0 a) 1))
(_w_out_1_0 (* 0.5 _u0 (+ 1 (sgn _u0))))
(_u1 4)
(_w_out_1_1 (* 0.5 _u1 (+ 1 (sgn _u1))))
(_w_out_2_0
(+ 1.0 (exp (* -1 (+ (* 3 _w_out_1_0) (* 2 _w_out_1_1))))))
(_w_out_2_1
(+ 1.0 (exp (* -1 (+ (* 4 _w_out_1_0) (* 5 _w_out_1_1))))))
(_u2 (+ (* 3 _w_out_2_0) (* 2 _w_out_2_1))))
(+ (* 0.5 _u2 _w_3_0_0 (+ 1 (sgn _u2))) (* 0.5 _u2 _w_3_0_1 (+ 1 (sgn _u2)))))
'_w_0_0_0)))
(check-equal?
(expand-let*
(contract-let*
(derivative
'(let* ((a (exp x))
(b (+ 1.0 a))
(c (+ -1.0 a))
(d (^ b -2)))
(* a (+ (^ b -1) (* -1 d c) (* -1 d a) (* (+ (* -1 d) (* 2 (^ b -3) c)) a))))
'x)))
(expand-let*
'(let* ((_g4 (exp x))
(b (+ 1.0 _g4))
(c (+ -1.0 _g4))
(_g0 (^ b -3))
(_g3 (^ b -2))
(_g1 (* 2 _g0 c))
(_g2 (* -1 _g3)))
(*
_g4
(+
(* (+ _g1 _g2) _g4)
(* -1 _g3 _g4)
(* (+ _g1 (* -2 _g3)) _g4)
(* _g4 (+ _g2 (* 2 _g0 _g4)))
(^ b -1)
(* -1 _g3 c)
(* -2 _g0 _g4 (+ (* -2 _g4) (* -1 c)))
(* _g4 (+ (* -1 _g3) (* -6 _g4 (^ b -4) c))))))))
(check-derivative
(λ (x)
`(let* ((a (exp ,x))
(b (+ 1.0 a))
(c (+ -1.0 a))
(d (^ b -3))
(e (^ b -2))
(f (* 2 d c))
(g (* -1 e)))
(*
a
(+
(^ b -1)
(* -1 e c)
(* -1 e a)
(* (+ (* -2 e) f) a)
(* (+ (* -1 e) f) a)
(* -2 d a (+ (* -1 c) (* -2 a)))
(* a (+ g (* 2 d a)))
(* a (+ g (* -6 (^ b -4) c a))))))))
(check-equal? ((derivative/proc sqr) 'a)
(* 'a 2))
(check-equal? ((derivative/proc sqr) 2)
4)
(check-equal? ((derivative/proc log) 1/2)
2)
(check-equal? ((derivative/proc log #:inexact? #t) (sqrt 2))
(->inexact (/ (sqrt 2))))
(check-equal?
(jacobian (+ (* 'c 'a) (* 'd (^ 'b 2)))
'(a b))
'(list c
(* 2 b d)))
(check-equal?
(rebind-all-let*
(jacobian (exp (+ (* 'c 'a) (* 'd (^ 'b 2))))
'(a b))
'_s)
'(let* ((_s0 (exp (+ (* a c) (* (^ b 2) d)))))
(list (* _s0 c)
(* 2 _s0 b d))))
(check-equal?
(rebind-all-let*
(jacobian (sin (exp (+ (* 'c 'a) (* 'd (^ 'b 2)))))
'(a b))
'_s)
'(let* ((_s0 (+ (* a c) (* (^ b 2) d)))
(_s1 (* (cos (exp _s0)) (exp _s0))))
(list (* _s1 c) (* 2 _s1 b d))))
;; 'variables' bound in let*
(check-equal?
(simplify-top
(jacobian
`(let* ([a (+ 3 x)]
[b (+ 2 x a)])
(+ (* a b)
(* (log a) (log b))))
'(a b)))
'(list 0 0))
;; Compare:
( tree - size ( jacobian ( apply * ( build - list 100 ( λ ( i ) ( + i 1 ' x ) ) ) )
'(x)))
( tree - size ( jacobian ( apply * ( build - list 100 ( λ ( i ) ( + i 1 ' x ) ) ) )
'(x))
#:log-product? #t)
| null | https://raw.githubusercontent.com/Metaxal/rascas/a14babb44b847a57743545824ebb326a2783aa35/tests/derivative.rkt | racket | Check that 'derivative is registered as a function
Register a function /after/ it has been used for derivation.
Simplify the expression to obtain the correct derivative.
WARNING: Test disabled because it's risky when using substitute
(see test just below)
Simulate a known function without a known derivative
list
let*
error: Cannot differentiate for a bound id (a)
'variables' bound in let*
Compare: | #lang racket/base
(require "../derivative.rkt"
"../misc.rkt"
"../algorithmic.rkt"
"../arithmetic.rkt"
"../rackunit.rkt"
"../automatic-simplify.rkt"
"../distribute.rkt"
"../substitute.rkt"
"../trig-functions.rkt"
"../special-functions.rkt")
Tool to test the symbolic derivative value against the numeric one
f must be a procedure of 1 argument
(define (check-derivative f [xs (build-list 10 (λ (i) (/ (- (random) .5)
(random))))])
(define dfnum (numeric-derivative f))
(define dfsym (derivative/proc f))
(for ([v (in-list xs)])
(check-= (->inexact
(sqr (- (dfnum v)
(dfsym v))))
0.
0.001)))
(check-equal? (derivative (+ (* 3 (^ 'x 2)) (* 4 'x)) 'x)
(+ (* 6 'x) 4))
(check-equal? (derivative (/ 3 'x) 'x)
(/ -3 (sqr 'x)))
(check-equal? (derivative (exp (* 3 'x)) 'x)
'(* 3 (exp (* 3 x))))
(check-equal? (derivative (log (* 3 'x)) 'x)
'(^ x -1))
(check-equal? (derivative (sin (* 3 'x)) 'x)
'(* 3 (cos (* 3 x))))
(check-equal? (derivative (cos (* 3 'x)) 'x)
'(* -3 (sin (* 3 x))))
(check-equal? (derivative (tan (* 3 'x)) 'x)
'(* 3 (^ (cos (* 3 x)) -2)))
TODO : Check registering a derivative of 3 args
(check-equal? (automatic-simplify '(derivative (sqr x) x))
(* 2 'x))
(let ()
(define bad-deriv (derivative '(__unknown-deriv (* x 2)) 'x))
(check-equal? bad-deriv '(derivative (__unknown-deriv (* x 2)) x))
(register-function '__unknown-deriv (λ (x) (sqr x)))
(check-equal? (automatic-simplify bad-deriv)
(* 8 'x)))
(let ()
(define (floc x) (+ x 10))
(register-function 'floc floc)
(check-exn exn:fail? (λ () (substitute (derivative '(floc x) 'x) 'x 0))))
(check-derivative gamma (build-list 10 (λ (i) (* 10 (random)))))
(check-equal? (derivative (_list 'x 'y 'x 'z) 'x)
'(list 1 0 1 0))
(check-equal? (derivative (_list (* 'x 2) (^ 'x 'a) (log 'x)) 'x)
'(list 2 (* a (^ x (+ -1 a))) (^ x -1)))
(check-equal? (derivative (_list (* 'x 2) (^ 'x 'a) (log 'x)) 'a)
'(list 0 (* (log x) (^ x a)) 0))
(check-equal? (derivative (_let* `([a ,(+ 'x 2)])
(* (+ 1 'a) (+ 2 'a))) 'x)
'(+ 3 (* 2 (+ 2 x))))
(check-equal? (derivative (expand-let* (_let* `([a ,(+ 'x 2)])
(* (+ 1 'a) (+ 2 'a)))) 'x)
'(+ 7 (* 2 x)))
(check-exn exn:fail?
(λ () (derivative (_let* `([a ,(+ 'x 2)]
[b ,(* 'a 2)])
(* (+ 1 'b) (+ 2 'a)))
'a)))
(check-equal? (derivative (_let* `([a (+ x 2)])
(* (+ 1 'a) (+ 2 'a))) 'y)
0)
(check-equal? (distribute-product
(expand-let*
(derivative (_let* `([b (* (+ 1 a) (+ 2 a))] [c (* (+ b 1) (+ b 2))] [d c])
(* (+ 'd 1) (+ 'd 2)))
'a)))
(distribute-product
(derivative (expand-let*
(_let* `([b (* (+ 1 a) (+ 2 a))] [c (* (+ b 1) (+ b 2))] [d c])
(* (+ 'd 1) (+ 'd 2))))
'a)))
(check-not-exn
(λ () (derivative
'(let* ((_u0 (+ (* _w_0_0_0 a) 1))
(_w_out_1_0 (* 0.5 _u0 (+ 1 (sgn _u0))))
(_u1 4)
(_w_out_1_1 (* 0.5 _u1 (+ 1 (sgn _u1))))
(_w_out_2_0
(+ 1.0 (exp (* -1 (+ (* 3 _w_out_1_0) (* 2 _w_out_1_1))))))
(_w_out_2_1
(+ 1.0 (exp (* -1 (+ (* 4 _w_out_1_0) (* 5 _w_out_1_1))))))
(_u2 (+ (* 3 _w_out_2_0) (* 2 _w_out_2_1))))
(+ (* 0.5 _u2 _w_3_0_0 (+ 1 (sgn _u2))) (* 0.5 _u2 _w_3_0_1 (+ 1 (sgn _u2)))))
'_w_0_0_0)))
(check-equal?
(expand-let*
(contract-let*
(derivative
'(let* ((a (exp x))
(b (+ 1.0 a))
(c (+ -1.0 a))
(d (^ b -2)))
(* a (+ (^ b -1) (* -1 d c) (* -1 d a) (* (+ (* -1 d) (* 2 (^ b -3) c)) a))))
'x)))
(expand-let*
'(let* ((_g4 (exp x))
(b (+ 1.0 _g4))
(c (+ -1.0 _g4))
(_g0 (^ b -3))
(_g3 (^ b -2))
(_g1 (* 2 _g0 c))
(_g2 (* -1 _g3)))
(*
_g4
(+
(* (+ _g1 _g2) _g4)
(* -1 _g3 _g4)
(* (+ _g1 (* -2 _g3)) _g4)
(* _g4 (+ _g2 (* 2 _g0 _g4)))
(^ b -1)
(* -1 _g3 c)
(* -2 _g0 _g4 (+ (* -2 _g4) (* -1 c)))
(* _g4 (+ (* -1 _g3) (* -6 _g4 (^ b -4) c))))))))
(check-derivative
(λ (x)
`(let* ((a (exp ,x))
(b (+ 1.0 a))
(c (+ -1.0 a))
(d (^ b -3))
(e (^ b -2))
(f (* 2 d c))
(g (* -1 e)))
(*
a
(+
(^ b -1)
(* -1 e c)
(* -1 e a)
(* (+ (* -2 e) f) a)
(* (+ (* -1 e) f) a)
(* -2 d a (+ (* -1 c) (* -2 a)))
(* a (+ g (* 2 d a)))
(* a (+ g (* -6 (^ b -4) c a))))))))
(check-equal? ((derivative/proc sqr) 'a)
(* 'a 2))
(check-equal? ((derivative/proc sqr) 2)
4)
(check-equal? ((derivative/proc log) 1/2)
2)
(check-equal? ((derivative/proc log #:inexact? #t) (sqrt 2))
(->inexact (/ (sqrt 2))))
(check-equal?
(jacobian (+ (* 'c 'a) (* 'd (^ 'b 2)))
'(a b))
'(list c
(* 2 b d)))
(check-equal?
(rebind-all-let*
(jacobian (exp (+ (* 'c 'a) (* 'd (^ 'b 2))))
'(a b))
'_s)
'(let* ((_s0 (exp (+ (* a c) (* (^ b 2) d)))))
(list (* _s0 c)
(* 2 _s0 b d))))
(check-equal?
(rebind-all-let*
(jacobian (sin (exp (+ (* 'c 'a) (* 'd (^ 'b 2)))))
'(a b))
'_s)
'(let* ((_s0 (+ (* a c) (* (^ b 2) d)))
(_s1 (* (cos (exp _s0)) (exp _s0))))
(list (* _s1 c) (* 2 _s1 b d))))
(check-equal?
(simplify-top
(jacobian
`(let* ([a (+ 3 x)]
[b (+ 2 x a)])
(+ (* a b)
(* (log a) (log b))))
'(a b)))
'(list 0 0))
( tree - size ( jacobian ( apply * ( build - list 100 ( λ ( i ) ( + i 1 ' x ) ) ) )
'(x)))
( tree - size ( jacobian ( apply * ( build - list 100 ( λ ( i ) ( + i 1 ' x ) ) ) )
'(x))
#:log-product? #t)
|
ea96d401d6800c29d179da3065c7e96e45095a118c9550212dc37466eb229ae6 | velveteer/crossed | logging.clj | (ns app.logging)
(defmacro log [& args]
`(.log js/console ~@args)) | null | https://raw.githubusercontent.com/velveteer/crossed/ebcd4260060bfb46ba1da4f722799239ad61d30c/src/app/logging.clj | clojure | (ns app.logging)
(defmacro log [& args]
`(.log js/console ~@args)) | |
60ca87a7d0fc1b6e35d0ddc3af21973627c16f4ed98aebd59db69ba9db49a921 | jumarko/clojure-experiments | files.clj | (ns clojure-experiments.files
"Various File IO examples.
See also `clojure-experiments.java.nio`.
See
-
- -to-get-list-of-classpath-resources-in-nested-jar"
(:require [clojure.java.io :as io]))
;;; List directory files, especially those packaged inside an uberjar
(defmulti list-files (fn [dir] (some-> dir (io/resource) .getProtocol)))
(defmethod list-files "file" [dir]
(-> dir io/resource io/file file-seq))
(defn list-files-in-jar-path
[filter-fn dir-path-in-jar]
(let [jar-path (subs dir-path-in-jar 5 (.indexOf dir-path-in-jar "!"))
jar-file (java.util.jar.JarFile. jar-path)]
finally some Clojure !
(->> jar-file
.entries
enumeration-seq
(filter filter-fn)
we call - > this is inconsistent with ` list - files " file " ` implementation
;; which returns java.io.File instances
(map #(.getName %)))))
(defmethod list-files "jar" [dir]
(list-files-in-jar-path
(fn [entry] (and (clojure.string/starts-with? (.getName entry)
"my-test-dir")))
(-> dir (io/resource) .getPath)))
(comment
(list-files "my-test-dir" )
(list-files-in-jar-path
(fn [entry] (and (clojure.string/starts-with? (.getName entry)
"my-test-dir")))
"file:/Users/jumar/workspace/clojure/leiningen/test-app/target/uberjar/test-app-0.1.0-SNAPSHOT-standalone.jar!/my-dir")
;; end
)
;;; Walking file tree - e.g. filtering git directories
(defn discover-no-subdirs [path]
(let [git-repos (atom [])]
(java.nio.file.Files/walkFileTree (java.nio.file.Paths/get path (make-array String 0))
(proxy [java.nio.file.SimpleFileVisitor] []
(preVisitDirectory [dir attrs]
(if (-> (.resolve dir ".git") .toFile .exists)
(do
(swap! git-repos conj (str dir))
java.nio.file.FileVisitResult/SKIP_SUBTREE)
java.nio.file.FileVisitResult/CONTINUE))))
@git-repos))
(comment
(def gits (time (discover-no-subdirs "/Users/jumar/workspace/java")))
"Elapsed time: 3780.919339 msecs")
| null | https://raw.githubusercontent.com/jumarko/clojure-experiments/7d7d48f7081484307d8a7c5178d6a90ad94077f5/src/clojure_experiments/files.clj | clojure | List directory files, especially those packaged inside an uberjar
which returns java.io.File instances
end
Walking file tree - e.g. filtering git directories | (ns clojure-experiments.files
"Various File IO examples.
See also `clojure-experiments.java.nio`.
See
-
- -to-get-list-of-classpath-resources-in-nested-jar"
(:require [clojure.java.io :as io]))
(defmulti list-files (fn [dir] (some-> dir (io/resource) .getProtocol)))
(defmethod list-files "file" [dir]
(-> dir io/resource io/file file-seq))
(defn list-files-in-jar-path
[filter-fn dir-path-in-jar]
(let [jar-path (subs dir-path-in-jar 5 (.indexOf dir-path-in-jar "!"))
jar-file (java.util.jar.JarFile. jar-path)]
finally some Clojure !
(->> jar-file
.entries
enumeration-seq
(filter filter-fn)
we call - > this is inconsistent with ` list - files " file " ` implementation
(map #(.getName %)))))
(defmethod list-files "jar" [dir]
(list-files-in-jar-path
(fn [entry] (and (clojure.string/starts-with? (.getName entry)
"my-test-dir")))
(-> dir (io/resource) .getPath)))
(comment
(list-files "my-test-dir" )
(list-files-in-jar-path
(fn [entry] (and (clojure.string/starts-with? (.getName entry)
"my-test-dir")))
"file:/Users/jumar/workspace/clojure/leiningen/test-app/target/uberjar/test-app-0.1.0-SNAPSHOT-standalone.jar!/my-dir")
)
(defn discover-no-subdirs [path]
(let [git-repos (atom [])]
(java.nio.file.Files/walkFileTree (java.nio.file.Paths/get path (make-array String 0))
(proxy [java.nio.file.SimpleFileVisitor] []
(preVisitDirectory [dir attrs]
(if (-> (.resolve dir ".git") .toFile .exists)
(do
(swap! git-repos conj (str dir))
java.nio.file.FileVisitResult/SKIP_SUBTREE)
java.nio.file.FileVisitResult/CONTINUE))))
@git-repos))
(comment
(def gits (time (discover-no-subdirs "/Users/jumar/workspace/java")))
"Elapsed time: 3780.919339 msecs")
|
a4f61170b801be8c553524b3184947f2f0f99b36d244bb7238d748dfffa53821 | tshatrov/webgunk | tests.lisp | (in-package :webgunk/test)
(define-test strip-whitespace-test
(assert-equal "aaa" (strip-whitespace " aaa "))
(assert-equal "aa
a" (strip-whitespace "aa
a"))
(assert-equal "a a a" (strip-whitespace "a a
a "))
)
(define-test http-request-test
(let* ((url "/")
(document (parse-request url '(:q "common lisp")))
(links (css:query "div.links_main a.large" document))
(attrs (get-attributes (car links))))
(assert-true links)
(assert-equal "large" (cdr (assoc "class" attrs :test #'equal)))
(assert-equal "Common Lisp" (node-text (car (css:query "#zero_click_heading" document))))
))
(define-test url-params-test
(assert-equal '(nil "" "")
(multiple-value-list (url-params "")))
(assert-equal '((("q" . "common lisp") ("hl" . "en"))
"/images"
"q=common+lisp&hl=en")
(multiple-value-list (url-params "/images?q=common+lisp&hl=en")))
(assert-equal '((("q" . "common lisp") ("hl" . "hl"))
nil
"q=common+lisp&hl")
(multiple-value-list (url-params "q=common+lisp&hl" :only-params t)))
)
| null | https://raw.githubusercontent.com/tshatrov/webgunk/0260c08e300ab76ed1f64c55ddf3c47d83830461/tests.lisp | lisp | (in-package :webgunk/test)
(define-test strip-whitespace-test
(assert-equal "aaa" (strip-whitespace " aaa "))
(assert-equal "aa
a" (strip-whitespace "aa
a"))
(assert-equal "a a a" (strip-whitespace "a a
a "))
)
(define-test http-request-test
(let* ((url "/")
(document (parse-request url '(:q "common lisp")))
(links (css:query "div.links_main a.large" document))
(attrs (get-attributes (car links))))
(assert-true links)
(assert-equal "large" (cdr (assoc "class" attrs :test #'equal)))
(assert-equal "Common Lisp" (node-text (car (css:query "#zero_click_heading" document))))
))
(define-test url-params-test
(assert-equal '(nil "" "")
(multiple-value-list (url-params "")))
(assert-equal '((("q" . "common lisp") ("hl" . "en"))
"/images"
"q=common+lisp&hl=en")
(multiple-value-list (url-params "/images?q=common+lisp&hl=en")))
(assert-equal '((("q" . "common lisp") ("hl" . "hl"))
nil
"q=common+lisp&hl")
(multiple-value-list (url-params "q=common+lisp&hl" :only-params t)))
)
| |
2d0499a6d5a2c026cf7d75ef76cc536c950c2c065a8086af9deff9791b2a4af1 | kongeor/evolduo-app | playground.clj | (ns evolduo-app.views.playground
(:require [evolduo-app.views.common :refer [base-view]]
[evolduo-app.views.components :as comps]
[clojure.string :as str]))
(defn- safe-parse-int [s]
(when s
(try (Integer/parseInt (str/trim s))
(catch NumberFormatException e))))
(comment
(safe-parse-int "a 2"))
(defn playground [req & {:keys [abc title] :as track}]
(let [{:keys [key mode progression chord tempo notes instrument accompaniment]} (-> req :params)
instrument (safe-parse-int instrument)
TODO sanitized params
(base-view
req
[:div
[:h3.title.is-3 "Playground"]
[:p.mb-4 "Playground allows you to try different combinations of keys, modes, progressions and chord types
without the result being persisted and evolved."]
[:form {:id "playground-form" :action "/playground" :method "GET"}
[:div.columns
[:div.column
[:label.label {:for "key"} "Key"]
[:div.field.mr-4
[:div.control
[:div.select
(comps/keys-select key)]]]
[:label.label {:for "mode"} "Mode"]
[:div.field.mr-4
[:div.control
[:div.select
(comps/mode-select mode)]]]]
[:div.column
[:label.label {:for "progression"} "Progression"]
[:div.field.mr-4
[:div.control
[:div.select
(comps/progression-select progression)]]]
[:label.label {:for "tempo"} "Tempo"]
[:div.field.mr-2
[:div.control
[:input.input {:type "number" :name "tempo" :value tempo :min "40" :max "240"}]]]]
[:div.column
[:label.label {:for "instrument"} "Instrument"]
[:div.field.mr-4
[:div.control
[:div.select
(comps/instrument-select instrument)]]]
[:label.label {:for "accompaniment"} "Accompaniment"]
[:div.field.mr-4
[:div.control
[:div.select
(comps/accompaniment-pattern-select accompaniment)]]]]
[:div.column
[:label.label {:for "chord"} "Chord"]
[:div.field.mr-4
[:div.control
[:div.select
(comps/chord-select chord)]]]
[:label.label {:for "notes"} "Notes"]
[:div.field.mr-4
[:div.control
[:div.select
(comps/note-type-select notes)]]]]]
[:div.control.mb-4
[:input.button.is-link {:type "submit" :value "Try"}]]
]
(when (some? abc)
[:div
(comps/abc-track {:chromosome_id 1 :abc abc}
:hide-reaction? true :instrument instrument :accompaniment accompaniment)])
]
:enable-abc? (some? abc)
: custom - script ( str " var abc = \ " " abc " \ " ; " )
TODO fix
:title title
))) | null | https://raw.githubusercontent.com/kongeor/evolduo-app/e97e389e3ce7edf06a4e6fc0ad4de8a273ef229f/src/evolduo_app/views/playground.clj | clojure | (ns evolduo-app.views.playground
(:require [evolduo-app.views.common :refer [base-view]]
[evolduo-app.views.components :as comps]
[clojure.string :as str]))
(defn- safe-parse-int [s]
(when s
(try (Integer/parseInt (str/trim s))
(catch NumberFormatException e))))
(comment
(safe-parse-int "a 2"))
(defn playground [req & {:keys [abc title] :as track}]
(let [{:keys [key mode progression chord tempo notes instrument accompaniment]} (-> req :params)
instrument (safe-parse-int instrument)
TODO sanitized params
(base-view
req
[:div
[:h3.title.is-3 "Playground"]
[:p.mb-4 "Playground allows you to try different combinations of keys, modes, progressions and chord types
without the result being persisted and evolved."]
[:form {:id "playground-form" :action "/playground" :method "GET"}
[:div.columns
[:div.column
[:label.label {:for "key"} "Key"]
[:div.field.mr-4
[:div.control
[:div.select
(comps/keys-select key)]]]
[:label.label {:for "mode"} "Mode"]
[:div.field.mr-4
[:div.control
[:div.select
(comps/mode-select mode)]]]]
[:div.column
[:label.label {:for "progression"} "Progression"]
[:div.field.mr-4
[:div.control
[:div.select
(comps/progression-select progression)]]]
[:label.label {:for "tempo"} "Tempo"]
[:div.field.mr-2
[:div.control
[:input.input {:type "number" :name "tempo" :value tempo :min "40" :max "240"}]]]]
[:div.column
[:label.label {:for "instrument"} "Instrument"]
[:div.field.mr-4
[:div.control
[:div.select
(comps/instrument-select instrument)]]]
[:label.label {:for "accompaniment"} "Accompaniment"]
[:div.field.mr-4
[:div.control
[:div.select
(comps/accompaniment-pattern-select accompaniment)]]]]
[:div.column
[:label.label {:for "chord"} "Chord"]
[:div.field.mr-4
[:div.control
[:div.select
(comps/chord-select chord)]]]
[:label.label {:for "notes"} "Notes"]
[:div.field.mr-4
[:div.control
[:div.select
(comps/note-type-select notes)]]]]]
[:div.control.mb-4
[:input.button.is-link {:type "submit" :value "Try"}]]
]
(when (some? abc)
[:div
(comps/abc-track {:chromosome_id 1 :abc abc}
:hide-reaction? true :instrument instrument :accompaniment accompaniment)])
]
:enable-abc? (some? abc)
: custom - script ( str " var abc = \ " " abc " \ " ; " )
TODO fix
:title title
))) | |
4d94efac8b2b892f300791e98768649ddcf8f9919004ca02d3e6d9d398abb021 | mikera/vectorz-clj | test_matrix.clj | (ns mikera.vectorz.test-matrix
(:use [clojure test])
(:require [mikera.vectorz.core :as v])
(:require [mikera.vectorz.matrix :as m])
(:import [mikera.matrixx AMatrix Matrixx Matrix])
(:import [mikera.vectorz AVector Vectorz Vector]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(deftest test-constructors
(testing "identity"
(is (= (m/matrix [[1 0] [0 1]]) (m/identity-matrix 2)))
(is (= (m/identity-matrix 3) (m/scale-matrix [1 1 1]))))
(testing "scale matrix"
(is (= (m/matrix [[1 0] [0 1]]) (m/scale-matrix 2 1))))
(testing "diagonal matrix"
(is (= (m/matrix [[2 0] [0 3]]) (m/diagonal-matrix [2 3]))))
(testing "rotation matrix"
(is (v/approx= (v/of 1 2 3)
(m/* (m/x-axis-rotation-matrix (* 2 Math/PI))
(v/of 1 2 3))))))
(deftest test-compose
(testing "composing scales"
(is (= (m/scale-matrix [3 6]) (m/* (m/scale-matrix [1 2]) (m/scale-matrix 2 3))))))
(deftest test-ops
(testing "as-vector"
(is (= (v/of 1 0 0 1) (m/as-vector (m/identity-matrix 2))))
(is (= (v/of 1 0) (m/get-row (m/identity-matrix 2) 0)))))
(deftest test-get-set
(testing "setting"
(let [m (m/clone (m/identity-matrix 2))]
(is (= 1.0 (m/get m 0 0)))
(m/set m 0 0 2.0)
(is (= 2.0 (m/get m 0 0))))))
(deftest test-arithmetic
(testing "identity"
(let [a (v/of 2 3)
m (m/identity-matrix 2)
r (m/* m a)]
(is (= a r)))))
(deftest test-predicates
(testing "fully mutable"
(is (m/fully-mutable? (m/new-matrix 3 3)))
)
(testing "square"
(is (m/square? (m/new-matrix 3 3)))
(is (m/square? (m/identity-matrix 10)))
(is (not (m/square? (m/new-matrix 4 3))))
)
(testing "identity"
(is (m/identity? (m/identity-matrix 3)))
(is (not (m/identity? (m/new-matrix 2 2 ))))
(is (m/identity? (m/scale-matrix [1 1 1])))
(is (not (m/identity? (m/scale-matrix [1 2 3]))))
)
(testing "zero"
(is (m/zero? (m/new-matrix 2 3)))
(is (m/zero? (m/scale-matrix [0 0 0 0 0])))
)
(testing "affine"
(is (m/affine-transform? (m/new-matrix 2 3)))))
(deftest test-dimensions
(testing "inputs"
(is (= 3 (m/input-dimensions (m/new-matrix 2 3)))))
(testing "outputs"
(is (= 2 (m/output-dimensions (m/new-matrix 2 3)))))
) | null | https://raw.githubusercontent.com/mikera/vectorz-clj/cf98ff89c7f1d26b98eb9bc18b1b0a3e53176dca/src/test/clojure/mikera/vectorz/test_matrix.clj | clojure | (ns mikera.vectorz.test-matrix
(:use [clojure test])
(:require [mikera.vectorz.core :as v])
(:require [mikera.vectorz.matrix :as m])
(:import [mikera.matrixx AMatrix Matrixx Matrix])
(:import [mikera.vectorz AVector Vectorz Vector]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(deftest test-constructors
(testing "identity"
(is (= (m/matrix [[1 0] [0 1]]) (m/identity-matrix 2)))
(is (= (m/identity-matrix 3) (m/scale-matrix [1 1 1]))))
(testing "scale matrix"
(is (= (m/matrix [[1 0] [0 1]]) (m/scale-matrix 2 1))))
(testing "diagonal matrix"
(is (= (m/matrix [[2 0] [0 3]]) (m/diagonal-matrix [2 3]))))
(testing "rotation matrix"
(is (v/approx= (v/of 1 2 3)
(m/* (m/x-axis-rotation-matrix (* 2 Math/PI))
(v/of 1 2 3))))))
(deftest test-compose
(testing "composing scales"
(is (= (m/scale-matrix [3 6]) (m/* (m/scale-matrix [1 2]) (m/scale-matrix 2 3))))))
(deftest test-ops
(testing "as-vector"
(is (= (v/of 1 0 0 1) (m/as-vector (m/identity-matrix 2))))
(is (= (v/of 1 0) (m/get-row (m/identity-matrix 2) 0)))))
(deftest test-get-set
(testing "setting"
(let [m (m/clone (m/identity-matrix 2))]
(is (= 1.0 (m/get m 0 0)))
(m/set m 0 0 2.0)
(is (= 2.0 (m/get m 0 0))))))
(deftest test-arithmetic
(testing "identity"
(let [a (v/of 2 3)
m (m/identity-matrix 2)
r (m/* m a)]
(is (= a r)))))
(deftest test-predicates
(testing "fully mutable"
(is (m/fully-mutable? (m/new-matrix 3 3)))
)
(testing "square"
(is (m/square? (m/new-matrix 3 3)))
(is (m/square? (m/identity-matrix 10)))
(is (not (m/square? (m/new-matrix 4 3))))
)
(testing "identity"
(is (m/identity? (m/identity-matrix 3)))
(is (not (m/identity? (m/new-matrix 2 2 ))))
(is (m/identity? (m/scale-matrix [1 1 1])))
(is (not (m/identity? (m/scale-matrix [1 2 3]))))
)
(testing "zero"
(is (m/zero? (m/new-matrix 2 3)))
(is (m/zero? (m/scale-matrix [0 0 0 0 0])))
)
(testing "affine"
(is (m/affine-transform? (m/new-matrix 2 3)))))
(deftest test-dimensions
(testing "inputs"
(is (= 3 (m/input-dimensions (m/new-matrix 2 3)))))
(testing "outputs"
(is (= 2 (m/output-dimensions (m/new-matrix 2 3)))))
) | |
52c1db59968a13ed314e234a0077d844eb0b4e72bf64ec6f4bab28b9adc5ac6f | IFCA/opencl | example03.hs | Copyright ( c ) 2011 ,
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 the names of other
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 .
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 the names of other
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
import Control.Parallel.OpenCL
import Foreign( castPtr, nullPtr, sizeOf )
import Foreign.C.Types( CFloat )
import Foreign.Marshal.Array( newArray, peekArray )
programSource1 :: String
programSource1 = "__kernel void duparray(__global float *in, __global float *out ){\n int id = get_global_id(0);\n out[id] = 2*in[id];\n}"
programSource2 :: String
programSource2 = "__kernel void triparray(__global float *in, __global float *out ){\n int id = get_global_id(0);\n out[id] = 3*in[id];\n}"
main :: IO ()
main = do
Initialize OpenCL
(platform:_) <- clGetPlatformIDs
(dev:_) <- clGetDeviceIDs platform CL_DEVICE_TYPE_ALL
context <- clCreateContext [] [dev] print
q <- clCreateCommandQueue context dev []
-- Initialize Kernels
program1 <- clCreateProgramWithSource context programSource1
clBuildProgram program1 [dev] ""
kernel1 <- clCreateKernel program1 "duparray"
kernel3 <- clCreateKernel program1 "duparray"
program2 <- clCreateProgramWithSource context programSource2
clBuildProgram program2 [dev] ""
kernel2 <- clCreateKernel program2 "triparray"
Initialize parameters
let original = [0 .. 10] :: [CFloat]
elemSize = sizeOf (0 :: CFloat)
vecSize = elemSize * length original
putStrLn $ "Original array = " ++ show original
input <- newArray original
mem_in <- clCreateBuffer context [CL_MEM_READ_ONLY, CL_MEM_COPY_HOST_PTR] (vecSize, castPtr input)
mem_mid <- clCreateBuffer context [CL_MEM_READ_WRITE] (vecSize, nullPtr)
mem_out1 <- clCreateBuffer context [CL_MEM_WRITE_ONLY] (vecSize, nullPtr)
mem_out2 <- clCreateBuffer context [CL_MEM_WRITE_ONLY] (vecSize, nullPtr)
clSetKernelArgSto kernel1 0 mem_in
clSetKernelArgSto kernel1 1 mem_mid
clSetKernelArgSto kernel2 0 mem_mid
clSetKernelArgSto kernel2 1 mem_out1
clSetKernelArgSto kernel3 0 mem_mid
clSetKernelArgSto kernel3 1 mem_out2
-- Execute Kernels
eventExec1 <- clEnqueueNDRangeKernel q kernel1 [length original] [] []
eventExec2 <- clEnqueueNDRangeKernel q kernel2 [length original] [] [eventExec1]
eventExec3 <- clEnqueueNDRangeKernel q kernel3 [length original] [] [eventExec1]
-- Get Result
eventRead <- clEnqueueReadBuffer q mem_out1 True 0 vecSize (castPtr input) [eventExec2,eventExec3]
result <- peekArray (length original) input
putStrLn $ "Result array 1 = " ++ show result
eventRead <- clEnqueueReadBuffer q mem_out2 True 0 vecSize (castPtr input) [eventExec2,eventExec3]
result <- peekArray (length original) input
putStrLn $ "Result array 2 = " ++ show result
return ()
| null | https://raw.githubusercontent.com/IFCA/opencl/80d0cb9d235819cd53e6a36d7a9258bc19d564ab/examples/example03.hs | haskell | Initialize Kernels
Execute Kernels
Get Result | Copyright ( c ) 2011 ,
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 the names of other
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 .
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 the names of other
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
import Control.Parallel.OpenCL
import Foreign( castPtr, nullPtr, sizeOf )
import Foreign.C.Types( CFloat )
import Foreign.Marshal.Array( newArray, peekArray )
programSource1 :: String
programSource1 = "__kernel void duparray(__global float *in, __global float *out ){\n int id = get_global_id(0);\n out[id] = 2*in[id];\n}"
programSource2 :: String
programSource2 = "__kernel void triparray(__global float *in, __global float *out ){\n int id = get_global_id(0);\n out[id] = 3*in[id];\n}"
main :: IO ()
main = do
Initialize OpenCL
(platform:_) <- clGetPlatformIDs
(dev:_) <- clGetDeviceIDs platform CL_DEVICE_TYPE_ALL
context <- clCreateContext [] [dev] print
q <- clCreateCommandQueue context dev []
program1 <- clCreateProgramWithSource context programSource1
clBuildProgram program1 [dev] ""
kernel1 <- clCreateKernel program1 "duparray"
kernel3 <- clCreateKernel program1 "duparray"
program2 <- clCreateProgramWithSource context programSource2
clBuildProgram program2 [dev] ""
kernel2 <- clCreateKernel program2 "triparray"
Initialize parameters
let original = [0 .. 10] :: [CFloat]
elemSize = sizeOf (0 :: CFloat)
vecSize = elemSize * length original
putStrLn $ "Original array = " ++ show original
input <- newArray original
mem_in <- clCreateBuffer context [CL_MEM_READ_ONLY, CL_MEM_COPY_HOST_PTR] (vecSize, castPtr input)
mem_mid <- clCreateBuffer context [CL_MEM_READ_WRITE] (vecSize, nullPtr)
mem_out1 <- clCreateBuffer context [CL_MEM_WRITE_ONLY] (vecSize, nullPtr)
mem_out2 <- clCreateBuffer context [CL_MEM_WRITE_ONLY] (vecSize, nullPtr)
clSetKernelArgSto kernel1 0 mem_in
clSetKernelArgSto kernel1 1 mem_mid
clSetKernelArgSto kernel2 0 mem_mid
clSetKernelArgSto kernel2 1 mem_out1
clSetKernelArgSto kernel3 0 mem_mid
clSetKernelArgSto kernel3 1 mem_out2
eventExec1 <- clEnqueueNDRangeKernel q kernel1 [length original] [] []
eventExec2 <- clEnqueueNDRangeKernel q kernel2 [length original] [] [eventExec1]
eventExec3 <- clEnqueueNDRangeKernel q kernel3 [length original] [] [eventExec1]
eventRead <- clEnqueueReadBuffer q mem_out1 True 0 vecSize (castPtr input) [eventExec2,eventExec3]
result <- peekArray (length original) input
putStrLn $ "Result array 1 = " ++ show result
eventRead <- clEnqueueReadBuffer q mem_out2 True 0 vecSize (castPtr input) [eventExec2,eventExec3]
result <- peekArray (length original) input
putStrLn $ "Result array 2 = " ++ show result
return ()
|
17fb6855d18623cc6cbeaa76a2a1bee8c0527c57bddc6f36345a5ae354ce763b | xanxys/hs2bf | GMachine.hs | -- | GMachine
reference : Implementing Functional Languages : a tutorial
--
GC is executed every 256 allocation .
module GMachine where
import Control.Arrow
import Control.Monad
import Control.Monad.State
import Control.Monad.Identity
import Data.Ord
import Data.Char
import Data.List
import Data.Maybe
import qualified Data.Map as M
import qualified Data.Set as S
import Util as U hiding(Pack)
import qualified Util as U
import SRuntime
import SAM
data GFCompileFlag=GFCompileFlag
{addrSpace :: Int -- ^ bytes
}
-- | Compile 'GMCode's to SAM
--
See my blog ( japanese ) for overview of operational model .
--
Heap frame of size k with n - byte address :
--
* 1 B : size of this frame
--
* 1 B : GC tag
--
-- * k B: payload
--
-- * n B: id of this frame
--
* 1 B : size of this frame
--
Heap frame of size k with n - byte address :
--
Is it a good idea to remove GC tag , and attach it only when GC is running ?
( PRO : normally faster , CON : slower )
--
--
Heap payload :
--
-- You can return from anywhere on stack to origin, but not from heap.
compile :: M.Map String [GMCode] -> Process SAM
compile m
|codeSpace>1 = error "GM->SAM: 255+ super combinator is not supported"
|heapSpace>1 = error "GM->SAM: 2+ byte addresses are not supported"
|M.notMember "main" m = error "GM->SAM: entry point not found"
|otherwise = return $ SAM (ss++hs) (library++dispatcher++procs)
where
t=M.fromList $ ("main",2):zip (filter (/="main") $ M.keys m) [3..]
-- code generation
library=genLibrary $ S.toList $ S.unions $ map (S.unions . map collectConArity) $ M.elems m
procs=map (uncurry $ compileProc t) $ M.assocs m
dispatcher=[exec $ M.assocs t]
-- layout configuration
codeSpace=ceiling $ log (fromIntegral $ M.size m+2)/log 256
heapSpace=1
ss=map (("S"++) . show) [0..heapSpace-1]
hs=["Hp","Hs"]
collectConArity :: GMCode -> S.Set Int
collectConArity (Pack _ n)=S.singleton n
collectConArity (Case cs)=S.unions $ map (S.unions . map collectConArity . snd) cs
collectConArity _=S.empty
simplify :: M.Map String [GMCode] -> Process (M.Map String [GMCode])
simplify=return . M.map elimBase . elimReduce . removeLoneSC
removeLoneSC :: M.Map String [GMCode] -> M.Map String [GMCode]
removeLoneSC m=M.filterWithKey (\k _->S.member k col) m
where col=rlscAux m S.empty (S.singleton "main")
rlscAux :: M.Map String [GMCode] -> S.Set String -> S.Set String -> S.Set String
rlscAux m col front
|S.null front = col
|otherwise = rlscAux m col' (S.difference new col')
where
col'=S.union col front
new=S.unions $ map (S.unions . map collectDepSC . find) $ S.toList front
find x=M.findWithDefault (error $ "rlscAux:"++show x) x m
collectDepSC :: GMCode -> S.Set String
collectDepSC (PushSC x)=S.singleton x
collectDepSC (Case cs)=S.unions $ map (S.unions . map collectDepSC . snd) cs
collectDepSC _=S.empty
| Optmize away /base/ cases like following .
--
* Case with 1 clause
--
-- * Pop 0
--
* Slide 0 ( in fact , successive ' 's form a ' Monoid ' )
elimBase :: [GMCode] -> [GMCode]
elimBase []=[]
elimBase (Slide 0:xs)=elimBase xs
elimBase (Slide n:Slide m:xs)=elimBase $ Slide (n+m):xs
elimBase (Case cs:xs)
|length cs<=1 = elimBase $ (snd $ head cs)++xs
|otherwise = Case (map (second elimBase) cs):elimBase xs
elimBase (Pop 0:xs)=elimBase xs
elimBase (x:xs)=x:elimBase xs
-- | Separate ['GMCode'] at 'Reduce'.
elimReduce :: M.Map String [GMCode] -> M.Map String [GMCode]
elimReduce=M.fromList . concatMap f . M.assocs
where f (n,xs)=aux n [] xs
aux :: String -> [GMCode] -> [GMCode] -> [(String,[GMCode])]
aux n cs []=[(n,reverse cs)]
aux n cs (Reduce _:xs)=(n,reverse cs++[PushSC n',Swap]):aux n' [] xs
where n'=n++"_"
aux n cs (Case as:xs)
|null rs = aux n (Case as:cs) xs
|otherwise = (n,reverse $ Case as'':cs):rs
where
as'=map (\(k,x)->(k,aux (n++"_d"++show k) [] $ x++xs)) as
as''=map (second $ snd . head) as'
rs=concatMap (tail . snd) as'
aux ns cs (x:xs)=aux ns (x:cs) xs
-- | Thin wrapper of 'compileCodeBlock'
compileProc :: M.Map String Int -> String -> [GMCode] -> SProc
compileProc m name cs=SProc ("!"++name) [] $ contWith m Origin cs []
data MPos
=HeapA
|StackA
|StackT
|Origin
deriving(Show,Eq)
fPos :: GMCode -> MPos
fPos (PushByte _)=HeapA
fPos (PushSC _)=HeapA
fPos MkApp=HeapA
fPos (Pack _ _)=HeapA
fPos Swap=StackT
fPos (Push _)=StackA
fPos (Slide _)=StackT
fPos (PushArg _)=StackT
fPos (Case _)=StackT
fPos (UnPack _)=StackA
fPos (Update _)=StackT
fPos (Pop _)=StackT
fPos (GMachine.Alloc _)=fPos $ PushByte 0
fPos (Arith _)=StackT
fPos (UError _)=StackA -- any position will do, actually.
fPos x=error $ show x
-- requirement: HeapA
newFrame :: Int -> [Int] -> (Pointer -> [Stmt]) -> [Stmt]
newFrame tag xs post=
[Comment $ unwords ["nf",show tag,show xs]
,SAM.Alloc "addr"
,Inline "#heapNewHp" ["addr"]
,Clear (Memory "Hp" $ size-2)
,Move (Register "addr") [Memory "Hp" $ size-2]
,Delete "addr"
,Val (Memory "Hp" 0) size
GC tag
,Clear (Memory "Hp" 2),Val (Memory "Hp" 2) tag -- node tag
]++
concatMap set (zip [3..] xs)++
[Clear (Memory "Hp" $ size-1),Val (Memory "Hp" $ size-1) size
,Clear (Memory "Hp" size) -- next frame
]++
post (Memory "Hp" $ size-2)
where
size=5+length xs
set (ix,v)=[Clear (Memory "Hp" ix),Val (Memory "Hp" ix) v]
| Compile ' GMCode 's from given ' MPos ' to ' Stmt 's , followed by ' Origin ' returning code .
contWith :: M.Map String Int -> MPos -> [GMCode] -> [Stmt] -> [Stmt]
contWith m Origin [] ss=ss
contWith m HeapA [] ss=ss++[Inline "#heap1Hp" []]
contWith m StackA [] ss=ss++[Inline "#stack1S0" []]
contWith m StackT [] ss=ss++[Inline "#stack1S0" []]
contWith m prev xs@(x:_) ss=ss++transition prev (fPos x)++[Comment (show x)]++compileCode m xs
-- TODO: come up with good abstraction
transition :: MPos -> MPos -> [Stmt]
transition x y
|x==y = []
|x==Origin && y==StackT = [Inline "#stackTopS0" []]
|x==Origin = []
|x==StackA && y==StackT = [Inline "#stackTopS0" []]
|x==StackA && y==Origin = [Inline "#stack1S0" []]
|x==StackA && y==HeapA = [Inline "#stack1S0" []]
|x==StackT && y==StackA = []
|x==StackT && y==Origin = [Inline "#stack1S0" []]
|x==StackT && y==HeapA = [Inline "#stack1S0" []]
|x==HeapA && y==StackT = [Inline "#heap1Hp" [],Inline "#stackTopS0" []]
|x==HeapA = [Inline "#heap1Hp" []]
-- | Compile a single 'GMCode' to a procedure. StackA|HeapA -> StackA|HeapA
compileCode :: M.Map String Int -> [GMCode] -> [Stmt]
compileCode m (PushByte x:is)= -- constTag x
contWith m StackT is $ newFrame constTag [x] $ \pa->
[SAM.Alloc "addr"
,Copy pa [Register "addr"]
,Inline "#heap1Hp" []
,Inline "#stackNewS0" []
,Move (Register "addr") [Memory "S0" 0]
,Delete "addr"
]
compileCode m (PushSC k:is)= -- scTag sc
contWith m StackT is $ newFrame scTag [m M.! k] $ \pa->
[SAM.Alloc "addr"
,Copy pa [Register "addr"]
,Inline "#heap1Hp" []
,Inline "#stackNewS0" []
,Move (Register "addr") [Memory "S0" 0]
,Delete "addr"
]
compileCode m (MkApp:is)= -- appTag ap0 ap1
contWith m HeapA is $ newFrame appTag [0,0] $ \pa->
[SAM.Alloc "addr"
,Copy pa [Register "addr"]
,Inline "#heap1Hp" []
,Inline "#stackNewS0" []
,SAM.Alloc "tr1"
,Move (Memory "S0" (-1)) [Register "tr1"]
,SAM.Alloc "tr2"
,Move (Memory "S0" (-2)) [Register "tr2"]
,Copy (Register "addr") [Memory "S0" (-2)]
,Locate (-2)
,Inline "#stack1S0" []
,Inline "#heapRefHp" ["addr"]
,Delete "addr"
,Move (Register "tr1") [Memory "Hp" 3]
,Delete "tr1"
,Move (Register "tr2") [Memory "Hp" 4]
,Delete "tr2"
]
compileCode m (Pack t 0:is)=
contWith m StackT is $ newFrame structTag [t] $ \pa->
[SAM.Alloc "addr"
,Copy pa [Register "addr"]
,Inline "#heap1Hp" []
,Inline "#stackNewS0" []
,Move (Register "addr") [Memory "S0" 0]
,Delete "addr"
]
compileCode m (Pack t n:is)= -- stTag t x1...xn
contWith m HeapA is $ newFrame structTag (t:replicate n 0) $ \pa->
[SAM.Alloc "addr"
,Copy pa [Register "addr"]
,Inline "#heap1Hp" []
,Inline "#stackNewS0" []
]++
concatMap (\n->let r="tr"++show n in [SAM.Alloc r,Move (Memory "S0" $ negate n) [Register r]]) [1..n]++
[Copy (Register "addr") [Memory "S0" $ negate n]
,Locate $ negate n
,Inline "#stack1S0" []
,Inline "#heapRefHp" ["addr"]
,Delete "addr"
]++
concatMap (\n->let r="tr"++show n in [Move (Register r) [Memory "Hp" $ n+3],Delete r]) [1..n]
compileCode m (UnPack 0:is)=contWith m StackT is $
[Inline "#stackNewS0" []
,Clear (Memory "S0" (-1))
,Locate (-2)
]
compileCode m (UnPack n:is)=contWith m StackA is $ -- the last item becomes top
[Inline "#stackNewS0" []
,SAM.Alloc "saddr"
,Move (Memory "S0" (-1)) [Register "saddr"]
,Locate (-2)
,Inline "#stack1S0" []
,Inline "#heapRefHp" ["saddr"]
,Delete "saddr"
]++
map (SAM.Alloc . ("tr"++) . show) [1..n]++
map (\x->Copy (Memory "Hp" $ 3+x) [Register $ "tr"++show x]) [1..n]++
[Inline "#heap1Hp" []
,Inline "#stackNewS0" []
]++
map (\x->Move (Register $ "tr"++show x) [Memory "S0" $ x-1]) (reverse [1..n])++
map (Delete . ("tr"++) . show) [1..n]
compileCode m (Swap:is)=contWith m StackT is $
[SAM.Alloc "temp"
,Move (Memory "S0" 0) [Register "temp"]
,Move (Memory "S0" (-1)) [Memory "S0" 0]
,Move (Register "temp") [Memory "S0" (-1)]
,Delete "temp"
]
compileCode m (Push n:is)=contWith m StackT is $
[Inline "#stackNewS0" []
,Copy (Memory "S0" $ negate $ n+1) [Memory "S0" 0]
]
compileCode m (Slide n:is)=if n<=0 then error "Slide 0" else contWith m StackT is $
[Clear (Memory "S0" $ negate n)
,Move (Memory "S0" 0) [Memory "S0" $ negate n]
]++
map (Clear . Memory "S0" . negate) [1..n-1]++
[Locate $ negate n]
compileCode m (PushArg n:is)=contWith m StackT is $
[SAM.Alloc "aaddr"
,Copy (Memory "S0" $ negate n) [Register "aaddr"]
,Inline "#stack1S0" []
,Inline "#heapRefHp" ["aaddr"]
,Delete "aaddr"
,SAM.Alloc "arg"
,Copy (Memory "Hp" 4) [Register "arg"]
,Inline "#heap1Hp" []
,Inline "#stackNewS0" []
,Move (Register "arg") [Memory "S0" 0]
,Delete "arg"
]
compileCode m (Case cs:is)=contWith m Origin is $
[SAM.Alloc "saddr"
,Copy (Memory "S0" 0) [Register "saddr"]
,Inline "#stack1S0" []
,Inline "#heapRefHp" ["saddr"]
,Delete "saddr"
,SAM.Alloc "tag"
,Copy (Memory "Hp" 3) [Register "tag"]
,Dispatch "tag" $ map (second $ flip (contWith m HeapA) []) cs
,Delete "tag"
]
compileCode m (Update n:is)=contWith m HeapA is $
[SAM.Alloc "to"
,Move (Memory "S0" 0) [Register "to"]
,Locate (-1)
,SAM.Alloc "from"
,Copy (Memory "S0" $ 1-n) [Register "from"]
,Inline "#stack1S0" []
-- rewrite stack
,While (Memory "S0" 0)
[Inline "#rewriteS0" ["from","to"]
,Locate 1
]
,Locate (-1)
,Inline "#stack1S0" []
-- rewrite heap
,While (Memory "Hp" 0)
[SAM.Alloc "ntag"
,Copy (Memory "Hp" 2) [Register "ntag"]
,Dispatch "ntag"
[(appTag,
[Locate 3
,Inline "#rewriteHp" ["from","to"]
,Locate 1
,Inline "#rewriteHp" ["from","to"]
,Locate 3
])
,(scTag,
[Locate 6])
,(constTag,
[Locate 6])
,(structTag,
[SAM.Alloc "size"
,Copy (Memory "Hp" 0) [Register "size"]
,Val (Register "size") (-6)
,Locate 4
,While (Register "size")
[Inline "#rewriteHp" ["from","to"]
,Locate 1
,Val (Register "size") (-1)
]
,Delete "size"
,Locate 2
])
]
,Delete "ntag"
]
,Delete "from"
,Delete "to"
]
compileCode m (Pop n:is)=contWith m StackT is $
concat $ replicate n [Clear (Memory "S0" 0),Locate (-1)]
compileCode m (GMachine.Alloc n:is)=compileCode m $ replicate n (PushByte 0)++is
compileCode m (UError s:_)=Clear ptr:concatMap (\d->[Val ptr d,Output ptr]) ds
where
ds=head ns:zipWith (-) (tail ns) ns
ns=map ord s
ptr=Memory "S0" 0
compileCode m (Arith op:is)=contWith m StackT is $
[SAM.Alloc "x"
,SAM.Alloc "y"
,Move (Memory "S0" 0) [Register "x"]
,Move (Memory "S0" (-1)) [Register "y"]
,Locate (-2)
,Inline "#stack1S0" []
,Inline "#heapRefHp" ["x"]
,Copy (Memory "Hp" 3) [Register "x"]
,Inline "#heap1Hp" []
,Inline "#heapRefHp" ["y"]
,Delete "y"
,SAM.Alloc "temp"
,Copy (Memory "Hp" 3) [Register "temp"]
]++
f (Register "temp") (Register "x") op++
[Delete "temp"
,SAM.Alloc "addr"
,Inline "#heapNewHp" ["addr"]
,Clear (Memory "Hp" 0) ,Val (Memory "Hp" 0) 6
,Clear (Memory "Hp" 1) ,Val (Memory "Hp" 1) 0
,Clear (Memory "Hp" 2) ,Val (Memory "Hp" 2) $ tag op
,Clear (Memory "Hp" 3) ,Move (Register "x") [Memory "Hp" 3] ,Delete "x"
,Clear (Memory "Hp" 4) ,Copy (Register "addr") [Memory "Hp" 4]
,Clear (Memory "Hp" 5) ,Val (Memory "Hp" 5) 6
,Clear (Memory "Hp" 6)
,Inline "#heap1Hp" []
,Inline "#stackNewS0" []
,Move (Register "addr") [Memory "S0" 0]
,Delete "addr"
]
where
tag CCmp=structTag
tag _=constTag
f from to AAdd=[While from [Val from (-1),Val to 1]]
f from to ASub=[While from [Val from (-1),Val to (-1)]]
f from to CCmp=
[SAM.Alloc "t"
,Val (Register "t") 1
,While (Register "t")
[SAM.Alloc "s"
,Copy from [Register "s"]
,Val (Register "t") 1
,While (Register "s")
[Clear (Register "s")
,Val (Register "t") (-1)
]
,Copy to [Register "s"]
,While (Register "s")
[Clear (Register "s")
,Val (Register "t") (-1)
]
,Val (Register "s") 1
,While (Register "t")
[Clear (Register "t")
,Val (Register "s") (-1)
]
,Move (Register "s") [Register "t"]
,Delete "s"
,Val from (-1)
,Val to (-1)
]
,Val from 1
,Val to 1
,While from [Clear from,Val (Register "t") 1]
,While to [Clear to,Val (Register "t") 2]
0 : EQ 1 : from > to 2 : to < from
,Delete "t"
]
-- | G-machine intstruction
--
Note1 : ' MkApp ' ' Pack ' ordering : first pushed - > last packed
--
Note2 : ' PushArg ' counts from
data GMCode
^ pop 1st ... nth items
^ replace all reference to the nth address to 0th address .
|Pop Int -- ^ remove n items
|Push Int
|PushSC String
|Alloc Int
|Swap -- ^ used for implementing 'elimReduce'
^ reduce stack top to WHNF
-- function
|MkApp -- ^ function must be pushed after arguments. then use this.
|PushArg Int
-- data structure
|Pack Int Int
|Case [(Int,[GMCode])]
|UnPack Int
-- arithmetic
|PushByte Int
|Arith ArithOp
-- error
|UError String -- ^ output the given string with undefined consequence
deriving(Show)
data ArithOp
=AAdd
|ASub
|CCmp
deriving(Show)
data RHint
=RByte
|RE
|RAny
deriving(Show)
pprint :: M.Map String [GMCode] -> String
pprint=compileSB . Group . intersperse EmptyLine . map (uncurry pprintGMF) . M.assocs
pprintGMF :: String -> [GMCode] -> SBlock
pprintGMF name cs=Group
[Line $ U.Pack [Prim name,Prim ":"]
,Indent $ Group $ map pprintGMC cs
]
pprintGMC :: GMCode -> SBlock
pprintGMC (Case cs)=Group
[Line $ Prim "Case"
,Indent $ Group $ map (f . first show) $ sortBy (comparing fst) cs
]
where f (label,xs)=Group [Line $ Span [Prim label,Prim "->"],Indent $ Group $ map pprintGMC xs]
pprintGMC c=Line $ Prim $ show c
-- | G-machine state for use in 'interpretGM'
type GMS=State GMInternal
type GMST m a=StateT GMInternal m a
data GMInternal=GMInternal{stack::Stack,heap::Heap} deriving(Show)
data GMNode
=App Address Address
|Const Int
|Struct Int [Address]
|Combinator String
deriving(Show)
type Stack=[Address]
type Heap=M.Map Address GMNode
newtype Address=Address Int deriving(Show,Eq,Ord)
interpret :: M.Map String [GMCode] -> IO ()
interpret fs=evalStateT (evalGM False fs []) (makeEmptySt "main")
interpretR :: M.Map String [GMCode] -> IO ()
interpretR fs=evalStateT (evalGM True fs []) (makeEmptySt "main")
makeEmptySt :: String -> GMInternal
makeEmptySt entry=runIdentity $ execStateT (alloc (Combinator entry) >>= push) $ GMInternal [] M.empty
-- | Interpret a single combinator and returns new combinator to be executed.
evalGM :: Bool -> M.Map String [GMCode] -> [GMCode] -> GMST IO ()
evalGM fl fs []=do
st<-get
liftIO $ putStrLn $ "GMi: aux:\n"++showState st
node<-refStack 0 >>= refHeap
case node of
App a0 a1 -> push a0 >> evalGM fl fs []
Combinator x -> evalGM fl fs (fs M.! x)
_ -> do x<-isRootNode
if x
then case node of
Struct 0 [f] -> do
pop
x<-liftIO (liftM ord getChar)
alloc (Const x) >>= push >> push f >> evalGM fl fs [MkApp]
Struct 1 [x,k] -> do
pop
refHeap x >>= (liftIO . putChar . unConst)
push k
evalGM fl fs []
Struct 2 [] -> pop >> return ()
else when fl $ do{[e,c]<-popn 2; Combinator x<-refHeap c; push e; evalGM fl fs (fs M.! x)}
where unConst (Const x)=chr x
evalGM fl fs (Reduce _:xs)=evalGM fl fs [] >> evalGM fl fs xs
evalGM fl fs (Push n:xs)=
refStack n >>= push >> evalGM fl fs xs
evalGM fl fs (PushArg n:xs)=do
App _ arg<-refStack n >>= refHeap
push arg
evalGM fl fs xs
evalGM fl fs (MkApp:xs)=do
[s0,s1]<-popn 2
alloc (App s0 s1) >>= push
evalGM fl fs xs
evalGM fl fs (Pack t n:xs)=do
ss<-popn n
alloc (Struct t ss) >>= push
evalGM fl fs xs
evalGM fl fs (PushSC n:xs)=do
alloc (Combinator n) >>= push
evalGM fl fs xs
evalGM fl fs (Slide n:xs)=do
x<-pop
popn n
push x
evalGM fl fs xs
evalGM fl fs (PushByte x:xs)=alloc (Const x) >>= push >> evalGM fl fs xs
evalGM fl fs (Case cs:xs)=do
Struct t _<-refStack 0 >>= refHeap
maybe (error $ "GMi: Case:"++show t) (evalGM fl fs . (++xs)) $ lookup t cs
evalGM fl fs (UnPack n:xs)=do
Struct _ cs<-pop >>= refHeap
when (length cs/=n) (error $ "GMi: UnPack arity error")
mapM_ push cs
evalGM fl fs xs
evalGM fl fs (Swap:xs)=popn 2 >>= mapM_ push >> evalGM fl fs xs
evalGM fl fs (Pop n:xs)=popn n >> evalGM fl fs xs
evalGM fl fs (Update n:xs)=do
t<-pop
f<-refStack $ n-1
modify $ \(GMInternal st hp)->GMInternal (map (fS f t) st) (M.map (fH f t) hp)
evalGM fl fs xs
where
fS f t x|x==f = t
|otherwise = x
fH f t (App x y)=App (fS f t x) (fS f t y)
fH f t (Struct tag xs)=Struct tag $ map (fS f t) xs
fH _ _ x=x
evalGM fl fs (GMachine.Alloc n:xs)=evalGM fl fs $ replicate n (PushByte 0)++xs
evalGM fl fs (Arith op:xs)=do
Const x<-pop >>= refHeap
Const y<-pop >>= refHeap
case op of
AAdd -> alloc (Const $ (x+y) `mod` 256) >>= push
ASub -> alloc (Const $ (x-y) `mod` 256) >>= push
CCmp -> alloc (Struct (if x==y then 0 else if x<y then 1 else 2) []) >>= push
evalGM fl fs xs
evalGM _ _ x=error $ "evalGM: unsupported: "++show x
showState :: GMInternal -> String
showState g=unlines $
unwords (map show st):map (\(k,v)->show k++":"++show v) (M.assocs hp)
where GMInternal st hp=GMachine.gc g
-- | do not modify pointers
gc :: GMInternal -> GMInternal
gc (GMInternal st hp)=GMInternal st hp'
where
hp'=M.filterWithKey (\k _ ->S.member k ns) $ hp
ns=S.unions $ map (collect hp) st
collect heap addr=S.insert addr $
case heap M.! addr of
App a0 a1 -> S.union (collect heap a0) (collect heap a1)
Struct _ as -> S.unions $ map (collect heap) as
_ -> S.empty
refHeap :: Monad m => Address -> GMST m GMNode
refHeap addr=liftM ((M.!addr) . heap) get
refStack :: Monad m => Int -> GMST m Address
refStack n=liftM ((!!n) . stack) get
isRootNode :: Monad m => GMST m Bool
isRootNode=do
n<-liftM (length . stack) get
return $ n==1
push :: Monad m => Address -> GMST m ()
push addr=do
GMInternal st h<-get
put $ GMInternal (addr:st) h
alloc :: Monad m => GMNode -> GMST m Address
alloc n=do
GMInternal st h<-get
let addr=if M.null h then Address 0 else let Address base=fst $ M.findMax h in Address (base+1)
put $ GMInternal st $ M.insert addr n h
return addr
pop :: Monad m => GMST m Address
pop=do
GMInternal (s:ss) h<-get
put $ GMInternal ss h
return s
popn :: Monad m => Int -> GMST m [Address]
popn=flip replicateM pop
| null | https://raw.githubusercontent.com/xanxys/hs2bf/fd8ef0fd42490779a7f082bc778afdfac77a7a9c/GMachine.hs | haskell | | GMachine
^ bytes
| Compile 'GMCode's to SAM
* k B: payload
* n B: id of this frame
You can return from anywhere on stack to origin, but not from heap.
code generation
layout configuration
* Pop 0
| Separate ['GMCode'] at 'Reduce'.
| Thin wrapper of 'compileCodeBlock'
any position will do, actually.
requirement: HeapA
node tag
next frame
TODO: come up with good abstraction
| Compile a single 'GMCode' to a procedure. StackA|HeapA -> StackA|HeapA
constTag x
scTag sc
appTag ap0 ap1
stTag t x1...xn
the last item becomes top
rewrite stack
rewrite heap
| G-machine intstruction
^ remove n items
^ used for implementing 'elimReduce'
function
^ function must be pushed after arguments. then use this.
data structure
arithmetic
error
^ output the given string with undefined consequence
| G-machine state for use in 'interpretGM'
| Interpret a single combinator and returns new combinator to be executed.
| do not modify pointers | reference : Implementing Functional Languages : a tutorial
GC is executed every 256 allocation .
module GMachine where
import Control.Arrow
import Control.Monad
import Control.Monad.State
import Control.Monad.Identity
import Data.Ord
import Data.Char
import Data.List
import Data.Maybe
import qualified Data.Map as M
import qualified Data.Set as S
import Util as U hiding(Pack)
import qualified Util as U
import SRuntime
import SAM
data GFCompileFlag=GFCompileFlag
}
See my blog ( japanese ) for overview of operational model .
Heap frame of size k with n - byte address :
* 1 B : size of this frame
* 1 B : GC tag
* 1 B : size of this frame
Heap frame of size k with n - byte address :
Is it a good idea to remove GC tag , and attach it only when GC is running ?
( PRO : normally faster , CON : slower )
Heap payload :
compile :: M.Map String [GMCode] -> Process SAM
compile m
|codeSpace>1 = error "GM->SAM: 255+ super combinator is not supported"
|heapSpace>1 = error "GM->SAM: 2+ byte addresses are not supported"
|M.notMember "main" m = error "GM->SAM: entry point not found"
|otherwise = return $ SAM (ss++hs) (library++dispatcher++procs)
where
t=M.fromList $ ("main",2):zip (filter (/="main") $ M.keys m) [3..]
library=genLibrary $ S.toList $ S.unions $ map (S.unions . map collectConArity) $ M.elems m
procs=map (uncurry $ compileProc t) $ M.assocs m
dispatcher=[exec $ M.assocs t]
codeSpace=ceiling $ log (fromIntegral $ M.size m+2)/log 256
heapSpace=1
ss=map (("S"++) . show) [0..heapSpace-1]
hs=["Hp","Hs"]
collectConArity :: GMCode -> S.Set Int
collectConArity (Pack _ n)=S.singleton n
collectConArity (Case cs)=S.unions $ map (S.unions . map collectConArity . snd) cs
collectConArity _=S.empty
simplify :: M.Map String [GMCode] -> Process (M.Map String [GMCode])
simplify=return . M.map elimBase . elimReduce . removeLoneSC
removeLoneSC :: M.Map String [GMCode] -> M.Map String [GMCode]
removeLoneSC m=M.filterWithKey (\k _->S.member k col) m
where col=rlscAux m S.empty (S.singleton "main")
rlscAux :: M.Map String [GMCode] -> S.Set String -> S.Set String -> S.Set String
rlscAux m col front
|S.null front = col
|otherwise = rlscAux m col' (S.difference new col')
where
col'=S.union col front
new=S.unions $ map (S.unions . map collectDepSC . find) $ S.toList front
find x=M.findWithDefault (error $ "rlscAux:"++show x) x m
collectDepSC :: GMCode -> S.Set String
collectDepSC (PushSC x)=S.singleton x
collectDepSC (Case cs)=S.unions $ map (S.unions . map collectDepSC . snd) cs
collectDepSC _=S.empty
| Optmize away /base/ cases like following .
* Case with 1 clause
* Slide 0 ( in fact , successive ' 's form a ' Monoid ' )
elimBase :: [GMCode] -> [GMCode]
elimBase []=[]
elimBase (Slide 0:xs)=elimBase xs
elimBase (Slide n:Slide m:xs)=elimBase $ Slide (n+m):xs
elimBase (Case cs:xs)
|length cs<=1 = elimBase $ (snd $ head cs)++xs
|otherwise = Case (map (second elimBase) cs):elimBase xs
elimBase (Pop 0:xs)=elimBase xs
elimBase (x:xs)=x:elimBase xs
elimReduce :: M.Map String [GMCode] -> M.Map String [GMCode]
elimReduce=M.fromList . concatMap f . M.assocs
where f (n,xs)=aux n [] xs
aux :: String -> [GMCode] -> [GMCode] -> [(String,[GMCode])]
aux n cs []=[(n,reverse cs)]
aux n cs (Reduce _:xs)=(n,reverse cs++[PushSC n',Swap]):aux n' [] xs
where n'=n++"_"
aux n cs (Case as:xs)
|null rs = aux n (Case as:cs) xs
|otherwise = (n,reverse $ Case as'':cs):rs
where
as'=map (\(k,x)->(k,aux (n++"_d"++show k) [] $ x++xs)) as
as''=map (second $ snd . head) as'
rs=concatMap (tail . snd) as'
aux ns cs (x:xs)=aux ns (x:cs) xs
compileProc :: M.Map String Int -> String -> [GMCode] -> SProc
compileProc m name cs=SProc ("!"++name) [] $ contWith m Origin cs []
data MPos
=HeapA
|StackA
|StackT
|Origin
deriving(Show,Eq)
fPos :: GMCode -> MPos
fPos (PushByte _)=HeapA
fPos (PushSC _)=HeapA
fPos MkApp=HeapA
fPos (Pack _ _)=HeapA
fPos Swap=StackT
fPos (Push _)=StackA
fPos (Slide _)=StackT
fPos (PushArg _)=StackT
fPos (Case _)=StackT
fPos (UnPack _)=StackA
fPos (Update _)=StackT
fPos (Pop _)=StackT
fPos (GMachine.Alloc _)=fPos $ PushByte 0
fPos (Arith _)=StackT
fPos x=error $ show x
newFrame :: Int -> [Int] -> (Pointer -> [Stmt]) -> [Stmt]
newFrame tag xs post=
[Comment $ unwords ["nf",show tag,show xs]
,SAM.Alloc "addr"
,Inline "#heapNewHp" ["addr"]
,Clear (Memory "Hp" $ size-2)
,Move (Register "addr") [Memory "Hp" $ size-2]
,Delete "addr"
,Val (Memory "Hp" 0) size
GC tag
]++
concatMap set (zip [3..] xs)++
[Clear (Memory "Hp" $ size-1),Val (Memory "Hp" $ size-1) size
]++
post (Memory "Hp" $ size-2)
where
size=5+length xs
set (ix,v)=[Clear (Memory "Hp" ix),Val (Memory "Hp" ix) v]
| Compile ' GMCode 's from given ' MPos ' to ' Stmt 's , followed by ' Origin ' returning code .
contWith :: M.Map String Int -> MPos -> [GMCode] -> [Stmt] -> [Stmt]
contWith m Origin [] ss=ss
contWith m HeapA [] ss=ss++[Inline "#heap1Hp" []]
contWith m StackA [] ss=ss++[Inline "#stack1S0" []]
contWith m StackT [] ss=ss++[Inline "#stack1S0" []]
contWith m prev xs@(x:_) ss=ss++transition prev (fPos x)++[Comment (show x)]++compileCode m xs
transition :: MPos -> MPos -> [Stmt]
transition x y
|x==y = []
|x==Origin && y==StackT = [Inline "#stackTopS0" []]
|x==Origin = []
|x==StackA && y==StackT = [Inline "#stackTopS0" []]
|x==StackA && y==Origin = [Inline "#stack1S0" []]
|x==StackA && y==HeapA = [Inline "#stack1S0" []]
|x==StackT && y==StackA = []
|x==StackT && y==Origin = [Inline "#stack1S0" []]
|x==StackT && y==HeapA = [Inline "#stack1S0" []]
|x==HeapA && y==StackT = [Inline "#heap1Hp" [],Inline "#stackTopS0" []]
|x==HeapA = [Inline "#heap1Hp" []]
compileCode :: M.Map String Int -> [GMCode] -> [Stmt]
contWith m StackT is $ newFrame constTag [x] $ \pa->
[SAM.Alloc "addr"
,Copy pa [Register "addr"]
,Inline "#heap1Hp" []
,Inline "#stackNewS0" []
,Move (Register "addr") [Memory "S0" 0]
,Delete "addr"
]
contWith m StackT is $ newFrame scTag [m M.! k] $ \pa->
[SAM.Alloc "addr"
,Copy pa [Register "addr"]
,Inline "#heap1Hp" []
,Inline "#stackNewS0" []
,Move (Register "addr") [Memory "S0" 0]
,Delete "addr"
]
contWith m HeapA is $ newFrame appTag [0,0] $ \pa->
[SAM.Alloc "addr"
,Copy pa [Register "addr"]
,Inline "#heap1Hp" []
,Inline "#stackNewS0" []
,SAM.Alloc "tr1"
,Move (Memory "S0" (-1)) [Register "tr1"]
,SAM.Alloc "tr2"
,Move (Memory "S0" (-2)) [Register "tr2"]
,Copy (Register "addr") [Memory "S0" (-2)]
,Locate (-2)
,Inline "#stack1S0" []
,Inline "#heapRefHp" ["addr"]
,Delete "addr"
,Move (Register "tr1") [Memory "Hp" 3]
,Delete "tr1"
,Move (Register "tr2") [Memory "Hp" 4]
,Delete "tr2"
]
compileCode m (Pack t 0:is)=
contWith m StackT is $ newFrame structTag [t] $ \pa->
[SAM.Alloc "addr"
,Copy pa [Register "addr"]
,Inline "#heap1Hp" []
,Inline "#stackNewS0" []
,Move (Register "addr") [Memory "S0" 0]
,Delete "addr"
]
contWith m HeapA is $ newFrame structTag (t:replicate n 0) $ \pa->
[SAM.Alloc "addr"
,Copy pa [Register "addr"]
,Inline "#heap1Hp" []
,Inline "#stackNewS0" []
]++
concatMap (\n->let r="tr"++show n in [SAM.Alloc r,Move (Memory "S0" $ negate n) [Register r]]) [1..n]++
[Copy (Register "addr") [Memory "S0" $ negate n]
,Locate $ negate n
,Inline "#stack1S0" []
,Inline "#heapRefHp" ["addr"]
,Delete "addr"
]++
concatMap (\n->let r="tr"++show n in [Move (Register r) [Memory "Hp" $ n+3],Delete r]) [1..n]
compileCode m (UnPack 0:is)=contWith m StackT is $
[Inline "#stackNewS0" []
,Clear (Memory "S0" (-1))
,Locate (-2)
]
[Inline "#stackNewS0" []
,SAM.Alloc "saddr"
,Move (Memory "S0" (-1)) [Register "saddr"]
,Locate (-2)
,Inline "#stack1S0" []
,Inline "#heapRefHp" ["saddr"]
,Delete "saddr"
]++
map (SAM.Alloc . ("tr"++) . show) [1..n]++
map (\x->Copy (Memory "Hp" $ 3+x) [Register $ "tr"++show x]) [1..n]++
[Inline "#heap1Hp" []
,Inline "#stackNewS0" []
]++
map (\x->Move (Register $ "tr"++show x) [Memory "S0" $ x-1]) (reverse [1..n])++
map (Delete . ("tr"++) . show) [1..n]
compileCode m (Swap:is)=contWith m StackT is $
[SAM.Alloc "temp"
,Move (Memory "S0" 0) [Register "temp"]
,Move (Memory "S0" (-1)) [Memory "S0" 0]
,Move (Register "temp") [Memory "S0" (-1)]
,Delete "temp"
]
compileCode m (Push n:is)=contWith m StackT is $
[Inline "#stackNewS0" []
,Copy (Memory "S0" $ negate $ n+1) [Memory "S0" 0]
]
compileCode m (Slide n:is)=if n<=0 then error "Slide 0" else contWith m StackT is $
[Clear (Memory "S0" $ negate n)
,Move (Memory "S0" 0) [Memory "S0" $ negate n]
]++
map (Clear . Memory "S0" . negate) [1..n-1]++
[Locate $ negate n]
compileCode m (PushArg n:is)=contWith m StackT is $
[SAM.Alloc "aaddr"
,Copy (Memory "S0" $ negate n) [Register "aaddr"]
,Inline "#stack1S0" []
,Inline "#heapRefHp" ["aaddr"]
,Delete "aaddr"
,SAM.Alloc "arg"
,Copy (Memory "Hp" 4) [Register "arg"]
,Inline "#heap1Hp" []
,Inline "#stackNewS0" []
,Move (Register "arg") [Memory "S0" 0]
,Delete "arg"
]
compileCode m (Case cs:is)=contWith m Origin is $
[SAM.Alloc "saddr"
,Copy (Memory "S0" 0) [Register "saddr"]
,Inline "#stack1S0" []
,Inline "#heapRefHp" ["saddr"]
,Delete "saddr"
,SAM.Alloc "tag"
,Copy (Memory "Hp" 3) [Register "tag"]
,Dispatch "tag" $ map (second $ flip (contWith m HeapA) []) cs
,Delete "tag"
]
compileCode m (Update n:is)=contWith m HeapA is $
[SAM.Alloc "to"
,Move (Memory "S0" 0) [Register "to"]
,Locate (-1)
,SAM.Alloc "from"
,Copy (Memory "S0" $ 1-n) [Register "from"]
,Inline "#stack1S0" []
,While (Memory "S0" 0)
[Inline "#rewriteS0" ["from","to"]
,Locate 1
]
,Locate (-1)
,Inline "#stack1S0" []
,While (Memory "Hp" 0)
[SAM.Alloc "ntag"
,Copy (Memory "Hp" 2) [Register "ntag"]
,Dispatch "ntag"
[(appTag,
[Locate 3
,Inline "#rewriteHp" ["from","to"]
,Locate 1
,Inline "#rewriteHp" ["from","to"]
,Locate 3
])
,(scTag,
[Locate 6])
,(constTag,
[Locate 6])
,(structTag,
[SAM.Alloc "size"
,Copy (Memory "Hp" 0) [Register "size"]
,Val (Register "size") (-6)
,Locate 4
,While (Register "size")
[Inline "#rewriteHp" ["from","to"]
,Locate 1
,Val (Register "size") (-1)
]
,Delete "size"
,Locate 2
])
]
,Delete "ntag"
]
,Delete "from"
,Delete "to"
]
compileCode m (Pop n:is)=contWith m StackT is $
concat $ replicate n [Clear (Memory "S0" 0),Locate (-1)]
compileCode m (GMachine.Alloc n:is)=compileCode m $ replicate n (PushByte 0)++is
compileCode m (UError s:_)=Clear ptr:concatMap (\d->[Val ptr d,Output ptr]) ds
where
ds=head ns:zipWith (-) (tail ns) ns
ns=map ord s
ptr=Memory "S0" 0
compileCode m (Arith op:is)=contWith m StackT is $
[SAM.Alloc "x"
,SAM.Alloc "y"
,Move (Memory "S0" 0) [Register "x"]
,Move (Memory "S0" (-1)) [Register "y"]
,Locate (-2)
,Inline "#stack1S0" []
,Inline "#heapRefHp" ["x"]
,Copy (Memory "Hp" 3) [Register "x"]
,Inline "#heap1Hp" []
,Inline "#heapRefHp" ["y"]
,Delete "y"
,SAM.Alloc "temp"
,Copy (Memory "Hp" 3) [Register "temp"]
]++
f (Register "temp") (Register "x") op++
[Delete "temp"
,SAM.Alloc "addr"
,Inline "#heapNewHp" ["addr"]
,Clear (Memory "Hp" 0) ,Val (Memory "Hp" 0) 6
,Clear (Memory "Hp" 1) ,Val (Memory "Hp" 1) 0
,Clear (Memory "Hp" 2) ,Val (Memory "Hp" 2) $ tag op
,Clear (Memory "Hp" 3) ,Move (Register "x") [Memory "Hp" 3] ,Delete "x"
,Clear (Memory "Hp" 4) ,Copy (Register "addr") [Memory "Hp" 4]
,Clear (Memory "Hp" 5) ,Val (Memory "Hp" 5) 6
,Clear (Memory "Hp" 6)
,Inline "#heap1Hp" []
,Inline "#stackNewS0" []
,Move (Register "addr") [Memory "S0" 0]
,Delete "addr"
]
where
tag CCmp=structTag
tag _=constTag
f from to AAdd=[While from [Val from (-1),Val to 1]]
f from to ASub=[While from [Val from (-1),Val to (-1)]]
f from to CCmp=
[SAM.Alloc "t"
,Val (Register "t") 1
,While (Register "t")
[SAM.Alloc "s"
,Copy from [Register "s"]
,Val (Register "t") 1
,While (Register "s")
[Clear (Register "s")
,Val (Register "t") (-1)
]
,Copy to [Register "s"]
,While (Register "s")
[Clear (Register "s")
,Val (Register "t") (-1)
]
,Val (Register "s") 1
,While (Register "t")
[Clear (Register "t")
,Val (Register "s") (-1)
]
,Move (Register "s") [Register "t"]
,Delete "s"
,Val from (-1)
,Val to (-1)
]
,Val from 1
,Val to 1
,While from [Clear from,Val (Register "t") 1]
,While to [Clear to,Val (Register "t") 2]
0 : EQ 1 : from > to 2 : to < from
,Delete "t"
]
Note1 : ' MkApp ' ' Pack ' ordering : first pushed - > last packed
Note2 : ' PushArg ' counts from
data GMCode
^ pop 1st ... nth items
^ replace all reference to the nth address to 0th address .
|Push Int
|PushSC String
|Alloc Int
^ reduce stack top to WHNF
|PushArg Int
|Pack Int Int
|Case [(Int,[GMCode])]
|UnPack Int
|PushByte Int
|Arith ArithOp
deriving(Show)
data ArithOp
=AAdd
|ASub
|CCmp
deriving(Show)
data RHint
=RByte
|RE
|RAny
deriving(Show)
pprint :: M.Map String [GMCode] -> String
pprint=compileSB . Group . intersperse EmptyLine . map (uncurry pprintGMF) . M.assocs
pprintGMF :: String -> [GMCode] -> SBlock
pprintGMF name cs=Group
[Line $ U.Pack [Prim name,Prim ":"]
,Indent $ Group $ map pprintGMC cs
]
pprintGMC :: GMCode -> SBlock
pprintGMC (Case cs)=Group
[Line $ Prim "Case"
,Indent $ Group $ map (f . first show) $ sortBy (comparing fst) cs
]
where f (label,xs)=Group [Line $ Span [Prim label,Prim "->"],Indent $ Group $ map pprintGMC xs]
pprintGMC c=Line $ Prim $ show c
type GMS=State GMInternal
type GMST m a=StateT GMInternal m a
data GMInternal=GMInternal{stack::Stack,heap::Heap} deriving(Show)
data GMNode
=App Address Address
|Const Int
|Struct Int [Address]
|Combinator String
deriving(Show)
type Stack=[Address]
type Heap=M.Map Address GMNode
newtype Address=Address Int deriving(Show,Eq,Ord)
interpret :: M.Map String [GMCode] -> IO ()
interpret fs=evalStateT (evalGM False fs []) (makeEmptySt "main")
interpretR :: M.Map String [GMCode] -> IO ()
interpretR fs=evalStateT (evalGM True fs []) (makeEmptySt "main")
makeEmptySt :: String -> GMInternal
makeEmptySt entry=runIdentity $ execStateT (alloc (Combinator entry) >>= push) $ GMInternal [] M.empty
evalGM :: Bool -> M.Map String [GMCode] -> [GMCode] -> GMST IO ()
evalGM fl fs []=do
st<-get
liftIO $ putStrLn $ "GMi: aux:\n"++showState st
node<-refStack 0 >>= refHeap
case node of
App a0 a1 -> push a0 >> evalGM fl fs []
Combinator x -> evalGM fl fs (fs M.! x)
_ -> do x<-isRootNode
if x
then case node of
Struct 0 [f] -> do
pop
x<-liftIO (liftM ord getChar)
alloc (Const x) >>= push >> push f >> evalGM fl fs [MkApp]
Struct 1 [x,k] -> do
pop
refHeap x >>= (liftIO . putChar . unConst)
push k
evalGM fl fs []
Struct 2 [] -> pop >> return ()
else when fl $ do{[e,c]<-popn 2; Combinator x<-refHeap c; push e; evalGM fl fs (fs M.! x)}
where unConst (Const x)=chr x
evalGM fl fs (Reduce _:xs)=evalGM fl fs [] >> evalGM fl fs xs
evalGM fl fs (Push n:xs)=
refStack n >>= push >> evalGM fl fs xs
evalGM fl fs (PushArg n:xs)=do
App _ arg<-refStack n >>= refHeap
push arg
evalGM fl fs xs
evalGM fl fs (MkApp:xs)=do
[s0,s1]<-popn 2
alloc (App s0 s1) >>= push
evalGM fl fs xs
evalGM fl fs (Pack t n:xs)=do
ss<-popn n
alloc (Struct t ss) >>= push
evalGM fl fs xs
evalGM fl fs (PushSC n:xs)=do
alloc (Combinator n) >>= push
evalGM fl fs xs
evalGM fl fs (Slide n:xs)=do
x<-pop
popn n
push x
evalGM fl fs xs
evalGM fl fs (PushByte x:xs)=alloc (Const x) >>= push >> evalGM fl fs xs
evalGM fl fs (Case cs:xs)=do
Struct t _<-refStack 0 >>= refHeap
maybe (error $ "GMi: Case:"++show t) (evalGM fl fs . (++xs)) $ lookup t cs
evalGM fl fs (UnPack n:xs)=do
Struct _ cs<-pop >>= refHeap
when (length cs/=n) (error $ "GMi: UnPack arity error")
mapM_ push cs
evalGM fl fs xs
evalGM fl fs (Swap:xs)=popn 2 >>= mapM_ push >> evalGM fl fs xs
evalGM fl fs (Pop n:xs)=popn n >> evalGM fl fs xs
evalGM fl fs (Update n:xs)=do
t<-pop
f<-refStack $ n-1
modify $ \(GMInternal st hp)->GMInternal (map (fS f t) st) (M.map (fH f t) hp)
evalGM fl fs xs
where
fS f t x|x==f = t
|otherwise = x
fH f t (App x y)=App (fS f t x) (fS f t y)
fH f t (Struct tag xs)=Struct tag $ map (fS f t) xs
fH _ _ x=x
evalGM fl fs (GMachine.Alloc n:xs)=evalGM fl fs $ replicate n (PushByte 0)++xs
evalGM fl fs (Arith op:xs)=do
Const x<-pop >>= refHeap
Const y<-pop >>= refHeap
case op of
AAdd -> alloc (Const $ (x+y) `mod` 256) >>= push
ASub -> alloc (Const $ (x-y) `mod` 256) >>= push
CCmp -> alloc (Struct (if x==y then 0 else if x<y then 1 else 2) []) >>= push
evalGM fl fs xs
evalGM _ _ x=error $ "evalGM: unsupported: "++show x
showState :: GMInternal -> String
showState g=unlines $
unwords (map show st):map (\(k,v)->show k++":"++show v) (M.assocs hp)
where GMInternal st hp=GMachine.gc g
gc :: GMInternal -> GMInternal
gc (GMInternal st hp)=GMInternal st hp'
where
hp'=M.filterWithKey (\k _ ->S.member k ns) $ hp
ns=S.unions $ map (collect hp) st
collect heap addr=S.insert addr $
case heap M.! addr of
App a0 a1 -> S.union (collect heap a0) (collect heap a1)
Struct _ as -> S.unions $ map (collect heap) as
_ -> S.empty
refHeap :: Monad m => Address -> GMST m GMNode
refHeap addr=liftM ((M.!addr) . heap) get
refStack :: Monad m => Int -> GMST m Address
refStack n=liftM ((!!n) . stack) get
isRootNode :: Monad m => GMST m Bool
isRootNode=do
n<-liftM (length . stack) get
return $ n==1
push :: Monad m => Address -> GMST m ()
push addr=do
GMInternal st h<-get
put $ GMInternal (addr:st) h
alloc :: Monad m => GMNode -> GMST m Address
alloc n=do
GMInternal st h<-get
let addr=if M.null h then Address 0 else let Address base=fst $ M.findMax h in Address (base+1)
put $ GMInternal st $ M.insert addr n h
return addr
pop :: Monad m => GMST m Address
pop=do
GMInternal (s:ss) h<-get
put $ GMInternal ss h
return s
popn :: Monad m => Int -> GMST m [Address]
popn=flip replicateM pop
|
984c6610fd97a77912a59a841ba5e624e9375c325fa268ed1a4eea30d90d2ce1 | NorfairKing/the-notes | Macro.hs | module Cryptography.SystemAlgebra.AbstractSystems.Macro where
import Types
import Macro.Arrows
import Macro.Math
import Macro.MetaMacro
import Functions.Application.Macro
-- | Concrete set of systems
syss_ :: Note
syss_ = phiu
-- | Concrete set of labels
labs_ :: Note
labs_ = lambdau
-- | Concrete Label assignment function
laf_ :: Note
laf_ = lambda
-- | Application of concrete Label assignment function
la :: Note -> Note
la = fn laf_
-- | Concrete system merging operation
smo_ :: Note
smo_ = comm0 "bigvee"
-- | System merging operation
sm :: Note -> Note -> Note
sm = binop smo_
-- | Interface connection operation
ico :: Note -- ^ System
^ Interface 1
^ Interface 2
-> Note
ico s i1 i2 = s ^ (i1 <> "-" <> i2)
-- | System with empty interface label set
emptysys :: Note
emptysys = comm0 "blacksquare"
-- | Merging interfaces
mio :: Note -- ^ System
-> Note -- ^ Interface set
-> Note -- ^ Resulting interface
-> Note
mio s l j = s ^ (l <> rightarrow <> j)
-- | Merging interfaces inverse operation
mioi :: Note -- ^ System
-> Note -- ^ Interface set
-> Note -- ^ Resulting interface
-> Note
mioi s j l = s ^ (sqbrac $ j <> rightarrow <> l)
-- | Convert resource with converter
conv :: Note -- ^ Converter
-> Note -- ^ Converted interface
-> Note -- ^ Resource
-> Note
conv a i s = a ^ i <> s
| Convert 1 - resource with converter
conv_ :: Note -- ^ Converter
-> Note -- ^ Resource
-> Note
conv_ a s = a <> s
| null | https://raw.githubusercontent.com/NorfairKing/the-notes/ff9551b05ec3432d21dd56d43536251bf337be04/src/Cryptography/SystemAlgebra/AbstractSystems/Macro.hs | haskell | | Concrete set of systems
| Concrete set of labels
| Concrete Label assignment function
| Application of concrete Label assignment function
| Concrete system merging operation
| System merging operation
| Interface connection operation
^ System
| System with empty interface label set
| Merging interfaces
^ System
^ Interface set
^ Resulting interface
| Merging interfaces inverse operation
^ System
^ Interface set
^ Resulting interface
| Convert resource with converter
^ Converter
^ Converted interface
^ Resource
^ Converter
^ Resource | module Cryptography.SystemAlgebra.AbstractSystems.Macro where
import Types
import Macro.Arrows
import Macro.Math
import Macro.MetaMacro
import Functions.Application.Macro
syss_ :: Note
syss_ = phiu
labs_ :: Note
labs_ = lambdau
laf_ :: Note
laf_ = lambda
la :: Note -> Note
la = fn laf_
smo_ :: Note
smo_ = comm0 "bigvee"
sm :: Note -> Note -> Note
sm = binop smo_
^ Interface 1
^ Interface 2
-> Note
ico s i1 i2 = s ^ (i1 <> "-" <> i2)
emptysys :: Note
emptysys = comm0 "blacksquare"
-> Note
mio s l j = s ^ (l <> rightarrow <> j)
-> Note
mioi s j l = s ^ (sqbrac $ j <> rightarrow <> l)
-> Note
conv a i s = a ^ i <> s
| Convert 1 - resource with converter
-> Note
conv_ a s = a <> s
|
7b5d1353c21f915331a7ad50b5db3c39e33e5d767830dc8138c3dc438b842661 | glagoly/glagoly | config.erl | -module(config).
-export([metainfo/0]).
-include_lib("kvs/include/metainfo.hrl").
-include_lib("kvs/include/kvs.hrl").
-include_lib("records.hrl").
metainfo() -> #schema{name = glagoly, tables = tables()}.
tables() ->
[
#table{name = login, fields = record_info(fields, login)},
#table{name = poll, fields = record_info(fields, poll), keys = [user]},
#table{name = alt, fields = record_info(fields, alt), keys = [user]},
#table{name = vote, fields = record_info(fields, vote)},
#table{name = my_poll, fields = record_info(fields, my_poll)}
].
| null | https://raw.githubusercontent.com/glagoly/glagoly/bd3754599ebb456fbcb1ee5864d87d85d9584ad3/src/config.erl | erlang | -module(config).
-export([metainfo/0]).
-include_lib("kvs/include/metainfo.hrl").
-include_lib("kvs/include/kvs.hrl").
-include_lib("records.hrl").
metainfo() -> #schema{name = glagoly, tables = tables()}.
tables() ->
[
#table{name = login, fields = record_info(fields, login)},
#table{name = poll, fields = record_info(fields, poll), keys = [user]},
#table{name = alt, fields = record_info(fields, alt), keys = [user]},
#table{name = vote, fields = record_info(fields, vote)},
#table{name = my_poll, fields = record_info(fields, my_poll)}
].
| |
767a16b1f7558d5bfb8a56610afcc626338459c5be411aefe43c4bf92bb67146 | clojurewerkz/cassaforte | metadata.clj | Copyright ( c ) 2012 - 2014 , , and the ClojureWerkz Team
;;
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; -2.0
;;
;; Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns clojurewerkz.cassaforte.metadata
"Main namespace for getting information about cluster, keyspaces, tables, etc."
(:refer-clojure :exclude [update])
(:require [clojurewerkz.cassaforte.client :as cc])
(:import [com.datastax.driver.core Session KeyspaceMetadata Metadata TableMetadata
ColumnMetadata TableOptionsMetadata Host UserType MaterializedViewMetadata
FunctionMetadata AggregateMetadata DataType IndexMetadata ClusteringOrder
AbstractTableMetadata DataType$Name]
[java.util Collection Map]))
;;
;;
;; Auxiliary functions, maybe need to be re-implemented
(def ^:private not-nil? (comp not nil?))
(defn- non-nil-coll [conv-func coll]
(filterv not-nil? (mapv conv-func coll)))
(defn- process-into-map
[conv-func field coll]
(into {} (non-nil-coll (fn [d] (when-let [m (conv-func d)]
[(get m field) m]))
coll)))
(defn- into-keyed-map [^Map coll]
(zipmap (map keyword (.keySet coll)) (.values coll)))
;; Functions for conversion of different objects into maps
(defn- convert-data-type [^DataType dt]
(when dt
(let [type-args (.getTypeArguments dt)
nm (.getName dt)
is-udt? (= nm DataType$Name/UDT)]
(-> {
:name (if is-udt?
(str (.getKeyspace ^UserType dt) "." (.getTypeName ^UserType dt) )
(str nm))
:collection? (.isCollection dt)
:frozen? (.isFrozen dt)
:user-defined? is-udt?
}
(cond-> (seq type-args) (assoc :type-args (mapv convert-data-type type-args)))))))
(defn- convert-user-types-meta [^UserType ut-meta]
(when ut-meta
{
:name (keyword (.getTypeName ut-meta))
:frozen? (.isFrozen ut-meta)
:keyspace (keyword (.getKeyspace ut-meta))
:fields (into {}
(filter not-nil?
(mapv (fn [^String field-name]
(when-let [ut (convert-data-type (.getFieldType ut-meta field-name))]
[(keyword field-name) ut]))
(.getFieldNames ut-meta))))
:cql (.asCQLQuery ut-meta)
}))
(defn- convert-func-meta [^FunctionMetadata fn-meta]
(when fn-meta
(let [args (.getArguments fn-meta)]
{
:cql (.asCQLQuery fn-meta)
:name (.getSignature fn-meta)
:simple-name (.getSimpleName fn-meta)
:arguments (into {} (zipmap (map keyword (.keySet args))
(map convert-data-type (.values args))))
:language (.getLanguage fn-meta)
:callable-on-nil? (.isCalledOnNullInput fn-meta)
:body (.getBody fn-meta)
:return-type (convert-data-type (.getReturnType fn-meta))
})))
(defn- convert-index-meta [^IndexMetadata idx-meta]
(when idx-meta
(let [idx-class (.getIndexClassName idx-meta)]
(-> {
:custom? (.isCustomIndex idx-meta)
:name (keyword (.getName idx-meta))
:kind (keyword (.name (.getKind idx-meta)))
:target (.getTarget idx-meta)
:cql (.asCQLQuery idx-meta)}
(cond-> idx-class (assoc :index-class idx-class))))))
(defn- convert-aggr-meta [^AggregateMetadata agg-meta]
(when agg-meta
{
:name (.getSignature agg-meta)
:simple-name (.getSimpleName agg-meta)
:return-type (convert-data-type (.getReturnType agg-meta))
:arguments (filterv not-nil? (mapv convert-data-type (.getArgumentTypes agg-meta)))
:cql (.asCQLQuery agg-meta)
:state-type (convert-data-type (.getStateType agg-meta))
:state-func (.. agg-meta getStateFunc getSignature)
:final-func (.. agg-meta getFinalFunc getSignature)
:init-state (.getInitCond agg-meta)
}))
(defn- convert-column [^ColumnMetadata col-meta]
(when col-meta
{:static? (.isStatic col-meta)
:name (keyword (.getName col-meta))
:type (convert-data-type (.getType col-meta))}))
(defn- convert-table-options [^TableOptionsMetadata opts]
(when opts
(let [caching (.getCaching opts)
compaction (.getCompaction opts)
comnt (.getComment opts)
compression (.getCompression opts)
extensions (.getExtensions opts)]
(-> {
:bloom-filter-fp-chance (.getBloomFilterFalsePositiveChance opts)
:crc-check-chance (.getCrcCheckChance opts)
:default-ttl (.getDefaultTimeToLive opts)
:compact-storage? (.isCompactStorage opts)
:cdc? (.isCDC opts)
:gc-grace (.getGcGraceInSeconds opts)
:local-read-repair-chance (.getLocalReadRepairChance opts)
:read-repair-chance (.getReadRepairChance opts)
:max-index-interval (.getMaxIndexInterval opts)
:min-index-interval (.getMinIndexInterval opts)
:replicate-on-write? (.getReplicateOnWrite opts)
:speculative-retry (.getSpeculativeRetry opts)
:memtable-flush-period (.getMemtableFlushPeriodInMs opts)
:populate-io-cache-on-flush? (.getPopulateIOCacheOnFlush opts)
}
(cond-> caching (assoc :caching (into-keyed-map caching)))
(cond-> (seq comnt) (assoc :comment comnt))
(cond-> compaction (assoc :compaction (into-keyed-map compaction)))
(cond-> extensions (assoc :extensions (into-keyed-map extensions)))
(cond-> compression (assoc :compression (into-keyed-map compression)))))))
;; TODO: Decide - do we need to include primary key, partition key, clustering & regular
;; columns as separate slots? Or it's better to leave filtering to user?
(defn- convert-abstract-table-meta [^AbstractTableMetadata at-meta]
(when at-meta
(let [id (.getId at-meta)
partition-key-names (non-nil-coll (fn [^ColumnMetadata v] (keyword (.getName v)))
(.getPartitionKey at-meta))
clustering-names (non-nil-coll (fn [^ColumnMetadata v] (keyword (.getName v)))
(.getClusteringColumns at-meta))
non-regular (into {} (concat (mapv #(vector % :partition-key) partition-key-names)
(mapv #(vector % :clustering) clustering-names)))
columns (non-nil-coll convert-column (.getColumns at-meta))
columns (mapv #(assoc % :kind (get non-regular (:name %) :regular)) columns)
primary-key (filterv #(not= (:kind %) :regular) columns)
partition-key (filterv #(= (:kind %) :partition-key) columns)
clustering-columns (filterv #(= (:kind %) :clustering) columns)
clustering-order (.getClusteringOrder at-meta)
options (convert-table-options (.getOptions at-meta))
regular-columns (filterv #(= (:kind %) :regular) columns)]
(-> {
:name (keyword (.getName at-meta))
:cql (.asCQLQuery at-meta)
:columns columns
:primary-key primary-key
:partition-key partition-key
}
(cond-> (seq regular-columns) (assoc :regular-columns regular-columns))
(cond-> (seq clustering-columns)
(assoc :clustering-columns
(mapv (fn [v1 ^ClusteringOrder v2]
(assoc v1 :order (keyword (.name v2))))
clustering-columns clustering-order)))
(cond-> id (assoc :id id))
(cond-> options (assoc :options options))))))
(defn- convert-mv-meta [^MaterializedViewMetadata mv-meta]
(when mv-meta
(assoc (convert-abstract-table-meta mv-meta)
:base-table (keyword (.. mv-meta getBaseTable getName)))))
(defn- convert-table-meta [^TableMetadata table-meta]
(when table-meta
(let [indexes (process-into-map convert-index-meta :name (.getIndexes table-meta))
mvs (process-into-map convert-mv-meta :name (.getViews table-meta))]
(-> (convert-abstract-table-meta table-meta)
(cond-> (seq indexes) (assoc :indexes indexes))
(cond-> (seq mvs) (assoc :materialized-views mvs))))))
(defn- convert-keyspace-meta
"Converts KeyspaceMetadata into Clojure map"
[^KeyspaceMetadata ks-meta detailed?]
(when ks-meta
(let [replication (.getReplication ks-meta)
tbl-meta (.getTables ks-meta)
tables (if detailed?
(process-into-map convert-table-meta :name tbl-meta)
(mapv (fn [^TableMetadata v]
(keyword (.getName v))) (seq tbl-meta)))
ut-meta (.getUserTypes ks-meta)
user-types (if detailed?
(process-into-map convert-user-types-meta :name ut-meta)
(mapv (fn [^UserType v]
(keyword (.getTypeName v))) (seq ut-meta)))
fn-meta (.getFunctions ks-meta)
functions (if detailed?
(process-into-map convert-func-meta :name fn-meta)
(mapv (fn [^FunctionMetadata v]
(.getSignature v)) (seq fn-meta)))
aggr-meta (.getAggregates ks-meta)
aggregates (if detailed?
(process-into-map convert-aggr-meta :name aggr-meta)
(mapv (fn [^AggregateMetadata v]
(.getSignature v)) (seq aggr-meta)))
mvs-meta (.getMaterializedViews ks-meta)
materialized-views (if detailed?
(process-into-map convert-mv-meta :name mvs-meta)
(mapv (fn [^MaterializedViewMetadata v]
(keyword (.getName v))) (seq mvs-meta)))]
(-> {
:replication (into-keyed-map replication)
:name (keyword (.getName ks-meta))
:durable-writes (.isDurableWrites ks-meta)
}
(cond-> (seq tables) (assoc :tables tables))
(cond-> (seq user-types) (assoc :user-types user-types))
(cond-> (seq functions) (assoc :functions functions))
(cond-> (seq aggregates) (assoc :aggregates aggregates))
(cond-> (seq materialized-views) (assoc :materialized-views materialized-views))
(cond-> detailed? (assoc :cql (.asCQLQuery ks-meta)))))))
(defn- ^Metadata get-cluster-meta [^Session session]
(when session
(when-let [cluster (.getCluster session)]
(.getMetadata cluster))))
(defn- ^KeyspaceMetadata get-keyspace-meta [^Session session ks]
(when-let [cluster-meta ^Metadata (get-cluster-meta session)]
(.getKeyspace cluster-meta (name ks))))
(defn keyspace
"Describes a keyspace.
Verbosity is regulated by :detailed? parameter that is equal to false by default."
[^Session session ks & {:keys [detailed?] :or {detailed? false}}]
(convert-keyspace-meta (get-keyspace-meta session ks) detailed?))
(defn keyspaces
"Describes all available keyspaces.
Verbosity is regulated by :detailed? parameter that is equal to false by default."
[^Session session & {:keys [detailed?] :or {detailed? false}}]
(when-let [cluster-meta ^Metadata (get-cluster-meta session)]
(process-into-map #(convert-keyspace-meta % detailed?)
:name (.getKeyspaces cluster-meta))))
(defn table
"Describes a table"
[^Session session ks table]
(when-let [ks-meta (get-keyspace-meta session ks)]
(convert-table-meta (.getTable ks-meta (name table)))))
(defn tables
"Returns descriptions of all the tables"
[^Session session ks]
(when-let [ks-meta (get-keyspace-meta session ks)]
(process-into-map convert-table-meta :name (.getTables ks-meta))))
(defn index
"Describes an index"
[^Session session ks table index]
(when-let [ks-meta (get-keyspace-meta session ks)]
(when-let [tbl (.getTable ks-meta (name table))]
(convert-index-meta (.getIndex tbl (name index))))))
(defn indexes
"Returns descriptions of indices"
[^Session session ks table]
(when-let [ks-meta (get-keyspace-meta session ks)]
(when-let [tbl (.getTable ks-meta (name table))]
(process-into-map convert-index-meta :name (.getIndexes tbl)))))
(defn materialized-view
"Describes a materialized view"
[^Session session ks mv]
(when-let [ks-meta (get-keyspace-meta session ks)]
(convert-mv-meta (.getMaterializedView ks-meta (name mv)))))
(defn materialized-views
"Returns descriptions of all materialized views"
[^Session session ks]
(when-let [ks-meta (get-keyspace-meta session ks)]
(process-into-map convert-mv-meta :name (.getMaterializedViews ks-meta))))
(defn user-type
"Describes a "
[^Session session ks utype]
(when-let [ks-meta (get-keyspace-meta session ks)]
(convert-user-types-meta (.getUserType ks-meta (name utype)))))
(defn user-types
"Returns descriptions of all user types"
[^Session session ks]
(when-let [ks-meta (get-keyspace-meta session ks)]
(process-into-map convert-user-types-meta :name (.getUserTypes ks-meta))))
(defn aggregate
"Describes a "
[^Session session ks aggr ^Collection arg-types]
(when-let [ks-meta (get-keyspace-meta session ks)]
(convert-aggr-meta (.getAggregate ks-meta (name aggr) arg-types))))
(defn aggregates
"Returns descriptions of all aggregates"
[^Session session ks]
(when-let [ks-meta (get-keyspace-meta session ks)]
(process-into-map convert-aggr-meta :name (.getAggregates ks-meta))))
(defn function
"Describes a "
[^Session session ks func ^Collection arg-types]
(when-let [ks-meta (get-keyspace-meta session ks)]
(convert-func-meta (.getFunction ks-meta (name func) arg-types))))
(defn functions
"Returns descriptions of all functions"
[^Session session ks]
(when-let [ks-meta (get-keyspace-meta session ks)]
(process-into-map convert-func-meta :name (.getFunctions ks-meta))))
(defn columns
"Describes columns of a table"
[^Session session ks tbl-name]
(:columns (table session ks tbl-name)))
(defn- get-host-info [^Host host detailed?]
(when host
(-> {:rack (.getRack host)
:datacenter (.getDatacenter host)
:up? (.isUp host)
:state (.getState host)
:cassandra-version (str (.getCassandraVersion host))
;; :dse-version (str (.getDseVersion host))
: dse - workloads ( .getDseWorkloads host )
:socket-address (str (.getSocketAddress host))
:listen-address (str (.getListenAddress host))
:address (str (.getAddress host))
:broadcast-address (str (.getBroadcastAddress host))
}
(cond-> detailed? (assoc :tokens (.getTokens host))))))
(defn- get-hosts-impl [^Metadata cluster-meta detailed?]
(when-let [hosts (.getAllHosts cluster-meta)]
(non-nil-coll #(get-host-info % detailed?) hosts)))
(defn hosts
"Returns information about hosts in cluster associated with session.
Verbosity is regulated by :detailed? parameter that is equal to false by default."
[^Session session & {:keys [detailed?] :or {detailed? false}}]
(when-let [cluster-meta ^Metadata (get-cluster-meta session)]
(get-hosts-impl cluster-meta detailed?)))
(defn cluster
"Describes cluster associated with session.
Verbosity is regulated by :detailed? parameter that is equal to false by default."
[^Session session & {:keys [detailed?] :or {detailed? false}}]
(when-let [cluster-meta ^Metadata (get-cluster-meta session)]
(-> {
:name (keyword (.getClusterName cluster-meta))
:hosts (get-hosts-impl cluster-meta detailed?)
:partitioner (.getPartitioner cluster-meta)
:keyspaces (process-into-map #(convert-keyspace-meta % detailed?)
:name (.getKeyspaces cluster-meta))
:schema-agreed? (.checkSchemaAgreement cluster-meta)
}
;; TODO: do we need it?
(cond-> detailed? (assoc :schema (.exportSchemaAsString cluster-meta))))))
(defn cluster-schema
"Returns full schema for cluster associated with session."
[^Session session]
(when-let [cluster-meta ^Metadata (get-cluster-meta session)]
(.exportSchemaAsString cluster-meta)))
| null | https://raw.githubusercontent.com/clojurewerkz/cassaforte/bd0b3ff44c5d7f993798270032aa41be0e8209c2/src/clojure/clojurewerkz/cassaforte/metadata.clj | clojure |
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Auxiliary functions, maybe need to be re-implemented
Functions for conversion of different objects into maps
TODO: Decide - do we need to include primary key, partition key, clustering & regular
columns as separate slots? Or it's better to leave filtering to user?
:dse-version (str (.getDseVersion host))
TODO: do we need it? | Copyright ( c ) 2012 - 2014 , , and the ClojureWerkz Team
distributed under the License is distributed on an " AS IS " BASIS ,
(ns clojurewerkz.cassaforte.metadata
"Main namespace for getting information about cluster, keyspaces, tables, etc."
(:refer-clojure :exclude [update])
(:require [clojurewerkz.cassaforte.client :as cc])
(:import [com.datastax.driver.core Session KeyspaceMetadata Metadata TableMetadata
ColumnMetadata TableOptionsMetadata Host UserType MaterializedViewMetadata
FunctionMetadata AggregateMetadata DataType IndexMetadata ClusteringOrder
AbstractTableMetadata DataType$Name]
[java.util Collection Map]))
(def ^:private not-nil? (comp not nil?))
(defn- non-nil-coll [conv-func coll]
(filterv not-nil? (mapv conv-func coll)))
(defn- process-into-map
[conv-func field coll]
(into {} (non-nil-coll (fn [d] (when-let [m (conv-func d)]
[(get m field) m]))
coll)))
(defn- into-keyed-map [^Map coll]
(zipmap (map keyword (.keySet coll)) (.values coll)))
(defn- convert-data-type [^DataType dt]
(when dt
(let [type-args (.getTypeArguments dt)
nm (.getName dt)
is-udt? (= nm DataType$Name/UDT)]
(-> {
:name (if is-udt?
(str (.getKeyspace ^UserType dt) "." (.getTypeName ^UserType dt) )
(str nm))
:collection? (.isCollection dt)
:frozen? (.isFrozen dt)
:user-defined? is-udt?
}
(cond-> (seq type-args) (assoc :type-args (mapv convert-data-type type-args)))))))
(defn- convert-user-types-meta [^UserType ut-meta]
(when ut-meta
{
:name (keyword (.getTypeName ut-meta))
:frozen? (.isFrozen ut-meta)
:keyspace (keyword (.getKeyspace ut-meta))
:fields (into {}
(filter not-nil?
(mapv (fn [^String field-name]
(when-let [ut (convert-data-type (.getFieldType ut-meta field-name))]
[(keyword field-name) ut]))
(.getFieldNames ut-meta))))
:cql (.asCQLQuery ut-meta)
}))
(defn- convert-func-meta [^FunctionMetadata fn-meta]
(when fn-meta
(let [args (.getArguments fn-meta)]
{
:cql (.asCQLQuery fn-meta)
:name (.getSignature fn-meta)
:simple-name (.getSimpleName fn-meta)
:arguments (into {} (zipmap (map keyword (.keySet args))
(map convert-data-type (.values args))))
:language (.getLanguage fn-meta)
:callable-on-nil? (.isCalledOnNullInput fn-meta)
:body (.getBody fn-meta)
:return-type (convert-data-type (.getReturnType fn-meta))
})))
(defn- convert-index-meta [^IndexMetadata idx-meta]
(when idx-meta
(let [idx-class (.getIndexClassName idx-meta)]
(-> {
:custom? (.isCustomIndex idx-meta)
:name (keyword (.getName idx-meta))
:kind (keyword (.name (.getKind idx-meta)))
:target (.getTarget idx-meta)
:cql (.asCQLQuery idx-meta)}
(cond-> idx-class (assoc :index-class idx-class))))))
(defn- convert-aggr-meta [^AggregateMetadata agg-meta]
(when agg-meta
{
:name (.getSignature agg-meta)
:simple-name (.getSimpleName agg-meta)
:return-type (convert-data-type (.getReturnType agg-meta))
:arguments (filterv not-nil? (mapv convert-data-type (.getArgumentTypes agg-meta)))
:cql (.asCQLQuery agg-meta)
:state-type (convert-data-type (.getStateType agg-meta))
:state-func (.. agg-meta getStateFunc getSignature)
:final-func (.. agg-meta getFinalFunc getSignature)
:init-state (.getInitCond agg-meta)
}))
(defn- convert-column [^ColumnMetadata col-meta]
(when col-meta
{:static? (.isStatic col-meta)
:name (keyword (.getName col-meta))
:type (convert-data-type (.getType col-meta))}))
(defn- convert-table-options [^TableOptionsMetadata opts]
(when opts
(let [caching (.getCaching opts)
compaction (.getCompaction opts)
comnt (.getComment opts)
compression (.getCompression opts)
extensions (.getExtensions opts)]
(-> {
:bloom-filter-fp-chance (.getBloomFilterFalsePositiveChance opts)
:crc-check-chance (.getCrcCheckChance opts)
:default-ttl (.getDefaultTimeToLive opts)
:compact-storage? (.isCompactStorage opts)
:cdc? (.isCDC opts)
:gc-grace (.getGcGraceInSeconds opts)
:local-read-repair-chance (.getLocalReadRepairChance opts)
:read-repair-chance (.getReadRepairChance opts)
:max-index-interval (.getMaxIndexInterval opts)
:min-index-interval (.getMinIndexInterval opts)
:replicate-on-write? (.getReplicateOnWrite opts)
:speculative-retry (.getSpeculativeRetry opts)
:memtable-flush-period (.getMemtableFlushPeriodInMs opts)
:populate-io-cache-on-flush? (.getPopulateIOCacheOnFlush opts)
}
(cond-> caching (assoc :caching (into-keyed-map caching)))
(cond-> (seq comnt) (assoc :comment comnt))
(cond-> compaction (assoc :compaction (into-keyed-map compaction)))
(cond-> extensions (assoc :extensions (into-keyed-map extensions)))
(cond-> compression (assoc :compression (into-keyed-map compression)))))))
(defn- convert-abstract-table-meta [^AbstractTableMetadata at-meta]
(when at-meta
(let [id (.getId at-meta)
partition-key-names (non-nil-coll (fn [^ColumnMetadata v] (keyword (.getName v)))
(.getPartitionKey at-meta))
clustering-names (non-nil-coll (fn [^ColumnMetadata v] (keyword (.getName v)))
(.getClusteringColumns at-meta))
non-regular (into {} (concat (mapv #(vector % :partition-key) partition-key-names)
(mapv #(vector % :clustering) clustering-names)))
columns (non-nil-coll convert-column (.getColumns at-meta))
columns (mapv #(assoc % :kind (get non-regular (:name %) :regular)) columns)
primary-key (filterv #(not= (:kind %) :regular) columns)
partition-key (filterv #(= (:kind %) :partition-key) columns)
clustering-columns (filterv #(= (:kind %) :clustering) columns)
clustering-order (.getClusteringOrder at-meta)
options (convert-table-options (.getOptions at-meta))
regular-columns (filterv #(= (:kind %) :regular) columns)]
(-> {
:name (keyword (.getName at-meta))
:cql (.asCQLQuery at-meta)
:columns columns
:primary-key primary-key
:partition-key partition-key
}
(cond-> (seq regular-columns) (assoc :regular-columns regular-columns))
(cond-> (seq clustering-columns)
(assoc :clustering-columns
(mapv (fn [v1 ^ClusteringOrder v2]
(assoc v1 :order (keyword (.name v2))))
clustering-columns clustering-order)))
(cond-> id (assoc :id id))
(cond-> options (assoc :options options))))))
(defn- convert-mv-meta [^MaterializedViewMetadata mv-meta]
(when mv-meta
(assoc (convert-abstract-table-meta mv-meta)
:base-table (keyword (.. mv-meta getBaseTable getName)))))
(defn- convert-table-meta [^TableMetadata table-meta]
(when table-meta
(let [indexes (process-into-map convert-index-meta :name (.getIndexes table-meta))
mvs (process-into-map convert-mv-meta :name (.getViews table-meta))]
(-> (convert-abstract-table-meta table-meta)
(cond-> (seq indexes) (assoc :indexes indexes))
(cond-> (seq mvs) (assoc :materialized-views mvs))))))
(defn- convert-keyspace-meta
"Converts KeyspaceMetadata into Clojure map"
[^KeyspaceMetadata ks-meta detailed?]
(when ks-meta
(let [replication (.getReplication ks-meta)
tbl-meta (.getTables ks-meta)
tables (if detailed?
(process-into-map convert-table-meta :name tbl-meta)
(mapv (fn [^TableMetadata v]
(keyword (.getName v))) (seq tbl-meta)))
ut-meta (.getUserTypes ks-meta)
user-types (if detailed?
(process-into-map convert-user-types-meta :name ut-meta)
(mapv (fn [^UserType v]
(keyword (.getTypeName v))) (seq ut-meta)))
fn-meta (.getFunctions ks-meta)
functions (if detailed?
(process-into-map convert-func-meta :name fn-meta)
(mapv (fn [^FunctionMetadata v]
(.getSignature v)) (seq fn-meta)))
aggr-meta (.getAggregates ks-meta)
aggregates (if detailed?
(process-into-map convert-aggr-meta :name aggr-meta)
(mapv (fn [^AggregateMetadata v]
(.getSignature v)) (seq aggr-meta)))
mvs-meta (.getMaterializedViews ks-meta)
materialized-views (if detailed?
(process-into-map convert-mv-meta :name mvs-meta)
(mapv (fn [^MaterializedViewMetadata v]
(keyword (.getName v))) (seq mvs-meta)))]
(-> {
:replication (into-keyed-map replication)
:name (keyword (.getName ks-meta))
:durable-writes (.isDurableWrites ks-meta)
}
(cond-> (seq tables) (assoc :tables tables))
(cond-> (seq user-types) (assoc :user-types user-types))
(cond-> (seq functions) (assoc :functions functions))
(cond-> (seq aggregates) (assoc :aggregates aggregates))
(cond-> (seq materialized-views) (assoc :materialized-views materialized-views))
(cond-> detailed? (assoc :cql (.asCQLQuery ks-meta)))))))
(defn- ^Metadata get-cluster-meta [^Session session]
(when session
(when-let [cluster (.getCluster session)]
(.getMetadata cluster))))
(defn- ^KeyspaceMetadata get-keyspace-meta [^Session session ks]
(when-let [cluster-meta ^Metadata (get-cluster-meta session)]
(.getKeyspace cluster-meta (name ks))))
(defn keyspace
"Describes a keyspace.
Verbosity is regulated by :detailed? parameter that is equal to false by default."
[^Session session ks & {:keys [detailed?] :or {detailed? false}}]
(convert-keyspace-meta (get-keyspace-meta session ks) detailed?))
(defn keyspaces
"Describes all available keyspaces.
Verbosity is regulated by :detailed? parameter that is equal to false by default."
[^Session session & {:keys [detailed?] :or {detailed? false}}]
(when-let [cluster-meta ^Metadata (get-cluster-meta session)]
(process-into-map #(convert-keyspace-meta % detailed?)
:name (.getKeyspaces cluster-meta))))
(defn table
"Describes a table"
[^Session session ks table]
(when-let [ks-meta (get-keyspace-meta session ks)]
(convert-table-meta (.getTable ks-meta (name table)))))
(defn tables
"Returns descriptions of all the tables"
[^Session session ks]
(when-let [ks-meta (get-keyspace-meta session ks)]
(process-into-map convert-table-meta :name (.getTables ks-meta))))
(defn index
"Describes an index"
[^Session session ks table index]
(when-let [ks-meta (get-keyspace-meta session ks)]
(when-let [tbl (.getTable ks-meta (name table))]
(convert-index-meta (.getIndex tbl (name index))))))
(defn indexes
"Returns descriptions of indices"
[^Session session ks table]
(when-let [ks-meta (get-keyspace-meta session ks)]
(when-let [tbl (.getTable ks-meta (name table))]
(process-into-map convert-index-meta :name (.getIndexes tbl)))))
(defn materialized-view
"Describes a materialized view"
[^Session session ks mv]
(when-let [ks-meta (get-keyspace-meta session ks)]
(convert-mv-meta (.getMaterializedView ks-meta (name mv)))))
(defn materialized-views
"Returns descriptions of all materialized views"
[^Session session ks]
(when-let [ks-meta (get-keyspace-meta session ks)]
(process-into-map convert-mv-meta :name (.getMaterializedViews ks-meta))))
(defn user-type
"Describes a "
[^Session session ks utype]
(when-let [ks-meta (get-keyspace-meta session ks)]
(convert-user-types-meta (.getUserType ks-meta (name utype)))))
(defn user-types
"Returns descriptions of all user types"
[^Session session ks]
(when-let [ks-meta (get-keyspace-meta session ks)]
(process-into-map convert-user-types-meta :name (.getUserTypes ks-meta))))
(defn aggregate
"Describes a "
[^Session session ks aggr ^Collection arg-types]
(when-let [ks-meta (get-keyspace-meta session ks)]
(convert-aggr-meta (.getAggregate ks-meta (name aggr) arg-types))))
(defn aggregates
"Returns descriptions of all aggregates"
[^Session session ks]
(when-let [ks-meta (get-keyspace-meta session ks)]
(process-into-map convert-aggr-meta :name (.getAggregates ks-meta))))
(defn function
"Describes a "
[^Session session ks func ^Collection arg-types]
(when-let [ks-meta (get-keyspace-meta session ks)]
(convert-func-meta (.getFunction ks-meta (name func) arg-types))))
(defn functions
"Returns descriptions of all functions"
[^Session session ks]
(when-let [ks-meta (get-keyspace-meta session ks)]
(process-into-map convert-func-meta :name (.getFunctions ks-meta))))
(defn columns
"Describes columns of a table"
[^Session session ks tbl-name]
(:columns (table session ks tbl-name)))
(defn- get-host-info [^Host host detailed?]
(when host
(-> {:rack (.getRack host)
:datacenter (.getDatacenter host)
:up? (.isUp host)
:state (.getState host)
:cassandra-version (str (.getCassandraVersion host))
: dse - workloads ( .getDseWorkloads host )
:socket-address (str (.getSocketAddress host))
:listen-address (str (.getListenAddress host))
:address (str (.getAddress host))
:broadcast-address (str (.getBroadcastAddress host))
}
(cond-> detailed? (assoc :tokens (.getTokens host))))))
(defn- get-hosts-impl [^Metadata cluster-meta detailed?]
(when-let [hosts (.getAllHosts cluster-meta)]
(non-nil-coll #(get-host-info % detailed?) hosts)))
(defn hosts
"Returns information about hosts in cluster associated with session.
Verbosity is regulated by :detailed? parameter that is equal to false by default."
[^Session session & {:keys [detailed?] :or {detailed? false}}]
(when-let [cluster-meta ^Metadata (get-cluster-meta session)]
(get-hosts-impl cluster-meta detailed?)))
(defn cluster
"Describes cluster associated with session.
Verbosity is regulated by :detailed? parameter that is equal to false by default."
[^Session session & {:keys [detailed?] :or {detailed? false}}]
(when-let [cluster-meta ^Metadata (get-cluster-meta session)]
(-> {
:name (keyword (.getClusterName cluster-meta))
:hosts (get-hosts-impl cluster-meta detailed?)
:partitioner (.getPartitioner cluster-meta)
:keyspaces (process-into-map #(convert-keyspace-meta % detailed?)
:name (.getKeyspaces cluster-meta))
:schema-agreed? (.checkSchemaAgreement cluster-meta)
}
(cond-> detailed? (assoc :schema (.exportSchemaAsString cluster-meta))))))
(defn cluster-schema
"Returns full schema for cluster associated with session."
[^Session session]
(when-let [cluster-meta ^Metadata (get-cluster-meta session)]
(.exportSchemaAsString cluster-meta)))
|
ab4da9bdc01b4e71436370a8688e8a6bf8a75e61504c497285fc7699389d9326 | nasa/Common-Metadata-Repository | user.clj | (ns user
"A dev namespace that supports Proto-REPL.
It seems that Proto-REPL doesn't support the flexible approach that lein
uses: any configurable ns can be the starting ns for a REPL. As such, this
minimal ns was created for Proto-REPL users, so they too can have an env
that supports startup and shutdown."
(:require
[clojure.java.io :as io]
[clojure.pprint :refer [pprint]]
[clojure.tools.namespace.repl :as repl]
[clojusc.system-manager.core :refer :all]
[cmr.plugin.jar.dev :as dev]))
| null | https://raw.githubusercontent.com/nasa/Common-Metadata-Repository/63001cf021d32d61030b1dcadd8b253e4a221662/other/cmr-exchange/jar-plugin-lib/dev-resources/src/user.clj | clojure | (ns user
"A dev namespace that supports Proto-REPL.
It seems that Proto-REPL doesn't support the flexible approach that lein
uses: any configurable ns can be the starting ns for a REPL. As such, this
minimal ns was created for Proto-REPL users, so they too can have an env
that supports startup and shutdown."
(:require
[clojure.java.io :as io]
[clojure.pprint :refer [pprint]]
[clojure.tools.namespace.repl :as repl]
[clojusc.system-manager.core :refer :all]
[cmr.plugin.jar.dev :as dev]))
| |
5a99e7f776d3d88190723a4d76b013e868bd74c9ecf43871623dfa7756b78ccd | nixin72/shan | install_test.clj | (ns shan.install-test
(:require
[clojure.test :refer [deftest testing is]]
[shan.macros :refer [suppress-stdout
with-test-env
with-failed-operation
with-input-queue]]
[shan.print :as p]
[shan.util :as u]
[shan.command.install :as in]
[shan.test-values :as tv]))
;;;;;;;;;;; test-generate-success-report ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(deftest test-generate-success-report
(println "Testing function" (p/bold "install/generate-success-report"))
(suppress-stdout
(testing "Test empty results"
(is (= (in/generate-success-report {})
{:failed false
:success {}
:commands #{}})))
(testing "Test single failing package"
(is (= (in/generate-success-report {:yay {"yay -S --noconfirm nano" nil}})
{:failed true
:success {:yay []}
:commands #{"yay -S --noconfirm nano"}})))
(testing "Test single successful package"
(is (= (in/generate-success-report '{:yay {"yay -S --noconfirm nano" nano}})
{:failed false
:success '{:yay [nano]}
:commands #{"yay -S --noconfirm nano"}})))
(testing "Test a successful and a failed package"
(is (= (in/generate-success-report '{:yay {"yay -S --noconfirm nano" nano}
:npm {"npm install --global expo" nil}})
{:failed true
:success '{:yay [nano] :npm []}
:commands #{"yay -S --noconfirm nano"
"npm install --global expo"}})))
(testing "Test a successful and a complex report"
(is (= (in/generate-success-report '{:yay {"yay -S --noconfirm nano" nano
"yay -S --noconfirm htop" htop}
:pip {"python -m pip install wakatime" nil}
:npm {"npm install --global expo" nil
"npm install --global react" react}})
{:failed true
:success '{:yay [nano htop] :npm [react] :pip []}
:commands #{"yay -S --noconfirm nano"
"yay -S --noconfirm htop"
"python -m pip install wakatime"
"npm install --global expo"
"npm install --global react"}})))))
;;;;;;;;;;; test-find-default-manager ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(deftest test-find-default-manager
(println "Testing function" (p/bold "install/find-default-manager"))
(suppress-stdout
(testing "Getting finding default package manager without setting it."
(is (= (with-input-queue '("0" "n")
(in/find-default-manager tv/install-map-simple-input))
(u/serialize '{:paru [fzf]}))))
(testing "Getting finding default package manager without setting it."
(is (= (with-input-queue '("1" "y")
(in/find-default-manager tv/install-map-simple-input))
(u/serialize '{:yay [fzf] :default-manager :yay}))))))
;; NOTE: The following tests are working with stateful code, however they do not
;; test the side effects of the changes of state. This code deals with removing
;; packages from the system, however it doesn't ensure the package was
;; successfully deleted or not. Instead, it ensures that the correct commands
;; are generated to successfully remove those packages. If those packages are
;; not successfully removed, then as long as the command is successfully
generated it 's probably not a problem with shan .
;;;;;;;;;;; test-cli-install ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(deftest test-cli-install
(println "Testing function" (p/bold "install/cli-install"))
(with-test-env [env tv/pre-installed-packages]
(testing "Test installing a single known package"
(is (= (in/cli-install {:_arguments ["micro"]})
#{"yay -S --noconfirm micro"})))
(testing "Test installing several packages from same manager"
(is (= (in/cli-install {:_arguments ["micro" "nano"]})
#{"yay -S --noconfirm micro"
"yay -S --noconfirm nano"})))
(testing "Test installing with specified manager"
(is (= (in/cli-install {:_arguments [":npm" "underscore" "react"]})
#{"npm install --global underscore"
"npm install --global react"})))
(testing "Test installing with several specified managers"
(is (= (in/cli-install {:_arguments [":npm" "underscore" ":yay" "micro"]})
#{"npm install --global underscore"
"yay -S --noconfirm micro"})))
(testing "Test installing with non-existant package"
(is (= (with-failed-operation
(in/cli-install {:_arguments ["some-garbage-input"]}))
#{"yay -S --noconfirm some-garbage-input"})))
(testing "All operations completeled successfully"
(is (= @env (-> tv/pre-installed-packages
(update :pacman conj 'micro 'nano)
(update :npm conj 'underscore 'react)))))))
| null | https://raw.githubusercontent.com/nixin72/shan/2fe648cb7648174900d25e5ef2af6a9263ee9f97/test/shan/install_test.clj | clojure | test-generate-success-report ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
test-find-default-manager ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
NOTE: The following tests are working with stateful code, however they do not
test the side effects of the changes of state. This code deals with removing
packages from the system, however it doesn't ensure the package was
successfully deleted or not. Instead, it ensures that the correct commands
are generated to successfully remove those packages. If those packages are
not successfully removed, then as long as the command is successfully
test-cli-install ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; | (ns shan.install-test
(:require
[clojure.test :refer [deftest testing is]]
[shan.macros :refer [suppress-stdout
with-test-env
with-failed-operation
with-input-queue]]
[shan.print :as p]
[shan.util :as u]
[shan.command.install :as in]
[shan.test-values :as tv]))
(deftest test-generate-success-report
(println "Testing function" (p/bold "install/generate-success-report"))
(suppress-stdout
(testing "Test empty results"
(is (= (in/generate-success-report {})
{:failed false
:success {}
:commands #{}})))
(testing "Test single failing package"
(is (= (in/generate-success-report {:yay {"yay -S --noconfirm nano" nil}})
{:failed true
:success {:yay []}
:commands #{"yay -S --noconfirm nano"}})))
(testing "Test single successful package"
(is (= (in/generate-success-report '{:yay {"yay -S --noconfirm nano" nano}})
{:failed false
:success '{:yay [nano]}
:commands #{"yay -S --noconfirm nano"}})))
(testing "Test a successful and a failed package"
(is (= (in/generate-success-report '{:yay {"yay -S --noconfirm nano" nano}
:npm {"npm install --global expo" nil}})
{:failed true
:success '{:yay [nano] :npm []}
:commands #{"yay -S --noconfirm nano"
"npm install --global expo"}})))
(testing "Test a successful and a complex report"
(is (= (in/generate-success-report '{:yay {"yay -S --noconfirm nano" nano
"yay -S --noconfirm htop" htop}
:pip {"python -m pip install wakatime" nil}
:npm {"npm install --global expo" nil
"npm install --global react" react}})
{:failed true
:success '{:yay [nano htop] :npm [react] :pip []}
:commands #{"yay -S --noconfirm nano"
"yay -S --noconfirm htop"
"python -m pip install wakatime"
"npm install --global expo"
"npm install --global react"}})))))
(deftest test-find-default-manager
(println "Testing function" (p/bold "install/find-default-manager"))
(suppress-stdout
(testing "Getting finding default package manager without setting it."
(is (= (with-input-queue '("0" "n")
(in/find-default-manager tv/install-map-simple-input))
(u/serialize '{:paru [fzf]}))))
(testing "Getting finding default package manager without setting it."
(is (= (with-input-queue '("1" "y")
(in/find-default-manager tv/install-map-simple-input))
(u/serialize '{:yay [fzf] :default-manager :yay}))))))
generated it 's probably not a problem with shan .
(deftest test-cli-install
(println "Testing function" (p/bold "install/cli-install"))
(with-test-env [env tv/pre-installed-packages]
(testing "Test installing a single known package"
(is (= (in/cli-install {:_arguments ["micro"]})
#{"yay -S --noconfirm micro"})))
(testing "Test installing several packages from same manager"
(is (= (in/cli-install {:_arguments ["micro" "nano"]})
#{"yay -S --noconfirm micro"
"yay -S --noconfirm nano"})))
(testing "Test installing with specified manager"
(is (= (in/cli-install {:_arguments [":npm" "underscore" "react"]})
#{"npm install --global underscore"
"npm install --global react"})))
(testing "Test installing with several specified managers"
(is (= (in/cli-install {:_arguments [":npm" "underscore" ":yay" "micro"]})
#{"npm install --global underscore"
"yay -S --noconfirm micro"})))
(testing "Test installing with non-existant package"
(is (= (with-failed-operation
(in/cli-install {:_arguments ["some-garbage-input"]}))
#{"yay -S --noconfirm some-garbage-input"})))
(testing "All operations completeled successfully"
(is (= @env (-> tv/pre-installed-packages
(update :pacman conj 'micro 'nano)
(update :npm conj 'underscore 'react)))))))
|
ee76aeaa3d5d54c1c1be5f8d18734dbbce2287d78f503fcf2cfc9fec6bdedc28 | donut-party/system | system_test.cljc | (ns donut.system-test
(:require
#?(:clj [clojure.test :refer [deftest is testing]]
:cljs [cljs.test :refer [deftest is testing] :include-macros true])
[donut.system :as ds :include-macros true]
[loom.alg :as la]
[loom.graph :as lg]
[malli.core :as m]
[clojure.string :as str]))
(defn config-port
[opts]
(get-in opts [::ds/config :port]))
(deftest merge-base-test
(is (= #::ds{:base {:pre-start [:foo]}
:defs {:app {:http-server {:pre-start [:foo]
:post-start [:bar]}}}}
(#'ds/merge-base #::ds{:base {:pre-start [:foo]}
:defs {:app {:http-server {:post-start [:bar]}}}})))
(is (= [:foo]
(get-in (#'ds/merge-base #::ds{:base {:pre-start [:foo]}
:defs {:app {:http-server [:bar]}}})
[::ds/defs :app :http-server :pre-start]))))
(deftest expand-refs-for-graph-test
(is (= #::ds{:defs {:env {:http-port {:x (ds/ref [:env :bar])}}
:app {:http-server {:port (ds/ref [:env :http-port])}}}}
(#'ds/expand-refs-for-graph
#::ds{:defs {:env {:http-port {:x (ds/local-ref [:bar])}}
:app {:http-server {:port (ds/ref [:env :http-port])}}}}))))
(deftest resolve-refs-test
(is (= #::ds{:defs {:app {:http-server {:port (ds/ref [:env :http-port])}}}
:resolved-defs {:app {:http-server {:port 9090}}},
:instances {:env {:http-port 9090}}}
(#'ds/resolve-refs #::ds{:defs {:app {:http-server {:port (ds/ref [:env :http-port])}}}
:instances {:env {:http-port 9090}}}
[:app :http-server]))))
(deftest ref-edges-test
(is (= [[[:env :http-port] [:env :bar]]
[[:app :http-server] [:env :http-port]]]
(#'ds/ref-edges #::ds{:defs {:env {:http-port {:deps {:x (ds/local-ref [:bar])}}}
:app {:http-server {:deps {:port (ds/ref [:env :http-port])}}}}}
:topsort))))
(deftest gen-graphs-test
(let [system (#'ds/gen-graphs #::ds{:defs {:env {:port-source nil
:http-port (ds/local-ref [:port-source])}
:app {:http-server {:port (ds/ref [:env :http-port])}}}})]
(is (= [[:app :http-server]
[:env :http-port]
[:env :port-source]]
(la/topsort (get-in system [::ds/graphs :topsort]))))
(is (= [[:env :port-source]
[:env :http-port]
[:app :http-server]]
(la/topsort (get-in system [::ds/graphs :reverse-topsort]))))))
(deftest simple-signal-test
(is (= #::ds{:instances {:app {:boop "boop"}}}
(-> #::ds{:defs {:app {:boop {::ds/start "boop"}}}}
(ds/signal ::ds/start)
(select-keys [::ds/instances]))))
(is (= #::ds{:instances {:app {:boop "boop and boop again"}}}
(-> #::ds{:defs {:app {:boop #::ds{:start "boop"
:stop (fn [{:keys [::ds/instance]}]
(str instance " and boop again"))}}}}
(ds/signal ::ds/start)
(ds/signal ::ds/stop)
(select-keys [::ds/instances])))))
(deftest ref-test
(testing "referred port number is passed to referrer"
(is (= #::ds{:instances {:env {:http-port 9090}
:app {:http-server 9090}}}
(-> #::ds{:defs {:env {:http-port #::ds{:start 9090}}
:app {:http-server #::ds{:start config-port
:config {:port (ds/ref [:env :http-port])}}}}}
(ds/signal ::ds/start)
(select-keys [::ds/instances]))))))
(deftest deep-ref-test
(testing "refs can be of arbitrary depth"
(is (= #::ds{:instances {:env {:http {:port 9090}}
:app {:http-server 9090}}}
(-> #::ds{:defs {:env {:http {:port 9090}}
:app {:http-server #::ds{:start config-port
;; [:env :http :port] reaches into the :http "component"
:config {:port (ds/ref [:env :http :port])}}}}}
(ds/signal ::ds/start)
(select-keys [::ds/instances])))))
(testing "components with deep refs are started in the correct order"
(let [vref-comp (fn [comp-name]
#::ds{:config {:ref (ds/ref [:group comp-name :v])}
:start (fn [{{ref :ref} ::ds/config}]
{:v ref})})]
(is (= #::ds{:instances {:group {:c1 {:v :x} :c2 {:v :x} :c3 {:v :x} :c4 {:v :x}}}}
(-> #::ds{:defs {:group {:c1 {:v :x}
:c2 (vref-comp :c4)
:c3 (vref-comp :c2)
:c4 (vref-comp :c1)}}}
(ds/signal ::ds/start)
(select-keys [::ds/instances])))))))
(deftest local-ref-test
(testing "ref of keyword resolves to component in same group"
(is (= #::ds{:instances {:app {:http-server 9090
:http-port 9090}}}
(-> #::ds{:defs {:app {:http-server #::ds{:start config-port
:config {:port (ds/local-ref [:http-port])}}
:http-port 9090}}}
(ds/signal ::ds/start)
(select-keys [::ds/instances]))))))
(deftest group-ref-test
(testing "referred group is passed to referrer"
(is (= #::ds{:instances {:env {:http-port 9090
:timeout 5000}
:app {:http-server {:http-port 9090
:timeout 5000}}}}
(-> #::ds{:defs {:env {:http-port #::ds{:start 9090}
:timeout #::ds{:start 5000}}
:app {:http-server #::ds{:start (fn [opts] (get-in opts [::ds/config :env]))
:config {:env (ds/ref [:env])}}}}}
(ds/signal ::ds/start)
(select-keys [::ds/instances]))))))
(deftest signal-constant-test
(testing "can forego a map for component def if value should be a constant"
(is (= #::ds{:instances {:env {:http-port 9090}
:app {:http-server 9090}}}
(-> #::ds{:defs {:env {:http-port 9090}
:app {:http-server #::ds{:start config-port
:config {:port (ds/ref [:env :http-port])}}}}}
(ds/signal ::ds/start)
(select-keys [::ds/instances]))))))
(deftest validate-component
(let [schema (m/schema int?)]
(is (= #::ds{:out {:validation {:env {:http-port {:schema schema
:value "9090"
:errors [{:path []
:in []
:schema schema
:value "9090"}]}}}}}
(-> #::ds{:base {::ds/post-start ds/validate-instance-with-malli}
:defs {:env {:http-port #::ds{:start "9090"
:schema schema}}
:app {:http-server #::ds{:start config-port
:config {:port (ds/ref [:env :http-port])}}}}}
(ds/signal ::ds/start)
(select-keys [::ds/out]))))))
(deftest lifecycle-values-ignored-when-not-system
(let [expected #::ds{:instances {:env {:http-port 9090}
:app {:http-server 9090}}}
system #::ds{:defs {:env {:http-port #::ds{:start 9090}}
:app {:http-server #::ds{:start config-port
:config {:port (ds/ref [:env :http-port])}}}}}]
(is (= expected
(-> system
(assoc-in [::ds/defs :app :http-server ::ds/pre-start] (constantly nil))
(ds/signal ::ds/start)
(select-keys [::ds/instances]))))
(is (= expected
(-> system
(assoc-in [::ds/defs :app :http-server ::ds/post-start] (constantly nil))
(ds/signal ::ds/start)
(select-keys [::ds/instances]))))))
(deftest gen-signal-computation-graph-test
(let [system (#'ds/gen-graphs #::ds{:defs {:env {:http-port 9090}
:app {:http-server {:port (ds/ref [:env :http-port])}}}})]
(is (= (->> [[:env :http-port :pre-start]
[:env :http-port :start]
[:env :http-port :post-start]
[:app :http-server :pre-start]
[:app :http-server :start]
[:app :http-server :post-start]]
(partition 2 1)
(apply lg/add-edges (lg/digraph)))
(#'ds/gen-signal-computation-graph system :start :reverse-topsort)))))
(deftest channel-fns-test
(testing "can chain channel fns"
(is (= #::ds{:instances {:app {:http-server 9090
:http-port 9090}}
:out {:info {:app {:http-server "info"}}}}
(-> #::ds{:defs {:app {:http-server #::ds{:start (fn [{:keys [::ds/config ->instance ->info]}]
(-> (->instance (:port config))
(->info "info")))
:config {:port (ds/local-ref [:http-port])}}
:http-port 9090}}}
(ds/signal ::ds/start)
(select-keys [::ds/instances ::ds/out]))))))
(deftest subsystem-test
(let [subsystem #::ds{:defs
{:local {:port 9090}
:app
{:local #::ds{:start (fn [_] :local)}
:server #::ds{:start (fn [{:keys [::ds/config]}] config)
:post-start (fn [{:keys [->info]}]
(->info "started"))
:stop (fn [{:keys [::ds/instance]}]
{:prev instance
:now :stopped})
:post-stop (fn [{:keys [->info]}]
(->info "stopped"))
:config {:job-queue (ds/ref [:common-services :job-queue])
:db (ds/ref [:common-services :db])
:port (ds/ref [:local :port])
:local (ds/local-ref [:local])}}}}}
started (-> #::ds{:defs
{:env
{:app-name "foo.app"}
:common-services
{:job-queue "job queue"
:db "db"}
:sub-systems
{:system-1 (ds/subsystem-component
subsystem
#{(ds/ref [:common-services :job-queue])
(ds/ref [:common-services :db])})
:system-2 (ds/subsystem-component
subsystem
#{(ds/ref [:common-services])})}}}
(ds/signal ::ds/start))]
(is (= {:job-queue "job queue"
:db "db"
:port 9090
:local :local}
(get-in started [::ds/instances :sub-systems :system-1 ::ds/instances :app :server])
(get-in started [::ds/instances :sub-systems :system-2 ::ds/instances :app :server])))
(is (= "started"
(get-in started [::ds/out :info :sub-systems :system-1 :app :server])
(get-in started [::ds/out :info :sub-systems :system-2 :app :server])))
(let [stopped (ds/signal started ::ds/stop)]
(is (= {:prev {:job-queue "job queue"
:db "db"
:port 9090
:local :local}
:now :stopped}
(get-in stopped [::ds/instances :sub-systems :system-1 ::ds/instances :app :server])
(get-in stopped [::ds/instances :sub-systems :system-2 ::ds/instances :app :server])))
(is (= "stopped"
(get-in stopped [::ds/out :info :sub-systems :system-1 :app :server])
(get-in stopped [::ds/out :info :sub-systems :system-2 :app :server]))))))
(deftest select-components-test
(testing "if you specify components, the union of their subgraphs is used"
(let [system-def {::ds/defs {:env {:http-port #::ds{:start 9090}}
:app {:http-server #::ds{:start config-port
:stop "stopped http-server"
:config {:port (ds/ref [:env :http-port])}}
:db #::ds{:start "db"
:stop "stopped db"}}}}
started (ds/signal system-def ::ds/start #{[:app :http-server]})]
(is (= {::ds/instances {:app {:http-server 9090}
:env {:http-port 9090}}}
(select-keys started [::ds/instances])))
(testing "the selected components are retained beyond the start"
(is (= {::ds/instances {:app {:http-server "stopped http-server"}
:env {:http-port 9090}}}
(-> started
(ds/signal ::ds/stop)
(select-keys [::ds/instances])))))
(testing "groups you can select groups"
(is (= {::ds/instances {:env {:http-port 9090}}}
(-> (ds/signal system-def ::ds/start #{:env})
(select-keys [::ds/instances]))))))))
(deftest ref-undefined-test
(is (thrown-with-msg?
#?(:clj clojure.lang.ExceptionInfo
:cljs js/Object)
#"Invalid ref"
(ds/signal {::ds/defs {:group-a {:foo :foo}
:group-b {:component {:ref-1 (ds/ref [:group-a :foo])
:ref-2 (ds/ref [:group-a :nonexistent-component])}}}}
::ds/start)))
(is (thrown-with-msg?
#?(:clj clojure.lang.ExceptionInfo
:cljs js/Object)
#"Invalid group ref"
(ds/signal {::ds/defs {:group {:component {:ref (ds/ref [:nonexistent :ref])}}}}
::ds/start)))
(is (thrown-with-msg?
#?(:clj clojure.lang.ExceptionInfo
:cljs js/Object)
#"Invalid group ref"
(ds/signal {::ds/defs {:group {:component {:ref (ds/ref [:nonexistent])}}}}
::ds/start))))
(defmethod ds/named-system ::system-config-test
[_]
{::ds/defs {:group {:component-a 1
:component-b 2
:component-c 3}}})
(deftest assoc-many-test
(is (= {:a {:b 1}
:c {:d 2}}
(ds/assoc-many {} {[:a :b] 1
[:c :d] 2})))
(is (= {:foo {:a {:b 1}
:c {:d 2}}}
(ds/assoc-many {}
[:foo]
{[:a :b] 1
[:c :d] 2}))))
(deftest system-config-test
(is (= {::ds/defs {:group {:component-a 1
:component-b 2
:component-c 4
:component-d 5}}}
(ds/system ::system-config-test
{[:group :component-c] 4
[:group :component-d] 5}))))
(deftest signal-helper-test
(testing "basic signal helpers work"
(is (= {::ds/instances {:app {:boop "boop"}}}
(-> {::ds/defs {:app {:boop #::ds{:start "boop"}}}}
(ds/start)
(select-keys [::ds/instances]))))
(is (= {::ds/instances {:app {:boop "boop and boop again"}}}
(-> {::ds/defs {:app {:boop #::ds{:start "boop"
:stop (fn [{:keys [::ds/instance]}]
(str instance " and boop again"))}}}}
(ds/start)
(ds/stop)
(select-keys [::ds/instances]))))))
(deftest signal-helper-overrides-test
(is (= {::ds/instances {:app {:boop "boop"}}}
(-> {::ds/defs {:app {:boop #::ds{:start "no boop"}}}}
(ds/start {[:app :boop ::ds/start] "boop"})
(select-keys [::ds/instances])))))
(deftest recognized-signals-exception-test
(is (thrown-with-msg?
#?(:clj clojure.lang.ExceptionInfo
:cljs js/Object)
#"Signal :foo is not recognized"
(ds/signal {::ds/defs {:group {:component "constant"}}}
:foo)))
(testing "should not throw exception"
(is (ds/signal {::ds/defs {:group {:component "constant"}}
::ds/signals (merge ds/default-signals {:foo {:order :topsort}})}
:foo))))
(deftest required-component-test
(is (thrown?
#?(:clj clojure.lang.ExceptionInfo
:cljs js/Object)
(ds/signal {::ds/defs {:group {:component ds/required-component}}}
::ds/start)))
(try (ds/signal {::ds/defs {:group {:component ds/required-component}}}
::ds/start)
(catch #?(:clj Exception :cljs :default) e
(is (= [:group :component]
(:component (ex-data e)))))))
(deftest get-registry-instance-test
(let [system (-> {::ds/registry {:the-boop [:app :boop]}
::ds/defs {:app {:boop #::ds{:start "no boop"}}}}
(ds/start))]
(is (= "no boop" (ds/registry-instance system :the-boop)))))
(deftest registry-instance-exception-test
(is (thrown-with-msg?
#?(:clj clojure.lang.ExceptionInfo
:cljs js/Object)
#":donut.system/registry does not contain registry-key"
(-> {::ds/defs {:group {:component "constant"}}}
ds/start
(ds/registry-instance :no-registry-key))))
(is (thrown-with-msg?
#?(:clj clojure.lang.ExceptionInfo
:cljs js/Object)
#"No component instance found for registry key."
(-> {::ds/registry {:a-key [:bad :path]}
::ds/defs {:group {:component "constant"}}}
ds/start
(ds/registry-instance :a-key)))))
(deftest component-ids-test
(is (= [[:group-a :a]
[:group-a :b]
[:group-b :a]
[:group-b :b]
[:group-b :c]]
(ds/component-ids {::ds/defs {:group-a {:a nil
:b nil}
:group-b {:a nil
:b nil
:c nil}}}))))
(deftest status-signal-test
(is (= {:group-a {:a :status-a}}
(::ds/status
(ds/signal {::ds/defs
{:group-a
{:a #::ds{:status (fn [_] :status-a)}}}}
::ds/status)))))
(deftest describe-system-test
(is (= {:group-a
{:a
{:name [:group-a :a]
:config nil
:resolved-config nil
:instance ["a-component"]
:status :status-a
:doc "a component doc"
:dependencies #{}}
:b
{:name [:group-a :b]
:config nil
:resolved-config nil
:instance "b-component"
:status :b-component
:doc nil
:dependencies #{}}}}
(ds/describe-system
(ds/start
{::ds/defs {:group-a {:a #::ds{:start (with-meta ["a-component"] {:doc "a component doc"})
:status (fn [_] :status-a)}
:b #::ds{:start (fn [_] "b-component")
:status (fn [{:keys [::ds/instance] :as x}]
(keyword instance))}}}})))))
(deftest with-*system*-test
(is (= {:group-a {:a "component a"
:b "component b"}}
(ds/with-*system*
{::ds/defs {:group-a {:a #::ds{:start "component a"}
:b #::ds{:start "component b"}}}}
(::ds/instances ds/*system*)
))))
(deftest update-many-test
(is (= {:a {:b "FOO"
:c 1}}
(ds/update-many
{:a {:b "foo"
:c 0}}
{[:a :b] str/upper-case
[:a :c] inc}))))
| null | https://raw.githubusercontent.com/donut-party/system/6c8a92eecd86d38247d69998667bfb955e9cb3ad/test/donut/system_test.cljc | clojure | [:env :http :port] reaches into the :http "component" | (ns donut.system-test
(:require
#?(:clj [clojure.test :refer [deftest is testing]]
:cljs [cljs.test :refer [deftest is testing] :include-macros true])
[donut.system :as ds :include-macros true]
[loom.alg :as la]
[loom.graph :as lg]
[malli.core :as m]
[clojure.string :as str]))
(defn config-port
[opts]
(get-in opts [::ds/config :port]))
(deftest merge-base-test
(is (= #::ds{:base {:pre-start [:foo]}
:defs {:app {:http-server {:pre-start [:foo]
:post-start [:bar]}}}}
(#'ds/merge-base #::ds{:base {:pre-start [:foo]}
:defs {:app {:http-server {:post-start [:bar]}}}})))
(is (= [:foo]
(get-in (#'ds/merge-base #::ds{:base {:pre-start [:foo]}
:defs {:app {:http-server [:bar]}}})
[::ds/defs :app :http-server :pre-start]))))
(deftest expand-refs-for-graph-test
(is (= #::ds{:defs {:env {:http-port {:x (ds/ref [:env :bar])}}
:app {:http-server {:port (ds/ref [:env :http-port])}}}}
(#'ds/expand-refs-for-graph
#::ds{:defs {:env {:http-port {:x (ds/local-ref [:bar])}}
:app {:http-server {:port (ds/ref [:env :http-port])}}}}))))
(deftest resolve-refs-test
(is (= #::ds{:defs {:app {:http-server {:port (ds/ref [:env :http-port])}}}
:resolved-defs {:app {:http-server {:port 9090}}},
:instances {:env {:http-port 9090}}}
(#'ds/resolve-refs #::ds{:defs {:app {:http-server {:port (ds/ref [:env :http-port])}}}
:instances {:env {:http-port 9090}}}
[:app :http-server]))))
(deftest ref-edges-test
(is (= [[[:env :http-port] [:env :bar]]
[[:app :http-server] [:env :http-port]]]
(#'ds/ref-edges #::ds{:defs {:env {:http-port {:deps {:x (ds/local-ref [:bar])}}}
:app {:http-server {:deps {:port (ds/ref [:env :http-port])}}}}}
:topsort))))
(deftest gen-graphs-test
(let [system (#'ds/gen-graphs #::ds{:defs {:env {:port-source nil
:http-port (ds/local-ref [:port-source])}
:app {:http-server {:port (ds/ref [:env :http-port])}}}})]
(is (= [[:app :http-server]
[:env :http-port]
[:env :port-source]]
(la/topsort (get-in system [::ds/graphs :topsort]))))
(is (= [[:env :port-source]
[:env :http-port]
[:app :http-server]]
(la/topsort (get-in system [::ds/graphs :reverse-topsort]))))))
(deftest simple-signal-test
(is (= #::ds{:instances {:app {:boop "boop"}}}
(-> #::ds{:defs {:app {:boop {::ds/start "boop"}}}}
(ds/signal ::ds/start)
(select-keys [::ds/instances]))))
(is (= #::ds{:instances {:app {:boop "boop and boop again"}}}
(-> #::ds{:defs {:app {:boop #::ds{:start "boop"
:stop (fn [{:keys [::ds/instance]}]
(str instance " and boop again"))}}}}
(ds/signal ::ds/start)
(ds/signal ::ds/stop)
(select-keys [::ds/instances])))))
(deftest ref-test
(testing "referred port number is passed to referrer"
(is (= #::ds{:instances {:env {:http-port 9090}
:app {:http-server 9090}}}
(-> #::ds{:defs {:env {:http-port #::ds{:start 9090}}
:app {:http-server #::ds{:start config-port
:config {:port (ds/ref [:env :http-port])}}}}}
(ds/signal ::ds/start)
(select-keys [::ds/instances]))))))
(deftest deep-ref-test
(testing "refs can be of arbitrary depth"
(is (= #::ds{:instances {:env {:http {:port 9090}}
:app {:http-server 9090}}}
(-> #::ds{:defs {:env {:http {:port 9090}}
:app {:http-server #::ds{:start config-port
:config {:port (ds/ref [:env :http :port])}}}}}
(ds/signal ::ds/start)
(select-keys [::ds/instances])))))
(testing "components with deep refs are started in the correct order"
(let [vref-comp (fn [comp-name]
#::ds{:config {:ref (ds/ref [:group comp-name :v])}
:start (fn [{{ref :ref} ::ds/config}]
{:v ref})})]
(is (= #::ds{:instances {:group {:c1 {:v :x} :c2 {:v :x} :c3 {:v :x} :c4 {:v :x}}}}
(-> #::ds{:defs {:group {:c1 {:v :x}
:c2 (vref-comp :c4)
:c3 (vref-comp :c2)
:c4 (vref-comp :c1)}}}
(ds/signal ::ds/start)
(select-keys [::ds/instances])))))))
(deftest local-ref-test
(testing "ref of keyword resolves to component in same group"
(is (= #::ds{:instances {:app {:http-server 9090
:http-port 9090}}}
(-> #::ds{:defs {:app {:http-server #::ds{:start config-port
:config {:port (ds/local-ref [:http-port])}}
:http-port 9090}}}
(ds/signal ::ds/start)
(select-keys [::ds/instances]))))))
(deftest group-ref-test
(testing "referred group is passed to referrer"
(is (= #::ds{:instances {:env {:http-port 9090
:timeout 5000}
:app {:http-server {:http-port 9090
:timeout 5000}}}}
(-> #::ds{:defs {:env {:http-port #::ds{:start 9090}
:timeout #::ds{:start 5000}}
:app {:http-server #::ds{:start (fn [opts] (get-in opts [::ds/config :env]))
:config {:env (ds/ref [:env])}}}}}
(ds/signal ::ds/start)
(select-keys [::ds/instances]))))))
(deftest signal-constant-test
(testing "can forego a map for component def if value should be a constant"
(is (= #::ds{:instances {:env {:http-port 9090}
:app {:http-server 9090}}}
(-> #::ds{:defs {:env {:http-port 9090}
:app {:http-server #::ds{:start config-port
:config {:port (ds/ref [:env :http-port])}}}}}
(ds/signal ::ds/start)
(select-keys [::ds/instances]))))))
(deftest validate-component
(let [schema (m/schema int?)]
(is (= #::ds{:out {:validation {:env {:http-port {:schema schema
:value "9090"
:errors [{:path []
:in []
:schema schema
:value "9090"}]}}}}}
(-> #::ds{:base {::ds/post-start ds/validate-instance-with-malli}
:defs {:env {:http-port #::ds{:start "9090"
:schema schema}}
:app {:http-server #::ds{:start config-port
:config {:port (ds/ref [:env :http-port])}}}}}
(ds/signal ::ds/start)
(select-keys [::ds/out]))))))
(deftest lifecycle-values-ignored-when-not-system
(let [expected #::ds{:instances {:env {:http-port 9090}
:app {:http-server 9090}}}
system #::ds{:defs {:env {:http-port #::ds{:start 9090}}
:app {:http-server #::ds{:start config-port
:config {:port (ds/ref [:env :http-port])}}}}}]
(is (= expected
(-> system
(assoc-in [::ds/defs :app :http-server ::ds/pre-start] (constantly nil))
(ds/signal ::ds/start)
(select-keys [::ds/instances]))))
(is (= expected
(-> system
(assoc-in [::ds/defs :app :http-server ::ds/post-start] (constantly nil))
(ds/signal ::ds/start)
(select-keys [::ds/instances]))))))
(deftest gen-signal-computation-graph-test
(let [system (#'ds/gen-graphs #::ds{:defs {:env {:http-port 9090}
:app {:http-server {:port (ds/ref [:env :http-port])}}}})]
(is (= (->> [[:env :http-port :pre-start]
[:env :http-port :start]
[:env :http-port :post-start]
[:app :http-server :pre-start]
[:app :http-server :start]
[:app :http-server :post-start]]
(partition 2 1)
(apply lg/add-edges (lg/digraph)))
(#'ds/gen-signal-computation-graph system :start :reverse-topsort)))))
(deftest channel-fns-test
(testing "can chain channel fns"
(is (= #::ds{:instances {:app {:http-server 9090
:http-port 9090}}
:out {:info {:app {:http-server "info"}}}}
(-> #::ds{:defs {:app {:http-server #::ds{:start (fn [{:keys [::ds/config ->instance ->info]}]
(-> (->instance (:port config))
(->info "info")))
:config {:port (ds/local-ref [:http-port])}}
:http-port 9090}}}
(ds/signal ::ds/start)
(select-keys [::ds/instances ::ds/out]))))))
(deftest subsystem-test
(let [subsystem #::ds{:defs
{:local {:port 9090}
:app
{:local #::ds{:start (fn [_] :local)}
:server #::ds{:start (fn [{:keys [::ds/config]}] config)
:post-start (fn [{:keys [->info]}]
(->info "started"))
:stop (fn [{:keys [::ds/instance]}]
{:prev instance
:now :stopped})
:post-stop (fn [{:keys [->info]}]
(->info "stopped"))
:config {:job-queue (ds/ref [:common-services :job-queue])
:db (ds/ref [:common-services :db])
:port (ds/ref [:local :port])
:local (ds/local-ref [:local])}}}}}
started (-> #::ds{:defs
{:env
{:app-name "foo.app"}
:common-services
{:job-queue "job queue"
:db "db"}
:sub-systems
{:system-1 (ds/subsystem-component
subsystem
#{(ds/ref [:common-services :job-queue])
(ds/ref [:common-services :db])})
:system-2 (ds/subsystem-component
subsystem
#{(ds/ref [:common-services])})}}}
(ds/signal ::ds/start))]
(is (= {:job-queue "job queue"
:db "db"
:port 9090
:local :local}
(get-in started [::ds/instances :sub-systems :system-1 ::ds/instances :app :server])
(get-in started [::ds/instances :sub-systems :system-2 ::ds/instances :app :server])))
(is (= "started"
(get-in started [::ds/out :info :sub-systems :system-1 :app :server])
(get-in started [::ds/out :info :sub-systems :system-2 :app :server])))
(let [stopped (ds/signal started ::ds/stop)]
(is (= {:prev {:job-queue "job queue"
:db "db"
:port 9090
:local :local}
:now :stopped}
(get-in stopped [::ds/instances :sub-systems :system-1 ::ds/instances :app :server])
(get-in stopped [::ds/instances :sub-systems :system-2 ::ds/instances :app :server])))
(is (= "stopped"
(get-in stopped [::ds/out :info :sub-systems :system-1 :app :server])
(get-in stopped [::ds/out :info :sub-systems :system-2 :app :server]))))))
(deftest select-components-test
(testing "if you specify components, the union of their subgraphs is used"
(let [system-def {::ds/defs {:env {:http-port #::ds{:start 9090}}
:app {:http-server #::ds{:start config-port
:stop "stopped http-server"
:config {:port (ds/ref [:env :http-port])}}
:db #::ds{:start "db"
:stop "stopped db"}}}}
started (ds/signal system-def ::ds/start #{[:app :http-server]})]
(is (= {::ds/instances {:app {:http-server 9090}
:env {:http-port 9090}}}
(select-keys started [::ds/instances])))
(testing "the selected components are retained beyond the start"
(is (= {::ds/instances {:app {:http-server "stopped http-server"}
:env {:http-port 9090}}}
(-> started
(ds/signal ::ds/stop)
(select-keys [::ds/instances])))))
(testing "groups you can select groups"
(is (= {::ds/instances {:env {:http-port 9090}}}
(-> (ds/signal system-def ::ds/start #{:env})
(select-keys [::ds/instances]))))))))
(deftest ref-undefined-test
(is (thrown-with-msg?
#?(:clj clojure.lang.ExceptionInfo
:cljs js/Object)
#"Invalid ref"
(ds/signal {::ds/defs {:group-a {:foo :foo}
:group-b {:component {:ref-1 (ds/ref [:group-a :foo])
:ref-2 (ds/ref [:group-a :nonexistent-component])}}}}
::ds/start)))
(is (thrown-with-msg?
#?(:clj clojure.lang.ExceptionInfo
:cljs js/Object)
#"Invalid group ref"
(ds/signal {::ds/defs {:group {:component {:ref (ds/ref [:nonexistent :ref])}}}}
::ds/start)))
(is (thrown-with-msg?
#?(:clj clojure.lang.ExceptionInfo
:cljs js/Object)
#"Invalid group ref"
(ds/signal {::ds/defs {:group {:component {:ref (ds/ref [:nonexistent])}}}}
::ds/start))))
(defmethod ds/named-system ::system-config-test
[_]
{::ds/defs {:group {:component-a 1
:component-b 2
:component-c 3}}})
(deftest assoc-many-test
(is (= {:a {:b 1}
:c {:d 2}}
(ds/assoc-many {} {[:a :b] 1
[:c :d] 2})))
(is (= {:foo {:a {:b 1}
:c {:d 2}}}
(ds/assoc-many {}
[:foo]
{[:a :b] 1
[:c :d] 2}))))
(deftest system-config-test
(is (= {::ds/defs {:group {:component-a 1
:component-b 2
:component-c 4
:component-d 5}}}
(ds/system ::system-config-test
{[:group :component-c] 4
[:group :component-d] 5}))))
(deftest signal-helper-test
(testing "basic signal helpers work"
(is (= {::ds/instances {:app {:boop "boop"}}}
(-> {::ds/defs {:app {:boop #::ds{:start "boop"}}}}
(ds/start)
(select-keys [::ds/instances]))))
(is (= {::ds/instances {:app {:boop "boop and boop again"}}}
(-> {::ds/defs {:app {:boop #::ds{:start "boop"
:stop (fn [{:keys [::ds/instance]}]
(str instance " and boop again"))}}}}
(ds/start)
(ds/stop)
(select-keys [::ds/instances]))))))
(deftest signal-helper-overrides-test
(is (= {::ds/instances {:app {:boop "boop"}}}
(-> {::ds/defs {:app {:boop #::ds{:start "no boop"}}}}
(ds/start {[:app :boop ::ds/start] "boop"})
(select-keys [::ds/instances])))))
(deftest recognized-signals-exception-test
(is (thrown-with-msg?
#?(:clj clojure.lang.ExceptionInfo
:cljs js/Object)
#"Signal :foo is not recognized"
(ds/signal {::ds/defs {:group {:component "constant"}}}
:foo)))
(testing "should not throw exception"
(is (ds/signal {::ds/defs {:group {:component "constant"}}
::ds/signals (merge ds/default-signals {:foo {:order :topsort}})}
:foo))))
(deftest required-component-test
(is (thrown?
#?(:clj clojure.lang.ExceptionInfo
:cljs js/Object)
(ds/signal {::ds/defs {:group {:component ds/required-component}}}
::ds/start)))
(try (ds/signal {::ds/defs {:group {:component ds/required-component}}}
::ds/start)
(catch #?(:clj Exception :cljs :default) e
(is (= [:group :component]
(:component (ex-data e)))))))
(deftest get-registry-instance-test
(let [system (-> {::ds/registry {:the-boop [:app :boop]}
::ds/defs {:app {:boop #::ds{:start "no boop"}}}}
(ds/start))]
(is (= "no boop" (ds/registry-instance system :the-boop)))))
(deftest registry-instance-exception-test
(is (thrown-with-msg?
#?(:clj clojure.lang.ExceptionInfo
:cljs js/Object)
#":donut.system/registry does not contain registry-key"
(-> {::ds/defs {:group {:component "constant"}}}
ds/start
(ds/registry-instance :no-registry-key))))
(is (thrown-with-msg?
#?(:clj clojure.lang.ExceptionInfo
:cljs js/Object)
#"No component instance found for registry key."
(-> {::ds/registry {:a-key [:bad :path]}
::ds/defs {:group {:component "constant"}}}
ds/start
(ds/registry-instance :a-key)))))
(deftest component-ids-test
(is (= [[:group-a :a]
[:group-a :b]
[:group-b :a]
[:group-b :b]
[:group-b :c]]
(ds/component-ids {::ds/defs {:group-a {:a nil
:b nil}
:group-b {:a nil
:b nil
:c nil}}}))))
(deftest status-signal-test
(is (= {:group-a {:a :status-a}}
(::ds/status
(ds/signal {::ds/defs
{:group-a
{:a #::ds{:status (fn [_] :status-a)}}}}
::ds/status)))))
(deftest describe-system-test
(is (= {:group-a
{:a
{:name [:group-a :a]
:config nil
:resolved-config nil
:instance ["a-component"]
:status :status-a
:doc "a component doc"
:dependencies #{}}
:b
{:name [:group-a :b]
:config nil
:resolved-config nil
:instance "b-component"
:status :b-component
:doc nil
:dependencies #{}}}}
(ds/describe-system
(ds/start
{::ds/defs {:group-a {:a #::ds{:start (with-meta ["a-component"] {:doc "a component doc"})
:status (fn [_] :status-a)}
:b #::ds{:start (fn [_] "b-component")
:status (fn [{:keys [::ds/instance] :as x}]
(keyword instance))}}}})))))
(deftest with-*system*-test
(is (= {:group-a {:a "component a"
:b "component b"}}
(ds/with-*system*
{::ds/defs {:group-a {:a #::ds{:start "component a"}
:b #::ds{:start "component b"}}}}
(::ds/instances ds/*system*)
))))
(deftest update-many-test
(is (= {:a {:b "FOO"
:c 1}}
(ds/update-many
{:a {:b "foo"
:c 0}}
{[:a :b] str/upper-case
[:a :c] inc}))))
|
fe08446423c87c4252ef328d07dbe1bf5b19bedee33ee119ec59f6e9347c1a3c | haskell-works/cabal-cache | S3.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TypeApplications #
module HaskellWorks.CabalCache.AWS.S3
( uriToS3Uri,
headS3Uri,
getS3Uri,
copyS3Uri,
putObject,
) where
import Control.Lens ((^.))
import Control.Monad (void, unless)
import Control.Monad.Catch (MonadCatch(..))
import Control.Monad.Except (MonadError)
import Control.Monad.IO.Class (MonadIO(..))
import Control.Monad.Trans.AWS (RsBody)
import Control.Monad.Trans.Except (ExceptT)
import Control.Monad.Trans.Resource (MonadResource, MonadUnliftIO, liftResourceT, runResourceT)
import Data.Conduit.Lazy (lazyConsume)
import HaskellWorks.CabalCache.AppError (AwsError(..))
import HaskellWorks.CabalCache.Error (CopyFailed(..), UnsupportedUri(..))
import HaskellWorks.CabalCache.Show (tshow)
import Network.AWS (MonadAWS, HasEnv)
import Network.AWS.Data (ToText(..), fromText)
import Network.URI (URI)
import qualified Control.Monad.Oops as OO
import qualified Data.ByteString.Lazy as LBS
import qualified HaskellWorks.CabalCache.IO.Console as CIO
import qualified HaskellWorks.CabalCache.AWS.Error as AWS
import qualified HaskellWorks.CabalCache.AWS.S3.URI as AWS
import qualified HaskellWorks.CabalCache.URI as URI
import qualified Network.AWS as AWS
import qualified Network.AWS.Data.Body as AWS
import qualified Network.AWS.S3 as AWS
import qualified System.IO as IO
-- | Access the response body as a lazy bytestring
lazyByteString :: MonadResource m => RsBody -> m LBS.ByteString
lazyByteString rsBody = liftResourceT $ LBS.fromChunks <$> lazyConsume (AWS._streamBody rsBody)
unsafeDownloadRequest :: (MonadAWS m, MonadResource m)
=> AWS.GetObject
-> m LBS.ByteString
unsafeDownloadRequest req = do
resp <- AWS.send req
lazyByteString (resp ^. AWS.gorsBody)
unsafeDownload :: (MonadAWS m, MonadResource m)
=> AWS.BucketName
-> AWS.ObjectKey
-> m LBS.ByteString
unsafeDownload bucketName objectKey = unsafeDownloadRequest (AWS.getObject bucketName objectKey)
uriToS3Uri :: URI -> Either UnsupportedUri AWS.S3Uri
uriToS3Uri uri = case fromText @AWS.S3Uri (tshow uri) of
Right s3Uri -> Right s3Uri
Left msg -> Left $ UnsupportedUri uri $ "Unable to parse URI" <> tshow msg
headS3Uri :: ()
=> MonadError (OO.Variant e) m
=> e `OO.CouldBe` AwsError
=> e `OO.CouldBe` UnsupportedUri
=> MonadCatch m
=> MonadResource m
=> HasEnv r
=> r
-> URI
-> m AWS.HeadObjectResponse
headS3Uri envAws uri = do
AWS.S3Uri b k <- OO.hoistEither $ uriToS3Uri (URI.reslashUri uri)
AWS.handleAwsError $ AWS.runAWS envAws $ AWS.send $ AWS.headObject b k
putObject :: ()
=> e `OO.CouldBe` AwsError
=> e `OO.CouldBe` UnsupportedUri
=> MonadCatch m
=> MonadUnliftIO m
=> HasEnv r
=> AWS.ToBody a
=> r
-> URI
-> a
-> ExceptT (OO.Variant e) m ()
putObject envAws uri lbs = do
AWS.S3Uri b k <- OO.hoistEither $ uriToS3Uri (URI.reslashUri uri)
let req = AWS.toBody lbs
let po = AWS.putObject b k req
AWS.handleAwsError $ void $ OO.suspend runResourceT $ AWS.runAWS envAws $ AWS.send po
getS3Uri :: ()
=> MonadError (OO.Variant e) m
=> e `OO.CouldBe` AwsError
=> e `OO.CouldBe` UnsupportedUri
=> MonadCatch m
=> MonadResource m
=> HasEnv r
=> r
-> URI
-> m LBS.ByteString
getS3Uri envAws uri = do
AWS.S3Uri b k <- OO.hoistEither $ uriToS3Uri (URI.reslashUri uri)
AWS.handleAwsError $ AWS.runAWS envAws $ unsafeDownload b k
copyS3Uri :: ()
=> HasEnv r
=> MonadUnliftIO m
=> e `OO.CouldBe` AwsError
=> e `OO.CouldBe` CopyFailed
=> e `OO.CouldBe` UnsupportedUri
=> r
-> URI
-> URI
-> ExceptT (OO.Variant e) m ()
copyS3Uri envAws source target = do
AWS.S3Uri sourceBucket sourceObjectKey <- OO.hoistEither $ uriToS3Uri (URI.reslashUri source)
AWS.S3Uri targetBucket targetObjectKey <- OO.hoistEither $ uriToS3Uri (URI.reslashUri target)
let copyObjectRequest = AWS.copyObject targetBucket (toText sourceBucket <> "/" <> toText sourceObjectKey) targetObjectKey
response <- OO.suspend runResourceT (AWS.runAWS envAws $ AWS.send copyObjectRequest)
let responseCode = response ^. AWS.corsResponseStatus
unless (200 <= responseCode && responseCode < 300) do
liftIO $ CIO.hPutStrLn IO.stderr $ "Error in S3 copy: " <> tshow response
OO.throw CopyFailed
| null | https://raw.githubusercontent.com/haskell-works/cabal-cache/841549c4f32da556125a6baa0c1ce9dc944658b4/src/HaskellWorks/CabalCache/AWS/S3.hs | haskell | # LANGUAGE OverloadedStrings #
| Access the response body as a lazy bytestring | # LANGUAGE TypeApplications #
module HaskellWorks.CabalCache.AWS.S3
( uriToS3Uri,
headS3Uri,
getS3Uri,
copyS3Uri,
putObject,
) where
import Control.Lens ((^.))
import Control.Monad (void, unless)
import Control.Monad.Catch (MonadCatch(..))
import Control.Monad.Except (MonadError)
import Control.Monad.IO.Class (MonadIO(..))
import Control.Monad.Trans.AWS (RsBody)
import Control.Monad.Trans.Except (ExceptT)
import Control.Monad.Trans.Resource (MonadResource, MonadUnliftIO, liftResourceT, runResourceT)
import Data.Conduit.Lazy (lazyConsume)
import HaskellWorks.CabalCache.AppError (AwsError(..))
import HaskellWorks.CabalCache.Error (CopyFailed(..), UnsupportedUri(..))
import HaskellWorks.CabalCache.Show (tshow)
import Network.AWS (MonadAWS, HasEnv)
import Network.AWS.Data (ToText(..), fromText)
import Network.URI (URI)
import qualified Control.Monad.Oops as OO
import qualified Data.ByteString.Lazy as LBS
import qualified HaskellWorks.CabalCache.IO.Console as CIO
import qualified HaskellWorks.CabalCache.AWS.Error as AWS
import qualified HaskellWorks.CabalCache.AWS.S3.URI as AWS
import qualified HaskellWorks.CabalCache.URI as URI
import qualified Network.AWS as AWS
import qualified Network.AWS.Data.Body as AWS
import qualified Network.AWS.S3 as AWS
import qualified System.IO as IO
lazyByteString :: MonadResource m => RsBody -> m LBS.ByteString
lazyByteString rsBody = liftResourceT $ LBS.fromChunks <$> lazyConsume (AWS._streamBody rsBody)
unsafeDownloadRequest :: (MonadAWS m, MonadResource m)
=> AWS.GetObject
-> m LBS.ByteString
unsafeDownloadRequest req = do
resp <- AWS.send req
lazyByteString (resp ^. AWS.gorsBody)
unsafeDownload :: (MonadAWS m, MonadResource m)
=> AWS.BucketName
-> AWS.ObjectKey
-> m LBS.ByteString
unsafeDownload bucketName objectKey = unsafeDownloadRequest (AWS.getObject bucketName objectKey)
uriToS3Uri :: URI -> Either UnsupportedUri AWS.S3Uri
uriToS3Uri uri = case fromText @AWS.S3Uri (tshow uri) of
Right s3Uri -> Right s3Uri
Left msg -> Left $ UnsupportedUri uri $ "Unable to parse URI" <> tshow msg
headS3Uri :: ()
=> MonadError (OO.Variant e) m
=> e `OO.CouldBe` AwsError
=> e `OO.CouldBe` UnsupportedUri
=> MonadCatch m
=> MonadResource m
=> HasEnv r
=> r
-> URI
-> m AWS.HeadObjectResponse
headS3Uri envAws uri = do
AWS.S3Uri b k <- OO.hoistEither $ uriToS3Uri (URI.reslashUri uri)
AWS.handleAwsError $ AWS.runAWS envAws $ AWS.send $ AWS.headObject b k
putObject :: ()
=> e `OO.CouldBe` AwsError
=> e `OO.CouldBe` UnsupportedUri
=> MonadCatch m
=> MonadUnliftIO m
=> HasEnv r
=> AWS.ToBody a
=> r
-> URI
-> a
-> ExceptT (OO.Variant e) m ()
putObject envAws uri lbs = do
AWS.S3Uri b k <- OO.hoistEither $ uriToS3Uri (URI.reslashUri uri)
let req = AWS.toBody lbs
let po = AWS.putObject b k req
AWS.handleAwsError $ void $ OO.suspend runResourceT $ AWS.runAWS envAws $ AWS.send po
getS3Uri :: ()
=> MonadError (OO.Variant e) m
=> e `OO.CouldBe` AwsError
=> e `OO.CouldBe` UnsupportedUri
=> MonadCatch m
=> MonadResource m
=> HasEnv r
=> r
-> URI
-> m LBS.ByteString
getS3Uri envAws uri = do
AWS.S3Uri b k <- OO.hoistEither $ uriToS3Uri (URI.reslashUri uri)
AWS.handleAwsError $ AWS.runAWS envAws $ unsafeDownload b k
copyS3Uri :: ()
=> HasEnv r
=> MonadUnliftIO m
=> e `OO.CouldBe` AwsError
=> e `OO.CouldBe` CopyFailed
=> e `OO.CouldBe` UnsupportedUri
=> r
-> URI
-> URI
-> ExceptT (OO.Variant e) m ()
copyS3Uri envAws source target = do
AWS.S3Uri sourceBucket sourceObjectKey <- OO.hoistEither $ uriToS3Uri (URI.reslashUri source)
AWS.S3Uri targetBucket targetObjectKey <- OO.hoistEither $ uriToS3Uri (URI.reslashUri target)
let copyObjectRequest = AWS.copyObject targetBucket (toText sourceBucket <> "/" <> toText sourceObjectKey) targetObjectKey
response <- OO.suspend runResourceT (AWS.runAWS envAws $ AWS.send copyObjectRequest)
let responseCode = response ^. AWS.corsResponseStatus
unless (200 <= responseCode && responseCode < 300) do
liftIO $ CIO.hPutStrLn IO.stderr $ "Error in S3 copy: " <> tshow response
OO.throw CopyFailed
|
f7662a0cec859760ce4ff4c9e4d5a024569af4132cd0673c10fee9f2f52ae81b | metametadata/carry | project.clj | (defproject
shopping-cart "0.1.0-SNAPSHOT"
:dependencies [[org.clojure/clojure "1.8.0"]
[org.clojure/clojurescript "1.9.229"]
[reagent "0.6.0" :exclusions [cljsjs/react]]
[cljsjs/react-with-addons "15.3.1-0"]
[org.clojure/core.match "0.3.0-alpha4"]
[datascript "0.15.4"]]
:pedantic? :abort
:plugins [[lein-cljsbuild "1.1.4"]
[lein-figwheel "0.5.8" :exclusions [org.clojure/clojure]]]
:clean-targets ^{:protect false} ["resources/public/js/compiled" "resources/private" "target"]
:cljsbuild {:builds [{:id "dev"
:source-paths ["src"
"../../src"
"../../contrib/reagent/src"]
:compiler {:main app.core
:asset-path "js/compiled/out"
:output-to "resources/public/js/compiled/frontend.js"
:output-dir "resources/public/js/compiled/out"
:source-map-timestamp true
:compiler-stats true
:parallel-build false}
:figwheel {:on-jsload "app.core/on-jsload"
:before-jsload "app.core/before-jsload"}}
{:id "min"
:source-paths ["src"
"../../src"
"../../contrib/reagent/src"]
:compiler {:main app.core
:output-to "resources/public/js/compiled/frontend.js"
:optimizations :advanced
:pretty-print false
:compiler-stats true
:parallel-build false}}]})
| null | https://raw.githubusercontent.com/metametadata/carry/fa5c7cd0d8f1b71edca70330acc97c6245638efb/examples/shopping-cart/project.clj | clojure | (defproject
shopping-cart "0.1.0-SNAPSHOT"
:dependencies [[org.clojure/clojure "1.8.0"]
[org.clojure/clojurescript "1.9.229"]
[reagent "0.6.0" :exclusions [cljsjs/react]]
[cljsjs/react-with-addons "15.3.1-0"]
[org.clojure/core.match "0.3.0-alpha4"]
[datascript "0.15.4"]]
:pedantic? :abort
:plugins [[lein-cljsbuild "1.1.4"]
[lein-figwheel "0.5.8" :exclusions [org.clojure/clojure]]]
:clean-targets ^{:protect false} ["resources/public/js/compiled" "resources/private" "target"]
:cljsbuild {:builds [{:id "dev"
:source-paths ["src"
"../../src"
"../../contrib/reagent/src"]
:compiler {:main app.core
:asset-path "js/compiled/out"
:output-to "resources/public/js/compiled/frontend.js"
:output-dir "resources/public/js/compiled/out"
:source-map-timestamp true
:compiler-stats true
:parallel-build false}
:figwheel {:on-jsload "app.core/on-jsload"
:before-jsload "app.core/before-jsload"}}
{:id "min"
:source-paths ["src"
"../../src"
"../../contrib/reagent/src"]
:compiler {:main app.core
:output-to "resources/public/js/compiled/frontend.js"
:optimizations :advanced
:pretty-print false
:compiler-stats true
:parallel-build false}}]})
| |
5ee9a3c2ac6340a12618804724c597b3ae2f12dca568ec9a1cadc21185c8b7da | erlangonrails/devdb | node_watcher_qc.erl | %% -------------------------------------------------------------------
%%
%% riak_core: Core Riak Application
%%
Copyright ( c ) 2007 - 2010 Basho Technologies , Inc. All Rights Reserved .
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% -------------------------------------------------------------------
-module(node_watcher_qc).
-ifdef(EQC).
-include_lib("eqc/include/eqc.hrl").
-include_lib("eqc/include/eqc_statem.hrl").
-include_lib("eunit/include/eunit.hrl").
-compile(export_all).
-record(state, { up_nodes = [],
services = [],
service_pids = [],
peers = []}).
-define(QC_OUT(P),
eqc:on_output(fun(Str, Args) -> io:format(user, Str, Args) end, P)).
-define(ORDSET(L), ordsets:from_list(L)).
qc_test_() ->
{timeout, 120, fun() -> ?assert(eqc:quickcheck(?QC_OUT(prop_main()))) end}.
prop_main() ->
Initialize necessary env settings
application:load(riak_core),
application:set_env(riak_core, gossip_interval, 250),
application:set_env(riak_core, ring_creation_size, 8),
%% Start supporting processes
riak_core_ring_events:start_link(),
riak_core_node_watcher_events:start_link(),
?FORALL(Cmds, commands(?MODULE),
begin
Setup ETS table to broadcasts
ets:new(?MODULE, [ordered_set, named_table, public]),
ets:insert_new(?MODULE, {bcast_id, 0}),
%% Start the watcher
{ok, Pid} = riak_core_node_watcher:start_link(),
%% Internal call to the node watcher to override default broadcast mechanism
gen_server:call(riak_core_node_watcher, {set_bcast_mod, ?MODULE, on_broadcast}),
%% Run the test
{_H, _S, Res} = run_commands(?MODULE, Cmds),
and kill our PID
unlink(Pid),
kill_and_wait(Pid),
%% Delete the ETS table
ets:delete(?MODULE),
case Res of
ok -> ok;
_ -> io:format(user, "QC result: ~p\n", [Res])
end,
aggregate(command_names(Cmds), Res == ok)
end).
%% ====================================================================
%% eqc_statem callbacks
%% ====================================================================
initial_state() ->
#state{ up_nodes = [node()] }.
command(S) ->
oneof([
{call, ?MODULE, ring_update, [g_ring_nodes()]},
{call, ?MODULE, local_service_up, [g_service()]},
{call, ?MODULE, local_service_down, [g_service()]},
{call, ?MODULE, local_service_kill, [g_service(), S]},
{call, ?MODULE, local_node_up, []},
{call, ?MODULE, local_node_down, []},
{call, ?MODULE, remote_service_up, [g_node(), g_services()]},
{call, ?MODULE, remote_service_down, [g_node()]},
{call, ?MODULE, remote_service_down_disterl, [g_node()]},
{call, ?MODULE, wait_for_bcast, []}
]).
precondition(S, {call, _, local_service_kill, [Service, S]}) ->
orddict:is_key(Service, S#state.service_pids);
precondition(S, {call, _, wait_for_bcast, _}) ->
is_node_up(node(), S);
precondition(_, _) ->
true.
next_state(S, Res, {call, _, local_service_up, [Service]}) ->
S2 = service_up(node(), Service, S),
Pids = orddict:store(Service, Res, S2#state.service_pids),
S2#state { service_pids = Pids };
next_state(S, _Res, {call, _, local_service_down, [Service]}) ->
S2 = service_down(node(), Service, S),
Pids = orddict:erase(Service, S2#state.service_pids),
S2#state { service_pids = Pids };
next_state(S, _Res, {call, _, local_service_kill, [Service, _]}) ->
S2 = service_down(node(), Service, S),
Pids = orddict:erase(Service, S2#state.service_pids),
S2#state { service_pids = Pids };
next_state(S, _Res, {call, _, local_node_up, []}) ->
node_up(node(), S);
next_state(S, _Res, {call, _, local_node_down, []}) ->
node_down(node(), S);
next_state(S, _Res, {call, _, remote_service_up, [Node, Services]}) ->
peer_up(Node, Services, S);
next_state(S, _Res, {call, _, Fn, [Node]})
when Fn == remote_service_down; Fn == remote_service_down_disterl ->
peer_down(Node, S);
next_state(S, _Res, {call, _, wait_for_bcast, _}) ->
S;
next_state(S, _Res, {call, _, ring_update, [Nodes]}) ->
Peers = ordsets:del_element(node(), ordsets:from_list(Nodes)),
peer_filter(S#state { peers = Peers }).
postcondition(S, {call, _, local_service_up, [Service]}, _Res) ->
S2 = service_up(node(), Service, S),
validate_broadcast(S, S2, service),
deep_validate(S2);
postcondition(S, {call, _, local_service_down, [Service]}, _Res) ->
S2 = service_down(node(), Service, S),
validate_broadcast(S, S2, service),
deep_validate(S2);
postcondition(S, {call, _, local_service_kill, [Service, _]}, _Res) ->
S2 = service_down(node(), Service, S),
validate_broadcast(S, S2, service),
deep_validate(S2);
postcondition(S, {call, _, local_node_up, _}, _Res) ->
S2 = node_up(node(), S),
validate_broadcast(S, S2, node),
deep_validate(S2);
postcondition(S, {call, _, local_node_down, _}, _Res) ->
S2 = node_down(node(), S),
validate_broadcast(S, S2, node),
deep_validate(S2);
postcondition(S, {call, _, remote_service_up, [Node, Services]}, _Res) ->
%% If the remote service WAS down, expect a broadcast to it, otherwise no
%% bcast should be present
Bcasts = broadcasts(),
case is_peer(Node, S) andalso not is_node_up(Node, S) of
true ->
case is_node_up(node(), S) of
true ->
ExpServices = services(node(), S),
?assertEqual({{up, node(), ExpServices}, [Node]}, hd(Bcasts));
false ->
?assertEqual({{down, node()}, [Node]}, hd(Bcasts))
end;
false ->
?assertEqual([], Bcasts)
end,
S2 = peer_up(Node, Services, S),
deep_validate(S2);
postcondition(S, {call, _, Fn, [Node]}, _Res)
when Fn == remote_service_down; Fn == remote_service_down_disterl ->
?assertEqual([], broadcasts()),
S2 = case is_peer(Node, S) of
true ->
node_down(Node, S);
false ->
S
end,
deep_validate(S2);
postcondition(S, {call, _, wait_for_bcast, _}, _Res) ->
validate_broadcast(S, S, service);
postcondition(S, {call, _, ring_update, [Nodes]}, _Res) ->
Ring update should generate a broadcast to all NEW peers
Bcasts = broadcasts(),
Peers = ordsets:del_element(node(), ordsets:from_list(Nodes)),
NewPeers = ordsets:subtract(Peers, S#state.peers),
case is_node_up(node(), S) of
true ->
ExpServices = services(node(), S),
?assertEqual({{up, node(), ExpServices}, NewPeers}, hd(Bcasts));
false ->
?assertEqual({{down, node()}, NewPeers}, hd(Bcasts))
end,
S2 = peer_filter(S#state { peers = Peers }),
deep_validate(S2).
deep_validate(S) ->
%% Verify that the list of services in the state match what the node watcher reports
ExpAllServices = services(S),
ActAllServices = riak_core_node_watcher:services(),
?assertEqual(ExpAllServices, ActAllServices),
%% Now that we verified the list of services match, build a list of node lists, per
%% service.
ExpNodes = ?ORDSET([snodes(Svc, S) || Svc <- ExpAllServices]),
ActNodes = ?ORDSET([?ORDSET(riak_core_node_watcher:nodes(Svc)) || Svc <- ExpAllServices]),
?assertEqual(ExpNodes, ActNodes),
true.
validate_broadcast(S0, Sfinal, Op) ->
Bcasts = broadcasts(),
Transition = {is_node_up(node(), S0), is_node_up(node(), Sfinal), Op},
ExpPeers = Sfinal#state.peers,
case Transition of
{false, true, _} -> %% down -> up
ExpServices = services(node(), Sfinal),
?assertEqual({{up, node(), ExpServices}, ExpPeers}, hd(Bcasts));
{true, false, _} -> %% up -> down
?assertEqual({{down, node()}, ExpPeers}, hd(Bcasts));
{true, true, service} -> %% up -> up (service change)
ExpServices = services(node(), Sfinal),
?assertEqual({{up, node(), ExpServices}, ExpPeers}, hd(Bcasts));
_ ->
?assertEqual([], Bcasts)
end,
true.
%% ====================================================================
%% Generators
%% ====================================================================
g_service() ->
oneof([s1, s2, s3, s4]).
g_node() ->
oneof(['n1@127.0.0.1', 'n2@127.0.0.1', 'n3@127.0.0.1']).
g_services() ->
list(elements([s1, s2, s3, s4])).
g_ring_nodes() ->
vector(app_helper:get_env(riak_core, ring_creation_size),
oneof([node(), 'n1@127.0.0.1', 'n2@127.0.0.1', 'n3@127.0.0.1'])).
%% ====================================================================
%% Calls
%% ====================================================================
local_service_up(Service) ->
Pid = spawn(fun() -> service_loop() end),
ok = riak_core_node_watcher:service_up(Service, Pid),
Pid.
local_service_down(Service) ->
ok = riak_core_node_watcher:service_down(Service).
local_service_kill(Service, State) ->
Avsn0 = riak_core_node_watcher:avsn(),
Pid = orddict:fetch(Service, State#state.service_pids),
kill_and_wait(Pid),
wait_for_avsn(Avsn0).
local_node_up() ->
riak_core_node_watcher:node_up().
local_node_down() ->
riak_core_node_watcher:node_down().
remote_service_up(Node, Services) ->
Avsn0 = riak_core_node_watcher:avsn(),
gen_server:cast(riak_core_node_watcher, {up, Node, Services}),
wait_for_avsn(Avsn0).
remote_service_down(Node) ->
Avsn0 = riak_core_node_watcher:avsn(),
gen_server:cast(riak_core_node_watcher, {down, Node}),
wait_for_avsn(Avsn0).
remote_service_down_disterl(Node) ->
Avsn0 = riak_core_node_watcher:avsn(),
riak_core_node_watcher ! {nodedown, Node},
wait_for_avsn(Avsn0).
wait_for_bcast() ->
{ok, Interval} = application:get_env(riak_core, gossip_interval),
timer:sleep(Interval + 50).
ring_update(Nodes) ->
Ring = build_ring(Nodes),
Avsn0 = riak_core_node_watcher:avsn(),
gen_server:cast(riak_core_node_watcher, {ring_update, Ring}),
wait_for_avsn(Avsn0),
?ORDSET(Nodes).
%% ====================================================================
State functions
%% ====================================================================
node_up(Node, S) ->
S#state { up_nodes = ordsets:add_element(Node, S#state.up_nodes) }.
node_down(Node, S) ->
S#state { up_nodes = ordsets:del_element(Node, S#state.up_nodes) }.
service_up(Node, Service, S) ->
S#state { services = ordsets:add_element({Node, Service}, S#state.services) }.
services_up(Node, Services, S) ->
NewServices = ?ORDSET([{Node, Svc} || Svc <- Services]),
OldServices = [{N, Svc} || {N, Svc} <- S#state.services,
Node /= N],
S#state { services = ordsets:union(NewServices, OldServices) }.
service_down(Node, Svc, S) ->
S#state { services = ordsets:del_element({Node, Svc}, S#state.services) }.
is_node_up(Node, S) ->
ordsets:is_element(Node, S#state.up_nodes).
is_peer(Node, S) ->
ordsets:is_element(Node, S#state.peers).
peer_up(Node, Services, S) ->
case is_peer(Node, S) of
true ->
node_up(Node, services_up(Node, Services, S));
false ->
S
end.
peer_down(Node, S) ->
case is_peer(Node, S) of
true ->
Services = [{N, Svc} || {N, Svc} <- S#state.services,
N /= Node],
node_down(Node, S#state { services = Services });
false ->
S
end.
peer_filter(S) ->
ThisNode = node(),
Services = [{N, Svc} || {N, Svc} <- S#state.services,
is_peer(N, S) orelse N == ThisNode],
UpNodes = [N || N <- S#state.up_nodes,
is_peer(N, S) orelse N == ThisNode],
S#state { services = Services, up_nodes = UpNodes }.
services(S) ->
?ORDSET([Svc || {N, Svc} <- S#state.services,
ordsets:is_element(N, S#state.up_nodes)]).
services(Node, S) ->
case ordsets:is_element(Node, S#state.up_nodes) of
true ->
all_services(Node, S);
false ->
[]
end.
snodes(S) ->
S#state.up_nodes.
snodes(Service, S) ->
?ORDSET([Node || {Node, Svc} <- S#state.services,
ordsets:is_element(Node, S#state.up_nodes),
Svc == Service]).
all_services(Node, S) ->
?ORDSET([Svc || {N, Svc} <- S#state.services,
N == Node]).
%% ====================================================================
Internal functions
%% ====================================================================
on_broadcast(Nodes, _Name, Msg) ->
Id = ets:update_counter(?MODULE, bcast_id, {2, 1}),
ets:insert_new(?MODULE, {Id, Msg, Nodes}).
broadcasts() ->
Bcasts = [list_to_tuple(L) || L <- ets:match(?MODULE, {'_', '$1', '$2'})],
ets:match_delete(?MODULE, {'_', '_', '_'}),
Bcasts.
kill_and_wait(Pid) ->
Mref = erlang:monitor(process, Pid),
exit(Pid, kill),
receive
{'DOWN', Mref, _, _, _} ->
ok
end.
wait_for_avsn(Avsn0) ->
case riak_core_node_watcher:avsn() of
Avsn0 ->
erlang:yield(),
wait_for_avsn(Avsn0);
_ ->
ok
end.
service_loop() ->
receive
_Any ->
service_loop()
end.
build_ring([Node | Rest]) ->
Inc = trunc(math:pow(2,160)-1) div app_helper:get_env(riak_core, ring_creation_size),
build_ring(Rest, 0, Inc, riak_core_ring:fresh(Node)).
build_ring([], _Id, _Inc, R) ->
R;
build_ring([Node | Rest], Id, Inc, R) ->
R2 = riak_core_ring:transfer_node(Id+Inc, Node, R),
build_ring(Rest, Id+Inc, Inc, R2).
-endif.
| null | https://raw.githubusercontent.com/erlangonrails/devdb/0e7eaa6bd810ec3892bfc3d933439560620d0941/dev/riak_core/test/node_watcher_qc.erl | erlang | -------------------------------------------------------------------
riak_core: Core Riak Application
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-------------------------------------------------------------------
Start supporting processes
Start the watcher
Internal call to the node watcher to override default broadcast mechanism
Run the test
Delete the ETS table
====================================================================
eqc_statem callbacks
====================================================================
If the remote service WAS down, expect a broadcast to it, otherwise no
bcast should be present
Verify that the list of services in the state match what the node watcher reports
Now that we verified the list of services match, build a list of node lists, per
service.
down -> up
up -> down
up -> up (service change)
====================================================================
Generators
====================================================================
====================================================================
Calls
====================================================================
====================================================================
====================================================================
====================================================================
==================================================================== | Copyright ( c ) 2007 - 2010 Basho Technologies , Inc. All Rights Reserved .
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
-module(node_watcher_qc).
-ifdef(EQC).
-include_lib("eqc/include/eqc.hrl").
-include_lib("eqc/include/eqc_statem.hrl").
-include_lib("eunit/include/eunit.hrl").
-compile(export_all).
-record(state, { up_nodes = [],
services = [],
service_pids = [],
peers = []}).
-define(QC_OUT(P),
eqc:on_output(fun(Str, Args) -> io:format(user, Str, Args) end, P)).
-define(ORDSET(L), ordsets:from_list(L)).
qc_test_() ->
{timeout, 120, fun() -> ?assert(eqc:quickcheck(?QC_OUT(prop_main()))) end}.
prop_main() ->
Initialize necessary env settings
application:load(riak_core),
application:set_env(riak_core, gossip_interval, 250),
application:set_env(riak_core, ring_creation_size, 8),
riak_core_ring_events:start_link(),
riak_core_node_watcher_events:start_link(),
?FORALL(Cmds, commands(?MODULE),
begin
Setup ETS table to broadcasts
ets:new(?MODULE, [ordered_set, named_table, public]),
ets:insert_new(?MODULE, {bcast_id, 0}),
{ok, Pid} = riak_core_node_watcher:start_link(),
gen_server:call(riak_core_node_watcher, {set_bcast_mod, ?MODULE, on_broadcast}),
{_H, _S, Res} = run_commands(?MODULE, Cmds),
and kill our PID
unlink(Pid),
kill_and_wait(Pid),
ets:delete(?MODULE),
case Res of
ok -> ok;
_ -> io:format(user, "QC result: ~p\n", [Res])
end,
aggregate(command_names(Cmds), Res == ok)
end).
initial_state() ->
#state{ up_nodes = [node()] }.
command(S) ->
oneof([
{call, ?MODULE, ring_update, [g_ring_nodes()]},
{call, ?MODULE, local_service_up, [g_service()]},
{call, ?MODULE, local_service_down, [g_service()]},
{call, ?MODULE, local_service_kill, [g_service(), S]},
{call, ?MODULE, local_node_up, []},
{call, ?MODULE, local_node_down, []},
{call, ?MODULE, remote_service_up, [g_node(), g_services()]},
{call, ?MODULE, remote_service_down, [g_node()]},
{call, ?MODULE, remote_service_down_disterl, [g_node()]},
{call, ?MODULE, wait_for_bcast, []}
]).
precondition(S, {call, _, local_service_kill, [Service, S]}) ->
orddict:is_key(Service, S#state.service_pids);
precondition(S, {call, _, wait_for_bcast, _}) ->
is_node_up(node(), S);
precondition(_, _) ->
true.
next_state(S, Res, {call, _, local_service_up, [Service]}) ->
S2 = service_up(node(), Service, S),
Pids = orddict:store(Service, Res, S2#state.service_pids),
S2#state { service_pids = Pids };
next_state(S, _Res, {call, _, local_service_down, [Service]}) ->
S2 = service_down(node(), Service, S),
Pids = orddict:erase(Service, S2#state.service_pids),
S2#state { service_pids = Pids };
next_state(S, _Res, {call, _, local_service_kill, [Service, _]}) ->
S2 = service_down(node(), Service, S),
Pids = orddict:erase(Service, S2#state.service_pids),
S2#state { service_pids = Pids };
next_state(S, _Res, {call, _, local_node_up, []}) ->
node_up(node(), S);
next_state(S, _Res, {call, _, local_node_down, []}) ->
node_down(node(), S);
next_state(S, _Res, {call, _, remote_service_up, [Node, Services]}) ->
peer_up(Node, Services, S);
next_state(S, _Res, {call, _, Fn, [Node]})
when Fn == remote_service_down; Fn == remote_service_down_disterl ->
peer_down(Node, S);
next_state(S, _Res, {call, _, wait_for_bcast, _}) ->
S;
next_state(S, _Res, {call, _, ring_update, [Nodes]}) ->
Peers = ordsets:del_element(node(), ordsets:from_list(Nodes)),
peer_filter(S#state { peers = Peers }).
postcondition(S, {call, _, local_service_up, [Service]}, _Res) ->
S2 = service_up(node(), Service, S),
validate_broadcast(S, S2, service),
deep_validate(S2);
postcondition(S, {call, _, local_service_down, [Service]}, _Res) ->
S2 = service_down(node(), Service, S),
validate_broadcast(S, S2, service),
deep_validate(S2);
postcondition(S, {call, _, local_service_kill, [Service, _]}, _Res) ->
S2 = service_down(node(), Service, S),
validate_broadcast(S, S2, service),
deep_validate(S2);
postcondition(S, {call, _, local_node_up, _}, _Res) ->
S2 = node_up(node(), S),
validate_broadcast(S, S2, node),
deep_validate(S2);
postcondition(S, {call, _, local_node_down, _}, _Res) ->
S2 = node_down(node(), S),
validate_broadcast(S, S2, node),
deep_validate(S2);
postcondition(S, {call, _, remote_service_up, [Node, Services]}, _Res) ->
Bcasts = broadcasts(),
case is_peer(Node, S) andalso not is_node_up(Node, S) of
true ->
case is_node_up(node(), S) of
true ->
ExpServices = services(node(), S),
?assertEqual({{up, node(), ExpServices}, [Node]}, hd(Bcasts));
false ->
?assertEqual({{down, node()}, [Node]}, hd(Bcasts))
end;
false ->
?assertEqual([], Bcasts)
end,
S2 = peer_up(Node, Services, S),
deep_validate(S2);
postcondition(S, {call, _, Fn, [Node]}, _Res)
when Fn == remote_service_down; Fn == remote_service_down_disterl ->
?assertEqual([], broadcasts()),
S2 = case is_peer(Node, S) of
true ->
node_down(Node, S);
false ->
S
end,
deep_validate(S2);
postcondition(S, {call, _, wait_for_bcast, _}, _Res) ->
validate_broadcast(S, S, service);
postcondition(S, {call, _, ring_update, [Nodes]}, _Res) ->
Ring update should generate a broadcast to all NEW peers
Bcasts = broadcasts(),
Peers = ordsets:del_element(node(), ordsets:from_list(Nodes)),
NewPeers = ordsets:subtract(Peers, S#state.peers),
case is_node_up(node(), S) of
true ->
ExpServices = services(node(), S),
?assertEqual({{up, node(), ExpServices}, NewPeers}, hd(Bcasts));
false ->
?assertEqual({{down, node()}, NewPeers}, hd(Bcasts))
end,
S2 = peer_filter(S#state { peers = Peers }),
deep_validate(S2).
deep_validate(S) ->
ExpAllServices = services(S),
ActAllServices = riak_core_node_watcher:services(),
?assertEqual(ExpAllServices, ActAllServices),
ExpNodes = ?ORDSET([snodes(Svc, S) || Svc <- ExpAllServices]),
ActNodes = ?ORDSET([?ORDSET(riak_core_node_watcher:nodes(Svc)) || Svc <- ExpAllServices]),
?assertEqual(ExpNodes, ActNodes),
true.
validate_broadcast(S0, Sfinal, Op) ->
Bcasts = broadcasts(),
Transition = {is_node_up(node(), S0), is_node_up(node(), Sfinal), Op},
ExpPeers = Sfinal#state.peers,
case Transition of
ExpServices = services(node(), Sfinal),
?assertEqual({{up, node(), ExpServices}, ExpPeers}, hd(Bcasts));
?assertEqual({{down, node()}, ExpPeers}, hd(Bcasts));
ExpServices = services(node(), Sfinal),
?assertEqual({{up, node(), ExpServices}, ExpPeers}, hd(Bcasts));
_ ->
?assertEqual([], Bcasts)
end,
true.
g_service() ->
oneof([s1, s2, s3, s4]).
g_node() ->
oneof(['n1@127.0.0.1', 'n2@127.0.0.1', 'n3@127.0.0.1']).
g_services() ->
list(elements([s1, s2, s3, s4])).
g_ring_nodes() ->
vector(app_helper:get_env(riak_core, ring_creation_size),
oneof([node(), 'n1@127.0.0.1', 'n2@127.0.0.1', 'n3@127.0.0.1'])).
local_service_up(Service) ->
Pid = spawn(fun() -> service_loop() end),
ok = riak_core_node_watcher:service_up(Service, Pid),
Pid.
local_service_down(Service) ->
ok = riak_core_node_watcher:service_down(Service).
local_service_kill(Service, State) ->
Avsn0 = riak_core_node_watcher:avsn(),
Pid = orddict:fetch(Service, State#state.service_pids),
kill_and_wait(Pid),
wait_for_avsn(Avsn0).
local_node_up() ->
riak_core_node_watcher:node_up().
local_node_down() ->
riak_core_node_watcher:node_down().
remote_service_up(Node, Services) ->
Avsn0 = riak_core_node_watcher:avsn(),
gen_server:cast(riak_core_node_watcher, {up, Node, Services}),
wait_for_avsn(Avsn0).
remote_service_down(Node) ->
Avsn0 = riak_core_node_watcher:avsn(),
gen_server:cast(riak_core_node_watcher, {down, Node}),
wait_for_avsn(Avsn0).
remote_service_down_disterl(Node) ->
Avsn0 = riak_core_node_watcher:avsn(),
riak_core_node_watcher ! {nodedown, Node},
wait_for_avsn(Avsn0).
wait_for_bcast() ->
{ok, Interval} = application:get_env(riak_core, gossip_interval),
timer:sleep(Interval + 50).
ring_update(Nodes) ->
Ring = build_ring(Nodes),
Avsn0 = riak_core_node_watcher:avsn(),
gen_server:cast(riak_core_node_watcher, {ring_update, Ring}),
wait_for_avsn(Avsn0),
?ORDSET(Nodes).
State functions
node_up(Node, S) ->
S#state { up_nodes = ordsets:add_element(Node, S#state.up_nodes) }.
node_down(Node, S) ->
S#state { up_nodes = ordsets:del_element(Node, S#state.up_nodes) }.
service_up(Node, Service, S) ->
S#state { services = ordsets:add_element({Node, Service}, S#state.services) }.
services_up(Node, Services, S) ->
NewServices = ?ORDSET([{Node, Svc} || Svc <- Services]),
OldServices = [{N, Svc} || {N, Svc} <- S#state.services,
Node /= N],
S#state { services = ordsets:union(NewServices, OldServices) }.
service_down(Node, Svc, S) ->
S#state { services = ordsets:del_element({Node, Svc}, S#state.services) }.
is_node_up(Node, S) ->
ordsets:is_element(Node, S#state.up_nodes).
is_peer(Node, S) ->
ordsets:is_element(Node, S#state.peers).
peer_up(Node, Services, S) ->
case is_peer(Node, S) of
true ->
node_up(Node, services_up(Node, Services, S));
false ->
S
end.
peer_down(Node, S) ->
case is_peer(Node, S) of
true ->
Services = [{N, Svc} || {N, Svc} <- S#state.services,
N /= Node],
node_down(Node, S#state { services = Services });
false ->
S
end.
peer_filter(S) ->
ThisNode = node(),
Services = [{N, Svc} || {N, Svc} <- S#state.services,
is_peer(N, S) orelse N == ThisNode],
UpNodes = [N || N <- S#state.up_nodes,
is_peer(N, S) orelse N == ThisNode],
S#state { services = Services, up_nodes = UpNodes }.
services(S) ->
?ORDSET([Svc || {N, Svc} <- S#state.services,
ordsets:is_element(N, S#state.up_nodes)]).
services(Node, S) ->
case ordsets:is_element(Node, S#state.up_nodes) of
true ->
all_services(Node, S);
false ->
[]
end.
snodes(S) ->
S#state.up_nodes.
snodes(Service, S) ->
?ORDSET([Node || {Node, Svc} <- S#state.services,
ordsets:is_element(Node, S#state.up_nodes),
Svc == Service]).
all_services(Node, S) ->
?ORDSET([Svc || {N, Svc} <- S#state.services,
N == Node]).
Internal functions
on_broadcast(Nodes, _Name, Msg) ->
Id = ets:update_counter(?MODULE, bcast_id, {2, 1}),
ets:insert_new(?MODULE, {Id, Msg, Nodes}).
broadcasts() ->
Bcasts = [list_to_tuple(L) || L <- ets:match(?MODULE, {'_', '$1', '$2'})],
ets:match_delete(?MODULE, {'_', '_', '_'}),
Bcasts.
kill_and_wait(Pid) ->
Mref = erlang:monitor(process, Pid),
exit(Pid, kill),
receive
{'DOWN', Mref, _, _, _} ->
ok
end.
wait_for_avsn(Avsn0) ->
case riak_core_node_watcher:avsn() of
Avsn0 ->
erlang:yield(),
wait_for_avsn(Avsn0);
_ ->
ok
end.
service_loop() ->
receive
_Any ->
service_loop()
end.
build_ring([Node | Rest]) ->
Inc = trunc(math:pow(2,160)-1) div app_helper:get_env(riak_core, ring_creation_size),
build_ring(Rest, 0, Inc, riak_core_ring:fresh(Node)).
build_ring([], _Id, _Inc, R) ->
R;
build_ring([Node | Rest], Id, Inc, R) ->
R2 = riak_core_ring:transfer_node(Id+Inc, Node, R),
build_ring(Rest, Id+Inc, Inc, R2).
-endif.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.