_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 |
|---|---|---|---|---|---|---|---|---|
405e4d9d7fbfd1ca15493f66b49ac3772845dc926158d050a9880ad65c927ce4 | AdRoll/rebar3_format | inline_items.erl | %% @doc All the lists of items in this module should be placed
in a single line if they 're small enough , but one item
%% per line if they're large.
-module(inline_items).
-format #{paper => 80}.
-export([short_tuple/0, short_list/0, short_fun/0]).
-export([short_bin/0, short_guard/1, short_lc/0]).
-export([short_bc/0, short_arglist/3]).
-export([long_tuple/0, long_list/0, long_fun/0, long_bin/0, long_guard/1,
long_lc/0, long_bc/0, long_arglist/7]).
-export([short/0, exact/0, long/0]).
-spec short_tuple() -> {T, T, T} when T :: {x, y, z}.
short_tuple() ->
X = {x, y, z},
Y = {x, y, z},
{X, Y, {x, y, z}}.
-spec short_list() -> [T | [T]] when T :: [x | y | z].
short_list() ->
X = [x, y, z],
Y = [x, y | z],
[X, Y, [x | y:z()]].
-spec short_fun() -> fun((X, Y, Z) -> {X, Y, Z}).
short_fun() ->
fun(X, Y, Z) -> {X, Y, Z} end.
-spec short_bin() -> binary().
short_bin() ->
X = <<1, 2, 3>>,
Y = <<1:1, 7:7, 2:2/little-integer-unit:32, 3/float>>,
<<X/binary, Y/binary>>.
-spec short_guard(integer()) -> integer().
short_guard(X) when is_integer(X), X < 2 ->
case X of
X when X >= -1 ->
X + 1;
X ->
X
end.
-spec short_lc() -> [{_, _, _}].
short_lc() ->
[{X, Y, Z} || {X, Y, Z} <- x:y(z), Z < Y].
-spec short_bc() -> binary().
short_bc() ->
<< <<X, Y, Z>> || <<X, Y, Z>> <= x:y(z), Z < Y >>.
-spec short_arglist(number(), number(), number()) -> number().
short_arglist(X, Y, Z) ->
X + Y + Z.
-spec long_tuple() -> {T, T, T} when T :: {x, y, z}.
long_tuple() ->
X = {x1,
x2,
x3,
x4,
y1,
y2,
y3,
y4,
very_very_long_name_1,
very_very_long_name_2,
very_very_long_name_3},
Y = {x1,
x2,
x3,
x4,
y1,
y2,
y3,
y4,
very_very_long_name_1,
very_very_long_name_2,
very_very_long_name_3},
{X,
Y,
{x1,
x2,
x3,
x4,
y1,
y2,
y3,
y4,
very_very_long_name_1,
very_very_long_name_2,
very_very_long_name_3}}.
-spec long_list() -> [T | [T]]
when T ::
[x1 |
x2 |
x3 |
x4 |
y1 |
y2 |
y3 |
y4 |
very_very_long_name_1 |
very_very_long_name_2 |
very_very_long_name_3].
long_list() ->
X = [x1,
x2,
x3,
x4,
y1,
y2,
y3,
y4,
very_very_long_name_1,
very_very_long_name_2,
very_very_long_name_3],
Y = [x1,
x2,
x3,
x4,
y1,
y2,
y3,
y4,
very_very_long_name_1,
very_very_long_name_2
| very_very_long_name_3],
[X,
Y,
[x1,
x2,
x3,
x4,
y1,
y2,
y3,
y4,
very_very_long_name_1,
very_very_long_name_2,
very_very_long_name_3
| y:z()]].
-spec long_fun() ->
fun((X1,
X2,
X3,
X4,
Y1,
Y2,
Y3,
Y4,
VeryVeryLongName1,
VeryVeryLongName2,
VeryVeryLongName3) ->
{X1,
X2,
X3,
X4,
Y1,
Y2,
Y3,
Y4,
VeryVeryLongName1,
VeryVeryLongName2,
VeryVeryLongName3}).
long_fun() ->
fun(X1,
X2,
X3,
X4,
Y1,
Y2,
Y3,
Y4,
VeryVeryLongName1,
VeryVeryLongName2,
VeryVeryLongName3) ->
{X1,
X2,
X3,
X4,
Y1,
Y2,
Y3,
Y4,
VeryVeryLongName1,
VeryVeryLongName2,
VeryVeryLongName3}
end.
-spec long_bin() -> binary().
long_bin() ->
X = <<1,
1,
1,
1,
2,
2,
2,
2,
333333333333333333,
333333333333333333,
333333333333333333,
333333333333333333>>,
Y = <<1:1,
1:1,
1:1,
1:1,
4:4,
2:2/little-integer-unit:32,
2:2/little-integer-unit:32,
2:2/little-integer-unit:32,
3/float,
3/float,
3/float,
3/float>>,
<<X/binary,
Y/binary,
X/binary,
Y/binary,
X/binary,
Y/binary,
X/binary,
Y/binary,
X/binary,
Y/binary>>.
-spec long_guard(integer()) -> integer().
long_guard(VeryVeryLongName)
when is_integer(VeryVeryLongName), VeryVeryLongName < 2,
VeryVeryLongName < 3;
VeryVeryLongName > 2 andalso VeryVeryLongName > 3 ->
if VeryVeryLongName >= -1;
VeryVeryLongName < 1, VeryVeryLongName > 0;
VeryVeryLongName == 0 ->
VeryVeryLongName + 1;
VeryVeryLongName ->
VeryVeryLongName
end.
-spec long_lc() -> [{_, _, _}].
long_lc() ->
[{X, Y, Z}
|| X <- generator:x(),
X < 1,
Y <- generator:y(),
Z <- generator:z(),
filter:x(Y, Z),
X + Y == Z].
-spec long_bc() -> binary().
long_bc() ->
<< <<X, Y, Z>>
|| <<X>> <- generator:x(),
X < 1,
<<Y:2/signed-integer-unit:8>> <- generator:y(),
Z <- generator:z(),
filter:x(Y, Z),
X + Y == Z >>.
-spec long_arglist(number(),
number(),
number(),
float(),
non_neg_integer(),
non_neg_integer(),
non_neg_integer()) ->
number().
long_arglist(X1,
X2,
X3,
Y1,
VeryVeryLongName1,
VeryVeryLongName2,
VeryVeryLongName3) ->
X1
+ X2
+ X3
+ Y1
+ VeryVeryLongName1
+ VeryVeryLongName2
+ VeryVeryLongName3.
short() ->
[these,
items,
should,
'not',
be,
inlined,
since,
they,
are,
less,
than,
25].
exact() ->
[these,
items,
should,
'not',
be,
inlined,
$(,
i,
".",
e,
". ",
each,
item,
should,
occupy,
a,
signle,
line,
$),
since,
they,
are,
exactly,
25,
$.].
long() ->
[these, items, should, be, inlined, they, are, more, than, 25, $., 'We',
can, be, sure, about, that, because, we, added, a, very, long, number,
'of', items, to, this, list].
| null | https://raw.githubusercontent.com/AdRoll/rebar3_format/5ffb11341796173317ae094d4e165b85fad6aa19/test_app/after/src/inline_items/inline_items.erl | erlang | @doc All the lists of items in this module should be placed
per line if they're large. | in a single line if they 're small enough , but one item
-module(inline_items).
-format #{paper => 80}.
-export([short_tuple/0, short_list/0, short_fun/0]).
-export([short_bin/0, short_guard/1, short_lc/0]).
-export([short_bc/0, short_arglist/3]).
-export([long_tuple/0, long_list/0, long_fun/0, long_bin/0, long_guard/1,
long_lc/0, long_bc/0, long_arglist/7]).
-export([short/0, exact/0, long/0]).
-spec short_tuple() -> {T, T, T} when T :: {x, y, z}.
short_tuple() ->
X = {x, y, z},
Y = {x, y, z},
{X, Y, {x, y, z}}.
-spec short_list() -> [T | [T]] when T :: [x | y | z].
short_list() ->
X = [x, y, z],
Y = [x, y | z],
[X, Y, [x | y:z()]].
-spec short_fun() -> fun((X, Y, Z) -> {X, Y, Z}).
short_fun() ->
fun(X, Y, Z) -> {X, Y, Z} end.
-spec short_bin() -> binary().
short_bin() ->
X = <<1, 2, 3>>,
Y = <<1:1, 7:7, 2:2/little-integer-unit:32, 3/float>>,
<<X/binary, Y/binary>>.
-spec short_guard(integer()) -> integer().
short_guard(X) when is_integer(X), X < 2 ->
case X of
X when X >= -1 ->
X + 1;
X ->
X
end.
-spec short_lc() -> [{_, _, _}].
short_lc() ->
[{X, Y, Z} || {X, Y, Z} <- x:y(z), Z < Y].
-spec short_bc() -> binary().
short_bc() ->
<< <<X, Y, Z>> || <<X, Y, Z>> <= x:y(z), Z < Y >>.
-spec short_arglist(number(), number(), number()) -> number().
short_arglist(X, Y, Z) ->
X + Y + Z.
-spec long_tuple() -> {T, T, T} when T :: {x, y, z}.
long_tuple() ->
X = {x1,
x2,
x3,
x4,
y1,
y2,
y3,
y4,
very_very_long_name_1,
very_very_long_name_2,
very_very_long_name_3},
Y = {x1,
x2,
x3,
x4,
y1,
y2,
y3,
y4,
very_very_long_name_1,
very_very_long_name_2,
very_very_long_name_3},
{X,
Y,
{x1,
x2,
x3,
x4,
y1,
y2,
y3,
y4,
very_very_long_name_1,
very_very_long_name_2,
very_very_long_name_3}}.
-spec long_list() -> [T | [T]]
when T ::
[x1 |
x2 |
x3 |
x4 |
y1 |
y2 |
y3 |
y4 |
very_very_long_name_1 |
very_very_long_name_2 |
very_very_long_name_3].
long_list() ->
X = [x1,
x2,
x3,
x4,
y1,
y2,
y3,
y4,
very_very_long_name_1,
very_very_long_name_2,
very_very_long_name_3],
Y = [x1,
x2,
x3,
x4,
y1,
y2,
y3,
y4,
very_very_long_name_1,
very_very_long_name_2
| very_very_long_name_3],
[X,
Y,
[x1,
x2,
x3,
x4,
y1,
y2,
y3,
y4,
very_very_long_name_1,
very_very_long_name_2,
very_very_long_name_3
| y:z()]].
-spec long_fun() ->
fun((X1,
X2,
X3,
X4,
Y1,
Y2,
Y3,
Y4,
VeryVeryLongName1,
VeryVeryLongName2,
VeryVeryLongName3) ->
{X1,
X2,
X3,
X4,
Y1,
Y2,
Y3,
Y4,
VeryVeryLongName1,
VeryVeryLongName2,
VeryVeryLongName3}).
long_fun() ->
fun(X1,
X2,
X3,
X4,
Y1,
Y2,
Y3,
Y4,
VeryVeryLongName1,
VeryVeryLongName2,
VeryVeryLongName3) ->
{X1,
X2,
X3,
X4,
Y1,
Y2,
Y3,
Y4,
VeryVeryLongName1,
VeryVeryLongName2,
VeryVeryLongName3}
end.
-spec long_bin() -> binary().
long_bin() ->
X = <<1,
1,
1,
1,
2,
2,
2,
2,
333333333333333333,
333333333333333333,
333333333333333333,
333333333333333333>>,
Y = <<1:1,
1:1,
1:1,
1:1,
4:4,
2:2/little-integer-unit:32,
2:2/little-integer-unit:32,
2:2/little-integer-unit:32,
3/float,
3/float,
3/float,
3/float>>,
<<X/binary,
Y/binary,
X/binary,
Y/binary,
X/binary,
Y/binary,
X/binary,
Y/binary,
X/binary,
Y/binary>>.
-spec long_guard(integer()) -> integer().
long_guard(VeryVeryLongName)
when is_integer(VeryVeryLongName), VeryVeryLongName < 2,
VeryVeryLongName < 3;
VeryVeryLongName > 2 andalso VeryVeryLongName > 3 ->
if VeryVeryLongName >= -1;
VeryVeryLongName < 1, VeryVeryLongName > 0;
VeryVeryLongName == 0 ->
VeryVeryLongName + 1;
VeryVeryLongName ->
VeryVeryLongName
end.
-spec long_lc() -> [{_, _, _}].
long_lc() ->
[{X, Y, Z}
|| X <- generator:x(),
X < 1,
Y <- generator:y(),
Z <- generator:z(),
filter:x(Y, Z),
X + Y == Z].
-spec long_bc() -> binary().
long_bc() ->
<< <<X, Y, Z>>
|| <<X>> <- generator:x(),
X < 1,
<<Y:2/signed-integer-unit:8>> <- generator:y(),
Z <- generator:z(),
filter:x(Y, Z),
X + Y == Z >>.
-spec long_arglist(number(),
number(),
number(),
float(),
non_neg_integer(),
non_neg_integer(),
non_neg_integer()) ->
number().
long_arglist(X1,
X2,
X3,
Y1,
VeryVeryLongName1,
VeryVeryLongName2,
VeryVeryLongName3) ->
X1
+ X2
+ X3
+ Y1
+ VeryVeryLongName1
+ VeryVeryLongName2
+ VeryVeryLongName3.
short() ->
[these,
items,
should,
'not',
be,
inlined,
since,
they,
are,
less,
than,
25].
exact() ->
[these,
items,
should,
'not',
be,
inlined,
$(,
i,
".",
e,
". ",
each,
item,
should,
occupy,
a,
signle,
line,
$),
since,
they,
are,
exactly,
25,
$.].
long() ->
[these, items, should, be, inlined, they, are, more, than, 25, $., 'We',
can, be, sure, about, that, because, we, added, a, very, long, number,
'of', items, to, this, list].
|
0d845f641039006a4917eedc7e288772cc35ba8004acec8c02a25a1eeb393912 | ocsigen/ocsigenserver | revproxy.ml | Ocsigen
*
* Module revproxy.ml
* Copyright ( C ) 2007
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation , with linking exception ;
* either version 2.1 of the License , or ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
*
* Module revproxy.ml
* Copyright (C) 2007 Vincent Balat
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, with linking exception;
* either version 2.1 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*)
(** Reverse proxy for Ocsigen
The reverse proxy is still experimental. *)
open Lwt.Infix
let section = Lwt_log.Section.make "ocsigen:ext:revproxy"
exception Bad_answer_from_http_server
type redir =
{ regexp : Pcre.regexp
; full_url : Ocsigen_lib.yesnomaybe
; dest : string
; pipeline : bool
; keephost : bool }
(** The table of redirections for each virtual server *)
(** Generate the pages from the request *)
let gen dir = function
| Ocsigen_extensions.Req_found _ ->
Lwt.return Ocsigen_extensions.Ext_do_nothing
| Ocsigen_extensions.Req_not_found (err, {Ocsigen_extensions.request_info; _})
->
Lwt.catch
(* Is it a redirection? *)
(fun () ->
Lwt_log.ign_info ~section "Is it a redirection?";
let dest =
let fi full =
Ocsigen_extensions.find_redirection dir.regexp full dir.dest
request_info
in
match dir.full_url with
| Ocsigen_lib.Yes -> fi true
| Ocsigen_lib.No -> fi false
| Ocsigen_lib.Maybe -> (
try fi false with Ocsigen_extensions.Not_concerned -> fi true)
in
let https, host, port, path =
try
(* FIXME: we do not seem to handle GET
parameters. Why? *)
match Ocsigen_lib.Url.parse dest with
| Some https, Some host, port, path, _, _, _ ->
let port =
match port with
| None -> if https then 443 else 80
| Some p -> p
in
https, host, port, path
| _ ->
raise
(Ocsigen_extensions.Error_in_config_file
("Revproxy : error in destination URL " ^ dest))
VVV catch only URL - related exceptions ?
with e ->
raise
(Ocsigen_extensions.Error_in_config_file
("Revproxy : error in destination URL " ^ dest ^ " - "
^ Printexc.to_string e))
in
Lwt_log.ign_info_f ~section "YES! Redirection to http%s:%d/%s"
(if https then "s" else "")
host port path;
Ocsigen_lib.Ip_address.get_inet_addr host >>= fun _inet_addr ->
(* It is now safe to start processing next request.
We are sure that the request won't be taken in disorder,
so we return. *)
let do_request () =
let headers =
let h =
Cohttp.Request.headers (Ocsigen_request.to_cohttp request_info)
in
let h =
Ocsigen_request.version request_info
|> Cohttp.Code.string_of_version
|> Cohttp.Header.replace h
Ocsigen_header.Name.(to_string x_forwarded_proto)
in
let h =
let forward =
let address =
Unix.string_of_inet_addr
(Ocsigen_request.address request_info)
in
String.concat ", "
(Ocsigen_request.remote_ip request_info
:: Ocsigen_request.forward_ip request_info
@ [address])
in
Cohttp.Header.replace h
Ocsigen_header.Name.(to_string x_forwarded_for)
forward
in
Cohttp.Header.remove h Ocsigen_header.Name.(to_string host)
and uri =
let scheme =
if Ocsigen_request.ssl request_info then "https" else "http"
and host =
match
if dir.keephost
then Ocsigen_request.host request_info
else None
with
| Some host -> host
| None -> host
in
Uri.make ~scheme ~host ~port ~path ()
and body = Ocsigen_request.body request_info
and meth = Ocsigen_request.meth request_info in
Cohttp_lwt_unix.Client.call ~headers ~body meth uri
in
Lwt.return
@@ Ocsigen_extensions.Ext_found
(fun () -> do_request () >|= Ocsigen_response.of_cohttp))
(function
| Ocsigen_extensions.Not_concerned ->
Lwt.return (Ocsigen_extensions.Ext_next err)
| e -> Lwt.fail e)
let parse_config config_elem =
let regexp = ref None in
let full_url = ref Ocsigen_lib.Yes in
let dest = ref None in
let pipeline = ref true in
let keephost = ref false in
Ocsigen_extensions.(
Configuration.process_element ~in_tag:"host"
~other_elements:(fun t _ _ -> raise (Bad_config_tag_for_extension t))
~elements:
[ Configuration.element ~name:"revproxy"
~attributes:
[ Configuration.attribute ~name:"regexp" (fun s ->
regexp := Some s;
full_url := Ocsigen_lib.Yes)
; Configuration.attribute ~name:"fullurl" (fun s ->
regexp := Some s;
full_url := Ocsigen_lib.Yes)
; Configuration.attribute ~name:"suburl" (fun s ->
regexp := Some s;
full_url := Ocsigen_lib.No)
; Configuration.attribute ~name:"dest" (fun s -> dest := Some s)
; Configuration.attribute ~name:"keephost" (function
| "keephost" -> keephost := true
| _ -> ())
; Configuration.attribute ~name:"nopipeline" (function
| "nopipeline" -> pipeline := false
| _ -> ()) ]
() ]
config_elem);
match !regexp, !full_url, !dest, !pipeline, !keephost with
| None, _, _, _, _ ->
Ocsigen_extensions.badconfig "Missing attribute 'regexp' for <revproxy>"
| _, _, None, _, _ ->
Ocsigen_extensions.badconfig "Missing attribute 'dest' for <revproxy>"
| Some regexp, full_url, Some dest, pipeline, keephost ->
gen
{ regexp = Ocsigen_lib.Netstring_pcre.regexp ("^" ^ regexp ^ "$")
; full_url
; dest
; pipeline
; keephost }
let () =
Ocsigen_extensions.register ~name:"revproxy"
~fun_site:(fun _ _ _ _ _ _ -> parse_config)
~respect_pipeline:true
We ask to respect pipeline order
when sending to extensions !
when sending to extensions! *)
()
| null | https://raw.githubusercontent.com/ocsigen/ocsigenserver/d468cf464dcc9f05f820c35f346ffdbe6b9c7931/src/extensions/revproxy.ml | ocaml | * Reverse proxy for Ocsigen
The reverse proxy is still experimental.
* The table of redirections for each virtual server
* Generate the pages from the request
Is it a redirection?
FIXME: we do not seem to handle GET
parameters. Why?
It is now safe to start processing next request.
We are sure that the request won't be taken in disorder,
so we return. | Ocsigen
*
* Module revproxy.ml
* Copyright ( C ) 2007
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation , with linking exception ;
* either version 2.1 of the License , or ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
*
* Module revproxy.ml
* Copyright (C) 2007 Vincent Balat
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, with linking exception;
* either version 2.1 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*)
open Lwt.Infix
let section = Lwt_log.Section.make "ocsigen:ext:revproxy"
exception Bad_answer_from_http_server
type redir =
{ regexp : Pcre.regexp
; full_url : Ocsigen_lib.yesnomaybe
; dest : string
; pipeline : bool
; keephost : bool }
let gen dir = function
| Ocsigen_extensions.Req_found _ ->
Lwt.return Ocsigen_extensions.Ext_do_nothing
| Ocsigen_extensions.Req_not_found (err, {Ocsigen_extensions.request_info; _})
->
Lwt.catch
(fun () ->
Lwt_log.ign_info ~section "Is it a redirection?";
let dest =
let fi full =
Ocsigen_extensions.find_redirection dir.regexp full dir.dest
request_info
in
match dir.full_url with
| Ocsigen_lib.Yes -> fi true
| Ocsigen_lib.No -> fi false
| Ocsigen_lib.Maybe -> (
try fi false with Ocsigen_extensions.Not_concerned -> fi true)
in
let https, host, port, path =
try
match Ocsigen_lib.Url.parse dest with
| Some https, Some host, port, path, _, _, _ ->
let port =
match port with
| None -> if https then 443 else 80
| Some p -> p
in
https, host, port, path
| _ ->
raise
(Ocsigen_extensions.Error_in_config_file
("Revproxy : error in destination URL " ^ dest))
VVV catch only URL - related exceptions ?
with e ->
raise
(Ocsigen_extensions.Error_in_config_file
("Revproxy : error in destination URL " ^ dest ^ " - "
^ Printexc.to_string e))
in
Lwt_log.ign_info_f ~section "YES! Redirection to http%s:%d/%s"
(if https then "s" else "")
host port path;
Ocsigen_lib.Ip_address.get_inet_addr host >>= fun _inet_addr ->
let do_request () =
let headers =
let h =
Cohttp.Request.headers (Ocsigen_request.to_cohttp request_info)
in
let h =
Ocsigen_request.version request_info
|> Cohttp.Code.string_of_version
|> Cohttp.Header.replace h
Ocsigen_header.Name.(to_string x_forwarded_proto)
in
let h =
let forward =
let address =
Unix.string_of_inet_addr
(Ocsigen_request.address request_info)
in
String.concat ", "
(Ocsigen_request.remote_ip request_info
:: Ocsigen_request.forward_ip request_info
@ [address])
in
Cohttp.Header.replace h
Ocsigen_header.Name.(to_string x_forwarded_for)
forward
in
Cohttp.Header.remove h Ocsigen_header.Name.(to_string host)
and uri =
let scheme =
if Ocsigen_request.ssl request_info then "https" else "http"
and host =
match
if dir.keephost
then Ocsigen_request.host request_info
else None
with
| Some host -> host
| None -> host
in
Uri.make ~scheme ~host ~port ~path ()
and body = Ocsigen_request.body request_info
and meth = Ocsigen_request.meth request_info in
Cohttp_lwt_unix.Client.call ~headers ~body meth uri
in
Lwt.return
@@ Ocsigen_extensions.Ext_found
(fun () -> do_request () >|= Ocsigen_response.of_cohttp))
(function
| Ocsigen_extensions.Not_concerned ->
Lwt.return (Ocsigen_extensions.Ext_next err)
| e -> Lwt.fail e)
let parse_config config_elem =
let regexp = ref None in
let full_url = ref Ocsigen_lib.Yes in
let dest = ref None in
let pipeline = ref true in
let keephost = ref false in
Ocsigen_extensions.(
Configuration.process_element ~in_tag:"host"
~other_elements:(fun t _ _ -> raise (Bad_config_tag_for_extension t))
~elements:
[ Configuration.element ~name:"revproxy"
~attributes:
[ Configuration.attribute ~name:"regexp" (fun s ->
regexp := Some s;
full_url := Ocsigen_lib.Yes)
; Configuration.attribute ~name:"fullurl" (fun s ->
regexp := Some s;
full_url := Ocsigen_lib.Yes)
; Configuration.attribute ~name:"suburl" (fun s ->
regexp := Some s;
full_url := Ocsigen_lib.No)
; Configuration.attribute ~name:"dest" (fun s -> dest := Some s)
; Configuration.attribute ~name:"keephost" (function
| "keephost" -> keephost := true
| _ -> ())
; Configuration.attribute ~name:"nopipeline" (function
| "nopipeline" -> pipeline := false
| _ -> ()) ]
() ]
config_elem);
match !regexp, !full_url, !dest, !pipeline, !keephost with
| None, _, _, _, _ ->
Ocsigen_extensions.badconfig "Missing attribute 'regexp' for <revproxy>"
| _, _, None, _, _ ->
Ocsigen_extensions.badconfig "Missing attribute 'dest' for <revproxy>"
| Some regexp, full_url, Some dest, pipeline, keephost ->
gen
{ regexp = Ocsigen_lib.Netstring_pcre.regexp ("^" ^ regexp ^ "$")
; full_url
; dest
; pipeline
; keephost }
let () =
Ocsigen_extensions.register ~name:"revproxy"
~fun_site:(fun _ _ _ _ _ _ -> parse_config)
~respect_pipeline:true
We ask to respect pipeline order
when sending to extensions !
when sending to extensions! *)
()
|
ce96f28d936f1fe520255a2c66befb062eaa0252e5d6b511fc7c393f935d7902 | FundingCircle/topology-grapher | config.clj | (ns topology-grapher.config)
(def work-dir "/tmp/graphs")
| null | https://raw.githubusercontent.com/FundingCircle/topology-grapher/c1e3518ef90f95097b3310d3d5cbd48750498e81/src/topology_grapher/config.clj | clojure | (ns topology-grapher.config)
(def work-dir "/tmp/graphs")
| |
6dc6171fd472223bab568165818bf3c2add85ce3b4afa695a6cfb30736022f92 | dyzsr/ocaml-selectml | ambiguity.ml | (* TEST
* expect
*)
[@@@warning "-8-11-12"] (* reduce the noise. *)
type ('a, 'b) eq = Refl : ('a, 'a) eq;;
[%%expect{|
type ('a, 'b) eq = Refl : ('a, 'a) eq
|}];;
let ret_e1 (type a b) (b : bool) (wit : (a, b) eq) (x : a) (y : b) =
match wit with
| Refl -> if b then x else y
| _ -> x
;;
[%%expect{|
Line 3, characters 29-30:
3 | | Refl -> if b then x else y
^
Error: This expression has type b = a but an expression was expected of type
a
This instance of a is ambiguous:
it would escape the scope of its equation
|}]
let ret_e2 (type a b) (b : bool) (wit : (a, b) eq) (x : a) (y : b) =
match wit with
| Refl -> if b then x else y
| _ -> y
;;
[%%expect{|
Line 3, characters 29-30:
3 | | Refl -> if b then x else y
^
Error: This expression has type b = a but an expression was expected of type
a
This instance of a is ambiguous:
it would escape the scope of its equation
|}]
let ret_ei1 (type a) (b : bool) (wit : (a, int) eq) (x : a) =
match wit with
| Refl -> if b then x else 0
| _ -> x
;;
[%%expect{|
Line 3, characters 29-30:
3 | | Refl -> if b then x else 0
^
Error: This expression has type int but an expression was expected of type
a = int
This instance of int is ambiguous:
it would escape the scope of its equation
|}]
let ret_ei2 (type a) (b : bool) (wit : (a, int) eq) (x : a) =
match wit with
| Refl -> if b then x else 0
| _ -> x
;;
[%%expect{|
Line 3, characters 29-30:
3 | | Refl -> if b then x else 0
^
Error: This expression has type int but an expression was expected of type
a = int
This instance of int is ambiguous:
it would escape the scope of its equation
|}]
let ret_f (type a b) (wit : (a, b) eq) (x : a) (y : b) =
match wit with
| Refl -> [x; y]
| _ -> [x]
;;
[%%expect{|
Line 3, characters 16-17:
3 | | Refl -> [x; y]
^
Error: This expression has type b = a but an expression was expected of type
a
This instance of a is ambiguous:
it would escape the scope of its equation
|}]
let ret_g1 (type a b) (wit : (a, b) eq) (x : a) (y : b) =
match wit with
| Refl -> [x; y]
| _ -> [y]
;;
[%%expect{|
Line 3, characters 16-17:
3 | | Refl -> [x; y]
^
Error: This expression has type b = a but an expression was expected of type
a
This instance of a is ambiguous:
it would escape the scope of its equation
|}]
First reported in MPR#7617 : the typechecker arbitrarily picks a
representative for an ambivalent type escaping its scope .
The commit that was implemented poses problems of its own : we are now
unifying the type of the patterns in the environment of each pattern , instead
of the outer one . The code discussed in PR#7617 passes because each branch
contains the same equation , but consider the following cases :
representative for an ambivalent type escaping its scope.
The commit that was implemented poses problems of its own: we are now
unifying the type of the patterns in the environment of each pattern, instead
of the outer one. The code discussed in PR#7617 passes because each branch
contains the same equation, but consider the following cases: *)
let f (type a b) (x : (a, b) eq) =
match x, [] with
| Refl, [(_ : a) | (_ : b)] -> []
| _, [(_ : a)] -> []
;;
[%%expect{|
Line 3, characters 4-29:
3 | | Refl, [(_ : a) | (_ : b)] -> []
^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This pattern matches values of type (a, b) eq * b list
This instance of b is ambiguous:
it would escape the scope of its equation
|}]
let g1 (type a b) (x : (a, b) eq) =
match x, [] with
| Refl, [(_ : a) | (_ : b)] -> []
| _, [(_ : b)] -> []
;;
[%%expect{|
Line 3, characters 4-29:
3 | | Refl, [(_ : a) | (_ : b)] -> []
^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This pattern matches values of type (a, b) eq * b list
This instance of b is ambiguous:
it would escape the scope of its equation
|}]
let g2 (type a b) (x : (a, b) eq) =
match x, [] with
| Refl, [(_ : b) | (_ : a)] -> []
| _, [(_ : a)] -> []
;;
[%%expect{|
Line 3, characters 4-29:
3 | | Refl, [(_ : b) | (_ : a)] -> []
^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This pattern matches values of type (a, b) eq * b list
This instance of b is ambiguous:
it would escape the scope of its equation
|}]
let h1 (type a b) (x : (a, b) eq) =
match x, [] with
| _, [(_ : a)] -> []
| Refl, [(_ : a) | (_ : b)] -> []
;;
[%%expect{|
Line 4, characters 4-29:
4 | | Refl, [(_ : a) | (_ : b)] -> []
^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This pattern matches values of type (a, b) eq * b list
This instance of b is ambiguous:
it would escape the scope of its equation
|}]
let h2 (type a b) (x : (a, b) eq) =
match x, [] with
| _, [(_ : b)] -> []
| Refl, [(_ : a) | (_ : b)] -> []
;;
[%%expect{|
Line 4, characters 4-29:
4 | | Refl, [(_ : a) | (_ : b)] -> []
^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This pattern matches values of type (a, b) eq * b list
This instance of b is ambiguous:
it would escape the scope of its equation
|}]
let h3 (type a b) (x : (a, b) eq) =
match x, [] with
| _, [(_ : a)] -> []
| Refl, [(_ : b) | (_ : a)] -> []
;;
[%%expect{|
Line 4, characters 4-29:
4 | | Refl, [(_ : b) | (_ : a)] -> []
^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This pattern matches values of type (a, b) eq * b list
This instance of b is ambiguous:
it would escape the scope of its equation
|}]
module T : sig
type t
type u
val eq : (t, u) eq
end = struct
type t = int
type u = int
let eq = Refl
end;;
[%%expect{|
module T : sig type t type u val eq : (t, u) eq end
|}]
module M = struct
let r = ref []
end
let foo p (e : (T.t, T.u) eq) (x : T.t) (y : T.u) =
match e with
| Refl ->
let z = if p then x else y in
let module N = struct
module type S = module type of struct let r = ref [z] end
end in
let module O : N.S = M in
()
module type S = module type of M ;;
[%%expect{|
module M : sig val r : '_weak1 list ref end
Line 12, characters 25-26:
12 | let module O : N.S = M in
^
Error: Signature mismatch:
Modules do not match:
sig val r : '_weak1 list ref end
is not included in
N.S
Values do not match:
val r : '_weak1 list ref
is not included in
val r : T.u list ref
The type '_weak1 list ref is not compatible with the type T.u list ref
Type '_weak1 is not compatible with type T.u = T.t
This instance of T.t is ambiguous:
it would escape the scope of its equation
|}]
module M = struct
let r = ref []
end
let foo p (e : (T.u, T.t) eq) (x : T.t) (y : T.u) =
match e with
| Refl ->
let z = if p then x else y in
let module N = struct
module type S = module type of struct let r = ref [z] end
end in
let module O : N.S = M in
()
module type S = module type of M ;;
[%%expect{|
module M : sig val r : '_weak2 list ref end
Line 12, characters 25-26:
12 | let module O : N.S = M in
^
Error: Signature mismatch:
Modules do not match:
sig val r : '_weak2 list ref end
is not included in
N.S
Values do not match:
val r : '_weak2 list ref
is not included in
val r : T.t list ref
The type '_weak2 list ref is not compatible with the type T.t list ref
Type '_weak2 is not compatible with type T.t = T.u
This instance of T.u is ambiguous:
it would escape the scope of its equation
|}]
| null | https://raw.githubusercontent.com/dyzsr/ocaml-selectml/875544110abb3350e9fb5ec9bbadffa332c270d2/testsuite/tests/typing-gadts/ambiguity.ml | ocaml | TEST
* expect
reduce the noise. |
type ('a, 'b) eq = Refl : ('a, 'a) eq;;
[%%expect{|
type ('a, 'b) eq = Refl : ('a, 'a) eq
|}];;
let ret_e1 (type a b) (b : bool) (wit : (a, b) eq) (x : a) (y : b) =
match wit with
| Refl -> if b then x else y
| _ -> x
;;
[%%expect{|
Line 3, characters 29-30:
3 | | Refl -> if b then x else y
^
Error: This expression has type b = a but an expression was expected of type
a
This instance of a is ambiguous:
it would escape the scope of its equation
|}]
let ret_e2 (type a b) (b : bool) (wit : (a, b) eq) (x : a) (y : b) =
match wit with
| Refl -> if b then x else y
| _ -> y
;;
[%%expect{|
Line 3, characters 29-30:
3 | | Refl -> if b then x else y
^
Error: This expression has type b = a but an expression was expected of type
a
This instance of a is ambiguous:
it would escape the scope of its equation
|}]
let ret_ei1 (type a) (b : bool) (wit : (a, int) eq) (x : a) =
match wit with
| Refl -> if b then x else 0
| _ -> x
;;
[%%expect{|
Line 3, characters 29-30:
3 | | Refl -> if b then x else 0
^
Error: This expression has type int but an expression was expected of type
a = int
This instance of int is ambiguous:
it would escape the scope of its equation
|}]
let ret_ei2 (type a) (b : bool) (wit : (a, int) eq) (x : a) =
match wit with
| Refl -> if b then x else 0
| _ -> x
;;
[%%expect{|
Line 3, characters 29-30:
3 | | Refl -> if b then x else 0
^
Error: This expression has type int but an expression was expected of type
a = int
This instance of int is ambiguous:
it would escape the scope of its equation
|}]
let ret_f (type a b) (wit : (a, b) eq) (x : a) (y : b) =
match wit with
| Refl -> [x; y]
| _ -> [x]
;;
[%%expect{|
Line 3, characters 16-17:
3 | | Refl -> [x; y]
^
Error: This expression has type b = a but an expression was expected of type
a
This instance of a is ambiguous:
it would escape the scope of its equation
|}]
let ret_g1 (type a b) (wit : (a, b) eq) (x : a) (y : b) =
match wit with
| Refl -> [x; y]
| _ -> [y]
;;
[%%expect{|
Line 3, characters 16-17:
3 | | Refl -> [x; y]
^
Error: This expression has type b = a but an expression was expected of type
a
This instance of a is ambiguous:
it would escape the scope of its equation
|}]
First reported in MPR#7617 : the typechecker arbitrarily picks a
representative for an ambivalent type escaping its scope .
The commit that was implemented poses problems of its own : we are now
unifying the type of the patterns in the environment of each pattern , instead
of the outer one . The code discussed in PR#7617 passes because each branch
contains the same equation , but consider the following cases :
representative for an ambivalent type escaping its scope.
The commit that was implemented poses problems of its own: we are now
unifying the type of the patterns in the environment of each pattern, instead
of the outer one. The code discussed in PR#7617 passes because each branch
contains the same equation, but consider the following cases: *)
let f (type a b) (x : (a, b) eq) =
match x, [] with
| Refl, [(_ : a) | (_ : b)] -> []
| _, [(_ : a)] -> []
;;
[%%expect{|
Line 3, characters 4-29:
3 | | Refl, [(_ : a) | (_ : b)] -> []
^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This pattern matches values of type (a, b) eq * b list
This instance of b is ambiguous:
it would escape the scope of its equation
|}]
let g1 (type a b) (x : (a, b) eq) =
match x, [] with
| Refl, [(_ : a) | (_ : b)] -> []
| _, [(_ : b)] -> []
;;
[%%expect{|
Line 3, characters 4-29:
3 | | Refl, [(_ : a) | (_ : b)] -> []
^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This pattern matches values of type (a, b) eq * b list
This instance of b is ambiguous:
it would escape the scope of its equation
|}]
let g2 (type a b) (x : (a, b) eq) =
match x, [] with
| Refl, [(_ : b) | (_ : a)] -> []
| _, [(_ : a)] -> []
;;
[%%expect{|
Line 3, characters 4-29:
3 | | Refl, [(_ : b) | (_ : a)] -> []
^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This pattern matches values of type (a, b) eq * b list
This instance of b is ambiguous:
it would escape the scope of its equation
|}]
let h1 (type a b) (x : (a, b) eq) =
match x, [] with
| _, [(_ : a)] -> []
| Refl, [(_ : a) | (_ : b)] -> []
;;
[%%expect{|
Line 4, characters 4-29:
4 | | Refl, [(_ : a) | (_ : b)] -> []
^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This pattern matches values of type (a, b) eq * b list
This instance of b is ambiguous:
it would escape the scope of its equation
|}]
let h2 (type a b) (x : (a, b) eq) =
match x, [] with
| _, [(_ : b)] -> []
| Refl, [(_ : a) | (_ : b)] -> []
;;
[%%expect{|
Line 4, characters 4-29:
4 | | Refl, [(_ : a) | (_ : b)] -> []
^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This pattern matches values of type (a, b) eq * b list
This instance of b is ambiguous:
it would escape the scope of its equation
|}]
let h3 (type a b) (x : (a, b) eq) =
match x, [] with
| _, [(_ : a)] -> []
| Refl, [(_ : b) | (_ : a)] -> []
;;
[%%expect{|
Line 4, characters 4-29:
4 | | Refl, [(_ : b) | (_ : a)] -> []
^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This pattern matches values of type (a, b) eq * b list
This instance of b is ambiguous:
it would escape the scope of its equation
|}]
module T : sig
type t
type u
val eq : (t, u) eq
end = struct
type t = int
type u = int
let eq = Refl
end;;
[%%expect{|
module T : sig type t type u val eq : (t, u) eq end
|}]
module M = struct
let r = ref []
end
let foo p (e : (T.t, T.u) eq) (x : T.t) (y : T.u) =
match e with
| Refl ->
let z = if p then x else y in
let module N = struct
module type S = module type of struct let r = ref [z] end
end in
let module O : N.S = M in
()
module type S = module type of M ;;
[%%expect{|
module M : sig val r : '_weak1 list ref end
Line 12, characters 25-26:
12 | let module O : N.S = M in
^
Error: Signature mismatch:
Modules do not match:
sig val r : '_weak1 list ref end
is not included in
N.S
Values do not match:
val r : '_weak1 list ref
is not included in
val r : T.u list ref
The type '_weak1 list ref is not compatible with the type T.u list ref
Type '_weak1 is not compatible with type T.u = T.t
This instance of T.t is ambiguous:
it would escape the scope of its equation
|}]
module M = struct
let r = ref []
end
let foo p (e : (T.u, T.t) eq) (x : T.t) (y : T.u) =
match e with
| Refl ->
let z = if p then x else y in
let module N = struct
module type S = module type of struct let r = ref [z] end
end in
let module O : N.S = M in
()
module type S = module type of M ;;
[%%expect{|
module M : sig val r : '_weak2 list ref end
Line 12, characters 25-26:
12 | let module O : N.S = M in
^
Error: Signature mismatch:
Modules do not match:
sig val r : '_weak2 list ref end
is not included in
N.S
Values do not match:
val r : '_weak2 list ref
is not included in
val r : T.t list ref
The type '_weak2 list ref is not compatible with the type T.t list ref
Type '_weak2 is not compatible with type T.t = T.u
This instance of T.u is ambiguous:
it would escape the scope of its equation
|}]
|
c7aca3ab8b2af581576af189013584872bcf6a425cf5c37081129b158a120fdd | ryantm/nixpkgs-update | Nix.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
module Nix
( assertNewerVersion,
assertOldVersionOn,
binPath,
build,
cachix,
getAttrString,
getChangelog,
getDerivationFile,
getDescription,
getHash,
getHashFromBuild,
getHomepage,
getIsBroken,
getMaintainers,
getPatches,
getSrcUrl,
hasPatchNamed,
hasUpdateScript,
lookupAttrPath,
numberOfFetchers,
numberOfHashes,
resultLink,
runUpdateScript,
fakeHash,
version,
Raw (..),
)
where
import Data.Maybe (fromJust)
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TL
import qualified Git
import Language.Haskell.TH.Env (envQ)
import OurPrelude
import qualified System.Process.Typed as TP
import System.Exit()
import Utils (UpdateEnv (..), nixBuildOptions, nixCommonOptions, srcOrMain)
import Prelude hiding (log)
binPath :: String
binPath = fromJust ($$(envQ "NIX") :: Maybe String) <> "/bin"
data Env = Env [(String, String)]
data Raw
= Raw
| NoRaw
data EvalOptions = EvalOptions Raw Env
rawOpt :: Raw -> [String]
rawOpt Raw = ["--raw"]
rawOpt NoRaw = []
nixEvalApply ::
MonadIO m =>
Text ->
Text ->
ExceptT Text m Text
nixEvalApply applyFunc attrPath =
ourReadProcess_
(proc (binPath <> "/nix") (["eval", ".#" <> T.unpack attrPath, "--apply", T.unpack applyFunc]))
& fmapRT (fst >>> T.strip)
nixEvalApplyRaw ::
MonadIO m =>
Text ->
Text ->
ExceptT Text m Text
nixEvalApplyRaw applyFunc attrPath =
ourReadProcess_
(proc (binPath <> "/nix") (["eval", ".#" <> T.unpack attrPath, "--raw", "--apply", T.unpack applyFunc]))
& fmapRT (fst >>> T.strip)
nixEvalExpr ::
MonadIO m =>
Text ->
ExceptT Text m Text
nixEvalExpr expr =
ourReadProcess_
(proc (binPath <> "/nix") (["eval", "--expr", T.unpack expr]))
& fmapRT (fst >>> T.strip)
-- Error if the "new version" is actually newer according to nix
assertNewerVersion :: MonadIO m => UpdateEnv -> ExceptT Text m ()
assertNewerVersion updateEnv = do
versionComparison <-
nixEvalExpr
( "(builtins.compareVersions \""
<> newVersion updateEnv
<> "\" \""
<> oldVersion updateEnv
<> "\")"
)
case versionComparison of
"1" -> return ()
a ->
throwE
( newVersion updateEnv
<> " is not newer than "
<> oldVersion updateEnv
<> " according to Nix; versionComparison: "
<> a
<> " "
)
-- This is extremely slow but gives us the best results we know of
lookupAttrPath :: MonadIO m => UpdateEnv -> ExceptT Text m Text
lookupAttrPath updateEnv =
-- lookup attrpath by nix-env
(proc
(binPath <> "/nix-env")
( [ "-qa",
(packageName updateEnv <> "-" <> oldVersion updateEnv) & T.unpack,
"-f",
".",
"--attr-path"
]
<> nixCommonOptions
)
& ourReadProcess_
& fmapRT (fst >>> T.lines >>> head >>> T.words >>> head))
<|>
-- if that fails, check by attrpath
(getAttrString "name" (packageName updateEnv))
& fmapRT (const (packageName updateEnv))
getDerivationFile :: MonadIO m => Text -> ExceptT Text m Text
getDerivationFile attrPath = do
npDir <- liftIO $ Git.nixpkgsDir
proc "env" ["EDITOR=echo", (binPath <> "/nix"), "edit", attrPath & T.unpack, "-f", "."]
& ourReadProcess_
& fmapRT (fst >>> T.strip >>> T.stripPrefix (T.pack npDir <> "/") >>> fromJust)
-- Get an attribute that can be evaluated off a derivation, as in:
getAttr " cargoSha256 " " ripgrep " - > 0lwz661rbm7kwkd6mallxym1pz8ynda5f03ynjfd16vrazy2dj21
getAttr :: MonadIO m => Text -> Text -> ExceptT Text m Text
getAttr attr = srcOrMain (nixEvalApply ("p: p."<> attr))
getAttrString :: MonadIO m => Text -> Text -> ExceptT Text m Text
getAttrString attr = srcOrMain (nixEvalApplyRaw ("p: p."<> attr))
getHash :: MonadIO m => Text -> ExceptT Text m Text
getHash = getAttrString "drvAttrs.outputHash"
getMaintainers :: MonadIO m => Text -> ExceptT Text m Text
getMaintainers =
nixEvalApplyRaw "p: let gh = m : m.github or \"\"; nonempty = s: s != \"\"; addAt = s: \"@\"+s; in builtins.concatStringsSep \" \" (map addAt (builtins.filter nonempty (map gh p.meta.maintainers or [])))"
readNixBool :: MonadIO m => ExceptT Text m Text -> ExceptT Text m Bool
readNixBool t = do
text <- t
case text of
"true" -> return True
"false" -> return False
a -> throwE ("Failed to read expected nix boolean " <> a <> " ")
getIsBroken :: MonadIO m => Text -> ExceptT Text m Bool
getIsBroken attrPath =
getAttr "meta.broken" attrPath
& readNixBool
getChangelog :: MonadIO m => Text -> ExceptT Text m Text
getChangelog = nixEvalApplyRaw "p: p.meta.changelog or \"\""
getDescription :: MonadIO m => Text -> ExceptT Text m Text
getDescription = nixEvalApplyRaw "p: p.meta.description or \"\""
getHomepage :: MonadIO m => Text -> ExceptT Text m Text
getHomepage = nixEvalApplyRaw "p: p.meta.homepage or \"\""
getSrcUrl :: MonadIO m => Text -> ExceptT Text m Text
getSrcUrl = srcOrMain
(nixEvalApplyRaw "p: builtins.elemAt p.drvAttrs.urls 0")
buildCmd :: Text -> ProcessConfig () () ()
buildCmd attrPath =
silently $ proc (binPath <> "/nix-build") (nixBuildOptions ++ ["-A", attrPath & T.unpack])
log :: Text -> ProcessConfig () () ()
log attrPath = proc (binPath <> "/nix") ["log", "-f", ".", attrPath & T.unpack]
build :: MonadIO m => Text -> ExceptT Text m ()
build attrPath =
(buildCmd attrPath & runProcess_ & tryIOTextET)
<|> ( do
_ <- buildFailedLog
throwE "nix log failed trying to get build logs "
)
where
buildFailedLog = do
buildLog <-
ourReadProcessInterleaved_ (log attrPath)
& fmap (T.lines >>> reverse >>> take 30 >>> reverse >>> T.unlines)
throwE ("nix build failed.\n" <> buildLog <> " ")
cachix :: MonadIO m => Text -> ExceptT Text m ()
cachix resultPath =
( setStdin
(byteStringInput (TL.encodeUtf8 (TL.fromStrict resultPath)))
(shell "cachix push nix-community")
& runProcess_
& tryIOTextET
)
<|> throwE "pushing to cachix failed"
numberOfFetchers :: Text -> Int
numberOfFetchers derivationContents =
countUp "fetchurl {" + countUp "fetchgit {" + countUp "fetchFromGitHub {"
where
countUp x = T.count x derivationContents
-- Sum the number of things that look like fixed-output derivation hashes
numberOfHashes :: Text -> Int
numberOfHashes derivationContents =
sum $ map countUp ["sha256 =", "sha256=", "cargoSha256 =", "cargoHash =", "vendorSha256 =", "vendorHash =", "hash ="]
where
countUp x = T.count x derivationContents
assertOldVersionOn ::
MonadIO m => UpdateEnv -> Text -> Text -> ExceptT Text m ()
assertOldVersionOn updateEnv branchName contents =
tryAssert
("Old version " <> oldVersionPattern <> " not present in " <> branchName <> " derivation file with contents: " <> contents)
(oldVersionPattern `T.isInfixOf` contents)
where
oldVersionPattern = oldVersion updateEnv <> "\""
resultLink :: MonadIO m => ExceptT Text m Text
resultLink =
T.strip
<$> ( ourReadProcessInterleaved_ "readlink ./result"
<|> ourReadProcessInterleaved_ "readlink ./result-bin"
<|> ourReadProcessInterleaved_ "readlink ./result-dev"
)
<|> throwE "Could not find result link. "
fakeHash :: Text
fakeHash = "sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
-- fixed-output derivation produced path '/nix/store/fg2hz90z5bc773gpsx4gfxn3l6fl66nw-source' with sha256 hash '0q1lsgc1621czrg49nmabq6am9sgxa9syxrwzlksqqr4dyzw4nmf' instead of the expected hash '0bp22mzkjy48gncj5vm9b7whzrggcbs5pd4cnb6k8jpl9j02dhdv'
getHashFromBuild :: MonadIO m => Text -> ExceptT Text m Text
getHashFromBuild =
srcOrMain
( \attrPath -> do
(exitCode, _, stderr) <- buildCmd attrPath & readProcess
when (exitCode == ExitSuccess) $ throwE "build succeeded unexpectedly"
let stdErrText = bytestringToText stderr
let firstSplit = T.splitOn "got: " stdErrText
firstSplitSecondPart <-
tryAt
("stderr did not split as expected full stderr was: \n" <> stdErrText)
firstSplit
1
let secondSplit = T.splitOn "\n" firstSplitSecondPart
tryHead
( "stderr did not split second part as expected full stderr was: \n"
<> stdErrText
<> "\nfirstSplitSecondPart:\n"
<> firstSplitSecondPart
)
secondSplit
)
version :: MonadIO m => ExceptT Text m Text
version = ourReadProcessInterleaved_ (proc (binPath <> "/nix") ["--version"])
getPatches :: MonadIO m => Text -> ExceptT Text m Text
getPatches =
nixEvalApply "p: map (patch: patch.name) p.patches"
hasPatchNamed :: MonadIO m => Text -> Text -> ExceptT Text m Bool
hasPatchNamed attrPath name = do
ps <- getPatches attrPath
return $ name `T.isInfixOf` ps
hasUpdateScript :: MonadIO m => Text -> ExceptT Text m Bool
hasUpdateScript attrPath= do
nixEvalApply
"p: builtins.hasAttr \"updateScript\" p" attrPath
& readNixBool
runUpdateScript :: MonadIO m => Text -> ExceptT Text m (ExitCode, Text)
runUpdateScript attrPath = do
let timeout = "10m" :: Text
(exitCode, output) <- ourReadProcessInterleaved $
TP.setStdin (TP.byteStringInput "\n") $
proc "timeout" [T.unpack timeout, "nix-shell", "maintainers/scripts/update.nix", "--argstr", "package", T.unpack attrPath ]
case exitCode of
ExitFailure 124 -> do
return (exitCode, "updateScript for " <> attrPath <> " took longer than " <> timeout <> " and timed out. Other output: " <> output)
_ -> do
return (exitCode, output)
| null | https://raw.githubusercontent.com/ryantm/nixpkgs-update/fd546296e7481ac1ab23350abbdbb33d4cf1ccec/src/Nix.hs | haskell | # LANGUAGE OverloadedStrings #
Error if the "new version" is actually newer according to nix
This is extremely slow but gives us the best results we know of
lookup attrpath by nix-env
if that fails, check by attrpath
Get an attribute that can be evaluated off a derivation, as in:
Sum the number of things that look like fixed-output derivation hashes
fixed-output derivation produced path '/nix/store/fg2hz90z5bc773gpsx4gfxn3l6fl66nw-source' with sha256 hash '0q1lsgc1621czrg49nmabq6am9sgxa9syxrwzlksqqr4dyzw4nmf' instead of the expected hash '0bp22mzkjy48gncj5vm9b7whzrggcbs5pd4cnb6k8jpl9j02dhdv' | # LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
module Nix
( assertNewerVersion,
assertOldVersionOn,
binPath,
build,
cachix,
getAttrString,
getChangelog,
getDerivationFile,
getDescription,
getHash,
getHashFromBuild,
getHomepage,
getIsBroken,
getMaintainers,
getPatches,
getSrcUrl,
hasPatchNamed,
hasUpdateScript,
lookupAttrPath,
numberOfFetchers,
numberOfHashes,
resultLink,
runUpdateScript,
fakeHash,
version,
Raw (..),
)
where
import Data.Maybe (fromJust)
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TL
import qualified Git
import Language.Haskell.TH.Env (envQ)
import OurPrelude
import qualified System.Process.Typed as TP
import System.Exit()
import Utils (UpdateEnv (..), nixBuildOptions, nixCommonOptions, srcOrMain)
import Prelude hiding (log)
binPath :: String
binPath = fromJust ($$(envQ "NIX") :: Maybe String) <> "/bin"
data Env = Env [(String, String)]
data Raw
= Raw
| NoRaw
data EvalOptions = EvalOptions Raw Env
rawOpt :: Raw -> [String]
rawOpt Raw = ["--raw"]
rawOpt NoRaw = []
nixEvalApply ::
MonadIO m =>
Text ->
Text ->
ExceptT Text m Text
nixEvalApply applyFunc attrPath =
ourReadProcess_
(proc (binPath <> "/nix") (["eval", ".#" <> T.unpack attrPath, "--apply", T.unpack applyFunc]))
& fmapRT (fst >>> T.strip)
nixEvalApplyRaw ::
MonadIO m =>
Text ->
Text ->
ExceptT Text m Text
nixEvalApplyRaw applyFunc attrPath =
ourReadProcess_
(proc (binPath <> "/nix") (["eval", ".#" <> T.unpack attrPath, "--raw", "--apply", T.unpack applyFunc]))
& fmapRT (fst >>> T.strip)
nixEvalExpr ::
MonadIO m =>
Text ->
ExceptT Text m Text
nixEvalExpr expr =
ourReadProcess_
(proc (binPath <> "/nix") (["eval", "--expr", T.unpack expr]))
& fmapRT (fst >>> T.strip)
assertNewerVersion :: MonadIO m => UpdateEnv -> ExceptT Text m ()
assertNewerVersion updateEnv = do
versionComparison <-
nixEvalExpr
( "(builtins.compareVersions \""
<> newVersion updateEnv
<> "\" \""
<> oldVersion updateEnv
<> "\")"
)
case versionComparison of
"1" -> return ()
a ->
throwE
( newVersion updateEnv
<> " is not newer than "
<> oldVersion updateEnv
<> " according to Nix; versionComparison: "
<> a
<> " "
)
lookupAttrPath :: MonadIO m => UpdateEnv -> ExceptT Text m Text
lookupAttrPath updateEnv =
(proc
(binPath <> "/nix-env")
( [ "-qa",
(packageName updateEnv <> "-" <> oldVersion updateEnv) & T.unpack,
"-f",
".",
"--attr-path"
]
<> nixCommonOptions
)
& ourReadProcess_
& fmapRT (fst >>> T.lines >>> head >>> T.words >>> head))
<|>
(getAttrString "name" (packageName updateEnv))
& fmapRT (const (packageName updateEnv))
getDerivationFile :: MonadIO m => Text -> ExceptT Text m Text
getDerivationFile attrPath = do
npDir <- liftIO $ Git.nixpkgsDir
proc "env" ["EDITOR=echo", (binPath <> "/nix"), "edit", attrPath & T.unpack, "-f", "."]
& ourReadProcess_
& fmapRT (fst >>> T.strip >>> T.stripPrefix (T.pack npDir <> "/") >>> fromJust)
getAttr " cargoSha256 " " ripgrep " - > 0lwz661rbm7kwkd6mallxym1pz8ynda5f03ynjfd16vrazy2dj21
getAttr :: MonadIO m => Text -> Text -> ExceptT Text m Text
getAttr attr = srcOrMain (nixEvalApply ("p: p."<> attr))
getAttrString :: MonadIO m => Text -> Text -> ExceptT Text m Text
getAttrString attr = srcOrMain (nixEvalApplyRaw ("p: p."<> attr))
getHash :: MonadIO m => Text -> ExceptT Text m Text
getHash = getAttrString "drvAttrs.outputHash"
getMaintainers :: MonadIO m => Text -> ExceptT Text m Text
getMaintainers =
nixEvalApplyRaw "p: let gh = m : m.github or \"\"; nonempty = s: s != \"\"; addAt = s: \"@\"+s; in builtins.concatStringsSep \" \" (map addAt (builtins.filter nonempty (map gh p.meta.maintainers or [])))"
readNixBool :: MonadIO m => ExceptT Text m Text -> ExceptT Text m Bool
readNixBool t = do
text <- t
case text of
"true" -> return True
"false" -> return False
a -> throwE ("Failed to read expected nix boolean " <> a <> " ")
getIsBroken :: MonadIO m => Text -> ExceptT Text m Bool
getIsBroken attrPath =
getAttr "meta.broken" attrPath
& readNixBool
getChangelog :: MonadIO m => Text -> ExceptT Text m Text
getChangelog = nixEvalApplyRaw "p: p.meta.changelog or \"\""
getDescription :: MonadIO m => Text -> ExceptT Text m Text
getDescription = nixEvalApplyRaw "p: p.meta.description or \"\""
getHomepage :: MonadIO m => Text -> ExceptT Text m Text
getHomepage = nixEvalApplyRaw "p: p.meta.homepage or \"\""
getSrcUrl :: MonadIO m => Text -> ExceptT Text m Text
getSrcUrl = srcOrMain
(nixEvalApplyRaw "p: builtins.elemAt p.drvAttrs.urls 0")
buildCmd :: Text -> ProcessConfig () () ()
buildCmd attrPath =
silently $ proc (binPath <> "/nix-build") (nixBuildOptions ++ ["-A", attrPath & T.unpack])
log :: Text -> ProcessConfig () () ()
log attrPath = proc (binPath <> "/nix") ["log", "-f", ".", attrPath & T.unpack]
build :: MonadIO m => Text -> ExceptT Text m ()
build attrPath =
(buildCmd attrPath & runProcess_ & tryIOTextET)
<|> ( do
_ <- buildFailedLog
throwE "nix log failed trying to get build logs "
)
where
buildFailedLog = do
buildLog <-
ourReadProcessInterleaved_ (log attrPath)
& fmap (T.lines >>> reverse >>> take 30 >>> reverse >>> T.unlines)
throwE ("nix build failed.\n" <> buildLog <> " ")
cachix :: MonadIO m => Text -> ExceptT Text m ()
cachix resultPath =
( setStdin
(byteStringInput (TL.encodeUtf8 (TL.fromStrict resultPath)))
(shell "cachix push nix-community")
& runProcess_
& tryIOTextET
)
<|> throwE "pushing to cachix failed"
numberOfFetchers :: Text -> Int
numberOfFetchers derivationContents =
countUp "fetchurl {" + countUp "fetchgit {" + countUp "fetchFromGitHub {"
where
countUp x = T.count x derivationContents
numberOfHashes :: Text -> Int
numberOfHashes derivationContents =
sum $ map countUp ["sha256 =", "sha256=", "cargoSha256 =", "cargoHash =", "vendorSha256 =", "vendorHash =", "hash ="]
where
countUp x = T.count x derivationContents
assertOldVersionOn ::
MonadIO m => UpdateEnv -> Text -> Text -> ExceptT Text m ()
assertOldVersionOn updateEnv branchName contents =
tryAssert
("Old version " <> oldVersionPattern <> " not present in " <> branchName <> " derivation file with contents: " <> contents)
(oldVersionPattern `T.isInfixOf` contents)
where
oldVersionPattern = oldVersion updateEnv <> "\""
resultLink :: MonadIO m => ExceptT Text m Text
resultLink =
T.strip
<$> ( ourReadProcessInterleaved_ "readlink ./result"
<|> ourReadProcessInterleaved_ "readlink ./result-bin"
<|> ourReadProcessInterleaved_ "readlink ./result-dev"
)
<|> throwE "Could not find result link. "
fakeHash :: Text
fakeHash = "sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
getHashFromBuild :: MonadIO m => Text -> ExceptT Text m Text
getHashFromBuild =
srcOrMain
( \attrPath -> do
(exitCode, _, stderr) <- buildCmd attrPath & readProcess
when (exitCode == ExitSuccess) $ throwE "build succeeded unexpectedly"
let stdErrText = bytestringToText stderr
let firstSplit = T.splitOn "got: " stdErrText
firstSplitSecondPart <-
tryAt
("stderr did not split as expected full stderr was: \n" <> stdErrText)
firstSplit
1
let secondSplit = T.splitOn "\n" firstSplitSecondPart
tryHead
( "stderr did not split second part as expected full stderr was: \n"
<> stdErrText
<> "\nfirstSplitSecondPart:\n"
<> firstSplitSecondPart
)
secondSplit
)
version :: MonadIO m => ExceptT Text m Text
version = ourReadProcessInterleaved_ (proc (binPath <> "/nix") ["--version"])
getPatches :: MonadIO m => Text -> ExceptT Text m Text
getPatches =
nixEvalApply "p: map (patch: patch.name) p.patches"
hasPatchNamed :: MonadIO m => Text -> Text -> ExceptT Text m Bool
hasPatchNamed attrPath name = do
ps <- getPatches attrPath
return $ name `T.isInfixOf` ps
hasUpdateScript :: MonadIO m => Text -> ExceptT Text m Bool
hasUpdateScript attrPath= do
nixEvalApply
"p: builtins.hasAttr \"updateScript\" p" attrPath
& readNixBool
runUpdateScript :: MonadIO m => Text -> ExceptT Text m (ExitCode, Text)
runUpdateScript attrPath = do
let timeout = "10m" :: Text
(exitCode, output) <- ourReadProcessInterleaved $
TP.setStdin (TP.byteStringInput "\n") $
proc "timeout" [T.unpack timeout, "nix-shell", "maintainers/scripts/update.nix", "--argstr", "package", T.unpack attrPath ]
case exitCode of
ExitFailure 124 -> do
return (exitCode, "updateScript for " <> attrPath <> " took longer than " <> timeout <> " and timed out. Other output: " <> output)
_ -> do
return (exitCode, output)
|
fe455057a23ae48c8e57ffcf5b6d5e0b4c00be6608af1cf765afe00d08e9cb01 | ds-wizard/engine-backend | List_DELETE.hs | module Wizard.Specs.API.Locale.List_DELETE (
list_DELETE,
) where
import Network.HTTP.Types
import Network.Wai (Application)
import Test.Hspec
import Test.Hspec.Wai hiding (shouldRespondWith)
import Test.Hspec.Wai.Matcher
import Wizard.Database.DAO.Locale.LocaleDAO
import qualified Wizard.Database.Migration.Development.Locale.LocaleMigration as LOC_Migration
import Wizard.Model.Context.AppContext
import SharedTest.Specs.API.Common
import Wizard.Specs.API.Common
import Wizard.Specs.Common
-- ------------------------------------------------------------------------
-- DELETE /locales
-- ------------------------------------------------------------------------
list_DELETE :: AppContext -> SpecWith ((), Application)
list_DELETE appContext =
describe "DELETE /locales" $ do
test_204 appContext
test_401 appContext
test_403 appContext
-- ----------------------------------------------------
-- ----------------------------------------------------
-- ----------------------------------------------------
reqMethod = methodDelete
reqUrl = "/locales?organizationId=global&localeId=dutch"
reqHeaders = [reqAuthHeader, reqCtHeader]
reqBody = ""
-- ----------------------------------------------------
-- ----------------------------------------------------
-- ----------------------------------------------------
test_204 appContext =
it "HTTP 204 NO CONTENT" $
-- GIVEN: Prepare expectation
do
let expStatus = 204
let expHeaders = resCorsHeaders
let expBody = ""
-- AND: Run migrations
runInContextIO LOC_Migration.runMigration appContext
-- WHEN: Call API
response <- request reqMethod reqUrl reqHeaders reqBody
-- THEN: Compare response with expectation
let responseMatcher =
ResponseMatcher {matchHeaders = expHeaders, matchStatus = expStatus, matchBody = bodyEquals expBody}
response `shouldRespondWith` responseMatcher
AND : Find result in DB and compare with expectation state
assertCountInDB findLocales appContext 2
-- ----------------------------------------------------
-- ----------------------------------------------------
-- ----------------------------------------------------
test_401 appContext = createAuthTest reqMethod reqUrl [reqCtHeader] reqBody
-- ----------------------------------------------------
-- ----------------------------------------------------
-- ----------------------------------------------------
test_403 appContext = createNoPermissionTest appContext reqMethod reqUrl [reqCtHeader] reqBody "LOC_PERM"
| null | https://raw.githubusercontent.com/ds-wizard/engine-backend/0ec94a4b0545f2de8a4e59686a4376023719d5e7/engine-wizard/test/Wizard/Specs/API/Locale/List_DELETE.hs | haskell | ------------------------------------------------------------------------
DELETE /locales
------------------------------------------------------------------------
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
GIVEN: Prepare expectation
AND: Run migrations
WHEN: Call API
THEN: Compare response with expectation
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
---------------------------------------------------- | module Wizard.Specs.API.Locale.List_DELETE (
list_DELETE,
) where
import Network.HTTP.Types
import Network.Wai (Application)
import Test.Hspec
import Test.Hspec.Wai hiding (shouldRespondWith)
import Test.Hspec.Wai.Matcher
import Wizard.Database.DAO.Locale.LocaleDAO
import qualified Wizard.Database.Migration.Development.Locale.LocaleMigration as LOC_Migration
import Wizard.Model.Context.AppContext
import SharedTest.Specs.API.Common
import Wizard.Specs.API.Common
import Wizard.Specs.Common
list_DELETE :: AppContext -> SpecWith ((), Application)
list_DELETE appContext =
describe "DELETE /locales" $ do
test_204 appContext
test_401 appContext
test_403 appContext
reqMethod = methodDelete
reqUrl = "/locales?organizationId=global&localeId=dutch"
reqHeaders = [reqAuthHeader, reqCtHeader]
reqBody = ""
test_204 appContext =
it "HTTP 204 NO CONTENT" $
do
let expStatus = 204
let expHeaders = resCorsHeaders
let expBody = ""
runInContextIO LOC_Migration.runMigration appContext
response <- request reqMethod reqUrl reqHeaders reqBody
let responseMatcher =
ResponseMatcher {matchHeaders = expHeaders, matchStatus = expStatus, matchBody = bodyEquals expBody}
response `shouldRespondWith` responseMatcher
AND : Find result in DB and compare with expectation state
assertCountInDB findLocales appContext 2
test_401 appContext = createAuthTest reqMethod reqUrl [reqCtHeader] reqBody
test_403 appContext = createNoPermissionTest appContext reqMethod reqUrl [reqCtHeader] reqBody "LOC_PERM"
|
3db117d0fde6d8af30bccf20ca695ea858f9ba1aaf71076a7f70f175c5b26126 | chris-taylor/Haskeme | Setup.hs | --#!/usr/bin/env runhaskell
import Distribution.Simple
main = defaultMain | null | https://raw.githubusercontent.com/chris-taylor/Haskeme/e9f9fc93c727c6127ac9e1d7e05f105a0fee4a38/Setup.hs | haskell | #!/usr/bin/env runhaskell | import Distribution.Simple
main = defaultMain |
18e2a66e0d6f434ca79b3b2ef08eb5953c93e3065d49e2a8911ab400fffc33a2 | hyperfiddle/electric | electric_recursion.cljc | (ns user.electric.electric-recursion
(:require [hyperfiddle.electric :as e]
[hyperfiddle.rcf :refer [tests tap % with]]))
(hyperfiddle.rcf/enable!)
Electric compiler has n't implemented recursion syntax yet but the primitives are in place
; so you can do it with explicit dynamic vars
all Electric defs are dynamic
(e/def Pong)
(tests
"recursion"
(def !x (atom 0))
(with (e/run
(try
(binding [Ping (e/fn [x] (case x 0 [:done] (cons x (Ping. (dec x)))))]
(tap (Ping. (e/watch !x))))))
% := [:done]
(swap! !x inc)
% := [1 :done]
(swap! !x inc)
% := [2 1 :done]
))
(tests
"mutual recursion"
(def !x (atom 1))
(with (e/run
(binding [Ping (e/fn [x] (case x 0 [:done] (cons x (Pong. (dec x)))))
Pong (e/fn [x] (Ping. x))]
(tap (Ping. (e/watch !x)))))
% := [1 :done]
(swap! !x inc)
% := [2 1 :done]))
(tests
"reactive fibonacci"
(e/def Fib)
(def !x (atom 5))
(with (e/run (binding [Fib (e/fn [n]
(case n
0 0
1 1
(+ (Fib. (- n 2)) ; self recur
(Fib. (- n 1)))))]
(tap (Fib. (e/watch !x)))))
% := 5
(swap! !x inc)
; reactive engine will reuse the topmost frame, it is still naive fib though
% := 8))
Todo : self - recursion and Clojure recur form
| null | https://raw.githubusercontent.com/hyperfiddle/electric/2446937b21440bf4faed8123e2ee544110203cee/src-docs/user/electric/electric_recursion.cljc | clojure | so you can do it with explicit dynamic vars
self recur
reactive engine will reuse the topmost frame, it is still naive fib though | (ns user.electric.electric-recursion
(:require [hyperfiddle.electric :as e]
[hyperfiddle.rcf :refer [tests tap % with]]))
(hyperfiddle.rcf/enable!)
Electric compiler has n't implemented recursion syntax yet but the primitives are in place
all Electric defs are dynamic
(e/def Pong)
(tests
"recursion"
(def !x (atom 0))
(with (e/run
(try
(binding [Ping (e/fn [x] (case x 0 [:done] (cons x (Ping. (dec x)))))]
(tap (Ping. (e/watch !x))))))
% := [:done]
(swap! !x inc)
% := [1 :done]
(swap! !x inc)
% := [2 1 :done]
))
(tests
"mutual recursion"
(def !x (atom 1))
(with (e/run
(binding [Ping (e/fn [x] (case x 0 [:done] (cons x (Pong. (dec x)))))
Pong (e/fn [x] (Ping. x))]
(tap (Ping. (e/watch !x)))))
% := [1 :done]
(swap! !x inc)
% := [2 1 :done]))
(tests
"reactive fibonacci"
(e/def Fib)
(def !x (atom 5))
(with (e/run (binding [Fib (e/fn [n]
(case n
0 0
1 1
(Fib. (- n 1)))))]
(tap (Fib. (e/watch !x)))))
% := 5
(swap! !x inc)
% := 8))
Todo : self - recursion and Clojure recur form
|
57d7739dbece189a54b9d5544ea02be7d8895fab5d6328ac7e561e1de449ccf5 | dhess/sicp-solutions | ex1.44.scm | (define dx 0.00001)
(define (smooth f)
(define (ave a b c) (/ (+ a b c) 3))
(lambda (x)
(ave (f (- x dx)) (f x) (f (+ x dx)))))
(define (compose f g)
(lambda (x) (f (g x))))
(define (inc x) (+ x 1))
(define (repeated f n)
(define (repeated-iter i result)
(if (= i n)
result
(repeated-iter (inc i) (compose f result))))
(repeated-iter 1 f))
(define (n-fold-smooth f n)
((repeated smooth n) f))
| null | https://raw.githubusercontent.com/dhess/sicp-solutions/2cf78db98917e9cb1252efda76fddc8e45fe4140/chap1/ex1.44.scm | scheme | (define dx 0.00001)
(define (smooth f)
(define (ave a b c) (/ (+ a b c) 3))
(lambda (x)
(ave (f (- x dx)) (f x) (f (+ x dx)))))
(define (compose f g)
(lambda (x) (f (g x))))
(define (inc x) (+ x 1))
(define (repeated f n)
(define (repeated-iter i result)
(if (= i n)
result
(repeated-iter (inc i) (compose f result))))
(repeated-iter 1 f))
(define (n-fold-smooth f n)
((repeated smooth n) f))
| |
470698d6d1fd37b72f2243b2774bb1d3a93f3d8f0c335b4ae3e580338c8e0250 | pyr/warp | layout.cljs | (ns warp.client.layout
(:require [clojure.string :as str]))
(defn h4
[& fragments]
[:h4 (str/join " " fragments)])
(defn h3
[& fragments]
[:h3 (str/join " " fragments)])
(defn h2
[& fragments]
[:h2 (str/join " " fragments)])
(defn h1
[& fragments]
[:h1 (str/join " " fragments)])
(defn link-to
[url link]
[:a {:href url} link])
(defn code
[& fragments]
[:code (str/join " " fragments)])
(defn console
[& fragments]
[:pre {:class "console"} (str/join " " fragments)])
(defn tr
[& row]
[:tr
(for [[i td] (map-indexed vector row)]
^{:key (str "tr-" i)} [:td td])])
(defn panel
[title content]
[:div {:class "panel panel-default"}
[:div {:class "panel-heading"}
[:h3 {:class "modal-title panel-title"} title]]
[:div {:class "panel-body"}
content]])
(defn table-striped
[columns rows]
[:table {:class "table table-striped"}
[:thead
[:tr (for [[i th] (map-indexed vector columns)]
^{:key (str "th-" i)} [:th th])]]
[:tbody rows]])
| null | https://raw.githubusercontent.com/pyr/warp/c3ee96d90b233a47c1104b4339fed071ec8afe68/src/warp/client/layout.cljs | clojure | (ns warp.client.layout
(:require [clojure.string :as str]))
(defn h4
[& fragments]
[:h4 (str/join " " fragments)])
(defn h3
[& fragments]
[:h3 (str/join " " fragments)])
(defn h2
[& fragments]
[:h2 (str/join " " fragments)])
(defn h1
[& fragments]
[:h1 (str/join " " fragments)])
(defn link-to
[url link]
[:a {:href url} link])
(defn code
[& fragments]
[:code (str/join " " fragments)])
(defn console
[& fragments]
[:pre {:class "console"} (str/join " " fragments)])
(defn tr
[& row]
[:tr
(for [[i td] (map-indexed vector row)]
^{:key (str "tr-" i)} [:td td])])
(defn panel
[title content]
[:div {:class "panel panel-default"}
[:div {:class "panel-heading"}
[:h3 {:class "modal-title panel-title"} title]]
[:div {:class "panel-body"}
content]])
(defn table-striped
[columns rows]
[:table {:class "table table-striped"}
[:thead
[:tr (for [[i th] (map-indexed vector columns)]
^{:key (str "th-" i)} [:th th])]]
[:tbody rows]])
| |
330ab164a269a14ceeb9393019b919a48e0c79715ff9ed6350dc5a373f4df7ce | mbenke/zpf2012 | DotP.hs | {-# LANGUAGE ParallelArrays #-}
{-# OPTIONS_GHC -fvectorise #-}
module DotP where
import qualified Prelude
import Data.Array.Parallel
import Data.Array.Parallel.Prelude
import Data.Array.Parallel.Prelude.Double as D
dotp_double :: [:Double:] -> [:Double:] -> Double
dotp_double xs ys = D.sumP [:x * y | x <- xs | y <- ys:]
dotp_wrapper :: PArray Double -> PArray Double -> Double
# NOINLINE dotp_wrapper #
dotp_wrapper v w = dotp_double (fromPArrayP v) (fromPArrayP w) | null | https://raw.githubusercontent.com/mbenke/zpf2012/faad6468f9400059de1c0735e12a84a2fdf24bb4/Code/dph/DotP.hs | haskell | # LANGUAGE ParallelArrays #
# OPTIONS_GHC -fvectorise # |
module DotP where
import qualified Prelude
import Data.Array.Parallel
import Data.Array.Parallel.Prelude
import Data.Array.Parallel.Prelude.Double as D
dotp_double :: [:Double:] -> [:Double:] -> Double
dotp_double xs ys = D.sumP [:x * y | x <- xs | y <- ys:]
dotp_wrapper :: PArray Double -> PArray Double -> Double
# NOINLINE dotp_wrapper #
dotp_wrapper v w = dotp_double (fromPArrayP v) (fromPArrayP w) |
a86e410f361c9a7abb0e3235f3d78e600dcbca1c25b899abb671a161f038f721 | arenadotio/pgx | pgx_value.ml | open Sexplib0.Sexp_conv
open Pgx_aux
type v = string [@@deriving compare, sexp_of]
type t = v option [@@deriving compare, sexp_of]
exception Conversion_failure of string [@@deriving sexp_of]
let convert_failure ?hint type_ s =
let hint =
match hint with
| None -> ""
| Some hint -> Printf.sprintf " (%s)" hint
in
Conversion_failure (Printf.sprintf "Unable to convert to %s%s: %s" type_ hint s)
|> raise
;;
let required f = function
| Some x -> f x
| None -> raise (Conversion_failure "Expected not-null but got null")
;;
let opt f v = Option.bind v f
let null = None
let of_binary b =
match b with
| "" -> Some ""
| _ ->
(try
let (`Hex hex) = Hex.of_string b in
Some ("\\x" ^ hex)
with
| exn -> convert_failure ~hint:(Printexc.to_string exn) "binary" b)
;;
let to_binary' = function
| "" -> ""
| t ->
(* Skip if not encoded as hex *)
(try
if String.sub t 0 2 <> "\\x"
then t (* Decode if encoded as hex *)
else `Hex (String.sub t 2 (String.length t - 2)) |> Hex.to_string
with
| exn -> convert_failure ~hint:(Printexc.to_string exn) "binary" t)
;;
let to_binary_exn = required to_binary'
let to_binary = Option.map to_binary'
let of_bool = function
| true -> Some "t"
| false -> Some "f"
;;
let to_bool' = function
| "t" -> true
| "f" -> false
| s -> convert_failure "bool" s
;;
let to_bool_exn = required to_bool'
let to_bool = Option.map to_bool'
let of_float' f =
match classify_float f with
| FP_infinite when f > 0. -> "Infinity"
| FP_infinite when f < 0. -> "-Infinity"
| FP_nan -> "NaN"
| _ -> string_of_float f
;;
let of_float f = Some (of_float' f)
let to_float' t =
match String.lowercase_ascii t with
| "infinity" -> infinity
| "-infinity" -> neg_infinity
| "nan" -> nan
| _ ->
(try float_of_string t with
| Failure hint -> convert_failure ~hint "float" t)
;;
let to_float_exn = required to_float'
let to_float = Option.map to_float'
type hstore = (string * string option) list [@@deriving compare, sexp_of]
let of_hstore hstore =
let string_of_quoted str = "\"" ^ str ^ "\"" in
let string_of_mapping (key, value) =
let key_str = string_of_quoted key
and value_str =
match value with
| Some v -> string_of_quoted v
| None -> "NULL"
in
key_str ^ "=>" ^ value_str
in
Some (String.concat ", " (List.map string_of_mapping hstore))
;;
let to_hstore' str =
let expect target stream =
if List.exists (fun c -> c <> Stream.next stream) target
then convert_failure "hstore" str
in
let parse_quoted stream =
let rec loop accum stream =
match Stream.next stream with
| '"' -> String.implode (List.rev accum)
(* FIXME: Slashes don't seem to round-trip properly *)
| '\\' -> loop (Stream.next stream :: accum) stream
| x -> loop (x :: accum) stream
in
expect [ '"' ] stream;
loop [] stream
in
let parse_value stream =
match Stream.peek stream with
| Some 'N' ->
expect [ 'N'; 'U'; 'L'; 'L' ] stream;
None
| _ -> Some (parse_quoted stream)
in
let parse_mapping stream =
let key = parse_quoted stream in
expect [ '='; '>' ] stream;
let value = parse_value stream in
key, value
in
let parse_main stream =
let rec loop accum stream =
let mapping = parse_mapping stream in
match Stream.peek stream with
| Some _ ->
expect [ ','; ' ' ] stream;
loop (mapping :: accum) stream
| None -> mapping :: accum
in
match Stream.peek stream with
| Some _ -> loop [] stream
| None -> []
in
parse_main (Stream.of_string str)
;;
let to_hstore_exn = required to_hstore'
let to_hstore = Option.map to_hstore'
type inet = Ipaddr.t * int [@@deriving compare]
let sexp_of_inet (addr, mask) = [%sexp_of: string * int] (Ipaddr.to_string addr, mask)
let of_inet (addr, mask) =
let hostmask =
match addr with
| Ipaddr.V4 _ -> 32
| Ipaddr.V6 _ -> 128
in
let addr = Ipaddr.to_string addr in
if mask = hostmask
then Some addr
else if mask >= 0 && mask < hostmask
then Some (addr ^ "/" ^ string_of_int mask)
else invalid_arg "mask"
;;
let to_inet' =
let re =
let open Re in
[ group
([ rep (compl [ set ":./" ]); group (set ":."); rep1 (compl [ char '/' ]) ] |> seq)
; opt (seq [ char '/'; group (rep1 any) ])
]
|> seq
|> compile
in
fun str ->
try
let subs = Re.exec re str in
let addr = Ipaddr.of_string_exn (Re.Group.get subs 1) in
(* optional match *)
let mask =
try Re.Group.get subs 3 with
| Not_found -> ""
in
if mask = ""
then addr, if Re.Group.get subs 2 = "." then 32 else 128
else addr, int_of_string mask
with
| exn -> convert_failure ~hint:(Printexc.to_string exn) "inet" str
;;
let to_inet_exn = required to_inet'
let to_inet = Option.map to_inet'
let of_int i = Some (string_of_int i)
let to_int' t =
try int_of_string t with
| Failure hint -> convert_failure ~hint "int" t
;;
let to_int_exn = required to_int'
let to_int = Option.map to_int'
let of_int32 i = Some (Int32.to_string i)
let to_int32' t =
try Int32.of_string t with
| Failure hint -> convert_failure ~hint "int32" t
;;
let to_int32_exn = required to_int32'
let to_int32 = Option.map to_int32'
let of_int64 i = Some (Int64.to_string i)
let to_int64' t =
try Int64.of_string t with
| Failure hint -> convert_failure ~hint "int64" t
;;
let to_int64_exn = required to_int64'
let to_int64 = Option.map to_int64'
let escape_string str =
let buf = Buffer.create 128 in
for i = 0 to String.length str - 1 do
match str.[i] with
| ('"' | '\\') as x ->
Buffer.add_char buf '\\';
Buffer.add_char buf x
| x -> Buffer.add_char buf x
done;
Buffer.contents buf
;;
let of_list (xs : t list) =
let buf = Buffer.create 128 in
Buffer.add_char buf '{';
let adder i x =
if i > 0 then Buffer.add_char buf ',';
match x with
| Some x ->
let x = escape_string x in
Buffer.add_char buf '"';
Buffer.add_string buf x;
Buffer.add_char buf '"'
| None -> Buffer.add_string buf "NULL"
in
List.iteri adder xs;
Buffer.add_char buf '}';
Some (Buffer.contents buf)
;;
let to_list' str =
let n = String.length str in
if n = 0 || str.[0] <> '{' || str.[n - 1] <> '}' then convert_failure "list" str;
let str = String.sub str 1 (n - 2) in
let buf = Buffer.create 128 in
let add_field accum =
let x = Buffer.contents buf in
Buffer.clear buf;
let field =
if x = "NULL"
then None
else (
let n = String.length x in
if n >= 2 && x.[0] = '"' then Some (String.sub x 1 (n - 2)) else Some x)
in
field :: accum
in
let loop (accum, quoted, escaped) = function
| '\\' when not escaped -> accum, quoted, true
| '"' when not escaped ->
Buffer.add_char buf '"';
accum, not quoted, false
| ',' when (not escaped) && not quoted -> add_field accum, false, false
| x ->
Buffer.add_char buf x;
accum, quoted, false
in
let accum, _, _ = String.fold_left loop ([], false, false) str in
let accum = if Buffer.length buf = 0 then accum else add_field accum in
List.rev accum
;;
let to_list_exn = required to_list'
let to_list = Option.map to_list'
type point = float * float [@@deriving compare, sexp_of]
let of_point (x, y) =
let x = of_float' x in
let y = of_float' y in
Some (Printf.sprintf "(%s,%s)" x y)
;;
let to_point' =
let point_re =
let open Re in
let part = seq [ rep space; group (rep any); rep space ] in
[ rep space; char '('; part; char ','; part; char ')'; rep space ]
|> seq
|> whole_string
|> compile
in
fun str ->
try
let subs = Re.exec point_re str in
float_of_string (Re.Group.get subs 1), float_of_string (Re.Group.get subs 2)
with
| exn -> convert_failure ~hint:(Printexc.to_string exn) "point" str
;;
let to_point_exn = required to_point'
let to_point = Option.map to_point'
let of_string t = Some t
let to_string_exn = required (fun t -> t)
let to_string t = t
let unit = Some ""
let to_unit' = function
| "" -> ()
| t -> convert_failure "unit" t
;;
let to_unit_exn = required to_unit'
let to_unit = Option.map to_unit'
type uuid = Uuidm.t [@@deriving compare]
let sexp_of_uuid u = Uuidm.to_string u |> sexp_of_string
let of_uuid s = Some (Uuidm.to_string s)
let to_uuid' t =
match Uuidm.of_string t with
| Some u -> u
| None -> convert_failure "uuid" t
;;
let to_uuid_exn = required to_uuid'
let to_uuid = Option.map to_uuid'
| null | https://raw.githubusercontent.com/arenadotio/pgx/5cc53c729e8ec5171d1909e47505137c7427c2c0/pgx/src/pgx_value.ml | ocaml | Skip if not encoded as hex
Decode if encoded as hex
FIXME: Slashes don't seem to round-trip properly
optional match | open Sexplib0.Sexp_conv
open Pgx_aux
type v = string [@@deriving compare, sexp_of]
type t = v option [@@deriving compare, sexp_of]
exception Conversion_failure of string [@@deriving sexp_of]
let convert_failure ?hint type_ s =
let hint =
match hint with
| None -> ""
| Some hint -> Printf.sprintf " (%s)" hint
in
Conversion_failure (Printf.sprintf "Unable to convert to %s%s: %s" type_ hint s)
|> raise
;;
let required f = function
| Some x -> f x
| None -> raise (Conversion_failure "Expected not-null but got null")
;;
let opt f v = Option.bind v f
let null = None
let of_binary b =
match b with
| "" -> Some ""
| _ ->
(try
let (`Hex hex) = Hex.of_string b in
Some ("\\x" ^ hex)
with
| exn -> convert_failure ~hint:(Printexc.to_string exn) "binary" b)
;;
let to_binary' = function
| "" -> ""
| t ->
(try
if String.sub t 0 2 <> "\\x"
else `Hex (String.sub t 2 (String.length t - 2)) |> Hex.to_string
with
| exn -> convert_failure ~hint:(Printexc.to_string exn) "binary" t)
;;
let to_binary_exn = required to_binary'
let to_binary = Option.map to_binary'
let of_bool = function
| true -> Some "t"
| false -> Some "f"
;;
let to_bool' = function
| "t" -> true
| "f" -> false
| s -> convert_failure "bool" s
;;
let to_bool_exn = required to_bool'
let to_bool = Option.map to_bool'
let of_float' f =
match classify_float f with
| FP_infinite when f > 0. -> "Infinity"
| FP_infinite when f < 0. -> "-Infinity"
| FP_nan -> "NaN"
| _ -> string_of_float f
;;
let of_float f = Some (of_float' f)
let to_float' t =
match String.lowercase_ascii t with
| "infinity" -> infinity
| "-infinity" -> neg_infinity
| "nan" -> nan
| _ ->
(try float_of_string t with
| Failure hint -> convert_failure ~hint "float" t)
;;
let to_float_exn = required to_float'
let to_float = Option.map to_float'
type hstore = (string * string option) list [@@deriving compare, sexp_of]
let of_hstore hstore =
let string_of_quoted str = "\"" ^ str ^ "\"" in
let string_of_mapping (key, value) =
let key_str = string_of_quoted key
and value_str =
match value with
| Some v -> string_of_quoted v
| None -> "NULL"
in
key_str ^ "=>" ^ value_str
in
Some (String.concat ", " (List.map string_of_mapping hstore))
;;
let to_hstore' str =
let expect target stream =
if List.exists (fun c -> c <> Stream.next stream) target
then convert_failure "hstore" str
in
let parse_quoted stream =
let rec loop accum stream =
match Stream.next stream with
| '"' -> String.implode (List.rev accum)
| '\\' -> loop (Stream.next stream :: accum) stream
| x -> loop (x :: accum) stream
in
expect [ '"' ] stream;
loop [] stream
in
let parse_value stream =
match Stream.peek stream with
| Some 'N' ->
expect [ 'N'; 'U'; 'L'; 'L' ] stream;
None
| _ -> Some (parse_quoted stream)
in
let parse_mapping stream =
let key = parse_quoted stream in
expect [ '='; '>' ] stream;
let value = parse_value stream in
key, value
in
let parse_main stream =
let rec loop accum stream =
let mapping = parse_mapping stream in
match Stream.peek stream with
| Some _ ->
expect [ ','; ' ' ] stream;
loop (mapping :: accum) stream
| None -> mapping :: accum
in
match Stream.peek stream with
| Some _ -> loop [] stream
| None -> []
in
parse_main (Stream.of_string str)
;;
let to_hstore_exn = required to_hstore'
let to_hstore = Option.map to_hstore'
type inet = Ipaddr.t * int [@@deriving compare]
let sexp_of_inet (addr, mask) = [%sexp_of: string * int] (Ipaddr.to_string addr, mask)
let of_inet (addr, mask) =
let hostmask =
match addr with
| Ipaddr.V4 _ -> 32
| Ipaddr.V6 _ -> 128
in
let addr = Ipaddr.to_string addr in
if mask = hostmask
then Some addr
else if mask >= 0 && mask < hostmask
then Some (addr ^ "/" ^ string_of_int mask)
else invalid_arg "mask"
;;
let to_inet' =
let re =
let open Re in
[ group
([ rep (compl [ set ":./" ]); group (set ":."); rep1 (compl [ char '/' ]) ] |> seq)
; opt (seq [ char '/'; group (rep1 any) ])
]
|> seq
|> compile
in
fun str ->
try
let subs = Re.exec re str in
let addr = Ipaddr.of_string_exn (Re.Group.get subs 1) in
let mask =
try Re.Group.get subs 3 with
| Not_found -> ""
in
if mask = ""
then addr, if Re.Group.get subs 2 = "." then 32 else 128
else addr, int_of_string mask
with
| exn -> convert_failure ~hint:(Printexc.to_string exn) "inet" str
;;
let to_inet_exn = required to_inet'
let to_inet = Option.map to_inet'
let of_int i = Some (string_of_int i)
let to_int' t =
try int_of_string t with
| Failure hint -> convert_failure ~hint "int" t
;;
let to_int_exn = required to_int'
let to_int = Option.map to_int'
let of_int32 i = Some (Int32.to_string i)
let to_int32' t =
try Int32.of_string t with
| Failure hint -> convert_failure ~hint "int32" t
;;
let to_int32_exn = required to_int32'
let to_int32 = Option.map to_int32'
let of_int64 i = Some (Int64.to_string i)
let to_int64' t =
try Int64.of_string t with
| Failure hint -> convert_failure ~hint "int64" t
;;
let to_int64_exn = required to_int64'
let to_int64 = Option.map to_int64'
let escape_string str =
let buf = Buffer.create 128 in
for i = 0 to String.length str - 1 do
match str.[i] with
| ('"' | '\\') as x ->
Buffer.add_char buf '\\';
Buffer.add_char buf x
| x -> Buffer.add_char buf x
done;
Buffer.contents buf
;;
let of_list (xs : t list) =
let buf = Buffer.create 128 in
Buffer.add_char buf '{';
let adder i x =
if i > 0 then Buffer.add_char buf ',';
match x with
| Some x ->
let x = escape_string x in
Buffer.add_char buf '"';
Buffer.add_string buf x;
Buffer.add_char buf '"'
| None -> Buffer.add_string buf "NULL"
in
List.iteri adder xs;
Buffer.add_char buf '}';
Some (Buffer.contents buf)
;;
let to_list' str =
let n = String.length str in
if n = 0 || str.[0] <> '{' || str.[n - 1] <> '}' then convert_failure "list" str;
let str = String.sub str 1 (n - 2) in
let buf = Buffer.create 128 in
let add_field accum =
let x = Buffer.contents buf in
Buffer.clear buf;
let field =
if x = "NULL"
then None
else (
let n = String.length x in
if n >= 2 && x.[0] = '"' then Some (String.sub x 1 (n - 2)) else Some x)
in
field :: accum
in
let loop (accum, quoted, escaped) = function
| '\\' when not escaped -> accum, quoted, true
| '"' when not escaped ->
Buffer.add_char buf '"';
accum, not quoted, false
| ',' when (not escaped) && not quoted -> add_field accum, false, false
| x ->
Buffer.add_char buf x;
accum, quoted, false
in
let accum, _, _ = String.fold_left loop ([], false, false) str in
let accum = if Buffer.length buf = 0 then accum else add_field accum in
List.rev accum
;;
let to_list_exn = required to_list'
let to_list = Option.map to_list'
type point = float * float [@@deriving compare, sexp_of]
let of_point (x, y) =
let x = of_float' x in
let y = of_float' y in
Some (Printf.sprintf "(%s,%s)" x y)
;;
let to_point' =
let point_re =
let open Re in
let part = seq [ rep space; group (rep any); rep space ] in
[ rep space; char '('; part; char ','; part; char ')'; rep space ]
|> seq
|> whole_string
|> compile
in
fun str ->
try
let subs = Re.exec point_re str in
float_of_string (Re.Group.get subs 1), float_of_string (Re.Group.get subs 2)
with
| exn -> convert_failure ~hint:(Printexc.to_string exn) "point" str
;;
let to_point_exn = required to_point'
let to_point = Option.map to_point'
let of_string t = Some t
let to_string_exn = required (fun t -> t)
let to_string t = t
let unit = Some ""
let to_unit' = function
| "" -> ()
| t -> convert_failure "unit" t
;;
let to_unit_exn = required to_unit'
let to_unit = Option.map to_unit'
type uuid = Uuidm.t [@@deriving compare]
let sexp_of_uuid u = Uuidm.to_string u |> sexp_of_string
let of_uuid s = Some (Uuidm.to_string s)
let to_uuid' t =
match Uuidm.of_string t with
| Some u -> u
| None -> convert_failure "uuid" t
;;
let to_uuid_exn = required to_uuid'
let to_uuid = Option.map to_uuid'
|
02da211dfc23001a19393536c54002405d596372f36c7d4327100524b4533589 | patricoferris/ocaml-multicore-monorepo | uutf.mli | ---------------------------------------------------------------------------
Copyright ( c ) 2012 The uutf programmers . All rights reserved .
Distributed under the ISC license , see terms at the end of the file .
---------------------------------------------------------------------------
Copyright (c) 2012 The uutf programmers. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
---------------------------------------------------------------------------*)
* Non - blocking streaming Unicode codec .
[ Uutf ] is a non - blocking streaming codec to { { : # decode}decode } and
{ { : # encode}encode } the { { : }
UTF-8 } , { { : } UTF-16 } , UTF-16LE
and UTF-16BE encoding schemes . It can efficiently work character by
character without blocking on IO . Decoders perform
character position tracking and support { { ! nln}newline normalization } .
Functions are also provided to { { ! String } fold over } the characters
of UTF encoded OCaml string values and to { { ! Buffer}directly encode }
characters in OCaml { ! . Buffer.t } values . { b Note } that since OCaml
4.14 , that functionality can be found in { ! . String } and
{ ! . Buffer } and you are encouraged to migrate to it .
See { { : # examples}examples } of use .
{ b References }
{ ul
{ - The Unicode Consortium .
{ e { { : }The Unicode Standard } } .
( latest version ) } }
[Uutf] is a non-blocking streaming codec to {{:#decode}decode} and
{{:#encode}encode} the {{:}
UTF-8}, {{:} UTF-16}, UTF-16LE
and UTF-16BE encoding schemes. It can efficiently work character by
character without blocking on IO. Decoders perform
character position tracking and support {{!nln}newline normalization}.
Functions are also provided to {{!String} fold over} the characters
of UTF encoded OCaml string values and to {{!Buffer}directly encode}
characters in OCaml {!Stdlib.Buffer.t} values. {b Note} that since OCaml
4.14, that functionality can be found in {!Stdlib.String} and
{!Stdlib.Buffer} and you are encouraged to migrate to it.
See {{:#examples}examples} of use.
{b References}
{ul
{- The Unicode Consortium.
{e {{:}The Unicode Standard}}.
(latest version)}}
*)
* { 1 : ucharcsts Special Unicode characters }
val u_bom : Uchar.t
* [ u_bom ] is the { { : /#byte_order_mark}byte
order mark } ( BOM ) character ( [ ] ) . From OCaml 4.06 on , use
{ ! } .
order mark} (BOM) character ([U+FEFF]). From OCaml 4.06 on, use
{!Uchar.bom}. *)
val u_rep : Uchar.t
* [ u_rep ] is the
{ { : /#replacement_character}replacement }
character ( [ U+FFFD ] ) . From OCaml 4.06 on , use
{ ! Uchar.rep } .
{{:/#replacement_character}replacement}
character ([U+FFFD]). From OCaml 4.06 on, use
{!Uchar.rep}. *)
* { 1 : schemes Unicode encoding schemes }
type encoding = [ `UTF_16 | `UTF_16BE | `UTF_16LE | `UTF_8 ]
* The type for Unicode
{ { : /#character_encoding_scheme}encoding
schemes } .
{{:/#character_encoding_scheme}encoding
schemes}. *)
type decoder_encoding = [ encoding | `US_ASCII | `ISO_8859_1 ]
* The type for encoding schemes { e decoded } by [ Uutf ] . Unicode encoding
schemes plus { { : } and
{ { : -international.org/publications/standards/Ecma-094.htm }
ISO / IEC 8859 - 1 } ( latin-1 ) .
schemes plus {{:}US-ASCII} and
{{:-international.org/publications/standards/Ecma-094.htm}
ISO/IEC 8859-1} (latin-1). *)
val encoding_of_string : string -> decoder_encoding option
(** [encoding_of_string s] converts a (case insensitive)
{{:-sets}IANA character set name}
to an encoding. *)
val encoding_to_string : [< decoder_encoding] -> string
(** [encoding_to_string e] is a
{{:-sets}IANA character set name}
for [e]. *)
* { 1 : decode Decode }
type src = [ `Channel of in_channel | `String of string | `Manual ]
* The type for input sources . With a [ ` Manual ] source the client
must provide input with { ! } .
must provide input with {!Manual.src}. *)
type nln = [ `ASCII of Uchar.t | `NLF of Uchar.t | `Readline of Uchar.t ]
* The type for newline normalizations . The variant argument is the
normalization character .
{ ul
{ - [ ` ASCII ] , normalizes ( [ U+000D ] ) , LF ( [ U+000A ] ) and CRLF
( < [ U+000D ] , [ U+000A ] > ) . }
{ - [ ` NLF ] , normalizes the Unicode newline function ( NLF ) . This is
NEL ( [ U+0085 ] ) and the normalizations of [ ` ASCII ] . }
{ - [ ` Readline ] , normalizes for a Unicode readline function . This is FF
( [ U+000C ] ) , LS ( [ U+2028 ] ) , PS ( [ U+2029 ] ) , and the normalizations
of [ ` NLF ] . } }
Used with an appropriate normalization character the [ ` NLF ] and
[ ` Readline ] normalizations allow to implement all the different
recommendations of Unicode 's newline guidelines ( section 5.8 in
Unicode 9.0.0 ) .
normalization character.
{ul
{- [`ASCII], normalizes CR ([U+000D]), LF ([U+000A]) and CRLF
(<[U+000D], [U+000A]>).}
{- [`NLF], normalizes the Unicode newline function (NLF). This is
NEL ([U+0085]) and the normalizations of [`ASCII].}
{- [`Readline], normalizes for a Unicode readline function. This is FF
([U+000C]), LS ([U+2028]), PS ([U+2029]), and the normalizations
of [`NLF].}}
Used with an appropriate normalization character the [`NLF] and
[`Readline] normalizations allow to implement all the different
recommendations of Unicode's newline guidelines (section 5.8 in
Unicode 9.0.0). *)
type decoder
(** The type for decoders. *)
val decoder : ?nln:[< nln] -> ?encoding:[< decoder_encoding] -> [< src] ->
decoder
* [ decoder nln encoding src ] is a decoder that inputs from [ src ] .
{ b Byte order mark . }
{ { : /#byte_order_mark}Byte order mark }
( BOM ) constraints are application dependent and prone to
misunderstandings ( see the
{ { : #BOM}FAQ } ) . Hence ,
[ Uutf ] decoders have a simple rule : an { e initial BOM is always
removed from the input and not counted in character position
tracking } . The function { ! decoder_removed_bom } does however return
[ true ] if a BOM was removed so that all the information can be
recovered if needed .
For UTF-16BE and UTF-16LE the above rule is a violation of
conformance D96 and D97 of the standard . [ Uutf ] favors the idea
that if there 's a BOM , decoding with [ ` UTF_16 ] or the [ ` UTF_16XX ]
corresponding to the BOM should decode the same character sequence
( this is not the case if you stick to the standard ) . The client
can however regain conformance by consulting the result of
{ ! decoder_removed_bom } and take appropriate action .
{ b Encoding . } [ encoding ] specifies the decoded encoding
scheme . If [ ` UTF_16 ] is used the endianness is determined
according to the standard : from a
{ { : }
if there is one , [ ` UTF_16BE ] otherwise .
If [ encoding ] is unspecified it is guessed . The result of a guess
can only be [ ` UTF_8 ] , [ ` UTF_16BE ] or [ ` UTF_16LE ] . The heuristic
looks at the first three bytes of input ( or less if impossible )
and takes the { e first } matching byte pattern in the table below .
{ v
xx = any byte
.. = any byte or no byte ( input too small )
pp = positive byte
uu = valid UTF-8 first byte
Bytes | Guess | Rationale
---------+-----------+-----------------------------------------------
EF BB BF | ` UTF_8 | UTF-8 BOM
FE FF .. | ` UTF_16BE | UTF-16BE BOM
FF FE .. | ` UTF_16LE | UTF-16LE BOM
00 pp .. | ` UTF_16BE | ASCII UTF-16BE and U+0000 is often forbidden
pp 00 .. | ` UTF_16LE | ASCII UTF-16LE and U+0000 is often forbidden
uu .. .. | ` UTF_8 | ASCII UTF-8 or valid UTF-8 first byte .
xx xx .. | ` UTF_16BE | Not UTF-8 = > UTF-16 , no BOM = > UTF-16BE
.. .. .. | ` UTF_8 | Single malformed UTF-8 byte or no input .
v }
This heuristic is compatible both with BOM based
recognitition and
{ { : #section-3}JSON-like encoding
recognition } that relies on ASCII being present at the beginning
of the stream . Also , { ! decoder_removed_bom } will tell the client
if the guess was BOM based .
{ b Newline normalization . } If [ nln ] is specified , the given
newline normalization is performed , see { ! nln } . Otherwise
all newlines are returned as found in the input .
{ b Character position . } The line number , column number , byte count
and character count of the last decoded character ( including
[ ` Malformed ] ones ) are respectively returned by { ! decoder_line } ,
{ ! decoder_col } , { ! } and { ! decoder_count } . Before
the first call to { ! val - decode } the line number is [ 1 ] and the column
is [ 0 ] . Each { ! val - decode } returning [ ` ] or [ ` Malformed ]
increments the column until a newline . On a newline , the line
number is incremented and the column set to zero . For example the
line is [ 2 ] and column [ 0 ] after the first newline was
decoded . This can be understood as if { ! val - decode } was moving an
insertion point to the right in the data . A { e newline } is
anything normalized by [ ` Readline ] , see { ! nln } .
[ Uutf ] assumes that each Unicode scalar value has a column width
of 1 . The same assumption may not be made by the display program
( e.g. for [ emacs ] ' compilation mode you need to set
[ compilation - error - screen - columns ] to [ nil ] ) . The problem is in
general difficult to solve without interaction or convention with the
display program 's rendering engine . Depending on the context better column
increments can be implemented by using { ! . Break.tty_width_hint } or
{ { : /#Grapheme_Cluster_Boundaries }
grapheme cluster boundaries } ( see { ! Uuseg } ) .
{b Byte order mark.}
{{:/#byte_order_mark}Byte order mark}
(BOM) constraints are application dependent and prone to
misunderstandings (see the
{{:#BOM}FAQ}). Hence,
[Uutf] decoders have a simple rule: an {e initial BOM is always
removed from the input and not counted in character position
tracking}. The function {!decoder_removed_bom} does however return
[true] if a BOM was removed so that all the information can be
recovered if needed.
For UTF-16BE and UTF-16LE the above rule is a violation of
conformance D96 and D97 of the standard. [Uutf] favors the idea
that if there's a BOM, decoding with [`UTF_16] or the [`UTF_16XX]
corresponding to the BOM should decode the same character sequence
(this is not the case if you stick to the standard). The client
can however regain conformance by consulting the result of
{!decoder_removed_bom} and take appropriate action.
{b Encoding.} [encoding] specifies the decoded encoding
scheme. If [`UTF_16] is used the endianness is determined
according to the standard: from a
{{:/#byte_order_mark}BOM}
if there is one, [`UTF_16BE] otherwise.
If [encoding] is unspecified it is guessed. The result of a guess
can only be [`UTF_8], [`UTF_16BE] or [`UTF_16LE]. The heuristic
looks at the first three bytes of input (or less if impossible)
and takes the {e first} matching byte pattern in the table below.
{v
xx = any byte
.. = any byte or no byte (input too small)
pp = positive byte
uu = valid UTF-8 first byte
Bytes | Guess | Rationale
---------+-----------+-----------------------------------------------
EF BB BF | `UTF_8 | UTF-8 BOM
FE FF .. | `UTF_16BE | UTF-16BE BOM
FF FE .. | `UTF_16LE | UTF-16LE BOM
00 pp .. | `UTF_16BE | ASCII UTF-16BE and U+0000 is often forbidden
pp 00 .. | `UTF_16LE | ASCII UTF-16LE and U+0000 is often forbidden
uu .. .. | `UTF_8 | ASCII UTF-8 or valid UTF-8 first byte.
xx xx .. | `UTF_16BE | Not UTF-8 => UTF-16, no BOM => UTF-16BE
.. .. .. | `UTF_8 | Single malformed UTF-8 byte or no input.
v}
This heuristic is compatible both with BOM based
recognitition and
{{:#section-3}JSON-like encoding
recognition} that relies on ASCII being present at the beginning
of the stream. Also, {!decoder_removed_bom} will tell the client
if the guess was BOM based.
{b Newline normalization.} If [nln] is specified, the given
newline normalization is performed, see {!nln}. Otherwise
all newlines are returned as found in the input.
{b Character position.} The line number, column number, byte count
and character count of the last decoded character (including
[`Malformed] ones) are respectively returned by {!decoder_line},
{!decoder_col}, {!decoder_byte_count} and {!decoder_count}. Before
the first call to {!val-decode} the line number is [1] and the column
is [0]. Each {!val-decode} returning [`Uchar] or [`Malformed]
increments the column until a newline. On a newline, the line
number is incremented and the column set to zero. For example the
line is [2] and column [0] after the first newline was
decoded. This can be understood as if {!val-decode} was moving an
insertion point to the right in the data. A {e newline} is
anything normalized by [`Readline], see {!nln}.
[Uutf] assumes that each Unicode scalar value has a column width
of 1. The same assumption may not be made by the display program
(e.g. for [emacs]' compilation mode you need to set
[compilation-error-screen-columns] to [nil]). The problem is in
general difficult to solve without interaction or convention with the
display program's rendering engine. Depending on the context better column
increments can be implemented by using {!Uucp.Break.tty_width_hint} or
{{:/#Grapheme_Cluster_Boundaries}
grapheme cluster boundaries} (see {!Uuseg}). *)
val decode : decoder ->
[ `Await | `Uchar of Uchar.t | `End | `Malformed of string]
* [ decode d ] is :
{ ul
{ - [ ` Await ] if [ d ] has a [ ` Manual ] input source and awaits
for more input . The client must use { ! } to provide it . }
{ - [ ` u ] if a Unicode scalar value [ u ] was decoded . }
{ - [ ` End ] if the end of input was reached . }
{ - [ ` Malformed bytes ] if the [ bytes ] sequence is malformed according to
the decoded encoding scheme . If you are interested in a best - effort
decoding you can still continue to decode after an error until the
decoder synchronizes again on valid bytes . It may however be a good
idea to signal the malformed characters by adding an { ! u_rep }
character to the parsed data , see the { { : # examples}examples } . } }
{ b Note . } Repeated invocation always eventually returns [ ` End ] , even
in case of errors .
{ul
{- [`Await] if [d] has a [`Manual] input source and awaits
for more input. The client must use {!Manual.src} to provide it.}
{- [`Uchar u] if a Unicode scalar value [u] was decoded.}
{- [`End] if the end of input was reached.}
{- [`Malformed bytes] if the [bytes] sequence is malformed according to
the decoded encoding scheme. If you are interested in a best-effort
decoding you can still continue to decode after an error until the
decoder synchronizes again on valid bytes. It may however be a good
idea to signal the malformed characters by adding an {!u_rep}
character to the parsed data, see the {{:#examples}examples}.}}
{b Note.} Repeated invocation always eventually returns [`End], even
in case of errors. *)
val decoder_encoding : decoder -> decoder_encoding
* [ decoder_encoding d ] is [ d ] 's the decoded encoding scheme of [ d ] .
{ b Warning . } If the decoder guesses the encoding or uses [ ` UTF_16 ] ,
rely on this value only after the first [ ` ] was decoded .
{b Warning.} If the decoder guesses the encoding or uses [`UTF_16],
rely on this value only after the first [`Uchar] was decoded. *)
(**/**)
(* This function is dangerous, it may destroy the current continuation.
But it's needed for things like XML parsers. *)
val set_decoder_encoding : decoder -> [< decoder_encoding] -> unit
* [ set_decoder_encoding d enc ] changes the decoded encoding
to [ enc ] after decoding started .
{ b Warning . } Call only after { ! val - decode } was called on [ d ] and that the
last call to it returned something different from [ ` Await ] or data may
be lost . After encoding guess wait for at least three [ ` Uchar]s .
to [enc] after decoding started.
{b Warning.} Call only after {!val-decode} was called on [d] and that the
last call to it returned something different from [`Await] or data may
be lost. After encoding guess wait for at least three [`Uchar]s. *)
(**/**)
val decoder_line : decoder -> int
* [ decoder_line d ] is the line number of the last
decoded ( or malformed ) character . See { ! } for details .
decoded (or malformed) character. See {!val-decoder} for details. *)
val decoder_col : decoder -> int
* [ decoder_col d ] is the column number of the last decoded
( or malformed ) character . See { ! } for details .
(or malformed) character. See {!val-decoder} for details. *)
val decoder_byte_count : decoder -> int
(** [decoder_byte_count d] is the number of bytes already decoded on
[d] (including malformed ones). This is the last {!val-decode}'s
end byte offset counting from the beginning of the stream. *)
val decoder_count : decoder -> int
* [ decoder_count d ] is the number of characters already decoded on [ d ]
( including malformed ones ) . See { ! } for details .
(including malformed ones). See {!val-decoder} for details. *)
val decoder_removed_bom : decoder -> bool
* [ decoder_removed_bom d ] is [ true ] iff an { e initial }
{ { : } was
removed from the input stream . See { ! } for details .
{{:/#byte_order_mark}BOM} was
removed from the input stream. See {!val-decoder} for details. *)
val decoder_src : decoder -> src
(** [decoder_src d] is [d]'s input source. *)
val decoder_nln : decoder -> nln option
(** [decoder_nln d] returns [d]'s newline normalization (if any). *)
val pp_decode : Format.formatter ->
[< `Await | `Uchar of Uchar.t | `End | `Malformed of string] -> unit
(** [pp_decode ppf v] prints an unspecified representation of [v] on
[ppf]. *)
* { 1 : encode Encode }
type dst = [ `Channel of out_channel | `Buffer of Buffer.t | `Manual ]
* The type for output destinations . With a [ ` Manual ] destination the client
must provide output storage with { ! } .
must provide output storage with {!Manual.dst}. *)
type encoder
* The type for Unicode encoders .
val encoder : [< encoding] -> [< dst] -> encoder
* [ encoder encoding dst ] is an encoder for [ encoding ] that outputs
to [ dst ] .
{ b Note . } No initial
{ { : }
is encoded . If needed , this duty is left to the client .
to [dst].
{b Note.} No initial
{{:/#byte_order_mark}BOM}
is encoded. If needed, this duty is left to the client. *)
val encode :
encoder -> [<`Await | `End | `Uchar of Uchar.t ] -> [`Ok | `Partial ]
* [ encode e v ] is :
{ ul
{ - [ ` Partial ] iff [ e ] has a [ ` Manual ] destination and needs more output
storage . The client must use { ! } to provide a new buffer
and then call { ! - encode } with [ ` Await ] until [ ` Ok ] is returned . }
{ - [ ` Ok ] when the encoder is ready to encode a new [ ` ] or [ ` End ] } }
For [ ` Manual ] destination , encoding [ ` End ] always returns
[ ` Partial ] , the client should continue as usual with [ ` Await ]
until [ ` Ok ] is returned at which point { ! Manual.dst_rem } [ e ] is
guaranteed to be the size of the last provided buffer ( i.e. nothing
was written ) .
{ b Raises . } [ Invalid_argument ] if an [ ` ] or [ ` End ] is encoded
after a [ ` Partial ] encode .
{ul
{- [`Partial] iff [e] has a [`Manual] destination and needs more output
storage. The client must use {!Manual.dst} to provide a new buffer
and then call {!val-encode} with [`Await] until [`Ok] is returned.}
{- [`Ok] when the encoder is ready to encode a new [`Uchar] or [`End]}}
For [`Manual] destination, encoding [`End] always returns
[`Partial], the client should continue as usual with [`Await]
until [`Ok] is returned at which point {!Manual.dst_rem} [e] is
guaranteed to be the size of the last provided buffer (i.e. nothing
was written).
{b Raises.} [Invalid_argument] if an [`Uchar] or [`End] is encoded
after a [`Partial] encode. *)
val encoder_encoding : encoder -> encoding
(** [encoder_encoding e] is [e]'s encoding. *)
val encoder_dst : encoder -> dst
(** [encoder_dst e] is [e]'s output destination. *)
* { 1 : manual Manual sources and destinations . }
(** Manual sources and destinations.
{b Warning.} Use only with [`Manual] decoder and encoders. *)
module Manual : sig
val src : decoder -> Bytes.t -> int -> int -> unit
(** [src d s j l] provides [d] with [l] bytes to read, starting at
[j] in [s]. This byte range is read by calls to {!val-decode} with [d]
until [`Await] is returned. To signal the end of input call the function
with [l = 0]. *)
val dst : encoder -> Bytes.t -> int -> int -> unit
(** [dst e s j l] provides [e] with [l] bytes to write, starting
at [j] in [s]. This byte range is written by calls to
{!val-encode} with [e] until [`Partial] is returned. Use {!dst_rem} to
know the remaining number of non-written free bytes in [s]. *)
val dst_rem : encoder -> int
* [ dst_rem e ] is the remaining number of non - written , free bytes
in the last buffer provided with { ! } .
in the last buffer provided with {!Manual.dst}. *)
end
* { 1 : strbuf String folders and Buffer encoders }
* Fold over the characters of UTF encoded OCaml [ string ] values .
{ b Note . } Since OCaml 4.14 , UTF decoders are available in
{ ! . String } . You are encouraged to migrate to them .
{b Note.} Since OCaml 4.14, UTF decoders are available in
{!Stdlib.String}. You are encouraged to migrate to them. *)
module String : sig
(** {1 Encoding guess} *)
val encoding_guess : string -> [ `UTF_8 | `UTF_16BE | `UTF_16LE ] * bool
* [ encoding_guess s ] is the encoding guessed for [ s ] coupled with
[ true ] iff there 's an initial
{ { : } .
[true] iff there's an initial
{{:/#byte_order_mark}BOM}. *)
* { 1 String folders }
{ b Note . } Initial { { : /#byte_order_mark}BOM}s
are also folded over .
{b Note.} Initial {{:/#byte_order_mark}BOM}s
are also folded over. *)
type 'a folder = 'a -> int -> [ `Uchar of Uchar.t | `Malformed of string ] ->
'a
* The type for character folders . The integer is the index in the
string where the [ ` ] or [ ` Malformed ] starts .
string where the [`Uchar] or [`Malformed] starts. *)
val fold_utf_8 : ?pos:int -> ?len:int -> 'a folder -> 'a -> string -> 'a
* [ fold_utf_8 f a s ? pos ? len ( ) ] is
[ f ( ] ... [ ( f ( f a pos u]{_0 } [ ) j]{_1 } [ u]{_1 } [ ) ] ... [ ) ] ... [ )
j]{_n } [ u]{_n }
where [ u]{_i } , [ j]{_i } are characters and their start position
in the UTF-8 encoded substring [ s ] starting at [ pos ] and [ len ]
long . The default value for [ pos ] is [ 0 ] and [ len ] is
[ String.length s - pos ] .
[f (] ... [(f (f a pos u]{_0}[) j]{_1}[ u]{_1}[)] ... [)] ... [)
j]{_n}[ u]{_n}
where [u]{_i}, [j]{_i} are characters and their start position
in the UTF-8 encoded substring [s] starting at [pos] and [len]
long. The default value for [pos] is [0] and [len] is
[String.length s - pos]. *)
val fold_utf_16be : ?pos:int -> ?len:int -> 'a folder -> 'a -> string -> 'a
* [ fold_utf_16be f a s ? pos ? len ( ) ] is
[ f ( ] ... [ ( f ( f a pos u]{_0 } [ ) j]{_1 } [ u]{_1 } [ ) ] ... [ ) ] ... [ )
j]{_n } [ u]{_n }
where [ u]{_i } , [ j]{_i } are characters and their start position
in the UTF-8 encoded substring [ s ] starting at [ pos ] and [ len ]
long . The default value for [ pos ] is [ 0 ] and [ len ] is
[ String.length s - pos ] .
[f (] ... [(f (f a pos u]{_0}[) j]{_1}[ u]{_1}[)] ... [)] ... [)
j]{_n}[ u]{_n}
where [u]{_i}, [j]{_i} are characters and their start position
in the UTF-8 encoded substring [s] starting at [pos] and [len]
long. The default value for [pos] is [0] and [len] is
[String.length s - pos]. *)
val fold_utf_16le : ?pos:int -> ?len:int -> 'a folder -> 'a -> string -> 'a
* [ fold_utf_16le f a s ? pos ? len ( ) ] is
[ f ( ] ... [ ( f ( f a pos u]{_0 } [ ) j]{_1 } [ u]{_1 } [ ) ] ... [ ) ] ... [ )
j]{_n } [ u]{_n }
where [ u]{_i } , [ j]{_i } are characters and their start position
in the UTF-8 encoded substring [ s ] starting at [ pos ] and [ len ]
long . The default value for [ pos ] is [ 0 ] and [ len ] is
[ String.length s - pos ] .
[f (] ... [(f (f a pos u]{_0}[) j]{_1}[ u]{_1}[)] ... [)] ... [)
j]{_n}[ u]{_n}
where [u]{_i}, [j]{_i} are characters and their start position
in the UTF-8 encoded substring [s] starting at [pos] and [len]
long. The default value for [pos] is [0] and [len] is
[String.length s - pos]. *)
end
* UTF encode characters in OCaml { ! Buffer.t } values .
{ b Note . } Since OCaml 4.06 , these encoders are available in
{ ! . Buffer } . You are encouraged to migrate to them .
{b Note.} Since OCaml 4.06, these encoders are available in
{!Stdlib.Buffer}. You are encouraged to migrate to them. *)
module Buffer : sig
* { 1 Buffer encoders }
val add_utf_8 : Buffer.t -> Uchar.t -> unit
* [ add_utf_8 b u ] adds the UTF-8 encoding of [ u ] to [ b ] .
val add_utf_16be : Buffer.t -> Uchar.t -> unit
* [ add_utf_16be b u ] adds the encoding of [ u ] to [ b ] .
val add_utf_16le : Buffer.t -> Uchar.t -> unit
* [ add_utf_16le b u ] adds the UTF-16LE encoding of [ u ] to [ b ] .
end
* { 1 : examples Examples }
{ 2 : readlines Read lines }
The value of [ lines src ] is the list of lines in [ src ] as UTF-8
encoded OCaml strings . Line breaks are determined according to the
recommendation R4 for a [ readline ] function in section 5.8 of
Unicode 9.0.0 . If a decoding error occurs we silently replace the
malformed sequence by the replacement character { ! u_rep } and continue .
{ [ let lines ? encoding ( src : [ ` Channel of in_channel | ` String of string ] ) =
let rec loop d buf acc = match Uutf.decode d with
| ` u - >
begin match Uchar.to_int u with
| 0x000A - >
let line = Buffer.contents buf in
Buffer.clear buf ; loop d buf ( line : : acc )
| _ - >
Uutf . Buffer.add_utf_8 buf u ; loop d buf acc
end
| ` End - > List.rev ( Buffer.contents buf : : acc )
| ` Malformed _ - > Uutf . Buffer.add_utf_8 buf Uutf.u_rep ; loop d buf acc
| ` Await - > assert false
in
let nln = ` Readline ( Uchar.of_int ) in
loop ( Uutf.decoder ~nln ? encoding src ) ( Buffer.create 512 ) [ ]
] }
Using the [ ` Manual ] interface , [ lines_fd ] does the same but on a Unix file
descriptor .
{ [ let lines_fd ? encoding ( fd : Unix.file_descr ) =
let rec loop fd s d buf acc = match Uutf.decode d with
| ` u - >
begin match Uchar.to_int u with
| 0x000A - >
let line = Buffer.contents buf in
Buffer.clear buf ; loop fd s d buf ( line : : acc )
| _ - >
Uutf . Buffer.add_utf_8 buf u ; loop fd s d buf acc
end
| ` End - > List.rev ( Buffer.contents buf : : acc )
| ` Malformed _ - > Uutf . Buffer.add_utf_8 buf Uutf.u_rep ; loop fd s d buf acc
| ` Await - >
let rec unix_read fd s j l = try fd s j l with
| Unix . Unix_error ( Unix . , _ , _ ) - > unix_read fd s j l
in
let rc = unix_read fd s 0 ( Bytes.length s ) in
Uutf.Manual.src d s 0 rc ; loop fd s d buf acc
in
let s = Bytes.create ( * UNIX_BUFFER_SIZE in 4.0.0
{2:readlines Read lines}
The value of [lines src] is the list of lines in [src] as UTF-8
encoded OCaml strings. Line breaks are determined according to the
recommendation R4 for a [readline] function in section 5.8 of
Unicode 9.0.0. If a decoding error occurs we silently replace the
malformed sequence by the replacement character {!u_rep} and continue.
{[let lines ?encoding (src : [`Channel of in_channel | `String of string]) =
let rec loop d buf acc = match Uutf.decode d with
| `Uchar u ->
begin match Uchar.to_int u with
| 0x000A ->
let line = Buffer.contents buf in
Buffer.clear buf; loop d buf (line :: acc)
| _ ->
Uutf.Buffer.add_utf_8 buf u; loop d buf acc
end
| `End -> List.rev (Buffer.contents buf :: acc)
| `Malformed _ -> Uutf.Buffer.add_utf_8 buf Uutf.u_rep; loop d buf acc
| `Await -> assert false
in
let nln = `Readline (Uchar.of_int 0x000A) in
loop (Uutf.decoder ~nln ?encoding src) (Buffer.create 512) []
]}
Using the [`Manual] interface, [lines_fd] does the same but on a Unix file
descriptor.
{[let lines_fd ?encoding (fd : Unix.file_descr) =
let rec loop fd s d buf acc = match Uutf.decode d with
| `Uchar u ->
begin match Uchar.to_int u with
| 0x000A ->
let line = Buffer.contents buf in
Buffer.clear buf; loop fd s d buf (line :: acc)
| _ ->
Uutf.Buffer.add_utf_8 buf u; loop fd s d buf acc
end
| `End -> List.rev (Buffer.contents buf :: acc)
| `Malformed _ -> Uutf.Buffer.add_utf_8 buf Uutf.u_rep; loop fd s d buf acc
| `Await ->
let rec unix_read fd s j l = try Unix.read fd s j l with
| Unix.Unix_error (Unix.EINTR, _, _) -> unix_read fd s j l
in
let rc = unix_read fd s 0 (Bytes.length s) in
Uutf.Manual.src d s 0 rc; loop fd s d buf acc
in
let s = Bytes.create 65536 (* UNIX_BUFFER_SIZE in 4.0.0 *) in
let nln = `Readline (Uchar.of_int 0x000A) in
loop fd s (Uutf.decoder ~nln ?encoding `Manual) (Buffer.create 512) []
]}
{2:recode Recode}
The result of [recode src out_encoding dst] has the characters of
[src] written on [dst] with encoding [out_encoding]. If a
decoding error occurs we silently replace the malformed sequence
by the replacement character {!u_rep} and continue. Note that we
don't add an initial
{{:/#byte_order_mark}BOM} to [dst],
recoding will thus loose the initial BOM [src] may have. Whether
this is a problem or not depends on the context.
{[let recode ?nln ?encoding out_encoding
(src : [`Channel of in_channel | `String of string])
(dst : [`Channel of out_channel | `Buffer of Buffer.t])
=
let rec loop d e = match Uutf.decode d with
| `Uchar _ as u -> ignore (Uutf.encode e u); loop d e
| `End -> ignore (Uutf.encode e `End)
| `Malformed _ -> ignore (Uutf.encode e (`Uchar Uutf.u_rep)); loop d e
| `Await -> assert false
in
let d = Uutf.decoder ?nln ?encoding src in
let e = Uutf.encoder out_encoding dst in
loop d e]}
Using the [`Manual] interface, [recode_fd] does the same but between
Unix file descriptors.
{[let recode_fd ?nln ?encoding out_encoding
(fdi : Unix.file_descr)
(fdo : Unix.file_descr)
=
let rec encode fd s e v = match Uutf.encode e v with `Ok -> ()
| `Partial ->
let rec unix_write fd s j l =
let rec write fd s j l = try Unix.single_write fd s j l with
| Unix.Unix_error (Unix.EINTR, _, _) -> write fd s j l
in
let wc = write fd s j l in
if wc < l then unix_write fd s (j + wc) (l - wc) else ()
in
unix_write fd s 0 (Bytes.length s - Uutf.Manual.dst_rem e);
Uutf.Manual.dst e s 0 (Bytes.length s);
encode fd s e `Await
in
let rec loop fdi fdo ds es d e = match Uutf.decode d with
| `Uchar _ as u -> encode fdo es e u; loop fdi fdo ds es d e
| `End -> encode fdo es e `End
| `Malformed _ -> encode fdo es e (`Uchar Uutf.u_rep); loop fdi fdo ds es d e
| `Await ->
let rec unix_read fd s j l = try Unix.read fd s j l with
| Unix.Unix_error (Unix.EINTR, _, _) -> unix_read fd s j l
in
let rc = unix_read fdi ds 0 (Bytes.length ds) in
Uutf.Manual.src d ds 0 rc; loop fdi fdo ds es d e
in
UNIX_BUFFER_SIZE in 4.0.0
UNIX_BUFFER_SIZE in 4.0.0
let d = Uutf.decoder ?nln ?encoding `Manual in
let e = Uutf.encoder out_encoding `Manual in
Uutf.Manual.dst e es 0 (Bytes.length es);
loop fdi fdo ds es d e]}
*)
---------------------------------------------------------------------------
Copyright ( c ) 2012 The uutf programmers
Permission to use , copy , modify , and/or distribute this software for any
purpose with or without fee is hereby granted , provided that the above
copyright notice and this permission notice appear in all copies .
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
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 The uutf programmers
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---------------------------------------------------------------------------*)
| null | https://raw.githubusercontent.com/patricoferris/ocaml-multicore-monorepo/22b441e6727bc303950b3b37c8fbc024c748fe55/duniverse/uutf/src/uutf.mli | ocaml | * [encoding_of_string s] converts a (case insensitive)
{{:-sets}IANA character set name}
to an encoding.
* [encoding_to_string e] is a
{{:-sets}IANA character set name}
for [e].
* The type for decoders.
*/*
This function is dangerous, it may destroy the current continuation.
But it's needed for things like XML parsers.
*/*
* [decoder_byte_count d] is the number of bytes already decoded on
[d] (including malformed ones). This is the last {!val-decode}'s
end byte offset counting from the beginning of the stream.
* [decoder_src d] is [d]'s input source.
* [decoder_nln d] returns [d]'s newline normalization (if any).
* [pp_decode ppf v] prints an unspecified representation of [v] on
[ppf].
* [encoder_encoding e] is [e]'s encoding.
* [encoder_dst e] is [e]'s output destination.
* Manual sources and destinations.
{b Warning.} Use only with [`Manual] decoder and encoders.
* [src d s j l] provides [d] with [l] bytes to read, starting at
[j] in [s]. This byte range is read by calls to {!val-decode} with [d]
until [`Await] is returned. To signal the end of input call the function
with [l = 0].
* [dst e s j l] provides [e] with [l] bytes to write, starting
at [j] in [s]. This byte range is written by calls to
{!val-encode} with [e] until [`Partial] is returned. Use {!dst_rem} to
know the remaining number of non-written free bytes in [s].
* {1 Encoding guess}
UNIX_BUFFER_SIZE in 4.0.0 | ---------------------------------------------------------------------------
Copyright ( c ) 2012 The uutf programmers . All rights reserved .
Distributed under the ISC license , see terms at the end of the file .
---------------------------------------------------------------------------
Copyright (c) 2012 The uutf programmers. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
---------------------------------------------------------------------------*)
* Non - blocking streaming Unicode codec .
[ Uutf ] is a non - blocking streaming codec to { { : # decode}decode } and
{ { : # encode}encode } the { { : }
UTF-8 } , { { : } UTF-16 } , UTF-16LE
and UTF-16BE encoding schemes . It can efficiently work character by
character without blocking on IO . Decoders perform
character position tracking and support { { ! nln}newline normalization } .
Functions are also provided to { { ! String } fold over } the characters
of UTF encoded OCaml string values and to { { ! Buffer}directly encode }
characters in OCaml { ! . Buffer.t } values . { b Note } that since OCaml
4.14 , that functionality can be found in { ! . String } and
{ ! . Buffer } and you are encouraged to migrate to it .
See { { : # examples}examples } of use .
{ b References }
{ ul
{ - The Unicode Consortium .
{ e { { : }The Unicode Standard } } .
( latest version ) } }
[Uutf] is a non-blocking streaming codec to {{:#decode}decode} and
{{:#encode}encode} the {{:}
UTF-8}, {{:} UTF-16}, UTF-16LE
and UTF-16BE encoding schemes. It can efficiently work character by
character without blocking on IO. Decoders perform
character position tracking and support {{!nln}newline normalization}.
Functions are also provided to {{!String} fold over} the characters
of UTF encoded OCaml string values and to {{!Buffer}directly encode}
characters in OCaml {!Stdlib.Buffer.t} values. {b Note} that since OCaml
4.14, that functionality can be found in {!Stdlib.String} and
{!Stdlib.Buffer} and you are encouraged to migrate to it.
See {{:#examples}examples} of use.
{b References}
{ul
{- The Unicode Consortium.
{e {{:}The Unicode Standard}}.
(latest version)}}
*)
* { 1 : ucharcsts Special Unicode characters }
val u_bom : Uchar.t
* [ u_bom ] is the { { : /#byte_order_mark}byte
order mark } ( BOM ) character ( [ ] ) . From OCaml 4.06 on , use
{ ! } .
order mark} (BOM) character ([U+FEFF]). From OCaml 4.06 on, use
{!Uchar.bom}. *)
val u_rep : Uchar.t
* [ u_rep ] is the
{ { : /#replacement_character}replacement }
character ( [ U+FFFD ] ) . From OCaml 4.06 on , use
{ ! Uchar.rep } .
{{:/#replacement_character}replacement}
character ([U+FFFD]). From OCaml 4.06 on, use
{!Uchar.rep}. *)
* { 1 : schemes Unicode encoding schemes }
type encoding = [ `UTF_16 | `UTF_16BE | `UTF_16LE | `UTF_8 ]
* The type for Unicode
{ { : /#character_encoding_scheme}encoding
schemes } .
{{:/#character_encoding_scheme}encoding
schemes}. *)
type decoder_encoding = [ encoding | `US_ASCII | `ISO_8859_1 ]
* The type for encoding schemes { e decoded } by [ Uutf ] . Unicode encoding
schemes plus { { : } and
{ { : -international.org/publications/standards/Ecma-094.htm }
ISO / IEC 8859 - 1 } ( latin-1 ) .
schemes plus {{:}US-ASCII} and
{{:-international.org/publications/standards/Ecma-094.htm}
ISO/IEC 8859-1} (latin-1). *)
val encoding_of_string : string -> decoder_encoding option
val encoding_to_string : [< decoder_encoding] -> string
* { 1 : decode Decode }
type src = [ `Channel of in_channel | `String of string | `Manual ]
* The type for input sources . With a [ ` Manual ] source the client
must provide input with { ! } .
must provide input with {!Manual.src}. *)
type nln = [ `ASCII of Uchar.t | `NLF of Uchar.t | `Readline of Uchar.t ]
* The type for newline normalizations . The variant argument is the
normalization character .
{ ul
{ - [ ` ASCII ] , normalizes ( [ U+000D ] ) , LF ( [ U+000A ] ) and CRLF
( < [ U+000D ] , [ U+000A ] > ) . }
{ - [ ` NLF ] , normalizes the Unicode newline function ( NLF ) . This is
NEL ( [ U+0085 ] ) and the normalizations of [ ` ASCII ] . }
{ - [ ` Readline ] , normalizes for a Unicode readline function . This is FF
( [ U+000C ] ) , LS ( [ U+2028 ] ) , PS ( [ U+2029 ] ) , and the normalizations
of [ ` NLF ] . } }
Used with an appropriate normalization character the [ ` NLF ] and
[ ` Readline ] normalizations allow to implement all the different
recommendations of Unicode 's newline guidelines ( section 5.8 in
Unicode 9.0.0 ) .
normalization character.
{ul
{- [`ASCII], normalizes CR ([U+000D]), LF ([U+000A]) and CRLF
(<[U+000D], [U+000A]>).}
{- [`NLF], normalizes the Unicode newline function (NLF). This is
NEL ([U+0085]) and the normalizations of [`ASCII].}
{- [`Readline], normalizes for a Unicode readline function. This is FF
([U+000C]), LS ([U+2028]), PS ([U+2029]), and the normalizations
of [`NLF].}}
Used with an appropriate normalization character the [`NLF] and
[`Readline] normalizations allow to implement all the different
recommendations of Unicode's newline guidelines (section 5.8 in
Unicode 9.0.0). *)
type decoder
val decoder : ?nln:[< nln] -> ?encoding:[< decoder_encoding] -> [< src] ->
decoder
* [ decoder nln encoding src ] is a decoder that inputs from [ src ] .
{ b Byte order mark . }
{ { : /#byte_order_mark}Byte order mark }
( BOM ) constraints are application dependent and prone to
misunderstandings ( see the
{ { : #BOM}FAQ } ) . Hence ,
[ Uutf ] decoders have a simple rule : an { e initial BOM is always
removed from the input and not counted in character position
tracking } . The function { ! decoder_removed_bom } does however return
[ true ] if a BOM was removed so that all the information can be
recovered if needed .
For UTF-16BE and UTF-16LE the above rule is a violation of
conformance D96 and D97 of the standard . [ Uutf ] favors the idea
that if there 's a BOM , decoding with [ ` UTF_16 ] or the [ ` UTF_16XX ]
corresponding to the BOM should decode the same character sequence
( this is not the case if you stick to the standard ) . The client
can however regain conformance by consulting the result of
{ ! decoder_removed_bom } and take appropriate action .
{ b Encoding . } [ encoding ] specifies the decoded encoding
scheme . If [ ` UTF_16 ] is used the endianness is determined
according to the standard : from a
{ { : }
if there is one , [ ` UTF_16BE ] otherwise .
If [ encoding ] is unspecified it is guessed . The result of a guess
can only be [ ` UTF_8 ] , [ ` UTF_16BE ] or [ ` UTF_16LE ] . The heuristic
looks at the first three bytes of input ( or less if impossible )
and takes the { e first } matching byte pattern in the table below .
{ v
xx = any byte
.. = any byte or no byte ( input too small )
pp = positive byte
uu = valid UTF-8 first byte
Bytes | Guess | Rationale
---------+-----------+-----------------------------------------------
EF BB BF | ` UTF_8 | UTF-8 BOM
FE FF .. | ` UTF_16BE | UTF-16BE BOM
FF FE .. | ` UTF_16LE | UTF-16LE BOM
00 pp .. | ` UTF_16BE | ASCII UTF-16BE and U+0000 is often forbidden
pp 00 .. | ` UTF_16LE | ASCII UTF-16LE and U+0000 is often forbidden
uu .. .. | ` UTF_8 | ASCII UTF-8 or valid UTF-8 first byte .
xx xx .. | ` UTF_16BE | Not UTF-8 = > UTF-16 , no BOM = > UTF-16BE
.. .. .. | ` UTF_8 | Single malformed UTF-8 byte or no input .
v }
This heuristic is compatible both with BOM based
recognitition and
{ { : #section-3}JSON-like encoding
recognition } that relies on ASCII being present at the beginning
of the stream . Also , { ! decoder_removed_bom } will tell the client
if the guess was BOM based .
{ b Newline normalization . } If [ nln ] is specified , the given
newline normalization is performed , see { ! nln } . Otherwise
all newlines are returned as found in the input .
{ b Character position . } The line number , column number , byte count
and character count of the last decoded character ( including
[ ` Malformed ] ones ) are respectively returned by { ! decoder_line } ,
{ ! decoder_col } , { ! } and { ! decoder_count } . Before
the first call to { ! val - decode } the line number is [ 1 ] and the column
is [ 0 ] . Each { ! val - decode } returning [ ` ] or [ ` Malformed ]
increments the column until a newline . On a newline , the line
number is incremented and the column set to zero . For example the
line is [ 2 ] and column [ 0 ] after the first newline was
decoded . This can be understood as if { ! val - decode } was moving an
insertion point to the right in the data . A { e newline } is
anything normalized by [ ` Readline ] , see { ! nln } .
[ Uutf ] assumes that each Unicode scalar value has a column width
of 1 . The same assumption may not be made by the display program
( e.g. for [ emacs ] ' compilation mode you need to set
[ compilation - error - screen - columns ] to [ nil ] ) . The problem is in
general difficult to solve without interaction or convention with the
display program 's rendering engine . Depending on the context better column
increments can be implemented by using { ! . Break.tty_width_hint } or
{ { : /#Grapheme_Cluster_Boundaries }
grapheme cluster boundaries } ( see { ! Uuseg } ) .
{b Byte order mark.}
{{:/#byte_order_mark}Byte order mark}
(BOM) constraints are application dependent and prone to
misunderstandings (see the
{{:#BOM}FAQ}). Hence,
[Uutf] decoders have a simple rule: an {e initial BOM is always
removed from the input and not counted in character position
tracking}. The function {!decoder_removed_bom} does however return
[true] if a BOM was removed so that all the information can be
recovered if needed.
For UTF-16BE and UTF-16LE the above rule is a violation of
conformance D96 and D97 of the standard. [Uutf] favors the idea
that if there's a BOM, decoding with [`UTF_16] or the [`UTF_16XX]
corresponding to the BOM should decode the same character sequence
(this is not the case if you stick to the standard). The client
can however regain conformance by consulting the result of
{!decoder_removed_bom} and take appropriate action.
{b Encoding.} [encoding] specifies the decoded encoding
scheme. If [`UTF_16] is used the endianness is determined
according to the standard: from a
{{:/#byte_order_mark}BOM}
if there is one, [`UTF_16BE] otherwise.
If [encoding] is unspecified it is guessed. The result of a guess
can only be [`UTF_8], [`UTF_16BE] or [`UTF_16LE]. The heuristic
looks at the first three bytes of input (or less if impossible)
and takes the {e first} matching byte pattern in the table below.
{v
xx = any byte
.. = any byte or no byte (input too small)
pp = positive byte
uu = valid UTF-8 first byte
Bytes | Guess | Rationale
---------+-----------+-----------------------------------------------
EF BB BF | `UTF_8 | UTF-8 BOM
FE FF .. | `UTF_16BE | UTF-16BE BOM
FF FE .. | `UTF_16LE | UTF-16LE BOM
00 pp .. | `UTF_16BE | ASCII UTF-16BE and U+0000 is often forbidden
pp 00 .. | `UTF_16LE | ASCII UTF-16LE and U+0000 is often forbidden
uu .. .. | `UTF_8 | ASCII UTF-8 or valid UTF-8 first byte.
xx xx .. | `UTF_16BE | Not UTF-8 => UTF-16, no BOM => UTF-16BE
.. .. .. | `UTF_8 | Single malformed UTF-8 byte or no input.
v}
This heuristic is compatible both with BOM based
recognitition and
{{:#section-3}JSON-like encoding
recognition} that relies on ASCII being present at the beginning
of the stream. Also, {!decoder_removed_bom} will tell the client
if the guess was BOM based.
{b Newline normalization.} If [nln] is specified, the given
newline normalization is performed, see {!nln}. Otherwise
all newlines are returned as found in the input.
{b Character position.} The line number, column number, byte count
and character count of the last decoded character (including
[`Malformed] ones) are respectively returned by {!decoder_line},
{!decoder_col}, {!decoder_byte_count} and {!decoder_count}. Before
the first call to {!val-decode} the line number is [1] and the column
is [0]. Each {!val-decode} returning [`Uchar] or [`Malformed]
increments the column until a newline. On a newline, the line
number is incremented and the column set to zero. For example the
line is [2] and column [0] after the first newline was
decoded. This can be understood as if {!val-decode} was moving an
insertion point to the right in the data. A {e newline} is
anything normalized by [`Readline], see {!nln}.
[Uutf] assumes that each Unicode scalar value has a column width
of 1. The same assumption may not be made by the display program
(e.g. for [emacs]' compilation mode you need to set
[compilation-error-screen-columns] to [nil]). The problem is in
general difficult to solve without interaction or convention with the
display program's rendering engine. Depending on the context better column
increments can be implemented by using {!Uucp.Break.tty_width_hint} or
{{:/#Grapheme_Cluster_Boundaries}
grapheme cluster boundaries} (see {!Uuseg}). *)
val decode : decoder ->
[ `Await | `Uchar of Uchar.t | `End | `Malformed of string]
* [ decode d ] is :
{ ul
{ - [ ` Await ] if [ d ] has a [ ` Manual ] input source and awaits
for more input . The client must use { ! } to provide it . }
{ - [ ` u ] if a Unicode scalar value [ u ] was decoded . }
{ - [ ` End ] if the end of input was reached . }
{ - [ ` Malformed bytes ] if the [ bytes ] sequence is malformed according to
the decoded encoding scheme . If you are interested in a best - effort
decoding you can still continue to decode after an error until the
decoder synchronizes again on valid bytes . It may however be a good
idea to signal the malformed characters by adding an { ! u_rep }
character to the parsed data , see the { { : # examples}examples } . } }
{ b Note . } Repeated invocation always eventually returns [ ` End ] , even
in case of errors .
{ul
{- [`Await] if [d] has a [`Manual] input source and awaits
for more input. The client must use {!Manual.src} to provide it.}
{- [`Uchar u] if a Unicode scalar value [u] was decoded.}
{- [`End] if the end of input was reached.}
{- [`Malformed bytes] if the [bytes] sequence is malformed according to
the decoded encoding scheme. If you are interested in a best-effort
decoding you can still continue to decode after an error until the
decoder synchronizes again on valid bytes. It may however be a good
idea to signal the malformed characters by adding an {!u_rep}
character to the parsed data, see the {{:#examples}examples}.}}
{b Note.} Repeated invocation always eventually returns [`End], even
in case of errors. *)
val decoder_encoding : decoder -> decoder_encoding
* [ decoder_encoding d ] is [ d ] 's the decoded encoding scheme of [ d ] .
{ b Warning . } If the decoder guesses the encoding or uses [ ` UTF_16 ] ,
rely on this value only after the first [ ` ] was decoded .
{b Warning.} If the decoder guesses the encoding or uses [`UTF_16],
rely on this value only after the first [`Uchar] was decoded. *)
val set_decoder_encoding : decoder -> [< decoder_encoding] -> unit
* [ set_decoder_encoding d enc ] changes the decoded encoding
to [ enc ] after decoding started .
{ b Warning . } Call only after { ! val - decode } was called on [ d ] and that the
last call to it returned something different from [ ` Await ] or data may
be lost . After encoding guess wait for at least three [ ` Uchar]s .
to [enc] after decoding started.
{b Warning.} Call only after {!val-decode} was called on [d] and that the
last call to it returned something different from [`Await] or data may
be lost. After encoding guess wait for at least three [`Uchar]s. *)
val decoder_line : decoder -> int
* [ decoder_line d ] is the line number of the last
decoded ( or malformed ) character . See { ! } for details .
decoded (or malformed) character. See {!val-decoder} for details. *)
val decoder_col : decoder -> int
* [ decoder_col d ] is the column number of the last decoded
( or malformed ) character . See { ! } for details .
(or malformed) character. See {!val-decoder} for details. *)
val decoder_byte_count : decoder -> int
val decoder_count : decoder -> int
* [ decoder_count d ] is the number of characters already decoded on [ d ]
( including malformed ones ) . See { ! } for details .
(including malformed ones). See {!val-decoder} for details. *)
val decoder_removed_bom : decoder -> bool
* [ decoder_removed_bom d ] is [ true ] iff an { e initial }
{ { : } was
removed from the input stream . See { ! } for details .
{{:/#byte_order_mark}BOM} was
removed from the input stream. See {!val-decoder} for details. *)
val decoder_src : decoder -> src
val decoder_nln : decoder -> nln option
val pp_decode : Format.formatter ->
[< `Await | `Uchar of Uchar.t | `End | `Malformed of string] -> unit
* { 1 : encode Encode }
type dst = [ `Channel of out_channel | `Buffer of Buffer.t | `Manual ]
* The type for output destinations . With a [ ` Manual ] destination the client
must provide output storage with { ! } .
must provide output storage with {!Manual.dst}. *)
type encoder
* The type for Unicode encoders .
val encoder : [< encoding] -> [< dst] -> encoder
* [ encoder encoding dst ] is an encoder for [ encoding ] that outputs
to [ dst ] .
{ b Note . } No initial
{ { : }
is encoded . If needed , this duty is left to the client .
to [dst].
{b Note.} No initial
{{:/#byte_order_mark}BOM}
is encoded. If needed, this duty is left to the client. *)
val encode :
encoder -> [<`Await | `End | `Uchar of Uchar.t ] -> [`Ok | `Partial ]
* [ encode e v ] is :
{ ul
{ - [ ` Partial ] iff [ e ] has a [ ` Manual ] destination and needs more output
storage . The client must use { ! } to provide a new buffer
and then call { ! - encode } with [ ` Await ] until [ ` Ok ] is returned . }
{ - [ ` Ok ] when the encoder is ready to encode a new [ ` ] or [ ` End ] } }
For [ ` Manual ] destination , encoding [ ` End ] always returns
[ ` Partial ] , the client should continue as usual with [ ` Await ]
until [ ` Ok ] is returned at which point { ! Manual.dst_rem } [ e ] is
guaranteed to be the size of the last provided buffer ( i.e. nothing
was written ) .
{ b Raises . } [ Invalid_argument ] if an [ ` ] or [ ` End ] is encoded
after a [ ` Partial ] encode .
{ul
{- [`Partial] iff [e] has a [`Manual] destination and needs more output
storage. The client must use {!Manual.dst} to provide a new buffer
and then call {!val-encode} with [`Await] until [`Ok] is returned.}
{- [`Ok] when the encoder is ready to encode a new [`Uchar] or [`End]}}
For [`Manual] destination, encoding [`End] always returns
[`Partial], the client should continue as usual with [`Await]
until [`Ok] is returned at which point {!Manual.dst_rem} [e] is
guaranteed to be the size of the last provided buffer (i.e. nothing
was written).
{b Raises.} [Invalid_argument] if an [`Uchar] or [`End] is encoded
after a [`Partial] encode. *)
val encoder_encoding : encoder -> encoding
val encoder_dst : encoder -> dst
* { 1 : manual Manual sources and destinations . }
module Manual : sig
val src : decoder -> Bytes.t -> int -> int -> unit
val dst : encoder -> Bytes.t -> int -> int -> unit
val dst_rem : encoder -> int
* [ dst_rem e ] is the remaining number of non - written , free bytes
in the last buffer provided with { ! } .
in the last buffer provided with {!Manual.dst}. *)
end
* { 1 : strbuf String folders and Buffer encoders }
* Fold over the characters of UTF encoded OCaml [ string ] values .
{ b Note . } Since OCaml 4.14 , UTF decoders are available in
{ ! . String } . You are encouraged to migrate to them .
{b Note.} Since OCaml 4.14, UTF decoders are available in
{!Stdlib.String}. You are encouraged to migrate to them. *)
module String : sig
val encoding_guess : string -> [ `UTF_8 | `UTF_16BE | `UTF_16LE ] * bool
* [ encoding_guess s ] is the encoding guessed for [ s ] coupled with
[ true ] iff there 's an initial
{ { : } .
[true] iff there's an initial
{{:/#byte_order_mark}BOM}. *)
* { 1 String folders }
{ b Note . } Initial { { : /#byte_order_mark}BOM}s
are also folded over .
{b Note.} Initial {{:/#byte_order_mark}BOM}s
are also folded over. *)
type 'a folder = 'a -> int -> [ `Uchar of Uchar.t | `Malformed of string ] ->
'a
* The type for character folders . The integer is the index in the
string where the [ ` ] or [ ` Malformed ] starts .
string where the [`Uchar] or [`Malformed] starts. *)
val fold_utf_8 : ?pos:int -> ?len:int -> 'a folder -> 'a -> string -> 'a
* [ fold_utf_8 f a s ? pos ? len ( ) ] is
[ f ( ] ... [ ( f ( f a pos u]{_0 } [ ) j]{_1 } [ u]{_1 } [ ) ] ... [ ) ] ... [ )
j]{_n } [ u]{_n }
where [ u]{_i } , [ j]{_i } are characters and their start position
in the UTF-8 encoded substring [ s ] starting at [ pos ] and [ len ]
long . The default value for [ pos ] is [ 0 ] and [ len ] is
[ String.length s - pos ] .
[f (] ... [(f (f a pos u]{_0}[) j]{_1}[ u]{_1}[)] ... [)] ... [)
j]{_n}[ u]{_n}
where [u]{_i}, [j]{_i} are characters and their start position
in the UTF-8 encoded substring [s] starting at [pos] and [len]
long. The default value for [pos] is [0] and [len] is
[String.length s - pos]. *)
val fold_utf_16be : ?pos:int -> ?len:int -> 'a folder -> 'a -> string -> 'a
* [ fold_utf_16be f a s ? pos ? len ( ) ] is
[ f ( ] ... [ ( f ( f a pos u]{_0 } [ ) j]{_1 } [ u]{_1 } [ ) ] ... [ ) ] ... [ )
j]{_n } [ u]{_n }
where [ u]{_i } , [ j]{_i } are characters and their start position
in the UTF-8 encoded substring [ s ] starting at [ pos ] and [ len ]
long . The default value for [ pos ] is [ 0 ] and [ len ] is
[ String.length s - pos ] .
[f (] ... [(f (f a pos u]{_0}[) j]{_1}[ u]{_1}[)] ... [)] ... [)
j]{_n}[ u]{_n}
where [u]{_i}, [j]{_i} are characters and their start position
in the UTF-8 encoded substring [s] starting at [pos] and [len]
long. The default value for [pos] is [0] and [len] is
[String.length s - pos]. *)
val fold_utf_16le : ?pos:int -> ?len:int -> 'a folder -> 'a -> string -> 'a
* [ fold_utf_16le f a s ? pos ? len ( ) ] is
[ f ( ] ... [ ( f ( f a pos u]{_0 } [ ) j]{_1 } [ u]{_1 } [ ) ] ... [ ) ] ... [ )
j]{_n } [ u]{_n }
where [ u]{_i } , [ j]{_i } are characters and their start position
in the UTF-8 encoded substring [ s ] starting at [ pos ] and [ len ]
long . The default value for [ pos ] is [ 0 ] and [ len ] is
[ String.length s - pos ] .
[f (] ... [(f (f a pos u]{_0}[) j]{_1}[ u]{_1}[)] ... [)] ... [)
j]{_n}[ u]{_n}
where [u]{_i}, [j]{_i} are characters and their start position
in the UTF-8 encoded substring [s] starting at [pos] and [len]
long. The default value for [pos] is [0] and [len] is
[String.length s - pos]. *)
end
* UTF encode characters in OCaml { ! Buffer.t } values .
{ b Note . } Since OCaml 4.06 , these encoders are available in
{ ! . Buffer } . You are encouraged to migrate to them .
{b Note.} Since OCaml 4.06, these encoders are available in
{!Stdlib.Buffer}. You are encouraged to migrate to them. *)
module Buffer : sig
* { 1 Buffer encoders }
val add_utf_8 : Buffer.t -> Uchar.t -> unit
* [ add_utf_8 b u ] adds the UTF-8 encoding of [ u ] to [ b ] .
val add_utf_16be : Buffer.t -> Uchar.t -> unit
* [ add_utf_16be b u ] adds the encoding of [ u ] to [ b ] .
val add_utf_16le : Buffer.t -> Uchar.t -> unit
* [ add_utf_16le b u ] adds the UTF-16LE encoding of [ u ] to [ b ] .
end
* { 1 : examples Examples }
{ 2 : readlines Read lines }
The value of [ lines src ] is the list of lines in [ src ] as UTF-8
encoded OCaml strings . Line breaks are determined according to the
recommendation R4 for a [ readline ] function in section 5.8 of
Unicode 9.0.0 . If a decoding error occurs we silently replace the
malformed sequence by the replacement character { ! u_rep } and continue .
{ [ let lines ? encoding ( src : [ ` Channel of in_channel | ` String of string ] ) =
let rec loop d buf acc = match Uutf.decode d with
| ` u - >
begin match Uchar.to_int u with
| 0x000A - >
let line = Buffer.contents buf in
Buffer.clear buf ; loop d buf ( line : : acc )
| _ - >
Uutf . Buffer.add_utf_8 buf u ; loop d buf acc
end
| ` End - > List.rev ( Buffer.contents buf : : acc )
| ` Malformed _ - > Uutf . Buffer.add_utf_8 buf Uutf.u_rep ; loop d buf acc
| ` Await - > assert false
in
let nln = ` Readline ( Uchar.of_int ) in
loop ( Uutf.decoder ~nln ? encoding src ) ( Buffer.create 512 ) [ ]
] }
Using the [ ` Manual ] interface , [ lines_fd ] does the same but on a Unix file
descriptor .
{ [ let lines_fd ? encoding ( fd : Unix.file_descr ) =
let rec loop fd s d buf acc = match Uutf.decode d with
| ` u - >
begin match Uchar.to_int u with
| 0x000A - >
let line = Buffer.contents buf in
Buffer.clear buf ; loop fd s d buf ( line : : acc )
| _ - >
Uutf . Buffer.add_utf_8 buf u ; loop fd s d buf acc
end
| ` End - > List.rev ( Buffer.contents buf : : acc )
| ` Malformed _ - > Uutf . Buffer.add_utf_8 buf Uutf.u_rep ; loop fd s d buf acc
| ` Await - >
let rec unix_read fd s j l = try fd s j l with
| Unix . Unix_error ( Unix . , _ , _ ) - > unix_read fd s j l
in
let rc = unix_read fd s 0 ( Bytes.length s ) in
Uutf.Manual.src d s 0 rc ; loop fd s d buf acc
in
let s = Bytes.create ( * UNIX_BUFFER_SIZE in 4.0.0
{2:readlines Read lines}
The value of [lines src] is the list of lines in [src] as UTF-8
encoded OCaml strings. Line breaks are determined according to the
recommendation R4 for a [readline] function in section 5.8 of
Unicode 9.0.0. If a decoding error occurs we silently replace the
malformed sequence by the replacement character {!u_rep} and continue.
{[let lines ?encoding (src : [`Channel of in_channel | `String of string]) =
let rec loop d buf acc = match Uutf.decode d with
| `Uchar u ->
begin match Uchar.to_int u with
| 0x000A ->
let line = Buffer.contents buf in
Buffer.clear buf; loop d buf (line :: acc)
| _ ->
Uutf.Buffer.add_utf_8 buf u; loop d buf acc
end
| `End -> List.rev (Buffer.contents buf :: acc)
| `Malformed _ -> Uutf.Buffer.add_utf_8 buf Uutf.u_rep; loop d buf acc
| `Await -> assert false
in
let nln = `Readline (Uchar.of_int 0x000A) in
loop (Uutf.decoder ~nln ?encoding src) (Buffer.create 512) []
]}
Using the [`Manual] interface, [lines_fd] does the same but on a Unix file
descriptor.
{[let lines_fd ?encoding (fd : Unix.file_descr) =
let rec loop fd s d buf acc = match Uutf.decode d with
| `Uchar u ->
begin match Uchar.to_int u with
| 0x000A ->
let line = Buffer.contents buf in
Buffer.clear buf; loop fd s d buf (line :: acc)
| _ ->
Uutf.Buffer.add_utf_8 buf u; loop fd s d buf acc
end
| `End -> List.rev (Buffer.contents buf :: acc)
| `Malformed _ -> Uutf.Buffer.add_utf_8 buf Uutf.u_rep; loop fd s d buf acc
| `Await ->
let rec unix_read fd s j l = try Unix.read fd s j l with
| Unix.Unix_error (Unix.EINTR, _, _) -> unix_read fd s j l
in
let rc = unix_read fd s 0 (Bytes.length s) in
Uutf.Manual.src d s 0 rc; loop fd s d buf acc
in
let nln = `Readline (Uchar.of_int 0x000A) in
loop fd s (Uutf.decoder ~nln ?encoding `Manual) (Buffer.create 512) []
]}
{2:recode Recode}
The result of [recode src out_encoding dst] has the characters of
[src] written on [dst] with encoding [out_encoding]. If a
decoding error occurs we silently replace the malformed sequence
by the replacement character {!u_rep} and continue. Note that we
don't add an initial
{{:/#byte_order_mark}BOM} to [dst],
recoding will thus loose the initial BOM [src] may have. Whether
this is a problem or not depends on the context.
{[let recode ?nln ?encoding out_encoding
(src : [`Channel of in_channel | `String of string])
(dst : [`Channel of out_channel | `Buffer of Buffer.t])
=
let rec loop d e = match Uutf.decode d with
| `Uchar _ as u -> ignore (Uutf.encode e u); loop d e
| `End -> ignore (Uutf.encode e `End)
| `Malformed _ -> ignore (Uutf.encode e (`Uchar Uutf.u_rep)); loop d e
| `Await -> assert false
in
let d = Uutf.decoder ?nln ?encoding src in
let e = Uutf.encoder out_encoding dst in
loop d e]}
Using the [`Manual] interface, [recode_fd] does the same but between
Unix file descriptors.
{[let recode_fd ?nln ?encoding out_encoding
(fdi : Unix.file_descr)
(fdo : Unix.file_descr)
=
let rec encode fd s e v = match Uutf.encode e v with `Ok -> ()
| `Partial ->
let rec unix_write fd s j l =
let rec write fd s j l = try Unix.single_write fd s j l with
| Unix.Unix_error (Unix.EINTR, _, _) -> write fd s j l
in
let wc = write fd s j l in
if wc < l then unix_write fd s (j + wc) (l - wc) else ()
in
unix_write fd s 0 (Bytes.length s - Uutf.Manual.dst_rem e);
Uutf.Manual.dst e s 0 (Bytes.length s);
encode fd s e `Await
in
let rec loop fdi fdo ds es d e = match Uutf.decode d with
| `Uchar _ as u -> encode fdo es e u; loop fdi fdo ds es d e
| `End -> encode fdo es e `End
| `Malformed _ -> encode fdo es e (`Uchar Uutf.u_rep); loop fdi fdo ds es d e
| `Await ->
let rec unix_read fd s j l = try Unix.read fd s j l with
| Unix.Unix_error (Unix.EINTR, _, _) -> unix_read fd s j l
in
let rc = unix_read fdi ds 0 (Bytes.length ds) in
Uutf.Manual.src d ds 0 rc; loop fdi fdo ds es d e
in
UNIX_BUFFER_SIZE in 4.0.0
UNIX_BUFFER_SIZE in 4.0.0
let d = Uutf.decoder ?nln ?encoding `Manual in
let e = Uutf.encoder out_encoding `Manual in
Uutf.Manual.dst e es 0 (Bytes.length es);
loop fdi fdo ds es d e]}
*)
---------------------------------------------------------------------------
Copyright ( c ) 2012 The uutf programmers
Permission to use , copy , modify , and/or distribute this software for any
purpose with or without fee is hereby granted , provided that the above
copyright notice and this permission notice appear in all copies .
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
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 The uutf programmers
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---------------------------------------------------------------------------*)
|
c3f0b1319a2e8ee3008c69dbfefc60b673bc0cd8180cbb629350a8dd80c5add4 | GetShopTV/swagger2 | Generator.hs | # LANGUAGE GADTs #
# LANGUAGE OverloadedLists #
# LANGUAGE ScopedTypeVariables #
module Data.Swagger.Schema.Generator where
import Prelude ()
import Prelude.Compat
import Control.Lens.Operators
import Control.Monad (filterM)
import Data.Aeson
import qualified Data.Aeson.KeyMap as KM
import Data.Aeson.Types
import qualified Data.HashMap.Strict.InsOrd as M
import Data.Maybe
import Data.Proxy
import Data.Scientific
import qualified Data.Set as S
import Data.Swagger
import Data.Swagger.Declare
import Data.Swagger.Internal.Schema.Validation (inferSchemaTypes)
import qualified Data.Text as T
import qualified Data.Vector as V
import Test.QuickCheck (arbitrary)
import Test.QuickCheck.Gen
import Test.QuickCheck.Property
-- | Note: 'schemaGen' may 'error', if schema type is not specified,
-- and cannot be inferred.
schemaGen :: Definitions Schema -> Schema -> Gen Value
schemaGen _ schema
| Just cases <- schema ^. paramSchema . enum_ = elements cases
schemaGen defns schema =
case schema ^. type_ of
Nothing ->
case inferSchemaTypes schema of
[ inferredType ] -> schemaGen defns (schema & type_ ?~ inferredType)
Gen is not
_ -> error "unable to infer schema type"
Just SwaggerBoolean -> Bool <$> elements [True, False]
Just SwaggerNull -> pure Null
Just SwaggerNumber
| Just min <- schema ^. minimum_
, Just max <- schema ^. maximum_ ->
Number . fromFloatDigits <$>
choose (toRealFloat min, toRealFloat max :: Double)
| otherwise -> Number .fromFloatDigits <$> (arbitrary :: Gen Double)
Just SwaggerInteger
| Just min <- schema ^. minimum_
, Just max <- schema ^. maximum_ ->
Number . fromInteger <$>
choose (truncate min, truncate max)
| otherwise -> Number . fromInteger <$> arbitrary
Just SwaggerArray
| Just 0 <- schema ^. maxLength -> pure $ Array V.empty
| Just items <- schema ^. items ->
case items of
SwaggerItemsObject ref -> do
size <- getSize
let itemSchema = dereference defns ref
minLength' = fromMaybe 0 $ fromInteger <$> schema ^. minItems
maxLength' = fromMaybe size $ fromInteger <$> schema ^. maxItems
arrayLength <- choose (minLength', max minLength' maxLength')
generatedArray <- vectorOf arrayLength $ schemaGen defns itemSchema
return . Array $ V.fromList generatedArray
SwaggerItemsArray refs ->
let itemGens = schemaGen defns . dereference defns <$> refs
in fmap (Array . V.fromList) $ sequence itemGens
Just SwaggerString -> do
size <- getSize
let minLength' = fromMaybe 0 $ fromInteger <$> schema ^. minLength
let maxLength' = fromMaybe size $ fromInteger <$> schema ^. maxLength
length <- choose (minLength', max minLength' maxLength')
str <- vectorOf length arbitrary
return . String $ T.pack str
Just SwaggerObject -> do
size <- getSize
let props = dereference defns <$> schema ^. properties
reqKeys = S.fromList $ schema ^. required
allKeys = S.fromList . M.keys $ schema ^. properties
optionalKeys = allKeys S.\\ reqKeys
minProps' = fromMaybe (length reqKeys) $
fromInteger <$> schema ^. minProperties
maxProps' = fromMaybe size $ fromInteger <$> schema ^. maxProperties
shuffledOptional <- shuffle $ S.toList optionalKeys
numProps <- choose (minProps', max minProps' maxProps')
let presentKeys = take numProps $ S.toList reqKeys ++ shuffledOptional
let presentProps = M.filterWithKey (\k _ -> k `elem` presentKeys) props
let gens = schemaGen defns <$> presentProps
additionalGens <- case schema ^. additionalProperties of
Just (AdditionalPropertiesSchema addlSchema) -> do
additionalKeys <- sequence . take (numProps - length presentProps) . repeat $ T.pack <$> arbitrary
return . M.fromList $ zip additionalKeys (repeat . schemaGen defns $ dereference defns addlSchema)
_ -> return []
x <- sequence $ gens <> additionalGens
return . Object . KM.fromHashMapText $ M.toHashMap x
where
dereference :: Definitions a -> Referenced a -> a
dereference _ (Inline a) = a
dereference defs (Ref (Reference ref)) = fromJust $ M.lookup ref defs
genValue :: (ToSchema a) => Proxy a -> Gen Value
genValue p =
let (defs, NamedSchema _ schema) = runDeclare (declareNamedSchema p) M.empty
in schemaGen defs schema
validateFromJSON :: forall a . (ToSchema a, FromJSON a) => Proxy a -> Property
validateFromJSON p = forAll (genValue p) $
\val -> case parseEither parseJSON val of
Right (_ :: a) -> succeeded
Left err -> failed
{ reason = err
}
| null | https://raw.githubusercontent.com/GetShopTV/swagger2/9846955d72e7242f3c1fa982911972cd9e4eb720/src/Data/Swagger/Schema/Generator.hs | haskell | | Note: 'schemaGen' may 'error', if schema type is not specified,
and cannot be inferred. | # LANGUAGE GADTs #
# LANGUAGE OverloadedLists #
# LANGUAGE ScopedTypeVariables #
module Data.Swagger.Schema.Generator where
import Prelude ()
import Prelude.Compat
import Control.Lens.Operators
import Control.Monad (filterM)
import Data.Aeson
import qualified Data.Aeson.KeyMap as KM
import Data.Aeson.Types
import qualified Data.HashMap.Strict.InsOrd as M
import Data.Maybe
import Data.Proxy
import Data.Scientific
import qualified Data.Set as S
import Data.Swagger
import Data.Swagger.Declare
import Data.Swagger.Internal.Schema.Validation (inferSchemaTypes)
import qualified Data.Text as T
import qualified Data.Vector as V
import Test.QuickCheck (arbitrary)
import Test.QuickCheck.Gen
import Test.QuickCheck.Property
schemaGen :: Definitions Schema -> Schema -> Gen Value
schemaGen _ schema
| Just cases <- schema ^. paramSchema . enum_ = elements cases
schemaGen defns schema =
case schema ^. type_ of
Nothing ->
case inferSchemaTypes schema of
[ inferredType ] -> schemaGen defns (schema & type_ ?~ inferredType)
Gen is not
_ -> error "unable to infer schema type"
Just SwaggerBoolean -> Bool <$> elements [True, False]
Just SwaggerNull -> pure Null
Just SwaggerNumber
| Just min <- schema ^. minimum_
, Just max <- schema ^. maximum_ ->
Number . fromFloatDigits <$>
choose (toRealFloat min, toRealFloat max :: Double)
| otherwise -> Number .fromFloatDigits <$> (arbitrary :: Gen Double)
Just SwaggerInteger
| Just min <- schema ^. minimum_
, Just max <- schema ^. maximum_ ->
Number . fromInteger <$>
choose (truncate min, truncate max)
| otherwise -> Number . fromInteger <$> arbitrary
Just SwaggerArray
| Just 0 <- schema ^. maxLength -> pure $ Array V.empty
| Just items <- schema ^. items ->
case items of
SwaggerItemsObject ref -> do
size <- getSize
let itemSchema = dereference defns ref
minLength' = fromMaybe 0 $ fromInteger <$> schema ^. minItems
maxLength' = fromMaybe size $ fromInteger <$> schema ^. maxItems
arrayLength <- choose (minLength', max minLength' maxLength')
generatedArray <- vectorOf arrayLength $ schemaGen defns itemSchema
return . Array $ V.fromList generatedArray
SwaggerItemsArray refs ->
let itemGens = schemaGen defns . dereference defns <$> refs
in fmap (Array . V.fromList) $ sequence itemGens
Just SwaggerString -> do
size <- getSize
let minLength' = fromMaybe 0 $ fromInteger <$> schema ^. minLength
let maxLength' = fromMaybe size $ fromInteger <$> schema ^. maxLength
length <- choose (minLength', max minLength' maxLength')
str <- vectorOf length arbitrary
return . String $ T.pack str
Just SwaggerObject -> do
size <- getSize
let props = dereference defns <$> schema ^. properties
reqKeys = S.fromList $ schema ^. required
allKeys = S.fromList . M.keys $ schema ^. properties
optionalKeys = allKeys S.\\ reqKeys
minProps' = fromMaybe (length reqKeys) $
fromInteger <$> schema ^. minProperties
maxProps' = fromMaybe size $ fromInteger <$> schema ^. maxProperties
shuffledOptional <- shuffle $ S.toList optionalKeys
numProps <- choose (minProps', max minProps' maxProps')
let presentKeys = take numProps $ S.toList reqKeys ++ shuffledOptional
let presentProps = M.filterWithKey (\k _ -> k `elem` presentKeys) props
let gens = schemaGen defns <$> presentProps
additionalGens <- case schema ^. additionalProperties of
Just (AdditionalPropertiesSchema addlSchema) -> do
additionalKeys <- sequence . take (numProps - length presentProps) . repeat $ T.pack <$> arbitrary
return . M.fromList $ zip additionalKeys (repeat . schemaGen defns $ dereference defns addlSchema)
_ -> return []
x <- sequence $ gens <> additionalGens
return . Object . KM.fromHashMapText $ M.toHashMap x
where
dereference :: Definitions a -> Referenced a -> a
dereference _ (Inline a) = a
dereference defs (Ref (Reference ref)) = fromJust $ M.lookup ref defs
genValue :: (ToSchema a) => Proxy a -> Gen Value
genValue p =
let (defs, NamedSchema _ schema) = runDeclare (declareNamedSchema p) M.empty
in schemaGen defs schema
validateFromJSON :: forall a . (ToSchema a, FromJSON a) => Proxy a -> Property
validateFromJSON p = forAll (genValue p) $
\val -> case parseEither parseJSON val of
Right (_ :: a) -> succeeded
Left err -> failed
{ reason = err
}
|
ba0ecf23d6e7ac9e0ea3481f15df628863835b49e336debc144a7bef6086bd8a | emqx/emqx-sn | emqx_sn_app.erl | %%--------------------------------------------------------------------
Copyright ( c ) 2020 EMQ Technologies Co. , Ltd. All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%--------------------------------------------------------------------
-module(emqx_sn_app).
-behaviour(application).
-emqx_plugin(protocol).
-export([ start/2
, stop/1
]).
-export([ start_listeners/0
, start_listener/1
, start_listener/3
, stop_listeners/0
, stop_listener/1
, stop_listener/3
]).
-define(UDP_SOCKOPTS, []).
-type(listener() :: {esockd:proto(), esockd:listen_on(), [esockd:option()]}).
%%--------------------------------------------------------------------
%% Application
%%--------------------------------------------------------------------
start(_Type, _Args) ->
Addr = application:get_env(emqx_sn, port, 1884),
GwId = application:get_env(emqx_sn, gateway_id, 1),
{ok, Sup} = emqx_sn_sup:start_link(Addr, GwId),
start_listeners(),
{ok, Sup}.
stop(_State) ->
stop_listeners(),
ok.
%%--------------------------------------------------------------------
%% Listners
%%--------------------------------------------------------------------
-spec start_listeners() -> ok.
start_listeners() ->
PredefTopics = application:get_env(emqx_sn, predefined, []),
ListenCfs = [begin
TabName = tabname(Proto, ListenOn),
{ok, RegistryPid} = emqx_sn_sup:start_registry_proc(emqx_sn_sup, TabName, PredefTopics),
{Proto, ListenOn, [{registry, {TabName, RegistryPid}} | Options]}
end || {Proto, ListenOn, Options} <- listeners_confs()],
lists:foreach(fun start_listener/1, ListenCfs).
-spec start_listener(listener()) -> ok.
start_listener({Proto, ListenOn, Options}) ->
case start_listener(Proto, ListenOn, Options) of
{ok, _} -> io:format("Start mqttsn:~s listener on ~s successfully.~n",
[Proto, format(ListenOn)]);
{error, Reason} ->
io:format(standard_error, "Failed to start mqttsn:~s listener on ~s - ~0p~n!",
[Proto, format(ListenOn), Reason]),
error(Reason)
end.
Start MQTTSN listener
-spec start_listener(esockd:proto(), esockd:listen_on(), [esockd:option()])
-> {ok, pid()} | {error, term()}.
start_listener(udp, ListenOn, Options) ->
start_udp_listener('mqttsn:udp', ListenOn, Options);
start_listener(dtls, ListenOn, Options) ->
start_udp_listener('mqttsn:dtls', ListenOn, Options).
@private
start_udp_listener(Name, ListenOn, Options) ->
SockOpts = esockd:parse_opt(Options),
esockd:open_udp(Name, ListenOn, merge_default(SockOpts),
{emqx_sn_gateway, start_link, [Options -- SockOpts]}).
-spec stop_listeners() -> ok.
stop_listeners() ->
lists:foreach(fun stop_listener/1, listeners_confs()).
-spec stop_listener(listener()) -> ok | {error, term()}.
stop_listener({Proto, ListenOn, Opts}) ->
StopRet = stop_listener(Proto, ListenOn, Opts),
case StopRet of
ok -> io:format("Stop mqttsn:~s listener on ~s successfully.~n",
[Proto, format(ListenOn)]);
{error, Reason} ->
io:format(standard_error, "Failed to stop mqttsn:~s listener on ~s - ~p~n.",
[Proto, format(ListenOn), Reason])
end,
StopRet.
-spec stop_listener(esockd:proto(), esockd:listen_on(), [esockd:option()])
-> ok | {error, term()}.
stop_listener(udp, ListenOn, _Opts) ->
esockd:close('mqttsn:udp', ListenOn);
stop_listener(dtls, ListenOn, _Opts) ->
esockd:close('mqttsn:dtls', ListenOn).
%%--------------------------------------------------------------------
Internal funcs
%%--------------------------------------------------------------------
@private
%% In order to compatible with the old version of the configuration format
listeners_confs() ->
ListenOn = application:get_env(emqx_sn, port, 1884),
GwId = application:get_env(emqx_sn, gateway_id, 1),
Username = application:get_env(emqx_sn, username, undefined),
Password = application:get_env(emqx_sn, password, undefined),
EnableQos3 = application:get_env(emqx_sn, enable_qos3, false),
EnableStats = application:get_env(emqx_sn, enable_stats, false),
IdleTimeout = application:get_env(emqx_sn, idle_timeout, 30000),
[{udp, ListenOn, [{gateway_id, GwId},
{username, Username},
{password, Password},
{enable_qos3, EnableQos3},
{enable_stats, EnableStats},
{idle_timeout, IdleTimeout},
{max_connections, 1024000},
{max_conn_rate, 1000},
{udp_options, []}]}].
merge_default(Options) ->
case lists:keytake(udp_options, 1, Options) of
{value, {udp_options, TcpOpts}, Options1} ->
[{udp_options, emqx_misc:merge_opts(?UDP_SOCKOPTS, TcpOpts)} | Options1];
false ->
[{udp_options, ?UDP_SOCKOPTS} | Options]
end.
format(Port) when is_integer(Port) ->
io_lib:format("0.0.0.0:~w", [Port]);
format({Addr, Port}) when is_list(Addr) ->
io_lib:format("~s:~w", [Addr, Port]);
format({Addr, Port}) when is_tuple(Addr) ->
io_lib:format("~s:~w", [inet:ntoa(Addr), Port]).
tabname(Proto, ListenOn) ->
list_to_atom(lists:flatten(["emqx_sn_registry__", atom_to_list(Proto), "_", format(ListenOn)])).
| null | https://raw.githubusercontent.com/emqx/emqx-sn/8f94f68f3740c328bd905e5d4581d58e9013fbba/src/emqx_sn_app.erl | erlang | --------------------------------------------------------------------
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--------------------------------------------------------------------
--------------------------------------------------------------------
Application
--------------------------------------------------------------------
--------------------------------------------------------------------
Listners
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
In order to compatible with the old version of the configuration format | Copyright ( c ) 2020 EMQ Technologies Co. , Ltd. All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(emqx_sn_app).
-behaviour(application).
-emqx_plugin(protocol).
-export([ start/2
, stop/1
]).
-export([ start_listeners/0
, start_listener/1
, start_listener/3
, stop_listeners/0
, stop_listener/1
, stop_listener/3
]).
-define(UDP_SOCKOPTS, []).
-type(listener() :: {esockd:proto(), esockd:listen_on(), [esockd:option()]}).
start(_Type, _Args) ->
Addr = application:get_env(emqx_sn, port, 1884),
GwId = application:get_env(emqx_sn, gateway_id, 1),
{ok, Sup} = emqx_sn_sup:start_link(Addr, GwId),
start_listeners(),
{ok, Sup}.
stop(_State) ->
stop_listeners(),
ok.
-spec start_listeners() -> ok.
start_listeners() ->
PredefTopics = application:get_env(emqx_sn, predefined, []),
ListenCfs = [begin
TabName = tabname(Proto, ListenOn),
{ok, RegistryPid} = emqx_sn_sup:start_registry_proc(emqx_sn_sup, TabName, PredefTopics),
{Proto, ListenOn, [{registry, {TabName, RegistryPid}} | Options]}
end || {Proto, ListenOn, Options} <- listeners_confs()],
lists:foreach(fun start_listener/1, ListenCfs).
-spec start_listener(listener()) -> ok.
start_listener({Proto, ListenOn, Options}) ->
case start_listener(Proto, ListenOn, Options) of
{ok, _} -> io:format("Start mqttsn:~s listener on ~s successfully.~n",
[Proto, format(ListenOn)]);
{error, Reason} ->
io:format(standard_error, "Failed to start mqttsn:~s listener on ~s - ~0p~n!",
[Proto, format(ListenOn), Reason]),
error(Reason)
end.
Start MQTTSN listener
-spec start_listener(esockd:proto(), esockd:listen_on(), [esockd:option()])
-> {ok, pid()} | {error, term()}.
start_listener(udp, ListenOn, Options) ->
start_udp_listener('mqttsn:udp', ListenOn, Options);
start_listener(dtls, ListenOn, Options) ->
start_udp_listener('mqttsn:dtls', ListenOn, Options).
@private
start_udp_listener(Name, ListenOn, Options) ->
SockOpts = esockd:parse_opt(Options),
esockd:open_udp(Name, ListenOn, merge_default(SockOpts),
{emqx_sn_gateway, start_link, [Options -- SockOpts]}).
-spec stop_listeners() -> ok.
stop_listeners() ->
lists:foreach(fun stop_listener/1, listeners_confs()).
-spec stop_listener(listener()) -> ok | {error, term()}.
stop_listener({Proto, ListenOn, Opts}) ->
StopRet = stop_listener(Proto, ListenOn, Opts),
case StopRet of
ok -> io:format("Stop mqttsn:~s listener on ~s successfully.~n",
[Proto, format(ListenOn)]);
{error, Reason} ->
io:format(standard_error, "Failed to stop mqttsn:~s listener on ~s - ~p~n.",
[Proto, format(ListenOn), Reason])
end,
StopRet.
-spec stop_listener(esockd:proto(), esockd:listen_on(), [esockd:option()])
-> ok | {error, term()}.
stop_listener(udp, ListenOn, _Opts) ->
esockd:close('mqttsn:udp', ListenOn);
stop_listener(dtls, ListenOn, _Opts) ->
esockd:close('mqttsn:dtls', ListenOn).
Internal funcs
@private
listeners_confs() ->
ListenOn = application:get_env(emqx_sn, port, 1884),
GwId = application:get_env(emqx_sn, gateway_id, 1),
Username = application:get_env(emqx_sn, username, undefined),
Password = application:get_env(emqx_sn, password, undefined),
EnableQos3 = application:get_env(emqx_sn, enable_qos3, false),
EnableStats = application:get_env(emqx_sn, enable_stats, false),
IdleTimeout = application:get_env(emqx_sn, idle_timeout, 30000),
[{udp, ListenOn, [{gateway_id, GwId},
{username, Username},
{password, Password},
{enable_qos3, EnableQos3},
{enable_stats, EnableStats},
{idle_timeout, IdleTimeout},
{max_connections, 1024000},
{max_conn_rate, 1000},
{udp_options, []}]}].
merge_default(Options) ->
case lists:keytake(udp_options, 1, Options) of
{value, {udp_options, TcpOpts}, Options1} ->
[{udp_options, emqx_misc:merge_opts(?UDP_SOCKOPTS, TcpOpts)} | Options1];
false ->
[{udp_options, ?UDP_SOCKOPTS} | Options]
end.
format(Port) when is_integer(Port) ->
io_lib:format("0.0.0.0:~w", [Port]);
format({Addr, Port}) when is_list(Addr) ->
io_lib:format("~s:~w", [Addr, Port]);
format({Addr, Port}) when is_tuple(Addr) ->
io_lib:format("~s:~w", [inet:ntoa(Addr), Port]).
tabname(Proto, ListenOn) ->
list_to_atom(lists:flatten(["emqx_sn_registry__", atom_to_list(Proto), "_", format(ListenOn)])).
|
efa2ecc7734cd420fdf679fee5dfaf2d2ffcbd836264a513b74f018d19373f64 | akiss/akiss | util.ml | (****************************************************************************)
(* Akiss *)
Copyright ( C ) 2011 - 2014 Baelde , Ciobaca , Delaune , Kremer
(* *)
(* This program is free software; you can redistribute it and/or modify *)
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
(* (at your option) any later version. *)
(* *)
(* This program is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU General Public License for more details. *)
(* *)
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
(****************************************************************************)
exception Bug
let bench = ref 0.
let bench_cur = ref 0.
let bench_start () = bench_cur := Sys.time ()
let bench_stop () = bench := !bench +. Sys.time () -. !bench_cur
let debug_output = ref false
let verbose_output = ref false
let about_seed = ref false
let debug_seed = ref false
let about_saturation = ref false
let debug_saturation = false
let about_tests = ref false
let debug_tests = ref false
let about_else = ref false
let about_execution = ref false
let about_theory = ref false
let debug_theory = false
let about_traces = ref false
let about_maude = ref false
let verboseOutput a =
if ! verbose_output || about_verbose then
Format.printf a
else
Format.ifprintf Format.std_formatter a
let debugOutput a =
if ! debug_output || ! then
Format.printf a
else
Format.ifprintf Format.std_formatter a
if !verbose_output || about_verbose then
Format.printf a
else
Format.ifprintf Format.std_formatter a
let debugOutput a =
if !debug_output || !about_debug then
Format.printf a
else
Format.ifprintf Format.std_formatter a*)
let normalOutput a =
if !verbose_output || !debug_output then
Format.ifprintf Format.std_formatter a
else
Format.printf a
TODO use the standard library :
* - List.rev is already tailrec
* - is many places , trmap is useless , reversing would be harmless
* - stop using lists as sets
* - List.rev is already tailrec
* - is many places, trmap is useless, reversing would be harmless
* - stop using lists as sets *)
let trmap f l = List.rev (List.rev_map f l)
(** When using lists as sets List.concat is uselessly costly (not
* tail-recursive) and the following union function is preferable.
* It does not preserve the order. *)
let rec union acc = function
| [] -> acc
| traces :: l -> union (List.rev_append traces acc) l
let union l = union [] l
(** Return a list without duplicates, for structural equality. *)
let unique =
let f res e =
if List.mem e res then
res
else
e::res
in
fun l -> List.fold_left f [] l
(** [create_list elem no]
* creates a list containing [no] times the element [elem]. *)
let rec create_list elem no =
if no = 0 then
[]
else
elem :: (create_list elem (no - 1))
(** [create_consecutive start no] returns the list
* [start;start+1;...;start+no-1] of length [no]. *)
let rec create_consecutive start no =
if no = 0 then
[]
else
start :: (create_consecutive (start + 1) (no - 1))
let fresh_string =
let counter = ref 0 in
fun prefix ->
let result = prefix ^ (string_of_int !counter) in
counter := !counter + 1;
result
let fresh_variable () = fresh_string "X"
let fresh_axiom () = fresh_string "axiom"
let combine l1 l2 =
List.fold_left
(fun c e1 ->
List.fold_left (fun c e2 -> (e1,e2)::c) c l2)
[]
l1
let list_diff big small =
List.filter (function x -> not (List.mem x small)) big
let list_intersect list1 list2 =
List.filter (function x -> List.mem x list2) list1
let rec is_prefix small big = match (small, big) with
| ([], _) -> true
| (s :: sr, b :: br) when s = b -> (is_prefix sr br)
| _ -> false
(* iterate f on a until a fixpoint is reached *)
let rec iterate f a =
let next = f a in
if next = a then
a
else
iterate f next
(* iterate "f" on "a" "n" times *)
let rec iterate_n n f a =
if n = 0 then
a
else
iterate_n (n - 1) f (f a)
let rec take n list =
if n = 0 then
[]
else
match list with
| hd :: tl -> hd :: take (n - 1) tl
| [] -> []
let rec all_prefixes = function
| [] -> []
| h :: t -> [] :: (trmap (fun x -> h :: x) (all_prefixes t))
let show_string_list list =
String.concat ", " list
let startswith s ~prefix =
if String.length s < String.length prefix then
false
else
try
for i = 0 to String.length prefix - 1 do
if s.[i] <> prefix.[i] then raise Not_found
done ;
true
with Not_found -> false
let output_string ch s = Format.fprintf ch "%s" s
let rec pp_list pp sep chan = function
| [] -> ()
| [x] -> pp chan x
| x::tl ->
pp chan x ;
output_string chan sep ;
pp_list pp sep chan tl
| null | https://raw.githubusercontent.com/akiss/akiss/5577c6bb31e463c18c1cb05430e344a2734c8407/src/util.ml | ocaml | **************************************************************************
Akiss
This program is free software; you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
**************************************************************************
* When using lists as sets List.concat is uselessly costly (not
* tail-recursive) and the following union function is preferable.
* It does not preserve the order.
* Return a list without duplicates, for structural equality.
* [create_list elem no]
* creates a list containing [no] times the element [elem].
* [create_consecutive start no] returns the list
* [start;start+1;...;start+no-1] of length [no].
iterate f on a until a fixpoint is reached
iterate "f" on "a" "n" times | Copyright ( C ) 2011 - 2014 Baelde , Ciobaca , Delaune , Kremer
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
exception Bug
let bench = ref 0.
let bench_cur = ref 0.
let bench_start () = bench_cur := Sys.time ()
let bench_stop () = bench := !bench +. Sys.time () -. !bench_cur
let debug_output = ref false
let verbose_output = ref false
let about_seed = ref false
let debug_seed = ref false
let about_saturation = ref false
let debug_saturation = false
let about_tests = ref false
let debug_tests = ref false
let about_else = ref false
let about_execution = ref false
let about_theory = ref false
let debug_theory = false
let about_traces = ref false
let about_maude = ref false
let verboseOutput a =
if ! verbose_output || about_verbose then
Format.printf a
else
Format.ifprintf Format.std_formatter a
let debugOutput a =
if ! debug_output || ! then
Format.printf a
else
Format.ifprintf Format.std_formatter a
if !verbose_output || about_verbose then
Format.printf a
else
Format.ifprintf Format.std_formatter a
let debugOutput a =
if !debug_output || !about_debug then
Format.printf a
else
Format.ifprintf Format.std_formatter a*)
let normalOutput a =
if !verbose_output || !debug_output then
Format.ifprintf Format.std_formatter a
else
Format.printf a
TODO use the standard library :
* - List.rev is already tailrec
* - is many places , trmap is useless , reversing would be harmless
* - stop using lists as sets
* - List.rev is already tailrec
* - is many places, trmap is useless, reversing would be harmless
* - stop using lists as sets *)
let trmap f l = List.rev (List.rev_map f l)
let rec union acc = function
| [] -> acc
| traces :: l -> union (List.rev_append traces acc) l
let union l = union [] l
let unique =
let f res e =
if List.mem e res then
res
else
e::res
in
fun l -> List.fold_left f [] l
let rec create_list elem no =
if no = 0 then
[]
else
elem :: (create_list elem (no - 1))
let rec create_consecutive start no =
if no = 0 then
[]
else
start :: (create_consecutive (start + 1) (no - 1))
let fresh_string =
let counter = ref 0 in
fun prefix ->
let result = prefix ^ (string_of_int !counter) in
counter := !counter + 1;
result
let fresh_variable () = fresh_string "X"
let fresh_axiom () = fresh_string "axiom"
let combine l1 l2 =
List.fold_left
(fun c e1 ->
List.fold_left (fun c e2 -> (e1,e2)::c) c l2)
[]
l1
let list_diff big small =
List.filter (function x -> not (List.mem x small)) big
let list_intersect list1 list2 =
List.filter (function x -> List.mem x list2) list1
let rec is_prefix small big = match (small, big) with
| ([], _) -> true
| (s :: sr, b :: br) when s = b -> (is_prefix sr br)
| _ -> false
let rec iterate f a =
let next = f a in
if next = a then
a
else
iterate f next
let rec iterate_n n f a =
if n = 0 then
a
else
iterate_n (n - 1) f (f a)
let rec take n list =
if n = 0 then
[]
else
match list with
| hd :: tl -> hd :: take (n - 1) tl
| [] -> []
let rec all_prefixes = function
| [] -> []
| h :: t -> [] :: (trmap (fun x -> h :: x) (all_prefixes t))
let show_string_list list =
String.concat ", " list
let startswith s ~prefix =
if String.length s < String.length prefix then
false
else
try
for i = 0 to String.length prefix - 1 do
if s.[i] <> prefix.[i] then raise Not_found
done ;
true
with Not_found -> false
let output_string ch s = Format.fprintf ch "%s" s
let rec pp_list pp sep chan = function
| [] -> ()
| [x] -> pp chan x
| x::tl ->
pp chan x ;
output_string chan sep ;
pp_list pp sep chan tl
|
b6718c86c4a4c027cda05fe1797a0f5e5f1e047a7dbe122588876731d8adb050 | dharmatech/abstracting | glu.scm | ;;;; glu.scm
(use easyffi)
(cond-expand
(msvc
#>
#define WIN32_LEAN_AND_MEAN 1
#include <windows.h>
#include <GL/glu.h>
<#)
(else
#>
#ifdef C_MACOSX
#include <OpenGL/glu.h>
#else
#include <GL/glu.h>
#endif
<#))
(foreign-parse #<<EOF
___declare(export_constants, yes)
/* ___declare(substitute, "^(GLU_|glu);glu:") */
typedef unsigned int GLenum;
typedef unsigned char GLboolean;
typedef unsigned int GLbitfield;
typedef void GLvoid;
typedef ___byte GLbyte; /* 1-byte signed */
/ * 2 - byte signed * /
/ * 4 - byte signed * /
typedef unsigned ___byte GLubyte; /* 1-byte unsigned */
/ * 2 - byte unsigned * /
/ * 4 - byte unsigned * /
/ * 4 - byte signed * /
typedef float GLfloat; /* single precision float */
/ * single precision float in [ 0,1 ] * /
typedef double GLdouble; /* double precision float */
/ * double precision float in [ 0,1 ] * /
/* Boolean */
#define GLU_FALSE 0
#define GLU_TRUE 1
/* StringName */
#define GLU_VERSION 100800
#define GLU_EXTENSIONS 100801
/* ErrorCode */
#define GLU_INVALID_ENUM 100900
#define GLU_INVALID_VALUE 100901
#define GLU_OUT_OF_MEMORY 100902
#define GLU_INVALID_OPERATION 100904
/* NurbsDisplay */
/* GLU_FILL */
#define GLU_OUTLINE_POLYGON 100240
#define GLU_OUTLINE_PATCH 100241
/* NurbsCallback */
#define GLU_NURBS_ERROR 100103
#define GLU_ERROR 100103
#define GLU_NURBS_BEGIN 100164
#define GLU_NURBS_BEGIN_EXT 100164
#define GLU_NURBS_VERTEX 100165
#define GLU_NURBS_VERTEX_EXT 100165
#define GLU_NURBS_NORMAL 100166
#define GLU_NURBS_NORMAL_EXT 100166
#define GLU_NURBS_COLOR 100167
#define GLU_NURBS_COLOR_EXT 100167
#define GLU_NURBS_TEXTURE_COORD 100168
#define GLU_NURBS_TEX_COORD_EXT 100168
#define GLU_NURBS_END 100169
#define GLU_NURBS_END_EXT 100169
#define GLU_NURBS_BEGIN_DATA 100170
#define GLU_NURBS_BEGIN_DATA_EXT 100170
#define GLU_NURBS_VERTEX_DATA 100171
#define GLU_NURBS_VERTEX_DATA_EXT 100171
#define GLU_NURBS_NORMAL_DATA 100172
#define GLU_NURBS_NORMAL_DATA_EXT 100172
#define GLU_NURBS_COLOR_DATA 100173
#define GLU_NURBS_COLOR_DATA_EXT 100173
#define GLU_NURBS_TEXTURE_COORD_DATA 100174
#define GLU_NURBS_TEX_COORD_DATA_EXT 100174
#define GLU_NURBS_END_DATA 100175
#define GLU_NURBS_END_DATA_EXT 100175
/* NurbsError */
#define GLU_NURBS_ERROR1 100251
#define GLU_NURBS_ERROR2 100252
#define GLU_NURBS_ERROR3 100253
#define GLU_NURBS_ERROR4 100254
#define GLU_NURBS_ERROR5 100255
#define GLU_NURBS_ERROR6 100256
#define GLU_NURBS_ERROR7 100257
#define GLU_NURBS_ERROR8 100258
#define GLU_NURBS_ERROR9 100259
#define GLU_NURBS_ERROR10 100260
#define GLU_NURBS_ERROR11 100261
#define GLU_NURBS_ERROR12 100262
#define GLU_NURBS_ERROR13 100263
#define GLU_NURBS_ERROR14 100264
#define GLU_NURBS_ERROR15 100265
#define GLU_NURBS_ERROR16 100266
#define GLU_NURBS_ERROR17 100267
#define GLU_NURBS_ERROR18 100268
#define GLU_NURBS_ERROR19 100269
#define GLU_NURBS_ERROR20 100270
#define GLU_NURBS_ERROR21 100271
#define GLU_NURBS_ERROR22 100272
#define GLU_NURBS_ERROR23 100273
#define GLU_NURBS_ERROR24 100274
#define GLU_NURBS_ERROR25 100275
#define GLU_NURBS_ERROR26 100276
#define GLU_NURBS_ERROR27 100277
#define GLU_NURBS_ERROR28 100278
#define GLU_NURBS_ERROR29 100279
#define GLU_NURBS_ERROR30 100280
#define GLU_NURBS_ERROR31 100281
#define GLU_NURBS_ERROR32 100282
#define GLU_NURBS_ERROR33 100283
#define GLU_NURBS_ERROR34 100284
#define GLU_NURBS_ERROR35 100285
#define GLU_NURBS_ERROR36 100286
#define GLU_NURBS_ERROR37 100287
/* NurbsProperty */
#define GLU_AUTO_LOAD_MATRIX 100200
#define GLU_CULLING 100201
#define GLU_SAMPLING_TOLERANCE 100203
#define GLU_DISPLAY_MODE 100204
#define GLU_PARAMETRIC_TOLERANCE 100202
#define GLU_SAMPLING_METHOD 100205
#define GLU_U_STEP 100206
#define GLU_V_STEP 100207
#define GLU_NURBS_MODE 100160
#define GLU_NURBS_MODE_EXT 100160
#define GLU_NURBS_TESSELLATOR 100161
#define GLU_NURBS_TESSELLATOR_EXT 100161
#define GLU_NURBS_RENDERER 100162
#define GLU_NURBS_RENDERER_EXT 100162
/* NurbsSampling */
#define GLU_OBJECT_PARAMETRIC_ERROR 100208
#define GLU_OBJECT_PARAMETRIC_ERROR_EXT 100208
#define GLU_OBJECT_PATH_LENGTH 100209
#define GLU_OBJECT_PATH_LENGTH_EXT 100209
#define GLU_PATH_LENGTH 100215
#define GLU_PARAMETRIC_ERROR 100216
#define GLU_DOMAIN_DISTANCE 100217
/* NurbsTrim */
#define GLU_MAP1_TRIM_2 100210
#define GLU_MAP1_TRIM_3 100211
/* QuadricDrawStyle */
#define GLU_POINT 100010
#define GLU_LINE 100011
#define GLU_FILL 100012
#define GLU_SILHOUETTE 100013
/* QuadricCallback */
/* GLU_ERROR */
/* QuadricNormal */
#define GLU_SMOOTH 100000
#define GLU_FLAT 100001
#define GLU_NONE 100002
/* QuadricOrientation */
#define GLU_OUTSIDE 100020
#define GLU_INSIDE 100021
/* TessCallback */
#define GLU_TESS_BEGIN 100100
#define GLU_BEGIN 100100
#define GLU_TESS_VERTEX 100101
#define GLU_VERTEX 100101
#define GLU_TESS_END 100102
#define GLU_END 100102
#define GLU_TESS_ERROR 100103
#define GLU_TESS_EDGE_FLAG 100104
#define GLU_EDGE_FLAG 100104
#define GLU_TESS_COMBINE 100105
#define GLU_TESS_BEGIN_DATA 100106
#define GLU_TESS_VERTEX_DATA 100107
#define GLU_TESS_END_DATA 100108
#define GLU_TESS_ERROR_DATA 100109
#define GLU_TESS_EDGE_FLAG_DATA 100110
#define GLU_TESS_COMBINE_DATA 100111
/* TessContour */
#define GLU_CW 100120
#define GLU_CCW 100121
#define GLU_INTERIOR 100122
#define GLU_EXTERIOR 100123
#define GLU_UNKNOWN 100124
/* TessProperty */
#define GLU_TESS_WINDING_RULE 100140
#define GLU_TESS_BOUNDARY_ONLY 100141
#define GLU_TESS_TOLERANCE 100142
/* TessError */
#define GLU_TESS_ERROR1 100151
#define GLU_TESS_ERROR2 100152
#define GLU_TESS_ERROR3 100153
#define GLU_TESS_ERROR4 100154
#define GLU_TESS_ERROR5 100155
#define GLU_TESS_ERROR6 100156
#define GLU_TESS_ERROR7 100157
#define GLU_TESS_ERROR8 100158
#define GLU_TESS_MISSING_BEGIN_POLYGON 100151
#define GLU_TESS_MISSING_BEGIN_CONTOUR 100152
#define GLU_TESS_MISSING_END_POLYGON 100153
#define GLU_TESS_MISSING_END_CONTOUR 100154
#define GLU_TESS_COORD_TOO_LARGE 100155
#define GLU_TESS_NEED_COMBINE_CALLBACK 100156
/* TessWinding */
#define GLU_TESS_WINDING_ODD 100130
#define GLU_TESS_WINDING_NONZERO 100131
#define GLU_TESS_WINDING_POSITIVE 100132
#define GLU_TESS_WINDING_NEGATIVE 100133
#define GLU_TESS_WINDING_ABS_GEQ_TWO 100134
/*************************************************************/
typedef struct GLUnurbs GLUnurbs;
typedef struct GLUquadric GLUquadric;
typedef struct GLUtesselator GLUtesselator;
#define GLU_TESS_MAX_COORD 1.0e+150
/* Internal convenience typedefs */
void gluBeginCurve (GLUnurbs* nurb);
void gluBeginPolygon (GLUtesselator* tess);
void gluBeginSurface (GLUnurbs* nurb);
void gluBeginTrim (GLUnurbs* nurb);
GLint gluBuild1DMipmaps (GLenum target, GLint internalFormat, GLsizei width, GLenum format, GLenum type, const void *data);
GLint gluBuild2DMipmaps (GLenum target, GLint internalFormat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *data);
void gluCylinder (GLUquadric* quad, GLdouble base, GLdouble top, GLdouble height, GLint slices, GLint stacks);
void gluDeleteNurbsRenderer (GLUnurbs* nurb);
void gluDeleteQuadric (GLUquadric* quad);
void gluDeleteTess (GLUtesselator* tess);
void gluDisk (GLUquadric* quad, GLdouble inner, GLdouble outer, GLint slices, GLint loops);
void gluEndCurve (GLUnurbs* nurb);
void gluEndPolygon (GLUtesselator* tess);
void gluEndSurface (GLUnurbs* nurb);
void gluEndTrim (GLUnurbs* nurb);
char * gluErrorString (GLenum err);
void gluGetNurbsProperty (GLUnurbs* nurb, GLenum property, GLfloat* data);
char * gluGetString (GLenum name);
void gluGetTessProperty (GLUtesselator* tess, GLenum which, GLdouble* data);
void gluLoadSamplingMatrices (GLUnurbs* nurb, const GLfloat *model, const GLfloat *perspective, const GLint *view);
void gluLookAt (GLdouble eyeX, GLdouble eyeY, GLdouble eyeZ, GLdouble centerX, GLdouble centerY, GLdouble centerZ, GLdouble upX, GLdouble upY, GLdouble upZ);
GLUnurbs* gluNewNurbsRenderer (void);
GLUquadric* gluNewQuadric (void);
GLUtesselator* gluNewTess (void);
void gluNextContour (GLUtesselator* tess, GLenum type);
void gluNurbsCurve (GLUnurbs* nurb, GLint knotCount, GLfloat *knots, GLint stride, GLfloat *control, GLint order, GLenum type);
void gluNurbsProperty (GLUnurbs* nurb, GLenum property, GLfloat value);
void gluNurbsSurface (GLUnurbs* nurb, GLint sKnotCount, GLfloat* sKnots, GLint tKnotCount, GLfloat* tKnots, GLint sStride, GLint tStride, GLfloat* control, GLint sOrder, GLint tOrder, GLenum type);
void gluOrtho2D (GLdouble left, GLdouble right, GLdouble bottom, GLdouble top);
void gluPartialDisk (GLUquadric* quad, GLdouble inner, GLdouble outer, GLint slices, GLint loops, GLdouble start, GLdouble sweep);
void gluPerspective (GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar);
void gluPickMatrix (GLdouble x, GLdouble y, GLdouble delX, GLdouble delY, GLint *viewport);
GLint gluProject (GLdouble objX, GLdouble objY, GLdouble objZ, const GLdouble *model, const GLdouble *proj, const GLint *view, GLdouble* winX, GLdouble* winY, GLdouble* winZ);
void gluPwlCurve (GLUnurbs* nurb, GLint count, GLfloat* data, GLint stride, GLenum type);
void gluQuadricDrawStyle (GLUquadric* quad, GLenum draw);
void gluQuadricNormals (GLUquadric* quad, GLenum normal);
void gluQuadricOrientation (GLUquadric* quad, GLenum orientation);
void gluQuadricTexture (GLUquadric* quad, GLboolean texture);
GLint gluScaleImage (GLenum format, GLsizei wIn, GLsizei hIn, GLenum typeIn, const void *dataIn, GLsizei wOut, GLsizei hOut, GLenum typeOut, GLvoid* dataOut);
void gluSphere (GLUquadric* quad, GLdouble radius, GLint slices, GLint stacks);
void gluTessBeginContour (GLUtesselator* tess);
void gluTessBeginPolygon (GLUtesselator* tess, GLvoid* data);
void gluTessEndContour (GLUtesselator* tess);
___safe void gluTessEndPolygon (GLUtesselator* tess);
void gluTessNormal (GLUtesselator* tess, GLdouble valueX, GLdouble valueY, GLdouble valueZ);
void gluTessProperty (GLUtesselator* tess, GLenum which, GLdouble data);
void gluTessVertex (GLUtesselator* tess, GLdouble *location, GLvoid* data);
GLint gluUnProject (GLdouble winX, GLdouble winY, GLdouble winZ, const GLdouble *model, const GLdouble *proj, const GLint *view, GLdouble* objX, GLdouble* objY, GLdouble* objZ);
EOF
)
The GLU that ships with windows is still version 1.2 , so I moved all GLU 1.3 functions here .
(cond-expand
(msvc)
(cygwin)
(else
(foreign-parse #<<EOF
GLint gluBuild1DMipmapLevels (GLenum target, GLint internalFormat, GLsizei width, GLenum format, GLenum type, GLint level, GLint base, GLint max, const void *data);
GLint gluBuild2DMipmapLevels (GLenum target, GLint internalFormat, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint level, GLint base, GLint max, const void *data);
GLint gluBuild3DMipmapLevels (GLenum target, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, GLint level, GLint base, GLint max, const void *data);
GLint gluBuild3DMipmaps (GLenum target, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *data);
GLboolean gluCheckExtension (const char *extName, const char *extString);
void gluNurbsCallbackData (GLUnurbs* nurb, GLvoid* userData);
void gluNurbsCallbackDataEXT (GLUnurbs* nurb, GLvoid* userData);
GLint gluUnProject4 (GLdouble winX, GLdouble winY, GLdouble winZ, GLdouble clipW, const GLdouble *model, const GLdouble *proj, const GLint *view, GLdouble nearVal, GLdouble farVal, GLdouble* objX, GLdouble* objY, GLdouble* objZ, GLdouble* objW);
EOF
)))
(declare (hide nurbs-func nurbs_cb quadric-func quadric_cb tess-func tess_cb))
(define nurbs-func #f)
(define quadric-func #f)
(define tess-func #f)
; The callback passed to gluTess/gluQuadric/gluNurbsCallback must be __stdcall in windows. Defining the
external functions ( nurbs_cb , , tess_cb ) as _ _ stdcall is done below ; however , I could n't figure
; out how to get the Easy FFI parser to handle a __stdcall function pointer. With foreign-safe-lambda,
I can specify a calling convention with the function type , but the MSVC compiler does n't like where
; chicken puts the __stdcall in the function pointer casts. To get around this, I created the wrapper
; functions used below.
(cond-expand
(msvc
#>
void chicken_wrap_gluTessCallback(GLUtesselator* tess, GLenum which) { gluTessCallback(tess, which, tess_cb); }
void chicken_wrap_gluQuadricCallback(GLUquadric* quad, GLenum which) { gluQuadricCallback(quad, which, quadric_cb); }
void chicken_wrap_gluNurbsCallback(GLUnurbs* nurb, GLenum which) { gluNurbsCallback(nurb, which, nurbs_cb); }
<#
(foreign-parse #<<EOF
void chicken_wrap_gluNurbsCallback(GLUnurbs* nurb, GLenum which);
void chicken_wrap_gluQuadricCallback(GLUquadric* quad, GLenum which);
void chicken_wrap_gluNurbsCallback(GLUnurbs* nurb, GLenum which);
EOF
)
(define-external "__stdcall" (nurbs_cb) void (nurbs-func))
(define-external "__stdcall" (quadric_cb) void (quadric-func))
(define-external "__stdcall" (tess_cb) void (tess-func))
(define (gluNurbsCallback p i proc) (chicken_wrap_gluNurbsCallback p i) (set! nurbs-func proc))
(define (gluQuadricCallback p i proc) (chicken_wrap_gluQuadricCallback p i) (set! quadric-func proc))
(define (gluTessCallback p i proc) (chicken_wrap_gluTessCallback p i) (set! tess-func proc)))
(else
(foreign-parse #<<EOF
void gluTessCallback (GLUtesselator* tess, GLenum which, void (*CallBackFunc)());
void gluQuadricCallback (GLUquadric* quad, GLenum which, void (*CallBackFunc)());
void gluNurbsCallback (GLUnurbs* nurb, GLenum which, void (*CallBackFunc)());
EOF
)
(define-external (nurbs_cb) void (nurbs-func))
(define-external (quadric_cb) void (quadric-func))
(define-external (tess_cb) void (tess-func))
(define gluNurbsCallback (let ([old gluNurbsCallback]) (lambda (p i proc) (old p i (location nurbs_cb)) (set! nurbs-func proc))))
(define gluQuadricCallback (let ([old gluQuadricCallback]) (lambda (p i proc) (old p i (location quadric_cb)) (set! quadric-func proc))))
(define gluTessCallback (let ([old gluTessCallback]) (lambda (p i proc) (old p i (location tess_cb)) (set! tess-func proc))))))
| null | https://raw.githubusercontent.com/dharmatech/abstracting/9dc5d9f45a9de03c6ee379f1928ebb393dfafc52/support/chicken/glu/glu.scm | scheme | glu.scm
/* 1-byte signed */
/* 1-byte unsigned */
/* single precision float */
/* double precision float */
The callback passed to gluTess/gluQuadric/gluNurbsCallback must be __stdcall in windows. Defining the
however , I could n't figure
out how to get the Easy FFI parser to handle a __stdcall function pointer. With foreign-safe-lambda,
chicken puts the __stdcall in the function pointer casts. To get around this, I created the wrapper
functions used below.
}
}
}
|
(use easyffi)
(cond-expand
(msvc
#>
#define WIN32_LEAN_AND_MEAN 1
#include <windows.h>
#include <GL/glu.h>
<#)
(else
#>
#ifdef C_MACOSX
#include <OpenGL/glu.h>
#else
#include <GL/glu.h>
#endif
<#))
(foreign-parse #<<EOF
___declare(export_constants, yes)
/* ___declare(substitute, "^(GLU_|glu);glu:") */
/ * 2 - byte signed * /
/ * 4 - byte signed * /
/ * 2 - byte unsigned * /
/ * 4 - byte unsigned * /
/ * 4 - byte signed * /
/ * single precision float in [ 0,1 ] * /
/ * double precision float in [ 0,1 ] * /
/* Boolean */
#define GLU_FALSE 0
#define GLU_TRUE 1
/* StringName */
#define GLU_VERSION 100800
#define GLU_EXTENSIONS 100801
/* ErrorCode */
#define GLU_INVALID_ENUM 100900
#define GLU_INVALID_VALUE 100901
#define GLU_OUT_OF_MEMORY 100902
#define GLU_INVALID_OPERATION 100904
/* NurbsDisplay */
/* GLU_FILL */
#define GLU_OUTLINE_POLYGON 100240
#define GLU_OUTLINE_PATCH 100241
/* NurbsCallback */
#define GLU_NURBS_ERROR 100103
#define GLU_ERROR 100103
#define GLU_NURBS_BEGIN 100164
#define GLU_NURBS_BEGIN_EXT 100164
#define GLU_NURBS_VERTEX 100165
#define GLU_NURBS_VERTEX_EXT 100165
#define GLU_NURBS_NORMAL 100166
#define GLU_NURBS_NORMAL_EXT 100166
#define GLU_NURBS_COLOR 100167
#define GLU_NURBS_COLOR_EXT 100167
#define GLU_NURBS_TEXTURE_COORD 100168
#define GLU_NURBS_TEX_COORD_EXT 100168
#define GLU_NURBS_END 100169
#define GLU_NURBS_END_EXT 100169
#define GLU_NURBS_BEGIN_DATA 100170
#define GLU_NURBS_BEGIN_DATA_EXT 100170
#define GLU_NURBS_VERTEX_DATA 100171
#define GLU_NURBS_VERTEX_DATA_EXT 100171
#define GLU_NURBS_NORMAL_DATA 100172
#define GLU_NURBS_NORMAL_DATA_EXT 100172
#define GLU_NURBS_COLOR_DATA 100173
#define GLU_NURBS_COLOR_DATA_EXT 100173
#define GLU_NURBS_TEXTURE_COORD_DATA 100174
#define GLU_NURBS_TEX_COORD_DATA_EXT 100174
#define GLU_NURBS_END_DATA 100175
#define GLU_NURBS_END_DATA_EXT 100175
/* NurbsError */
#define GLU_NURBS_ERROR1 100251
#define GLU_NURBS_ERROR2 100252
#define GLU_NURBS_ERROR3 100253
#define GLU_NURBS_ERROR4 100254
#define GLU_NURBS_ERROR5 100255
#define GLU_NURBS_ERROR6 100256
#define GLU_NURBS_ERROR7 100257
#define GLU_NURBS_ERROR8 100258
#define GLU_NURBS_ERROR9 100259
#define GLU_NURBS_ERROR10 100260
#define GLU_NURBS_ERROR11 100261
#define GLU_NURBS_ERROR12 100262
#define GLU_NURBS_ERROR13 100263
#define GLU_NURBS_ERROR14 100264
#define GLU_NURBS_ERROR15 100265
#define GLU_NURBS_ERROR16 100266
#define GLU_NURBS_ERROR17 100267
#define GLU_NURBS_ERROR18 100268
#define GLU_NURBS_ERROR19 100269
#define GLU_NURBS_ERROR20 100270
#define GLU_NURBS_ERROR21 100271
#define GLU_NURBS_ERROR22 100272
#define GLU_NURBS_ERROR23 100273
#define GLU_NURBS_ERROR24 100274
#define GLU_NURBS_ERROR25 100275
#define GLU_NURBS_ERROR26 100276
#define GLU_NURBS_ERROR27 100277
#define GLU_NURBS_ERROR28 100278
#define GLU_NURBS_ERROR29 100279
#define GLU_NURBS_ERROR30 100280
#define GLU_NURBS_ERROR31 100281
#define GLU_NURBS_ERROR32 100282
#define GLU_NURBS_ERROR33 100283
#define GLU_NURBS_ERROR34 100284
#define GLU_NURBS_ERROR35 100285
#define GLU_NURBS_ERROR36 100286
#define GLU_NURBS_ERROR37 100287
/* NurbsProperty */
#define GLU_AUTO_LOAD_MATRIX 100200
#define GLU_CULLING 100201
#define GLU_SAMPLING_TOLERANCE 100203
#define GLU_DISPLAY_MODE 100204
#define GLU_PARAMETRIC_TOLERANCE 100202
#define GLU_SAMPLING_METHOD 100205
#define GLU_U_STEP 100206
#define GLU_V_STEP 100207
#define GLU_NURBS_MODE 100160
#define GLU_NURBS_MODE_EXT 100160
#define GLU_NURBS_TESSELLATOR 100161
#define GLU_NURBS_TESSELLATOR_EXT 100161
#define GLU_NURBS_RENDERER 100162
#define GLU_NURBS_RENDERER_EXT 100162
/* NurbsSampling */
#define GLU_OBJECT_PARAMETRIC_ERROR 100208
#define GLU_OBJECT_PARAMETRIC_ERROR_EXT 100208
#define GLU_OBJECT_PATH_LENGTH 100209
#define GLU_OBJECT_PATH_LENGTH_EXT 100209
#define GLU_PATH_LENGTH 100215
#define GLU_PARAMETRIC_ERROR 100216
#define GLU_DOMAIN_DISTANCE 100217
/* NurbsTrim */
#define GLU_MAP1_TRIM_2 100210
#define GLU_MAP1_TRIM_3 100211
/* QuadricDrawStyle */
#define GLU_POINT 100010
#define GLU_LINE 100011
#define GLU_FILL 100012
#define GLU_SILHOUETTE 100013
/* QuadricCallback */
/* GLU_ERROR */
/* QuadricNormal */
#define GLU_SMOOTH 100000
#define GLU_FLAT 100001
#define GLU_NONE 100002
/* QuadricOrientation */
#define GLU_OUTSIDE 100020
#define GLU_INSIDE 100021
/* TessCallback */
#define GLU_TESS_BEGIN 100100
#define GLU_BEGIN 100100
#define GLU_TESS_VERTEX 100101
#define GLU_VERTEX 100101
#define GLU_TESS_END 100102
#define GLU_END 100102
#define GLU_TESS_ERROR 100103
#define GLU_TESS_EDGE_FLAG 100104
#define GLU_EDGE_FLAG 100104
#define GLU_TESS_COMBINE 100105
#define GLU_TESS_BEGIN_DATA 100106
#define GLU_TESS_VERTEX_DATA 100107
#define GLU_TESS_END_DATA 100108
#define GLU_TESS_ERROR_DATA 100109
#define GLU_TESS_EDGE_FLAG_DATA 100110
#define GLU_TESS_COMBINE_DATA 100111
/* TessContour */
#define GLU_CW 100120
#define GLU_CCW 100121
#define GLU_INTERIOR 100122
#define GLU_EXTERIOR 100123
#define GLU_UNKNOWN 100124
/* TessProperty */
#define GLU_TESS_WINDING_RULE 100140
#define GLU_TESS_BOUNDARY_ONLY 100141
#define GLU_TESS_TOLERANCE 100142
/* TessError */
#define GLU_TESS_ERROR1 100151
#define GLU_TESS_ERROR2 100152
#define GLU_TESS_ERROR3 100153
#define GLU_TESS_ERROR4 100154
#define GLU_TESS_ERROR5 100155
#define GLU_TESS_ERROR6 100156
#define GLU_TESS_ERROR7 100157
#define GLU_TESS_ERROR8 100158
#define GLU_TESS_MISSING_BEGIN_POLYGON 100151
#define GLU_TESS_MISSING_BEGIN_CONTOUR 100152
#define GLU_TESS_MISSING_END_POLYGON 100153
#define GLU_TESS_MISSING_END_CONTOUR 100154
#define GLU_TESS_COORD_TOO_LARGE 100155
#define GLU_TESS_NEED_COMBINE_CALLBACK 100156
/* TessWinding */
#define GLU_TESS_WINDING_ODD 100130
#define GLU_TESS_WINDING_NONZERO 100131
#define GLU_TESS_WINDING_POSITIVE 100132
#define GLU_TESS_WINDING_NEGATIVE 100133
#define GLU_TESS_WINDING_ABS_GEQ_TWO 100134
/*************************************************************/
#define GLU_TESS_MAX_COORD 1.0e+150
/* Internal convenience typedefs */
EOF
)
The GLU that ships with windows is still version 1.2 , so I moved all GLU 1.3 functions here .
(cond-expand
(msvc)
(cygwin)
(else
(foreign-parse #<<EOF
EOF
)))
(declare (hide nurbs-func nurbs_cb quadric-func quadric_cb tess-func tess_cb))
(define nurbs-func #f)
(define quadric-func #f)
(define tess-func #f)
I can specify a calling convention with the function type , but the MSVC compiler does n't like where
(cond-expand
(msvc
#>
<#
(foreign-parse #<<EOF
EOF
)
(define-external "__stdcall" (nurbs_cb) void (nurbs-func))
(define-external "__stdcall" (quadric_cb) void (quadric-func))
(define-external "__stdcall" (tess_cb) void (tess-func))
(define (gluNurbsCallback p i proc) (chicken_wrap_gluNurbsCallback p i) (set! nurbs-func proc))
(define (gluQuadricCallback p i proc) (chicken_wrap_gluQuadricCallback p i) (set! quadric-func proc))
(define (gluTessCallback p i proc) (chicken_wrap_gluTessCallback p i) (set! tess-func proc)))
(else
(foreign-parse #<<EOF
EOF
)
(define-external (nurbs_cb) void (nurbs-func))
(define-external (quadric_cb) void (quadric-func))
(define-external (tess_cb) void (tess-func))
(define gluNurbsCallback (let ([old gluNurbsCallback]) (lambda (p i proc) (old p i (location nurbs_cb)) (set! nurbs-func proc))))
(define gluQuadricCallback (let ([old gluQuadricCallback]) (lambda (p i proc) (old p i (location quadric_cb)) (set! quadric-func proc))))
(define gluTessCallback (let ([old gluTessCallback]) (lambda (p i proc) (old p i (location tess_cb)) (set! tess-func proc))))))
|
06e63bb5ad1df4f49e0e717ef7161a778ab28c995365600f572493bd0d1f2c8e | nikita-volkov/rebase | Mutable.hs | module Rebase.Data.Vector.Storable.Mutable
(
module Data.Vector.Storable.Mutable
)
where
import Data.Vector.Storable.Mutable
| null | https://raw.githubusercontent.com/nikita-volkov/rebase/7c77a0443e80bdffd4488a4239628177cac0761b/library/Rebase/Data/Vector/Storable/Mutable.hs | haskell | module Rebase.Data.Vector.Storable.Mutable
(
module Data.Vector.Storable.Mutable
)
where
import Data.Vector.Storable.Mutable
| |
a0ca0220a29db8adcf7b393bc88296bb7412195965fc341e66ead77c9fe65c80 | wireless-net/erlang-nommu | wxFontPickerCtrl.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2008 - 2013 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at /.
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%% This file is generated DO NOT EDIT
%% @doc See external documentation: <a href="">wxFontPickerCtrl</a>.
%% <p>This class is derived (and can use functions) from:
%% <br />{@link wxPickerBase}
%% <br />{@link wxControl}
%% <br />{@link wxWindow}
%% <br />{@link wxEvtHandler}
%% </p>
%% @type wxFontPickerCtrl(). An object reference, The representation is internal
%% and can be changed without notice. It can't be used for comparsion
%% stored on disc or distributed for use on other nodes.
-module(wxFontPickerCtrl).
-include("wxe.hrl").
-export([create/3,create/4,destroy/1,getMaxPointSize/1,getSelectedFont/1,new/0,
new/2,new/3,setMaxPointSize/2,setSelectedFont/2]).
%% inherited exports
-export([cacheBestSize/2,captureMouse/1,center/1,center/2,centerOnParent/1,
centerOnParent/2,centre/1,centre/2,centreOnParent/1,centreOnParent/2,
clearBackground/1,clientToScreen/2,clientToScreen/3,close/1,close/2,
connect/2,connect/3,convertDialogToPixels/2,convertPixelsToDialog/2,
destroyChildren/1,disable/1,disconnect/1,disconnect/2,disconnect/3,
enable/1,enable/2,findWindow/2,fit/1,fitInside/1,freeze/1,getAcceleratorTable/1,
getBackgroundColour/1,getBackgroundStyle/1,getBestSize/1,getCaret/1,
getCharHeight/1,getCharWidth/1,getChildren/1,getClientSize/1,getContainingSizer/1,
getCursor/1,getDropTarget/1,getEventHandler/1,getExtraStyle/1,getFont/1,
getForegroundColour/1,getGrandParent/1,getHandle/1,getHelpText/1,
getId/1,getInternalMargin/1,getLabel/1,getMaxSize/1,getMinSize/1,getName/1,
getParent/1,getPickerCtrlProportion/1,getPosition/1,getRect/1,getScreenPosition/1,
getScreenRect/1,getScrollPos/2,getScrollRange/2,getScrollThumb/2,
getSize/1,getSizer/1,getTextCtrl/1,getTextCtrlProportion/1,getTextExtent/2,
getTextExtent/3,getToolTip/1,getUpdateRegion/1,getVirtualSize/1,getWindowStyleFlag/1,
getWindowVariant/1,hasCapture/1,hasScrollbar/2,hasTextCtrl/1,hasTransparentBackground/1,
hide/1,inheritAttributes/1,initDialog/1,invalidateBestSize/1,isEnabled/1,
isExposed/2,isExposed/3,isExposed/5,isPickerCtrlGrowable/1,isRetained/1,
isShown/1,isTextCtrlGrowable/1,isTopLevel/1,layout/1,lineDown/1,lineUp/1,
lower/1,makeModal/1,makeModal/2,move/2,move/3,move/4,moveAfterInTabOrder/2,
moveBeforeInTabOrder/2,navigate/1,navigate/2,pageDown/1,pageUp/1,parent_class/1,
popEventHandler/1,popEventHandler/2,popupMenu/2,popupMenu/3,popupMenu/4,
raise/1,refresh/1,refresh/2,refreshRect/2,refreshRect/3,releaseMouse/1,
removeChild/2,reparent/2,screenToClient/1,screenToClient/2,scrollLines/2,
scrollPages/2,scrollWindow/3,scrollWindow/4,setAcceleratorTable/2,
setAutoLayout/2,setBackgroundColour/2,setBackgroundStyle/2,setCaret/2,
setClientSize/2,setClientSize/3,setContainingSizer/2,setCursor/2,
setDropTarget/2,setExtraStyle/2,setFocus/1,setFocusFromKbd/1,setFont/2,
setForegroundColour/2,setHelpText/2,setId/2,setInternalMargin/2,setLabel/2,
setMaxSize/2,setMinSize/2,setName/2,setOwnBackgroundColour/2,setOwnFont/2,
setOwnForegroundColour/2,setPalette/2,setPickerCtrlGrowable/1,setPickerCtrlGrowable/2,
setPickerCtrlProportion/2,setScrollPos/3,setScrollPos/4,setScrollbar/5,
setScrollbar/6,setSize/2,setSize/3,setSize/5,setSize/6,setSizeHints/2,
setSizeHints/3,setSizeHints/4,setSizer/2,setSizer/3,setSizerAndFit/2,
setSizerAndFit/3,setTextCtrlGrowable/1,setTextCtrlGrowable/2,setTextCtrlProportion/2,
setThemeEnabled/2,setToolTip/2,setVirtualSize/2,setVirtualSize/3,
setVirtualSizeHints/2,setVirtualSizeHints/3,setVirtualSizeHints/4,
setWindowStyle/2,setWindowStyleFlag/2,setWindowVariant/2,shouldInheritColours/1,
show/1,show/2,thaw/1,transferDataFromWindow/1,transferDataToWindow/1,
update/1,updateWindowUI/1,updateWindowUI/2,validate/1,warpPointer/3]).
-export_type([wxFontPickerCtrl/0]).
%% @hidden
parent_class(wxPickerBase) -> true;
parent_class(wxControl) -> true;
parent_class(wxWindow) -> true;
parent_class(wxEvtHandler) -> true;
parent_class(_Class) -> erlang:error({badtype, ?MODULE}).
-type wxFontPickerCtrl() :: wx:wx_object().
%% @doc See <a href="#wxfontpickerctrlwxfontpickerctrl">external documentation</a>.
-spec new() -> wxFontPickerCtrl().
new() ->
wxe_util:construct(?wxFontPickerCtrl_new_0,
<<>>).
@equiv new(Parent , Id , [ ] )
-spec new(Parent, Id) -> wxFontPickerCtrl() when
Parent::wxWindow:wxWindow(), Id::integer().
new(Parent,Id)
when is_record(Parent, wx_ref),is_integer(Id) ->
new(Parent,Id, []).
%% @doc See <a href="#wxfontpickerctrlwxfontpickerctrl">external documentation</a>.
-spec new(Parent, Id, [Option]) -> wxFontPickerCtrl() when
Parent::wxWindow:wxWindow(), Id::integer(),
Option :: {initial, wxFont:wxFont()}
| {pos, {X::integer(), Y::integer()}}
| {size, {W::integer(), H::integer()}}
| {style, integer()}
| {validator, wx:wx_object()}.
new(#wx_ref{type=ParentT,ref=ParentRef},Id, Options)
when is_integer(Id),is_list(Options) ->
?CLASS(ParentT,wxWindow),
MOpts = fun({initial, #wx_ref{type=InitialT,ref=InitialRef}}, Acc) -> ?CLASS(InitialT,wxFont),[<<1:32/?UI,InitialRef:32/?UI>>|Acc];
({pos, {PosX,PosY}}, Acc) -> [<<2:32/?UI,PosX:32/?UI,PosY:32/?UI,0:32>>|Acc];
({size, {SizeW,SizeH}}, Acc) -> [<<3:32/?UI,SizeW:32/?UI,SizeH:32/?UI,0:32>>|Acc];
({style, Style}, Acc) -> [<<4:32/?UI,Style:32/?UI>>|Acc];
({validator, #wx_ref{type=ValidatorT,ref=ValidatorRef}}, Acc) -> ?CLASS(ValidatorT,wx),[<<5:32/?UI,ValidatorRef:32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:construct(?wxFontPickerCtrl_new_3,
<<ParentRef:32/?UI,Id:32/?UI, BinOpt/binary>>).
%% @equiv create(This,Parent,Id, [])
-spec create(This, Parent, Id) -> boolean() when
This::wxFontPickerCtrl(), Parent::wxWindow:wxWindow(), Id::integer().
create(This,Parent,Id)
when is_record(This, wx_ref),is_record(Parent, wx_ref),is_integer(Id) ->
create(This,Parent,Id, []).
%% @doc See <a href="#wxfontpickerctrlcreate">external documentation</a>.
-spec create(This, Parent, Id, [Option]) -> boolean() when
This::wxFontPickerCtrl(), Parent::wxWindow:wxWindow(), Id::integer(),
Option :: {initial, wxFont:wxFont()}
| {pos, {X::integer(), Y::integer()}}
| {size, {W::integer(), H::integer()}}
| {style, integer()}
| {validator, wx:wx_object()}.
create(#wx_ref{type=ThisT,ref=ThisRef},#wx_ref{type=ParentT,ref=ParentRef},Id, Options)
when is_integer(Id),is_list(Options) ->
?CLASS(ThisT,wxFontPickerCtrl),
?CLASS(ParentT,wxWindow),
MOpts = fun({initial, #wx_ref{type=InitialT,ref=InitialRef}}, Acc) -> ?CLASS(InitialT,wxFont),[<<1:32/?UI,InitialRef:32/?UI>>|Acc];
({pos, {PosX,PosY}}, Acc) -> [<<2:32/?UI,PosX:32/?UI,PosY:32/?UI,0:32>>|Acc];
({size, {SizeW,SizeH}}, Acc) -> [<<3:32/?UI,SizeW:32/?UI,SizeH:32/?UI,0:32>>|Acc];
({style, Style}, Acc) -> [<<4:32/?UI,Style:32/?UI>>|Acc];
({validator, #wx_ref{type=ValidatorT,ref=ValidatorRef}}, Acc) -> ?CLASS(ValidatorT,wx),[<<5:32/?UI,ValidatorRef:32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxFontPickerCtrl_Create,
<<ThisRef:32/?UI,ParentRef:32/?UI,Id:32/?UI, 0:32,BinOpt/binary>>).
%% @doc See <a href="#wxfontpickerctrlgetselectedfont">external documentation</a>.
-spec getSelectedFont(This) -> wxFont:wxFont() when
This::wxFontPickerCtrl().
getSelectedFont(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxFontPickerCtrl),
wxe_util:call(?wxFontPickerCtrl_GetSelectedFont,
<<ThisRef:32/?UI>>).
%% @doc See <a href="#wxfontpickerctrlsetselectedfont">external documentation</a>.
-spec setSelectedFont(This, F) -> ok when
This::wxFontPickerCtrl(), F::wxFont:wxFont().
setSelectedFont(#wx_ref{type=ThisT,ref=ThisRef},#wx_ref{type=FT,ref=FRef}) ->
?CLASS(ThisT,wxFontPickerCtrl),
?CLASS(FT,wxFont),
wxe_util:cast(?wxFontPickerCtrl_SetSelectedFont,
<<ThisRef:32/?UI,FRef:32/?UI>>).
%% @doc See <a href="#wxfontpickerctrlgetmaxpointsize">external documentation</a>.
-spec getMaxPointSize(This) -> integer() when
This::wxFontPickerCtrl().
getMaxPointSize(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxFontPickerCtrl),
wxe_util:call(?wxFontPickerCtrl_GetMaxPointSize,
<<ThisRef:32/?UI>>).
%% @doc See <a href="#wxfontpickerctrlsetmaxpointsize">external documentation</a>.
-spec setMaxPointSize(This, Max) -> ok when
This::wxFontPickerCtrl(), Max::integer().
setMaxPointSize(#wx_ref{type=ThisT,ref=ThisRef},Max)
when is_integer(Max) ->
?CLASS(ThisT,wxFontPickerCtrl),
wxe_util:cast(?wxFontPickerCtrl_SetMaxPointSize,
<<ThisRef:32/?UI,Max:32/?UI>>).
%% @doc Destroys this object, do not use object again
-spec destroy(This::wxFontPickerCtrl()) -> ok.
destroy(Obj=#wx_ref{type=Type}) ->
?CLASS(Type,wxFontPickerCtrl),
wxe_util:destroy(?DESTROY_OBJECT,Obj),
ok.
From wxPickerBase
%% @hidden
isPickerCtrlGrowable(This) -> wxPickerBase:isPickerCtrlGrowable(This).
%% @hidden
setTextCtrlGrowable(This, Options) -> wxPickerBase:setTextCtrlGrowable(This, Options).
%% @hidden
setTextCtrlGrowable(This) -> wxPickerBase:setTextCtrlGrowable(This).
%% @hidden
setPickerCtrlGrowable(This, Options) -> wxPickerBase:setPickerCtrlGrowable(This, Options).
%% @hidden
setPickerCtrlGrowable(This) -> wxPickerBase:setPickerCtrlGrowable(This).
%% @hidden
isTextCtrlGrowable(This) -> wxPickerBase:isTextCtrlGrowable(This).
%% @hidden
getTextCtrl(This) -> wxPickerBase:getTextCtrl(This).
%% @hidden
hasTextCtrl(This) -> wxPickerBase:hasTextCtrl(This).
%% @hidden
getPickerCtrlProportion(This) -> wxPickerBase:getPickerCtrlProportion(This).
%% @hidden
getTextCtrlProportion(This) -> wxPickerBase:getTextCtrlProportion(This).
%% @hidden
setPickerCtrlProportion(This,Prop) -> wxPickerBase:setPickerCtrlProportion(This,Prop).
%% @hidden
setTextCtrlProportion(This,Prop) -> wxPickerBase:setTextCtrlProportion(This,Prop).
%% @hidden
getInternalMargin(This) -> wxPickerBase:getInternalMargin(This).
%% @hidden
setInternalMargin(This,Newmargin) -> wxPickerBase:setInternalMargin(This,Newmargin).
%% From wxControl
%% @hidden
setLabel(This,Label) -> wxControl:setLabel(This,Label).
%% @hidden
getLabel(This) -> wxControl:getLabel(This).
%% From wxWindow
%% @hidden
warpPointer(This,X,Y) -> wxWindow:warpPointer(This,X,Y).
%% @hidden
validate(This) -> wxWindow:validate(This).
%% @hidden
updateWindowUI(This, Options) -> wxWindow:updateWindowUI(This, Options).
%% @hidden
updateWindowUI(This) -> wxWindow:updateWindowUI(This).
%% @hidden
update(This) -> wxWindow:update(This).
%% @hidden
transferDataToWindow(This) -> wxWindow:transferDataToWindow(This).
%% @hidden
transferDataFromWindow(This) -> wxWindow:transferDataFromWindow(This).
%% @hidden
thaw(This) -> wxWindow:thaw(This).
%% @hidden
show(This, Options) -> wxWindow:show(This, Options).
%% @hidden
show(This) -> wxWindow:show(This).
%% @hidden
shouldInheritColours(This) -> wxWindow:shouldInheritColours(This).
%% @hidden
setWindowVariant(This,Variant) -> wxWindow:setWindowVariant(This,Variant).
%% @hidden
setWindowStyleFlag(This,Style) -> wxWindow:setWindowStyleFlag(This,Style).
%% @hidden
setWindowStyle(This,Style) -> wxWindow:setWindowStyle(This,Style).
%% @hidden
setVirtualSizeHints(This,MinW,MinH, Options) -> wxWindow:setVirtualSizeHints(This,MinW,MinH, Options).
%% @hidden
setVirtualSizeHints(This,MinW,MinH) -> wxWindow:setVirtualSizeHints(This,MinW,MinH).
%% @hidden
setVirtualSizeHints(This,MinSize) -> wxWindow:setVirtualSizeHints(This,MinSize).
%% @hidden
setVirtualSize(This,X,Y) -> wxWindow:setVirtualSize(This,X,Y).
%% @hidden
setVirtualSize(This,Size) -> wxWindow:setVirtualSize(This,Size).
%% @hidden
setToolTip(This,Tip) -> wxWindow:setToolTip(This,Tip).
%% @hidden
setThemeEnabled(This,EnableTheme) -> wxWindow:setThemeEnabled(This,EnableTheme).
%% @hidden
setSizerAndFit(This,Sizer, Options) -> wxWindow:setSizerAndFit(This,Sizer, Options).
%% @hidden
setSizerAndFit(This,Sizer) -> wxWindow:setSizerAndFit(This,Sizer).
%% @hidden
setSizer(This,Sizer, Options) -> wxWindow:setSizer(This,Sizer, Options).
%% @hidden
setSizer(This,Sizer) -> wxWindow:setSizer(This,Sizer).
%% @hidden
setSizeHints(This,MinW,MinH, Options) -> wxWindow:setSizeHints(This,MinW,MinH, Options).
%% @hidden
setSizeHints(This,MinW,MinH) -> wxWindow:setSizeHints(This,MinW,MinH).
%% @hidden
setSizeHints(This,MinSize) -> wxWindow:setSizeHints(This,MinSize).
%% @hidden
setSize(This,X,Y,Width,Height, Options) -> wxWindow:setSize(This,X,Y,Width,Height, Options).
%% @hidden
setSize(This,X,Y,Width,Height) -> wxWindow:setSize(This,X,Y,Width,Height).
%% @hidden
setSize(This,Width,Height) -> wxWindow:setSize(This,Width,Height).
%% @hidden
setSize(This,Rect) -> wxWindow:setSize(This,Rect).
%% @hidden
setScrollPos(This,Orient,Pos, Options) -> wxWindow:setScrollPos(This,Orient,Pos, Options).
%% @hidden
setScrollPos(This,Orient,Pos) -> wxWindow:setScrollPos(This,Orient,Pos).
%% @hidden
setScrollbar(This,Orient,Pos,ThumbVisible,Range, Options) -> wxWindow:setScrollbar(This,Orient,Pos,ThumbVisible,Range, Options).
%% @hidden
setScrollbar(This,Orient,Pos,ThumbVisible,Range) -> wxWindow:setScrollbar(This,Orient,Pos,ThumbVisible,Range).
%% @hidden
setPalette(This,Pal) -> wxWindow:setPalette(This,Pal).
%% @hidden
setName(This,Name) -> wxWindow:setName(This,Name).
%% @hidden
setId(This,Winid) -> wxWindow:setId(This,Winid).
%% @hidden
setHelpText(This,Text) -> wxWindow:setHelpText(This,Text).
%% @hidden
setForegroundColour(This,Colour) -> wxWindow:setForegroundColour(This,Colour).
%% @hidden
setFont(This,Font) -> wxWindow:setFont(This,Font).
%% @hidden
setFocusFromKbd(This) -> wxWindow:setFocusFromKbd(This).
%% @hidden
setFocus(This) -> wxWindow:setFocus(This).
%% @hidden
setExtraStyle(This,ExStyle) -> wxWindow:setExtraStyle(This,ExStyle).
%% @hidden
setDropTarget(This,DropTarget) -> wxWindow:setDropTarget(This,DropTarget).
%% @hidden
setOwnForegroundColour(This,Colour) -> wxWindow:setOwnForegroundColour(This,Colour).
%% @hidden
setOwnFont(This,Font) -> wxWindow:setOwnFont(This,Font).
%% @hidden
setOwnBackgroundColour(This,Colour) -> wxWindow:setOwnBackgroundColour(This,Colour).
%% @hidden
setMinSize(This,MinSize) -> wxWindow:setMinSize(This,MinSize).
%% @hidden
setMaxSize(This,MaxSize) -> wxWindow:setMaxSize(This,MaxSize).
%% @hidden
setCursor(This,Cursor) -> wxWindow:setCursor(This,Cursor).
%% @hidden
setContainingSizer(This,Sizer) -> wxWindow:setContainingSizer(This,Sizer).
%% @hidden
setClientSize(This,Width,Height) -> wxWindow:setClientSize(This,Width,Height).
%% @hidden
setClientSize(This,Size) -> wxWindow:setClientSize(This,Size).
%% @hidden
setCaret(This,Caret) -> wxWindow:setCaret(This,Caret).
%% @hidden
setBackgroundStyle(This,Style) -> wxWindow:setBackgroundStyle(This,Style).
%% @hidden
setBackgroundColour(This,Colour) -> wxWindow:setBackgroundColour(This,Colour).
%% @hidden
setAutoLayout(This,AutoLayout) -> wxWindow:setAutoLayout(This,AutoLayout).
%% @hidden
setAcceleratorTable(This,Accel) -> wxWindow:setAcceleratorTable(This,Accel).
%% @hidden
scrollWindow(This,Dx,Dy, Options) -> wxWindow:scrollWindow(This,Dx,Dy, Options).
%% @hidden
scrollWindow(This,Dx,Dy) -> wxWindow:scrollWindow(This,Dx,Dy).
%% @hidden
scrollPages(This,Pages) -> wxWindow:scrollPages(This,Pages).
%% @hidden
scrollLines(This,Lines) -> wxWindow:scrollLines(This,Lines).
%% @hidden
screenToClient(This,Pt) -> wxWindow:screenToClient(This,Pt).
%% @hidden
screenToClient(This) -> wxWindow:screenToClient(This).
%% @hidden
reparent(This,NewParent) -> wxWindow:reparent(This,NewParent).
%% @hidden
removeChild(This,Child) -> wxWindow:removeChild(This,Child).
%% @hidden
releaseMouse(This) -> wxWindow:releaseMouse(This).
%% @hidden
refreshRect(This,Rect, Options) -> wxWindow:refreshRect(This,Rect, Options).
%% @hidden
refreshRect(This,Rect) -> wxWindow:refreshRect(This,Rect).
%% @hidden
refresh(This, Options) -> wxWindow:refresh(This, Options).
%% @hidden
refresh(This) -> wxWindow:refresh(This).
%% @hidden
raise(This) -> wxWindow:raise(This).
%% @hidden
popupMenu(This,Menu,X,Y) -> wxWindow:popupMenu(This,Menu,X,Y).
%% @hidden
popupMenu(This,Menu, Options) -> wxWindow:popupMenu(This,Menu, Options).
%% @hidden
popupMenu(This,Menu) -> wxWindow:popupMenu(This,Menu).
%% @hidden
popEventHandler(This, Options) -> wxWindow:popEventHandler(This, Options).
%% @hidden
popEventHandler(This) -> wxWindow:popEventHandler(This).
%% @hidden
pageUp(This) -> wxWindow:pageUp(This).
%% @hidden
pageDown(This) -> wxWindow:pageDown(This).
%% @hidden
navigate(This, Options) -> wxWindow:navigate(This, Options).
%% @hidden
navigate(This) -> wxWindow:navigate(This).
%% @hidden
moveBeforeInTabOrder(This,Win) -> wxWindow:moveBeforeInTabOrder(This,Win).
%% @hidden
moveAfterInTabOrder(This,Win) -> wxWindow:moveAfterInTabOrder(This,Win).
%% @hidden
move(This,X,Y, Options) -> wxWindow:move(This,X,Y, Options).
%% @hidden
move(This,X,Y) -> wxWindow:move(This,X,Y).
%% @hidden
move(This,Pt) -> wxWindow:move(This,Pt).
%% @hidden
makeModal(This, Options) -> wxWindow:makeModal(This, Options).
%% @hidden
makeModal(This) -> wxWindow:makeModal(This).
%% @hidden
lower(This) -> wxWindow:lower(This).
%% @hidden
lineUp(This) -> wxWindow:lineUp(This).
%% @hidden
lineDown(This) -> wxWindow:lineDown(This).
%% @hidden
layout(This) -> wxWindow:layout(This).
%% @hidden
isTopLevel(This) -> wxWindow:isTopLevel(This).
%% @hidden
isShown(This) -> wxWindow:isShown(This).
%% @hidden
isRetained(This) -> wxWindow:isRetained(This).
%% @hidden
isExposed(This,X,Y,W,H) -> wxWindow:isExposed(This,X,Y,W,H).
%% @hidden
isExposed(This,X,Y) -> wxWindow:isExposed(This,X,Y).
%% @hidden
isExposed(This,Pt) -> wxWindow:isExposed(This,Pt).
%% @hidden
isEnabled(This) -> wxWindow:isEnabled(This).
%% @hidden
invalidateBestSize(This) -> wxWindow:invalidateBestSize(This).
%% @hidden
initDialog(This) -> wxWindow:initDialog(This).
%% @hidden
inheritAttributes(This) -> wxWindow:inheritAttributes(This).
%% @hidden
hide(This) -> wxWindow:hide(This).
%% @hidden
hasTransparentBackground(This) -> wxWindow:hasTransparentBackground(This).
%% @hidden
hasScrollbar(This,Orient) -> wxWindow:hasScrollbar(This,Orient).
%% @hidden
hasCapture(This) -> wxWindow:hasCapture(This).
%% @hidden
getWindowVariant(This) -> wxWindow:getWindowVariant(This).
%% @hidden
getWindowStyleFlag(This) -> wxWindow:getWindowStyleFlag(This).
%% @hidden
getVirtualSize(This) -> wxWindow:getVirtualSize(This).
%% @hidden
getUpdateRegion(This) -> wxWindow:getUpdateRegion(This).
%% @hidden
getToolTip(This) -> wxWindow:getToolTip(This).
%% @hidden
getTextExtent(This,String, Options) -> wxWindow:getTextExtent(This,String, Options).
%% @hidden
getTextExtent(This,String) -> wxWindow:getTextExtent(This,String).
%% @hidden
getSizer(This) -> wxWindow:getSizer(This).
%% @hidden
getSize(This) -> wxWindow:getSize(This).
%% @hidden
getScrollThumb(This,Orient) -> wxWindow:getScrollThumb(This,Orient).
%% @hidden
getScrollRange(This,Orient) -> wxWindow:getScrollRange(This,Orient).
%% @hidden
getScrollPos(This,Orient) -> wxWindow:getScrollPos(This,Orient).
%% @hidden
getScreenRect(This) -> wxWindow:getScreenRect(This).
%% @hidden
getScreenPosition(This) -> wxWindow:getScreenPosition(This).
%% @hidden
getRect(This) -> wxWindow:getRect(This).
%% @hidden
getPosition(This) -> wxWindow:getPosition(This).
%% @hidden
getParent(This) -> wxWindow:getParent(This).
%% @hidden
getName(This) -> wxWindow:getName(This).
%% @hidden
getMinSize(This) -> wxWindow:getMinSize(This).
%% @hidden
getMaxSize(This) -> wxWindow:getMaxSize(This).
%% @hidden
getId(This) -> wxWindow:getId(This).
%% @hidden
getHelpText(This) -> wxWindow:getHelpText(This).
%% @hidden
getHandle(This) -> wxWindow:getHandle(This).
%% @hidden
getGrandParent(This) -> wxWindow:getGrandParent(This).
%% @hidden
getForegroundColour(This) -> wxWindow:getForegroundColour(This).
%% @hidden
getFont(This) -> wxWindow:getFont(This).
%% @hidden
getExtraStyle(This) -> wxWindow:getExtraStyle(This).
%% @hidden
getEventHandler(This) -> wxWindow:getEventHandler(This).
%% @hidden
getDropTarget(This) -> wxWindow:getDropTarget(This).
%% @hidden
getCursor(This) -> wxWindow:getCursor(This).
%% @hidden
getContainingSizer(This) -> wxWindow:getContainingSizer(This).
%% @hidden
getClientSize(This) -> wxWindow:getClientSize(This).
%% @hidden
getChildren(This) -> wxWindow:getChildren(This).
%% @hidden
getCharWidth(This) -> wxWindow:getCharWidth(This).
%% @hidden
getCharHeight(This) -> wxWindow:getCharHeight(This).
%% @hidden
getCaret(This) -> wxWindow:getCaret(This).
%% @hidden
getBestSize(This) -> wxWindow:getBestSize(This).
%% @hidden
getBackgroundStyle(This) -> wxWindow:getBackgroundStyle(This).
%% @hidden
getBackgroundColour(This) -> wxWindow:getBackgroundColour(This).
%% @hidden
getAcceleratorTable(This) -> wxWindow:getAcceleratorTable(This).
%% @hidden
freeze(This) -> wxWindow:freeze(This).
%% @hidden
fitInside(This) -> wxWindow:fitInside(This).
%% @hidden
fit(This) -> wxWindow:fit(This).
%% @hidden
findWindow(This,Winid) -> wxWindow:findWindow(This,Winid).
%% @hidden
enable(This, Options) -> wxWindow:enable(This, Options).
%% @hidden
enable(This) -> wxWindow:enable(This).
%% @hidden
disable(This) -> wxWindow:disable(This).
%% @hidden
destroyChildren(This) -> wxWindow:destroyChildren(This).
%% @hidden
convertPixelsToDialog(This,Sz) -> wxWindow:convertPixelsToDialog(This,Sz).
%% @hidden
convertDialogToPixels(This,Sz) -> wxWindow:convertDialogToPixels(This,Sz).
%% @hidden
close(This, Options) -> wxWindow:close(This, Options).
%% @hidden
close(This) -> wxWindow:close(This).
%% @hidden
clientToScreen(This,X,Y) -> wxWindow:clientToScreen(This,X,Y).
%% @hidden
clientToScreen(This,Pt) -> wxWindow:clientToScreen(This,Pt).
%% @hidden
clearBackground(This) -> wxWindow:clearBackground(This).
%% @hidden
centreOnParent(This, Options) -> wxWindow:centreOnParent(This, Options).
%% @hidden
centreOnParent(This) -> wxWindow:centreOnParent(This).
%% @hidden
centre(This, Options) -> wxWindow:centre(This, Options).
%% @hidden
centre(This) -> wxWindow:centre(This).
%% @hidden
centerOnParent(This, Options) -> wxWindow:centerOnParent(This, Options).
%% @hidden
centerOnParent(This) -> wxWindow:centerOnParent(This).
%% @hidden
center(This, Options) -> wxWindow:center(This, Options).
%% @hidden
center(This) -> wxWindow:center(This).
%% @hidden
captureMouse(This) -> wxWindow:captureMouse(This).
%% @hidden
cacheBestSize(This,Size) -> wxWindow:cacheBestSize(This,Size).
%% From wxEvtHandler
%% @hidden
disconnect(This,EventType, Options) -> wxEvtHandler:disconnect(This,EventType, Options).
%% @hidden
disconnect(This,EventType) -> wxEvtHandler:disconnect(This,EventType).
%% @hidden
disconnect(This) -> wxEvtHandler:disconnect(This).
%% @hidden
connect(This,EventType, Options) -> wxEvtHandler:connect(This,EventType, Options).
%% @hidden
connect(This,EventType) -> wxEvtHandler:connect(This,EventType).
| null | https://raw.githubusercontent.com/wireless-net/erlang-nommu/79f32f81418e022d8ad8e0e447deaea407289926/lib/wx/src/gen/wxFontPickerCtrl.erl | erlang |
%CopyrightBegin%
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved online at /.
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
%CopyrightEnd%
This file is generated DO NOT EDIT
@doc See external documentation: <a href="">wxFontPickerCtrl</a>.
<p>This class is derived (and can use functions) from:
<br />{@link wxPickerBase}
<br />{@link wxControl}
<br />{@link wxWindow}
<br />{@link wxEvtHandler}
</p>
@type wxFontPickerCtrl(). An object reference, The representation is internal
and can be changed without notice. It can't be used for comparsion
stored on disc or distributed for use on other nodes.
inherited exports
@hidden
@doc See <a href="#wxfontpickerctrlwxfontpickerctrl">external documentation</a>.
@doc See <a href="#wxfontpickerctrlwxfontpickerctrl">external documentation</a>.
@equiv create(This,Parent,Id, [])
@doc See <a href="#wxfontpickerctrlcreate">external documentation</a>.
@doc See <a href="#wxfontpickerctrlgetselectedfont">external documentation</a>.
@doc See <a href="#wxfontpickerctrlsetselectedfont">external documentation</a>.
@doc See <a href="#wxfontpickerctrlgetmaxpointsize">external documentation</a>.
@doc See <a href="#wxfontpickerctrlsetmaxpointsize">external documentation</a>.
@doc Destroys this object, do not use object again
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
From wxControl
@hidden
@hidden
From wxWindow
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
From wxEvtHandler
@hidden
@hidden
@hidden
@hidden
@hidden | Copyright Ericsson AB 2008 - 2013 . All Rights Reserved .
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
-module(wxFontPickerCtrl).
-include("wxe.hrl").
-export([create/3,create/4,destroy/1,getMaxPointSize/1,getSelectedFont/1,new/0,
new/2,new/3,setMaxPointSize/2,setSelectedFont/2]).
-export([cacheBestSize/2,captureMouse/1,center/1,center/2,centerOnParent/1,
centerOnParent/2,centre/1,centre/2,centreOnParent/1,centreOnParent/2,
clearBackground/1,clientToScreen/2,clientToScreen/3,close/1,close/2,
connect/2,connect/3,convertDialogToPixels/2,convertPixelsToDialog/2,
destroyChildren/1,disable/1,disconnect/1,disconnect/2,disconnect/3,
enable/1,enable/2,findWindow/2,fit/1,fitInside/1,freeze/1,getAcceleratorTable/1,
getBackgroundColour/1,getBackgroundStyle/1,getBestSize/1,getCaret/1,
getCharHeight/1,getCharWidth/1,getChildren/1,getClientSize/1,getContainingSizer/1,
getCursor/1,getDropTarget/1,getEventHandler/1,getExtraStyle/1,getFont/1,
getForegroundColour/1,getGrandParent/1,getHandle/1,getHelpText/1,
getId/1,getInternalMargin/1,getLabel/1,getMaxSize/1,getMinSize/1,getName/1,
getParent/1,getPickerCtrlProportion/1,getPosition/1,getRect/1,getScreenPosition/1,
getScreenRect/1,getScrollPos/2,getScrollRange/2,getScrollThumb/2,
getSize/1,getSizer/1,getTextCtrl/1,getTextCtrlProportion/1,getTextExtent/2,
getTextExtent/3,getToolTip/1,getUpdateRegion/1,getVirtualSize/1,getWindowStyleFlag/1,
getWindowVariant/1,hasCapture/1,hasScrollbar/2,hasTextCtrl/1,hasTransparentBackground/1,
hide/1,inheritAttributes/1,initDialog/1,invalidateBestSize/1,isEnabled/1,
isExposed/2,isExposed/3,isExposed/5,isPickerCtrlGrowable/1,isRetained/1,
isShown/1,isTextCtrlGrowable/1,isTopLevel/1,layout/1,lineDown/1,lineUp/1,
lower/1,makeModal/1,makeModal/2,move/2,move/3,move/4,moveAfterInTabOrder/2,
moveBeforeInTabOrder/2,navigate/1,navigate/2,pageDown/1,pageUp/1,parent_class/1,
popEventHandler/1,popEventHandler/2,popupMenu/2,popupMenu/3,popupMenu/4,
raise/1,refresh/1,refresh/2,refreshRect/2,refreshRect/3,releaseMouse/1,
removeChild/2,reparent/2,screenToClient/1,screenToClient/2,scrollLines/2,
scrollPages/2,scrollWindow/3,scrollWindow/4,setAcceleratorTable/2,
setAutoLayout/2,setBackgroundColour/2,setBackgroundStyle/2,setCaret/2,
setClientSize/2,setClientSize/3,setContainingSizer/2,setCursor/2,
setDropTarget/2,setExtraStyle/2,setFocus/1,setFocusFromKbd/1,setFont/2,
setForegroundColour/2,setHelpText/2,setId/2,setInternalMargin/2,setLabel/2,
setMaxSize/2,setMinSize/2,setName/2,setOwnBackgroundColour/2,setOwnFont/2,
setOwnForegroundColour/2,setPalette/2,setPickerCtrlGrowable/1,setPickerCtrlGrowable/2,
setPickerCtrlProportion/2,setScrollPos/3,setScrollPos/4,setScrollbar/5,
setScrollbar/6,setSize/2,setSize/3,setSize/5,setSize/6,setSizeHints/2,
setSizeHints/3,setSizeHints/4,setSizer/2,setSizer/3,setSizerAndFit/2,
setSizerAndFit/3,setTextCtrlGrowable/1,setTextCtrlGrowable/2,setTextCtrlProportion/2,
setThemeEnabled/2,setToolTip/2,setVirtualSize/2,setVirtualSize/3,
setVirtualSizeHints/2,setVirtualSizeHints/3,setVirtualSizeHints/4,
setWindowStyle/2,setWindowStyleFlag/2,setWindowVariant/2,shouldInheritColours/1,
show/1,show/2,thaw/1,transferDataFromWindow/1,transferDataToWindow/1,
update/1,updateWindowUI/1,updateWindowUI/2,validate/1,warpPointer/3]).
-export_type([wxFontPickerCtrl/0]).
parent_class(wxPickerBase) -> true;
parent_class(wxControl) -> true;
parent_class(wxWindow) -> true;
parent_class(wxEvtHandler) -> true;
parent_class(_Class) -> erlang:error({badtype, ?MODULE}).
-type wxFontPickerCtrl() :: wx:wx_object().
-spec new() -> wxFontPickerCtrl().
new() ->
wxe_util:construct(?wxFontPickerCtrl_new_0,
<<>>).
@equiv new(Parent , Id , [ ] )
-spec new(Parent, Id) -> wxFontPickerCtrl() when
Parent::wxWindow:wxWindow(), Id::integer().
new(Parent,Id)
when is_record(Parent, wx_ref),is_integer(Id) ->
new(Parent,Id, []).
-spec new(Parent, Id, [Option]) -> wxFontPickerCtrl() when
Parent::wxWindow:wxWindow(), Id::integer(),
Option :: {initial, wxFont:wxFont()}
| {pos, {X::integer(), Y::integer()}}
| {size, {W::integer(), H::integer()}}
| {style, integer()}
| {validator, wx:wx_object()}.
new(#wx_ref{type=ParentT,ref=ParentRef},Id, Options)
when is_integer(Id),is_list(Options) ->
?CLASS(ParentT,wxWindow),
MOpts = fun({initial, #wx_ref{type=InitialT,ref=InitialRef}}, Acc) -> ?CLASS(InitialT,wxFont),[<<1:32/?UI,InitialRef:32/?UI>>|Acc];
({pos, {PosX,PosY}}, Acc) -> [<<2:32/?UI,PosX:32/?UI,PosY:32/?UI,0:32>>|Acc];
({size, {SizeW,SizeH}}, Acc) -> [<<3:32/?UI,SizeW:32/?UI,SizeH:32/?UI,0:32>>|Acc];
({style, Style}, Acc) -> [<<4:32/?UI,Style:32/?UI>>|Acc];
({validator, #wx_ref{type=ValidatorT,ref=ValidatorRef}}, Acc) -> ?CLASS(ValidatorT,wx),[<<5:32/?UI,ValidatorRef:32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:construct(?wxFontPickerCtrl_new_3,
<<ParentRef:32/?UI,Id:32/?UI, BinOpt/binary>>).
-spec create(This, Parent, Id) -> boolean() when
This::wxFontPickerCtrl(), Parent::wxWindow:wxWindow(), Id::integer().
create(This,Parent,Id)
when is_record(This, wx_ref),is_record(Parent, wx_ref),is_integer(Id) ->
create(This,Parent,Id, []).
-spec create(This, Parent, Id, [Option]) -> boolean() when
This::wxFontPickerCtrl(), Parent::wxWindow:wxWindow(), Id::integer(),
Option :: {initial, wxFont:wxFont()}
| {pos, {X::integer(), Y::integer()}}
| {size, {W::integer(), H::integer()}}
| {style, integer()}
| {validator, wx:wx_object()}.
create(#wx_ref{type=ThisT,ref=ThisRef},#wx_ref{type=ParentT,ref=ParentRef},Id, Options)
when is_integer(Id),is_list(Options) ->
?CLASS(ThisT,wxFontPickerCtrl),
?CLASS(ParentT,wxWindow),
MOpts = fun({initial, #wx_ref{type=InitialT,ref=InitialRef}}, Acc) -> ?CLASS(InitialT,wxFont),[<<1:32/?UI,InitialRef:32/?UI>>|Acc];
({pos, {PosX,PosY}}, Acc) -> [<<2:32/?UI,PosX:32/?UI,PosY:32/?UI,0:32>>|Acc];
({size, {SizeW,SizeH}}, Acc) -> [<<3:32/?UI,SizeW:32/?UI,SizeH:32/?UI,0:32>>|Acc];
({style, Style}, Acc) -> [<<4:32/?UI,Style:32/?UI>>|Acc];
({validator, #wx_ref{type=ValidatorT,ref=ValidatorRef}}, Acc) -> ?CLASS(ValidatorT,wx),[<<5:32/?UI,ValidatorRef:32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxFontPickerCtrl_Create,
<<ThisRef:32/?UI,ParentRef:32/?UI,Id:32/?UI, 0:32,BinOpt/binary>>).
-spec getSelectedFont(This) -> wxFont:wxFont() when
This::wxFontPickerCtrl().
getSelectedFont(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxFontPickerCtrl),
wxe_util:call(?wxFontPickerCtrl_GetSelectedFont,
<<ThisRef:32/?UI>>).
-spec setSelectedFont(This, F) -> ok when
This::wxFontPickerCtrl(), F::wxFont:wxFont().
setSelectedFont(#wx_ref{type=ThisT,ref=ThisRef},#wx_ref{type=FT,ref=FRef}) ->
?CLASS(ThisT,wxFontPickerCtrl),
?CLASS(FT,wxFont),
wxe_util:cast(?wxFontPickerCtrl_SetSelectedFont,
<<ThisRef:32/?UI,FRef:32/?UI>>).
-spec getMaxPointSize(This) -> integer() when
This::wxFontPickerCtrl().
getMaxPointSize(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxFontPickerCtrl),
wxe_util:call(?wxFontPickerCtrl_GetMaxPointSize,
<<ThisRef:32/?UI>>).
-spec setMaxPointSize(This, Max) -> ok when
This::wxFontPickerCtrl(), Max::integer().
setMaxPointSize(#wx_ref{type=ThisT,ref=ThisRef},Max)
when is_integer(Max) ->
?CLASS(ThisT,wxFontPickerCtrl),
wxe_util:cast(?wxFontPickerCtrl_SetMaxPointSize,
<<ThisRef:32/?UI,Max:32/?UI>>).
-spec destroy(This::wxFontPickerCtrl()) -> ok.
destroy(Obj=#wx_ref{type=Type}) ->
?CLASS(Type,wxFontPickerCtrl),
wxe_util:destroy(?DESTROY_OBJECT,Obj),
ok.
From wxPickerBase
isPickerCtrlGrowable(This) -> wxPickerBase:isPickerCtrlGrowable(This).
setTextCtrlGrowable(This, Options) -> wxPickerBase:setTextCtrlGrowable(This, Options).
setTextCtrlGrowable(This) -> wxPickerBase:setTextCtrlGrowable(This).
setPickerCtrlGrowable(This, Options) -> wxPickerBase:setPickerCtrlGrowable(This, Options).
setPickerCtrlGrowable(This) -> wxPickerBase:setPickerCtrlGrowable(This).
isTextCtrlGrowable(This) -> wxPickerBase:isTextCtrlGrowable(This).
getTextCtrl(This) -> wxPickerBase:getTextCtrl(This).
hasTextCtrl(This) -> wxPickerBase:hasTextCtrl(This).
getPickerCtrlProportion(This) -> wxPickerBase:getPickerCtrlProportion(This).
getTextCtrlProportion(This) -> wxPickerBase:getTextCtrlProportion(This).
setPickerCtrlProportion(This,Prop) -> wxPickerBase:setPickerCtrlProportion(This,Prop).
setTextCtrlProportion(This,Prop) -> wxPickerBase:setTextCtrlProportion(This,Prop).
getInternalMargin(This) -> wxPickerBase:getInternalMargin(This).
setInternalMargin(This,Newmargin) -> wxPickerBase:setInternalMargin(This,Newmargin).
setLabel(This,Label) -> wxControl:setLabel(This,Label).
getLabel(This) -> wxControl:getLabel(This).
warpPointer(This,X,Y) -> wxWindow:warpPointer(This,X,Y).
validate(This) -> wxWindow:validate(This).
updateWindowUI(This, Options) -> wxWindow:updateWindowUI(This, Options).
updateWindowUI(This) -> wxWindow:updateWindowUI(This).
update(This) -> wxWindow:update(This).
transferDataToWindow(This) -> wxWindow:transferDataToWindow(This).
transferDataFromWindow(This) -> wxWindow:transferDataFromWindow(This).
thaw(This) -> wxWindow:thaw(This).
show(This, Options) -> wxWindow:show(This, Options).
show(This) -> wxWindow:show(This).
shouldInheritColours(This) -> wxWindow:shouldInheritColours(This).
setWindowVariant(This,Variant) -> wxWindow:setWindowVariant(This,Variant).
setWindowStyleFlag(This,Style) -> wxWindow:setWindowStyleFlag(This,Style).
setWindowStyle(This,Style) -> wxWindow:setWindowStyle(This,Style).
setVirtualSizeHints(This,MinW,MinH, Options) -> wxWindow:setVirtualSizeHints(This,MinW,MinH, Options).
setVirtualSizeHints(This,MinW,MinH) -> wxWindow:setVirtualSizeHints(This,MinW,MinH).
setVirtualSizeHints(This,MinSize) -> wxWindow:setVirtualSizeHints(This,MinSize).
setVirtualSize(This,X,Y) -> wxWindow:setVirtualSize(This,X,Y).
setVirtualSize(This,Size) -> wxWindow:setVirtualSize(This,Size).
setToolTip(This,Tip) -> wxWindow:setToolTip(This,Tip).
setThemeEnabled(This,EnableTheme) -> wxWindow:setThemeEnabled(This,EnableTheme).
setSizerAndFit(This,Sizer, Options) -> wxWindow:setSizerAndFit(This,Sizer, Options).
setSizerAndFit(This,Sizer) -> wxWindow:setSizerAndFit(This,Sizer).
setSizer(This,Sizer, Options) -> wxWindow:setSizer(This,Sizer, Options).
setSizer(This,Sizer) -> wxWindow:setSizer(This,Sizer).
setSizeHints(This,MinW,MinH, Options) -> wxWindow:setSizeHints(This,MinW,MinH, Options).
setSizeHints(This,MinW,MinH) -> wxWindow:setSizeHints(This,MinW,MinH).
setSizeHints(This,MinSize) -> wxWindow:setSizeHints(This,MinSize).
setSize(This,X,Y,Width,Height, Options) -> wxWindow:setSize(This,X,Y,Width,Height, Options).
setSize(This,X,Y,Width,Height) -> wxWindow:setSize(This,X,Y,Width,Height).
setSize(This,Width,Height) -> wxWindow:setSize(This,Width,Height).
setSize(This,Rect) -> wxWindow:setSize(This,Rect).
setScrollPos(This,Orient,Pos, Options) -> wxWindow:setScrollPos(This,Orient,Pos, Options).
setScrollPos(This,Orient,Pos) -> wxWindow:setScrollPos(This,Orient,Pos).
setScrollbar(This,Orient,Pos,ThumbVisible,Range, Options) -> wxWindow:setScrollbar(This,Orient,Pos,ThumbVisible,Range, Options).
setScrollbar(This,Orient,Pos,ThumbVisible,Range) -> wxWindow:setScrollbar(This,Orient,Pos,ThumbVisible,Range).
setPalette(This,Pal) -> wxWindow:setPalette(This,Pal).
setName(This,Name) -> wxWindow:setName(This,Name).
setId(This,Winid) -> wxWindow:setId(This,Winid).
setHelpText(This,Text) -> wxWindow:setHelpText(This,Text).
setForegroundColour(This,Colour) -> wxWindow:setForegroundColour(This,Colour).
setFont(This,Font) -> wxWindow:setFont(This,Font).
setFocusFromKbd(This) -> wxWindow:setFocusFromKbd(This).
setFocus(This) -> wxWindow:setFocus(This).
setExtraStyle(This,ExStyle) -> wxWindow:setExtraStyle(This,ExStyle).
setDropTarget(This,DropTarget) -> wxWindow:setDropTarget(This,DropTarget).
setOwnForegroundColour(This,Colour) -> wxWindow:setOwnForegroundColour(This,Colour).
setOwnFont(This,Font) -> wxWindow:setOwnFont(This,Font).
setOwnBackgroundColour(This,Colour) -> wxWindow:setOwnBackgroundColour(This,Colour).
setMinSize(This,MinSize) -> wxWindow:setMinSize(This,MinSize).
setMaxSize(This,MaxSize) -> wxWindow:setMaxSize(This,MaxSize).
setCursor(This,Cursor) -> wxWindow:setCursor(This,Cursor).
setContainingSizer(This,Sizer) -> wxWindow:setContainingSizer(This,Sizer).
setClientSize(This,Width,Height) -> wxWindow:setClientSize(This,Width,Height).
setClientSize(This,Size) -> wxWindow:setClientSize(This,Size).
setCaret(This,Caret) -> wxWindow:setCaret(This,Caret).
setBackgroundStyle(This,Style) -> wxWindow:setBackgroundStyle(This,Style).
setBackgroundColour(This,Colour) -> wxWindow:setBackgroundColour(This,Colour).
setAutoLayout(This,AutoLayout) -> wxWindow:setAutoLayout(This,AutoLayout).
setAcceleratorTable(This,Accel) -> wxWindow:setAcceleratorTable(This,Accel).
scrollWindow(This,Dx,Dy, Options) -> wxWindow:scrollWindow(This,Dx,Dy, Options).
scrollWindow(This,Dx,Dy) -> wxWindow:scrollWindow(This,Dx,Dy).
scrollPages(This,Pages) -> wxWindow:scrollPages(This,Pages).
scrollLines(This,Lines) -> wxWindow:scrollLines(This,Lines).
screenToClient(This,Pt) -> wxWindow:screenToClient(This,Pt).
screenToClient(This) -> wxWindow:screenToClient(This).
reparent(This,NewParent) -> wxWindow:reparent(This,NewParent).
removeChild(This,Child) -> wxWindow:removeChild(This,Child).
releaseMouse(This) -> wxWindow:releaseMouse(This).
refreshRect(This,Rect, Options) -> wxWindow:refreshRect(This,Rect, Options).
refreshRect(This,Rect) -> wxWindow:refreshRect(This,Rect).
refresh(This, Options) -> wxWindow:refresh(This, Options).
refresh(This) -> wxWindow:refresh(This).
raise(This) -> wxWindow:raise(This).
popupMenu(This,Menu,X,Y) -> wxWindow:popupMenu(This,Menu,X,Y).
popupMenu(This,Menu, Options) -> wxWindow:popupMenu(This,Menu, Options).
popupMenu(This,Menu) -> wxWindow:popupMenu(This,Menu).
popEventHandler(This, Options) -> wxWindow:popEventHandler(This, Options).
popEventHandler(This) -> wxWindow:popEventHandler(This).
pageUp(This) -> wxWindow:pageUp(This).
pageDown(This) -> wxWindow:pageDown(This).
navigate(This, Options) -> wxWindow:navigate(This, Options).
navigate(This) -> wxWindow:navigate(This).
moveBeforeInTabOrder(This,Win) -> wxWindow:moveBeforeInTabOrder(This,Win).
moveAfterInTabOrder(This,Win) -> wxWindow:moveAfterInTabOrder(This,Win).
move(This,X,Y, Options) -> wxWindow:move(This,X,Y, Options).
move(This,X,Y) -> wxWindow:move(This,X,Y).
move(This,Pt) -> wxWindow:move(This,Pt).
makeModal(This, Options) -> wxWindow:makeModal(This, Options).
makeModal(This) -> wxWindow:makeModal(This).
lower(This) -> wxWindow:lower(This).
lineUp(This) -> wxWindow:lineUp(This).
lineDown(This) -> wxWindow:lineDown(This).
layout(This) -> wxWindow:layout(This).
isTopLevel(This) -> wxWindow:isTopLevel(This).
isShown(This) -> wxWindow:isShown(This).
isRetained(This) -> wxWindow:isRetained(This).
isExposed(This,X,Y,W,H) -> wxWindow:isExposed(This,X,Y,W,H).
isExposed(This,X,Y) -> wxWindow:isExposed(This,X,Y).
isExposed(This,Pt) -> wxWindow:isExposed(This,Pt).
isEnabled(This) -> wxWindow:isEnabled(This).
invalidateBestSize(This) -> wxWindow:invalidateBestSize(This).
initDialog(This) -> wxWindow:initDialog(This).
inheritAttributes(This) -> wxWindow:inheritAttributes(This).
hide(This) -> wxWindow:hide(This).
hasTransparentBackground(This) -> wxWindow:hasTransparentBackground(This).
hasScrollbar(This,Orient) -> wxWindow:hasScrollbar(This,Orient).
hasCapture(This) -> wxWindow:hasCapture(This).
getWindowVariant(This) -> wxWindow:getWindowVariant(This).
getWindowStyleFlag(This) -> wxWindow:getWindowStyleFlag(This).
getVirtualSize(This) -> wxWindow:getVirtualSize(This).
getUpdateRegion(This) -> wxWindow:getUpdateRegion(This).
getToolTip(This) -> wxWindow:getToolTip(This).
getTextExtent(This,String, Options) -> wxWindow:getTextExtent(This,String, Options).
getTextExtent(This,String) -> wxWindow:getTextExtent(This,String).
getSizer(This) -> wxWindow:getSizer(This).
getSize(This) -> wxWindow:getSize(This).
getScrollThumb(This,Orient) -> wxWindow:getScrollThumb(This,Orient).
getScrollRange(This,Orient) -> wxWindow:getScrollRange(This,Orient).
getScrollPos(This,Orient) -> wxWindow:getScrollPos(This,Orient).
getScreenRect(This) -> wxWindow:getScreenRect(This).
getScreenPosition(This) -> wxWindow:getScreenPosition(This).
getRect(This) -> wxWindow:getRect(This).
getPosition(This) -> wxWindow:getPosition(This).
getParent(This) -> wxWindow:getParent(This).
getName(This) -> wxWindow:getName(This).
getMinSize(This) -> wxWindow:getMinSize(This).
getMaxSize(This) -> wxWindow:getMaxSize(This).
getId(This) -> wxWindow:getId(This).
getHelpText(This) -> wxWindow:getHelpText(This).
getHandle(This) -> wxWindow:getHandle(This).
getGrandParent(This) -> wxWindow:getGrandParent(This).
getForegroundColour(This) -> wxWindow:getForegroundColour(This).
getFont(This) -> wxWindow:getFont(This).
getExtraStyle(This) -> wxWindow:getExtraStyle(This).
getEventHandler(This) -> wxWindow:getEventHandler(This).
getDropTarget(This) -> wxWindow:getDropTarget(This).
getCursor(This) -> wxWindow:getCursor(This).
getContainingSizer(This) -> wxWindow:getContainingSizer(This).
getClientSize(This) -> wxWindow:getClientSize(This).
getChildren(This) -> wxWindow:getChildren(This).
getCharWidth(This) -> wxWindow:getCharWidth(This).
getCharHeight(This) -> wxWindow:getCharHeight(This).
getCaret(This) -> wxWindow:getCaret(This).
getBestSize(This) -> wxWindow:getBestSize(This).
getBackgroundStyle(This) -> wxWindow:getBackgroundStyle(This).
getBackgroundColour(This) -> wxWindow:getBackgroundColour(This).
getAcceleratorTable(This) -> wxWindow:getAcceleratorTable(This).
freeze(This) -> wxWindow:freeze(This).
fitInside(This) -> wxWindow:fitInside(This).
fit(This) -> wxWindow:fit(This).
findWindow(This,Winid) -> wxWindow:findWindow(This,Winid).
enable(This, Options) -> wxWindow:enable(This, Options).
enable(This) -> wxWindow:enable(This).
disable(This) -> wxWindow:disable(This).
destroyChildren(This) -> wxWindow:destroyChildren(This).
convertPixelsToDialog(This,Sz) -> wxWindow:convertPixelsToDialog(This,Sz).
convertDialogToPixels(This,Sz) -> wxWindow:convertDialogToPixels(This,Sz).
close(This, Options) -> wxWindow:close(This, Options).
close(This) -> wxWindow:close(This).
clientToScreen(This,X,Y) -> wxWindow:clientToScreen(This,X,Y).
clientToScreen(This,Pt) -> wxWindow:clientToScreen(This,Pt).
clearBackground(This) -> wxWindow:clearBackground(This).
centreOnParent(This, Options) -> wxWindow:centreOnParent(This, Options).
centreOnParent(This) -> wxWindow:centreOnParent(This).
centre(This, Options) -> wxWindow:centre(This, Options).
centre(This) -> wxWindow:centre(This).
centerOnParent(This, Options) -> wxWindow:centerOnParent(This, Options).
centerOnParent(This) -> wxWindow:centerOnParent(This).
center(This, Options) -> wxWindow:center(This, Options).
center(This) -> wxWindow:center(This).
captureMouse(This) -> wxWindow:captureMouse(This).
cacheBestSize(This,Size) -> wxWindow:cacheBestSize(This,Size).
disconnect(This,EventType, Options) -> wxEvtHandler:disconnect(This,EventType, Options).
disconnect(This,EventType) -> wxEvtHandler:disconnect(This,EventType).
disconnect(This) -> wxEvtHandler:disconnect(This).
connect(This,EventType, Options) -> wxEvtHandler:connect(This,EventType, Options).
connect(This,EventType) -> wxEvtHandler:connect(This,EventType).
|
120a53563f2de31dfa355aa32f02b2b7a18d460fec9e3c62d59ca47a5caa8f9c | ixmatus/orgmode-parse | Test.hs | module Main where
import Content.Contents
import Content.List
import Content.Paragraph
import Document
import Drawer
import Headline
import Test.Tasty
import Timestamps
main :: IO ()
main = defaultMain tests
tests :: TestTree
tests = testGroup
"OrgMode Parser Tests"
[ parserHeadlineTests
, parserDrawerTests
, parserTimestampTests
, parserParagraphs
, parserLists
, parserContents
, parserWeekdayTests
, parserSmallDocumentTests
]
| null | https://raw.githubusercontent.com/ixmatus/orgmode-parse/89adc4087556bb0dd58a7648a9e7e239463aa059/test/Test.hs | haskell | module Main where
import Content.Contents
import Content.List
import Content.Paragraph
import Document
import Drawer
import Headline
import Test.Tasty
import Timestamps
main :: IO ()
main = defaultMain tests
tests :: TestTree
tests = testGroup
"OrgMode Parser Tests"
[ parserHeadlineTests
, parserDrawerTests
, parserTimestampTests
, parserParagraphs
, parserLists
, parserContents
, parserWeekdayTests
, parserSmallDocumentTests
]
| |
571cf9ae246beb978209626d7ff15d6d1cc1329873e2a1d4ea8f426300fc708e | freizl/dive-into-haskell | Main.hs | {-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Monad.Trans.State
import Control.Monad.Trans.Reader
import Data.List
import Control.Monad.Trans.Except
import Control.Monad.Trans.Maybe (MaybeT(..))
import Control.Monad.IO.Class
main :: IO ()
main = putStrLn "Hello, Haskell!"
---
-- * StateT
---
-- Compare with default behavior (see `26.org`),
-- what's the problem with this implementation?
1 . given the ` runStateT ` , has to add ` Monad m ` constrain .
2 . shall the signature be ` ( s ' - > s ) - > StateT s m a - > StateT s ' m a `
-- ^ NO. `s` is passing through all the way hence has to be same type.
-- runStateT :: StateT s m a -> s -> m (a, s)
--
withStateT2 :: Monad m => (s -> s) -> StateT s m a -> StateT s m a
withStateT2 f m = StateT $ \s -> do
(a1, s1) <- runStateT m (f s)
return (a1, s1)
s1 :: StateT Int IO Bool
s1 = StateT $ \s -> return (s > 0, s)
s2 :: StateT String IO Bool
s2 = StateT $ \s -> do
putStrLn "s2"
return ("hw" `isSubsequenceOf` s, "<hello world>" ++ s)
t2 :: IO ()
t2 = do
let f = (++ " :D: ") :: String -> String
let st = withStateT f s2
(a, s) <- runStateT st "init hw statet"
print (a, s)
t1 :: IO ()
t1 = do
let f = (+ 3)
let st = withStateT2 f s1
(a, s) <- runStateT st 1
print (a, s)
---
-- * Reader
---
-- why it is `r' -> r` instead of `r -> r'`
-- this is only feasible way.
-- given a function `r -> r`, it is intend to modify `r`
hence modify the ` r ` before password ` m ` ( 2nd arguments ) .
--
-- runReaderT :: ReaderT r m a -> r -> m a
-- see the `r` has been 'dropped'
v.s.
-- runStateT :: StateT s m a -> s -> m (a, s)
the ` s ` will be pass through
--
withReaderT2 :: (r' -> r) -> ReaderT r m a -> ReaderT r' m a
withReaderT2 f m = ReaderT $ \r -> runReaderT m (f r)
---
-- * Multiple layers
---
{-
newtype ExceptT e m a = ExceptT { runExceptT :: m (Either e a) }
newtype MaybeT m a = MaybeT { runMaybeT :: m (Maybe a) }
newtype ReaderT r m a = ReaderT { runReaderT :: r -> m a }
newtype StateT s m a = StateT { runStateT :: s -> m (a, s) }
-}
embedded :: MaybeT (ExceptT String (ReaderT () IO)) Int
embedded = MaybeT $ ExceptT $ ReaderT $ const $ return (Right (Just 1))
-- instance (MonadIO m) => MonadIO (MaybeT m) where
-- liftIO ioa = MaybeT $ liftIO $ Just <$> ioa
-- instance (MonadIO m) => MonadIO (ReaderT r m) where
-- liftIO ioa = ReaderT $ const (liftIO ioa)
-- instance (MonadIO m) => MonadIO (StateT s m) where
-- liftIO ioa = StateT $ \s -> do
-- a <- liftIO ioa
-- return (a, s)
| null | https://raw.githubusercontent.com/freizl/dive-into-haskell/b18a6bfe212db6c3a5d707b4a640170b8bcf9330/readings/haskell-book/26/Main.hs | haskell | # LANGUAGE OverloadedStrings #
-
* StateT
-
Compare with default behavior (see `26.org`),
what's the problem with this implementation?
^ NO. `s` is passing through all the way hence has to be same type.
runStateT :: StateT s m a -> s -> m (a, s)
-
* Reader
-
why it is `r' -> r` instead of `r -> r'`
this is only feasible way.
given a function `r -> r`, it is intend to modify `r`
runReaderT :: ReaderT r m a -> r -> m a
see the `r` has been 'dropped'
runStateT :: StateT s m a -> s -> m (a, s)
-
* Multiple layers
-
newtype ExceptT e m a = ExceptT { runExceptT :: m (Either e a) }
newtype MaybeT m a = MaybeT { runMaybeT :: m (Maybe a) }
newtype ReaderT r m a = ReaderT { runReaderT :: r -> m a }
newtype StateT s m a = StateT { runStateT :: s -> m (a, s) }
instance (MonadIO m) => MonadIO (MaybeT m) where
liftIO ioa = MaybeT $ liftIO $ Just <$> ioa
instance (MonadIO m) => MonadIO (ReaderT r m) where
liftIO ioa = ReaderT $ const (liftIO ioa)
instance (MonadIO m) => MonadIO (StateT s m) where
liftIO ioa = StateT $ \s -> do
a <- liftIO ioa
return (a, s) | module Main where
import Control.Monad.Trans.State
import Control.Monad.Trans.Reader
import Data.List
import Control.Monad.Trans.Except
import Control.Monad.Trans.Maybe (MaybeT(..))
import Control.Monad.IO.Class
main :: IO ()
main = putStrLn "Hello, Haskell!"
1 . given the ` runStateT ` , has to add ` Monad m ` constrain .
2 . shall the signature be ` ( s ' - > s ) - > StateT s m a - > StateT s ' m a `
withStateT2 :: Monad m => (s -> s) -> StateT s m a -> StateT s m a
withStateT2 f m = StateT $ \s -> do
(a1, s1) <- runStateT m (f s)
return (a1, s1)
s1 :: StateT Int IO Bool
s1 = StateT $ \s -> return (s > 0, s)
s2 :: StateT String IO Bool
s2 = StateT $ \s -> do
putStrLn "s2"
return ("hw" `isSubsequenceOf` s, "<hello world>" ++ s)
t2 :: IO ()
t2 = do
let f = (++ " :D: ") :: String -> String
let st = withStateT f s2
(a, s) <- runStateT st "init hw statet"
print (a, s)
t1 :: IO ()
t1 = do
let f = (+ 3)
let st = withStateT2 f s1
(a, s) <- runStateT st 1
print (a, s)
hence modify the ` r ` before password ` m ` ( 2nd arguments ) .
v.s.
the ` s ` will be pass through
withReaderT2 :: (r' -> r) -> ReaderT r m a -> ReaderT r' m a
withReaderT2 f m = ReaderT $ \r -> runReaderT m (f r)
embedded :: MaybeT (ExceptT String (ReaderT () IO)) Int
embedded = MaybeT $ ExceptT $ ReaderT $ const $ return (Right (Just 1))
|
4dfa070379f88c0e1c2e932fb3f6c43daab110037988d6b87ee2908b69417186 | mpelleau/AbSolute | out.ml | open Libabsolute
open Signature
open Picasso
module Make (D : Domain) = struct
let print_list ?(t = false) msg print l =
Format.printf "%i %s" (List.length l) msg ;
if t then
List.iteri (fun i -> Format.printf "\nsol n°%i:\n%a" (i + 1) print) l ;
Format.printf "\n"
let blue e = ((150, 150, 255), D.render e)
let green e = ((150, 255, 150), D.render e)
let build_render abciss ordinate res =
let open Result in
let r = Rendering.create ~abciss ~ordinate ~title:"AbSolute" 800. 800. in
let r = Rendering.add_l r (List.map blue res.sure) in
Rendering.add_l r (List.map green res.unsure)
let build_render3d abciss ordinate height res =
let open Result in
let r = Rendering3d.create ~abciss ~ordinate ~height () in
let r = Rendering3d.add_l r (List.map blue res.sure) in
Rendering3d.add_l r (List.map green res.unsure)
let witness w =
let open Consistency in
match w with
| Unfeasible ->
Format.printf "problem unsatisfiable.\n" ;
exit 3
| Maybe ->
Format.printf "no solution found, but the problem maybe admits some.\n" ;
exit 4
| Witness i ->
Format.printf "problem satisfiable.\nwitness value:\n%a\n"
Instance.print i ;
exit 5
let satisfiability w =
let open Kleene in
match w with
| False ->
Format.printf "problem unsatisfiable.\n" ;
exit 3
| Unknown ->
Format.printf "no solution found, but the problem maybe admits some.\n" ;
exit 4
| True ->
Format.printf "problem satisfiable.\n" ;
exit 5
(* text output on std out *)
let terminal_output ?(t = false) fmt res =
let print_unsure fmt e = Format.fprintf fmt "%a\n" D.print e in
let open Result in
print_list ~t "inner solutions" D.print res.sure ;
print_list ~t "outter solutions" print_unsure res.unsure ;
Format.printf "total time : %fs\n" (Sys.time ()) ;
if not !Constant.trace then
Format.fprintf fmt
"you can use the -trace (or -t) option to list the solutions\n" ;
match (res.sure, res.unsure) with
| [], [] ->
Format.printf "problem unsatisfiable.\n" ;
exit 3
| [], _ :: _ ->
Format.printf "no solution found, but the problem maybe admits some.\n" ;
exit 4
| _ :: _, _ ->
Format.printf "problem satisfiable.\n" ;
exit 5
let vars2D prob =
let vars = Csp.get_var_names prob |> Array.of_list in
let size = Array.length vars in
(vars.(0), vars.(1 mod size))
let vars3D prob =
let vars = Csp.get_var_names prob |> Array.of_list in
let size = Array.length vars in
(vars.(0), vars.(1 mod size), vars.(2 mod size))
let results ?(t = false) prob res =
let open Constant in
( if !obj then
let v1, v2, v3 = vars3D prob in
let render = build_render3d v1 v2 v3 res in
to_obj render "out/absolute.obj" ) ;
if !visualization || !tex || !svg then (
let v1, v2 = vars2D prob in
let render = build_render v1 v2 res in
if !tex then to_latex render "out/name.tex" ;
if !svg then to_svg render "out/name.svg" ;
if !visualization then show render ) ;
Format.printf "%a\n%!" (terminal_output ~t) res
end
| null | https://raw.githubusercontent.com/mpelleau/AbSolute/8cdea2008161a7c4899db653b85da88b2fe79891/absolute-solver/out.ml | ocaml | text output on std out | open Libabsolute
open Signature
open Picasso
module Make (D : Domain) = struct
let print_list ?(t = false) msg print l =
Format.printf "%i %s" (List.length l) msg ;
if t then
List.iteri (fun i -> Format.printf "\nsol n°%i:\n%a" (i + 1) print) l ;
Format.printf "\n"
let blue e = ((150, 150, 255), D.render e)
let green e = ((150, 255, 150), D.render e)
let build_render abciss ordinate res =
let open Result in
let r = Rendering.create ~abciss ~ordinate ~title:"AbSolute" 800. 800. in
let r = Rendering.add_l r (List.map blue res.sure) in
Rendering.add_l r (List.map green res.unsure)
let build_render3d abciss ordinate height res =
let open Result in
let r = Rendering3d.create ~abciss ~ordinate ~height () in
let r = Rendering3d.add_l r (List.map blue res.sure) in
Rendering3d.add_l r (List.map green res.unsure)
let witness w =
let open Consistency in
match w with
| Unfeasible ->
Format.printf "problem unsatisfiable.\n" ;
exit 3
| Maybe ->
Format.printf "no solution found, but the problem maybe admits some.\n" ;
exit 4
| Witness i ->
Format.printf "problem satisfiable.\nwitness value:\n%a\n"
Instance.print i ;
exit 5
let satisfiability w =
let open Kleene in
match w with
| False ->
Format.printf "problem unsatisfiable.\n" ;
exit 3
| Unknown ->
Format.printf "no solution found, but the problem maybe admits some.\n" ;
exit 4
| True ->
Format.printf "problem satisfiable.\n" ;
exit 5
let terminal_output ?(t = false) fmt res =
let print_unsure fmt e = Format.fprintf fmt "%a\n" D.print e in
let open Result in
print_list ~t "inner solutions" D.print res.sure ;
print_list ~t "outter solutions" print_unsure res.unsure ;
Format.printf "total time : %fs\n" (Sys.time ()) ;
if not !Constant.trace then
Format.fprintf fmt
"you can use the -trace (or -t) option to list the solutions\n" ;
match (res.sure, res.unsure) with
| [], [] ->
Format.printf "problem unsatisfiable.\n" ;
exit 3
| [], _ :: _ ->
Format.printf "no solution found, but the problem maybe admits some.\n" ;
exit 4
| _ :: _, _ ->
Format.printf "problem satisfiable.\n" ;
exit 5
let vars2D prob =
let vars = Csp.get_var_names prob |> Array.of_list in
let size = Array.length vars in
(vars.(0), vars.(1 mod size))
let vars3D prob =
let vars = Csp.get_var_names prob |> Array.of_list in
let size = Array.length vars in
(vars.(0), vars.(1 mod size), vars.(2 mod size))
let results ?(t = false) prob res =
let open Constant in
( if !obj then
let v1, v2, v3 = vars3D prob in
let render = build_render3d v1 v2 v3 res in
to_obj render "out/absolute.obj" ) ;
if !visualization || !tex || !svg then (
let v1, v2 = vars2D prob in
let render = build_render v1 v2 res in
if !tex then to_latex render "out/name.tex" ;
if !svg then to_svg render "out/name.svg" ;
if !visualization then show render ) ;
Format.printf "%a\n%!" (terminal_output ~t) res
end
|
7aca3c6614c2f0e8b9b202faaecd8bddaec55587710556fbc45cec9c8c1c6dec | pixlsus/registry.gimp.org_static | layers-slices.scm | ; Layers-slices script-fu
( c)2009
;; This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 3 or higher .
;; v0.1
; Function to delete "SLICE-" layers from the image
(define (delete-layer image)
(let* (
(layers (cadr (gimp-image-get-layers image))) ; Layer array
(i (- (car (gimp-image-get-layers image)) 1 )) ; Layer number
(name "")
(layer 0)
)
(while (>= i 0)
(let* (
(layer (aref layers i)) ; Pick the layer to check
(name (car (gimp-drawable-get-name layer))) ; extract the name
)
(set! i (- i 1))
(if (string-ci=? "slice-" (substring name 0 6))
(gimp-image-remove-layer image layer) ; delete the layer
)
)
)
)
)
; For each layer, check if the name begins with "SLICE-",
; create a duplicate image, remove the "SLICE-" layers, flatten the image, crop to
; the layer dimensions and save it
(define (manage-images image param-directory param-jpg-quality)
(let* (
(layers (cadr (gimp-image-get-layers image))) ; array of layers
(i (- (car (gimp-image-get-layers image)) 1 )) ; Number of layers
(layer 0)
(flatten-layer 0)
(name "")
)
(while (>= i 0)
(let* (
(layer (aref layers i)) ; pick the layer to work on
(name (car (gimp-drawable-get-name layer))) ; retreive it's name
)
(set! i (- i 1))
" slice- " is 6 , " .xxx " is 4 , any valid name will be at least 11 long
(if (string-ci=? "SLICE-" (substring name 0 6))
; It's a "slice-" layer
(let* (
; Store the Slice layer parameters
(x (car (gimp-drawable-offsets layer)))
(y (cadr (gimp-drawable-offsets layer)))
(height (car (gimp-drawable-height layer)))
(width (car (gimp-drawable-width layer)))
; store the filename to use
(filename (substring name 6 (string-length name)))
(extension (substring filename (- (string-length filename) 4) (string-length filename)))
;create the duplicated image
(newimage (car (gimp-image-duplicate image)))
)
(delete-layer newimage) ; call the function to delete all "SLICE-" layers from the new image
(set! flatten-layer (car (gimp-image-flatten newimage))) ; flatten the resulting image
(gimp-image-crop newimage width height x y) ; crop the image to the stored dimensions
; save the image, depending on the extension
(if (string-ci=? ".jpg" extension)
(file-jpeg-save RUN-NONINTERACTIVE ; no dialog
newimage ; cropped flatten image
flatten-layer ; resulting layer
(string-append param-directory "/" filename) ; filename with target directory
(string-append param-directory "/" filename) ; filename with target directory
param-jpg-quality ; Requested quality
0.0 ; smoothing factor
1 ; Optimize entropy
Progressive loading
"" ; comment
0 ; subsampling option number
Force baseline JPEG
0 ; Frequency of restart markers
1 ; DCT algorithm
)
(if (string-ci=? ".png" extension)
(file-png-save2 RUN-NONINTERACTIVE ; no dialog
newimage ; cropped flatten image
flatten-layer ; resulting layer
(string-append param-directory "/" filename) ; filename with target directory
(string-append param-directory "/" filename) ; filename with target directory
Adam7 interlacing
9 ; compression factor
0 ; Write bkGD chunk
Write gAMA chunk
0 ; Write oFFs chunk
0 ; Write pHYs chunk
0 ; Write tIME chunk
0 ; Write comment
0 ; Preserve color of transparent pixels
)
(gimp-message (string-append "Invalid file extension \"" extension "\"for filename \"" filename "\". Use .jpg or .png only."))
)
)
)
)
)
)
)
)
)
; main function
(define (script-fu-layers-slices
image
drawable
param-directory
param-jpg-quality)
(set! param-jpg-quality (/ param-jpg-quality 100)) ; quality is 0<quality<1 and parameter is 0<param<100
(gimp-image-undo-group-start image) ; take care of the Undo, even if it should not be needed...
(manage-images image param-directory param-jpg-quality) ; Call the function to scan layers and create the images
(gimp-image-undo-group-end image)
(gimp-displays-flush) ; update the display (should not be needed...)
)
Registering of the function in GIMP
(script-fu-register "script-fu-layers-slices"
"Layers Slices..."
"Create one image per layer named \"SLICE-xxx\".\
Each image will be cropped to the layer size, flatten\
and saved as xxx.\
Extension (.png or .jpg) must be specified."
"Robert Hendrickx"
"Robert Hendrickx"
"(c)2009 Robert Hendrickx"
"RGB* GRAY* INDEXED*"
SF-IMAGE "Image" 0
SF-DRAWABLE "Drawable" 0
SF-DIRNAME "Target directory" ""
SF-ADJUSTMENT "JPG Quality" '(90 0 100 1 10 0 SF-SLIDER)
)
(script-fu-menu-register "script-fu-layers-slices"
"<Image>/Filters/Web")
| null | https://raw.githubusercontent.com/pixlsus/registry.gimp.org_static/ffcde7400f402728373ff6579947c6ffe87d1a5e/registry.gimp.org/files/layers-slices.scm | scheme | Layers-slices script-fu
This program is free software; you can redistribute it and/or modify
v0.1
Function to delete "SLICE-" layers from the image
Layer array
Layer number
Pick the layer to check
extract the name
delete the layer
For each layer, check if the name begins with "SLICE-",
create a duplicate image, remove the "SLICE-" layers, flatten the image, crop to
the layer dimensions and save it
array of layers
Number of layers
pick the layer to work on
retreive it's name
It's a "slice-" layer
Store the Slice layer parameters
store the filename to use
create the duplicated image
call the function to delete all "SLICE-" layers from the new image
flatten the resulting image
crop the image to the stored dimensions
save the image, depending on the extension
no dialog
cropped flatten image
resulting layer
filename with target directory
filename with target directory
Requested quality
smoothing factor
Optimize entropy
comment
subsampling option number
Frequency of restart markers
DCT algorithm
no dialog
cropped flatten image
resulting layer
filename with target directory
filename with target directory
compression factor
Write bkGD chunk
Write oFFs chunk
Write pHYs chunk
Write tIME chunk
Write comment
Preserve color of transparent pixels
main function
quality is 0<quality<1 and parameter is 0<param<100
take care of the Undo, even if it should not be needed...
Call the function to scan layers and create the images
update the display (should not be needed...)
| ( c)2009
it under the terms of the GNU General Public License version 3 or higher .
(define (delete-layer image)
(let* (
(name "")
(layer 0)
)
(while (>= i 0)
(let* (
)
(set! i (- i 1))
(if (string-ci=? "slice-" (substring name 0 6))
)
)
)
)
)
(define (manage-images image param-directory param-jpg-quality)
(let* (
(layer 0)
(flatten-layer 0)
(name "")
)
(while (>= i 0)
(let* (
)
(set! i (- i 1))
" slice- " is 6 , " .xxx " is 4 , any valid name will be at least 11 long
(if (string-ci=? "SLICE-" (substring name 0 6))
(let* (
(x (car (gimp-drawable-offsets layer)))
(y (cadr (gimp-drawable-offsets layer)))
(height (car (gimp-drawable-height layer)))
(width (car (gimp-drawable-width layer)))
(filename (substring name 6 (string-length name)))
(extension (substring filename (- (string-length filename) 4) (string-length filename)))
(newimage (car (gimp-image-duplicate image)))
)
(if (string-ci=? ".jpg" extension)
Progressive loading
Force baseline JPEG
)
(if (string-ci=? ".png" extension)
Adam7 interlacing
Write gAMA chunk
)
(gimp-message (string-append "Invalid file extension \"" extension "\"for filename \"" filename "\". Use .jpg or .png only."))
)
)
)
)
)
)
)
)
)
(define (script-fu-layers-slices
image
drawable
param-directory
param-jpg-quality)
(gimp-image-undo-group-end image)
)
Registering of the function in GIMP
(script-fu-register "script-fu-layers-slices"
"Layers Slices..."
"Create one image per layer named \"SLICE-xxx\".\
Each image will be cropped to the layer size, flatten\
and saved as xxx.\
Extension (.png or .jpg) must be specified."
"Robert Hendrickx"
"Robert Hendrickx"
"(c)2009 Robert Hendrickx"
"RGB* GRAY* INDEXED*"
SF-IMAGE "Image" 0
SF-DRAWABLE "Drawable" 0
SF-DIRNAME "Target directory" ""
SF-ADJUSTMENT "JPG Quality" '(90 0 100 1 10 0 SF-SLIDER)
)
(script-fu-menu-register "script-fu-layers-slices"
"<Image>/Filters/Web")
|
3bdb22acb1c1b1437f36671149951f1edb8bb08a35e0fb91aa6795f2a8cefe12 | acl2/acl2 | octal-digits-validation@useless-runes.lsp | (JAVA::GRAMMAR-OCT-DIGITP)
(JAVA::GRAMMAR-OCT-DIGITP-SUFF)
(JAVA::BOOLEANP-OF-GRAMMAR-OCT-DIGITP)
(JAVA::GRAMMAR-OCT-DIGITP)
(JAVA::SINGLETON-WHEN-GRAMMAR-OCT-DIGITP
(452 450 (:REWRITE DEFAULT-CAR))
(450 450 (:REWRITE CAR-WHEN-ALL-EQUALP))
(368 48 (:REWRITE ABNF::TREE-TERMINATEDP-OF-CAR-WHEN-TREE-LIST-TERMINATEDP))
(351 54 (:REWRITE ABNF::TREEP-WHEN-TREE-OPTIONP))
(304 80 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-OF-CAR-WHEN-TREE-LIST-LIST-TERMINATEDP))
(270 27 (:REWRITE ABNF::TREE-OPTIONP-WHEN-TREEP))
(182 180 (:REWRITE DEFAULT-CDR))
(160 160 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-SUBSETP-EQUAL))
(160 160 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-LIST-TERMINATEDP))
(134 134 (:REWRITE ABNF::TREE-TERMINATEDP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-TERMINATEDP))
(130 130 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-SUBSETP-EQUAL))
(108 108 (:REWRITE ABNF::TREEP-WHEN-MEMBER-EQUAL-OF-TREE-LISTP))
(81 81 (:TYPE-PRESCRIPTION ABNF::TREE-OPTIONP))
(80 80 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-NOT-CONSP))
(80 80 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-ATOM))
(70 65 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-NOT-CONSP))
(70 65 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-ATOM))
(54 54 (:REWRITE ABNF::TREEP-WHEN-PARSE-TREEP))
(54 54 (:REWRITE ABNF::TREEP-WHEN-IN-TREE-SETP-BINDS-FREE-X))
(54 54 (:REWRITE JAVA::ABNF-TREEP-WHEN-ABNF-TREE-WITH-ROOT-P))
(48 8 (:REWRITE ABNF::TREE-MATCH-ELEMENT-P-OF-CAR-WHEN-TREE-LIST-MATCH-ELEMENT-P))
(45 18 (:REWRITE LEN-WHEN-ATOM))
(38 33 (:REWRITE ABNF::TREE-LIST-LIST->STRING-WHEN-ATOM))
(32 32 (:REWRITE ABNF::TREE-LIST->STRING-WHEN-ATOM))
(18 18 (:REWRITE ABNF::TREE-MATCH-ELEMENT-P-WHEN-MEMBER-EQUAL-OF-TREE-LIST-MATCH-ELEMENT-P))
(16 16 (:TYPE-PRESCRIPTION ABNF::TREE-LIST-MATCH-ELEMENT-P))
(16 16 (:REWRITE-QUOTED-CONSTANT NFIX-UNDER-NAT-EQUIV))
(16 16 (:REWRITE-QUOTED-CONSTANT IFIX-UNDER-INT-EQUIV))
(16 16 (:REWRITE ABNF::TREE-LIST-MATCH-ELEMENT-P-WHEN-SUBSETP-EQUAL))
(8 8 (:REWRITE ABNF::TREE-LIST-MATCH-ELEMENT-P-WHEN-NOT-CONSP))
(4 4 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP))
(4 4 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2))
(4 4 (:LINEAR LEN-WHEN-PREFIXP))
(2 2 (:REWRITE JAVA::ABNF-TREE-WITH-ROOT-P-WHEN-MEMBER-EQUAL-OF-ABNF-TREE-LIST-WITH-ROOT-P))
(2 2 (:LINEAR INDEX-OF-<-LEN))
(1 1 (:REWRITE-QUOTED-CONSTANT ABNF::RULELIST-FIX-UNDER-RULELIST-EQUIV))
(1 1 (:REWRITE JAVA::GRAMMAR-OCT-DIGITP-SUFF))
)
(JAVA::OCT-DIGIT-TREE
(4 4 (:REWRITE JAVA::OCT-DIGITP-WHEN-MEMBER-EQUAL-OF-OCT-DIGIT-LISTP))
(4 4 (:REWRITE DEFAULT-<-2))
(4 4 (:REWRITE DEFAULT-<-1))
(2 2 (:REWRITE ABNF::TREEP-WHEN-PARSE-TREEP))
(2 2 (:REWRITE ABNF::TREEP-WHEN-IN-TREE-SETP-BINDS-FREE-X))
(2 2 (:REWRITE ABNF::TREE-LISTP-WHEN-SUBSETP-EQUAL))
(2 2 (:REWRITE ABNF::TREE-LISTP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-LISTP))
(2 2 (:REWRITE ABNF::TREE-LIST-LISTP-WHEN-SUBSETP-EQUAL))
(2 2 (:REWRITE JAVA::ABNF-TREEP-WHEN-ABNF-TREE-WITH-ROOT-P))
(1 1 (:TYPE-PRESCRIPTION JAVA::OCT-DIGIT-FIX))
(1 1 (:REWRITE-QUOTED-CONSTANT NAT-LIST-FIX-UNDER-NAT-LIST-EQUIV))
(1 1 (:REWRITE ABNF::TREE-LISTP-WHEN-NOT-CONSP))
(1 1 (:REWRITE ABNF::TREE-LIST-LISTP-WHEN-NOT-CONSP))
(1 1 (:REWRITE NAT-LISTP-WHEN-UNSIGNED-BYTE-LISTP))
(1 1 (:REWRITE JAVA::ABNF-TREE-LISTP-WHEN-ABNF-TREE-LIST-WITH-ROOT-P))
)
(JAVA::RETURN-TYPE-OF-OCT-DIGIT-TREE
(28 28 (:REWRITE DEFAULT-<-2))
(28 28 (:REWRITE DEFAULT-<-1))
(24 24 (:REWRITE DEFAULT-CDR))
(24 24 (:REWRITE DEFAULT-CAR))
(19 19 (:REWRITE-QUOTED-CONSTANT NFIX-UNDER-NAT-EQUIV))
(19 19 (:REWRITE-QUOTED-CONSTANT IFIX-UNDER-INT-EQUIV))
(18 18 (:REWRITE ABNF::TREE-MATCH-ELEMENT-P-WHEN-MEMBER-EQUAL-OF-TREE-LIST-MATCH-ELEMENT-P))
(18 3 (:REWRITE ABNF::TREEP-WHEN-TREE-OPTIONP))
(18 2 (:REWRITE JAVA::OCT-DIGIT-FIX-WHEN-OCT-DIGITP))
(9 3 (:REWRITE ABNF::TREE-OPTIONP-WHEN-TREEP))
(8 8 (:REWRITE JAVA::OCT-DIGITP-WHEN-MEMBER-EQUAL-OF-OCT-DIGIT-LISTP))
(6 6 (:TYPE-PRESCRIPTION ABNF::TREE-OPTIONP))
(4 4 (:REWRITE-QUOTED-CONSTANT ABNF::TREE-LIST-LIST-FIX-UNDER-TREE-LIST-LIST-EQUIV))
(4 4 (:REWRITE-QUOTED-CONSTANT ABNF::TREE-LIST-FIX-UNDER-TREE-LIST-EQUIV))
(4 4 (:REWRITE-QUOTED-CONSTANT NAT-LIST-FIX-UNDER-NAT-LIST-EQUIV))
(4 4 (:REWRITE ABNF::TREE-TERMINATEDP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-TERMINATEDP))
(4 4 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-SUBSETP-EQUAL))
(3 3 (:REWRITE-QUOTED-CONSTANT ABNF::RULENAME-OPTION-FIX-UNDER-RULENAME-OPTION-EQUIV))
(3 3 (:REWRITE ABNF::TREEP-WHEN-PARSE-TREEP))
(3 3 (:REWRITE ABNF::TREEP-WHEN-IN-TREE-SETP-BINDS-FREE-X))
(3 3 (:REWRITE JAVA::ABNF-TREEP-WHEN-ABNF-TREE-WITH-ROOT-P))
(2 2 (:TYPE-PRESCRIPTION JAVA::OCT-DIGITP))
(2 2 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-SUBSETP-EQUAL))
(2 2 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-LIST-TERMINATEDP))
(2 2 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-NOT-CONSP))
(2 2 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-ATOM))
(1 1 (:REWRITE-QUOTED-CONSTANT ABNF::RULELIST-FIX-UNDER-RULELIST-EQUIV))
(1 1 (:REWRITE-QUOTED-CONSTANT ABNF::ELEMENT-FIX-UNDER-ELEMENT-EQUIV))
(1 1 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-NOT-CONSP))
(1 1 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-ATOM))
)
(JAVA::TREE->STRING-OF-OCT-DIGIT-TREE
(10 2 (:REWRITE JAVA::OCT-DIGIT-FIX-WHEN-OCT-DIGITP))
(9 9 (:REWRITE DEFAULT-<-2))
(9 9 (:REWRITE DEFAULT-<-1))
(6 6 (:REWRITE JAVA::OCT-DIGITP-WHEN-MEMBER-EQUAL-OF-OCT-DIGIT-LISTP))
(6 1 (:REWRITE ABNF::TREEP-WHEN-TREE-OPTIONP))
(3 1 (:REWRITE ABNF::TREE-OPTIONP-WHEN-TREEP))
(2 2 (:TYPE-PRESCRIPTION ABNF::TREE-OPTIONP))
(2 2 (:REWRITE-QUOTED-CONSTANT ABNF::TREE-LIST-LIST-FIX-UNDER-TREE-LIST-LIST-EQUIV))
(2 2 (:REWRITE-QUOTED-CONSTANT ABNF::TREE-LIST-FIX-UNDER-TREE-LIST-EQUIV))
(2 2 (:REWRITE-QUOTED-CONSTANT NFIX-UNDER-NAT-EQUIV))
(2 2 (:REWRITE-QUOTED-CONSTANT NAT-LIST-FIX-UNDER-NAT-LIST-EQUIV))
(2 2 (:REWRITE-QUOTED-CONSTANT IFIX-UNDER-INT-EQUIV))
(1 1 (:TYPE-PRESCRIPTION JAVA::OCT-DIGITP))
(1 1 (:REWRITE-QUOTED-CONSTANT ABNF::RULENAME-OPTION-FIX-UNDER-RULENAME-OPTION-EQUIV))
(1 1 (:REWRITE ABNF::TREEP-WHEN-PARSE-TREEP))
(1 1 (:REWRITE ABNF::TREEP-WHEN-IN-TREE-SETP-BINDS-FREE-X))
(1 1 (:REWRITE ABNF::TREE-LIST-LIST->STRING-WHEN-ATOM))
(1 1 (:REWRITE JAVA::ABNF-TREEP-WHEN-ABNF-TREE-WITH-ROOT-P))
)
(JAVA::OCT-DIGIT-TREE-OF-OCT-DIGIT-FIX-DIGIT)
(JAVA::OCT-DIGIT-TREE-OCT-DIGIT-EQUIV-CONGRUENCE-ON-DIGIT)
(JAVA::GRAMMAR-OCT-DIGITP-WHEN-OCT-DIGITP)
(JAVA::LEMMA
(2201 1908 (:REWRITE DEFAULT-CDR))
(2045 1575 (:REWRITE DEFAULT-CAR))
(1575 1575 (:REWRITE CAR-WHEN-ALL-EQUALP))
(1568 98 (:REWRITE SET::SETS-ARE-TRUE-LISTS-CHEAP))
(1274 98 (:REWRITE TRUE-LISTP-WHEN-ATOM))
(1120 79 (:REWRITE ABNF::RULENAME-OPTIONP-WHEN-RULENAMEP))
(586 47 (:REWRITE ABNF::RULENAMEP-OF-CAR-WHEN-RULENAME-LISTP))
(576 80 (:REWRITE ABNF::TREEP-OF-CAR-WHEN-TREE-LISTP))
(497 497 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 2))
(497 497 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 1))
(497 497 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 2))
(497 497 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 1))
(497 497 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 2))
(497 497 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 1))
(497 497 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 2))
(497 497 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 1))
(497 497 (:REWRITE CONSP-BY-LEN))
(490 35 (:REWRITE JAVA::OCT-DIGITP-OF-CAR-WHEN-OCT-DIGIT-LISTP))
(448 32 (:REWRITE INTEGERP-OF-CAR-WHEN-INTEGER-LISTP))
(440 66 (:REWRITE NAT-LISTP-WHEN-NOT-CONSP))
(384 16 (:DEFINITION INTEGER-LISTP))
(368 128 (:REWRITE LEN-WHEN-ATOM))
(344 108 (:REWRITE ABNF::TREE-LISTP-OF-CAR-WHEN-TREE-LIST-LISTP))
(288 43 (:REWRITE ABNF::RULENAME-LISTP-OF-CDR-WHEN-RULENAME-LISTP))
(286 47 (:REWRITE ABNF::RULENAMEP-WHEN-RULENAME-OPTIONP))
(256 16 (:REWRITE NAT-LIST-FIX-WHEN-NAT-LISTP))
(248 248 (:REWRITE ABNF::TREE-LISTP-WHEN-SUBSETP-EQUAL))
(248 248 (:REWRITE ABNF::TREE-LISTP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-LISTP))
(246 246 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP))
(246 246 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2))
(246 246 (:LINEAR LEN-WHEN-PREFIXP))
(224 32 (:REWRITE INTEGER-LISTP-WHEN-NOT-CONSP))
(210 35 (:REWRITE JAVA::OCT-DIGIT-LISTP-WHEN-NOT-CONSP))
(204 204 (:REWRITE ABNF::TREEP-WHEN-MEMBER-EQUAL-OF-TREE-LISTP))
(200 200 (:REWRITE ABNF::TREE-LIST-LISTP-WHEN-SUBSETP-EQUAL))
(198 198 (:REWRITE CONSP-OF-CDR-BY-LEN))
(196 196 (:TYPE-PRESCRIPTION SET::SETP-TYPE))
(196 98 (:REWRITE ABNF::SETP-WHEN-TREE-SETP))
(196 98 (:REWRITE ABNF::SETP-WHEN-RULENAME-SETP))
(196 98 (:REWRITE SET::SETP-WHEN-NAT-SETP))
(196 98 (:REWRITE OMAP::SETP-WHEN-MAPP))
(196 98 (:REWRITE SET::SETP-WHEN-INTEGER-SETP))
(196 98 (:REWRITE SET::NONEMPTY-MEANS-SET))
(172 172 (:REWRITE ABNF::RULENAME-LISTP-WHEN-SUBSETP-EQUAL))
(144 86 (:REWRITE ABNF::RULENAME-LISTP-WHEN-NOT-CONSP))
(124 124 (:TYPE-PRESCRIPTION ABNF::RULENAMEP))
(124 124 (:REWRITE JAVA::ABNF-TREE-LISTP-WHEN-ABNF-TREE-LIST-WITH-ROOT-P))
(123 123 (:LINEAR INDEX-OF-<-LEN))
(110 110 (:REWRITE ABNF::TREEP-WHEN-PARSE-TREEP))
(110 110 (:REWRITE ABNF::TREEP-WHEN-IN-TREE-SETP-BINDS-FREE-X))
(110 110 (:REWRITE JAVA::ABNF-TREEP-WHEN-ABNF-TREE-WITH-ROOT-P))
(98 98 (:TYPE-PRESCRIPTION ABNF::TREE-SETP))
(98 98 (:TYPE-PRESCRIPTION ABNF::RULENAME-SETP))
(98 98 (:TYPE-PRESCRIPTION SET::NAT-SETP))
(98 98 (:TYPE-PRESCRIPTION OMAP::MAPP))
(98 98 (:TYPE-PRESCRIPTION SET::INTEGER-SETP))
(98 98 (:TYPE-PRESCRIPTION SET::EMPTY-TYPE))
(98 98 (:REWRITE TRUE-LISTP-WHEN-UNSIGNED-BYTE-LISTP))
(98 98 (:REWRITE TRUE-LISTP-WHEN-SIGNED-BYTE-LISTP))
(98 98 (:REWRITE JAVA::TRUE-LISTP-WHEN-ABNF-TREE-LIST-WITH-ROOT-P))
(98 98 (:REWRITE SET::IN-SET))
(96 16 (:REWRITE ABNF::TREE-MATCH-ELEMENT-P-OF-CAR-WHEN-TREE-LIST-MATCH-ELEMENT-P))
(94 94 (:REWRITE ABNF::RULENAMEP-WHEN-MEMBER-EQUAL-OF-RULENAME-LISTP))
(94 94 (:REWRITE ABNF::RULENAMEP-OF-CAR-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP))
(70 70 (:REWRITE JAVA::OCT-DIGITP-WHEN-MEMBER-EQUAL-OF-OCT-DIGIT-LISTP))
(70 70 (:REWRITE JAVA::OCT-DIGIT-LISTP-WHEN-SUBSETP-EQUAL))
(68 68 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-SUBSETP-EQUAL))
(68 34 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-NOT-CONSP))
(68 34 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-ATOM))
(66 66 (:REWRITE NAT-LISTP-WHEN-UNSIGNED-BYTE-LISTP))
(48 4 (:REWRITE ABNF::TREE-LIST-LIST-FIX-UNDER-IFF))
(47 47 (:REWRITE ABNF::RULENAMEP-WHEN-IN-RULENAME-SETP-BINDS-FREE-X))
(34 34 (:REWRITE ABNF::TREE-MATCH-ELEMENT-P-WHEN-MEMBER-EQUAL-OF-TREE-LIST-MATCH-ELEMENT-P))
(32 32 (:TYPE-PRESCRIPTION ABNF::TREE-LIST-MATCH-ELEMENT-P))
(32 32 (:REWRITE-QUOTED-CONSTANT NFIX-UNDER-NAT-EQUIV))
(32 32 (:REWRITE-QUOTED-CONSTANT IFIX-UNDER-INT-EQUIV))
(32 32 (:REWRITE ABNF::TREE-LIST-MATCH-ELEMENT-P-WHEN-SUBSETP-EQUAL))
(32 16 (:REWRITE INTEGER-LISTP-OF-CDR-WHEN-INTEGER-LISTP))
(22 22 (:REWRITE ABNF::TREE-TERMINATEDP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-TERMINATEDP))
(16 16 (:TYPE-PRESCRIPTION ABNF::TREE-LIST-LIST-FIX$INLINE))
(16 16 (:REWRITE ABNF::TREE-LIST-MATCH-ELEMENT-P-WHEN-NOT-CONSP))
(16 16 (:REWRITE DEFAULT-<-2))
(16 16 (:REWRITE DEFAULT-<-1))
(11 11 (:REWRITE ABNF::RULENAME-OPTION-FIX-WHEN-NONE))
(8 4 (:REWRITE ABNF::TREE-LIST-LISTP-OF-CDR-WHEN-TREE-LIST-LISTP))
(5 5 (:REWRITE CONSP-OF-CDDR-BY-LEN))
(2 2 (:REWRITE-QUOTED-CONSTANT ABNF::RULELIST-FIX-UNDER-RULELIST-EQUIV))
(1 1 (:REWRITE-QUOTED-CONSTANT ABNF::ELEMENT-FIX-UNDER-ELEMENT-EQUIV))
(1 1 (:REWRITE-QUOTED-CONSTANT ABNF::ALTERNATION-FIX-UNDER-ALTERNATION-EQUIV))
)
(JAVA::OCT-DIGITP-WHEN-GRAMMAR-OCT-DIGITP
(48 3 (:REWRITE JAVA::OCT-DIGITP-OF-CAR-WHEN-OCT-DIGIT-LISTP))
(30 3 (:REWRITE JAVA::OCT-DIGIT-LISTP-WHEN-NOT-CONSP))
(30 3 (:REWRITE DEFAULT-CAR))
(6 6 (:TYPE-PRESCRIPTION JAVA::OCT-DIGIT-LISTP))
(6 6 (:REWRITE JAVA::OCT-DIGITP-WHEN-MEMBER-EQUAL-OF-OCT-DIGIT-LISTP))
(6 6 (:REWRITE JAVA::OCT-DIGIT-LISTP-WHEN-SUBSETP-EQUAL))
(6 6 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 2))
(6 6 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 1))
(6 6 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 2))
(6 6 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 1))
(6 6 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 2))
(6 6 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 1))
(6 6 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 2))
(6 6 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 1))
(6 6 (:REWRITE JAVA::ABNF-TREE-WITH-ROOT-P-WHEN-MEMBER-EQUAL-OF-ABNF-TREE-LIST-WITH-ROOT-P))
)
(JAVA::OCT-DIGITP-IS-GRAMMAR-OCT-DIGITP
(2 2 (:REWRITE JAVA::OCT-DIGITP-WHEN-MEMBER-EQUAL-OF-OCT-DIGIT-LISTP))
)
| null | https://raw.githubusercontent.com/acl2/acl2/f64742cc6d41c35f9d3f94e154cd5fd409105d34/books/kestrel/java/language/.sys/octal-digits-validation%40useless-runes.lsp | lisp | (JAVA::GRAMMAR-OCT-DIGITP)
(JAVA::GRAMMAR-OCT-DIGITP-SUFF)
(JAVA::BOOLEANP-OF-GRAMMAR-OCT-DIGITP)
(JAVA::GRAMMAR-OCT-DIGITP)
(JAVA::SINGLETON-WHEN-GRAMMAR-OCT-DIGITP
(452 450 (:REWRITE DEFAULT-CAR))
(450 450 (:REWRITE CAR-WHEN-ALL-EQUALP))
(368 48 (:REWRITE ABNF::TREE-TERMINATEDP-OF-CAR-WHEN-TREE-LIST-TERMINATEDP))
(351 54 (:REWRITE ABNF::TREEP-WHEN-TREE-OPTIONP))
(304 80 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-OF-CAR-WHEN-TREE-LIST-LIST-TERMINATEDP))
(270 27 (:REWRITE ABNF::TREE-OPTIONP-WHEN-TREEP))
(182 180 (:REWRITE DEFAULT-CDR))
(160 160 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-SUBSETP-EQUAL))
(160 160 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-LIST-TERMINATEDP))
(134 134 (:REWRITE ABNF::TREE-TERMINATEDP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-TERMINATEDP))
(130 130 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-SUBSETP-EQUAL))
(108 108 (:REWRITE ABNF::TREEP-WHEN-MEMBER-EQUAL-OF-TREE-LISTP))
(81 81 (:TYPE-PRESCRIPTION ABNF::TREE-OPTIONP))
(80 80 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-NOT-CONSP))
(80 80 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-ATOM))
(70 65 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-NOT-CONSP))
(70 65 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-ATOM))
(54 54 (:REWRITE ABNF::TREEP-WHEN-PARSE-TREEP))
(54 54 (:REWRITE ABNF::TREEP-WHEN-IN-TREE-SETP-BINDS-FREE-X))
(54 54 (:REWRITE JAVA::ABNF-TREEP-WHEN-ABNF-TREE-WITH-ROOT-P))
(48 8 (:REWRITE ABNF::TREE-MATCH-ELEMENT-P-OF-CAR-WHEN-TREE-LIST-MATCH-ELEMENT-P))
(45 18 (:REWRITE LEN-WHEN-ATOM))
(38 33 (:REWRITE ABNF::TREE-LIST-LIST->STRING-WHEN-ATOM))
(32 32 (:REWRITE ABNF::TREE-LIST->STRING-WHEN-ATOM))
(18 18 (:REWRITE ABNF::TREE-MATCH-ELEMENT-P-WHEN-MEMBER-EQUAL-OF-TREE-LIST-MATCH-ELEMENT-P))
(16 16 (:TYPE-PRESCRIPTION ABNF::TREE-LIST-MATCH-ELEMENT-P))
(16 16 (:REWRITE-QUOTED-CONSTANT NFIX-UNDER-NAT-EQUIV))
(16 16 (:REWRITE-QUOTED-CONSTANT IFIX-UNDER-INT-EQUIV))
(16 16 (:REWRITE ABNF::TREE-LIST-MATCH-ELEMENT-P-WHEN-SUBSETP-EQUAL))
(8 8 (:REWRITE ABNF::TREE-LIST-MATCH-ELEMENT-P-WHEN-NOT-CONSP))
(4 4 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP))
(4 4 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2))
(4 4 (:LINEAR LEN-WHEN-PREFIXP))
(2 2 (:REWRITE JAVA::ABNF-TREE-WITH-ROOT-P-WHEN-MEMBER-EQUAL-OF-ABNF-TREE-LIST-WITH-ROOT-P))
(2 2 (:LINEAR INDEX-OF-<-LEN))
(1 1 (:REWRITE-QUOTED-CONSTANT ABNF::RULELIST-FIX-UNDER-RULELIST-EQUIV))
(1 1 (:REWRITE JAVA::GRAMMAR-OCT-DIGITP-SUFF))
)
(JAVA::OCT-DIGIT-TREE
(4 4 (:REWRITE JAVA::OCT-DIGITP-WHEN-MEMBER-EQUAL-OF-OCT-DIGIT-LISTP))
(4 4 (:REWRITE DEFAULT-<-2))
(4 4 (:REWRITE DEFAULT-<-1))
(2 2 (:REWRITE ABNF::TREEP-WHEN-PARSE-TREEP))
(2 2 (:REWRITE ABNF::TREEP-WHEN-IN-TREE-SETP-BINDS-FREE-X))
(2 2 (:REWRITE ABNF::TREE-LISTP-WHEN-SUBSETP-EQUAL))
(2 2 (:REWRITE ABNF::TREE-LISTP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-LISTP))
(2 2 (:REWRITE ABNF::TREE-LIST-LISTP-WHEN-SUBSETP-EQUAL))
(2 2 (:REWRITE JAVA::ABNF-TREEP-WHEN-ABNF-TREE-WITH-ROOT-P))
(1 1 (:TYPE-PRESCRIPTION JAVA::OCT-DIGIT-FIX))
(1 1 (:REWRITE-QUOTED-CONSTANT NAT-LIST-FIX-UNDER-NAT-LIST-EQUIV))
(1 1 (:REWRITE ABNF::TREE-LISTP-WHEN-NOT-CONSP))
(1 1 (:REWRITE ABNF::TREE-LIST-LISTP-WHEN-NOT-CONSP))
(1 1 (:REWRITE NAT-LISTP-WHEN-UNSIGNED-BYTE-LISTP))
(1 1 (:REWRITE JAVA::ABNF-TREE-LISTP-WHEN-ABNF-TREE-LIST-WITH-ROOT-P))
)
(JAVA::RETURN-TYPE-OF-OCT-DIGIT-TREE
(28 28 (:REWRITE DEFAULT-<-2))
(28 28 (:REWRITE DEFAULT-<-1))
(24 24 (:REWRITE DEFAULT-CDR))
(24 24 (:REWRITE DEFAULT-CAR))
(19 19 (:REWRITE-QUOTED-CONSTANT NFIX-UNDER-NAT-EQUIV))
(19 19 (:REWRITE-QUOTED-CONSTANT IFIX-UNDER-INT-EQUIV))
(18 18 (:REWRITE ABNF::TREE-MATCH-ELEMENT-P-WHEN-MEMBER-EQUAL-OF-TREE-LIST-MATCH-ELEMENT-P))
(18 3 (:REWRITE ABNF::TREEP-WHEN-TREE-OPTIONP))
(18 2 (:REWRITE JAVA::OCT-DIGIT-FIX-WHEN-OCT-DIGITP))
(9 3 (:REWRITE ABNF::TREE-OPTIONP-WHEN-TREEP))
(8 8 (:REWRITE JAVA::OCT-DIGITP-WHEN-MEMBER-EQUAL-OF-OCT-DIGIT-LISTP))
(6 6 (:TYPE-PRESCRIPTION ABNF::TREE-OPTIONP))
(4 4 (:REWRITE-QUOTED-CONSTANT ABNF::TREE-LIST-LIST-FIX-UNDER-TREE-LIST-LIST-EQUIV))
(4 4 (:REWRITE-QUOTED-CONSTANT ABNF::TREE-LIST-FIX-UNDER-TREE-LIST-EQUIV))
(4 4 (:REWRITE-QUOTED-CONSTANT NAT-LIST-FIX-UNDER-NAT-LIST-EQUIV))
(4 4 (:REWRITE ABNF::TREE-TERMINATEDP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-TERMINATEDP))
(4 4 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-SUBSETP-EQUAL))
(3 3 (:REWRITE-QUOTED-CONSTANT ABNF::RULENAME-OPTION-FIX-UNDER-RULENAME-OPTION-EQUIV))
(3 3 (:REWRITE ABNF::TREEP-WHEN-PARSE-TREEP))
(3 3 (:REWRITE ABNF::TREEP-WHEN-IN-TREE-SETP-BINDS-FREE-X))
(3 3 (:REWRITE JAVA::ABNF-TREEP-WHEN-ABNF-TREE-WITH-ROOT-P))
(2 2 (:TYPE-PRESCRIPTION JAVA::OCT-DIGITP))
(2 2 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-SUBSETP-EQUAL))
(2 2 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-LIST-TERMINATEDP))
(2 2 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-NOT-CONSP))
(2 2 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-ATOM))
(1 1 (:REWRITE-QUOTED-CONSTANT ABNF::RULELIST-FIX-UNDER-RULELIST-EQUIV))
(1 1 (:REWRITE-QUOTED-CONSTANT ABNF::ELEMENT-FIX-UNDER-ELEMENT-EQUIV))
(1 1 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-NOT-CONSP))
(1 1 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-ATOM))
)
(JAVA::TREE->STRING-OF-OCT-DIGIT-TREE
(10 2 (:REWRITE JAVA::OCT-DIGIT-FIX-WHEN-OCT-DIGITP))
(9 9 (:REWRITE DEFAULT-<-2))
(9 9 (:REWRITE DEFAULT-<-1))
(6 6 (:REWRITE JAVA::OCT-DIGITP-WHEN-MEMBER-EQUAL-OF-OCT-DIGIT-LISTP))
(6 1 (:REWRITE ABNF::TREEP-WHEN-TREE-OPTIONP))
(3 1 (:REWRITE ABNF::TREE-OPTIONP-WHEN-TREEP))
(2 2 (:TYPE-PRESCRIPTION ABNF::TREE-OPTIONP))
(2 2 (:REWRITE-QUOTED-CONSTANT ABNF::TREE-LIST-LIST-FIX-UNDER-TREE-LIST-LIST-EQUIV))
(2 2 (:REWRITE-QUOTED-CONSTANT ABNF::TREE-LIST-FIX-UNDER-TREE-LIST-EQUIV))
(2 2 (:REWRITE-QUOTED-CONSTANT NFIX-UNDER-NAT-EQUIV))
(2 2 (:REWRITE-QUOTED-CONSTANT NAT-LIST-FIX-UNDER-NAT-LIST-EQUIV))
(2 2 (:REWRITE-QUOTED-CONSTANT IFIX-UNDER-INT-EQUIV))
(1 1 (:TYPE-PRESCRIPTION JAVA::OCT-DIGITP))
(1 1 (:REWRITE-QUOTED-CONSTANT ABNF::RULENAME-OPTION-FIX-UNDER-RULENAME-OPTION-EQUIV))
(1 1 (:REWRITE ABNF::TREEP-WHEN-PARSE-TREEP))
(1 1 (:REWRITE ABNF::TREEP-WHEN-IN-TREE-SETP-BINDS-FREE-X))
(1 1 (:REWRITE ABNF::TREE-LIST-LIST->STRING-WHEN-ATOM))
(1 1 (:REWRITE JAVA::ABNF-TREEP-WHEN-ABNF-TREE-WITH-ROOT-P))
)
(JAVA::OCT-DIGIT-TREE-OF-OCT-DIGIT-FIX-DIGIT)
(JAVA::OCT-DIGIT-TREE-OCT-DIGIT-EQUIV-CONGRUENCE-ON-DIGIT)
(JAVA::GRAMMAR-OCT-DIGITP-WHEN-OCT-DIGITP)
(JAVA::LEMMA
(2201 1908 (:REWRITE DEFAULT-CDR))
(2045 1575 (:REWRITE DEFAULT-CAR))
(1575 1575 (:REWRITE CAR-WHEN-ALL-EQUALP))
(1568 98 (:REWRITE SET::SETS-ARE-TRUE-LISTS-CHEAP))
(1274 98 (:REWRITE TRUE-LISTP-WHEN-ATOM))
(1120 79 (:REWRITE ABNF::RULENAME-OPTIONP-WHEN-RULENAMEP))
(586 47 (:REWRITE ABNF::RULENAMEP-OF-CAR-WHEN-RULENAME-LISTP))
(576 80 (:REWRITE ABNF::TREEP-OF-CAR-WHEN-TREE-LISTP))
(497 497 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 2))
(497 497 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 1))
(497 497 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 2))
(497 497 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 1))
(497 497 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 2))
(497 497 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 1))
(497 497 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 2))
(497 497 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 1))
(497 497 (:REWRITE CONSP-BY-LEN))
(490 35 (:REWRITE JAVA::OCT-DIGITP-OF-CAR-WHEN-OCT-DIGIT-LISTP))
(448 32 (:REWRITE INTEGERP-OF-CAR-WHEN-INTEGER-LISTP))
(440 66 (:REWRITE NAT-LISTP-WHEN-NOT-CONSP))
(384 16 (:DEFINITION INTEGER-LISTP))
(368 128 (:REWRITE LEN-WHEN-ATOM))
(344 108 (:REWRITE ABNF::TREE-LISTP-OF-CAR-WHEN-TREE-LIST-LISTP))
(288 43 (:REWRITE ABNF::RULENAME-LISTP-OF-CDR-WHEN-RULENAME-LISTP))
(286 47 (:REWRITE ABNF::RULENAMEP-WHEN-RULENAME-OPTIONP))
(256 16 (:REWRITE NAT-LIST-FIX-WHEN-NAT-LISTP))
(248 248 (:REWRITE ABNF::TREE-LISTP-WHEN-SUBSETP-EQUAL))
(248 248 (:REWRITE ABNF::TREE-LISTP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-LISTP))
(246 246 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP))
(246 246 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2))
(246 246 (:LINEAR LEN-WHEN-PREFIXP))
(224 32 (:REWRITE INTEGER-LISTP-WHEN-NOT-CONSP))
(210 35 (:REWRITE JAVA::OCT-DIGIT-LISTP-WHEN-NOT-CONSP))
(204 204 (:REWRITE ABNF::TREEP-WHEN-MEMBER-EQUAL-OF-TREE-LISTP))
(200 200 (:REWRITE ABNF::TREE-LIST-LISTP-WHEN-SUBSETP-EQUAL))
(198 198 (:REWRITE CONSP-OF-CDR-BY-LEN))
(196 196 (:TYPE-PRESCRIPTION SET::SETP-TYPE))
(196 98 (:REWRITE ABNF::SETP-WHEN-TREE-SETP))
(196 98 (:REWRITE ABNF::SETP-WHEN-RULENAME-SETP))
(196 98 (:REWRITE SET::SETP-WHEN-NAT-SETP))
(196 98 (:REWRITE OMAP::SETP-WHEN-MAPP))
(196 98 (:REWRITE SET::SETP-WHEN-INTEGER-SETP))
(196 98 (:REWRITE SET::NONEMPTY-MEANS-SET))
(172 172 (:REWRITE ABNF::RULENAME-LISTP-WHEN-SUBSETP-EQUAL))
(144 86 (:REWRITE ABNF::RULENAME-LISTP-WHEN-NOT-CONSP))
(124 124 (:TYPE-PRESCRIPTION ABNF::RULENAMEP))
(124 124 (:REWRITE JAVA::ABNF-TREE-LISTP-WHEN-ABNF-TREE-LIST-WITH-ROOT-P))
(123 123 (:LINEAR INDEX-OF-<-LEN))
(110 110 (:REWRITE ABNF::TREEP-WHEN-PARSE-TREEP))
(110 110 (:REWRITE ABNF::TREEP-WHEN-IN-TREE-SETP-BINDS-FREE-X))
(110 110 (:REWRITE JAVA::ABNF-TREEP-WHEN-ABNF-TREE-WITH-ROOT-P))
(98 98 (:TYPE-PRESCRIPTION ABNF::TREE-SETP))
(98 98 (:TYPE-PRESCRIPTION ABNF::RULENAME-SETP))
(98 98 (:TYPE-PRESCRIPTION SET::NAT-SETP))
(98 98 (:TYPE-PRESCRIPTION OMAP::MAPP))
(98 98 (:TYPE-PRESCRIPTION SET::INTEGER-SETP))
(98 98 (:TYPE-PRESCRIPTION SET::EMPTY-TYPE))
(98 98 (:REWRITE TRUE-LISTP-WHEN-UNSIGNED-BYTE-LISTP))
(98 98 (:REWRITE TRUE-LISTP-WHEN-SIGNED-BYTE-LISTP))
(98 98 (:REWRITE JAVA::TRUE-LISTP-WHEN-ABNF-TREE-LIST-WITH-ROOT-P))
(98 98 (:REWRITE SET::IN-SET))
(96 16 (:REWRITE ABNF::TREE-MATCH-ELEMENT-P-OF-CAR-WHEN-TREE-LIST-MATCH-ELEMENT-P))
(94 94 (:REWRITE ABNF::RULENAMEP-WHEN-MEMBER-EQUAL-OF-RULENAME-LISTP))
(94 94 (:REWRITE ABNF::RULENAMEP-OF-CAR-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP))
(70 70 (:REWRITE JAVA::OCT-DIGITP-WHEN-MEMBER-EQUAL-OF-OCT-DIGIT-LISTP))
(70 70 (:REWRITE JAVA::OCT-DIGIT-LISTP-WHEN-SUBSETP-EQUAL))
(68 68 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-SUBSETP-EQUAL))
(68 34 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-NOT-CONSP))
(68 34 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-ATOM))
(66 66 (:REWRITE NAT-LISTP-WHEN-UNSIGNED-BYTE-LISTP))
(48 4 (:REWRITE ABNF::TREE-LIST-LIST-FIX-UNDER-IFF))
(47 47 (:REWRITE ABNF::RULENAMEP-WHEN-IN-RULENAME-SETP-BINDS-FREE-X))
(34 34 (:REWRITE ABNF::TREE-MATCH-ELEMENT-P-WHEN-MEMBER-EQUAL-OF-TREE-LIST-MATCH-ELEMENT-P))
(32 32 (:TYPE-PRESCRIPTION ABNF::TREE-LIST-MATCH-ELEMENT-P))
(32 32 (:REWRITE-QUOTED-CONSTANT NFIX-UNDER-NAT-EQUIV))
(32 32 (:REWRITE-QUOTED-CONSTANT IFIX-UNDER-INT-EQUIV))
(32 32 (:REWRITE ABNF::TREE-LIST-MATCH-ELEMENT-P-WHEN-SUBSETP-EQUAL))
(32 16 (:REWRITE INTEGER-LISTP-OF-CDR-WHEN-INTEGER-LISTP))
(22 22 (:REWRITE ABNF::TREE-TERMINATEDP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-TERMINATEDP))
(16 16 (:TYPE-PRESCRIPTION ABNF::TREE-LIST-LIST-FIX$INLINE))
(16 16 (:REWRITE ABNF::TREE-LIST-MATCH-ELEMENT-P-WHEN-NOT-CONSP))
(16 16 (:REWRITE DEFAULT-<-2))
(16 16 (:REWRITE DEFAULT-<-1))
(11 11 (:REWRITE ABNF::RULENAME-OPTION-FIX-WHEN-NONE))
(8 4 (:REWRITE ABNF::TREE-LIST-LISTP-OF-CDR-WHEN-TREE-LIST-LISTP))
(5 5 (:REWRITE CONSP-OF-CDDR-BY-LEN))
(2 2 (:REWRITE-QUOTED-CONSTANT ABNF::RULELIST-FIX-UNDER-RULELIST-EQUIV))
(1 1 (:REWRITE-QUOTED-CONSTANT ABNF::ELEMENT-FIX-UNDER-ELEMENT-EQUIV))
(1 1 (:REWRITE-QUOTED-CONSTANT ABNF::ALTERNATION-FIX-UNDER-ALTERNATION-EQUIV))
)
(JAVA::OCT-DIGITP-WHEN-GRAMMAR-OCT-DIGITP
(48 3 (:REWRITE JAVA::OCT-DIGITP-OF-CAR-WHEN-OCT-DIGIT-LISTP))
(30 3 (:REWRITE JAVA::OCT-DIGIT-LISTP-WHEN-NOT-CONSP))
(30 3 (:REWRITE DEFAULT-CAR))
(6 6 (:TYPE-PRESCRIPTION JAVA::OCT-DIGIT-LISTP))
(6 6 (:REWRITE JAVA::OCT-DIGITP-WHEN-MEMBER-EQUAL-OF-OCT-DIGIT-LISTP))
(6 6 (:REWRITE JAVA::OCT-DIGIT-LISTP-WHEN-SUBSETP-EQUAL))
(6 6 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 2))
(6 6 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 1))
(6 6 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 2))
(6 6 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 1))
(6 6 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 2))
(6 6 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 1))
(6 6 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 2))
(6 6 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 1))
(6 6 (:REWRITE JAVA::ABNF-TREE-WITH-ROOT-P-WHEN-MEMBER-EQUAL-OF-ABNF-TREE-LIST-WITH-ROOT-P))
)
(JAVA::OCT-DIGITP-IS-GRAMMAR-OCT-DIGITP
(2 2 (:REWRITE JAVA::OCT-DIGITP-WHEN-MEMBER-EQUAL-OF-OCT-DIGIT-LISTP))
)
| |
82477e2cd194761fbf62e4bdb95b52e3dcbbcbd1978391727d6207c891d08d69 | input-output-hk/plutus-apps | Playground.hs | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TypeApplications #
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
module Plutus.Trace.Playground(
PlaygroundTrace
-- * Constructing traces
, Waiting.waitUntilSlot
, Waiting.waitNSlots
, Waiting.nextSlot
, EmulatedWalletAPI.payToWallet
, RunContractPlayground.callEndpoint
-- * Running traces
, EmulatorConfig(..)
, initialChainState
, runPlaygroundStream
-- * Interpreter
, interpretPlaygroundTrace
, walletInstanceTag
) where
import Control.Lens
import Control.Monad (void)
import Control.Monad.Freer (Eff, Member, interpret, raise, reinterpret, subsume)
import Control.Monad.Freer.Coroutine (Yield)
import Control.Monad.Freer.Error (Error, handleError, throwError)
import Control.Monad.Freer.Extras.Log (LogMessage, LogMsg (..), mapLog)
import Control.Monad.Freer.Extras.Modify (raiseEnd)
import Control.Monad.Freer.Reader (Reader)
import Control.Monad.Freer.State (State, evalState)
import Data.Aeson qualified as JSON
import Data.Foldable (traverse_)
import Data.Map (Map)
import Data.Map qualified as Map
import Data.Maybe (fromMaybe)
import Cardano.Node.Emulator.Chain (ChainControlEffect)
import Cardano.Node.Emulator.Params (pNetworkId, pSlotConfig)
import Plutus.Contract (Contract (..))
import Plutus.Trace.Effects.ContractInstanceId (ContractInstanceIdEff, handleDeterministicIds)
import Plutus.Trace.Effects.EmulatedWalletAPI (EmulatedWalletAPI, handleEmulatedWalletAPI)
import Plutus.Trace.Effects.EmulatedWalletAPI qualified as EmulatedWalletAPI
import Plutus.Trace.Effects.RunContractPlayground (RunContractPlayground, handleRunContractPlayground)
import Plutus.Trace.Effects.RunContractPlayground qualified as RunContractPlayground
import Plutus.Trace.Effects.Waiting (Waiting, handleWaiting)
import Plutus.Trace.Effects.Waiting qualified as Waiting
import Plutus.Trace.Emulator.ContractInstance (EmulatorRuntimeError)
import Plutus.Trace.Emulator.System (launchSystemThreads)
import Plutus.Trace.Emulator.Types (ContractConstraints, EmulatorMessage (..),
EmulatorRuntimeError (EmulatedWalletError), EmulatorThreads, walletInstanceTag)
import Plutus.Trace.Scheduler (EmSystemCall, ThreadId, exit, runThreads)
import Streaming (Stream)
import Streaming.Prelude (Of)
import Wallet.Emulator.MultiAgent (EmulatorEvent, EmulatorEvent' (..), EmulatorState, MultiAgentControlEffect,
MultiAgentEffect, schedulerEvent)
import Wallet.Emulator.Stream (EmulatorConfig (..), EmulatorErr (..), initialChainState, runTraceStream)
import Wallet.Emulator.Wallet (Wallet (..), knownWallets)
import Wallet.Types (ContractInstanceId)
Note [ Playground traces ]
The list of effects we can use in traces for the playground is slightly
different from that for regular traces :
* There is only a single contract
* We do n't need to start contract instances manually ( see note
[ Wallet contract instances ] )
* We have fewer actions . Only " call endpoint " and " wait " are supported in the
UI .
Therefore we can get by with a smaller list of effects for the ' PlaygroundTrace '
type .
Of particular note is the absence of
' . Trace . Effects . EmulatorControl . EmulatorControl ' . This means that we can ,
theoretically , run playground traces not just against the simulated environment
but also against a live system . See note [ The EmulatorControl effect ]
The list of effects we can use in traces for the Plutus playground is slightly
different from that for regular traces:
* There is only a single contract
* We don't need to start contract instances manually (see note
[Wallet contract instances])
* We have fewer actions. Only "call endpoint" and "wait" are supported in the
UI.
Therefore we can get by with a smaller list of effects for the 'PlaygroundTrace'
type.
Of particular note is the absence of
'Plutus.Trace.Effects.EmulatorControl.EmulatorControl'. This means that we can,
theoretically, run playground traces not just against the simulated environment
but also against a live system. See note [The EmulatorControl effect]
-}
type PlaygroundTrace a =
Eff
'[ RunContractPlayground
, Error EmulatorRuntimeError
, Waiting
, EmulatedWalletAPI
] a
handlePlaygroundTrace ::
forall w s e effs a.
( ContractConstraints s
, Show e
, JSON.ToJSON e
, JSON.ToJSON w
, Monoid w
, Member MultiAgentEffect effs
, Member (LogMsg EmulatorEvent') effs
, Member (Error EmulatorRuntimeError) effs
, Member (State (Map Wallet ContractInstanceId)) effs
, Member (State EmulatorThreads) effs
, Member ContractInstanceIdEff effs
)
=> EmulatorConfig
-> Contract w s e ()
-> PlaygroundTrace a
-> Eff (Reader ThreadId ': Yield (EmSystemCall effs EmulatorMessage a) (Maybe EmulatorMessage) ': effs) ()
handlePlaygroundTrace conf contract action = do
result <- flip handleError (throwError . EmulatedWalletError)
. reinterpret handleEmulatedWalletAPI
. interpret (handleWaiting @_ @effs @a (pSlotConfig $ _params conf))
. subsume
. interpret (handleRunContractPlayground @w @s @e @_ @effs @a (pNetworkId $ _params conf) contract)
$ raiseEnd action
void $ exit @effs @EmulatorMessage result
| Run a ' Trace Playground ' , streaming the log messages as they arrive
runPlaygroundStream :: forall w s e effs a.
( ContractConstraints s
, Show e
, JSON.ToJSON e
, JSON.ToJSON w
, Monoid w
)
=> EmulatorConfig
-> Contract w s e ()
-> PlaygroundTrace a
-> Stream (Of (LogMessage EmulatorEvent)) (Eff effs) (Either EmulatorErr a, EmulatorState)
runPlaygroundStream conf contract =
let wallets = fromMaybe knownWallets (preview (initialChainState . _Left . to Map.keys) conf)
in runTraceStream conf . interpretPlaygroundTrace conf contract wallets
interpretPlaygroundTrace :: forall w s e effs a.
( Member MultiAgentEffect effs
, Member MultiAgentControlEffect effs
, Member (Error EmulatorRuntimeError) effs
, Member ChainControlEffect effs
, Member (LogMsg EmulatorEvent') effs
, ContractConstraints s
, Show e
, JSON.ToJSON e
, JSON.ToJSON w
, Monoid w
)
=> EmulatorConfig
-> Contract w s e () -- ^ The contract
-> [Wallet] -- ^ Wallets that should be simulated in the emulator
-> PlaygroundTrace a
-> Eff effs (Maybe a)
interpretPlaygroundTrace conf contract wallets action =
evalState @EmulatorThreads mempty
$ evalState @(Map Wallet ContractInstanceId) Map.empty
$ handleDeterministicIds
$ interpret (mapLog (review schedulerEvent))
$ runThreads
$ do
raise $ launchSystemThreads wallets
handlePlaygroundTrace conf contract $ do
void Waiting.nextSlot
traverse_ RunContractPlayground.launchContract wallets
action
| null | https://raw.githubusercontent.com/input-output-hk/plutus-apps/8706e6c7c525b4973a7b6d2ed7c9d0ef9cd4ef46/plutus-contract/src/Plutus/Trace/Playground.hs | haskell | # LANGUAGE GADTs #
# LANGUAGE OverloadedStrings #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
* Constructing traces
* Running traces
* Interpreter
^ The contract
^ Wallets that should be simulated in the emulator | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE TypeApplications #
module Plutus.Trace.Playground(
PlaygroundTrace
, Waiting.waitUntilSlot
, Waiting.waitNSlots
, Waiting.nextSlot
, EmulatedWalletAPI.payToWallet
, RunContractPlayground.callEndpoint
, EmulatorConfig(..)
, initialChainState
, runPlaygroundStream
, interpretPlaygroundTrace
, walletInstanceTag
) where
import Control.Lens
import Control.Monad (void)
import Control.Monad.Freer (Eff, Member, interpret, raise, reinterpret, subsume)
import Control.Monad.Freer.Coroutine (Yield)
import Control.Monad.Freer.Error (Error, handleError, throwError)
import Control.Monad.Freer.Extras.Log (LogMessage, LogMsg (..), mapLog)
import Control.Monad.Freer.Extras.Modify (raiseEnd)
import Control.Monad.Freer.Reader (Reader)
import Control.Monad.Freer.State (State, evalState)
import Data.Aeson qualified as JSON
import Data.Foldable (traverse_)
import Data.Map (Map)
import Data.Map qualified as Map
import Data.Maybe (fromMaybe)
import Cardano.Node.Emulator.Chain (ChainControlEffect)
import Cardano.Node.Emulator.Params (pNetworkId, pSlotConfig)
import Plutus.Contract (Contract (..))
import Plutus.Trace.Effects.ContractInstanceId (ContractInstanceIdEff, handleDeterministicIds)
import Plutus.Trace.Effects.EmulatedWalletAPI (EmulatedWalletAPI, handleEmulatedWalletAPI)
import Plutus.Trace.Effects.EmulatedWalletAPI qualified as EmulatedWalletAPI
import Plutus.Trace.Effects.RunContractPlayground (RunContractPlayground, handleRunContractPlayground)
import Plutus.Trace.Effects.RunContractPlayground qualified as RunContractPlayground
import Plutus.Trace.Effects.Waiting (Waiting, handleWaiting)
import Plutus.Trace.Effects.Waiting qualified as Waiting
import Plutus.Trace.Emulator.ContractInstance (EmulatorRuntimeError)
import Plutus.Trace.Emulator.System (launchSystemThreads)
import Plutus.Trace.Emulator.Types (ContractConstraints, EmulatorMessage (..),
EmulatorRuntimeError (EmulatedWalletError), EmulatorThreads, walletInstanceTag)
import Plutus.Trace.Scheduler (EmSystemCall, ThreadId, exit, runThreads)
import Streaming (Stream)
import Streaming.Prelude (Of)
import Wallet.Emulator.MultiAgent (EmulatorEvent, EmulatorEvent' (..), EmulatorState, MultiAgentControlEffect,
MultiAgentEffect, schedulerEvent)
import Wallet.Emulator.Stream (EmulatorConfig (..), EmulatorErr (..), initialChainState, runTraceStream)
import Wallet.Emulator.Wallet (Wallet (..), knownWallets)
import Wallet.Types (ContractInstanceId)
Note [ Playground traces ]
The list of effects we can use in traces for the playground is slightly
different from that for regular traces :
* There is only a single contract
* We do n't need to start contract instances manually ( see note
[ Wallet contract instances ] )
* We have fewer actions . Only " call endpoint " and " wait " are supported in the
UI .
Therefore we can get by with a smaller list of effects for the ' PlaygroundTrace '
type .
Of particular note is the absence of
' . Trace . Effects . EmulatorControl . EmulatorControl ' . This means that we can ,
theoretically , run playground traces not just against the simulated environment
but also against a live system . See note [ The EmulatorControl effect ]
The list of effects we can use in traces for the Plutus playground is slightly
different from that for regular traces:
* There is only a single contract
* We don't need to start contract instances manually (see note
[Wallet contract instances])
* We have fewer actions. Only "call endpoint" and "wait" are supported in the
UI.
Therefore we can get by with a smaller list of effects for the 'PlaygroundTrace'
type.
Of particular note is the absence of
'Plutus.Trace.Effects.EmulatorControl.EmulatorControl'. This means that we can,
theoretically, run playground traces not just against the simulated environment
but also against a live system. See note [The EmulatorControl effect]
-}
type PlaygroundTrace a =
Eff
'[ RunContractPlayground
, Error EmulatorRuntimeError
, Waiting
, EmulatedWalletAPI
] a
handlePlaygroundTrace ::
forall w s e effs a.
( ContractConstraints s
, Show e
, JSON.ToJSON e
, JSON.ToJSON w
, Monoid w
, Member MultiAgentEffect effs
, Member (LogMsg EmulatorEvent') effs
, Member (Error EmulatorRuntimeError) effs
, Member (State (Map Wallet ContractInstanceId)) effs
, Member (State EmulatorThreads) effs
, Member ContractInstanceIdEff effs
)
=> EmulatorConfig
-> Contract w s e ()
-> PlaygroundTrace a
-> Eff (Reader ThreadId ': Yield (EmSystemCall effs EmulatorMessage a) (Maybe EmulatorMessage) ': effs) ()
handlePlaygroundTrace conf contract action = do
result <- flip handleError (throwError . EmulatedWalletError)
. reinterpret handleEmulatedWalletAPI
. interpret (handleWaiting @_ @effs @a (pSlotConfig $ _params conf))
. subsume
. interpret (handleRunContractPlayground @w @s @e @_ @effs @a (pNetworkId $ _params conf) contract)
$ raiseEnd action
void $ exit @effs @EmulatorMessage result
| Run a ' Trace Playground ' , streaming the log messages as they arrive
runPlaygroundStream :: forall w s e effs a.
( ContractConstraints s
, Show e
, JSON.ToJSON e
, JSON.ToJSON w
, Monoid w
)
=> EmulatorConfig
-> Contract w s e ()
-> PlaygroundTrace a
-> Stream (Of (LogMessage EmulatorEvent)) (Eff effs) (Either EmulatorErr a, EmulatorState)
runPlaygroundStream conf contract =
let wallets = fromMaybe knownWallets (preview (initialChainState . _Left . to Map.keys) conf)
in runTraceStream conf . interpretPlaygroundTrace conf contract wallets
interpretPlaygroundTrace :: forall w s e effs a.
( Member MultiAgentEffect effs
, Member MultiAgentControlEffect effs
, Member (Error EmulatorRuntimeError) effs
, Member ChainControlEffect effs
, Member (LogMsg EmulatorEvent') effs
, ContractConstraints s
, Show e
, JSON.ToJSON e
, JSON.ToJSON w
, Monoid w
)
=> EmulatorConfig
-> PlaygroundTrace a
-> Eff effs (Maybe a)
interpretPlaygroundTrace conf contract wallets action =
evalState @EmulatorThreads mempty
$ evalState @(Map Wallet ContractInstanceId) Map.empty
$ handleDeterministicIds
$ interpret (mapLog (review schedulerEvent))
$ runThreads
$ do
raise $ launchSystemThreads wallets
handlePlaygroundTrace conf contract $ do
void Waiting.nextSlot
traverse_ RunContractPlayground.launchContract wallets
action
|
33ffb844fc1cdc7f01f5dac804f9e337135652e443d58deb3895c3fd21c35547 | ice1000/learn | small-enough-beginner.hs | module Kata where
smallEnough :: [Int] -> Int -> Bool
smallEnough xs v = all (<= v) xs
| null | https://raw.githubusercontent.com/ice1000/learn/4ce5ea1897c97f7b5b3aee46ccd994e3613a58dd/Haskell/CW-Kata/small-enough-beginner.hs | haskell | module Kata where
smallEnough :: [Int] -> Int -> Bool
smallEnough xs v = all (<= v) xs
| |
b83b95fb9a3897305044346a0b8609b6a171a3c39d1442c8e0f14b7da5c6b0df | tsloughter/kuberl | kuberl_v1_component_condition.erl | -module(kuberl_v1_component_condition).
-export([encode/1]).
-export_type([kuberl_v1_component_condition/0]).
-type kuberl_v1_component_condition() ::
#{ 'error' => binary(),
'message' => binary(),
'status' := binary(),
'type' := binary()
}.
encode(#{ 'error' := Error,
'message' := Message,
'status' := Status,
'type' := Type
}) ->
#{ 'error' => Error,
'message' => Message,
'status' => Status,
'type' => Type
}.
| null | https://raw.githubusercontent.com/tsloughter/kuberl/f02ae6680d6ea5db6e8b6c7acbee8c4f9df482e2/gen/kuberl_v1_component_condition.erl | erlang | -module(kuberl_v1_component_condition).
-export([encode/1]).
-export_type([kuberl_v1_component_condition/0]).
-type kuberl_v1_component_condition() ::
#{ 'error' => binary(),
'message' => binary(),
'status' := binary(),
'type' := binary()
}.
encode(#{ 'error' := Error,
'message' := Message,
'status' := Status,
'type' := Type
}) ->
#{ 'error' => Error,
'message' => Message,
'status' => Status,
'type' => Type
}.
| |
8bb5c9a4eee77b87ef03f1e73f460ae775562dbd74aeb0a4c1e554ad27e4b472 | damn/cdq | selection_list.clj | (ns game.player.skill.selection-list
(:use utils.core
[engine.core :only (initialize)]
engine.render
(game settings ingame-gui session)
(game.components core
[render :only (rendering)]
[ingame-loop :only (ingame-loop-comp)])
game.components.skills.core
(game.player.skill skillmanager
[learnable :only (render-skillbutton-tooltip)])))
(declare selected-skill-buttons skill-selection-hotkeys)
(intern 'game.player.skill.skillmanager
'change-selected-skill-button-images
(fn [mousebutton new-icon]
(swap! (get selected-skill-buttons mousebutton) assoc :image new-icon)))
(def- select-skills-list {})
(declare create-skills-list button-y)
(def- xleftselectedskillbutton 2)
(def- xrightselectedskillbutton 20)
(defn- set-visible-skills-list [mousebutton bool]
(when bool
(create-skills-list mousebutton (case mousebutton
:left xleftselectedskillbutton
:right xrightselectedskillbutton)
button-y))
(doseq [{:keys [button]} (mousebutton select-skills-list)]
(set-visible button bool)))
(defn- is-visible-skills-list? [mousebutton]
(when-let [buttons (mousebutton select-skills-list)]
(-> buttons first :button is-visible?)))
(defn- render-button-hotkeys [g mousebutton]
(when (is-visible-skills-list? mousebutton)
(doseq [{:keys [button skill]} (mousebutton select-skills-list)]
(when-let [{:keys [mouse digit] :as hotkey}
(get @skill-selection-hotkeys (:type skill))]
(when (= mousebutton mouse)
(let [[x y] (get-absolute-posi button)]
(render-readable-text g x y digit)))))))
TODO rename skillbutton ...
(when (is-visible-skills-list? mousebutton)
(runmap
#(render-skillbutton-tooltip g %)
(mousebutton select-skills-list))))
(let [transparent-red (rgbcolor :r 0.9 :a 0.7)]
(defn- render-button-cooldown-overlay [g mouse]
(when (is-cooling-down? (get-selected-skill mouse))
(fill-rect g (get-bounds (get selected-skill-buttons mouse)) transparent-red))))
(defn some-skill-selection-list-visible? [] (some is-visible-skills-list? mousebuttons))
(defn close-skill-selection-lists [] (dorun (map #(set-visible-skills-list % false) mousebuttons)))
(ingame-loop-comp :update-skill-selection-buttons
(rendering [g c]
(doseq [button mousebuttons]
(render-button-cooldown-overlay g button)
(render-button-hotkeys g button))))
(ingame-loop-comp :skill-selection-list-tooltips
(rendering :tooltips [g c]
(runmap #(render-button-tooltip g %) mousebuttons)))
(defn- create-selected-skill-button [mousebutton x]
(let [button (make-imgbutton :image (create-skill-icon "icons/stomp.png") ; this icon will be replaced during create-player-skillmanager and the correct icon for each mouse
:location [x (- screen-height 18)]
:pressed #(set-visible-skills-list mousebutton true)
:tooltip (str "Select " (name mousebutton) "-mouse skill")
:parent ingamestate-display)
[x y w h] (get-bounds button)]
(def- button-height h)
(def- button-y y)
button))
(initialize
(def ^:private selected-skill-buttons
{:left (create-selected-skill-button :left xleftselectedskillbutton)
:right (create-selected-skill-button :right xrightselectedskillbutton)}))
(defn- create-skills-list [mousebutton buttonx buttony]
(doseq [button (map :button (mousebutton select-skills-list))]
(remove-guicomponent ingamestate-display button))
(alter-var-root #'select-skills-list assoc-in [mousebutton]
(let [puffer 5
starty (- buttony button-height puffer)]
(map-indexed
(fn [idx skill]
{:skill skill
:button (make-imgbutton
:image (:icon skill)
:location [buttonx
(- starty (* idx (inc button-height)))]
:pressed (fn []
(set-visible-skills-list mousebutton false)
(set-selected-skill mousebutton skill))
:parent ingamestate-display)})
(get-skills-for-mousebutton mousebutton)))))
;; Hotkeys
(def ^:private skill-selection-hotkeys (atom {}))
for example { : default - hands { : digit 1 : mouse : left } }
(def hotkeys-session (atom-session skill-selection-hotkeys :save-session true))
(defn- get-skilltype-with-hotkey [digit]
(find-first
#(= (:digit (get @skill-selection-hotkeys %)) digit)
(keys @skill-selection-hotkeys)))
(defn- set-skill-hotkey [skilltype digit mousebutton]
{:pre [(not (get-skilltype-with-hotkey digit))]}
(swap! skill-selection-hotkeys assoc skilltype {:digit digit :mouse mousebutton}))
(defn- try-set-skill-hotkey [mousebutton digit]
(when (is-visible-skills-list? mousebutton)
(when-let [selected-skill-button (find-first #(mouseover? @(:button %)) (mousebutton select-skills-list))]
(when-let [same-digit-hotkeyed-skilltype (get-skilltype-with-hotkey digit)]
(swap! skill-selection-hotkeys dissoc same-digit-hotkeyed-skilltype))
(set-skill-hotkey (:type (:skill selected-skill-button)) digit mousebutton))))
(defn- update-skill-hotkeys [digit]
(cond
(try-set-skill-hotkey :left digit) nil
(try-set-skill-hotkey :right digit) nil
:else
(when-let [skilltype (get-skilltype-with-hotkey digit)]
(let [mousebutton (:mouse (get @skill-selection-hotkeys skilltype))]
(when-let [skill (find-first #(= (:type %) skilltype)
(get-skills-for-mousebutton mousebutton))]
(set-selected-skill mousebutton skill)
(set-visible-skills-list mousebutton false))))))
(def- numberkeys (map #(keyword (str %)) (range 10)))
(ingame-loop-comp :up-skill-hotkeys
(active [delta c _]
(doseq [k numberkeys
:when (engine.input/is-key-pressed? k)]
(update-skill-hotkeys (Integer/parseInt (name k))))))
(intern 'game.player.skill.skillmanager 'assign-unused-hotkey-and-open-skillslist
(fn [skilltype]
(let [unused-hotkey (find-first #(not (get-skilltype-with-hotkey %)) [1,2,3,4,5,6,7,8,9,0])
mousebutton (if (= skilltype :psi-charger) :left :right)]
(set-skill-hotkey skilltype unused-hotkey mousebutton)
(set-visible-skills-list mousebutton true))))
| null | https://raw.githubusercontent.com/damn/cdq/5093dbdba91c445e403f53ce96ead05d5ed8262b/src/game/player/skill/selection_list.clj | clojure | this icon will be replaced during create-player-skillmanager and the correct icon for each mouse
Hotkeys | (ns game.player.skill.selection-list
(:use utils.core
[engine.core :only (initialize)]
engine.render
(game settings ingame-gui session)
(game.components core
[render :only (rendering)]
[ingame-loop :only (ingame-loop-comp)])
game.components.skills.core
(game.player.skill skillmanager
[learnable :only (render-skillbutton-tooltip)])))
(declare selected-skill-buttons skill-selection-hotkeys)
(intern 'game.player.skill.skillmanager
'change-selected-skill-button-images
(fn [mousebutton new-icon]
(swap! (get selected-skill-buttons mousebutton) assoc :image new-icon)))
(def- select-skills-list {})
(declare create-skills-list button-y)
(def- xleftselectedskillbutton 2)
(def- xrightselectedskillbutton 20)
(defn- set-visible-skills-list [mousebutton bool]
(when bool
(create-skills-list mousebutton (case mousebutton
:left xleftselectedskillbutton
:right xrightselectedskillbutton)
button-y))
(doseq [{:keys [button]} (mousebutton select-skills-list)]
(set-visible button bool)))
(defn- is-visible-skills-list? [mousebutton]
(when-let [buttons (mousebutton select-skills-list)]
(-> buttons first :button is-visible?)))
(defn- render-button-hotkeys [g mousebutton]
(when (is-visible-skills-list? mousebutton)
(doseq [{:keys [button skill]} (mousebutton select-skills-list)]
(when-let [{:keys [mouse digit] :as hotkey}
(get @skill-selection-hotkeys (:type skill))]
(when (= mousebutton mouse)
(let [[x y] (get-absolute-posi button)]
(render-readable-text g x y digit)))))))
TODO rename skillbutton ...
(when (is-visible-skills-list? mousebutton)
(runmap
#(render-skillbutton-tooltip g %)
(mousebutton select-skills-list))))
(let [transparent-red (rgbcolor :r 0.9 :a 0.7)]
(defn- render-button-cooldown-overlay [g mouse]
(when (is-cooling-down? (get-selected-skill mouse))
(fill-rect g (get-bounds (get selected-skill-buttons mouse)) transparent-red))))
(defn some-skill-selection-list-visible? [] (some is-visible-skills-list? mousebuttons))
(defn close-skill-selection-lists [] (dorun (map #(set-visible-skills-list % false) mousebuttons)))
(ingame-loop-comp :update-skill-selection-buttons
(rendering [g c]
(doseq [button mousebuttons]
(render-button-cooldown-overlay g button)
(render-button-hotkeys g button))))
(ingame-loop-comp :skill-selection-list-tooltips
(rendering :tooltips [g c]
(runmap #(render-button-tooltip g %) mousebuttons)))
(defn- create-selected-skill-button [mousebutton x]
:location [x (- screen-height 18)]
:pressed #(set-visible-skills-list mousebutton true)
:tooltip (str "Select " (name mousebutton) "-mouse skill")
:parent ingamestate-display)
[x y w h] (get-bounds button)]
(def- button-height h)
(def- button-y y)
button))
(initialize
(def ^:private selected-skill-buttons
{:left (create-selected-skill-button :left xleftselectedskillbutton)
:right (create-selected-skill-button :right xrightselectedskillbutton)}))
(defn- create-skills-list [mousebutton buttonx buttony]
(doseq [button (map :button (mousebutton select-skills-list))]
(remove-guicomponent ingamestate-display button))
(alter-var-root #'select-skills-list assoc-in [mousebutton]
(let [puffer 5
starty (- buttony button-height puffer)]
(map-indexed
(fn [idx skill]
{:skill skill
:button (make-imgbutton
:image (:icon skill)
:location [buttonx
(- starty (* idx (inc button-height)))]
:pressed (fn []
(set-visible-skills-list mousebutton false)
(set-selected-skill mousebutton skill))
:parent ingamestate-display)})
(get-skills-for-mousebutton mousebutton)))))
(def ^:private skill-selection-hotkeys (atom {}))
for example { : default - hands { : digit 1 : mouse : left } }
(def hotkeys-session (atom-session skill-selection-hotkeys :save-session true))
(defn- get-skilltype-with-hotkey [digit]
(find-first
#(= (:digit (get @skill-selection-hotkeys %)) digit)
(keys @skill-selection-hotkeys)))
(defn- set-skill-hotkey [skilltype digit mousebutton]
{:pre [(not (get-skilltype-with-hotkey digit))]}
(swap! skill-selection-hotkeys assoc skilltype {:digit digit :mouse mousebutton}))
(defn- try-set-skill-hotkey [mousebutton digit]
(when (is-visible-skills-list? mousebutton)
(when-let [selected-skill-button (find-first #(mouseover? @(:button %)) (mousebutton select-skills-list))]
(when-let [same-digit-hotkeyed-skilltype (get-skilltype-with-hotkey digit)]
(swap! skill-selection-hotkeys dissoc same-digit-hotkeyed-skilltype))
(set-skill-hotkey (:type (:skill selected-skill-button)) digit mousebutton))))
(defn- update-skill-hotkeys [digit]
(cond
(try-set-skill-hotkey :left digit) nil
(try-set-skill-hotkey :right digit) nil
:else
(when-let [skilltype (get-skilltype-with-hotkey digit)]
(let [mousebutton (:mouse (get @skill-selection-hotkeys skilltype))]
(when-let [skill (find-first #(= (:type %) skilltype)
(get-skills-for-mousebutton mousebutton))]
(set-selected-skill mousebutton skill)
(set-visible-skills-list mousebutton false))))))
(def- numberkeys (map #(keyword (str %)) (range 10)))
(ingame-loop-comp :up-skill-hotkeys
(active [delta c _]
(doseq [k numberkeys
:when (engine.input/is-key-pressed? k)]
(update-skill-hotkeys (Integer/parseInt (name k))))))
(intern 'game.player.skill.skillmanager 'assign-unused-hotkey-and-open-skillslist
(fn [skilltype]
(let [unused-hotkey (find-first #(not (get-skilltype-with-hotkey %)) [1,2,3,4,5,6,7,8,9,0])
mousebutton (if (= skilltype :psi-charger) :left :right)]
(set-skill-hotkey skilltype unused-hotkey mousebutton)
(set-visible-skills-list mousebutton true))))
|
b4a72f2bbfb1c8d7892d5947c883f5e5d8c91f41171e7a4472812479e7d24409 | sulami/spielwiese | single-byte-xor-cypher.hs | {-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.List (minimumBy)
import Data.Ord (comparing)
import qualified Data.ByteString as BS
import Matasano
main = do
let enc = "1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736"
options = [ replicate (BS.length enc) x | x <- [65..90] ]
test = (\w -> (score w,w)) . unsafeFromHex . xorByteString (Hex enc) .
toHex . BS.pack
print . minimumBy (comparing fst) $ map test options
| null | https://raw.githubusercontent.com/sulami/spielwiese/da354aa112d43d7ec5f258f4b5afafd7a88c8aa8/matasano/single-byte-xor-cypher.hs | haskell | # LANGUAGE OverloadedStrings # |
module Main where
import Data.List (minimumBy)
import Data.Ord (comparing)
import qualified Data.ByteString as BS
import Matasano
main = do
let enc = "1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736"
options = [ replicate (BS.length enc) x | x <- [65..90] ]
test = (\w -> (score w,w)) . unsafeFromHex . xorByteString (Hex enc) .
toHex . BS.pack
print . minimumBy (comparing fst) $ map test options
|
54c8f98e8f9aefbdcc78cc5091ad7fd30a808605da11c0e506e5e053e0a3b57d | mit-plv/riscv-semantics | ExecuteClash.hs | module Platform.ExecuteClash where
import Spec.Decode
import Spec.Machine
import qualified Spec.CSRField as Field
import Spec.ExecuteI as I
import Spec.ExecuteM as M
import Spec.ExecuteCSR as CSR
import Control.Monad
import Control.Monad.Trans.Maybe
import Prelude
execute :: (RiscvMachine p t) => Instruction -> p ()
execute inst = do
case inst of
IInstruction i -> I.execute i
MInstruction i - > M.execute i
-- I64Instruction i -> I64.execute i
-- M64Instruction i -> M64.execute i
CSRInstruction i - > CSR.execute i
InvalidInstruction i - > raiseExceptionWithInfo 0 2 i
raiseExceptionWithInfo 0 2 0
cycles < - getCSRField Field . MCycle
setCSRField Field . MCycle ( cycles + 1 )
Field . MInstRet
setCSRField Field . MInstRet ( instret + 1 )
| null | https://raw.githubusercontent.com/mit-plv/riscv-semantics/1c0da3cac9d3f8dd813d26c0d2fbaccbb2210313/src/Platform/ExecuteClash.hs | haskell | I64Instruction i -> I64.execute i
M64Instruction i -> M64.execute i | module Platform.ExecuteClash where
import Spec.Decode
import Spec.Machine
import qualified Spec.CSRField as Field
import Spec.ExecuteI as I
import Spec.ExecuteM as M
import Spec.ExecuteCSR as CSR
import Control.Monad
import Control.Monad.Trans.Maybe
import Prelude
execute :: (RiscvMachine p t) => Instruction -> p ()
execute inst = do
case inst of
IInstruction i -> I.execute i
MInstruction i - > M.execute i
CSRInstruction i - > CSR.execute i
InvalidInstruction i - > raiseExceptionWithInfo 0 2 i
raiseExceptionWithInfo 0 2 0
cycles < - getCSRField Field . MCycle
setCSRField Field . MCycle ( cycles + 1 )
Field . MInstRet
setCSRField Field . MInstRet ( instret + 1 )
|
a624b78e3ba2eb58db16efda4830e55ef4fc4a4d62f6d751b8b35dca49b5c6b8 | jtod/Hydra | Reg1Run.hs | -- Reg1Run: simulation driver for reg1
This file is part of Hydra . See README and
Copyright ( c ) 2022
Module Main where
import HDL.Hydra.Core.Lib
import Reg1
main :: IO ()
main = reg1Run testData
testData :: [String]
testData =
------------------------
-- ld x output
------------------------
[ "1 1" -- 0 output in cycle 0 is initial state
1 state changed to 1 at tick between cycles 0/1
1 no change
1 no change
1 still see 1 but at end of cycle , set state to 0
, "0 0" -- 0 during this cycle can see result of state change
0 but set state to 1 on tick at end of cycle
1 the 1 becomes visible in this cycle
, "0 0" -- 0 the 0 now becomes visible
, "0 0" -- 0 no change
]
reg1Run :: [String] -> IO ()
reg1Run xs = driver $ do
-- Input data
useData xs
-- Input ports
ld <- inputBit "ld"
x <- inputBit "x"
-- Circuit
let y = reg1 ld x
outputBit "y" y
-- Run
runSimulation
| null | https://raw.githubusercontent.com/jtod/Hydra/cf67a88050720acfff6a51b16d5f9efbd154dc1e/examples/register/Reg1Run.hs | haskell | Reg1Run: simulation driver for reg1
----------------------
ld x output
----------------------
0 output in cycle 0 is initial state
0 during this cycle can see result of state change
0 the 0 now becomes visible
0 no change
Input data
Input ports
Circuit
Run
| This file is part of Hydra . See README and
Copyright ( c ) 2022
Module Main where
import HDL.Hydra.Core.Lib
import Reg1
main :: IO ()
main = reg1Run testData
testData :: [String]
testData =
1 state changed to 1 at tick between cycles 0/1
1 no change
1 no change
1 still see 1 but at end of cycle , set state to 0
0 but set state to 1 on tick at end of cycle
1 the 1 becomes visible in this cycle
]
reg1Run :: [String] -> IO ()
reg1Run xs = driver $ do
useData xs
ld <- inputBit "ld"
x <- inputBit "x"
let y = reg1 ld x
outputBit "y" y
runSimulation
|
d9222ec7de8ce4bd5d14f7d0dd81648002c0d7b0314344107545c189dc3dd950 | AshleyYakeley/Truth | Test.hs | module Main
( main
) where
import Options
import Options.Applicative
import Options.Applicative.Help hiding ((</>))
import Shapes
import Shapes.Test
parseResult :: Show a => ParserResult a -> Result String a
parseResult (Success a) = SuccessResult a
parseResult r = FailureResult $ show r
testOptions :: [String] -> Result String Options -> TestTree
testOptions args expected =
testTree (intercalate " " args) $ let
found = parseResult $ execParserPure defaultPrefs optParserInfo args
in assertEqual "" expected found
testOptionParsing :: TestTree
testOptionParsing =
testTree
"option-parsing"
[ testOptions ["-v"] $ SuccessResult ShowVersionOption
, testOptions ["--version"] $ SuccessResult ShowVersionOption
, testTree
"script"
[ testOptions ["scriptname"] $
SuccessResult $ RunFileOption (MkRunOptions True [] Nothing) False ("scriptname", [])
, testOptions ["scriptname", "a"] $
SuccessResult $ RunFileOption (MkRunOptions True [] Nothing) False ("scriptname", ["a"])
, testOptions ["scriptname", "-x"] $
SuccessResult $ RunFileOption (MkRunOptions True [] Nothing) False ("scriptname", ["-x"])
, testOptions ["scriptname", "--opt"] $
SuccessResult $ RunFileOption (MkRunOptions True [] Nothing) False ("scriptname", ["--opt"])
, testOptions ["scriptname", "-n"] $
SuccessResult $ RunFileOption (MkRunOptions True [] Nothing) False ("scriptname", ["-n"])
, testOptions ["scriptname", "-v"] $
SuccessResult $ RunFileOption (MkRunOptions True [] Nothing) False ("scriptname", ["-v"])
, testOptions ["scriptname", "--data", "dpath"] $
SuccessResult $ RunFileOption (MkRunOptions True [] Nothing) False ("scriptname", ["--data", "dpath"])
, testOptions ["-n", "scriptname"] $
SuccessResult $ RunFileOption (MkRunOptions True [] Nothing) True ("scriptname", [])
, testOptions ["-n", "scriptname", "-n"] $
SuccessResult $ RunFileOption (MkRunOptions True [] Nothing) True ("scriptname", ["-n"])
, testOptions ["-I", "incpath", "scriptname"] $
SuccessResult $ RunFileOption (MkRunOptions True ["incpath"] Nothing) False ("scriptname", [])
, testOptions ["-I", "path1", "-I", "path2", "scriptname"] $
SuccessResult $ RunFileOption (MkRunOptions True ["path1", "path2"] Nothing) False ("scriptname", [])
, testOptions ["--include", "incpath", "scriptname"] $
SuccessResult $ RunFileOption (MkRunOptions True ["incpath"] Nothing) False ("scriptname", [])
, testOptions ["--include", "path1", "--include", "path2", "scriptname"] $
SuccessResult $ RunFileOption (MkRunOptions True ["path1", "path2"] Nothing) False ("scriptname", [])
, testOptions ["--data", "dpath", "scriptname"] $
SuccessResult $ RunFileOption (MkRunOptions True [] (Just "dpath")) False ("scriptname", [])
, testOptions ["--data", "dpath", "scriptname", "arg1"] $
SuccessResult $ RunFileOption (MkRunOptions True [] (Just "dpath")) False ("scriptname", ["arg1"])
, testOptions ["--data", "dpath", "scriptname", "arg1", "arg2"] $
SuccessResult $
RunFileOption (MkRunOptions True [] (Just "dpath")) False ("scriptname", ["arg1", "arg2"])
, testOptions ["-n", "--data", "dpath", "scriptname", "arg1", "arg2"] $
SuccessResult $
RunFileOption (MkRunOptions True [] (Just "dpath")) True ("scriptname", ["arg1", "arg2"])
]
, testTree
"interactive"
[ testOptions ["-i"] $ SuccessResult $ RunInteractiveOption $ MkRunOptions True [] Nothing
, testOptions ["-i", "--data", "dpath"] $
SuccessResult $ RunInteractiveOption $ MkRunOptions True [] $ Just "dpath"
, testOptions ["--interactive"] $ SuccessResult $ RunInteractiveOption $ MkRunOptions True [] Nothing
, testOptions ["-I", "incpath", "--interactive"] $
SuccessResult $ RunInteractiveOption $ MkRunOptions True ["incpath"] Nothing
, testOptions ["--include", "incpath", "--interactive"] $
SuccessResult $ RunInteractiveOption $ MkRunOptions True ["incpath"] Nothing
, testOptions ["--interactive", "-I", "incpath"] $
SuccessResult $ RunInteractiveOption $ MkRunOptions True ["incpath"] Nothing
, testOptions ["-I", "path1", "-I", "path2", "--interactive"] $
SuccessResult $ RunInteractiveOption $ MkRunOptions True ["path1", "path2"] Nothing
, testOptions ["--include", "path1", "--include", "path2", "--interactive"] $
SuccessResult $ RunInteractiveOption $ MkRunOptions True ["path1", "path2"] Nothing
, testOptions ["--interactive", "-I", "path1", "-I", "path2"] $
SuccessResult $ RunInteractiveOption $ MkRunOptions True ["path1", "path2"] Nothing
, testOptions ["--interactive", "--data", "dpath"] $
SuccessResult $ RunInteractiveOption $ MkRunOptions True [] $ Just "dpath"
]
]
testOptionHelp :: TestTree
testOptionHelp =
testHandleVsFile ("test" </> "golden") "option-help" $ \h -> do
let pr = execParserPure defaultPrefs optParserInfo ["--help"]
case pr of
Failure (ParserFailure f) ->
case f "pinafore" of
(ph, _, _) -> hPutStrLn h $ renderHelp 80 ph
_ -> assertFailure "parser didn't fail"
tests :: TestTree
tests = testTree "app" [testOptionParsing, testOptionHelp]
main :: IO ()
main = testMain tests
| null | https://raw.githubusercontent.com/AshleyYakeley/Truth/d704b8baaa77dac002922eccecdd91018c4b7eef/Pinafore/pinafore-app/app/main/Test.hs | haskell | module Main
( main
) where
import Options
import Options.Applicative
import Options.Applicative.Help hiding ((</>))
import Shapes
import Shapes.Test
parseResult :: Show a => ParserResult a -> Result String a
parseResult (Success a) = SuccessResult a
parseResult r = FailureResult $ show r
testOptions :: [String] -> Result String Options -> TestTree
testOptions args expected =
testTree (intercalate " " args) $ let
found = parseResult $ execParserPure defaultPrefs optParserInfo args
in assertEqual "" expected found
testOptionParsing :: TestTree
testOptionParsing =
testTree
"option-parsing"
[ testOptions ["-v"] $ SuccessResult ShowVersionOption
, testOptions ["--version"] $ SuccessResult ShowVersionOption
, testTree
"script"
[ testOptions ["scriptname"] $
SuccessResult $ RunFileOption (MkRunOptions True [] Nothing) False ("scriptname", [])
, testOptions ["scriptname", "a"] $
SuccessResult $ RunFileOption (MkRunOptions True [] Nothing) False ("scriptname", ["a"])
, testOptions ["scriptname", "-x"] $
SuccessResult $ RunFileOption (MkRunOptions True [] Nothing) False ("scriptname", ["-x"])
, testOptions ["scriptname", "--opt"] $
SuccessResult $ RunFileOption (MkRunOptions True [] Nothing) False ("scriptname", ["--opt"])
, testOptions ["scriptname", "-n"] $
SuccessResult $ RunFileOption (MkRunOptions True [] Nothing) False ("scriptname", ["-n"])
, testOptions ["scriptname", "-v"] $
SuccessResult $ RunFileOption (MkRunOptions True [] Nothing) False ("scriptname", ["-v"])
, testOptions ["scriptname", "--data", "dpath"] $
SuccessResult $ RunFileOption (MkRunOptions True [] Nothing) False ("scriptname", ["--data", "dpath"])
, testOptions ["-n", "scriptname"] $
SuccessResult $ RunFileOption (MkRunOptions True [] Nothing) True ("scriptname", [])
, testOptions ["-n", "scriptname", "-n"] $
SuccessResult $ RunFileOption (MkRunOptions True [] Nothing) True ("scriptname", ["-n"])
, testOptions ["-I", "incpath", "scriptname"] $
SuccessResult $ RunFileOption (MkRunOptions True ["incpath"] Nothing) False ("scriptname", [])
, testOptions ["-I", "path1", "-I", "path2", "scriptname"] $
SuccessResult $ RunFileOption (MkRunOptions True ["path1", "path2"] Nothing) False ("scriptname", [])
, testOptions ["--include", "incpath", "scriptname"] $
SuccessResult $ RunFileOption (MkRunOptions True ["incpath"] Nothing) False ("scriptname", [])
, testOptions ["--include", "path1", "--include", "path2", "scriptname"] $
SuccessResult $ RunFileOption (MkRunOptions True ["path1", "path2"] Nothing) False ("scriptname", [])
, testOptions ["--data", "dpath", "scriptname"] $
SuccessResult $ RunFileOption (MkRunOptions True [] (Just "dpath")) False ("scriptname", [])
, testOptions ["--data", "dpath", "scriptname", "arg1"] $
SuccessResult $ RunFileOption (MkRunOptions True [] (Just "dpath")) False ("scriptname", ["arg1"])
, testOptions ["--data", "dpath", "scriptname", "arg1", "arg2"] $
SuccessResult $
RunFileOption (MkRunOptions True [] (Just "dpath")) False ("scriptname", ["arg1", "arg2"])
, testOptions ["-n", "--data", "dpath", "scriptname", "arg1", "arg2"] $
SuccessResult $
RunFileOption (MkRunOptions True [] (Just "dpath")) True ("scriptname", ["arg1", "arg2"])
]
, testTree
"interactive"
[ testOptions ["-i"] $ SuccessResult $ RunInteractiveOption $ MkRunOptions True [] Nothing
, testOptions ["-i", "--data", "dpath"] $
SuccessResult $ RunInteractiveOption $ MkRunOptions True [] $ Just "dpath"
, testOptions ["--interactive"] $ SuccessResult $ RunInteractiveOption $ MkRunOptions True [] Nothing
, testOptions ["-I", "incpath", "--interactive"] $
SuccessResult $ RunInteractiveOption $ MkRunOptions True ["incpath"] Nothing
, testOptions ["--include", "incpath", "--interactive"] $
SuccessResult $ RunInteractiveOption $ MkRunOptions True ["incpath"] Nothing
, testOptions ["--interactive", "-I", "incpath"] $
SuccessResult $ RunInteractiveOption $ MkRunOptions True ["incpath"] Nothing
, testOptions ["-I", "path1", "-I", "path2", "--interactive"] $
SuccessResult $ RunInteractiveOption $ MkRunOptions True ["path1", "path2"] Nothing
, testOptions ["--include", "path1", "--include", "path2", "--interactive"] $
SuccessResult $ RunInteractiveOption $ MkRunOptions True ["path1", "path2"] Nothing
, testOptions ["--interactive", "-I", "path1", "-I", "path2"] $
SuccessResult $ RunInteractiveOption $ MkRunOptions True ["path1", "path2"] Nothing
, testOptions ["--interactive", "--data", "dpath"] $
SuccessResult $ RunInteractiveOption $ MkRunOptions True [] $ Just "dpath"
]
]
testOptionHelp :: TestTree
testOptionHelp =
testHandleVsFile ("test" </> "golden") "option-help" $ \h -> do
let pr = execParserPure defaultPrefs optParserInfo ["--help"]
case pr of
Failure (ParserFailure f) ->
case f "pinafore" of
(ph, _, _) -> hPutStrLn h $ renderHelp 80 ph
_ -> assertFailure "parser didn't fail"
tests :: TestTree
tests = testTree "app" [testOptionParsing, testOptionHelp]
main :: IO ()
main = testMain tests
| |
ffa9576a3ce8deaa49d7583a9469d6ae622bc926463d7f7c6c89e74911084b5c | glguy/advent2015 | Day7.hs | # LANGUAGE DeriveFunctor #
module Main where
import Data.Bits
import Data.Map (Map)
import Data.Word
import Text.Read (readMaybe)
import qualified Data.Map as Map
data Gate a = Gate1 Op1 a | Gate2 Op2 a a deriving Functor
data Op1 = Not | Id
data Op2 = And | Or | LShift | RShift
main :: IO ()
main =
do circuit1 <- loadInput
let answer1 = findAnswer circuit1
print answer1
let circuit2 = Map.insert "b" (Gate1 Id (show answer1)) circuit1
print (findAnswer circuit2)
loadInput :: IO (Map String (Gate String))
loadInput = parseLines <$> readFile "input7.txt"
-- | Build a circuit and compute output 'a'
findAnswer :: Map String (Gate String) -> Word16
findAnswer circuit = tieCircuit circuit Map.! "a"
tieCircuit :: Map String (Gate String) -> Map String Word16
tieCircuit m = m'
where
m' = fmap (evalGate . fmap evalKey) m
evalKey key
| Just n <- readMaybe key = n
| otherwise = m' Map.! key
evalGate :: Gate Word16 -> Word16
evalGate (Gate1 Id x ) = x
evalGate (Gate1 Not x ) = complement x
evalGate (Gate2 And x y) = x .&. y
evalGate (Gate2 Or x y) = x .|. y
evalGate (Gate2 RShift x y) = x `shiftR` fromIntegral y
evalGate (Gate2 LShift x y) = x `shiftL` fromIntegral y
parseLines :: String -> Map String (Gate String)
parseLines = Map.fromList . map parseLine . lines
-- | Parse a line describing a gate in the circuit.
parseLine :: String -> (String, Gate String)
parseLine cmd =
case words cmd of
[x, "->",y] -> (y, Gate1 Id x)
["NOT",x, "->",y] -> (y, Gate1 Not x)
[x,"AND", y,"->",z] -> (z, Gate2 And x y)
[x,"OR", y,"->",z] -> (z, Gate2 Or x y)
[x,"LSHIFT",y,"->",z] -> (z, Gate2 LShift x y)
[x,"RSHIFT",y,"->",z] -> (z, Gate2 RShift x y)
_ -> error ("parseLine: " ++ cmd)
| null | https://raw.githubusercontent.com/glguy/advent2015/e59b93c41363be85eb7f11396db5c95e79e485ad/Day7.hs | haskell | | Build a circuit and compute output 'a'
| Parse a line describing a gate in the circuit. | # LANGUAGE DeriveFunctor #
module Main where
import Data.Bits
import Data.Map (Map)
import Data.Word
import Text.Read (readMaybe)
import qualified Data.Map as Map
data Gate a = Gate1 Op1 a | Gate2 Op2 a a deriving Functor
data Op1 = Not | Id
data Op2 = And | Or | LShift | RShift
main :: IO ()
main =
do circuit1 <- loadInput
let answer1 = findAnswer circuit1
print answer1
let circuit2 = Map.insert "b" (Gate1 Id (show answer1)) circuit1
print (findAnswer circuit2)
loadInput :: IO (Map String (Gate String))
loadInput = parseLines <$> readFile "input7.txt"
findAnswer :: Map String (Gate String) -> Word16
findAnswer circuit = tieCircuit circuit Map.! "a"
tieCircuit :: Map String (Gate String) -> Map String Word16
tieCircuit m = m'
where
m' = fmap (evalGate . fmap evalKey) m
evalKey key
| Just n <- readMaybe key = n
| otherwise = m' Map.! key
evalGate :: Gate Word16 -> Word16
evalGate (Gate1 Id x ) = x
evalGate (Gate1 Not x ) = complement x
evalGate (Gate2 And x y) = x .&. y
evalGate (Gate2 Or x y) = x .|. y
evalGate (Gate2 RShift x y) = x `shiftR` fromIntegral y
evalGate (Gate2 LShift x y) = x `shiftL` fromIntegral y
parseLines :: String -> Map String (Gate String)
parseLines = Map.fromList . map parseLine . lines
parseLine :: String -> (String, Gate String)
parseLine cmd =
case words cmd of
[x, "->",y] -> (y, Gate1 Id x)
["NOT",x, "->",y] -> (y, Gate1 Not x)
[x,"AND", y,"->",z] -> (z, Gate2 And x y)
[x,"OR", y,"->",z] -> (z, Gate2 Or x y)
[x,"LSHIFT",y,"->",z] -> (z, Gate2 LShift x y)
[x,"RSHIFT",y,"->",z] -> (z, Gate2 RShift x y)
_ -> error ("parseLine: " ++ cmd)
|
e4b1df84632770c4bef0537ebadc654d553eb0910e098de00d69ef7c8baed1a2 | RichiH/git-annex | Win32Notify.hs | Win32 - notify interface
-
- Copyright 2013 < >
-
- License : BSD-2 - clause
-
- Copyright 2013 Joey Hess <>
-
- License: BSD-2-clause
-}
module Utility.DirWatcher.Win32Notify where
import Common hiding (isDirectory)
import Utility.DirWatcher.Types
import System.Win32.Notify
import qualified System.PosixCompat.Files as Files
watchDir :: FilePath -> (FilePath -> Bool) -> Bool -> WatchHooks -> IO WatchManager
watchDir dir ignored scanevents hooks = do
scan dir
wm <- initWatchManager
void $ watchDirectory wm dir True [Create, Delete, Modify, Move] dispatch
return wm
where
dispatch evt
| ignoredPath ignored (filePath evt) = noop
| otherwise = case evt of
(Deleted _ _)
| isDirectory evt -> runhook delDirHook Nothing
| otherwise -> runhook delHook Nothing
(Created _ _)
| isDirectory evt -> noop
| otherwise -> runhook addHook Nothing
(Modified _ _)
| isDirectory evt -> noop
Add hooks are run when a file is modified for
- compatability with INotify , which calls the add
- hook when a file is closed , and so tends to call
- both add and modify for file modifications .
- compatability with INotify, which calls the add
- hook when a file is closed, and so tends to call
- both add and modify for file modifications. -}
| otherwise -> do
runhook addHook Nothing
runhook modifyHook Nothing
where
runhook h s = maybe noop (\a -> a (filePath evt) s) (h hooks)
scan d = unless (ignoredPath ignored d) $
mapM_ go =<< dirContentsRecursiveSkipping (const False) False d
where
go f
| ignoredPath ignored f = noop
| otherwise = do
ms <- getstatus f
case ms of
Nothing -> noop
Just s
| Files.isRegularFile s ->
when scanevents $
runhook addHook ms
| otherwise ->
noop
where
runhook h s = maybe noop (\a -> a f s) (h hooks)
getstatus = catchMaybeIO . getFileStatus
{- Check each component of the path to see if it's ignored. -}
ignoredPath :: (FilePath -> Bool) -> FilePath -> Bool
ignoredPath ignored = any ignored . map dropTrailingPathSeparator . splitPath
| null | https://raw.githubusercontent.com/RichiH/git-annex/bbcad2b0af8cd9264d0cb86e6ca126ae626171f3/Utility/DirWatcher/Win32Notify.hs | haskell | Check each component of the path to see if it's ignored. | Win32 - notify interface
-
- Copyright 2013 < >
-
- License : BSD-2 - clause
-
- Copyright 2013 Joey Hess <>
-
- License: BSD-2-clause
-}
module Utility.DirWatcher.Win32Notify where
import Common hiding (isDirectory)
import Utility.DirWatcher.Types
import System.Win32.Notify
import qualified System.PosixCompat.Files as Files
watchDir :: FilePath -> (FilePath -> Bool) -> Bool -> WatchHooks -> IO WatchManager
watchDir dir ignored scanevents hooks = do
scan dir
wm <- initWatchManager
void $ watchDirectory wm dir True [Create, Delete, Modify, Move] dispatch
return wm
where
dispatch evt
| ignoredPath ignored (filePath evt) = noop
| otherwise = case evt of
(Deleted _ _)
| isDirectory evt -> runhook delDirHook Nothing
| otherwise -> runhook delHook Nothing
(Created _ _)
| isDirectory evt -> noop
| otherwise -> runhook addHook Nothing
(Modified _ _)
| isDirectory evt -> noop
Add hooks are run when a file is modified for
- compatability with INotify , which calls the add
- hook when a file is closed , and so tends to call
- both add and modify for file modifications .
- compatability with INotify, which calls the add
- hook when a file is closed, and so tends to call
- both add and modify for file modifications. -}
| otherwise -> do
runhook addHook Nothing
runhook modifyHook Nothing
where
runhook h s = maybe noop (\a -> a (filePath evt) s) (h hooks)
scan d = unless (ignoredPath ignored d) $
mapM_ go =<< dirContentsRecursiveSkipping (const False) False d
where
go f
| ignoredPath ignored f = noop
| otherwise = do
ms <- getstatus f
case ms of
Nothing -> noop
Just s
| Files.isRegularFile s ->
when scanevents $
runhook addHook ms
| otherwise ->
noop
where
runhook h s = maybe noop (\a -> a f s) (h hooks)
getstatus = catchMaybeIO . getFileStatus
ignoredPath :: (FilePath -> Bool) -> FilePath -> Bool
ignoredPath ignored = any ignored . map dropTrailingPathSeparator . splitPath
|
1654d766272a856779f0e52e45e3eb060d254661b85e8c4a61f106074ad4563b | shirok/Gauche | japanize.scm | -*- coding : utf-8 -*-
;;; This is just a joke.
(define-syntax λ
(syntax-rules () ((_ args body ...) (lambda args body ...))))
(define-syntax 定義
(syntax-rules (は)
((_ (f . args) body ...)
(define (f . args) body ...))
((_ var val)
(define var val))
((_ var は val)
(define var val))))
(define-syntax もし
(syntax-rules (ならば でなければ)
((_ test ならば then)
(if test then))
((_ test ならば then でなければ else)
(if test then else))
((_ test でなければ else)
(unless test else))
((_ test then)
(if test then))
((_ test then else)
(if test then else))))
(define-syntax 代入
(syntax-rules (へ)
((_ var へ val)
(set! var val))
((_ var val)
(set! var val))))
(define-syntax 局所定義
(syntax-rules (は)
((_ ((var は val) ...) body ...)
(let ((var val) ...) body ...))
((_ ((var val) ...) body ...)
(let ((var val) ...) body ...))
))
(define-syntax 順次局所定義
(syntax-rules (は)
((_ ((var は val) ...) body ...)
(let* ((var val) ...) body ...))
((_ ((var val) ...) body ...)
(let* ((var val) ...) body ...))
))
(define-syntax 再帰局所定義
(syntax-rules (は)
((_ ((var は val) ...) body ...)
(letrec ((var val) ...) body ...))
((_ ((var val) ...) body ...)
(letrec ((var val) ...) body ...))
))
(define < <)
(define ≦ <=)
(define = =)
(define > >)
(define ≧ >=)
(define + +)
(define − -)
(define × *)
(define ÷ /)
(define 文字列→リスト string->list)
(define 逆リスト reverse)
;;-----------------------------------------------
;; examples
(定義 階乗 は
(λ (n) (もし (≦ n 2) ならば n でなければ (× n (階乗 (− n 1))))))
(定義 回文か? は
(λ (文字列)
(順次局所定義 ((文字リスト は (文字列→リスト 文字列))
(逆文字リスト は (逆リスト 文字リスト)))
(equal? 逆文字リスト 文字リスト))))
| null | https://raw.githubusercontent.com/shirok/Gauche/ecaf82f72e2e946f62d99ed8febe0df8960d20c4/examples/japanize.scm | scheme | This is just a joke.
-----------------------------------------------
examples | -*- coding : utf-8 -*-
(define-syntax λ
(syntax-rules () ((_ args body ...) (lambda args body ...))))
(define-syntax 定義
(syntax-rules (は)
((_ (f . args) body ...)
(define (f . args) body ...))
((_ var val)
(define var val))
((_ var は val)
(define var val))))
(define-syntax もし
(syntax-rules (ならば でなければ)
((_ test ならば then)
(if test then))
((_ test ならば then でなければ else)
(if test then else))
((_ test でなければ else)
(unless test else))
((_ test then)
(if test then))
((_ test then else)
(if test then else))))
(define-syntax 代入
(syntax-rules (へ)
((_ var へ val)
(set! var val))
((_ var val)
(set! var val))))
(define-syntax 局所定義
(syntax-rules (は)
((_ ((var は val) ...) body ...)
(let ((var val) ...) body ...))
((_ ((var val) ...) body ...)
(let ((var val) ...) body ...))
))
(define-syntax 順次局所定義
(syntax-rules (は)
((_ ((var は val) ...) body ...)
(let* ((var val) ...) body ...))
((_ ((var val) ...) body ...)
(let* ((var val) ...) body ...))
))
(define-syntax 再帰局所定義
(syntax-rules (は)
((_ ((var は val) ...) body ...)
(letrec ((var val) ...) body ...))
((_ ((var val) ...) body ...)
(letrec ((var val) ...) body ...))
))
(define < <)
(define ≦ <=)
(define = =)
(define > >)
(define ≧ >=)
(define + +)
(define − -)
(define × *)
(define ÷ /)
(define 文字列→リスト string->list)
(define 逆リスト reverse)
(定義 階乗 は
(λ (n) (もし (≦ n 2) ならば n でなければ (× n (階乗 (− n 1))))))
(定義 回文か? は
(λ (文字列)
(順次局所定義 ((文字リスト は (文字列→リスト 文字列))
(逆文字リスト は (逆リスト 文字リスト)))
(equal? 逆文字リスト 文字リスト))))
|
dbb01330db3ee331b2c8af8a2aa012b7abf2552b0320b98a0657b1cc3e2e58e0 | yzhs/ocamlllvm | unused_var.ml | (***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 2004 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
$ I d : unused_var.ml 11110 2011 - 07 - 04 21:15:01Z doligez $
open Parsetree
let silent v = String.length v > 0 && v.[0] = '_';;
let add_vars tbl (vll1, vll2) =
let add_var (v, _loc, used) = Hashtbl.add tbl v used in
List.iter add_var vll1;
List.iter add_var vll2;
;;
let rm_vars tbl (vll1, vll2) =
let rm_var (v, _, _) = Hashtbl.remove tbl v in
List.iter rm_var vll1;
List.iter rm_var vll2;
;;
let w_suspicious x = Warnings.Unused_var x;;
let w_strict x = Warnings.Unused_var_strict x;;
let check_rm_vars ppf tbl (vlul_pat, vlul_as) =
let check_rm_var kind (v, loc, used) =
if not !used && not (silent v)
then Location.print_warning loc ppf (kind v);
Hashtbl.remove tbl v;
in
List.iter (check_rm_var w_strict) vlul_pat;
List.iter (check_rm_var w_suspicious) vlul_as;
;;
let check_rm_let ppf tbl vlulpl =
let check_rm_one flag (v, loc, used) =
Hashtbl.remove tbl v;
flag && (silent v || not !used)
in
let warn_var w_kind (v, loc, used) =
if not (silent v) && not !used
then Location.print_warning loc ppf (w_kind v)
in
let check_rm_pat (def, def_as) =
let def_unused = List.fold_left check_rm_one true def in
let all_unused = List.fold_left check_rm_one def_unused def_as in
List.iter (warn_var (if all_unused then w_suspicious else w_strict)) def;
List.iter (warn_var w_suspicious) def_as;
in
List.iter check_rm_pat vlulpl;
;;
let rec get_vars ((vacc, asacc) as acc) p =
match p.ppat_desc with
| Ppat_any -> acc
| Ppat_var v -> ((v, p.ppat_loc, ref false) :: vacc, asacc)
| Ppat_alias (pp, v) ->
get_vars (vacc, ((v, p.ppat_loc, ref false) :: asacc)) pp
| Ppat_constant _ -> acc
| Ppat_tuple pl -> List.fold_left get_vars acc pl
| Ppat_construct (_, po, _) -> get_vars_option acc po
| Ppat_variant (_, po) -> get_vars_option acc po
| Ppat_record (ipl, cls) ->
List.fold_left (fun a (_, p) -> get_vars a p) acc ipl
| Ppat_array pl -> List.fold_left get_vars acc pl
| Ppat_or (p1, _p2) -> get_vars acc p1
| Ppat_lazy p -> get_vars acc p
| Ppat_constraint (pp, _) -> get_vars acc pp
| Ppat_type _ -> acc
and get_vars_option acc po =
match po with
| Some p -> get_vars acc p
| None -> acc
;;
let get_pel_vars pel =
List.map (fun (p, _) -> get_vars ([], []) p) pel
;;
let rec structure ppf tbl l =
List.iter (structure_item ppf tbl) l
and structure_item ppf tbl s =
match s.pstr_desc with
| Pstr_eval e -> expression ppf tbl e;
| Pstr_value (recflag, pel) -> let_pel ppf tbl recflag pel None;
| Pstr_primitive _ -> ()
| Pstr_type _ -> ()
| Pstr_exception _ -> ()
| Pstr_exn_rebind _ -> ()
| Pstr_module (_, me) -> module_expr ppf tbl me;
| Pstr_recmodule stml ->
List.iter (fun (_, _, me) -> module_expr ppf tbl me) stml;
| Pstr_modtype _ -> ()
| Pstr_open _ -> ()
| Pstr_class cdl -> List.iter (class_declaration ppf tbl) cdl;
| Pstr_class_type _ -> ()
| Pstr_include me -> module_expr ppf tbl me;
and expression ppf tbl e =
match e.pexp_desc with
| Pexp_ident (Longident.Lident id) ->
begin try (Hashtbl.find tbl id) := true;
with Not_found -> ()
end;
| Pexp_ident _ -> ()
| Pexp_constant _ -> ()
| Pexp_let (recflag, pel, e) ->
let_pel ppf tbl recflag pel (Some (fun ppf tbl -> expression ppf tbl e));
| Pexp_function (_, eo, pel) ->
expression_option ppf tbl eo;
match_pel ppf tbl pel;
| Pexp_apply (e, lel) ->
expression ppf tbl e;
List.iter (fun (_, e) -> expression ppf tbl e) lel;
| Pexp_match (e, pel) ->
expression ppf tbl e;
match_pel ppf tbl pel;
| Pexp_try (e, pel) ->
expression ppf tbl e;
match_pel ppf tbl pel;
| Pexp_tuple el -> List.iter (expression ppf tbl) el;
| Pexp_construct (_, eo, _) -> expression_option ppf tbl eo;
| Pexp_variant (_, eo) -> expression_option ppf tbl eo;
| Pexp_record (iel, eo) ->
List.iter (fun (_, e) -> expression ppf tbl e) iel;
expression_option ppf tbl eo;
| Pexp_field (e, _) -> expression ppf tbl e;
| Pexp_setfield (e1, _, e2) ->
expression ppf tbl e1;
expression ppf tbl e2;
| Pexp_array el -> List.iter (expression ppf tbl) el;
| Pexp_ifthenelse (e1, e2, eo) ->
expression ppf tbl e1;
expression ppf tbl e2;
expression_option ppf tbl eo;
| Pexp_sequence (e1, e2) ->
expression ppf tbl e1;
expression ppf tbl e2;
| Pexp_while (e1, e2) ->
expression ppf tbl e1;
expression ppf tbl e2;
| Pexp_for (id, e1, e2, _, e3) ->
expression ppf tbl e1;
expression ppf tbl e2;
let defined = ([ (id, e.pexp_loc, ref true) ], []) in
add_vars tbl defined;
expression ppf tbl e3;
check_rm_vars ppf tbl defined;
| Pexp_constraint (e, _, _) -> expression ppf tbl e;
| Pexp_when (e1, e2) ->
expression ppf tbl e1;
expression ppf tbl e2;
| Pexp_send (e, _) -> expression ppf tbl e;
| Pexp_new _ -> ()
| Pexp_setinstvar (_, e) -> expression ppf tbl e;
| Pexp_override sel -> List.iter (fun (_, e) -> expression ppf tbl e) sel;
| Pexp_letmodule (_, me, e) ->
module_expr ppf tbl me;
expression ppf tbl e;
| Pexp_assert e -> expression ppf tbl e;
| Pexp_assertfalse -> ()
| Pexp_lazy e -> expression ppf tbl e;
| Pexp_poly (e, _) -> expression ppf tbl e;
| Pexp_object cs -> class_structure ppf tbl cs;
| Pexp_newtype (_, e) -> expression ppf tbl e
| Pexp_pack (me, _) -> module_expr ppf tbl me
| Pexp_open (_, e) -> expression ppf tbl e
and expression_option ppf tbl eo =
match eo with
| Some e -> expression ppf tbl e;
| None -> ()
and let_pel ppf tbl recflag pel body =
match recflag with
| Asttypes.Recursive ->
let defined = get_pel_vars pel in
List.iter (add_vars tbl) defined;
List.iter (fun (_, e) -> expression ppf tbl e) pel;
begin match body with
| None ->
List.iter (rm_vars tbl) defined;
| Some f ->
f ppf tbl;
check_rm_let ppf tbl defined;
end;
| _ ->
List.iter (fun (_, e) -> expression ppf tbl e) pel;
begin match body with
| None -> ()
| Some f ->
let defined = get_pel_vars pel in
List.iter (add_vars tbl) defined;
f ppf tbl;
check_rm_let ppf tbl defined;
end;
and match_pel ppf tbl pel =
List.iter (match_pe ppf tbl) pel
and match_pe ppf tbl (p, e) =
let defined = get_vars ([], []) p in
add_vars tbl defined;
expression ppf tbl e;
check_rm_vars ppf tbl defined;
and module_expr ppf tbl me =
match me.pmod_desc with
| Pmod_ident _ -> ()
| Pmod_structure s -> structure ppf tbl s
| Pmod_functor (_, _, me) -> module_expr ppf tbl me
| Pmod_apply (me1, me2) ->
module_expr ppf tbl me1;
module_expr ppf tbl me2;
| Pmod_constraint (me, _) -> module_expr ppf tbl me
| Pmod_unpack (e, _) -> expression ppf tbl e
and class_declaration ppf tbl cd = class_expr ppf tbl cd.pci_expr
and class_expr ppf tbl ce =
match ce.pcl_desc with
| Pcl_constr _ -> ()
| Pcl_structure cs -> class_structure ppf tbl cs;
| Pcl_fun (_, _, _, ce) -> class_expr ppf tbl ce;
| Pcl_apply (ce, lel) ->
class_expr ppf tbl ce;
List.iter (fun (_, e) -> expression ppf tbl e) lel;
| Pcl_let (recflag, pel, ce) ->
let_pel ppf tbl recflag pel (Some (fun ppf tbl -> class_expr ppf tbl ce));
| Pcl_constraint (ce, _) -> class_expr ppf tbl ce;
and class_structure ppf tbl (p, cfl) =
let defined = get_vars ([], []) p in
add_vars tbl defined;
List.iter (class_field ppf tbl) cfl;
check_rm_vars ppf tbl defined;
and class_field ppf tbl cf =
match cf with
| Pcf_inher (_, ce, _) -> class_expr ppf tbl ce;
| Pcf_val (_, _, _, e, _) -> expression ppf tbl e;
| Pcf_virt _ | Pcf_valvirt _ -> ()
| Pcf_meth (_, _, _, e, _) -> expression ppf tbl e;
| Pcf_cstr _ -> ()
| Pcf_let (recflag, pel, _) -> let_pel ppf tbl recflag pel None;
| Pcf_init e -> expression ppf tbl e;
;;
let warn ppf ast =
if Warnings.is_active (w_suspicious "") || Warnings.is_active (w_strict "")
then begin
let tbl = Hashtbl.create 97 in
structure ppf tbl ast;
end;
ast
;;
| null | https://raw.githubusercontent.com/yzhs/ocamlllvm/45cbf449d81f2ef9d234968e49a4305aaa39ace2/src/typing/unused_var.ml | ocaml | *********************************************************************
Objective Caml
********************************************************************* | , projet Cristal , INRIA Rocquencourt
Copyright 2004 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
$ I d : unused_var.ml 11110 2011 - 07 - 04 21:15:01Z doligez $
open Parsetree
let silent v = String.length v > 0 && v.[0] = '_';;
let add_vars tbl (vll1, vll2) =
let add_var (v, _loc, used) = Hashtbl.add tbl v used in
List.iter add_var vll1;
List.iter add_var vll2;
;;
let rm_vars tbl (vll1, vll2) =
let rm_var (v, _, _) = Hashtbl.remove tbl v in
List.iter rm_var vll1;
List.iter rm_var vll2;
;;
let w_suspicious x = Warnings.Unused_var x;;
let w_strict x = Warnings.Unused_var_strict x;;
let check_rm_vars ppf tbl (vlul_pat, vlul_as) =
let check_rm_var kind (v, loc, used) =
if not !used && not (silent v)
then Location.print_warning loc ppf (kind v);
Hashtbl.remove tbl v;
in
List.iter (check_rm_var w_strict) vlul_pat;
List.iter (check_rm_var w_suspicious) vlul_as;
;;
let check_rm_let ppf tbl vlulpl =
let check_rm_one flag (v, loc, used) =
Hashtbl.remove tbl v;
flag && (silent v || not !used)
in
let warn_var w_kind (v, loc, used) =
if not (silent v) && not !used
then Location.print_warning loc ppf (w_kind v)
in
let check_rm_pat (def, def_as) =
let def_unused = List.fold_left check_rm_one true def in
let all_unused = List.fold_left check_rm_one def_unused def_as in
List.iter (warn_var (if all_unused then w_suspicious else w_strict)) def;
List.iter (warn_var w_suspicious) def_as;
in
List.iter check_rm_pat vlulpl;
;;
let rec get_vars ((vacc, asacc) as acc) p =
match p.ppat_desc with
| Ppat_any -> acc
| Ppat_var v -> ((v, p.ppat_loc, ref false) :: vacc, asacc)
| Ppat_alias (pp, v) ->
get_vars (vacc, ((v, p.ppat_loc, ref false) :: asacc)) pp
| Ppat_constant _ -> acc
| Ppat_tuple pl -> List.fold_left get_vars acc pl
| Ppat_construct (_, po, _) -> get_vars_option acc po
| Ppat_variant (_, po) -> get_vars_option acc po
| Ppat_record (ipl, cls) ->
List.fold_left (fun a (_, p) -> get_vars a p) acc ipl
| Ppat_array pl -> List.fold_left get_vars acc pl
| Ppat_or (p1, _p2) -> get_vars acc p1
| Ppat_lazy p -> get_vars acc p
| Ppat_constraint (pp, _) -> get_vars acc pp
| Ppat_type _ -> acc
and get_vars_option acc po =
match po with
| Some p -> get_vars acc p
| None -> acc
;;
let get_pel_vars pel =
List.map (fun (p, _) -> get_vars ([], []) p) pel
;;
let rec structure ppf tbl l =
List.iter (structure_item ppf tbl) l
and structure_item ppf tbl s =
match s.pstr_desc with
| Pstr_eval e -> expression ppf tbl e;
| Pstr_value (recflag, pel) -> let_pel ppf tbl recflag pel None;
| Pstr_primitive _ -> ()
| Pstr_type _ -> ()
| Pstr_exception _ -> ()
| Pstr_exn_rebind _ -> ()
| Pstr_module (_, me) -> module_expr ppf tbl me;
| Pstr_recmodule stml ->
List.iter (fun (_, _, me) -> module_expr ppf tbl me) stml;
| Pstr_modtype _ -> ()
| Pstr_open _ -> ()
| Pstr_class cdl -> List.iter (class_declaration ppf tbl) cdl;
| Pstr_class_type _ -> ()
| Pstr_include me -> module_expr ppf tbl me;
and expression ppf tbl e =
match e.pexp_desc with
| Pexp_ident (Longident.Lident id) ->
begin try (Hashtbl.find tbl id) := true;
with Not_found -> ()
end;
| Pexp_ident _ -> ()
| Pexp_constant _ -> ()
| Pexp_let (recflag, pel, e) ->
let_pel ppf tbl recflag pel (Some (fun ppf tbl -> expression ppf tbl e));
| Pexp_function (_, eo, pel) ->
expression_option ppf tbl eo;
match_pel ppf tbl pel;
| Pexp_apply (e, lel) ->
expression ppf tbl e;
List.iter (fun (_, e) -> expression ppf tbl e) lel;
| Pexp_match (e, pel) ->
expression ppf tbl e;
match_pel ppf tbl pel;
| Pexp_try (e, pel) ->
expression ppf tbl e;
match_pel ppf tbl pel;
| Pexp_tuple el -> List.iter (expression ppf tbl) el;
| Pexp_construct (_, eo, _) -> expression_option ppf tbl eo;
| Pexp_variant (_, eo) -> expression_option ppf tbl eo;
| Pexp_record (iel, eo) ->
List.iter (fun (_, e) -> expression ppf tbl e) iel;
expression_option ppf tbl eo;
| Pexp_field (e, _) -> expression ppf tbl e;
| Pexp_setfield (e1, _, e2) ->
expression ppf tbl e1;
expression ppf tbl e2;
| Pexp_array el -> List.iter (expression ppf tbl) el;
| Pexp_ifthenelse (e1, e2, eo) ->
expression ppf tbl e1;
expression ppf tbl e2;
expression_option ppf tbl eo;
| Pexp_sequence (e1, e2) ->
expression ppf tbl e1;
expression ppf tbl e2;
| Pexp_while (e1, e2) ->
expression ppf tbl e1;
expression ppf tbl e2;
| Pexp_for (id, e1, e2, _, e3) ->
expression ppf tbl e1;
expression ppf tbl e2;
let defined = ([ (id, e.pexp_loc, ref true) ], []) in
add_vars tbl defined;
expression ppf tbl e3;
check_rm_vars ppf tbl defined;
| Pexp_constraint (e, _, _) -> expression ppf tbl e;
| Pexp_when (e1, e2) ->
expression ppf tbl e1;
expression ppf tbl e2;
| Pexp_send (e, _) -> expression ppf tbl e;
| Pexp_new _ -> ()
| Pexp_setinstvar (_, e) -> expression ppf tbl e;
| Pexp_override sel -> List.iter (fun (_, e) -> expression ppf tbl e) sel;
| Pexp_letmodule (_, me, e) ->
module_expr ppf tbl me;
expression ppf tbl e;
| Pexp_assert e -> expression ppf tbl e;
| Pexp_assertfalse -> ()
| Pexp_lazy e -> expression ppf tbl e;
| Pexp_poly (e, _) -> expression ppf tbl e;
| Pexp_object cs -> class_structure ppf tbl cs;
| Pexp_newtype (_, e) -> expression ppf tbl e
| Pexp_pack (me, _) -> module_expr ppf tbl me
| Pexp_open (_, e) -> expression ppf tbl e
and expression_option ppf tbl eo =
match eo with
| Some e -> expression ppf tbl e;
| None -> ()
and let_pel ppf tbl recflag pel body =
match recflag with
| Asttypes.Recursive ->
let defined = get_pel_vars pel in
List.iter (add_vars tbl) defined;
List.iter (fun (_, e) -> expression ppf tbl e) pel;
begin match body with
| None ->
List.iter (rm_vars tbl) defined;
| Some f ->
f ppf tbl;
check_rm_let ppf tbl defined;
end;
| _ ->
List.iter (fun (_, e) -> expression ppf tbl e) pel;
begin match body with
| None -> ()
| Some f ->
let defined = get_pel_vars pel in
List.iter (add_vars tbl) defined;
f ppf tbl;
check_rm_let ppf tbl defined;
end;
and match_pel ppf tbl pel =
List.iter (match_pe ppf tbl) pel
and match_pe ppf tbl (p, e) =
let defined = get_vars ([], []) p in
add_vars tbl defined;
expression ppf tbl e;
check_rm_vars ppf tbl defined;
and module_expr ppf tbl me =
match me.pmod_desc with
| Pmod_ident _ -> ()
| Pmod_structure s -> structure ppf tbl s
| Pmod_functor (_, _, me) -> module_expr ppf tbl me
| Pmod_apply (me1, me2) ->
module_expr ppf tbl me1;
module_expr ppf tbl me2;
| Pmod_constraint (me, _) -> module_expr ppf tbl me
| Pmod_unpack (e, _) -> expression ppf tbl e
and class_declaration ppf tbl cd = class_expr ppf tbl cd.pci_expr
and class_expr ppf tbl ce =
match ce.pcl_desc with
| Pcl_constr _ -> ()
| Pcl_structure cs -> class_structure ppf tbl cs;
| Pcl_fun (_, _, _, ce) -> class_expr ppf tbl ce;
| Pcl_apply (ce, lel) ->
class_expr ppf tbl ce;
List.iter (fun (_, e) -> expression ppf tbl e) lel;
| Pcl_let (recflag, pel, ce) ->
let_pel ppf tbl recflag pel (Some (fun ppf tbl -> class_expr ppf tbl ce));
| Pcl_constraint (ce, _) -> class_expr ppf tbl ce;
and class_structure ppf tbl (p, cfl) =
let defined = get_vars ([], []) p in
add_vars tbl defined;
List.iter (class_field ppf tbl) cfl;
check_rm_vars ppf tbl defined;
and class_field ppf tbl cf =
match cf with
| Pcf_inher (_, ce, _) -> class_expr ppf tbl ce;
| Pcf_val (_, _, _, e, _) -> expression ppf tbl e;
| Pcf_virt _ | Pcf_valvirt _ -> ()
| Pcf_meth (_, _, _, e, _) -> expression ppf tbl e;
| Pcf_cstr _ -> ()
| Pcf_let (recflag, pel, _) -> let_pel ppf tbl recflag pel None;
| Pcf_init e -> expression ppf tbl e;
;;
let warn ppf ast =
if Warnings.is_active (w_suspicious "") || Warnings.is_active (w_strict "")
then begin
let tbl = Hashtbl.create 97 in
structure ppf tbl ast;
end;
ast
;;
|
9e8c849680eef6a68f28f07adb796aff17daa454aaf0b5328938dad9c64c3843 | input-output-hk/ouroboros-network | ChainProducerState.hs | {-# LANGUAGE DataKinds #-}
# LANGUAGE NamedFieldPuns #
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
# OPTIONS_GHC -Wno - incomplete - uni - patterns #
module Test.ChainProducerState
( ChainProducerStateTest (..)
, ChainProducerStateForkTest (..)
, tests
) where
import Data.List (unfoldr)
import qualified Data.Map as Map
import Test.QuickCheck
import Test.Tasty
import Test.Tasty.QuickCheck
import Ouroboros.Network.Block (HasHeader, genesisPoint, pointSlot)
import Ouroboros.Network.Mock.Chain (Chain, ChainUpdate (..),
Point (..), headPoint, pointOnChain)
import qualified Ouroboros.Network.Mock.Chain as Chain
import Ouroboros.Network.Mock.ConcreteBlock (Block)
import Ouroboros.Network.Mock.ProducerState
import Test.ChainGenerators (TestBlockChain (..),
TestBlockChainAndUpdates (..), TestChainFork (..),
mkRollbackPoint)
tests :: TestTree
tests =
testGroup "ChainProducerState"
[ testGroup "Test Arbitrary instances"
[ testProperty "ChainProducerStateForkTest's generator"
prop_arbitrary_ChainProducerStateForkTest
, testProperty "ChainProducerStateForkTest's shrinker"
(withMaxSuccess 25 prop_shrink_ChainProducerStateForkTest)
]
, testProperty "check initial follower state" prop_init_lookup
, testProperty "check second follower state" prop_init_next_lookup
, testProperty "check follower state after updateFollower" prop_update_lookup
, testProperty "check follower state after updateFollower2" prop_update_next_lookup
, testProperty "producer syncronise (1)" prop_producer_sync1
, testProperty "producer syncronise (2)" prop_producer_sync2
, testProperty "switch fork" prop_switchFork
]
--
-- Properties
--
-- | Check that followers start in the expected state, at the right point and
-- in the rollback state.
--
prop_init_lookup :: ChainProducerStateTest -> Bool
prop_init_lookup (ChainProducerStateTest c _ p) =
let (c', rid) = initFollower p c in
lookupFollower c' rid == FollowerState p FollowerBackTo
-- | As above but check that when we move the follower on by one, from the
-- rollback state, they stay at the same point but are now in the forward state.
--
prop_init_next_lookup :: ChainProducerStateTest -> Bool
prop_init_next_lookup (ChainProducerStateTest c _ p) =
let (c', rid) = initFollower p c
Just (u, c'') = followerInstruction rid c'
in u == RollBack p
&& lookupFollower c'' rid == FollowerState p FollowerForwardFrom
-- | Check that after moving the follower point that the follower is in the
-- expected state, at the right point and in the rollback state.
--
prop_update_lookup :: ChainProducerStateTest -> Bool
prop_update_lookup (ChainProducerStateTest c rid p) =
let c' = updateFollower rid p c in
lookupFollower c' rid == FollowerState p FollowerBackTo
-- | As above but check that when we move the follower on by one, from the
-- rollback state, they stay at the same point but are now in the forward state.
--
prop_update_next_lookup :: ChainProducerStateTest -> Bool
prop_update_next_lookup (ChainProducerStateTest c rid p) =
let c' = updateFollower rid p c
Just (u, c'') = followerInstruction rid c'
in u == RollBack p
&& lookupFollower c'' rid == FollowerState p FollowerForwardFrom
-- | This says that if we take a chain producer and apply a bunch of updates
-- and initialise a consumer to the producer's initial chain, then by
-- applying update instructions from the producer to the consumer then the
-- consumer ends up in the same final state.
--
-- The limitation of this test is that it applies all the updates to the
producer first and then syncronises without changing the producer .
--
prop_producer_sync1 :: TestBlockChainAndUpdates -> Bool
prop_producer_sync1 (TestBlockChainAndUpdates c us) =
let producer0 = initChainProducerState c
(producer1, rid) = initFollower (Chain.headPoint c) producer0
Just producer = applyChainUpdates us producer1
consumer0 = c
consumerUpdates = iterateFollowerUntilDone rid producer
Just consumer = Chain.applyChainUpdates consumerUpdates consumer0
in
consumer == producerChain producer
where
iterateFollowerUntilDone rid = unfoldr (followerInstruction rid)
-- | A variation on 'prop_producer_sync1' where we take an arbitrary
-- interleaving of applying changes to the producer and doing syncronisation
-- steps between the producer and consumer.
--
prop_producer_sync2 :: TestBlockChainAndUpdates -> [Bool] -> Bool
prop_producer_sync2 (TestBlockChainAndUpdates chain0 us0) choices =
let producer0 = initChainProducerState chain0
(producer1, rid) = initFollower (Chain.headPoint chain0) producer0
consumer0 = chain0
(producer,
consumer) = go rid producer1 consumer0 choices us0
in consumer == producerChain producer
where
-- apply update to producer
go rid p c (False:bs) (u:us) =
let Just p' = applyChainUpdate u p
in go rid p' c bs us
-- all producer updates are done
go rid p c (False:_bs) [] = go rid p c [] []
-- apply update to consumer
go rid p c (True:bs) us =
case followerInstruction rid p of
Nothing -> go rid p c bs us
Just (u, p') -> go rid p' c' bs us
where Just c' = Chain.applyChainUpdate u c
-- producer is not changing, just run consumer
go rid p c [] _ =
case followerInstruction rid p of
Nothing -> (p, c)
Just (u, p') -> go rid p' c' [] []
where Just c' = Chain.applyChainUpdate u c
prop_switchFork :: ChainProducerStateForkTest -> Bool
prop_switchFork (ChainProducerStateForkTest cps f) =
let cps' = switchFork f cps
in
invChainProducerState cps'
&& all
(uncurry followerInv)
(zip (followerStates cps) (followerStates cps'))
where
followerInv :: HasHeader block
=> FollowerState block -> FollowerState block -> Bool
followerInv fs fs'
-- points only move backward
= pointSlot (followerPoint fs') <= pointSlot (followerPoint fs)
if follower 's point moves back , ` followerNext ` is changed to ` FollowerBackTo `
&& ((pointSlot (followerPoint fs') < pointSlot (followerPoint fs)) `implies` (followerNext fs' == FollowerBackTo))
-- if follower's point is not changed, also next instruction is not changed
&& ((followerPoint fs' == followerPoint fs) `implies` (followerNext fs' == followerNext fs))
implies :: Bool -> Bool -> Bool
implies a b = not a || b
followerStates :: ChainProducerState block -> [FollowerState block]
followerStates = map snd . Map.toAscList . chainFollowers
--
-- Generators
--
data ChainProducerStateTest
= ChainProducerStateTest
(ChainProducerState Block) -- ^ producer state with a single follower
FollowerId -- ^ follower's id
(Point Block) -- ^ intersection point of the follower
deriving Show
genFollowerState :: Int -- ^ length of the chain
-> Chain Block
-> Gen (FollowerState Block)
genFollowerState n c = do
followerPoint <- frequency
[ (2, return (headPoint c))
, (2, return (mkRollbackPoint c n))
, (8, mkRollbackPoint c <$> choose (1, fromIntegral n - 1))
]
followerNext <- oneof
[ return FollowerForwardFrom
, return FollowerBackTo
]
return $ FollowerState{followerPoint, followerNext}
instance Arbitrary ChainProducerStateTest where
arbitrary = do
TestBlockChain c <- arbitrary
let n = Chain.length c
rs <- Map.fromList . zip [0..] <$> listOf1 (genFollowerState n c)
rid <- choose (0, length rs - 1)
p <- if n == 0
then return genesisPoint
else mkRollbackPoint c <$> choose (0, n)
return (ChainProducerStateTest (ChainProducerState c rs (length rs)) rid p)
data ChainProducerStateForkTest
= ChainProducerStateForkTest
(ChainProducerState Block) -- ^ chain producer state
(Chain Block) -- ^ fork of the producer's chain
deriving Show
instance Arbitrary ChainProducerStateForkTest where
arbitrary = do
TestChainFork _ c f <- arbitrary
let l = Chain.length c
rs <- Map.fromList . zip [0..] <$> listOf (genFollowerState l c)
return $ ChainProducerStateForkTest (ChainProducerState c rs (length rs)) f
shrink (ChainProducerStateForkTest (ChainProducerState c rs nr) f)
-- shrink followers
= [ ChainProducerStateForkTest (ChainProducerState c rs' nr) f
| rs' <- map Map.fromList . shrinkList (const []) . Map.toList $ rs
]
-- shrink the fork chain
++ [ ChainProducerStateForkTest (ChainProducerState c rs nr) f'
| TestBlockChain f' <- shrink (TestBlockChain f)
]
-- shrink chain and fix up followers
++ [ ChainProducerStateForkTest (ChainProducerState c' (fixupFollowerPointer c' <$> rs) nr) f
| TestBlockChain c' <- shrink (TestBlockChain c)
]
where
fixupFollowerPointer :: Chain Block -> FollowerState Block -> FollowerState Block
fixupFollowerPointer c' fs@FollowerState{followerPoint} =
if pointOnChain followerPoint c'
then fs
else fs { followerPoint = headPoint c' }
prop_arbitrary_ChainProducerStateForkTest :: ChainProducerStateForkTest -> Bool
prop_arbitrary_ChainProducerStateForkTest (ChainProducerStateForkTest c f) =
invChainProducerState c && Chain.valid f
prop_shrink_ChainProducerStateForkTest :: ChainProducerStateForkTest -> Bool
prop_shrink_ChainProducerStateForkTest c =
and [ invChainProducerState c' && Chain.valid f
| ChainProducerStateForkTest c' f <- shrink c
]
| null | https://raw.githubusercontent.com/input-output-hk/ouroboros-network/2793b6993c8f6ed158f432055fa4ef581acdb661/ouroboros-network-protocols/testlib/Test/ChainProducerState.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
Properties
| Check that followers start in the expected state, at the right point and
in the rollback state.
| As above but check that when we move the follower on by one, from the
rollback state, they stay at the same point but are now in the forward state.
| Check that after moving the follower point that the follower is in the
expected state, at the right point and in the rollback state.
| As above but check that when we move the follower on by one, from the
rollback state, they stay at the same point but are now in the forward state.
| This says that if we take a chain producer and apply a bunch of updates
and initialise a consumer to the producer's initial chain, then by
applying update instructions from the producer to the consumer then the
consumer ends up in the same final state.
The limitation of this test is that it applies all the updates to the
| A variation on 'prop_producer_sync1' where we take an arbitrary
interleaving of applying changes to the producer and doing syncronisation
steps between the producer and consumer.
apply update to producer
all producer updates are done
apply update to consumer
producer is not changing, just run consumer
points only move backward
if follower's point is not changed, also next instruction is not changed
Generators
^ producer state with a single follower
^ follower's id
^ intersection point of the follower
^ length of the chain
^ chain producer state
^ fork of the producer's chain
shrink followers
shrink the fork chain
shrink chain and fix up followers | # LANGUAGE NamedFieldPuns #
# OPTIONS_GHC -Wno - incomplete - uni - patterns #
module Test.ChainProducerState
( ChainProducerStateTest (..)
, ChainProducerStateForkTest (..)
, tests
) where
import Data.List (unfoldr)
import qualified Data.Map as Map
import Test.QuickCheck
import Test.Tasty
import Test.Tasty.QuickCheck
import Ouroboros.Network.Block (HasHeader, genesisPoint, pointSlot)
import Ouroboros.Network.Mock.Chain (Chain, ChainUpdate (..),
Point (..), headPoint, pointOnChain)
import qualified Ouroboros.Network.Mock.Chain as Chain
import Ouroboros.Network.Mock.ConcreteBlock (Block)
import Ouroboros.Network.Mock.ProducerState
import Test.ChainGenerators (TestBlockChain (..),
TestBlockChainAndUpdates (..), TestChainFork (..),
mkRollbackPoint)
tests :: TestTree
tests =
testGroup "ChainProducerState"
[ testGroup "Test Arbitrary instances"
[ testProperty "ChainProducerStateForkTest's generator"
prop_arbitrary_ChainProducerStateForkTest
, testProperty "ChainProducerStateForkTest's shrinker"
(withMaxSuccess 25 prop_shrink_ChainProducerStateForkTest)
]
, testProperty "check initial follower state" prop_init_lookup
, testProperty "check second follower state" prop_init_next_lookup
, testProperty "check follower state after updateFollower" prop_update_lookup
, testProperty "check follower state after updateFollower2" prop_update_next_lookup
, testProperty "producer syncronise (1)" prop_producer_sync1
, testProperty "producer syncronise (2)" prop_producer_sync2
, testProperty "switch fork" prop_switchFork
]
prop_init_lookup :: ChainProducerStateTest -> Bool
prop_init_lookup (ChainProducerStateTest c _ p) =
let (c', rid) = initFollower p c in
lookupFollower c' rid == FollowerState p FollowerBackTo
prop_init_next_lookup :: ChainProducerStateTest -> Bool
prop_init_next_lookup (ChainProducerStateTest c _ p) =
let (c', rid) = initFollower p c
Just (u, c'') = followerInstruction rid c'
in u == RollBack p
&& lookupFollower c'' rid == FollowerState p FollowerForwardFrom
prop_update_lookup :: ChainProducerStateTest -> Bool
prop_update_lookup (ChainProducerStateTest c rid p) =
let c' = updateFollower rid p c in
lookupFollower c' rid == FollowerState p FollowerBackTo
prop_update_next_lookup :: ChainProducerStateTest -> Bool
prop_update_next_lookup (ChainProducerStateTest c rid p) =
let c' = updateFollower rid p c
Just (u, c'') = followerInstruction rid c'
in u == RollBack p
&& lookupFollower c'' rid == FollowerState p FollowerForwardFrom
producer first and then syncronises without changing the producer .
prop_producer_sync1 :: TestBlockChainAndUpdates -> Bool
prop_producer_sync1 (TestBlockChainAndUpdates c us) =
let producer0 = initChainProducerState c
(producer1, rid) = initFollower (Chain.headPoint c) producer0
Just producer = applyChainUpdates us producer1
consumer0 = c
consumerUpdates = iterateFollowerUntilDone rid producer
Just consumer = Chain.applyChainUpdates consumerUpdates consumer0
in
consumer == producerChain producer
where
iterateFollowerUntilDone rid = unfoldr (followerInstruction rid)
prop_producer_sync2 :: TestBlockChainAndUpdates -> [Bool] -> Bool
prop_producer_sync2 (TestBlockChainAndUpdates chain0 us0) choices =
let producer0 = initChainProducerState chain0
(producer1, rid) = initFollower (Chain.headPoint chain0) producer0
consumer0 = chain0
(producer,
consumer) = go rid producer1 consumer0 choices us0
in consumer == producerChain producer
where
go rid p c (False:bs) (u:us) =
let Just p' = applyChainUpdate u p
in go rid p' c bs us
go rid p c (False:_bs) [] = go rid p c [] []
go rid p c (True:bs) us =
case followerInstruction rid p of
Nothing -> go rid p c bs us
Just (u, p') -> go rid p' c' bs us
where Just c' = Chain.applyChainUpdate u c
go rid p c [] _ =
case followerInstruction rid p of
Nothing -> (p, c)
Just (u, p') -> go rid p' c' [] []
where Just c' = Chain.applyChainUpdate u c
prop_switchFork :: ChainProducerStateForkTest -> Bool
prop_switchFork (ChainProducerStateForkTest cps f) =
let cps' = switchFork f cps
in
invChainProducerState cps'
&& all
(uncurry followerInv)
(zip (followerStates cps) (followerStates cps'))
where
followerInv :: HasHeader block
=> FollowerState block -> FollowerState block -> Bool
followerInv fs fs'
= pointSlot (followerPoint fs') <= pointSlot (followerPoint fs)
if follower 's point moves back , ` followerNext ` is changed to ` FollowerBackTo `
&& ((pointSlot (followerPoint fs') < pointSlot (followerPoint fs)) `implies` (followerNext fs' == FollowerBackTo))
&& ((followerPoint fs' == followerPoint fs) `implies` (followerNext fs' == followerNext fs))
implies :: Bool -> Bool -> Bool
implies a b = not a || b
followerStates :: ChainProducerState block -> [FollowerState block]
followerStates = map snd . Map.toAscList . chainFollowers
data ChainProducerStateTest
= ChainProducerStateTest
deriving Show
-> Chain Block
-> Gen (FollowerState Block)
genFollowerState n c = do
followerPoint <- frequency
[ (2, return (headPoint c))
, (2, return (mkRollbackPoint c n))
, (8, mkRollbackPoint c <$> choose (1, fromIntegral n - 1))
]
followerNext <- oneof
[ return FollowerForwardFrom
, return FollowerBackTo
]
return $ FollowerState{followerPoint, followerNext}
instance Arbitrary ChainProducerStateTest where
arbitrary = do
TestBlockChain c <- arbitrary
let n = Chain.length c
rs <- Map.fromList . zip [0..] <$> listOf1 (genFollowerState n c)
rid <- choose (0, length rs - 1)
p <- if n == 0
then return genesisPoint
else mkRollbackPoint c <$> choose (0, n)
return (ChainProducerStateTest (ChainProducerState c rs (length rs)) rid p)
data ChainProducerStateForkTest
= ChainProducerStateForkTest
deriving Show
instance Arbitrary ChainProducerStateForkTest where
arbitrary = do
TestChainFork _ c f <- arbitrary
let l = Chain.length c
rs <- Map.fromList . zip [0..] <$> listOf (genFollowerState l c)
return $ ChainProducerStateForkTest (ChainProducerState c rs (length rs)) f
shrink (ChainProducerStateForkTest (ChainProducerState c rs nr) f)
= [ ChainProducerStateForkTest (ChainProducerState c rs' nr) f
| rs' <- map Map.fromList . shrinkList (const []) . Map.toList $ rs
]
++ [ ChainProducerStateForkTest (ChainProducerState c rs nr) f'
| TestBlockChain f' <- shrink (TestBlockChain f)
]
++ [ ChainProducerStateForkTest (ChainProducerState c' (fixupFollowerPointer c' <$> rs) nr) f
| TestBlockChain c' <- shrink (TestBlockChain c)
]
where
fixupFollowerPointer :: Chain Block -> FollowerState Block -> FollowerState Block
fixupFollowerPointer c' fs@FollowerState{followerPoint} =
if pointOnChain followerPoint c'
then fs
else fs { followerPoint = headPoint c' }
prop_arbitrary_ChainProducerStateForkTest :: ChainProducerStateForkTest -> Bool
prop_arbitrary_ChainProducerStateForkTest (ChainProducerStateForkTest c f) =
invChainProducerState c && Chain.valid f
prop_shrink_ChainProducerStateForkTest :: ChainProducerStateForkTest -> Bool
prop_shrink_ChainProducerStateForkTest c =
and [ invChainProducerState c' && Chain.valid f
| ChainProducerStateForkTest c' f <- shrink c
]
|
609400ccd065614d721a74eb8ff0d45968959f30e398e0ee5583fdfebed8f3d5 | skroutz/clj-skroutz | favorite_lists.clj | (ns clj_skroutz.favorite_lists
"Implements user favorite lists endpoints.
/"
(:use [clj_skroutz.core :refer [api-call]]))
(defn all
"Lists all favorite lists of a user.
/#list-favorite-lists"
[& options]
(api-call :get "favorite_lists" [] options))
(defn create
"Creates a new favorite list.
/#create-a-favoritelist"
[name & options]
(api-call :post "favorite_lists" []
(conj options ["query_params" {"favorite_list[name]" name}])))
(defn destroy
"Destroys a favorite list.
/#destroy-a-favoritelist"
[id & options]
(api-call :delete "favorite_lists/%s" [id] options))
(defn favorites
"Lists favorites from a list.
/#list-favorites-belonging-to-list"
[id & options]
(api-call :get "favorite_lists/%s/favorites" [id] options))
| null | https://raw.githubusercontent.com/skroutz/clj-skroutz/25c6c32f5ac8d5ea082ef4dbede6720f74d15ef0/src/clj_skroutz/favorite_lists.clj | clojure | (ns clj_skroutz.favorite_lists
"Implements user favorite lists endpoints.
/"
(:use [clj_skroutz.core :refer [api-call]]))
(defn all
"Lists all favorite lists of a user.
/#list-favorite-lists"
[& options]
(api-call :get "favorite_lists" [] options))
(defn create
"Creates a new favorite list.
/#create-a-favoritelist"
[name & options]
(api-call :post "favorite_lists" []
(conj options ["query_params" {"favorite_list[name]" name}])))
(defn destroy
"Destroys a favorite list.
/#destroy-a-favoritelist"
[id & options]
(api-call :delete "favorite_lists/%s" [id] options))
(defn favorites
"Lists favorites from a list.
/#list-favorites-belonging-to-list"
[id & options]
(api-call :get "favorite_lists/%s/favorites" [id] options))
| |
0c25f6646bebc52386a4460410e3ee03eff4c3573d59e634330b19baeb918bb6 | cram-code/cram_core | offline-episode-knowledge.lisp | ;;;
Copyright ( c ) 2009 - 2010
;;; 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.
;;;
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
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.
;;;
(in-package #:cram-execution-trace)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Offline episodes
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; NOTE ON THREAD SAFETY
;;;
We guarantee no thread safety for offline episodes . We do n't see why one
;;; would need to access this from multiple threads. If the use case arises,
;;; we can change it.
(defclass offline-episode-knowledge (episode-knowledge)
((max-time :reader max-time
:type timestamp)
(task-list :reader task-list
:type list)
(goal-task-list :reader goal-task-list
:type list)
(fluent-changes-hash-table :type hash-table)
(fluent-durations-hash-table :type hash-table)))
(defmethod initialize-instance :after ((episode offline-episode-knowledge)
&key &allow-other-keys)
(with-slots (execution-trace max-time zero-time task-tree task-list
goal-task-list fluent-changes-hash-table fluent-durations-hash-table)
episode
(setf max-time (calculate-max-time execution-trace #'identity zero-time)
task-list (calculate-task-list task-tree)
goal-task-list (calculate-goal-task-list task-list)
fluent-changes-hash-table (copy-hash-table execution-trace
:key #'calculate-fluent-changes)
fluent-durations-hash-table (copy-hash-table fluent-changes-hash-table
:key (rcurry #'changes->durations
max-time)))))
(defmethod task-tree ((episode offline-episode-knowledge))
(slot-value episode 'task-tree))
(defmethod traced-fluent-instances ((episode offline-episode-knowledge) fluent-name)
(with-slots (execution-trace) episode
(gethash fluent-name execution-trace)))
(defmethod fluent-changes ((episode offline-episode-knowledge) fluent-name)
(with-slots (fluent-changes-hash-table) episode
(gethash fluent-name fluent-changes-hash-table)))
(defmethod fluent-durations ((episode offline-episode-knowledge) fluent-name)
(with-slots (fluent-durations-hash-table) episode
(gethash fluent-name fluent-durations-hash-table)))
(defmethod traced-fluents-hash-table ((episode offline-episode-knowledge))
(slot-value episode 'execution-trace))
(defmethod traced-fluent-names ((episode offline-episode-knowledge))
(with-slots (execution-trace) episode
(hash-table-keys execution-trace)))
(defmethod running-p ((episode offline-episode-knowledge))
(declare (ignore episode))
nil)
| null | https://raw.githubusercontent.com/cram-code/cram_core/984046abe2ec9e25b63e52007ed3b857c3d9a13c/cram_execution_trace/src/episode-knowledge/offline-episode-knowledge.lisp | lisp |
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.
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
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.
Offline episodes
NOTE ON THREAD SAFETY
would need to access this from multiple threads. If the use case arises,
we can change it. | Copyright ( c ) 2009 - 2010
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR
LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN
(in-package #:cram-execution-trace)
We guarantee no thread safety for offline episodes . We do n't see why one
(defclass offline-episode-knowledge (episode-knowledge)
((max-time :reader max-time
:type timestamp)
(task-list :reader task-list
:type list)
(goal-task-list :reader goal-task-list
:type list)
(fluent-changes-hash-table :type hash-table)
(fluent-durations-hash-table :type hash-table)))
(defmethod initialize-instance :after ((episode offline-episode-knowledge)
&key &allow-other-keys)
(with-slots (execution-trace max-time zero-time task-tree task-list
goal-task-list fluent-changes-hash-table fluent-durations-hash-table)
episode
(setf max-time (calculate-max-time execution-trace #'identity zero-time)
task-list (calculate-task-list task-tree)
goal-task-list (calculate-goal-task-list task-list)
fluent-changes-hash-table (copy-hash-table execution-trace
:key #'calculate-fluent-changes)
fluent-durations-hash-table (copy-hash-table fluent-changes-hash-table
:key (rcurry #'changes->durations
max-time)))))
(defmethod task-tree ((episode offline-episode-knowledge))
(slot-value episode 'task-tree))
(defmethod traced-fluent-instances ((episode offline-episode-knowledge) fluent-name)
(with-slots (execution-trace) episode
(gethash fluent-name execution-trace)))
(defmethod fluent-changes ((episode offline-episode-knowledge) fluent-name)
(with-slots (fluent-changes-hash-table) episode
(gethash fluent-name fluent-changes-hash-table)))
(defmethod fluent-durations ((episode offline-episode-knowledge) fluent-name)
(with-slots (fluent-durations-hash-table) episode
(gethash fluent-name fluent-durations-hash-table)))
(defmethod traced-fluents-hash-table ((episode offline-episode-knowledge))
(slot-value episode 'execution-trace))
(defmethod traced-fluent-names ((episode offline-episode-knowledge))
(with-slots (execution-trace) episode
(hash-table-keys execution-trace)))
(defmethod running-p ((episode offline-episode-knowledge))
(declare (ignore episode))
nil)
|
9119229d96ca2d0027024ec4e505302399f7ba3f1ac73457d16f081a211bd3d2 | CryptoKami/cryptokami-core | Lens.hs | # LANGUAGE TypeOperators #
-- | Lenses for main blockchain types.
--
Lenses whose name starts with ` mainBlock ' are from ' MainBlock ' to
-- small parts of it. It makes it clear what exactly is stored in
' MainBlock ' . Similar fact is true for ` mainHeader ' prefix .
module Pos.Core.Block.Main.Lens
(
-- * MainToSign
msHeaderHash
, msBodyProof
, msSlot
, msChainDiff
, msExtraHeader
-- * Extra types
, mehBlockVersion
, mehSoftwareVersion
, mehAttributes
, mebAttributes
-- * MainConsensusData
, mcdSlot
, mcdLeaderKey
, mcdDifficulty
, mcdSignature
-- * MainBlockHeader
, mainHeaderPrevBlock
, mainHeaderProof
, mainHeaderSlot
, mainHeaderLeaderKey
, mainHeaderDifficulty
, mainHeaderSignature
, mainHeaderBlockVersion
, mainHeaderSoftwareVersion
, mainHeaderAttributes
-- * MainBody
, mbSscPayload
, mbTxPayload
, mbDlgPayload
, mbUpdatePayload
, mbTxs
, mbWitnesses
* MainBlock
, mainBlockPrevBlock
, mainBlockProof
, mainBlockSlot
, mainBlockLeaderKey
, mainBlockDifficulty
, mainBlockSignature
, mainBlockBlockVersion
, mainBlockSoftwareVersion
, mainBlockHeaderAttributes
, mainBlockEBDataProof
, mainBlockTxPayload
, mainBlockSscPayload
, mainBlockDlgPayload
, mainBlockUpdatePayload
, mainBlockAttributes
) where
import Universum
import Control.Lens (makeLenses)
import Pos.Core.Block.Blockchain (gbBody, gbExtra, gbHeader, gbPrevBlock, gbhBodyProof,
gbhConsensus, gbhExtra, gbhPrevBlock)
import Pos.Core.Block.Main.Chain (Body (..), BodyProof (..), ConsensusData (..))
import Pos.Core.Block.Main.Types (BlockBodyAttributes, BlockHeaderAttributes,
BlockSignature, MainBlock, MainBlockHeader,
MainBlockchain, MainExtraBodyData, MainExtraHeaderData,
MainToSign (..))
import Pos.Core.Common (ChainDifficulty, HeaderHash)
import Pos.Core.Delegation (DlgPayload)
import Pos.Core.Slotting.Types (SlotId)
import Pos.Core.Ssc (SscPayload)
import Pos.Core.Txp (Tx, TxPayload, TxWitness, txpTxs, txpWitnesses)
import Pos.Core.Update (BlockVersion, SoftwareVersion, UpdatePayload)
import Pos.Crypto (Hash, PublicKey)
import Pos.Merkle (MerkleTree)
----------------------------------------------------------------------------
-- MainToSign
----------------------------------------------------------------------------
makeLenses ''MainToSign
----------------------------------------------------------------------------
-- Extra types
----------------------------------------------------------------------------
makeLenses ''MainExtraHeaderData
makeLenses ''MainExtraBodyData
----------------------------------------------------------------------------
-- MainConsensusData
----------------------------------------------------------------------------
makeLenses 'MainConsensusData
----------------------------------------------------------------------------
-- MainBlockHeader
----------------------------------------------------------------------------
| Lens from ' MainBlockHeader ' to ' HeaderHash ' of its parent .
mainHeaderPrevBlock :: Lens' MainBlockHeader HeaderHash
mainHeaderPrevBlock = gbhPrevBlock
| Lens from ' MainBlockHeader ' to ' MainProof ' .
mainHeaderProof ::
Lens' MainBlockHeader (BodyProof MainBlockchain)
mainHeaderProof = gbhBodyProof
-- | Lens from 'MainBlockHeader' to 'SlotId'.
mainHeaderSlot :: Lens' MainBlockHeader SlotId
mainHeaderSlot = gbhConsensus . mcdSlot
| Lens from ' MainBlockHeader ' to ' PublicKey ' .
mainHeaderLeaderKey :: Lens' MainBlockHeader PublicKey
mainHeaderLeaderKey = gbhConsensus . mcdLeaderKey
| Lens from ' MainBlockHeader ' to ' ChainDifficulty ' .
mainHeaderDifficulty :: Lens' MainBlockHeader ChainDifficulty
mainHeaderDifficulty = gbhConsensus . mcdDifficulty
-- | Lens from 'MainBlockHeader' to 'Signature'.
mainHeaderSignature :: Lens' MainBlockHeader BlockSignature
mainHeaderSignature = gbhConsensus . mcdSignature
-- | Lens from 'MainBlockHeader' to 'BlockVersion'.
mainHeaderBlockVersion ::
Lens' MainBlockHeader BlockVersion
mainHeaderBlockVersion = gbhExtra . mehBlockVersion
-- | Lens from 'MainBlockHeader' to 'SoftwareVersion'.
mainHeaderSoftwareVersion ::
Lens' MainBlockHeader SoftwareVersion
mainHeaderSoftwareVersion = gbhExtra . mehSoftwareVersion
-- | Lens from 'MainBlockHeader' to 'BlockHeaderAttributes'.
mainHeaderAttributes ::
Lens' MainBlockHeader BlockHeaderAttributes
mainHeaderAttributes = gbhExtra . mehAttributes
-- | Lens from 'MainBlockHeader' to 'MainExtraBodyData'
mainHeaderEBDataProof ::
Lens' MainBlockHeader (Hash MainExtraBodyData)
mainHeaderEBDataProof = gbhExtra . mehEBDataProof
----------------------------------------------------------------------------
-- MainBody
----------------------------------------------------------------------------
makeLenses 'MainBody
-- | Lens for transaction tree in main block body.
mbTxs :: Lens' (Body MainBlockchain) (MerkleTree Tx)
mbTxs = mbTxPayload . txpTxs
-- | Lens for witness list in main block body.
mbWitnesses :: Lens' (Body MainBlockchain) [TxWitness]
mbWitnesses = mbTxPayload . txpWitnesses
----------------------------------------------------------------------------
MainBlock
----------------------------------------------------------------------------
| Lens from ' MainBlock ' to ' HeaderHash ' of its parent .
mainBlockPrevBlock :: Lens' MainBlock HeaderHash
mainBlockPrevBlock = gbPrevBlock
| Lens from ' MainBlock ' to ' MainProof ' .
mainBlockProof :: Lens' MainBlock (BodyProof MainBlockchain)
mainBlockProof = gbHeader . mainHeaderProof
| Lens from ' MainBlock ' to ' SlotId ' .
mainBlockSlot :: Lens' MainBlock SlotId
mainBlockSlot = gbHeader . mainHeaderSlot
| Lens from ' MainBlock ' to ' PublicKey ' .
mainBlockLeaderKey :: Lens' MainBlock PublicKey
mainBlockLeaderKey = gbHeader . mainHeaderLeaderKey
| Lens from ' MainBlock ' to ' ChainDifficulty ' .
mainBlockDifficulty :: Lens' MainBlock ChainDifficulty
mainBlockDifficulty = gbHeader . mainHeaderDifficulty
| Lens from ' MainBlock ' to ' Signature ' .
mainBlockSignature :: Lens' MainBlock BlockSignature
mainBlockSignature = gbHeader . mainHeaderSignature
| Lens from ' MainBlock ' to ' BlockVersion ' .
mainBlockBlockVersion ::
Lens' MainBlock BlockVersion
mainBlockBlockVersion = gbHeader . mainHeaderBlockVersion
| Lens from ' MainBlock ' to ' SoftwareVersion ' .
mainBlockSoftwareVersion ::
Lens' MainBlock SoftwareVersion
mainBlockSoftwareVersion = gbHeader . mainHeaderSoftwareVersion
| Lens from ' MainBlock ' to ' BlockHeaderAttributes ' .
mainBlockHeaderAttributes ::
Lens' MainBlock BlockHeaderAttributes
mainBlockHeaderAttributes = gbHeader . mainHeaderAttributes
| Lens from ' MainBlock ' to proof ( hash ) of ' MainExtraBodyData ' .
mainBlockEBDataProof ::
Lens' MainBlock (Hash MainExtraBodyData)
mainBlockEBDataProof = gbHeader . mainHeaderEBDataProof
| Lens from ' MainBlock ' to ' TxPayload ' .
mainBlockTxPayload :: Lens' MainBlock TxPayload
mainBlockTxPayload = gbBody . mbTxPayload
| Lens from ' MainBlock ' to ' SscPayload ' .
mainBlockSscPayload :: Lens' MainBlock SscPayload
mainBlockSscPayload = gbBody . mbSscPayload
| Lens from ' MainBlock ' to ' UpdatePayload ' .
mainBlockUpdatePayload :: Lens' MainBlock UpdatePayload
mainBlockUpdatePayload = gbBody . mbUpdatePayload
| Lens from ' MainBlock ' to ' DlgPayload ' .
mainBlockDlgPayload :: Lens' MainBlock DlgPayload
mainBlockDlgPayload = gbBody . mbDlgPayload
| Lens from ' MainBlock ' to ' BlockBodyAttributes ' .
mainBlockAttributes :: Lens' MainBlock BlockBodyAttributes
mainBlockAttributes = gbExtra . mebAttributes
| null | https://raw.githubusercontent.com/CryptoKami/cryptokami-core/12ca60a9ad167b6327397b3b2f928c19436ae114/core/Pos/Core/Block/Main/Lens.hs | haskell | | Lenses for main blockchain types.
small parts of it. It makes it clear what exactly is stored in
* MainToSign
* Extra types
* MainConsensusData
* MainBlockHeader
* MainBody
--------------------------------------------------------------------------
MainToSign
--------------------------------------------------------------------------
--------------------------------------------------------------------------
Extra types
--------------------------------------------------------------------------
--------------------------------------------------------------------------
MainConsensusData
--------------------------------------------------------------------------
--------------------------------------------------------------------------
MainBlockHeader
--------------------------------------------------------------------------
| Lens from 'MainBlockHeader' to 'SlotId'.
| Lens from 'MainBlockHeader' to 'Signature'.
| Lens from 'MainBlockHeader' to 'BlockVersion'.
| Lens from 'MainBlockHeader' to 'SoftwareVersion'.
| Lens from 'MainBlockHeader' to 'BlockHeaderAttributes'.
| Lens from 'MainBlockHeader' to 'MainExtraBodyData'
--------------------------------------------------------------------------
MainBody
--------------------------------------------------------------------------
| Lens for transaction tree in main block body.
| Lens for witness list in main block body.
--------------------------------------------------------------------------
-------------------------------------------------------------------------- | # LANGUAGE TypeOperators #
Lenses whose name starts with ` mainBlock ' are from ' MainBlock ' to
' MainBlock ' . Similar fact is true for ` mainHeader ' prefix .
module Pos.Core.Block.Main.Lens
(
msHeaderHash
, msBodyProof
, msSlot
, msChainDiff
, msExtraHeader
, mehBlockVersion
, mehSoftwareVersion
, mehAttributes
, mebAttributes
, mcdSlot
, mcdLeaderKey
, mcdDifficulty
, mcdSignature
, mainHeaderPrevBlock
, mainHeaderProof
, mainHeaderSlot
, mainHeaderLeaderKey
, mainHeaderDifficulty
, mainHeaderSignature
, mainHeaderBlockVersion
, mainHeaderSoftwareVersion
, mainHeaderAttributes
, mbSscPayload
, mbTxPayload
, mbDlgPayload
, mbUpdatePayload
, mbTxs
, mbWitnesses
* MainBlock
, mainBlockPrevBlock
, mainBlockProof
, mainBlockSlot
, mainBlockLeaderKey
, mainBlockDifficulty
, mainBlockSignature
, mainBlockBlockVersion
, mainBlockSoftwareVersion
, mainBlockHeaderAttributes
, mainBlockEBDataProof
, mainBlockTxPayload
, mainBlockSscPayload
, mainBlockDlgPayload
, mainBlockUpdatePayload
, mainBlockAttributes
) where
import Universum
import Control.Lens (makeLenses)
import Pos.Core.Block.Blockchain (gbBody, gbExtra, gbHeader, gbPrevBlock, gbhBodyProof,
gbhConsensus, gbhExtra, gbhPrevBlock)
import Pos.Core.Block.Main.Chain (Body (..), BodyProof (..), ConsensusData (..))
import Pos.Core.Block.Main.Types (BlockBodyAttributes, BlockHeaderAttributes,
BlockSignature, MainBlock, MainBlockHeader,
MainBlockchain, MainExtraBodyData, MainExtraHeaderData,
MainToSign (..))
import Pos.Core.Common (ChainDifficulty, HeaderHash)
import Pos.Core.Delegation (DlgPayload)
import Pos.Core.Slotting.Types (SlotId)
import Pos.Core.Ssc (SscPayload)
import Pos.Core.Txp (Tx, TxPayload, TxWitness, txpTxs, txpWitnesses)
import Pos.Core.Update (BlockVersion, SoftwareVersion, UpdatePayload)
import Pos.Crypto (Hash, PublicKey)
import Pos.Merkle (MerkleTree)
makeLenses ''MainToSign
makeLenses ''MainExtraHeaderData
makeLenses ''MainExtraBodyData
makeLenses 'MainConsensusData
| Lens from ' MainBlockHeader ' to ' HeaderHash ' of its parent .
mainHeaderPrevBlock :: Lens' MainBlockHeader HeaderHash
mainHeaderPrevBlock = gbhPrevBlock
| Lens from ' MainBlockHeader ' to ' MainProof ' .
mainHeaderProof ::
Lens' MainBlockHeader (BodyProof MainBlockchain)
mainHeaderProof = gbhBodyProof
mainHeaderSlot :: Lens' MainBlockHeader SlotId
mainHeaderSlot = gbhConsensus . mcdSlot
| Lens from ' MainBlockHeader ' to ' PublicKey ' .
mainHeaderLeaderKey :: Lens' MainBlockHeader PublicKey
mainHeaderLeaderKey = gbhConsensus . mcdLeaderKey
| Lens from ' MainBlockHeader ' to ' ChainDifficulty ' .
mainHeaderDifficulty :: Lens' MainBlockHeader ChainDifficulty
mainHeaderDifficulty = gbhConsensus . mcdDifficulty
mainHeaderSignature :: Lens' MainBlockHeader BlockSignature
mainHeaderSignature = gbhConsensus . mcdSignature
mainHeaderBlockVersion ::
Lens' MainBlockHeader BlockVersion
mainHeaderBlockVersion = gbhExtra . mehBlockVersion
mainHeaderSoftwareVersion ::
Lens' MainBlockHeader SoftwareVersion
mainHeaderSoftwareVersion = gbhExtra . mehSoftwareVersion
mainHeaderAttributes ::
Lens' MainBlockHeader BlockHeaderAttributes
mainHeaderAttributes = gbhExtra . mehAttributes
mainHeaderEBDataProof ::
Lens' MainBlockHeader (Hash MainExtraBodyData)
mainHeaderEBDataProof = gbhExtra . mehEBDataProof
makeLenses 'MainBody
mbTxs :: Lens' (Body MainBlockchain) (MerkleTree Tx)
mbTxs = mbTxPayload . txpTxs
mbWitnesses :: Lens' (Body MainBlockchain) [TxWitness]
mbWitnesses = mbTxPayload . txpWitnesses
MainBlock
| Lens from ' MainBlock ' to ' HeaderHash ' of its parent .
mainBlockPrevBlock :: Lens' MainBlock HeaderHash
mainBlockPrevBlock = gbPrevBlock
| Lens from ' MainBlock ' to ' MainProof ' .
mainBlockProof :: Lens' MainBlock (BodyProof MainBlockchain)
mainBlockProof = gbHeader . mainHeaderProof
| Lens from ' MainBlock ' to ' SlotId ' .
mainBlockSlot :: Lens' MainBlock SlotId
mainBlockSlot = gbHeader . mainHeaderSlot
| Lens from ' MainBlock ' to ' PublicKey ' .
mainBlockLeaderKey :: Lens' MainBlock PublicKey
mainBlockLeaderKey = gbHeader . mainHeaderLeaderKey
| Lens from ' MainBlock ' to ' ChainDifficulty ' .
mainBlockDifficulty :: Lens' MainBlock ChainDifficulty
mainBlockDifficulty = gbHeader . mainHeaderDifficulty
| Lens from ' MainBlock ' to ' Signature ' .
mainBlockSignature :: Lens' MainBlock BlockSignature
mainBlockSignature = gbHeader . mainHeaderSignature
| Lens from ' MainBlock ' to ' BlockVersion ' .
mainBlockBlockVersion ::
Lens' MainBlock BlockVersion
mainBlockBlockVersion = gbHeader . mainHeaderBlockVersion
| Lens from ' MainBlock ' to ' SoftwareVersion ' .
mainBlockSoftwareVersion ::
Lens' MainBlock SoftwareVersion
mainBlockSoftwareVersion = gbHeader . mainHeaderSoftwareVersion
| Lens from ' MainBlock ' to ' BlockHeaderAttributes ' .
mainBlockHeaderAttributes ::
Lens' MainBlock BlockHeaderAttributes
mainBlockHeaderAttributes = gbHeader . mainHeaderAttributes
| Lens from ' MainBlock ' to proof ( hash ) of ' MainExtraBodyData ' .
mainBlockEBDataProof ::
Lens' MainBlock (Hash MainExtraBodyData)
mainBlockEBDataProof = gbHeader . mainHeaderEBDataProof
| Lens from ' MainBlock ' to ' TxPayload ' .
mainBlockTxPayload :: Lens' MainBlock TxPayload
mainBlockTxPayload = gbBody . mbTxPayload
| Lens from ' MainBlock ' to ' SscPayload ' .
mainBlockSscPayload :: Lens' MainBlock SscPayload
mainBlockSscPayload = gbBody . mbSscPayload
| Lens from ' MainBlock ' to ' UpdatePayload ' .
mainBlockUpdatePayload :: Lens' MainBlock UpdatePayload
mainBlockUpdatePayload = gbBody . mbUpdatePayload
| Lens from ' MainBlock ' to ' DlgPayload ' .
mainBlockDlgPayload :: Lens' MainBlock DlgPayload
mainBlockDlgPayload = gbBody . mbDlgPayload
| Lens from ' MainBlock ' to ' BlockBodyAttributes ' .
mainBlockAttributes :: Lens' MainBlock BlockBodyAttributes
mainBlockAttributes = gbExtra . mebAttributes
|
8e1c3b7f6c10491f7000d8e0bf98a6bca5e169709c607698c006577c92fd7cd2 | Clojure2D/clojure2d-examples | interval.clj | (ns rt4.in-one-weekend.ch10b.interval
(:refer-clojure :exclude [empty])
(:require [fastmath.core :as m]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(m/use-primitive-operators)
(defprotocol IntervalProto
(contains [interval x]) ;; a <= x <= b
;; introduced due to the bug in the book (in the time of writing this code), a < x <= b
(contains- [interval x])
(clamp [interval x]))
(defrecord Interval [^double mn ^double mx]
IntervalProto
(contains [_ x] (m/between? mn mx ^double x))
(contains- [_ x] (m/between-? mn mx ^double x))
(clamp [_ x] (m/constrain ^double x mn mx)))
(defn interval
([] (->Interval ##Inf ##-Inf))
([m] (map->Interval m))
([^double mn ^double mx] (->Interval mn mx)))
(def empty (interval))
(def universe (interval ##-Inf ##Inf))
| null | https://raw.githubusercontent.com/Clojure2D/clojure2d-examples/ead92d6f17744b91070e6308157364ad4eab8a1b/src/rt4/in_one_weekend/ch10b/interval.clj | clojure | a <= x <= b
introduced due to the bug in the book (in the time of writing this code), a < x <= b | (ns rt4.in-one-weekend.ch10b.interval
(:refer-clojure :exclude [empty])
(:require [fastmath.core :as m]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(m/use-primitive-operators)
(defprotocol IntervalProto
(contains- [interval x])
(clamp [interval x]))
(defrecord Interval [^double mn ^double mx]
IntervalProto
(contains [_ x] (m/between? mn mx ^double x))
(contains- [_ x] (m/between-? mn mx ^double x))
(clamp [_ x] (m/constrain ^double x mn mx)))
(defn interval
([] (->Interval ##Inf ##-Inf))
([m] (map->Interval m))
([^double mn ^double mx] (->Interval mn mx)))
(def empty (interval))
(def universe (interval ##-Inf ##Inf))
|
1e713de51bc8e02a0758ddc1a9c52030fc77c73981f557b673577e41777c7c5c | cedlemo/OCaml-GI-ctypes-bindings-generator | Recent_filter_info.mli | open Ctypes
type t
val t_typ : t structure typ
val f_contains: (Recent_filter_flags.t_list, t structure) field
val f_uri: (string, t structure) field
val f_display_name: (string, t structure) field
val f_mime_type: (string, t structure) field
Struct field Recent_filter_info : C Array type for Types . Array tag tag not implemented
Struct field Recent_filter_info : C Array type for Types . Array tag tag not implemented
val f_age: (int32, t structure) field
| null | https://raw.githubusercontent.com/cedlemo/OCaml-GI-ctypes-bindings-generator/21a4d449f9dbd6785131979b91aa76877bad2615/tools/Gtk3/Recent_filter_info.mli | ocaml | open Ctypes
type t
val t_typ : t structure typ
val f_contains: (Recent_filter_flags.t_list, t structure) field
val f_uri: (string, t structure) field
val f_display_name: (string, t structure) field
val f_mime_type: (string, t structure) field
Struct field Recent_filter_info : C Array type for Types . Array tag tag not implemented
Struct field Recent_filter_info : C Array type for Types . Array tag tag not implemented
val f_age: (int32, t structure) field
| |
cf66f75cb1f0de0a64dba7b50e10068f4c8f7f531429bc6b44b464d4e24e1035 | danilkolikov/dfl | ParserError.hs | # LANGUAGE FlexibleContexts #
|
Module : Frontend . Syntax . ParserError
Description : Functions for handling parser errors
Copyright : ( c ) , 2019
License : MIT
Functions for handling errors of
Module : Frontend.Syntax.ParserError
Description : Functions for handling parser errors
Copyright : (c) Danil Kolikov, 2019
License : MIT
Functions for handling errors of Megaparsec
-}
module Frontend.Syntax.ParserError where
import qualified Data.List.NonEmpty as NE
import qualified Data.Set as S
import Text.Megaparsec
( ErrorFancy(..)
, ErrorItem(..)
, ParseError(..)
, ParseErrorBundle(..)
, PosState(..)
, Token
)
import Frontend.Syntax.Position
( SourceLocation(..)
, SourcePosition(..)
, castSourcePosition
)
| Converts a error into a user - defined data type , which includes
-- a source position
wrapPositionBundle ::
(Show (Token s))
=> (SourcePosition -> Maybe (Token s) -> [String] -> a)
-> (SourcePosition -> ErrorFancy e -> a)
-> ParseErrorBundle s e
-> a
wrapPositionBundle wrapParserError wrapInnerError bundle =
let firstError = NE.head . bundleErrors $ bundle
position =
castSourcePosition . pstateSourcePos . bundlePosState $ bundle
in case firstError of
TrivialError _ got expected ->
wrapParserError
position
(getTokens' <$> got)
(getLabel <$> S.toList expected)
FancyError _ errors -> wrapInnerError position (S.findMin errors)
| Converts a error into a user - defined data type , which includes
-- a source location
wrapLocationBundle ::
(Show (Token s))
=> (Int -> SourceLocation)
-> (SourceLocation -> Maybe (Token s) -> [String] -> a)
-> (SourceLocation -> ErrorFancy e -> a)
-> ParseErrorBundle s e
-> a
wrapLocationBundle getLocation wrapParserError wrapInnerError bundle =
let firstError = NE.head . bundleErrors $ bundle
in case firstError of
TrivialError pos got expected ->
wrapParserError
(getLocation pos)
(getTokens' <$> got)
(getLabel <$> S.toList expected)
FancyError pos errors ->
wrapInnerError (getLocation pos) (S.findMin errors)
-- Helper functions
-- | Get tokens from an ErrorItem
getTokens' :: ErrorItem a -> a
getTokens' (Tokens ts) = NE.head ts
getTokens' _ = undefined
| Get label from an ErrorItem
getLabel :: (Show a) => ErrorItem a -> String
getLabel (Label chars) = NE.toList chars
getLabel (Tokens ts) = concatMap show ts
getLabel EndOfInput = "End Of Input"
| null | https://raw.githubusercontent.com/danilkolikov/dfl/698a8f32e23b381afe803fc0e353293a3bf644ba/src/Frontend/Syntax/ParserError.hs | haskell | a source position
a source location
Helper functions
| Get tokens from an ErrorItem | # LANGUAGE FlexibleContexts #
|
Module : Frontend . Syntax . ParserError
Description : Functions for handling parser errors
Copyright : ( c ) , 2019
License : MIT
Functions for handling errors of
Module : Frontend.Syntax.ParserError
Description : Functions for handling parser errors
Copyright : (c) Danil Kolikov, 2019
License : MIT
Functions for handling errors of Megaparsec
-}
module Frontend.Syntax.ParserError where
import qualified Data.List.NonEmpty as NE
import qualified Data.Set as S
import Text.Megaparsec
( ErrorFancy(..)
, ErrorItem(..)
, ParseError(..)
, ParseErrorBundle(..)
, PosState(..)
, Token
)
import Frontend.Syntax.Position
( SourceLocation(..)
, SourcePosition(..)
, castSourcePosition
)
| Converts a error into a user - defined data type , which includes
wrapPositionBundle ::
(Show (Token s))
=> (SourcePosition -> Maybe (Token s) -> [String] -> a)
-> (SourcePosition -> ErrorFancy e -> a)
-> ParseErrorBundle s e
-> a
wrapPositionBundle wrapParserError wrapInnerError bundle =
let firstError = NE.head . bundleErrors $ bundle
position =
castSourcePosition . pstateSourcePos . bundlePosState $ bundle
in case firstError of
TrivialError _ got expected ->
wrapParserError
position
(getTokens' <$> got)
(getLabel <$> S.toList expected)
FancyError _ errors -> wrapInnerError position (S.findMin errors)
| Converts a error into a user - defined data type , which includes
wrapLocationBundle ::
(Show (Token s))
=> (Int -> SourceLocation)
-> (SourceLocation -> Maybe (Token s) -> [String] -> a)
-> (SourceLocation -> ErrorFancy e -> a)
-> ParseErrorBundle s e
-> a
wrapLocationBundle getLocation wrapParserError wrapInnerError bundle =
let firstError = NE.head . bundleErrors $ bundle
in case firstError of
TrivialError pos got expected ->
wrapParserError
(getLocation pos)
(getTokens' <$> got)
(getLabel <$> S.toList expected)
FancyError pos errors ->
wrapInnerError (getLocation pos) (S.findMin errors)
getTokens' :: ErrorItem a -> a
getTokens' (Tokens ts) = NE.head ts
getTokens' _ = undefined
| Get label from an ErrorItem
getLabel :: (Show a) => ErrorItem a -> String
getLabel (Label chars) = NE.toList chars
getLabel (Tokens ts) = concatMap show ts
getLabel EndOfInput = "End Of Input"
|
7a0d8ef98bb1b12daab0bcb194348df116be1fcc9c7f44b4dfd6bd6d31861903 | vyos/vyconf | config_tree.mli | type value_behaviour = AddValue | ReplaceValue
exception Duplicate_value
exception Node_has_no_value
exception No_such_value
exception Useless_set
type config_node_data = {
values : string list;
comment : string option;
inactive : bool;
ephemeral : bool;
} [@@deriving yojson]
type t = config_node_data Vytree.t [@@deriving yojson]
val default_data : config_node_data
val make : string -> t
val set : t -> string list -> string option -> value_behaviour -> t
val delete : t -> string list -> string option -> t
val get_values : t -> string list -> string list
val get_value : t -> string list -> string
val set_comment : t -> string list -> string option -> t
val get_comment : t -> string list -> string option
val set_inactive : t -> string list -> bool -> t
val is_inactive : t -> string list -> bool
val set_ephemeral : t -> string list -> bool -> t
val is_ephemeral : t -> string list -> bool
* Interface to two rendering routines :
1 . The stand - alone routine , when [ reftree ] is not provided
2 . The reference - tree guided routine , when [ reftree ] is provided .
If an { i incomplete } reftree is supplied , then the remaining portion of the
config tree will be rendered according to the stand - alone routine .
If an { i incompatible } reftree is supplied ( i.e. , the name of the nodes of
the reftree do not match the name of the nodes in the config tree ) , then the
exception { ! Config_tree . Renderer . Inapt_reftree } is raised .
@param indent spaces by which each level of nesting should be indented
@param reftree optional reference tree used to instruct rendering
@param cmp function used to sort the order of children , overruled
if [ reftree ] specifies [ keep_order ] for a node
@param showephemeral boolean determining whether ephemeral nodes are shown
@param showinactive boolean determining whether inactive nodes are shown
1. The stand-alone routine, when [reftree] is not provided
2. The reference-tree guided routine, when [reftree] is provided.
If an {i incomplete} reftree is supplied, then the remaining portion of the
config tree will be rendered according to the stand-alone routine.
If an {i incompatible} reftree is supplied (i.e., the name of the nodes of
the reftree do not match the name of the nodes in the config tree), then the
exception {! Config_tree.Renderer.Inapt_reftree} is raised.
@param indent spaces by which each level of nesting should be indented
@param reftree optional reference tree used to instruct rendering
@param cmp function used to sort the order of children, overruled
if [reftree] specifies [keep_order] for a node
@param showephemeral boolean determining whether ephemeral nodes are shown
@param showinactive boolean determining whether inactive nodes are shown
*)
val render :
?indent:int ->
?reftree:(Reference_tree.t option)->
?cmp:(string -> string -> int) ->
?showephemeral:bool ->
?showinactive:bool ->
t ->
string
val render_at_level :
?indent:int ->
?reftree:(Reference_tree.t option)->
?cmp:(string -> string -> int) ->
?showephemeral:bool ->
?showinactive:bool ->
t ->
string list ->
string
val render_commands: ?reftree:(Reference_tree.t option) -> ?alwayssort:bool -> ?sortchildren:bool -> t -> string list -> string
| null | https://raw.githubusercontent.com/vyos/vyconf/dd9271b4304c6b1a5a2576821d1b2b8fd3aa6bf5/src/config_tree.mli | ocaml | type value_behaviour = AddValue | ReplaceValue
exception Duplicate_value
exception Node_has_no_value
exception No_such_value
exception Useless_set
type config_node_data = {
values : string list;
comment : string option;
inactive : bool;
ephemeral : bool;
} [@@deriving yojson]
type t = config_node_data Vytree.t [@@deriving yojson]
val default_data : config_node_data
val make : string -> t
val set : t -> string list -> string option -> value_behaviour -> t
val delete : t -> string list -> string option -> t
val get_values : t -> string list -> string list
val get_value : t -> string list -> string
val set_comment : t -> string list -> string option -> t
val get_comment : t -> string list -> string option
val set_inactive : t -> string list -> bool -> t
val is_inactive : t -> string list -> bool
val set_ephemeral : t -> string list -> bool -> t
val is_ephemeral : t -> string list -> bool
* Interface to two rendering routines :
1 . The stand - alone routine , when [ reftree ] is not provided
2 . The reference - tree guided routine , when [ reftree ] is provided .
If an { i incomplete } reftree is supplied , then the remaining portion of the
config tree will be rendered according to the stand - alone routine .
If an { i incompatible } reftree is supplied ( i.e. , the name of the nodes of
the reftree do not match the name of the nodes in the config tree ) , then the
exception { ! Config_tree . Renderer . Inapt_reftree } is raised .
@param indent spaces by which each level of nesting should be indented
@param reftree optional reference tree used to instruct rendering
@param cmp function used to sort the order of children , overruled
if [ reftree ] specifies [ keep_order ] for a node
@param showephemeral boolean determining whether ephemeral nodes are shown
@param showinactive boolean determining whether inactive nodes are shown
1. The stand-alone routine, when [reftree] is not provided
2. The reference-tree guided routine, when [reftree] is provided.
If an {i incomplete} reftree is supplied, then the remaining portion of the
config tree will be rendered according to the stand-alone routine.
If an {i incompatible} reftree is supplied (i.e., the name of the nodes of
the reftree do not match the name of the nodes in the config tree), then the
exception {! Config_tree.Renderer.Inapt_reftree} is raised.
@param indent spaces by which each level of nesting should be indented
@param reftree optional reference tree used to instruct rendering
@param cmp function used to sort the order of children, overruled
if [reftree] specifies [keep_order] for a node
@param showephemeral boolean determining whether ephemeral nodes are shown
@param showinactive boolean determining whether inactive nodes are shown
*)
val render :
?indent:int ->
?reftree:(Reference_tree.t option)->
?cmp:(string -> string -> int) ->
?showephemeral:bool ->
?showinactive:bool ->
t ->
string
val render_at_level :
?indent:int ->
?reftree:(Reference_tree.t option)->
?cmp:(string -> string -> int) ->
?showephemeral:bool ->
?showinactive:bool ->
t ->
string list ->
string
val render_commands: ?reftree:(Reference_tree.t option) -> ?alwayssort:bool -> ?sortchildren:bool -> t -> string list -> string
| |
cf8efb273ba287d61f668e7fbff5c47c13a8c91f5b5340418de1104a20dc050c | sebashack/servantRestfulAPI | BreadCrumbs.hs | module HelperLibs.SCalendar.BreadCrumbs where
import Control.Monad
import HelperLibs.SCalendar.DataTypes
import qualified Data.Set as S
import qualified Data.Time as TM
import qualified Data.Text as T
BreadCrumbs to move around the calendar --
data Crumb = LeftCrumb (From, To) Q QN Calendar
| RightCrumb (From, To) Q QN Calendar
deriving Eq
instance Show Crumb where
show c = "crumb"
type Breadcrumbs = [Crumb]
type CalendarZipper = (Calendar, Breadcrumbs)
goLeft :: CalendarZipper -> Maybe CalendarZipper
goLeft (Node (from, to) q qn left right, bs) =
Just (left, LeftCrumb (from, to) q qn right : bs)
goLeft (TimeUnit _ _ _, _) = Nothing
goLeft (Empty _, _) = Nothing
goRight :: CalendarZipper -> Maybe CalendarZipper
goRight(Node (from, to) q qn left right, bs) =
Just (right, RightCrumb (from, to) q qn left : bs)
goRight (TimeUnit _ _ _, _) = Nothing
goRight (Empty _, _) = Nothing
goUp :: CalendarZipper -> Maybe CalendarZipper
goUp (calendar, LeftCrumb interval q qn right : bs)
= Just (Node interval q qn calendar right, bs)
goUp (calendar, RightCrumb interval q qn left : bs)
= Just (Node interval q qn left calendar, bs)
goUp (_, []) = Nothing
upToRoot :: CalendarZipper -> Maybe CalendarZipper
upToRoot (node, []) = Just (node, [])
upToRoot zipper = do
parent <- goUp zipper
upToRoot parent
| null | https://raw.githubusercontent.com/sebashack/servantRestfulAPI/e625535d196acefaff4f5bf03108816be668fe4d/libs/HelperLibs/SCalendar/BreadCrumbs.hs | haskell | module HelperLibs.SCalendar.BreadCrumbs where
import Control.Monad
import HelperLibs.SCalendar.DataTypes
import qualified Data.Set as S
import qualified Data.Time as TM
import qualified Data.Text as T
data Crumb = LeftCrumb (From, To) Q QN Calendar
| RightCrumb (From, To) Q QN Calendar
deriving Eq
instance Show Crumb where
show c = "crumb"
type Breadcrumbs = [Crumb]
type CalendarZipper = (Calendar, Breadcrumbs)
goLeft :: CalendarZipper -> Maybe CalendarZipper
goLeft (Node (from, to) q qn left right, bs) =
Just (left, LeftCrumb (from, to) q qn right : bs)
goLeft (TimeUnit _ _ _, _) = Nothing
goLeft (Empty _, _) = Nothing
goRight :: CalendarZipper -> Maybe CalendarZipper
goRight(Node (from, to) q qn left right, bs) =
Just (right, RightCrumb (from, to) q qn left : bs)
goRight (TimeUnit _ _ _, _) = Nothing
goRight (Empty _, _) = Nothing
goUp :: CalendarZipper -> Maybe CalendarZipper
goUp (calendar, LeftCrumb interval q qn right : bs)
= Just (Node interval q qn calendar right, bs)
goUp (calendar, RightCrumb interval q qn left : bs)
= Just (Node interval q qn left calendar, bs)
goUp (_, []) = Nothing
upToRoot :: CalendarZipper -> Maybe CalendarZipper
upToRoot (node, []) = Just (node, [])
upToRoot zipper = do
parent <- goUp zipper
upToRoot parent
| |
ec97707d3915c769c95a623c6f9b01a9a2060451d1eb6cf65d1bae70e45899d5 | JustusAdam/language-haskell | CommentLike.hs | SYNTAX TEST " source.haskell " " Test ending of comment - like blocks "
{- a b -} a b
-- ^^^^^^^^^ comment.block.haskell
-- ^ ^ - comment.block.haskell
{-$ a b -} a b
-- ^^^^^^^^^^ comment.block.documentation.haskell
-- ^ ^ - comment.block.documentation.haskell
# SPECIALISE foo : : a - > b #
-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.preprocessor.haskell
-- ^ ^ - meta.preprocessor.haskell
{-@ foo :: A -> B @-} c d
^ ^ storage.type.haskell
-- ^ ^ - block.liquidhaskell.haskell
@ type NonEmpty a = { v:[a ] | 0 < len v } @
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ block.liquidhaskell.haskell
-- ^ ^ - block.liquidhaskell.haskell
| null | https://raw.githubusercontent.com/JustusAdam/language-haskell/c9ee1b3ee166c44db9ce350920ba502fcc868245/test/tests/CommentLike.hs | haskell | a b
^^^^^^^^^ comment.block.haskell
^ ^ - comment.block.haskell
$ a b
^^^^^^^^^^ comment.block.documentation.haskell
^ ^ - comment.block.documentation.haskell
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.preprocessor.haskell
^ ^ - meta.preprocessor.haskell
@ foo :: A -> B @
^ ^ - block.liquidhaskell.haskell
^ ^ - block.liquidhaskell.haskell | SYNTAX TEST " source.haskell " " Test ending of comment - like blocks "
# SPECIALISE foo : : a - > b #
^ ^ storage.type.haskell
@ type NonEmpty a = { v:[a ] | 0 < len v } @
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ block.liquidhaskell.haskell
|
da0c68e31c1f9142d200d98d78de8197824160c334e417bf1eaa1f7ad525f70b | jolby/colors | core.cljc | by
April 16 , 2010
Copyright ( c ) , 2010 . All rights reserved . The use
and distribution terms for this software are covered by the Eclipse
;; Public License 1.0 (-1.0.php)
;; which can be found in the file epl-v10.html at the root of this
;; distribution. By using this software in any fashion, you are
;; agreeing to be bound by the terms of this license. You must not
;; remove this notice, or any other, from this software.
(ns com.evocomputing.colors.palettes.core
(:use [com.evocomputing.colors :only (create-color)]))
(defn inclusive-seq
"Return n evenly spaced points along the range start - end (inclusive)."
[n start end]
(assert (pos? n))
(condp = n
1 [start]
2 [start end]
(let [numsegs (dec n)
step (/ (- end start) numsegs)]
(conj (loop [acc [] num start idx 0]
(if (= idx numsegs) acc
(recur (conj acc num) (+ step num) (inc idx)))) end))))
(defn rainbow-hsl
"Computes a rainbow of colors (qualitative palette) defined by
different hues given a single value of each saturation and lightness.
Arguments:
numcolors: Number of colors to be produced in this palette.
Optional Arguments:
:s (keyword) saturation. 0.0 - 100.0 (default 50.0)
:l (keyword) lightness. 0.0 - 100.0. (default 70.0)
:start (keyword) hue where rainbow starts. 0 - 360 (default 0)
:end (keyword) hue where rainbow ends. 0 - 360 (default: (* 360 (/ (- numcolors 1) numcolors)))
"
[numcolors & opts]
(let [opts (merge {:s 50.0 :l 70.0 :start 0 :end (* 360 (/ (- numcolors 1) numcolors))}
(when opts (apply assoc {} opts)))
hvals (inclusive-seq numcolors (:start opts) (:end opts))]
(map #(create-color :h (float %) :s (:s opts) :l (:l opts))
hvals)))
(defn diverge-hsl
"Compute a set of colors diverging
from a neutral center (grey or white, without color) to two
different extreme colors (blue and red by default). For the
diverging HSL colors, again two hues :h are needed, a maximal
saturation ':s' and two lightnesses ':l'. The colors are then created by
an interpolation between the full color hsl1,
a neutral color hsl and the other full color hsl2.
Arguments:
numcolors: Number of colors to be produced in this palette.
Optional Arguments:
:h-start (keyword) starting hue (default 260)
:h-end (keyword) ending hue (default 0)
:s (keyword) saturation. 0.0 - 100.0 (default 80.0)
:l-start (keyword) starting lightness. 0.0 - 100.0. (default 30.0)
:l-end (keyword) ending lightness. 0.0 - 100.0. (default 90.0)
:power (keyword) control parameter determining how saturation and lightness should
be increased (1 = linear, 2 = quadratic, etc.) (default 1.5)
"
[numcolors & opts]
(let [opts (merge {:h-start 260 :h-end 0
:s 80.0
:l-start 30.0 :l-end 90.0
:power 1.5}
(when opts (apply assoc {} opts)))
diff-l (- (:l-end opts) (:l-start opts))]
(map #(create-color :h (if (> % 0) (:h-start opts) (:h-end opts))
:s (* (:s opts) (Math/pow (Math/abs %) (:power opts)))
:l (- (:l-end opts) (* diff-l (Math/pow (Math/abs %) (:power opts)))))
(inclusive-seq numcolors -1.0 1.0))))
(defn sequential-hsl
"Creates a sequential palette starting at the full color
(h :s-start :l-start) through to a light color (h :s-end :l-end) by
interpolation.
Arguments:
numcolors: Number of colors to be produced in this palette.
Optional Arguments:
:h (keyword) starting hue (default 260)
:s-start (keyword) starting saturation. 0.0 - 100.0 (default 80.0)
:l-start (keyword) starting lightness. 0.0 - 100.0. (default 30.0)
:s-end (keyword) ending saturation. 0.0 - 100.0 (default 0.0)
:l-end (keyword) ending lightness. 0.0 - 100.0. (default 90.0)
:power (keyword) control parameter determining how saturation and lightness should
be increased (1 = linear, 2 = quadratic, etc.)
"
[numcolors & opts]
(let [opts (merge {:h 260
:s-start 80.0 :l-start 30.0
:s-end 0.0 :l-end 90.0 :power 1.5}
(when opts (apply assoc {} opts)))
diff-s (- (:s-end opts) (:s-start opts))
diff-l (- (:l-end opts) (:l-start opts))]
(map #(create-color :h (:h opts)
:s (- (:s-end opts) (* diff-s (Math/pow % (:power opts))))
:l (- (:l-end opts) (* diff-l (Math/pow % (:power opts)))))
(inclusive-seq numcolors 1.0 0.0))))
(defn heat-hsl
"Create heat palette in HSL space. By default, it goes from a red to
a yellow hue, while simultaneously going to lighter colors (i.e.,
increasing lightness) and reducing the amount of color (i.e.,
decreasing saturation).
Arguments:
numcolors: Number of colors to be produced in this palette.
Optional Arguments:
:h-start (keyword) starting hue (default 260)
:h-end (keyword) ending hue (default 260)
:s-start (keyword) starting saturation. 0.0 - 100.0 (default 80.0)
:l-start (keyword) starting lightness. 0.0 - 100.0. (default 30.0)
:s-end (keyword) ending saturation. 0.0 - 100.0 (default 0.0)
:l-end (keyword) ending lightness. 0.0 - 100.0. (default 90.0)
:power-saturation (keyword) control parameter determining how saturation should increase
:power-lightness (keyword) control parameter determining how lightness should increase
be increased (1 = linear, 2 = quadratic, etc.)
"
[numcolors & opts]
(let [opts (merge {:h-start 0 :h-end 90
:s-start 100.0 :s-end 30.0
:l-start 50.0 :l-end 90.0
:power-saturation 0.20 :power-lightness 1.0}
(when opts (apply assoc {} opts)))
diff-h (- (:h-end opts) (:h-start opts))
diff-s (- (:s-end opts) (:s-start opts))
diff-l (- (:l-end opts) (:l-start opts))]
(map #(create-color :h (- (:h-end opts) (* (- diff-h) %))
:s (- (:s-end opts) (* diff-s (Math/pow % (:power-saturation opts))))
:l (- (:l-end opts) (* diff-l (Math/pow % (:power-lightness opts)))))
(inclusive-seq numcolors 1.0 0.0))))
(defn terrain-hsl
"The 'terrain_hcl' palette simply calls 'heat_hcl' with
different parameters, providing suitable terrain colors."
[numcolors & opts]
(heat-hsl numcolors :h-start 130 :h-end 0
:s-start 80.0 :s-end 0.0
:l-start 60.0 :l-end 95.0
:power-saturation 0.10 :power-lightness 1.0))
| null | https://raw.githubusercontent.com/jolby/colors/30607e456cb7e80bc5b58f04b59505db92ae728e/src/com/evocomputing/colors/palettes/core.cljc | clojure | Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this
distribution. By using this software in any fashion, you are
agreeing to be bound by the terms of this license. You must not
remove this notice, or any other, from this software. | by
April 16 , 2010
Copyright ( c ) , 2010 . All rights reserved . The use
and distribution terms for this software are covered by the Eclipse
(ns com.evocomputing.colors.palettes.core
(:use [com.evocomputing.colors :only (create-color)]))
(defn inclusive-seq
"Return n evenly spaced points along the range start - end (inclusive)."
[n start end]
(assert (pos? n))
(condp = n
1 [start]
2 [start end]
(let [numsegs (dec n)
step (/ (- end start) numsegs)]
(conj (loop [acc [] num start idx 0]
(if (= idx numsegs) acc
(recur (conj acc num) (+ step num) (inc idx)))) end))))
(defn rainbow-hsl
"Computes a rainbow of colors (qualitative palette) defined by
different hues given a single value of each saturation and lightness.
Arguments:
numcolors: Number of colors to be produced in this palette.
Optional Arguments:
:s (keyword) saturation. 0.0 - 100.0 (default 50.0)
:l (keyword) lightness. 0.0 - 100.0. (default 70.0)
:start (keyword) hue where rainbow starts. 0 - 360 (default 0)
:end (keyword) hue where rainbow ends. 0 - 360 (default: (* 360 (/ (- numcolors 1) numcolors)))
"
[numcolors & opts]
(let [opts (merge {:s 50.0 :l 70.0 :start 0 :end (* 360 (/ (- numcolors 1) numcolors))}
(when opts (apply assoc {} opts)))
hvals (inclusive-seq numcolors (:start opts) (:end opts))]
(map #(create-color :h (float %) :s (:s opts) :l (:l opts))
hvals)))
(defn diverge-hsl
"Compute a set of colors diverging
from a neutral center (grey or white, without color) to two
different extreme colors (blue and red by default). For the
diverging HSL colors, again two hues :h are needed, a maximal
saturation ':s' and two lightnesses ':l'. The colors are then created by
an interpolation between the full color hsl1,
a neutral color hsl and the other full color hsl2.
Arguments:
numcolors: Number of colors to be produced in this palette.
Optional Arguments:
:h-start (keyword) starting hue (default 260)
:h-end (keyword) ending hue (default 0)
:s (keyword) saturation. 0.0 - 100.0 (default 80.0)
:l-start (keyword) starting lightness. 0.0 - 100.0. (default 30.0)
:l-end (keyword) ending lightness. 0.0 - 100.0. (default 90.0)
:power (keyword) control parameter determining how saturation and lightness should
be increased (1 = linear, 2 = quadratic, etc.) (default 1.5)
"
[numcolors & opts]
(let [opts (merge {:h-start 260 :h-end 0
:s 80.0
:l-start 30.0 :l-end 90.0
:power 1.5}
(when opts (apply assoc {} opts)))
diff-l (- (:l-end opts) (:l-start opts))]
(map #(create-color :h (if (> % 0) (:h-start opts) (:h-end opts))
:s (* (:s opts) (Math/pow (Math/abs %) (:power opts)))
:l (- (:l-end opts) (* diff-l (Math/pow (Math/abs %) (:power opts)))))
(inclusive-seq numcolors -1.0 1.0))))
(defn sequential-hsl
"Creates a sequential palette starting at the full color
(h :s-start :l-start) through to a light color (h :s-end :l-end) by
interpolation.
Arguments:
numcolors: Number of colors to be produced in this palette.
Optional Arguments:
:h (keyword) starting hue (default 260)
:s-start (keyword) starting saturation. 0.0 - 100.0 (default 80.0)
:l-start (keyword) starting lightness. 0.0 - 100.0. (default 30.0)
:s-end (keyword) ending saturation. 0.0 - 100.0 (default 0.0)
:l-end (keyword) ending lightness. 0.0 - 100.0. (default 90.0)
:power (keyword) control parameter determining how saturation and lightness should
be increased (1 = linear, 2 = quadratic, etc.)
"
[numcolors & opts]
(let [opts (merge {:h 260
:s-start 80.0 :l-start 30.0
:s-end 0.0 :l-end 90.0 :power 1.5}
(when opts (apply assoc {} opts)))
diff-s (- (:s-end opts) (:s-start opts))
diff-l (- (:l-end opts) (:l-start opts))]
(map #(create-color :h (:h opts)
:s (- (:s-end opts) (* diff-s (Math/pow % (:power opts))))
:l (- (:l-end opts) (* diff-l (Math/pow % (:power opts)))))
(inclusive-seq numcolors 1.0 0.0))))
(defn heat-hsl
"Create heat palette in HSL space. By default, it goes from a red to
a yellow hue, while simultaneously going to lighter colors (i.e.,
increasing lightness) and reducing the amount of color (i.e.,
decreasing saturation).
Arguments:
numcolors: Number of colors to be produced in this palette.
Optional Arguments:
:h-start (keyword) starting hue (default 260)
:h-end (keyword) ending hue (default 260)
:s-start (keyword) starting saturation. 0.0 - 100.0 (default 80.0)
:l-start (keyword) starting lightness. 0.0 - 100.0. (default 30.0)
:s-end (keyword) ending saturation. 0.0 - 100.0 (default 0.0)
:l-end (keyword) ending lightness. 0.0 - 100.0. (default 90.0)
:power-saturation (keyword) control parameter determining how saturation should increase
:power-lightness (keyword) control parameter determining how lightness should increase
be increased (1 = linear, 2 = quadratic, etc.)
"
[numcolors & opts]
(let [opts (merge {:h-start 0 :h-end 90
:s-start 100.0 :s-end 30.0
:l-start 50.0 :l-end 90.0
:power-saturation 0.20 :power-lightness 1.0}
(when opts (apply assoc {} opts)))
diff-h (- (:h-end opts) (:h-start opts))
diff-s (- (:s-end opts) (:s-start opts))
diff-l (- (:l-end opts) (:l-start opts))]
(map #(create-color :h (- (:h-end opts) (* (- diff-h) %))
:s (- (:s-end opts) (* diff-s (Math/pow % (:power-saturation opts))))
:l (- (:l-end opts) (* diff-l (Math/pow % (:power-lightness opts)))))
(inclusive-seq numcolors 1.0 0.0))))
(defn terrain-hsl
"The 'terrain_hcl' palette simply calls 'heat_hcl' with
different parameters, providing suitable terrain colors."
[numcolors & opts]
(heat-hsl numcolors :h-start 130 :h-end 0
:s-start 80.0 :s-end 0.0
:l-start 60.0 :l-end 95.0
:power-saturation 0.10 :power-lightness 1.0))
|
893f91e9a3b94dc1722984d8e74f1c83fffae8d8154e57596f81ebc9cd653b41 | raydeejay/cl-microvm | opcodes.lisp | -*- Mode : Lisp ; Syntax : ANSI - Common - Lisp ; Coding : utf-8 -*-
(in-package #:cl-microvm)
;; when the opcode is executed the PC is already past the operands
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; OPCODES
(defun illegal (&rest args)
(declare (ignore args))
(error "Illegal opcode"))
(defparameter *opcodes* (make-array '(32) :initial-element #'illegal))
(defparameter *opcode-names* (make-array '(32) :initial-element 'illegal))
(defmacro define-opcode (number name args &body body)
`(let ((fn (lambda (vm ,@args) ,@body)))
(setf (elt *opcodes* ,number) fn
(elt *opcode-names* ,number) ',name)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
0OP
(define-opcode #x00 nop ())
(define-opcode #x01 ret ()
(setf (pc vm) (pop (stack vm))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 1OP
;; some (or all) operators can take both an address (which can
;; represent memory/registers/ports/stack?) or a literal/constant
;; operators can take both an indirection (which can represent
;; memory/registers/ports/stack?) or a literal/constant (which can
;; represent either a numerical value or a memory address
;; w tt nnnnn
;; w represents the width of the operators
( 0 means byte - sized , 1 means word - sized )
types are encoded as the two most significant bytes of the byte
;; holding an opcode:
;; 0 being a constant/literal value,
;; 1 an indirected value
there are 32 available operators , 4 are unassigned
(define-opcode #x02 push (addr)
(push (elt (memory vm) addr) (stack vm)))
(define-opcode #x03 pop (addr)
(setf (elt (memory vm) addr)
(pop (stack vm))))
(define-opcode #x04 call (addr)
(push (pc vm) (stack vm))
(setf (pc vm) addr))
(define-opcode #x05 inc (arg)
(incf (elt (memory vm) arg)))
(define-opcode #x06 dec (addr)
(decf (elt (memory vm) addr)))
(define-opcode #x07 not (arg)
(setf (elt (memory vm) arg) (lognot (elt (memory vm) arg))))
(define-opcode #x08 jmp (address)
(setf (pc vm) address))
;; presumably these use either registers (TBI) or stack (implemented)
;; we'll go with stack for now because it's simpler, as using
;; registers requires deciding where they will reside, and
implementing MOV
(define-opcode #x09 je (address)
(when (= (pop (stack vm)) (pop (stack vm)))
(setf (pc vm) address)))
(define-opcode #x0a jne (address)
(when (/= (pop (stack vm)) (pop (stack vm)))
(setf (pc vm) address)))
(define-opcode #x0b jg (address))
(define-opcode #x0c jge (address))
(define-opcode #x0d jl (address))
;; (define-opcode #x0e jle (address))
(define-opcode #x0e prs (address)
(let ((len (elt (memory vm) address)))
(format t "~A~%" (map 'string #'code-char (subseq (memory vm) (1+ address) (+ 1 address len))))))
(define-opcode #x0f prn (address)
(princ (fetch-byte vm address)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2OP
(define-opcode #x10 mov (arg0 arg1)
;; hacked together implementation, needs more work
;; read value arg1, place at address arg0
when address is lower than 16 , use a register ?
(setf (elt (memory vm) arg0) arg1))
(define-opcode #x11 add (dest src))
(define-opcode #x12 sub (dest src))
(define-opcode #x13 mul (dest src))
(define-opcode #x14 div (dest src))
(define-opcode #x15 mod (arg0 arg1)) ; stores result in the R (result) register
(define-opcode #x16 xor (arg0 arg1))
(define-opcode #x17 or (arg0 arg1))
(define-opcode #x18 and (arg0 arg1))
(define-opcode #x19 shl (arg0 arg1))
(define-opcode #x1a shr (arg0 arg1))
(define-opcode #x1b cmp (arg0 arg1))
| null | https://raw.githubusercontent.com/raydeejay/cl-microvm/65e1d11c251f28198ed199bd2d66aa3cdd34a7c8/opcodes.lisp | lisp | Syntax : ANSI - Common - Lisp ; Coding : utf-8 -*-
when the opcode is executed the PC is already past the operands
OPCODES
1OP
some (or all) operators can take both an address (which can
represent memory/registers/ports/stack?) or a literal/constant
operators can take both an indirection (which can represent
memory/registers/ports/stack?) or a literal/constant (which can
represent either a numerical value or a memory address
w tt nnnnn
w represents the width of the operators
holding an opcode:
0 being a constant/literal value,
1 an indirected value
presumably these use either registers (TBI) or stack (implemented)
we'll go with stack for now because it's simpler, as using
registers requires deciding where they will reside, and
(define-opcode #x0e jle (address))
hacked together implementation, needs more work
read value arg1, place at address arg0
stores result in the R (result) register |
(in-package #:cl-microvm)
(defun illegal (&rest args)
(declare (ignore args))
(error "Illegal opcode"))
(defparameter *opcodes* (make-array '(32) :initial-element #'illegal))
(defparameter *opcode-names* (make-array '(32) :initial-element 'illegal))
(defmacro define-opcode (number name args &body body)
`(let ((fn (lambda (vm ,@args) ,@body)))
(setf (elt *opcodes* ,number) fn
(elt *opcode-names* ,number) ',name)))
0OP
(define-opcode #x00 nop ())
(define-opcode #x01 ret ()
(setf (pc vm) (pop (stack vm))))
( 0 means byte - sized , 1 means word - sized )
types are encoded as the two most significant bytes of the byte
there are 32 available operators , 4 are unassigned
(define-opcode #x02 push (addr)
(push (elt (memory vm) addr) (stack vm)))
(define-opcode #x03 pop (addr)
(setf (elt (memory vm) addr)
(pop (stack vm))))
(define-opcode #x04 call (addr)
(push (pc vm) (stack vm))
(setf (pc vm) addr))
(define-opcode #x05 inc (arg)
(incf (elt (memory vm) arg)))
(define-opcode #x06 dec (addr)
(decf (elt (memory vm) addr)))
(define-opcode #x07 not (arg)
(setf (elt (memory vm) arg) (lognot (elt (memory vm) arg))))
(define-opcode #x08 jmp (address)
(setf (pc vm) address))
implementing MOV
(define-opcode #x09 je (address)
(when (= (pop (stack vm)) (pop (stack vm)))
(setf (pc vm) address)))
(define-opcode #x0a jne (address)
(when (/= (pop (stack vm)) (pop (stack vm)))
(setf (pc vm) address)))
(define-opcode #x0b jg (address))
(define-opcode #x0c jge (address))
(define-opcode #x0d jl (address))
(define-opcode #x0e prs (address)
(let ((len (elt (memory vm) address)))
(format t "~A~%" (map 'string #'code-char (subseq (memory vm) (1+ address) (+ 1 address len))))))
(define-opcode #x0f prn (address)
(princ (fetch-byte vm address)))
2OP
(define-opcode #x10 mov (arg0 arg1)
when address is lower than 16 , use a register ?
(setf (elt (memory vm) arg0) arg1))
(define-opcode #x11 add (dest src))
(define-opcode #x12 sub (dest src))
(define-opcode #x13 mul (dest src))
(define-opcode #x14 div (dest src))
(define-opcode #x16 xor (arg0 arg1))
(define-opcode #x17 or (arg0 arg1))
(define-opcode #x18 and (arg0 arg1))
(define-opcode #x19 shl (arg0 arg1))
(define-opcode #x1a shr (arg0 arg1))
(define-opcode #x1b cmp (arg0 arg1))
|
72a5305475937e8d29305017eccd6b3f38300272210288f2761e71e79bd15654 | dbushenko/scotty-blog-postgres | Main.hs | {-# LANGUAGE OverloadedStrings #-}
module Main where
import Db
import Views
import Auth
import Domain
import Web.Scotty
import Web.Scotty.Internal.Types (ActionT)
import Network.Wai
import Network.Wai.Middleware.Static
import Network.Wai.Middleware.RequestLogger (logStdoutDev, logStdout)
import Network.Wai.Middleware.HttpAuth
import Control.Applicative
import Control.Monad.IO.Class
import qualified Data.Configurator as C
import qualified Data.Configurator.Types as C
import Data.Pool(Pool, createPool, withResource)
import qualified Data.Text.Lazy as TL
import Data.Aeson
import Database.PostgreSQL.Simple
Parse file " application.conf " and get the DB connection info
makeDbConfig :: C.Config -> IO (Maybe Db.DbConfig)
makeDbConfig conf = do
name <- C.lookup conf "database.name" :: IO (Maybe String)
user <- C.lookup conf "database.user" :: IO (Maybe String)
password <- C.lookup conf "database.password" :: IO (Maybe String)
return $ DbConfig <$> name
<*> user
<*> password
-- The function knows which resources are available only for the
-- authenticated users
protectedResources :: Request -> IO Bool
protectedResources request = do
let path = pathInfo request
return $ protect path
where protect (p : _) = p == "admin" -- all requests to /admin/* should be authenticated
protect _ = False -- other requests are allowed for anonymous users
main :: IO ()
main = do
loadedConf <- C.load [C.Required "application.conf"]
dbConf <- makeDbConfig loadedConf
case dbConf of
Nothing -> putStrLn "No database configuration found, terminating..."
Just conf -> do
pool <- createPool (newConn conf) close 1 40 10
scotty 3000 $ do
middleware $ staticPolicy (noDots >-> addBase "static") -- serve static files
log all requests ; for production use logStdout
middleware $ basicAuth (verifyCredentials pool) -- check if the user is authenticated for protected resources
"Haskell Blog Realm" { authIsProtected = protectedResources } -- function which restricts access to some routes only for authenticated users
-- LIST
get "/articles" $ do articles <- liftIO $ listArticles pool -- get the ist of articles for DB
articlesList articles -- show articles list
-- VIEW
get "/articles/:id" $ do id <- param "id" :: ActionM TL.Text -- get the article id from the request
maybeArticle <- liftIO $ findArticle pool id -- get the article from the DB
viewArticle maybeArticle -- show the article if it was found
-- CREATE
post "/admin/articles" $ do article <- getArticleParam -- read the request body, try to parse it into article
insertArticle pool article -- insert the parsed article into the DB
createdArticle article -- show info that the article was created
-- UPDATE
put "/admin/articles" $ do article <- getArticleParam -- read the request body, try to parse it into article
updateArticle pool article -- update parsed article in the DB
updatedArticle article -- show info that the article was updated
-- DELETE
delete "/admin/articles/:id" $ do id <- param "id" :: ActionM TL.Text -- get the article id
deleteArticle pool id -- delete the article from the DB
deletedArticle id -- show info that the article was deleted
-----------------------------------------------
Parse the request body into the Article
getArticleParam :: ActionT TL.Text IO (Maybe Article)
getArticleParam = do b <- body
return $ (decode b :: Maybe Article)
where makeArticle s = ""
| null | https://raw.githubusercontent.com/dbushenko/scotty-blog-postgres/bc5d12caf6b3052c6b6ac7023c8fe3fdd7912979/src/Main.hs | haskell | # LANGUAGE OverloadedStrings #
The function knows which resources are available only for the
authenticated users
all requests to /admin/* should be authenticated
other requests are allowed for anonymous users
serve static files
check if the user is authenticated for protected resources
function which restricts access to some routes only for authenticated users
LIST
get the ist of articles for DB
show articles list
VIEW
get the article id from the request
get the article from the DB
show the article if it was found
CREATE
read the request body, try to parse it into article
insert the parsed article into the DB
show info that the article was created
UPDATE
read the request body, try to parse it into article
update parsed article in the DB
show info that the article was updated
DELETE
get the article id
delete the article from the DB
show info that the article was deleted
--------------------------------------------- |
module Main where
import Db
import Views
import Auth
import Domain
import Web.Scotty
import Web.Scotty.Internal.Types (ActionT)
import Network.Wai
import Network.Wai.Middleware.Static
import Network.Wai.Middleware.RequestLogger (logStdoutDev, logStdout)
import Network.Wai.Middleware.HttpAuth
import Control.Applicative
import Control.Monad.IO.Class
import qualified Data.Configurator as C
import qualified Data.Configurator.Types as C
import Data.Pool(Pool, createPool, withResource)
import qualified Data.Text.Lazy as TL
import Data.Aeson
import Database.PostgreSQL.Simple
Parse file " application.conf " and get the DB connection info
makeDbConfig :: C.Config -> IO (Maybe Db.DbConfig)
makeDbConfig conf = do
name <- C.lookup conf "database.name" :: IO (Maybe String)
user <- C.lookup conf "database.user" :: IO (Maybe String)
password <- C.lookup conf "database.password" :: IO (Maybe String)
return $ DbConfig <$> name
<*> user
<*> password
protectedResources :: Request -> IO Bool
protectedResources request = do
let path = pathInfo request
return $ protect path
main :: IO ()
main = do
loadedConf <- C.load [C.Required "application.conf"]
dbConf <- makeDbConfig loadedConf
case dbConf of
Nothing -> putStrLn "No database configuration found, terminating..."
Just conf -> do
pool <- createPool (newConn conf) close 1 40 10
scotty 3000 $ do
log all requests ; for production use logStdout
Parse the request body into the Article
getArticleParam :: ActionT TL.Text IO (Maybe Article)
getArticleParam = do b <- body
return $ (decode b :: Maybe Article)
where makeArticle s = ""
|
3ff293021162f585d8f44183b683ce19bf52a93f2d74f35348e1890bbd5b0ad6 | blynn/compiler | wrap4.hs | GHC wrapper for " methodically " and friends .
$ cc -c stub.c
-- $ ghci wrap4.hs stub.o
# , LambdaCase #
# LANGUAGE CPP #
# LANGUAGE TupleSections #
# LANGUAGE NoMonomorphismRestriction #
# LANGUAGE FlexibleInstances #
# LANGUAGE QuasiQuotes #
# LANGUAGE ExtendedDefaultRules #
import Prelude (Bool(..), Char, Int, Word, String, IO)
import Data.Char (chr, ord)
import qualified Prelude
import qualified Data.Map as Map
import System.IO.Unsafe (unsafePerformIO)
import System.Exit (exitSuccess)
import Text.RawString.QQ
default (Int)
_to64 :: Word -> Word -> Word
_to64 a b = Prelude.fromIntegral a Prelude.+ Prelude.fromIntegral b Prelude.* (2 :: Word) Prelude.^ 32
_lohi :: Word -> (Word, Word)
_lohi w = (Prelude.fromIntegral r, Prelude.fromIntegral q)
where (q, r) = w `Prelude.divMod` (2 Prelude.^ 32)
intFromWord :: Word -> Int
intFromWord = Prelude.fromIntegral
word64Add a b c d = _lohi $ _to64 a b Prelude.+ _to64 c d
word64Sub a b c d = _lohi $ _to64 a b Prelude.- _to64 c d
word64Mul a b c d = _lohi $ _to64 a b Prelude.* _to64 c d
word64Div a b c d = _lohi $ _to64 a b `Prelude.div` _to64 c d
word64Mod a b c d = _lohi $ _to64 a b `Prelude.mod` _to64 c d
intAdd :: Int -> Int -> Int
intAdd = (Prelude.+)
intSub :: Int -> Int -> Int
intSub = (Prelude.-)
intMul :: Int -> Int -> Int
intMul = (Prelude.*)
intDiv :: Int -> Int -> Int
intDiv = Prelude.div
intMod :: Int -> Int -> Int
intMod = Prelude.mod
intQuot :: Int -> Int -> Int
intQuot = Prelude.quot
intRem :: Int -> Int -> Int
intRem = Prelude.rem
intEq :: Int -> Int -> Bool
intEq = (Prelude.==)
intLE :: Int -> Int -> Bool
intLE = (Prelude.<=)
wordAdd :: Word -> Word -> Word
wordAdd = (Prelude.+)
wordSub :: Word -> Word -> Word
wordSub = (Prelude.-)
wordMul :: Word -> Word -> Word
wordMul = (Prelude.*)
wordDiv :: Word -> Word -> Word
wordDiv = Prelude.div
wordMod :: Word -> Word -> Word
wordMod = Prelude.mod
wordQuot :: Word -> Word -> Word
wordQuot = Prelude.quot
wordRem :: Word -> Word -> Word
wordRem = Prelude.rem
wordEq :: Word -> Word -> Bool
wordEq = (Prelude.==)
wordLE :: Word -> Word -> Bool
wordLE = (Prelude.<=)
wordFromInt :: Int -> Word
wordFromInt = Prelude.fromIntegral
charEq :: Char -> Char -> Bool
charEq = (Prelude.==)
charLE :: Char -> Char -> Bool
charLE = (Prelude.<=)
ioPure = Prelude.pure :: a -> IO a
ioBind = (Prelude.>>=) :: IO a -> (a -> IO b) -> IO b
#include "methodically.hs"
instance Prelude.Functor Parser where fmap = fmap
instance Prelude.Applicative Parser where pure = pure ; (<*>) = (<*>)
instance Prelude.Monad Parser where return = return ; (>>=) = (>>=)
instance Prelude.Functor (Either a) where fmap = fmap
instance Prelude.Applicative (Either a) where pure = pure ; (<*>) = (<*>)
instance Prelude.Monad (Either a) where return = return ; (>>=) = (>>=)
instance Prelude.Functor Maybe where fmap = fmap
instance Prelude.Applicative Maybe where pure = pure ; (<*>) = (<*>)
instance Prelude.Monad Maybe where return = return ; (>>=) = (>>=)
instance Prelude . Show Pred where showsPrec _ = showPred
instance Prelude . Show Type where showsPrec _ = showType
instance Prelude . Show Ast where showsPrec _
instance Prelude . Show Qual where showsPrec _ = showQual
| null | https://raw.githubusercontent.com/blynn/compiler/b9fe455ad4ee4fbabe77f2f5c3c9aaa53cffa85b/wrap4.hs | haskell | $ ghci wrap4.hs stub.o | GHC wrapper for " methodically " and friends .
$ cc -c stub.c
# , LambdaCase #
# LANGUAGE CPP #
# LANGUAGE TupleSections #
# LANGUAGE NoMonomorphismRestriction #
# LANGUAGE FlexibleInstances #
# LANGUAGE QuasiQuotes #
# LANGUAGE ExtendedDefaultRules #
import Prelude (Bool(..), Char, Int, Word, String, IO)
import Data.Char (chr, ord)
import qualified Prelude
import qualified Data.Map as Map
import System.IO.Unsafe (unsafePerformIO)
import System.Exit (exitSuccess)
import Text.RawString.QQ
default (Int)
_to64 :: Word -> Word -> Word
_to64 a b = Prelude.fromIntegral a Prelude.+ Prelude.fromIntegral b Prelude.* (2 :: Word) Prelude.^ 32
_lohi :: Word -> (Word, Word)
_lohi w = (Prelude.fromIntegral r, Prelude.fromIntegral q)
where (q, r) = w `Prelude.divMod` (2 Prelude.^ 32)
intFromWord :: Word -> Int
intFromWord = Prelude.fromIntegral
word64Add a b c d = _lohi $ _to64 a b Prelude.+ _to64 c d
word64Sub a b c d = _lohi $ _to64 a b Prelude.- _to64 c d
word64Mul a b c d = _lohi $ _to64 a b Prelude.* _to64 c d
word64Div a b c d = _lohi $ _to64 a b `Prelude.div` _to64 c d
word64Mod a b c d = _lohi $ _to64 a b `Prelude.mod` _to64 c d
intAdd :: Int -> Int -> Int
intAdd = (Prelude.+)
intSub :: Int -> Int -> Int
intSub = (Prelude.-)
intMul :: Int -> Int -> Int
intMul = (Prelude.*)
intDiv :: Int -> Int -> Int
intDiv = Prelude.div
intMod :: Int -> Int -> Int
intMod = Prelude.mod
intQuot :: Int -> Int -> Int
intQuot = Prelude.quot
intRem :: Int -> Int -> Int
intRem = Prelude.rem
intEq :: Int -> Int -> Bool
intEq = (Prelude.==)
intLE :: Int -> Int -> Bool
intLE = (Prelude.<=)
wordAdd :: Word -> Word -> Word
wordAdd = (Prelude.+)
wordSub :: Word -> Word -> Word
wordSub = (Prelude.-)
wordMul :: Word -> Word -> Word
wordMul = (Prelude.*)
wordDiv :: Word -> Word -> Word
wordDiv = Prelude.div
wordMod :: Word -> Word -> Word
wordMod = Prelude.mod
wordQuot :: Word -> Word -> Word
wordQuot = Prelude.quot
wordRem :: Word -> Word -> Word
wordRem = Prelude.rem
wordEq :: Word -> Word -> Bool
wordEq = (Prelude.==)
wordLE :: Word -> Word -> Bool
wordLE = (Prelude.<=)
wordFromInt :: Int -> Word
wordFromInt = Prelude.fromIntegral
charEq :: Char -> Char -> Bool
charEq = (Prelude.==)
charLE :: Char -> Char -> Bool
charLE = (Prelude.<=)
ioPure = Prelude.pure :: a -> IO a
ioBind = (Prelude.>>=) :: IO a -> (a -> IO b) -> IO b
#include "methodically.hs"
instance Prelude.Functor Parser where fmap = fmap
instance Prelude.Applicative Parser where pure = pure ; (<*>) = (<*>)
instance Prelude.Monad Parser where return = return ; (>>=) = (>>=)
instance Prelude.Functor (Either a) where fmap = fmap
instance Prelude.Applicative (Either a) where pure = pure ; (<*>) = (<*>)
instance Prelude.Monad (Either a) where return = return ; (>>=) = (>>=)
instance Prelude.Functor Maybe where fmap = fmap
instance Prelude.Applicative Maybe where pure = pure ; (<*>) = (<*>)
instance Prelude.Monad Maybe where return = return ; (>>=) = (>>=)
instance Prelude . Show Pred where showsPrec _ = showPred
instance Prelude . Show Type where showsPrec _ = showType
instance Prelude . Show Ast where showsPrec _
instance Prelude . Show Qual where showsPrec _ = showQual
|
b5a29d240d7125aec885745134dce7acf31ef2f6ac479311bfed0bd2e98311f0 | pbevin/cardelli | Parse.hs | module Parse(parseExpr, parseFun) where
import Control.Applicative hiding (many, optional, (<|>))
import Control.Monad
import Text.Parsec
import Text.Parsec.String
import Text.Parsec.Expr
import qualified Text.Parsec.Token as T
import Text.Parsec.Language (emptyDef)
import VarName
import AST
funStyle :: T.LanguageDef st
funStyle = emptyDef{ T.commentStart = "{-"
, T.commentEnd = "-}"
, T.identStart = letter
, T.identLetter = alphaNum <|> char '_'
, T.reservedOpNames = ["="]
, T.reservedNames = ["fun", "let", "rec", "in",
"if", "then", "else"]
}
-- Exp ::=
Ide |
-- "if" Exp "then" Exp "else" Exp |
-- "fun" "(" Ide ")" Exp |
-- Exp "(" Exp ")" |
-- "let" Decl "in" Exp | "(" Exp ")"
-- Decl ::=
" = " Exp |
Decl " then " Decl | " rec " Decl |
" ( " Decl " ) "
--
lexer = T.makeTokenParser funStyle
parens = T.parens lexer
identifier = T.identifier lexer
integer = T.integer lexer
reserved = T.reserved lexer
reservedOp = T.reservedOp lexer
symbol = T.symbol lexer
atom = liftM Var identifier
number = liftM Num integer
cond :: Parser Expr
cond = do
reserved "if"
test <- expr
reserved "then"
ifTrue <- expr
reserved "else"
ifFalse <- expr
return $ Cond test ifTrue ifFalse
lambda :: Parser Expr
lambda = do
reserved "fun"
var <- parens identifier
body <- expr
return $ Lambda var body
block :: Parser Expr
block = do
reserved "let"
d <- decl
reserved "in"
e <- expr
return $ Block d e
term :: Parser Expr
term = let simpleTerm = parens(expr)
<|> cond
<|> block
<|> lambda
<|> number
<|> atom
in do
t <- simpleTerm
applications <- many (parens exprList)
return $ foldl FunCall t $ concat applications
exprList :: Parser [Expr]
exprList = expr `sepBy` (symbol ",")
mkUnOp op a = FunCall (Var op) a
mkBinOp op a b = FunCall (mkUnOp op a) b
binary name fn = Infix (do { reservedOp name; return (mkBinOp fn) }) AssocLeft
unary name fn = Prefix (do { reservedOp name; return (mkUnOp fn) })
table = [
[ unary "-" "negate" ],
[ unary "!" "not" ],
[ binary "&" "and", binary "|" "or" ],
[ binary "*" "times", binary "/" "div" ],
[ binary "+" "plus", binary "-" "minus" ],
[ binary "==" "eq" ]]
expr :: Parser Expr
expr = buildExpressionParser table term <?> "expression"
assign :: Parser Decl
assign = do
var <- identifier
reservedOp "="
e <- expr
return $ Assign var e
seqDecl :: Parser Decl
seqDecl = liftM2 Seq decl decl
rec :: Parser Decl
rec = liftM Rec (reserved "rec" *> decl)
decl :: Parser Decl
decl = let simpleDecl = assign <|> rec <|> parens(decl)
in do
t <- simpleDecl `sepBy` (reserved "then")
return $ foldl1 Seq t
parseExpr :: String -> Either ParseError Expr
parseExpr str = parse (expr <* eof) "" str
parseFun :: String -> Expr
parseFun str = case parseExpr str of
Left err -> error $ show err
Right expr -> expr
| null | https://raw.githubusercontent.com/pbevin/cardelli/bf239351289d379796fa68c25bb6c56be0e67925/hs/src/Parse.hs | haskell | Exp ::=
"if" Exp "then" Exp "else" Exp |
"fun" "(" Ide ")" Exp |
Exp "(" Exp ")" |
"let" Decl "in" Exp | "(" Exp ")"
Decl ::=
| module Parse(parseExpr, parseFun) where
import Control.Applicative hiding (many, optional, (<|>))
import Control.Monad
import Text.Parsec
import Text.Parsec.String
import Text.Parsec.Expr
import qualified Text.Parsec.Token as T
import Text.Parsec.Language (emptyDef)
import VarName
import AST
funStyle :: T.LanguageDef st
funStyle = emptyDef{ T.commentStart = "{-"
, T.commentEnd = "-}"
, T.identStart = letter
, T.identLetter = alphaNum <|> char '_'
, T.reservedOpNames = ["="]
, T.reservedNames = ["fun", "let", "rec", "in",
"if", "then", "else"]
}
Ide |
" = " Exp |
Decl " then " Decl | " rec " Decl |
" ( " Decl " ) "
lexer = T.makeTokenParser funStyle
parens = T.parens lexer
identifier = T.identifier lexer
integer = T.integer lexer
reserved = T.reserved lexer
reservedOp = T.reservedOp lexer
symbol = T.symbol lexer
atom = liftM Var identifier
number = liftM Num integer
cond :: Parser Expr
cond = do
reserved "if"
test <- expr
reserved "then"
ifTrue <- expr
reserved "else"
ifFalse <- expr
return $ Cond test ifTrue ifFalse
lambda :: Parser Expr
lambda = do
reserved "fun"
var <- parens identifier
body <- expr
return $ Lambda var body
block :: Parser Expr
block = do
reserved "let"
d <- decl
reserved "in"
e <- expr
return $ Block d e
term :: Parser Expr
term = let simpleTerm = parens(expr)
<|> cond
<|> block
<|> lambda
<|> number
<|> atom
in do
t <- simpleTerm
applications <- many (parens exprList)
return $ foldl FunCall t $ concat applications
exprList :: Parser [Expr]
exprList = expr `sepBy` (symbol ",")
mkUnOp op a = FunCall (Var op) a
mkBinOp op a b = FunCall (mkUnOp op a) b
binary name fn = Infix (do { reservedOp name; return (mkBinOp fn) }) AssocLeft
unary name fn = Prefix (do { reservedOp name; return (mkUnOp fn) })
table = [
[ unary "-" "negate" ],
[ unary "!" "not" ],
[ binary "&" "and", binary "|" "or" ],
[ binary "*" "times", binary "/" "div" ],
[ binary "+" "plus", binary "-" "minus" ],
[ binary "==" "eq" ]]
expr :: Parser Expr
expr = buildExpressionParser table term <?> "expression"
assign :: Parser Decl
assign = do
var <- identifier
reservedOp "="
e <- expr
return $ Assign var e
seqDecl :: Parser Decl
seqDecl = liftM2 Seq decl decl
rec :: Parser Decl
rec = liftM Rec (reserved "rec" *> decl)
decl :: Parser Decl
decl = let simpleDecl = assign <|> rec <|> parens(decl)
in do
t <- simpleDecl `sepBy` (reserved "then")
return $ foldl1 Seq t
parseExpr :: String -> Either ParseError Expr
parseExpr str = parse (expr <* eof) "" str
parseFun :: String -> Expr
parseFun str = case parseExpr str of
Left err -> error $ show err
Right expr -> expr
|
ef501effd1db575677448a2281ff517a9568e554b9273b740091e7077f2c55d0 | zachjs/sv2v | Interface.hs | # LANGUAGE PatternSynonyms #
sv2v
- Author : < >
-
- Conversion for interfaces
- Author: Zachary Snow <>
-
- Conversion for interfaces
-}
module Convert.Interface (convert) where
import Data.List (intercalate, (\\))
import Data.Maybe (isJust, isNothing, mapMaybe)
import Control.Monad.Writer.Strict
import qualified Data.Map.Strict as Map
import Convert.ExprUtils (endianCondExpr)
import Convert.Scoper
import Convert.Traverse
import Language.SystemVerilog.AST
data PartInfo = PartInfo
{ pKind :: PartKW
, pPorts :: [Identifier]
, pItems :: [ModuleItem]
}
type PartInfos = Map.Map Identifier PartInfo
type ModportInstances = [(Identifier, (Identifier, Identifier))]
type ModportBinding = (Identifier, (Substitutions, Expr))
type Substitutions = [(Expr, Expr)]
convert :: [AST] -> [AST]
convert files =
if needsFlattening
then files
else traverseFiles
(collectDescriptionsM collectPart)
(map . convertDescription)
files
where
-- we can only collect/map non-extern interfaces and modules
collectPart :: Description -> Writer PartInfos ()
collectPart (Part _ False kw _ name ports items) =
tell $ Map.singleton name $ PartInfo kw ports items
collectPart _ = return ()
-- multidimensional instances need to be flattened before this
-- conversion can proceed
needsFlattening =
getAny $ execWriter $ mapM (collectDescriptionsM checkPart) files
checkPart :: Description -> Writer Any ()
checkPart (Part _ _ _ _ _ _ items) =
mapM (collectNestedModuleItemsM checkItem) items >> return ()
checkPart _ = return ()
checkItem :: ModuleItem -> Writer Any ()
checkItem (Instance _ _ _ rs _) = when (length rs > 1) $ tell $ Any True
checkItem _ = return ()
convertDescription :: PartInfos -> Description -> Description
convertDescription _ (Part _ _ Interface _ name _ _) =
PackageItem $ Decl $ CommentDecl $ "removed interface: " ++ name
convertDescription parts (Part attrs extern Module lifetime name ports items) =
if null $ extractModportInstances name $ PartInfo Module ports items then
Part attrs extern Module lifetime name ports items'
else
PackageItem $ Decl $ CommentDecl $
"removed module with interface ports: " ++ name
where
items' = evalScoper $ scopeModuleItems scoper name items
scoper = scopeModuleItem traverseDeclM traverseModuleItemM return return
traverseDeclM :: Decl -> Scoper [ModportDecl] Decl
traverseDeclM decl = do
case decl of
Variable _ _ x _ _ -> insertElem x DeclVal
Net _ _ _ _ x _ _ -> insertElem x DeclVal
Param _ _ x _ -> insertElem x DeclVal
ParamType _ x _ -> insertElem x DeclVal
CommentDecl{} -> return ()
return decl
lookupIntfElem :: Scopes [ModportDecl] -> Expr -> LookupResult [ModportDecl]
lookupIntfElem modports expr =
case lookupElem modports expr of
Just (_, _, DeclVal) -> Nothing
other -> other
traverseModuleItemM :: ModuleItem -> Scoper [ModportDecl] ModuleItem
traverseModuleItemM (Modport modportName modportDecls) =
insertElem modportName modportDecls >> return (Generate [])
traverseModuleItemM instanceItem@Instance{} = do
modports <- embedScopes (\l () -> l) ()
if isNothing maybePartInfo then
return instanceItem
else if partKind == Interface then
-- inline instantiation of an interface
scoper $ Generate $ map GenModuleItem $
inlineInstance modports rs []
partItems part instanceName paramBindings portBindings
else if null modportInstances then
return instanceItem
else do
-- inline instantiation of a module
let modportBindings = getModportBindings modports
let unconnected = map fst modportInstances \\
map fst modportBindings
if not (null unconnected)
then scopedErrorM $ "instance " ++ instanceName ++ " of "
++ part ++ " has unconnected interface ports: "
++ intercalate ", " unconnected
else scoper $ Generate $ map GenModuleItem $
inlineInstance modports rs modportBindings partItems
part instanceName paramBindings portBindings
where
Instance part paramBindings instanceName rs portBindings =
instanceItem
maybePartInfo = Map.lookup part parts
Just partInfo = maybePartInfo
PartInfo partKind _ partItems = partInfo
modportInstances = extractModportInstances part partInfo
getModportBindings modports = mapMaybe
(inferModportBinding modports modportInstances) $
map (second $ addImpliedSlice modports) portBindings
second f = \(a, b) -> (a, f b)
traverseModuleItemM other = return other
add explicit slices for bindings of entire modport instance arrays
addImpliedSlice :: Scopes [ModportDecl] -> Expr -> Expr
addImpliedSlice modports orig@(Dot expr modportName) =
case lookupIntfElem modports (InstArrKey expr) of
Just (_, _, InstArrVal l r) ->
Dot (Range expr NonIndexed (l, r)) modportName
_ -> orig
addImpliedSlice modports expr =
case lookupIntfElem modports (InstArrKey expr) of
Just (_, _, InstArrVal l r) ->
Range expr NonIndexed (l, r)
_ -> expr
-- elaborates and resolves provided modport bindings
inferModportBinding :: Scopes [ModportDecl] -> ModportInstances ->
PortBinding -> Maybe ModportBinding
inferModportBinding modports modportInstances (portName, expr) =
if maybeInfo == Nothing
then Nothing
else Just (portName, modportBinding)
where
modportBinding = (substitutions, replaceBit modportE)
substitutions =
genSubstitutions modports base instanceE modportE
maybeInfo =
lookupModportBinding modports modportInstances portName bitd
Just (instanceE, modportE) = maybeInfo
(exprUndot, bitd) = case expr of
Dot subExpr x -> (subExpr, Dot bitdUndot x)
_ -> (expr, bitdUndot)
bitdUndot = case exprUndot of
Range subExpr _ _ -> Bit subExpr taggedOffset
Bit subExpr _ -> Bit subExpr untaggedOffset
_ -> exprUndot
bitReplacement = case exprUndot of
Range _ mode range -> \e -> Range e mode range
Bit _ idx -> flip Bit idx
_ -> id
base = case exprUndot of
Range{} -> Bit (Ident portName) Tag
_ -> Ident portName
untaggedOffset = Ident $ modportBaseName portName
taggedOffset = BinOp Add Tag untaggedOffset
replaceBit :: Expr -> Expr
replaceBit (Bit subExpr idx) =
if idx == untaggedOffset || idx == taggedOffset
then bitReplacement subExpr
else Bit subExpr idx
replaceBit (Dot subExpr x) =
Dot (replaceBit subExpr) x
replaceBit (Ident x) = Ident x
replaceBit _ = error "replaceBit invariant violated"
-- determines the underlying modport and interface instances associated
with the given port binding , if it is a modport binding
lookupModportBinding :: Scopes [ModportDecl] -> ModportInstances
-> Identifier -> Expr -> Maybe (Expr, Expr)
lookupModportBinding modports modportInstances portName expr =
if bindingIsModport then
-- provided specific instance modport
foundModport expr
else if bindingIsBundle && portIsBundle then
-- bundle bound to a generic bundle
foundModport expr
else if bindingIsBundle && not portIsBundle then
given entire interface , but just bound to a modport
foundModport $ Dot expr modportName
else if modportInstance /= Nothing then
scopedError modports $ "could not resolve modport binding "
++ show expr ++ " for port " ++ portName ++ " of type "
++ showModportType interfaceName modportName
else
Nothing
where
bindingIsModport = lookupIntfElem modports expr /= Nothing
bindingIsBundle = lookupIntfElem modports (Dot expr "") /= Nothing
portIsBundle = null modportName
modportInstance = lookup portName modportInstances
(interfaceName, modportName) =
case modportInstance of
Just x -> x
Nothing -> scopedError modports $
"can't deduce modport for interface " ++ show expr
++ " bound to port " ++ portName
foundModport modportE =
if (null interfaceName || bInterfaceName == interfaceName)
&& (null modportName || bModportName == modportName)
then Just (instanceE, qualifyModport modportE)
else scopedError modports msg
where
bModportName =
case modportE of
Dot _ x -> x
_ -> ""
instanceE = findInstance modportE
Just (_, _, InterfaceTypeVal bInterfaceName) =
lookupIntfElem modports $ InterfaceTypeKey
(findInstance modportE)
msg = "port " ++ portName ++ " has type "
++ showModportType interfaceName modportName
++ ", but the binding " ++ show expr ++ " has type "
++ showModportType bInterfaceName bModportName
findInstance :: Expr -> Expr
findInstance e =
case lookupIntfElem modports (Dot e "") of
Nothing -> case e of
Bit e' _ -> findInstance e'
Dot e' _ -> findInstance e'
_ -> error "internal invariant violated"
Just (accesses, _, _) -> accessesToExpr $ init accesses
qualifyModport :: Expr -> Expr
qualifyModport e =
accessesToExpr $
case lookupIntfElem modports e of
Just (accesses, _, _) -> accesses
Nothing ->
case lookupIntfElem modports (Dot e "") of
Just (accesses, _, _) -> init accesses
Nothing -> scopedError modports $
"could not find modport " ++ show e
showModportType :: Identifier -> Identifier -> String
showModportType "" "" = "generic interface"
showModportType intf "" = intf
showModportType intf modp = intf ++ '.' : modp
expand a modport binding into a series of expression substitutions
genSubstitutions :: Scopes [ModportDecl] -> Expr -> Expr -> Expr
-> [(Expr, Expr)]
genSubstitutions modports baseE instanceE modportE =
(baseE, instanceE) :
map toPortBinding modportDecls
where
a = lookupIntfElem modports modportE
b = lookupIntfElem modports (Dot modportE "")
Just (_, replacements, modportDecls) =
if a == Nothing then b else a
toPortBinding (_, x, e) = (x', e')
where
x' = Dot baseE x
e' = replaceInExpr replacements e
association list of modport instances in the given module body
extractModportInstances :: Identifier -> PartInfo -> ModportInstances
extractModportInstances part partInfo =
execWriter $ runScoperT $ scopeModuleItems collector part decls
where
collector = scopeModuleItem checkDecl return return return
decls = filter isDecl $ pItems partInfo
checkDecl :: Decl -> ScoperT () (Writer ModportInstances) Decl
checkDecl decl@(Variable _ t x _ _) =
if maybeInfo == Nothing then
return decl
else if elem x (pPorts partInfo) then
tell [(x, info)] >> return decl
else
scopedErrorM $
"Modport not in port list: " ++ show t ++ " " ++ x
++ ". Is this an interface missing a port list?"
where
maybeInfo = extractModportInfo t
Just info = maybeInfo
checkDecl decl = return decl
extractModportInfo :: Type -> Maybe (Identifier, Identifier)
extractModportInfo (InterfaceT "" "" _) = Just ("", "")
extractModportInfo (InterfaceT interfaceName modportName _) =
if isInterface interfaceName
then Just (interfaceName, modportName)
else Nothing
extractModportInfo (Alias interfaceName _) =
if isInterface interfaceName
then Just (interfaceName, "")
else Nothing
extractModportInfo _ = Nothing
isInterface :: Identifier -> Bool
isInterface partName =
case Map.lookup partName parts of
Nothing -> False
Just info -> pKind info == Interface
convertDescription _ other = other
isDecl :: ModuleItem -> Bool
isDecl (MIPackageItem Decl{}) = True
isDecl _ = False
-- produce the implicit modport decls for an interface bundle
impliedModport :: [ModuleItem] -> [ModportDecl]
impliedModport =
execWriter . mapM
(collectNestedModuleItemsM $ collectDeclsM collectModportDecls)
where
collectModportDecls :: Decl -> Writer [ModportDecl] ()
collectModportDecls (Variable _ _ x _ _) =
tell [(Inout, x, Ident x)]
collectModportDecls (Net _ _ _ _ x _ _) =
tell [(Inout, x, Ident x)]
collectModportDecls _ = return ()
-- convert an interface-bound module instantiation or an interface instantiation
-- into a series of equivalent inlined module items
inlineInstance :: Scopes [ModportDecl] -> [Range] -> [ModportBinding]
-> [ModuleItem] -> Identifier -> Identifier -> [ParamBinding]
-> [PortBinding] -> [ModuleItem]
inlineInstance global ranges modportBindings items partName
instanceName instanceParams instancePorts =
comment :
map (MIPackageItem . Decl) bindingBaseParams ++
map (MIPackageItem . Decl) parameterBinds ++
wrapInstance instanceName items'
: portBindings
where
items' = evalScoper $ scopeModuleItems scoper partName $
map (traverseNestedModuleItems rewriteItem) $
if null modportBindings
then itemsChecked ++ infoModports
else itemsChecked
itemsChecked = checkBeforeInline global partName items checkErrMsg
infoModports = [typeModport, dimensionModport, bundleModport]
scoper = scopeModuleItem
traverseDeclM traverseModuleItemM traverseGenItemM traverseStmtM
key = shortHash (partName, instanceName)
-- synthetic modports to be collected and removed after inlining
bundleModport = Modport "" (impliedModport items)
dimensionModport = if not isArray
then Generate []
else InstArrEncoded arrayLeft arrayRight
typeModport = InterfaceTypeEncoded partName
inlineKind =
if null modportBindings
then "interface"
else "module"
comment = MIPackageItem $ Decl $ CommentDecl $
"expanded " ++ inlineKind ++ " instance: " ++ instanceName
portBindings =
wrapPortBindings $
map portBindingItem $
filter ((/= Nil) . snd) $
filter notSubstituted instancePorts
notSubstituted :: PortBinding -> Bool
notSubstituted (portName, _) =
lookup portName modportBindings == Nothing
wrapPortBindings :: [ModuleItem] -> [ModuleItem]
wrapPortBindings =
if isArray
then (\x -> [x]) . wrapInstance blockName
else id
where blockName = instanceName ++ "_port_bindings"
rewriteItem :: ModuleItem -> ModuleItem
rewriteItem =
traverseDecls $
removeModportInstance .
removeDeclDir .
overrideParam
traverseDeclM :: Decl -> Scoper () Decl
traverseDeclM decl = do
case decl of
Variable _ _ x _ _ -> insertElem x ()
Net _ _ _ _ x _ _ -> insertElem x ()
Param _ _ x _ -> insertElem x ()
ParamType _ x _ -> insertElem x ()
CommentDecl{} -> return ()
traverseDeclExprsM traverseExprM decl
traverseModuleItemM :: ModuleItem -> Scoper () ModuleItem
traverseModuleItemM item@Modport{} =
traverseExprsM (scopeExpr >=> traverseExprM) item
traverseModuleItemM item@(Instance _ _ x _ _) =
insertElem x () >> traverseExprsM traverseExprM item
traverseModuleItemM item =
traverseExprsM traverseExprM item >>=
traverseLHSsM traverseLHSM
traverseGenItemM :: GenItem -> Scoper () GenItem
traverseGenItemM item@(GenFor (x, _) _ _ _) = do
-- don't want to be scoped in modports
insertElem x ()
item' <- traverseGenItemExprsM traverseExprM item
removeElem x
return item'
traverseGenItemM item =
traverseGenItemExprsM traverseExprM item
traverseStmtM :: Stmt -> Scoper () Stmt
traverseStmtM =
traverseStmtExprsM traverseExprM >=>
traverseStmtLHSsM traverseLHSM
-- used for replacing usages of modports in the module being inlined
modportSubstitutions = concatMap (fst . snd) modportBindings
lhsReplacements = map (\(x, y) -> (toLHS x, toLHS y)) exprReplacements
exprReplacements = filter ((/= Nil) . snd) modportSubstitutions
-- LHSs are replaced using simple substitutions
traverseLHSM :: LHS -> Scoper () LHS
traverseLHSM =
fmap replaceLHS .
embedScopes tagLHS
tagLHS :: Scopes () -> LHS -> LHS
tagLHS scopes lhs
| lookupElem scopes lhs /= Nothing =
LHSDot (renamePartLHS lhs) "@"
| Just portName <- partScopedModportRef $ lhsToExpr lhs =
LHSIdent portName
| otherwise =
traverseSinglyNestedLHSs (tagLHS scopes) lhs
renamePartLHS :: LHS -> LHS
renamePartLHS (LHSDot (LHSIdent x) y) =
if x == partName
then LHSDot scopedInstanceLHS y
else LHSDot (LHSIdent x) y
renamePartLHS lhs = traverseSinglyNestedLHSs renamePartLHS lhs
replaceLHS :: LHS -> LHS
replaceLHS (LHSDot lhs "@") = lhs
replaceLHS (LHSDot (LHSBit lhs elt) field) =
case lookup (LHSDot (LHSBit lhs Tag) field) lhsReplacements of
Just resolved -> replaceLHSArrTag elt resolved
Nothing -> LHSDot (replaceLHS $ LHSBit lhs elt) field
replaceLHS lhs =
case lookup lhs lhsReplacements of
Just lhs' -> lhs'
Nothing -> traverseSinglyNestedLHSs replaceLHS lhs
replaceLHSArrTag :: Expr -> LHS -> LHS
replaceLHSArrTag =
traverseNestedLHSs . (traverseLHSExprs . replaceArrTag)
-- top-level expressions may be modports bound to other modports
traverseExprM :: Expr -> Scoper () Expr
traverseExprM =
fmap replaceExpr .
embedScopes tagExpr
tagExpr :: Scopes () -> Expr -> Expr
tagExpr scopes expr
| lookupElem scopes expr /= Nothing =
Dot (renamePartExpr expr) "@"
| Just portName <- partScopedModportRef expr =
Ident portName
| otherwise =
visitExprsStep (tagExpr scopes) expr
renamePartExpr :: Expr -> Expr
renamePartExpr (Dot (Ident x) y) =
if x == partName
then Dot scopedInstanceExpr y
else Dot (Ident x) y
renamePartExpr expr = visitExprsStep renamePartExpr expr
replaceExpr :: Expr -> Expr
replaceExpr (Dot expr "@") = expr
replaceExpr (Ident x) =
case lookup x modportBindings of
Just (_, m) -> m
Nothing -> Ident x
replaceExpr expr =
replaceExpr' expr
replaceExpr' :: Expr -> Expr
replaceExpr' (Dot expr "@") = expr
replaceExpr' (Dot (Bit expr elt) field) =
case lookup (Dot (Bit expr Tag) field) exprReplacements of
Just resolved -> replaceArrTag (replaceExpr' elt) resolved
Nothing -> Dot (replaceExpr' $ Bit expr elt) field
replaceExpr' (Bit expr elt) =
case lookup (Bit expr Tag) exprReplacements of
Just resolved -> replaceArrTag (replaceExpr' elt) resolved
Nothing -> Bit (replaceExpr' expr) (replaceExpr' elt)
replaceExpr' expr@(Dot Ident{} _) =
case lookup expr exprReplacements of
Just expr' -> expr'
Nothing -> visitExprsStep replaceExprAny expr
replaceExpr' (Ident x) = Ident x
replaceExpr' expr = replaceExprAny expr
replaceExprAny :: Expr -> Expr
replaceExprAny expr =
case lookup expr exprReplacements of
Just expr' -> expr'
Nothing -> visitExprsStep replaceExpr' expr
replaceArrTag :: Expr -> Expr -> Expr
replaceArrTag replacement Tag = replacement
replaceArrTag replacement expr =
visitExprsStep (replaceArrTag replacement) expr
partScopedModportRef :: Expr -> Maybe Identifier
partScopedModportRef (Dot (Ident x) y) =
if x == partName && lookup y modportBindings /= Nothing
then Just y
else Nothing
partScopedModportRef _ = Nothing
visitExprsStep :: (Expr -> Expr) -> Expr -> Expr
visitExprsStep exprMapper =
traverseSinglyNestedExprs exprMapper
. traverseExprTypes (traverseNestedTypes typeMapper)
where typeMapper = traverseTypeExprs exprMapper
checkErrMsg :: String -> String
checkErrMsg exprStr = "inlining instance \"" ++ instanceName
++ "\" of " ++ inlineKind ++ " \"" ++ partName
++ "\" would make expression \"" ++ exprStr ++ "\" used in \""
++ instanceName ++ "\" resolvable when it wasn't previously"
-- unambiguous reference to the current instance
scopedInstanceRaw = accessesToExpr $ localAccesses global instanceName
scopedInstanceExpr =
if isArray
then Bit scopedInstanceRaw (Ident loopVar)
else scopedInstanceRaw
Just scopedInstanceLHS = exprToLHS scopedInstanceExpr
removeModportInstance :: Decl -> Decl
removeModportInstance (Variable d t x a e) =
if maybeModportBinding == Nothing then
Variable d t x a e
else if makeBindingBaseExpr modportE == Nothing then
CommentDecl $ "removed modport instance " ++ x
else if null modportDims then
localparam (modportBaseName x) bindingBaseExpr
else
localparam (modportBaseName x) $
BinOp Sub bindingBaseExpr (sliceLo NonIndexed modportDim)
where
maybeModportBinding = lookup x modportBindings
Just (_, modportE) = maybeModportBinding
bindingBaseExpr = Ident $ bindingBaseName ++ x
modportDims = a ++ snd (typeRanges t)
[modportDim] = modportDims
removeModportInstance other = other
removeDeclDir :: Decl -> Decl
removeDeclDir (Variable _ t x a e) =
Variable Local t' x a e
where t' = case t of
Implicit Unspecified rs ->
IntegerVector TLogic Unspecified rs
_ -> t
removeDeclDir decl@Net{} =
traverseNetAsVar removeDeclDir decl
removeDeclDir other = other
capture the lower bound for each modport array binding
bindingBaseParams = mapMaybe makeBindingBaseParam modportBindings
makeBindingBaseParam :: ModportBinding -> Maybe Decl
makeBindingBaseParam (portName, (_, modportE)) =
fmap (localparam $ bindingBaseName ++ portName) $
makeBindingBaseExpr modportE
bindingBaseName = "_bbase_" ++ key ++ "_"
makeBindingBaseExpr :: Expr -> Maybe Expr
makeBindingBaseExpr modportE =
case modportE of
Dot (Range _ mode range) _ -> Just $ sliceLo mode range
Range _ mode range -> Just $ sliceLo mode range
Dot (Bit _ idx) _ -> Just idx
Bit _ idx -> Just idx
_ -> Nothing
localparam :: Identifier -> Expr -> Decl
localparam = Param Localparam (Implicit Unspecified [])
paramTmp = "_param_" ++ key ++ "_"
parameterBinds = map makeParameterBind instanceParams
makeParameterBind :: ParamBinding -> Decl
makeParameterBind (x, Left t) =
ParamType Localparam (paramTmp ++ x) t
makeParameterBind (x, Right e) =
Param Localparam UnknownType (paramTmp ++ x) e
overrideParam :: Decl -> Decl
overrideParam (Param Parameter t x e) =
Param Localparam t x $
case lookup x instanceParams of
Nothing -> e
Just _ -> Ident $ paramTmp ++ x
overrideParam (ParamType Parameter x t) =
ParamType Localparam x $
case lookup x instanceParams of
Nothing -> t
Just _ -> Alias (paramTmp ++ x) []
overrideParam other = other
portBindingItem :: PortBinding -> ModuleItem
portBindingItem (ident, expr) =
if findDeclDir ident == Input
then bind (LHSDot (inj LHSBit LHSIdent) ident) expr
else bind (toLHS expr) (Dot (inj Bit Ident) ident)
where
bind = Assign AssignOptionNone
inj bit idn = if null ranges
then idn instanceName
else bit (idn instanceName) (Ident loopVar)
declDirs = execWriter $
mapM (collectDeclsM collectDeclDir) items
collectDeclDir :: Decl -> Writer (Map.Map Identifier Direction) ()
collectDeclDir (Variable dir _ ident _ _) =
when (dir /= Local) $
tell $ Map.singleton ident dir
collectDeclDir net@Net{} =
collectNetAsVarM collectDeclDir net
collectDeclDir _ = return ()
findDeclDir :: Identifier -> Direction
findDeclDir ident =
case Map.lookup ident declDirs of
Nothing -> error $ "could not find decl dir of " ++ ident
++ " among " ++ show declDirs
Just dir -> dir
toLHS :: Expr -> LHS
toLHS expr =
case exprToLHS expr of
Just lhs -> lhs
Nothing -> error $ "trying to bind an " ++ inlineKind
++ " output to " ++ show expr ++ " but that can't be an LHS"
for instance arrays , a unique identifier to be used as a genvar
loopVar = "_arr_" ++ key
isArray = not $ null ranges
[arrayRange@(arrayLeft, arrayRight)] = ranges
-- wrap the given item in a generate loop if necessary
wrapInstance :: Identifier -> [ModuleItem] -> ModuleItem
wrapInstance blockName moduleItems =
Generate $
if not isArray then
[item]
else
[ GenModuleItem (Genvar loopVar)
, GenFor inits cond incr item
]
where
item = GenBlock blockName $ map GenModuleItem moduleItems
inits = (loopVar, arrayLeft)
cond = endianCondExpr arrayRange
(BinOp Ge (Ident loopVar) arrayRight)
(BinOp Le (Ident loopVar) arrayRight)
incr = (loopVar, AsgnOp Add, step)
step = endianCondExpr arrayRange
(UniOp UniSub $ RawNum 1) (RawNum 1)
used for modport array binding offset placeholders
pattern Tag :: Expr
pattern Tag = Ident "%"
modportBaseName :: Identifier -> Identifier
modportBaseName = (++) "_mbase_"
-- the dimensions of interface instance arrays are encoded as synthetic modports
during inlining , enabling subsequent modport bindings to implicitly use the
-- bounds of the interface instance array when the bounds are unspecified
pattern InstArrName :: Identifier
pattern InstArrName = "~instance_array_dimensions~"
pattern InstArrVal :: Expr -> Expr -> [ModportDecl]
pattern InstArrVal l r = [(Local, "l", l), (Local, "r", r)]
pattern InstArrKey :: Expr -> Expr
pattern InstArrKey expr = Dot (Bit expr (RawNum 0)) InstArrName
pattern InstArrEncoded :: Expr -> Expr -> ModuleItem
pattern InstArrEncoded l r = Modport InstArrName (InstArrVal l r)
-- encoding for normal declarations in the current module
pattern DeclVal :: [ModportDecl]
pattern DeclVal = [(Local, "~decl~", Nil)]
-- encoding for the interface type of an interface instantiation
pattern InterfaceTypeName :: Identifier
pattern InterfaceTypeName = "~interface_type~"
pattern InterfaceTypeVal :: Identifier -> [ModportDecl]
pattern InterfaceTypeVal x = [(Local, "~interface~type~", Ident x)]
pattern InterfaceTypeKey :: Expr -> Expr
pattern InterfaceTypeKey e = Dot e InterfaceTypeName
pattern InterfaceTypeEncoded :: Identifier -> ModuleItem
pattern InterfaceTypeEncoded x = Modport InterfaceTypeName (InterfaceTypeVal x)
-- determines the lower bound for the given slice
sliceLo :: PartSelectMode -> Range -> Expr
sliceLo NonIndexed (l, r) = endianCondExpr (l, r) r l
sliceLo IndexedPlus (base, _) = base
sliceLo IndexedMinus (base, len) = BinOp Add (BinOp Sub base len) (RawNum 1)
-- check for cases where an expression in an inlined part only resolves after
-- inlining, potentially hiding a design error
checkBeforeInline :: Scopes a -> Identifier -> [ModuleItem]
-> (String -> String) -> [ModuleItem]
checkBeforeInline global partName items checkErrMsg =
evalScoper $ scopeModuleItems scoper partName $ items
where
scoper = scopeModuleItem
checkDecl checkModuleItem checkGenItem checkStmt
checkDecl :: Decl -> Scoper () Decl
checkDecl decl = do
case decl of
Variable _ _ x _ _ -> insertElem x ()
Net _ _ _ _ x _ _ -> insertElem x ()
Param _ _ x _ -> insertElem x ()
ParamType _ x _ -> insertElem x ()
CommentDecl{} -> return ()
traverseDeclExprsM checkExpr decl
checkModuleItem :: ModuleItem -> Scoper () ModuleItem
checkModuleItem item@(Instance _ _ x _ _) =
insertElem x () >> traverseExprsM checkExpr item
checkModuleItem item =
traverseExprsM checkExpr item >>=
traverseLHSsM checkLHS
checkGenItem :: GenItem -> Scoper () GenItem
checkGenItem = traverseGenItemExprsM checkExpr
checkStmt :: Stmt -> Scoper () Stmt
checkStmt =
traverseStmtExprsM checkExpr >=>
traverseStmtLHSsM checkLHS
checkExpr :: Expr -> Scoper () Expr
checkExpr = embedScopes checkExprResolutionId
checkLHS :: LHS -> Scoper () LHS
checkLHS = embedScopes checkLHSResolutionId
checkLHSResolutionId :: Scopes () -> LHS -> LHS
checkLHSResolutionId local lhs = checkExprResolution local expr lhs
where expr = lhsToExpr lhs
checkExprResolutionId :: Scopes () -> Expr -> Expr
checkExprResolutionId local expr = checkExprResolution local expr expr
-- error if the given expression resolves globally but not locally
checkExprResolution :: Scopes () -> Expr -> a -> a
checkExprResolution local expr =
if exprResolves global expr && not (anyPrefixResolves local expr)
then scopedError local $ checkErrMsg $ show expr
else id
-- check if hierarchical prefix of an expr exists in the given scope
anyPrefixResolves :: Scopes () -> Expr -> Bool
anyPrefixResolves local expr =
exprResolves local expr ||
case expr of
Dot inner _ -> anyPrefixResolves local inner
Bit inner _ -> anyPrefixResolves local inner
_ -> False
-- check if expr exists in the given scope
exprResolves :: Scopes a -> Expr -> Bool
exprResolves local (Ident x) =
isJust (lookupElem local x) || isLoopVar local x
exprResolves local expr =
isJust (lookupElem local expr)
| null | https://raw.githubusercontent.com/zachjs/sv2v/e00582de8f1ccf9b4ad1f1a262eb43c27cdcc1bd/src/Convert/Interface.hs | haskell | we can only collect/map non-extern interfaces and modules
multidimensional instances need to be flattened before this
conversion can proceed
inline instantiation of an interface
inline instantiation of a module
elaborates and resolves provided modport bindings
determines the underlying modport and interface instances associated
provided specific instance modport
bundle bound to a generic bundle
produce the implicit modport decls for an interface bundle
convert an interface-bound module instantiation or an interface instantiation
into a series of equivalent inlined module items
synthetic modports to be collected and removed after inlining
don't want to be scoped in modports
used for replacing usages of modports in the module being inlined
LHSs are replaced using simple substitutions
top-level expressions may be modports bound to other modports
unambiguous reference to the current instance
wrap the given item in a generate loop if necessary
the dimensions of interface instance arrays are encoded as synthetic modports
bounds of the interface instance array when the bounds are unspecified
encoding for normal declarations in the current module
encoding for the interface type of an interface instantiation
determines the lower bound for the given slice
check for cases where an expression in an inlined part only resolves after
inlining, potentially hiding a design error
error if the given expression resolves globally but not locally
check if hierarchical prefix of an expr exists in the given scope
check if expr exists in the given scope | # LANGUAGE PatternSynonyms #
sv2v
- Author : < >
-
- Conversion for interfaces
- Author: Zachary Snow <>
-
- Conversion for interfaces
-}
module Convert.Interface (convert) where
import Data.List (intercalate, (\\))
import Data.Maybe (isJust, isNothing, mapMaybe)
import Control.Monad.Writer.Strict
import qualified Data.Map.Strict as Map
import Convert.ExprUtils (endianCondExpr)
import Convert.Scoper
import Convert.Traverse
import Language.SystemVerilog.AST
data PartInfo = PartInfo
{ pKind :: PartKW
, pPorts :: [Identifier]
, pItems :: [ModuleItem]
}
type PartInfos = Map.Map Identifier PartInfo
type ModportInstances = [(Identifier, (Identifier, Identifier))]
type ModportBinding = (Identifier, (Substitutions, Expr))
type Substitutions = [(Expr, Expr)]
convert :: [AST] -> [AST]
convert files =
if needsFlattening
then files
else traverseFiles
(collectDescriptionsM collectPart)
(map . convertDescription)
files
where
collectPart :: Description -> Writer PartInfos ()
collectPart (Part _ False kw _ name ports items) =
tell $ Map.singleton name $ PartInfo kw ports items
collectPart _ = return ()
needsFlattening =
getAny $ execWriter $ mapM (collectDescriptionsM checkPart) files
checkPart :: Description -> Writer Any ()
checkPart (Part _ _ _ _ _ _ items) =
mapM (collectNestedModuleItemsM checkItem) items >> return ()
checkPart _ = return ()
checkItem :: ModuleItem -> Writer Any ()
checkItem (Instance _ _ _ rs _) = when (length rs > 1) $ tell $ Any True
checkItem _ = return ()
convertDescription :: PartInfos -> Description -> Description
convertDescription _ (Part _ _ Interface _ name _ _) =
PackageItem $ Decl $ CommentDecl $ "removed interface: " ++ name
convertDescription parts (Part attrs extern Module lifetime name ports items) =
if null $ extractModportInstances name $ PartInfo Module ports items then
Part attrs extern Module lifetime name ports items'
else
PackageItem $ Decl $ CommentDecl $
"removed module with interface ports: " ++ name
where
items' = evalScoper $ scopeModuleItems scoper name items
scoper = scopeModuleItem traverseDeclM traverseModuleItemM return return
traverseDeclM :: Decl -> Scoper [ModportDecl] Decl
traverseDeclM decl = do
case decl of
Variable _ _ x _ _ -> insertElem x DeclVal
Net _ _ _ _ x _ _ -> insertElem x DeclVal
Param _ _ x _ -> insertElem x DeclVal
ParamType _ x _ -> insertElem x DeclVal
CommentDecl{} -> return ()
return decl
lookupIntfElem :: Scopes [ModportDecl] -> Expr -> LookupResult [ModportDecl]
lookupIntfElem modports expr =
case lookupElem modports expr of
Just (_, _, DeclVal) -> Nothing
other -> other
traverseModuleItemM :: ModuleItem -> Scoper [ModportDecl] ModuleItem
traverseModuleItemM (Modport modportName modportDecls) =
insertElem modportName modportDecls >> return (Generate [])
traverseModuleItemM instanceItem@Instance{} = do
modports <- embedScopes (\l () -> l) ()
if isNothing maybePartInfo then
return instanceItem
else if partKind == Interface then
scoper $ Generate $ map GenModuleItem $
inlineInstance modports rs []
partItems part instanceName paramBindings portBindings
else if null modportInstances then
return instanceItem
else do
let modportBindings = getModportBindings modports
let unconnected = map fst modportInstances \\
map fst modportBindings
if not (null unconnected)
then scopedErrorM $ "instance " ++ instanceName ++ " of "
++ part ++ " has unconnected interface ports: "
++ intercalate ", " unconnected
else scoper $ Generate $ map GenModuleItem $
inlineInstance modports rs modportBindings partItems
part instanceName paramBindings portBindings
where
Instance part paramBindings instanceName rs portBindings =
instanceItem
maybePartInfo = Map.lookup part parts
Just partInfo = maybePartInfo
PartInfo partKind _ partItems = partInfo
modportInstances = extractModportInstances part partInfo
getModportBindings modports = mapMaybe
(inferModportBinding modports modportInstances) $
map (second $ addImpliedSlice modports) portBindings
second f = \(a, b) -> (a, f b)
traverseModuleItemM other = return other
add explicit slices for bindings of entire modport instance arrays
addImpliedSlice :: Scopes [ModportDecl] -> Expr -> Expr
addImpliedSlice modports orig@(Dot expr modportName) =
case lookupIntfElem modports (InstArrKey expr) of
Just (_, _, InstArrVal l r) ->
Dot (Range expr NonIndexed (l, r)) modportName
_ -> orig
addImpliedSlice modports expr =
case lookupIntfElem modports (InstArrKey expr) of
Just (_, _, InstArrVal l r) ->
Range expr NonIndexed (l, r)
_ -> expr
inferModportBinding :: Scopes [ModportDecl] -> ModportInstances ->
PortBinding -> Maybe ModportBinding
inferModportBinding modports modportInstances (portName, expr) =
if maybeInfo == Nothing
then Nothing
else Just (portName, modportBinding)
where
modportBinding = (substitutions, replaceBit modportE)
substitutions =
genSubstitutions modports base instanceE modportE
maybeInfo =
lookupModportBinding modports modportInstances portName bitd
Just (instanceE, modportE) = maybeInfo
(exprUndot, bitd) = case expr of
Dot subExpr x -> (subExpr, Dot bitdUndot x)
_ -> (expr, bitdUndot)
bitdUndot = case exprUndot of
Range subExpr _ _ -> Bit subExpr taggedOffset
Bit subExpr _ -> Bit subExpr untaggedOffset
_ -> exprUndot
bitReplacement = case exprUndot of
Range _ mode range -> \e -> Range e mode range
Bit _ idx -> flip Bit idx
_ -> id
base = case exprUndot of
Range{} -> Bit (Ident portName) Tag
_ -> Ident portName
untaggedOffset = Ident $ modportBaseName portName
taggedOffset = BinOp Add Tag untaggedOffset
replaceBit :: Expr -> Expr
replaceBit (Bit subExpr idx) =
if idx == untaggedOffset || idx == taggedOffset
then bitReplacement subExpr
else Bit subExpr idx
replaceBit (Dot subExpr x) =
Dot (replaceBit subExpr) x
replaceBit (Ident x) = Ident x
replaceBit _ = error "replaceBit invariant violated"
with the given port binding , if it is a modport binding
lookupModportBinding :: Scopes [ModportDecl] -> ModportInstances
-> Identifier -> Expr -> Maybe (Expr, Expr)
lookupModportBinding modports modportInstances portName expr =
if bindingIsModport then
foundModport expr
else if bindingIsBundle && portIsBundle then
foundModport expr
else if bindingIsBundle && not portIsBundle then
given entire interface , but just bound to a modport
foundModport $ Dot expr modportName
else if modportInstance /= Nothing then
scopedError modports $ "could not resolve modport binding "
++ show expr ++ " for port " ++ portName ++ " of type "
++ showModportType interfaceName modportName
else
Nothing
where
bindingIsModport = lookupIntfElem modports expr /= Nothing
bindingIsBundle = lookupIntfElem modports (Dot expr "") /= Nothing
portIsBundle = null modportName
modportInstance = lookup portName modportInstances
(interfaceName, modportName) =
case modportInstance of
Just x -> x
Nothing -> scopedError modports $
"can't deduce modport for interface " ++ show expr
++ " bound to port " ++ portName
foundModport modportE =
if (null interfaceName || bInterfaceName == interfaceName)
&& (null modportName || bModportName == modportName)
then Just (instanceE, qualifyModport modportE)
else scopedError modports msg
where
bModportName =
case modportE of
Dot _ x -> x
_ -> ""
instanceE = findInstance modportE
Just (_, _, InterfaceTypeVal bInterfaceName) =
lookupIntfElem modports $ InterfaceTypeKey
(findInstance modportE)
msg = "port " ++ portName ++ " has type "
++ showModportType interfaceName modportName
++ ", but the binding " ++ show expr ++ " has type "
++ showModportType bInterfaceName bModportName
findInstance :: Expr -> Expr
findInstance e =
case lookupIntfElem modports (Dot e "") of
Nothing -> case e of
Bit e' _ -> findInstance e'
Dot e' _ -> findInstance e'
_ -> error "internal invariant violated"
Just (accesses, _, _) -> accessesToExpr $ init accesses
qualifyModport :: Expr -> Expr
qualifyModport e =
accessesToExpr $
case lookupIntfElem modports e of
Just (accesses, _, _) -> accesses
Nothing ->
case lookupIntfElem modports (Dot e "") of
Just (accesses, _, _) -> init accesses
Nothing -> scopedError modports $
"could not find modport " ++ show e
showModportType :: Identifier -> Identifier -> String
showModportType "" "" = "generic interface"
showModportType intf "" = intf
showModportType intf modp = intf ++ '.' : modp
expand a modport binding into a series of expression substitutions
genSubstitutions :: Scopes [ModportDecl] -> Expr -> Expr -> Expr
-> [(Expr, Expr)]
genSubstitutions modports baseE instanceE modportE =
(baseE, instanceE) :
map toPortBinding modportDecls
where
a = lookupIntfElem modports modportE
b = lookupIntfElem modports (Dot modportE "")
Just (_, replacements, modportDecls) =
if a == Nothing then b else a
toPortBinding (_, x, e) = (x', e')
where
x' = Dot baseE x
e' = replaceInExpr replacements e
association list of modport instances in the given module body
extractModportInstances :: Identifier -> PartInfo -> ModportInstances
extractModportInstances part partInfo =
execWriter $ runScoperT $ scopeModuleItems collector part decls
where
collector = scopeModuleItem checkDecl return return return
decls = filter isDecl $ pItems partInfo
checkDecl :: Decl -> ScoperT () (Writer ModportInstances) Decl
checkDecl decl@(Variable _ t x _ _) =
if maybeInfo == Nothing then
return decl
else if elem x (pPorts partInfo) then
tell [(x, info)] >> return decl
else
scopedErrorM $
"Modport not in port list: " ++ show t ++ " " ++ x
++ ". Is this an interface missing a port list?"
where
maybeInfo = extractModportInfo t
Just info = maybeInfo
checkDecl decl = return decl
extractModportInfo :: Type -> Maybe (Identifier, Identifier)
extractModportInfo (InterfaceT "" "" _) = Just ("", "")
extractModportInfo (InterfaceT interfaceName modportName _) =
if isInterface interfaceName
then Just (interfaceName, modportName)
else Nothing
extractModportInfo (Alias interfaceName _) =
if isInterface interfaceName
then Just (interfaceName, "")
else Nothing
extractModportInfo _ = Nothing
isInterface :: Identifier -> Bool
isInterface partName =
case Map.lookup partName parts of
Nothing -> False
Just info -> pKind info == Interface
convertDescription _ other = other
isDecl :: ModuleItem -> Bool
isDecl (MIPackageItem Decl{}) = True
isDecl _ = False
impliedModport :: [ModuleItem] -> [ModportDecl]
impliedModport =
execWriter . mapM
(collectNestedModuleItemsM $ collectDeclsM collectModportDecls)
where
collectModportDecls :: Decl -> Writer [ModportDecl] ()
collectModportDecls (Variable _ _ x _ _) =
tell [(Inout, x, Ident x)]
collectModportDecls (Net _ _ _ _ x _ _) =
tell [(Inout, x, Ident x)]
collectModportDecls _ = return ()
inlineInstance :: Scopes [ModportDecl] -> [Range] -> [ModportBinding]
-> [ModuleItem] -> Identifier -> Identifier -> [ParamBinding]
-> [PortBinding] -> [ModuleItem]
inlineInstance global ranges modportBindings items partName
instanceName instanceParams instancePorts =
comment :
map (MIPackageItem . Decl) bindingBaseParams ++
map (MIPackageItem . Decl) parameterBinds ++
wrapInstance instanceName items'
: portBindings
where
items' = evalScoper $ scopeModuleItems scoper partName $
map (traverseNestedModuleItems rewriteItem) $
if null modportBindings
then itemsChecked ++ infoModports
else itemsChecked
itemsChecked = checkBeforeInline global partName items checkErrMsg
infoModports = [typeModport, dimensionModport, bundleModport]
scoper = scopeModuleItem
traverseDeclM traverseModuleItemM traverseGenItemM traverseStmtM
key = shortHash (partName, instanceName)
bundleModport = Modport "" (impliedModport items)
dimensionModport = if not isArray
then Generate []
else InstArrEncoded arrayLeft arrayRight
typeModport = InterfaceTypeEncoded partName
inlineKind =
if null modportBindings
then "interface"
else "module"
comment = MIPackageItem $ Decl $ CommentDecl $
"expanded " ++ inlineKind ++ " instance: " ++ instanceName
portBindings =
wrapPortBindings $
map portBindingItem $
filter ((/= Nil) . snd) $
filter notSubstituted instancePorts
notSubstituted :: PortBinding -> Bool
notSubstituted (portName, _) =
lookup portName modportBindings == Nothing
wrapPortBindings :: [ModuleItem] -> [ModuleItem]
wrapPortBindings =
if isArray
then (\x -> [x]) . wrapInstance blockName
else id
where blockName = instanceName ++ "_port_bindings"
rewriteItem :: ModuleItem -> ModuleItem
rewriteItem =
traverseDecls $
removeModportInstance .
removeDeclDir .
overrideParam
traverseDeclM :: Decl -> Scoper () Decl
traverseDeclM decl = do
case decl of
Variable _ _ x _ _ -> insertElem x ()
Net _ _ _ _ x _ _ -> insertElem x ()
Param _ _ x _ -> insertElem x ()
ParamType _ x _ -> insertElem x ()
CommentDecl{} -> return ()
traverseDeclExprsM traverseExprM decl
traverseModuleItemM :: ModuleItem -> Scoper () ModuleItem
traverseModuleItemM item@Modport{} =
traverseExprsM (scopeExpr >=> traverseExprM) item
traverseModuleItemM item@(Instance _ _ x _ _) =
insertElem x () >> traverseExprsM traverseExprM item
traverseModuleItemM item =
traverseExprsM traverseExprM item >>=
traverseLHSsM traverseLHSM
traverseGenItemM :: GenItem -> Scoper () GenItem
traverseGenItemM item@(GenFor (x, _) _ _ _) = do
insertElem x ()
item' <- traverseGenItemExprsM traverseExprM item
removeElem x
return item'
traverseGenItemM item =
traverseGenItemExprsM traverseExprM item
traverseStmtM :: Stmt -> Scoper () Stmt
traverseStmtM =
traverseStmtExprsM traverseExprM >=>
traverseStmtLHSsM traverseLHSM
modportSubstitutions = concatMap (fst . snd) modportBindings
lhsReplacements = map (\(x, y) -> (toLHS x, toLHS y)) exprReplacements
exprReplacements = filter ((/= Nil) . snd) modportSubstitutions
traverseLHSM :: LHS -> Scoper () LHS
traverseLHSM =
fmap replaceLHS .
embedScopes tagLHS
tagLHS :: Scopes () -> LHS -> LHS
tagLHS scopes lhs
| lookupElem scopes lhs /= Nothing =
LHSDot (renamePartLHS lhs) "@"
| Just portName <- partScopedModportRef $ lhsToExpr lhs =
LHSIdent portName
| otherwise =
traverseSinglyNestedLHSs (tagLHS scopes) lhs
renamePartLHS :: LHS -> LHS
renamePartLHS (LHSDot (LHSIdent x) y) =
if x == partName
then LHSDot scopedInstanceLHS y
else LHSDot (LHSIdent x) y
renamePartLHS lhs = traverseSinglyNestedLHSs renamePartLHS lhs
replaceLHS :: LHS -> LHS
replaceLHS (LHSDot lhs "@") = lhs
replaceLHS (LHSDot (LHSBit lhs elt) field) =
case lookup (LHSDot (LHSBit lhs Tag) field) lhsReplacements of
Just resolved -> replaceLHSArrTag elt resolved
Nothing -> LHSDot (replaceLHS $ LHSBit lhs elt) field
replaceLHS lhs =
case lookup lhs lhsReplacements of
Just lhs' -> lhs'
Nothing -> traverseSinglyNestedLHSs replaceLHS lhs
replaceLHSArrTag :: Expr -> LHS -> LHS
replaceLHSArrTag =
traverseNestedLHSs . (traverseLHSExprs . replaceArrTag)
traverseExprM :: Expr -> Scoper () Expr
traverseExprM =
fmap replaceExpr .
embedScopes tagExpr
tagExpr :: Scopes () -> Expr -> Expr
tagExpr scopes expr
| lookupElem scopes expr /= Nothing =
Dot (renamePartExpr expr) "@"
| Just portName <- partScopedModportRef expr =
Ident portName
| otherwise =
visitExprsStep (tagExpr scopes) expr
renamePartExpr :: Expr -> Expr
renamePartExpr (Dot (Ident x) y) =
if x == partName
then Dot scopedInstanceExpr y
else Dot (Ident x) y
renamePartExpr expr = visitExprsStep renamePartExpr expr
replaceExpr :: Expr -> Expr
replaceExpr (Dot expr "@") = expr
replaceExpr (Ident x) =
case lookup x modportBindings of
Just (_, m) -> m
Nothing -> Ident x
replaceExpr expr =
replaceExpr' expr
replaceExpr' :: Expr -> Expr
replaceExpr' (Dot expr "@") = expr
replaceExpr' (Dot (Bit expr elt) field) =
case lookup (Dot (Bit expr Tag) field) exprReplacements of
Just resolved -> replaceArrTag (replaceExpr' elt) resolved
Nothing -> Dot (replaceExpr' $ Bit expr elt) field
replaceExpr' (Bit expr elt) =
case lookup (Bit expr Tag) exprReplacements of
Just resolved -> replaceArrTag (replaceExpr' elt) resolved
Nothing -> Bit (replaceExpr' expr) (replaceExpr' elt)
replaceExpr' expr@(Dot Ident{} _) =
case lookup expr exprReplacements of
Just expr' -> expr'
Nothing -> visitExprsStep replaceExprAny expr
replaceExpr' (Ident x) = Ident x
replaceExpr' expr = replaceExprAny expr
replaceExprAny :: Expr -> Expr
replaceExprAny expr =
case lookup expr exprReplacements of
Just expr' -> expr'
Nothing -> visitExprsStep replaceExpr' expr
replaceArrTag :: Expr -> Expr -> Expr
replaceArrTag replacement Tag = replacement
replaceArrTag replacement expr =
visitExprsStep (replaceArrTag replacement) expr
partScopedModportRef :: Expr -> Maybe Identifier
partScopedModportRef (Dot (Ident x) y) =
if x == partName && lookup y modportBindings /= Nothing
then Just y
else Nothing
partScopedModportRef _ = Nothing
visitExprsStep :: (Expr -> Expr) -> Expr -> Expr
visitExprsStep exprMapper =
traverseSinglyNestedExprs exprMapper
. traverseExprTypes (traverseNestedTypes typeMapper)
where typeMapper = traverseTypeExprs exprMapper
checkErrMsg :: String -> String
checkErrMsg exprStr = "inlining instance \"" ++ instanceName
++ "\" of " ++ inlineKind ++ " \"" ++ partName
++ "\" would make expression \"" ++ exprStr ++ "\" used in \""
++ instanceName ++ "\" resolvable when it wasn't previously"
scopedInstanceRaw = accessesToExpr $ localAccesses global instanceName
scopedInstanceExpr =
if isArray
then Bit scopedInstanceRaw (Ident loopVar)
else scopedInstanceRaw
Just scopedInstanceLHS = exprToLHS scopedInstanceExpr
removeModportInstance :: Decl -> Decl
removeModportInstance (Variable d t x a e) =
if maybeModportBinding == Nothing then
Variable d t x a e
else if makeBindingBaseExpr modportE == Nothing then
CommentDecl $ "removed modport instance " ++ x
else if null modportDims then
localparam (modportBaseName x) bindingBaseExpr
else
localparam (modportBaseName x) $
BinOp Sub bindingBaseExpr (sliceLo NonIndexed modportDim)
where
maybeModportBinding = lookup x modportBindings
Just (_, modportE) = maybeModportBinding
bindingBaseExpr = Ident $ bindingBaseName ++ x
modportDims = a ++ snd (typeRanges t)
[modportDim] = modportDims
removeModportInstance other = other
removeDeclDir :: Decl -> Decl
removeDeclDir (Variable _ t x a e) =
Variable Local t' x a e
where t' = case t of
Implicit Unspecified rs ->
IntegerVector TLogic Unspecified rs
_ -> t
removeDeclDir decl@Net{} =
traverseNetAsVar removeDeclDir decl
removeDeclDir other = other
capture the lower bound for each modport array binding
bindingBaseParams = mapMaybe makeBindingBaseParam modportBindings
makeBindingBaseParam :: ModportBinding -> Maybe Decl
makeBindingBaseParam (portName, (_, modportE)) =
fmap (localparam $ bindingBaseName ++ portName) $
makeBindingBaseExpr modportE
bindingBaseName = "_bbase_" ++ key ++ "_"
makeBindingBaseExpr :: Expr -> Maybe Expr
makeBindingBaseExpr modportE =
case modportE of
Dot (Range _ mode range) _ -> Just $ sliceLo mode range
Range _ mode range -> Just $ sliceLo mode range
Dot (Bit _ idx) _ -> Just idx
Bit _ idx -> Just idx
_ -> Nothing
localparam :: Identifier -> Expr -> Decl
localparam = Param Localparam (Implicit Unspecified [])
paramTmp = "_param_" ++ key ++ "_"
parameterBinds = map makeParameterBind instanceParams
makeParameterBind :: ParamBinding -> Decl
makeParameterBind (x, Left t) =
ParamType Localparam (paramTmp ++ x) t
makeParameterBind (x, Right e) =
Param Localparam UnknownType (paramTmp ++ x) e
overrideParam :: Decl -> Decl
overrideParam (Param Parameter t x e) =
Param Localparam t x $
case lookup x instanceParams of
Nothing -> e
Just _ -> Ident $ paramTmp ++ x
overrideParam (ParamType Parameter x t) =
ParamType Localparam x $
case lookup x instanceParams of
Nothing -> t
Just _ -> Alias (paramTmp ++ x) []
overrideParam other = other
portBindingItem :: PortBinding -> ModuleItem
portBindingItem (ident, expr) =
if findDeclDir ident == Input
then bind (LHSDot (inj LHSBit LHSIdent) ident) expr
else bind (toLHS expr) (Dot (inj Bit Ident) ident)
where
bind = Assign AssignOptionNone
inj bit idn = if null ranges
then idn instanceName
else bit (idn instanceName) (Ident loopVar)
declDirs = execWriter $
mapM (collectDeclsM collectDeclDir) items
collectDeclDir :: Decl -> Writer (Map.Map Identifier Direction) ()
collectDeclDir (Variable dir _ ident _ _) =
when (dir /= Local) $
tell $ Map.singleton ident dir
collectDeclDir net@Net{} =
collectNetAsVarM collectDeclDir net
collectDeclDir _ = return ()
findDeclDir :: Identifier -> Direction
findDeclDir ident =
case Map.lookup ident declDirs of
Nothing -> error $ "could not find decl dir of " ++ ident
++ " among " ++ show declDirs
Just dir -> dir
toLHS :: Expr -> LHS
toLHS expr =
case exprToLHS expr of
Just lhs -> lhs
Nothing -> error $ "trying to bind an " ++ inlineKind
++ " output to " ++ show expr ++ " but that can't be an LHS"
for instance arrays , a unique identifier to be used as a genvar
loopVar = "_arr_" ++ key
isArray = not $ null ranges
[arrayRange@(arrayLeft, arrayRight)] = ranges
wrapInstance :: Identifier -> [ModuleItem] -> ModuleItem
wrapInstance blockName moduleItems =
Generate $
if not isArray then
[item]
else
[ GenModuleItem (Genvar loopVar)
, GenFor inits cond incr item
]
where
item = GenBlock blockName $ map GenModuleItem moduleItems
inits = (loopVar, arrayLeft)
cond = endianCondExpr arrayRange
(BinOp Ge (Ident loopVar) arrayRight)
(BinOp Le (Ident loopVar) arrayRight)
incr = (loopVar, AsgnOp Add, step)
step = endianCondExpr arrayRange
(UniOp UniSub $ RawNum 1) (RawNum 1)
used for modport array binding offset placeholders
pattern Tag :: Expr
pattern Tag = Ident "%"
modportBaseName :: Identifier -> Identifier
modportBaseName = (++) "_mbase_"
during inlining , enabling subsequent modport bindings to implicitly use the
pattern InstArrName :: Identifier
pattern InstArrName = "~instance_array_dimensions~"
pattern InstArrVal :: Expr -> Expr -> [ModportDecl]
pattern InstArrVal l r = [(Local, "l", l), (Local, "r", r)]
pattern InstArrKey :: Expr -> Expr
pattern InstArrKey expr = Dot (Bit expr (RawNum 0)) InstArrName
pattern InstArrEncoded :: Expr -> Expr -> ModuleItem
pattern InstArrEncoded l r = Modport InstArrName (InstArrVal l r)
pattern DeclVal :: [ModportDecl]
pattern DeclVal = [(Local, "~decl~", Nil)]
pattern InterfaceTypeName :: Identifier
pattern InterfaceTypeName = "~interface_type~"
pattern InterfaceTypeVal :: Identifier -> [ModportDecl]
pattern InterfaceTypeVal x = [(Local, "~interface~type~", Ident x)]
pattern InterfaceTypeKey :: Expr -> Expr
pattern InterfaceTypeKey e = Dot e InterfaceTypeName
pattern InterfaceTypeEncoded :: Identifier -> ModuleItem
pattern InterfaceTypeEncoded x = Modport InterfaceTypeName (InterfaceTypeVal x)
sliceLo :: PartSelectMode -> Range -> Expr
sliceLo NonIndexed (l, r) = endianCondExpr (l, r) r l
sliceLo IndexedPlus (base, _) = base
sliceLo IndexedMinus (base, len) = BinOp Add (BinOp Sub base len) (RawNum 1)
checkBeforeInline :: Scopes a -> Identifier -> [ModuleItem]
-> (String -> String) -> [ModuleItem]
checkBeforeInline global partName items checkErrMsg =
evalScoper $ scopeModuleItems scoper partName $ items
where
scoper = scopeModuleItem
checkDecl checkModuleItem checkGenItem checkStmt
checkDecl :: Decl -> Scoper () Decl
checkDecl decl = do
case decl of
Variable _ _ x _ _ -> insertElem x ()
Net _ _ _ _ x _ _ -> insertElem x ()
Param _ _ x _ -> insertElem x ()
ParamType _ x _ -> insertElem x ()
CommentDecl{} -> return ()
traverseDeclExprsM checkExpr decl
checkModuleItem :: ModuleItem -> Scoper () ModuleItem
checkModuleItem item@(Instance _ _ x _ _) =
insertElem x () >> traverseExprsM checkExpr item
checkModuleItem item =
traverseExprsM checkExpr item >>=
traverseLHSsM checkLHS
checkGenItem :: GenItem -> Scoper () GenItem
checkGenItem = traverseGenItemExprsM checkExpr
checkStmt :: Stmt -> Scoper () Stmt
checkStmt =
traverseStmtExprsM checkExpr >=>
traverseStmtLHSsM checkLHS
checkExpr :: Expr -> Scoper () Expr
checkExpr = embedScopes checkExprResolutionId
checkLHS :: LHS -> Scoper () LHS
checkLHS = embedScopes checkLHSResolutionId
checkLHSResolutionId :: Scopes () -> LHS -> LHS
checkLHSResolutionId local lhs = checkExprResolution local expr lhs
where expr = lhsToExpr lhs
checkExprResolutionId :: Scopes () -> Expr -> Expr
checkExprResolutionId local expr = checkExprResolution local expr expr
checkExprResolution :: Scopes () -> Expr -> a -> a
checkExprResolution local expr =
if exprResolves global expr && not (anyPrefixResolves local expr)
then scopedError local $ checkErrMsg $ show expr
else id
anyPrefixResolves :: Scopes () -> Expr -> Bool
anyPrefixResolves local expr =
exprResolves local expr ||
case expr of
Dot inner _ -> anyPrefixResolves local inner
Bit inner _ -> anyPrefixResolves local inner
_ -> False
exprResolves :: Scopes a -> Expr -> Bool
exprResolves local (Ident x) =
isJust (lookupElem local x) || isLoopVar local x
exprResolves local expr =
isJust (lookupElem local expr)
|
5c61ed36b99204fafb4bcbb0664c16766c8c2241c4d76db7bdbdac257f768b8e | ucsd-progsys/liquidhaskell | Main.hs | module Main where
import Test.Tasty
import ErrorFilterReportTests
main :: IO ()
main = defaultMain tests
tests :: TestTree
tests = testGroup "Tests"
errorFilterReportTests
| null | https://raw.githubusercontent.com/ucsd-progsys/liquidhaskell/f46dbafd6ce1f61af5b56f31924c21639c982a8a/tests/tasty/Main.hs | haskell | module Main where
import Test.Tasty
import ErrorFilterReportTests
main :: IO ()
main = defaultMain tests
tests :: TestTree
tests = testGroup "Tests"
errorFilterReportTests
| |
f6f236c2d91cff5eb5da062cdf83ecc048d7ebabb87b328cd378c543e911911c | LambdaHack/LambdaHack | Frequency.hs | # LANGUAGE DeriveGeneric , DeriveTraversable , TupleSections #
-- | A list of entities with relative frequencies of appearance.
module Game.LambdaHack.Core.Frequency
( -- * The @Frequency@ type
Frequency
-- * Construction
, uniformFreq, toFreq, maxBoundInt32
-- * Transformation
, scaleFreq
-- * Consumption
, nullFreq, runFrequency, nameFrequency
) where
import Prelude ()
import Game.LambdaHack.Core.Prelude
import Control.Applicative
import Data.Int (Int32)
import GHC.Generics (Generic)
maxBoundInt32 :: Int
maxBoundInt32 = toIntegralCrash (maxBound :: Int32)
-- | The frequency distribution type. Not normalized (operations may
-- or may not group the same elements and sum their frequencies). However,
elements with less than zero frequency are removed upon construction .
--
-- The @Eq@ instance compares raw representations, not relative,
-- normalized frequencies, so operations don't need to preserve
-- the expected equalities.
data Frequency a = Frequency
{ runFrequency :: [(Int, a)] -- ^ give acces to raw frequency values
, nameFrequency :: Text -- ^ short description for debug, etc.
}
deriving (Show, Eq, Ord, Foldable, Traversable, Generic)
instance Monad Frequency where
Frequency xs name >>= f =
Frequency [
#ifdef WITH_EXPENSIVE_ASSERTIONS
assert (toInteger p * toInteger q <= toInteger maxBoundInt32
`blame` (name, map fst xs))
#endif
(p * q, y)
| (p, x) <- xs
, (q, y) <- runFrequency (f x)
]
("bind (" <> name <> ")")
instance Functor Frequency where
fmap f (Frequency xs name) = Frequency (map (second f) xs) name
instance Applicative Frequency where
# INLINE pure #
pure x = Frequency [(1, x)] "pure"
Frequency fs fname <*> Frequency ys yname =
Frequency [
#ifdef WITH_EXPENSIVE_ASSERTIONS
assert (toInteger p * toInteger q <= toInteger maxBoundInt32
`blame` (fname, map fst fs, yname, map fst ys))
#endif
(p * q, f y)
| (p, f) <- fs
, (q, y) <- ys
]
("(" <> fname <> ") <*> (" <> yname <> ")")
instance MonadPlus Frequency where
mplus (Frequency xs xname) (Frequency ys yname) =
let name = case (xs, ys) of
([], []) -> "[]"
([], _) -> yname
(_, []) -> xname
_ -> "(" <> xname <> ") ++ (" <> yname <> ")"
in Frequency (xs ++ ys) name
mzero = Frequency [] "[]"
instance Alternative Frequency where
(<|>) = mplus
empty = mzero
-- | Uniform discrete frequency distribution.
uniformFreq :: Text -> [a] -> Frequency a
uniformFreq name l = Frequency (map (1,) l) name
-- | Takes a name and a list of frequencies and items
-- into the frequency distribution.
toFreq :: Text -> [(Int, a)] -> Frequency a
toFreq name l =
#ifdef WITH_EXPENSIVE_ASSERTIONS
assert (all (\(p, _) -> toInteger p <= toInteger maxBoundInt32) l
`blame` (name, map fst l)) $
#endif
Frequency (filter ((> 0 ) . fst) l) name
-- | Scale frequency distribution, multiplying it
-- by a positive integer constant.
scaleFreq :: Show a => Int -> Frequency a -> Frequency a
scaleFreq n (Frequency xs name) =
assert (n > 0 `blame` "non-positive frequency scale" `swith` (name, n, xs)) $
let multN p =
#ifdef WITH_EXPENSIVE_ASSERTIONS
assert (toInteger p * toInteger n <= toInteger maxBoundInt32
`blame` (n, Frequency xs name)) $
#endif
p * n
in Frequency (map (first multN) xs) name
-- | Test if the frequency distribution is empty.
nullFreq :: Frequency a -> Bool
nullFreq (Frequency fs _) = null fs
| null | https://raw.githubusercontent.com/LambdaHack/LambdaHack/d1c429d729c503790c44dca43a8e57ae6354f801/definition-src/Game/LambdaHack/Core/Frequency.hs | haskell | | A list of entities with relative frequencies of appearance.
* The @Frequency@ type
* Construction
* Transformation
* Consumption
| The frequency distribution type. Not normalized (operations may
or may not group the same elements and sum their frequencies). However,
The @Eq@ instance compares raw representations, not relative,
normalized frequencies, so operations don't need to preserve
the expected equalities.
^ give acces to raw frequency values
^ short description for debug, etc.
| Uniform discrete frequency distribution.
| Takes a name and a list of frequencies and items
into the frequency distribution.
| Scale frequency distribution, multiplying it
by a positive integer constant.
| Test if the frequency distribution is empty. | # LANGUAGE DeriveGeneric , DeriveTraversable , TupleSections #
module Game.LambdaHack.Core.Frequency
Frequency
, uniformFreq, toFreq, maxBoundInt32
, scaleFreq
, nullFreq, runFrequency, nameFrequency
) where
import Prelude ()
import Game.LambdaHack.Core.Prelude
import Control.Applicative
import Data.Int (Int32)
import GHC.Generics (Generic)
maxBoundInt32 :: Int
maxBoundInt32 = toIntegralCrash (maxBound :: Int32)
elements with less than zero frequency are removed upon construction .
data Frequency a = Frequency
}
deriving (Show, Eq, Ord, Foldable, Traversable, Generic)
instance Monad Frequency where
Frequency xs name >>= f =
Frequency [
#ifdef WITH_EXPENSIVE_ASSERTIONS
assert (toInteger p * toInteger q <= toInteger maxBoundInt32
`blame` (name, map fst xs))
#endif
(p * q, y)
| (p, x) <- xs
, (q, y) <- runFrequency (f x)
]
("bind (" <> name <> ")")
instance Functor Frequency where
fmap f (Frequency xs name) = Frequency (map (second f) xs) name
instance Applicative Frequency where
# INLINE pure #
pure x = Frequency [(1, x)] "pure"
Frequency fs fname <*> Frequency ys yname =
Frequency [
#ifdef WITH_EXPENSIVE_ASSERTIONS
assert (toInteger p * toInteger q <= toInteger maxBoundInt32
`blame` (fname, map fst fs, yname, map fst ys))
#endif
(p * q, f y)
| (p, f) <- fs
, (q, y) <- ys
]
("(" <> fname <> ") <*> (" <> yname <> ")")
instance MonadPlus Frequency where
mplus (Frequency xs xname) (Frequency ys yname) =
let name = case (xs, ys) of
([], []) -> "[]"
([], _) -> yname
(_, []) -> xname
_ -> "(" <> xname <> ") ++ (" <> yname <> ")"
in Frequency (xs ++ ys) name
mzero = Frequency [] "[]"
instance Alternative Frequency where
(<|>) = mplus
empty = mzero
uniformFreq :: Text -> [a] -> Frequency a
uniformFreq name l = Frequency (map (1,) l) name
toFreq :: Text -> [(Int, a)] -> Frequency a
toFreq name l =
#ifdef WITH_EXPENSIVE_ASSERTIONS
assert (all (\(p, _) -> toInteger p <= toInteger maxBoundInt32) l
`blame` (name, map fst l)) $
#endif
Frequency (filter ((> 0 ) . fst) l) name
scaleFreq :: Show a => Int -> Frequency a -> Frequency a
scaleFreq n (Frequency xs name) =
assert (n > 0 `blame` "non-positive frequency scale" `swith` (name, n, xs)) $
let multN p =
#ifdef WITH_EXPENSIVE_ASSERTIONS
assert (toInteger p * toInteger n <= toInteger maxBoundInt32
`blame` (n, Frequency xs name)) $
#endif
p * n
in Frequency (map (first multN) xs) name
nullFreq :: Frequency a -> Bool
nullFreq (Frequency fs _) = null fs
|
9cfb85cee14167e7858bf602f447f8ca07cb83fdab19f0abe90df249225843bb | HealthSamurai/dojo.clj | 15_destructuring_test.clj | (ns koans.15-destructuring-test
(:require [koans.engine :refer :all]))
(def test-address
{:street-address "123 Test Lane"
:city "Testerville"
:state "TX"})
(meditations
"Destructuring is an arbiter: it breaks up arguments"
(= __ ((fn [[a b]] (str b a))
[:foo :bar]))
"Whether in function definitions"
(= (str "An Oxford comma list of apples, "
"oranges, "
"and pears.")
((fn [[a b c]] __)
["apples" "oranges" "pears"]))
"Or in let expressions"
(= "Rich Hickey aka The Clojurer aka Go Time aka Lambda Guru"
(let [[first-name last-name & aliases]
(list "Rich" "Hickey" "The Clojurer" "Go Time" "Lambda Guru")]
__))
"You can regain the full argument if you like arguing"
(= {:original-parts ["Stephen" "Hawking"] :named-parts {:first "Stephen" :last "Hawking"}}
(let [[first-name last-name :as full-name] ["Stephen" "Hawking"]]
__))
"Break up maps by key"
(= "123 Test Lane, Testerville, TX"
(let [{street-address :street-address, city :city, state :state} test-address]
__))
"Or more succinctly"
(= "123 Test Lane, Testerville, TX"
(let [{:keys [street-address __ __]} test-address]
__))
"All together now!"
(= "Test Testerson, 123 Test Lane, Testerville, TX"
(___ ["Test" "Testerson"] test-address)))
| null | https://raw.githubusercontent.com/HealthSamurai/dojo.clj/94922640f534897ab2b181c608b54bfbb8351d7b/test/koans/15_destructuring_test.clj | clojure | (ns koans.15-destructuring-test
(:require [koans.engine :refer :all]))
(def test-address
{:street-address "123 Test Lane"
:city "Testerville"
:state "TX"})
(meditations
"Destructuring is an arbiter: it breaks up arguments"
(= __ ((fn [[a b]] (str b a))
[:foo :bar]))
"Whether in function definitions"
(= (str "An Oxford comma list of apples, "
"oranges, "
"and pears.")
((fn [[a b c]] __)
["apples" "oranges" "pears"]))
"Or in let expressions"
(= "Rich Hickey aka The Clojurer aka Go Time aka Lambda Guru"
(let [[first-name last-name & aliases]
(list "Rich" "Hickey" "The Clojurer" "Go Time" "Lambda Guru")]
__))
"You can regain the full argument if you like arguing"
(= {:original-parts ["Stephen" "Hawking"] :named-parts {:first "Stephen" :last "Hawking"}}
(let [[first-name last-name :as full-name] ["Stephen" "Hawking"]]
__))
"Break up maps by key"
(= "123 Test Lane, Testerville, TX"
(let [{street-address :street-address, city :city, state :state} test-address]
__))
"Or more succinctly"
(= "123 Test Lane, Testerville, TX"
(let [{:keys [street-address __ __]} test-address]
__))
"All together now!"
(= "Test Testerson, 123 Test Lane, Testerville, TX"
(___ ["Test" "Testerson"] test-address)))
| |
3de122a8926683d2a021edf0778ab48681cb0e3bbc2be341bd8163f1e769dbad | technomancy/grenchman | repl.ml | open Core.Std
open Async.Std
let repl_message input session =
([("session", session);
("op", "eval");
("id", "repl-" ^ (Uuid.to_string (Uuid.create ())));
("ns", ! Client.ns);
("code", input)],
Nrepl.print_all)
let dummy_message session =
([("session", session);
("op", "eval");
("id", "repl-dummy");
("ns", "user");
("code", "nil")],
Nrepl.default_actions)
let repl_done = function
| Some Bencode.String(id) -> (String.sub id 0 5) = "repl-"
| Some _ | None -> false
let is_complete_form input =
try let _ = Sexp.of_string input in true with
| _ -> false
let rec read_form prompt prev_input =
match Readline.read prompt with
| Some read_input ->
let input = prev_input ^ read_input in
if is_complete_form input then
Some input
else
read_form " > " input
| None -> None
let rec loop (r,w,p) resp =
let prompt = (!Client.ns ^ "=> ") in
if repl_done (List.Assoc.find resp "id") then
match read_form prompt "", List.Assoc.find resp "session" with
| Some input, Some Bencode.String(session) ->
Nrepl.send w p (repl_message input session)
| Some _, _ -> Core.Std.Printf.eprintf "Missing session.\n"; Pervasives.exit 1
| None, _ -> Pervasives.exit 0
let main port =
let handler = Client.handler loop in
let _ = Nrepl.new_session "127.0.0.1" port [dummy_message] handler in
never_returns (Scheduler.go ())
| null | https://raw.githubusercontent.com/technomancy/grenchman/713689773402dc329ea36b183b721552d7fd02cf/repl.ml | ocaml | open Core.Std
open Async.Std
let repl_message input session =
([("session", session);
("op", "eval");
("id", "repl-" ^ (Uuid.to_string (Uuid.create ())));
("ns", ! Client.ns);
("code", input)],
Nrepl.print_all)
let dummy_message session =
([("session", session);
("op", "eval");
("id", "repl-dummy");
("ns", "user");
("code", "nil")],
Nrepl.default_actions)
let repl_done = function
| Some Bencode.String(id) -> (String.sub id 0 5) = "repl-"
| Some _ | None -> false
let is_complete_form input =
try let _ = Sexp.of_string input in true with
| _ -> false
let rec read_form prompt prev_input =
match Readline.read prompt with
| Some read_input ->
let input = prev_input ^ read_input in
if is_complete_form input then
Some input
else
read_form " > " input
| None -> None
let rec loop (r,w,p) resp =
let prompt = (!Client.ns ^ "=> ") in
if repl_done (List.Assoc.find resp "id") then
match read_form prompt "", List.Assoc.find resp "session" with
| Some input, Some Bencode.String(session) ->
Nrepl.send w p (repl_message input session)
| Some _, _ -> Core.Std.Printf.eprintf "Missing session.\n"; Pervasives.exit 1
| None, _ -> Pervasives.exit 0
let main port =
let handler = Client.handler loop in
let _ = Nrepl.new_session "127.0.0.1" port [dummy_message] handler in
never_returns (Scheduler.go ())
| |
eaa47f1c1d4727fc22ab4cea0eace7ca8d0b64ef2e65dcc969d420ff74c8fa36 | tezos/tezos-mirror | injector_operation.mli | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2022 Nomadic Labs , < >
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
to deal in the Software without restriction , including without limitation
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
and/or sell copies of the Software , and to permit persons to whom the
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
open Injector_sigs
module Make (O : PARAM_OPERATION) : INJECTOR_OPERATION with type operation = O.t
| null | https://raw.githubusercontent.com/tezos/tezos-mirror/8a1c0d2236bfa9c0143704ac0cdacb6e89b208b0/src/lib_injector/injector_operation.mli | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*************************************************************************** | Copyright ( c ) 2022 Nomadic Labs , < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
open Injector_sigs
module Make (O : PARAM_OPERATION) : INJECTOR_OPERATION with type operation = O.t
|
8c5fe3863f4f5a58d64f4cb755530ebfc3d2ef6464687ecddeedf14b29f07143 | grin-compiler/grin | Util.hs | # LANGUAGE LambdaCase , FlexibleContexts , RecordWildCards #
module Transformations.ExtendedSyntax.Util where
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe
import Control.Monad
import Control.Monad.State
import Control.Monad.Trans.Except
import Control.Comonad
import Control.Comonad.Cofree
import Data.Functor.Foldable as Foldable
import Lens.Micro.Platform
import Grin.ExtendedSyntax.Grin
import Grin.ExtendedSyntax.Pretty
import Grin.ExtendedSyntax.TypeEnvDefs
HINT : Name usage in Exp
- variable def
names in CPat
names in LPat
arg names in Def
- variable use
names in
names in FetchI and Update
- function binder
function name in Def
- function reference
function name in SApp
HINT: Name usage in Exp
- variable def
names in CPat
names in LPat
arg names in Def
- variable use
names in Val
names in FetchI and Update
- function binder
function name in Def
- function reference
function name in SApp
-}
foldNameUseExpF :: (Monoid m) => (Name -> m) -> ExpF a -> m
foldNameUseExpF f = \case
ECaseF v _ -> f v
SAppF fun args -> f fun <> foldMap f args
SReturnF val -> foldNames f val
SStoreF v -> f v
SUpdateF p v -> f p <> f v
SFetchF p -> f p
_ -> mempty
data DefRole = FunName | FunParam | BindVar | AltVar
deriving (Eq, Show)
foldNameDefExpF :: (Monoid m) => (DefRole -> Name -> m) -> ExpF a -> m
foldNameDefExpF f = \case
DefF name args _ -> mconcat $ (f FunName name) : map (f FunParam) args
EBindF _ bPat _ -> f BindVar (_bPatVar bPat)
QUESTION : What should be the alt name 's DefRole ? Now it is BindVar , because it rebinds the scrutinee .
AltF cpat n _ -> f BindVar n <> foldNames (f AltVar) cpat
_ -> mempty
mapNamesCPat :: (Name -> Name) -> CPat -> CPat
mapNamesCPat f = \case
NodePat tag args -> NodePat tag (map f args)
cpat -> cpat
-- apply a function to all @Name@s in a @Val@
mapNamesVal :: (Name -> Name) -> Val -> Val
mapNamesVal f = \case
ConstTagNode tag args -> ConstTagNode tag (map f args)
Var name -> Var $ f name
val -> val
mapNamesBPat :: (Name -> Name) -> BPat -> BPat
mapNamesBPat f = \case
VarPat v -> VarPat (f v)
AsPat tag vars v -> AsPat tag (map f vars) (f v)
-- TODO: replace at use sites with
-- mapValVal :: (Val -> Val) -> Val -> Val
-- mapValVal f val = case f val of
-- ConstTagNode tag vals -> ConstTagNode tag (map (mapValVal f) vals)
name vals - > name ( map ( mapValVal f ) vals )
-- val -> val
mapValsExp :: (Val -> Val) -> Exp -> Exp
mapValsExp f = \case
-- NOTE: does not recurse into alts
ECase scrut alts -> ECase scrut alts
SReturn val -> SReturn $ f val
exp -> exp
mapValsExpM :: Monad m => (Val -> m Val) -> Exp -> m Exp
mapValsExpM f = \case
SReturn val -> SReturn <$> f val
exp -> pure exp
mapNameUseExp :: (Name -> Name) -> Exp -> Exp
mapNameUseExp f = \case
SStore v -> SStore (f v)
SFetch p -> SFetch (f p)
SUpdate p v -> SUpdate (f p) (f v)
-- NOTE: does not recurse into alts
ECase scrut alts -> ECase (f scrut) alts
SApp fun args -> SApp (f fun) (map f args)
exp -> mapValsExp (mapNamesVal f) exp
subst :: Ord a => Map a a -> a -> a
subst env x = Map.findWithDefault x x env
substitute all @Names@s in an @Exp@ ( non - recursive )
substVarRefExp :: Map Name Name -> Exp -> Exp
substVarRefExp env = mapNameUseExp (subst env)
substitute all @Names@s in a @Val@ ( non - recursive )
substNamesVal :: Map Name Name -> Val -> Val
substNamesVal env = mapNamesVal (subst env)
-- specialized version of @subst@ to @Val@s (non-recursive)
substValsVal :: Map Val Val -> Val -> Val
substValsVal env = subst env
-- substitute all @Val@s in an @Exp@ (non-recursive)
substVals :: Map Val Val -> Exp -> Exp
substVals env = mapValsExp (subst env)
cPatToVal :: CPat -> Val
cPatToVal = \case
NodePat tag args -> ConstTagNode tag args
LitPat lit -> Lit lit
DefaultPat -> Unit
cPatToAsPat :: Name -> CPat -> BPat
cPatToAsPat name (NodePat tag args) = AsPat tag args name
cPatToAsPat _ cPat = error $ "cPatToAsPat: cannot convert to as-pattern: " ++ show (PP cPat)
-- monadic recursion schemes
-- see: -recursion-schemes
cataM
:: (Monad m, Traversable (Base t), Recursive t)
=> (Base t a -> m a) -> t -> m a
cataM alg = c where
c = alg <=< traverse c . project
anaM
:: (Monad m, Traversable (Base t), Corecursive t)
=> (a -> m (Base t a)) -> a -> m t
anaM coalg = a where
a = (pure . embed) <=< traverse a <=< coalg
paraM
:: (Monad m, Traversable (Base t), Recursive t)
=> (Base t (t, a) -> m a) -> t -> m a
paraM alg = p where
p = alg <=< traverse f . project
f t = liftM2 (,) (pure t) (p t)
apoM
:: (Monad m, Traversable (Base t), Corecursive t)
=> (a -> m (Base t (Either t a))) -> a -> m t
apoM coalg = a where
a = (pure . embed) <=< traverse f <=< coalg
f = either pure a
hyloM
:: (Monad m, Traversable t)
=> (t b -> m b) -> (a -> m (t a)) -> a -> m b
hyloM alg coalg = h
where h = alg <=< traverse h <=< coalg
histoM
:: (Monad m, Traversable (Base t), Recursive t)
=> (Base t (Cofree (Base t) a) -> m a) -> t -> m a
histoM h = pure . extract <=< worker where
worker = f <=< traverse worker . project
f x = (:<) <$> h x <*> pure x
-- misc
-- QUESTION: How should this be changed?
skipUnit :: ExpF Exp -> Exp
skipUnit = \case
-- EBindF (SReturn Unit) _ rightExp -> rightExp
exp -> embed exp
newtype TagInfo = TagInfo { _tagArityMap :: Map.Map Tag Int }
deriving (Eq, Show)
updateTagInfo :: Tag -> Int -> TagInfo -> TagInfo
updateTagInfo t n ti@(TagInfo m) =
case Map.lookup t m of
Just arity | arity < n -> TagInfo $ Map.insert t n m
Nothing -> TagInfo $ Map.insert t n m
_ -> ti
collectTagInfo :: Exp -> TagInfo
collectTagInfo = flip execState (TagInfo Map.empty) . cataM alg
where
alg :: ExpF () -> State TagInfo ()
alg = \case
SReturnF val -> goVal val
AltF cpat _ _ -> goCPat cpat
_ -> pure ()
goVal :: Val -> State TagInfo ()
goVal (ConstTagNode t args) = modify $ updateTagInfo t (length args)
goVal _ = pure ()
goCPat :: CPat -> State TagInfo ()
goCPat (NodePat t args) = modify $ updateTagInfo t (length args)
goCPat _ = pure ()
lookupExcept :: (Monad m, Ord k) =>
String ->
k -> Map k v ->
ExceptT String m v
lookupExcept err k = maybe (throwE err) pure . Map.lookup k
lookupExceptT :: (MonadTrans t, Monad m, Ord k) =>
String ->
k -> Map k v ->
t (ExceptT String m) v
lookupExceptT err k = lift . lookupExcept err k
mapWithDoubleKey :: (Ord k1, Ord k2) =>
(k1 -> k2 -> a -> b) ->
Map k1 (Map k2 a) ->
Map k1 (Map k2 b)
mapWithDoubleKey f = Map.mapWithKey (\k1 m -> Map.mapWithKey (f k1) m)
mapWithDoubleKeyM :: (Ord k1, Ord k2, Monad m) =>
(k1 -> k2 -> a -> m b) ->
Map k1 (Map k2 a) ->
m (Map k1 (Map k2 b))
mapWithDoubleKeyM f = sequence . Map.mapWithKey (\k1 m -> sequence $ Map.mapWithKey (f k1) m)
lookupWithDoubleKey :: (Ord k1, Ord k2) => k1 -> k2 -> Map k1 (Map k2 v) -> Maybe v
lookupWithDoubleKey k1 k2 m = Map.lookup k1 m >>= Map.lookup k2
lookupWithDoubleKeyExcept :: (Monad m, Ord k1, Ord k2) =>
String -> k1 -> k2 ->
Map k1 (Map k2 v) ->
ExceptT String m v
lookupWithDoubleKeyExcept err k1 k2 = maybe (throwE err) pure
. lookupWithDoubleKey k1 k2
lookupWithDoubleKeyExceptT :: (MonadTrans t, Monad m, Ord k1, Ord k2) =>
String -> k1 -> k2 ->
Map k1 (Map k2 v) ->
t (ExceptT String m) v
lookupWithDoubleKeyExceptT err k1 k2 = lift . lookupWithDoubleKeyExcept err k1 k2
notFoundIn :: Show a => String -> a -> String -> String
notFoundIn n1 x n2 = n1 ++ " " ++ show x ++ " not found in " ++ n2
markToRemove :: a -> Bool -> Maybe a
markToRemove x True = Just x
markToRemove _ False = Nothing
zipFilter :: [a] -> [Bool] -> [a]
zipFilter xs = catMaybes . zipWith markToRemove xs
bindToUndefineds :: Monad m => TypeEnv -> Exp -> [Name] -> ExceptT String m Exp
bindToUndefineds TypeEnv{..} = foldM bindToUndefined where
bindToUndefined :: Monad m => Exp -> Name -> ExceptT String m Exp
bindToUndefined rhs v = do
ty <- lookupExcept (notInTypeEnv v) v _variable
let ty' = simplifyType ty
pure $ EBind (SReturn (Undefined ty')) (VarPat v) rhs
notInTypeEnv v = "Variable " ++ show (PP v) ++ " was not found in the type environment."
simplifySimpleType :: SimpleType -> SimpleType
simplifySimpleType (T_Location _) = T_UnspecifiedLocation
simplifySimpleType t = t
simplifyNodeSet :: NodeSet -> NodeSet
simplifyNodeSet = fmap (fmap simplifySimpleType)
simplifyType :: Type -> Type
simplifyType (T_SimpleType st) = T_SimpleType $ simplifySimpleType st
simplifyType (T_NodeSet ns) = T_NodeSet $ simplifyNodeSet ns
| null | https://raw.githubusercontent.com/grin-compiler/grin/44ac2958810ecee969c8028d2d2a082d47fba51b/grin/src/Transformations/ExtendedSyntax/Util.hs | haskell | apply a function to all @Name@s in a @Val@
TODO: replace at use sites with
mapValVal :: (Val -> Val) -> Val -> Val
mapValVal f val = case f val of
ConstTagNode tag vals -> ConstTagNode tag (map (mapValVal f) vals)
val -> val
NOTE: does not recurse into alts
NOTE: does not recurse into alts
specialized version of @subst@ to @Val@s (non-recursive)
substitute all @Val@s in an @Exp@ (non-recursive)
monadic recursion schemes
see: -recursion-schemes
misc
QUESTION: How should this be changed?
EBindF (SReturn Unit) _ rightExp -> rightExp | # LANGUAGE LambdaCase , FlexibleContexts , RecordWildCards #
module Transformations.ExtendedSyntax.Util where
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe
import Control.Monad
import Control.Monad.State
import Control.Monad.Trans.Except
import Control.Comonad
import Control.Comonad.Cofree
import Data.Functor.Foldable as Foldable
import Lens.Micro.Platform
import Grin.ExtendedSyntax.Grin
import Grin.ExtendedSyntax.Pretty
import Grin.ExtendedSyntax.TypeEnvDefs
HINT : Name usage in Exp
- variable def
names in CPat
names in LPat
arg names in Def
- variable use
names in
names in FetchI and Update
- function binder
function name in Def
- function reference
function name in SApp
HINT: Name usage in Exp
- variable def
names in CPat
names in LPat
arg names in Def
- variable use
names in Val
names in FetchI and Update
- function binder
function name in Def
- function reference
function name in SApp
-}
foldNameUseExpF :: (Monoid m) => (Name -> m) -> ExpF a -> m
foldNameUseExpF f = \case
ECaseF v _ -> f v
SAppF fun args -> f fun <> foldMap f args
SReturnF val -> foldNames f val
SStoreF v -> f v
SUpdateF p v -> f p <> f v
SFetchF p -> f p
_ -> mempty
data DefRole = FunName | FunParam | BindVar | AltVar
deriving (Eq, Show)
foldNameDefExpF :: (Monoid m) => (DefRole -> Name -> m) -> ExpF a -> m
foldNameDefExpF f = \case
DefF name args _ -> mconcat $ (f FunName name) : map (f FunParam) args
EBindF _ bPat _ -> f BindVar (_bPatVar bPat)
QUESTION : What should be the alt name 's DefRole ? Now it is BindVar , because it rebinds the scrutinee .
AltF cpat n _ -> f BindVar n <> foldNames (f AltVar) cpat
_ -> mempty
mapNamesCPat :: (Name -> Name) -> CPat -> CPat
mapNamesCPat f = \case
NodePat tag args -> NodePat tag (map f args)
cpat -> cpat
mapNamesVal :: (Name -> Name) -> Val -> Val
mapNamesVal f = \case
ConstTagNode tag args -> ConstTagNode tag (map f args)
Var name -> Var $ f name
val -> val
mapNamesBPat :: (Name -> Name) -> BPat -> BPat
mapNamesBPat f = \case
VarPat v -> VarPat (f v)
AsPat tag vars v -> AsPat tag (map f vars) (f v)
name vals - > name ( map ( mapValVal f ) vals )
mapValsExp :: (Val -> Val) -> Exp -> Exp
mapValsExp f = \case
ECase scrut alts -> ECase scrut alts
SReturn val -> SReturn $ f val
exp -> exp
mapValsExpM :: Monad m => (Val -> m Val) -> Exp -> m Exp
mapValsExpM f = \case
SReturn val -> SReturn <$> f val
exp -> pure exp
mapNameUseExp :: (Name -> Name) -> Exp -> Exp
mapNameUseExp f = \case
SStore v -> SStore (f v)
SFetch p -> SFetch (f p)
SUpdate p v -> SUpdate (f p) (f v)
ECase scrut alts -> ECase (f scrut) alts
SApp fun args -> SApp (f fun) (map f args)
exp -> mapValsExp (mapNamesVal f) exp
subst :: Ord a => Map a a -> a -> a
subst env x = Map.findWithDefault x x env
substitute all @Names@s in an @Exp@ ( non - recursive )
substVarRefExp :: Map Name Name -> Exp -> Exp
substVarRefExp env = mapNameUseExp (subst env)
substitute all @Names@s in a @Val@ ( non - recursive )
substNamesVal :: Map Name Name -> Val -> Val
substNamesVal env = mapNamesVal (subst env)
substValsVal :: Map Val Val -> Val -> Val
substValsVal env = subst env
substVals :: Map Val Val -> Exp -> Exp
substVals env = mapValsExp (subst env)
cPatToVal :: CPat -> Val
cPatToVal = \case
NodePat tag args -> ConstTagNode tag args
LitPat lit -> Lit lit
DefaultPat -> Unit
cPatToAsPat :: Name -> CPat -> BPat
cPatToAsPat name (NodePat tag args) = AsPat tag args name
cPatToAsPat _ cPat = error $ "cPatToAsPat: cannot convert to as-pattern: " ++ show (PP cPat)
cataM
:: (Monad m, Traversable (Base t), Recursive t)
=> (Base t a -> m a) -> t -> m a
cataM alg = c where
c = alg <=< traverse c . project
anaM
:: (Monad m, Traversable (Base t), Corecursive t)
=> (a -> m (Base t a)) -> a -> m t
anaM coalg = a where
a = (pure . embed) <=< traverse a <=< coalg
paraM
:: (Monad m, Traversable (Base t), Recursive t)
=> (Base t (t, a) -> m a) -> t -> m a
paraM alg = p where
p = alg <=< traverse f . project
f t = liftM2 (,) (pure t) (p t)
apoM
:: (Monad m, Traversable (Base t), Corecursive t)
=> (a -> m (Base t (Either t a))) -> a -> m t
apoM coalg = a where
a = (pure . embed) <=< traverse f <=< coalg
f = either pure a
hyloM
:: (Monad m, Traversable t)
=> (t b -> m b) -> (a -> m (t a)) -> a -> m b
hyloM alg coalg = h
where h = alg <=< traverse h <=< coalg
histoM
:: (Monad m, Traversable (Base t), Recursive t)
=> (Base t (Cofree (Base t) a) -> m a) -> t -> m a
histoM h = pure . extract <=< worker where
worker = f <=< traverse worker . project
f x = (:<) <$> h x <*> pure x
skipUnit :: ExpF Exp -> Exp
skipUnit = \case
exp -> embed exp
newtype TagInfo = TagInfo { _tagArityMap :: Map.Map Tag Int }
deriving (Eq, Show)
updateTagInfo :: Tag -> Int -> TagInfo -> TagInfo
updateTagInfo t n ti@(TagInfo m) =
case Map.lookup t m of
Just arity | arity < n -> TagInfo $ Map.insert t n m
Nothing -> TagInfo $ Map.insert t n m
_ -> ti
collectTagInfo :: Exp -> TagInfo
collectTagInfo = flip execState (TagInfo Map.empty) . cataM alg
where
alg :: ExpF () -> State TagInfo ()
alg = \case
SReturnF val -> goVal val
AltF cpat _ _ -> goCPat cpat
_ -> pure ()
goVal :: Val -> State TagInfo ()
goVal (ConstTagNode t args) = modify $ updateTagInfo t (length args)
goVal _ = pure ()
goCPat :: CPat -> State TagInfo ()
goCPat (NodePat t args) = modify $ updateTagInfo t (length args)
goCPat _ = pure ()
lookupExcept :: (Monad m, Ord k) =>
String ->
k -> Map k v ->
ExceptT String m v
lookupExcept err k = maybe (throwE err) pure . Map.lookup k
lookupExceptT :: (MonadTrans t, Monad m, Ord k) =>
String ->
k -> Map k v ->
t (ExceptT String m) v
lookupExceptT err k = lift . lookupExcept err k
mapWithDoubleKey :: (Ord k1, Ord k2) =>
(k1 -> k2 -> a -> b) ->
Map k1 (Map k2 a) ->
Map k1 (Map k2 b)
mapWithDoubleKey f = Map.mapWithKey (\k1 m -> Map.mapWithKey (f k1) m)
mapWithDoubleKeyM :: (Ord k1, Ord k2, Monad m) =>
(k1 -> k2 -> a -> m b) ->
Map k1 (Map k2 a) ->
m (Map k1 (Map k2 b))
mapWithDoubleKeyM f = sequence . Map.mapWithKey (\k1 m -> sequence $ Map.mapWithKey (f k1) m)
lookupWithDoubleKey :: (Ord k1, Ord k2) => k1 -> k2 -> Map k1 (Map k2 v) -> Maybe v
lookupWithDoubleKey k1 k2 m = Map.lookup k1 m >>= Map.lookup k2
lookupWithDoubleKeyExcept :: (Monad m, Ord k1, Ord k2) =>
String -> k1 -> k2 ->
Map k1 (Map k2 v) ->
ExceptT String m v
lookupWithDoubleKeyExcept err k1 k2 = maybe (throwE err) pure
. lookupWithDoubleKey k1 k2
lookupWithDoubleKeyExceptT :: (MonadTrans t, Monad m, Ord k1, Ord k2) =>
String -> k1 -> k2 ->
Map k1 (Map k2 v) ->
t (ExceptT String m) v
lookupWithDoubleKeyExceptT err k1 k2 = lift . lookupWithDoubleKeyExcept err k1 k2
notFoundIn :: Show a => String -> a -> String -> String
notFoundIn n1 x n2 = n1 ++ " " ++ show x ++ " not found in " ++ n2
markToRemove :: a -> Bool -> Maybe a
markToRemove x True = Just x
markToRemove _ False = Nothing
zipFilter :: [a] -> [Bool] -> [a]
zipFilter xs = catMaybes . zipWith markToRemove xs
bindToUndefineds :: Monad m => TypeEnv -> Exp -> [Name] -> ExceptT String m Exp
bindToUndefineds TypeEnv{..} = foldM bindToUndefined where
bindToUndefined :: Monad m => Exp -> Name -> ExceptT String m Exp
bindToUndefined rhs v = do
ty <- lookupExcept (notInTypeEnv v) v _variable
let ty' = simplifyType ty
pure $ EBind (SReturn (Undefined ty')) (VarPat v) rhs
notInTypeEnv v = "Variable " ++ show (PP v) ++ " was not found in the type environment."
simplifySimpleType :: SimpleType -> SimpleType
simplifySimpleType (T_Location _) = T_UnspecifiedLocation
simplifySimpleType t = t
simplifyNodeSet :: NodeSet -> NodeSet
simplifyNodeSet = fmap (fmap simplifySimpleType)
simplifyType :: Type -> Type
simplifyType (T_SimpleType st) = T_SimpleType $ simplifySimpleType st
simplifyType (T_NodeSet ns) = T_NodeSet $ simplifyNodeSet ns
|
97766f86308b4232a552f8e2a856f55ad7cfa9592f5ac893799c81278d81a4e1 | music-suite/music-suite | NewTTStuff.hs |
sameDurations :: Voice a -> Voice b -> Bool
mergeIfSameDuration :: Voice a -> Voice b -> Maybe (Voice (a, b))
mergeIfSameDurationWith :: (a -> b -> c) -> Voice a -> Voice b -> Maybe (Voice c)
-- TODO relate to Splittable
splitAt ::
splitAt :: [Duration] -> Voice a -> [Voice a]
-- This is a specification
splitTiesVoiceAt : : a = > [ Duration ] - > Voice a - > [ Voice a ]
splitLatterToAssureSameDuration :: Voice b -> Voice b -> Voice b
splitLatterToAssureSameDurationWith :: (b -> (b, b)) -> Voice b -> Voice b -> Voice b
TODO more potential here !
-- Compare music21's Stream.chordify
polyToHomophonic :: [Voice a] -> Maybe (Voice [a])
polyToHomophonicForce :: [Voice a] -> Voice [a]
homoToPolyphonic :: Voice [a] -> [Voice a]
joinVoice :: Voice (Voice a) -> a
changeCrossing :: Ord a => Voice a -> Voice a -> (Voice a, Voice a)
changeCrossingBy :: Ord b => (a -> b) -> Voice a -> Voice a -> (Voice a, Voice a)
-- More generally
| If two voices have * exactly * overlapping notes , do something with them ( i.e. swap them )
processExactOverlaps :: (a -> a -> (a, a)) -> Voice a -> Voice a -> (Voice a, Voice a)
processExactOverlaps' :: (a -> b -> Either (a,b) (b,a)) -> Voice a -> Voice b -> (Voice (Either b a), Voice (Either a b))
-- Position of each value
onsetsRelative :: Time -> Voice a -> [Time]
offsetsRelative :: Time -> Voice a -> [Time]
midpointsRelative :: Time -> Voice a -> [Time]
erasRelative :: Time -> Voice a -> [Span]
onsetMap :: Time -> Voice a -> Map Time a
offsetMap :: Time -> Voice a -> Map Time a
midpointMap :: Time -> Voice a -> Map Time a
eraMap :: Time -> Voice a -> Map Span a
TODO relates to Track ( old " Score " )
-- Note that eraMap for Track
durations :: Voice a -> [Duration]
values :: Voice a -> [a] -- Same as Foldable.toList
isPossiblyInfinite :: Voice a -> Bool
hasMelodicDissonanceWith :: (a -> a -> Bool) -> Voice a -> Bool
hasIntervalWith :: AffineSpace a => (Diff a -> Bool) -> Voice a -> Bool
hasDurationWith :: (Duration -> Bool) -> Voice a -> Bool
reifyVoice :: Voice a -> Voice (Duration, a)
mapWithIndex :: (Int -> a -> b) -> Voice a -> Voice b
mapWithDuration :: (Duration -> a -> b) -> Voice a -> Voice b
mapWithIndexAndDuration :: (Int -> Duration -> a -> b) -> Voice a -> Voice b
-- Up to meta-data...
_ :: Iso (Voice ()) [Duration]
asingleton' :: Prism (Voice a) (Duration, a)
asingleton :: Prism (Voice a) a
-- More interesting for score...
separateVoicesWith :: (a -> k) -> Voice a -> Map k (Voice a)
-- List functions as voice functions for free
-- TODO this *only* works with fully polymorphic functions, so combinators where
-- user arguments can restrict the function (i.e. intersperse) does not work
freeVoiceR :: (forall a. -> [a] -> a) -> Voice a -> (a, Duration)
-- head last null "length"
freeVoiceRNoDur :: ([a] -> a) -> Voice a -> a
-- head last null "length"
-- sum product maximum minimum
TODO folds and scans ?
freeVoice :: (forall a. -> [a] -> [a]) -> Voice a -> Voice a
-- tail init reverse cycle take drop
freeVoice2 :: (forall a. -> [a] -> [a] -> [a]) -> Voice a -> Voice a -> Voice a
-- "special" lifted functions
empty :: Voice a
singleton :: a -> Voice a
cons :: a -> Voice a -> Voice a
snoc :: Voice a -> a -> Voice a
append :: Voice a -> Voice a -> Voice a
ap :: Voice (a -> b) -> Voice a -> Voice b
apDur :: Voice (Duration -> Duration -> a -> b) -> Voice a -> Voice b
-- TODO ap vs. zip
-- Which one is the instance?
intersperse :: Duration -> a -> Voice a -> Voice a
-- intercalate :: Voice a -> Voice (Voice a) -> Voice a
subsequences :: Voice a -> [Voice a]
permutations :: Voice a -> [Voice a]
iterate :: (a -> a) -> a -> Voice a
repeat :: a -> Voice a
replicate :: Int -> a -> Voice a
unfoldr :: (b -> Maybe (a, b)) -> b -> Voice a
-- Standard levels in a score
data ScoreLevel
= Score -- parallell composition of
| Part -- sequential composition of
| Bar -- sequential composition of
| Chord -- parallel composition
-- Idea: API to "tag" a voice/chord with its level
-- Similar to music21 "groups"
Differences between Voice and Chord ( except the obviously different composition styles ):
- Voice is a Monoid , Chord just a Semigroup ( ? ? )
- Rationale : We want to separate Note / Chord / Rest
- Scores are always sorted ( i.e. more like ( multi)sets than lists ) ( ? ? )
- TODO is there / Applicative for MultiSet / SortedList ?
Differences between Voice and Chord (except the obviously different composition styles):
- Voice is a Monoid, Chord just a Semigroup (??)
- Rationale: We want to separate Note/Chord/Rest
- Scores are always sorted (i.e. more like (multi)sets than lists) (??)
- TODO is there Monad/Applicative for MultiSet/SortedList?
-}
{-
- TODO represent spanners using (Voice a, Map (Int,Int) s)
Arguably this should be part of Voice
-}
{-
TODO the MVoice/TVoice stuff
-}
newtype MVoice = Voice (Maybe a)
newtype PVoice = [Either Duration (Voice a)]
TODO the context stuff
TODO the context stuff
-}
{-
TODO Zippers
-}
{-
Inspired by music21 variants
-}
newtype Variant a = { _getVariant :: [a] }
instance Representable Variant where
type Rep = Positive
tabulate f = fmap f [1..]
index v n = cycle v !! n' where n' = fromIntegral n
-- OR
-- index v n = v !! n `mod` (length n)
expandRepeats :: [Voice (Variant a)] -> Voice a
--------------
invert :: Transposable a => Chord a -> Chord a
inversions :: Transposable a => Chord a -> [Chord a]
chordToScore :: Chord a -> Score a
arpUp3 :: Chord a -> Score a
arpDown3 :: Chord a -> Score a
alberti3 :: Chord a -> Score a
majorTriad :: Transposable a => a -> Chord a
minorTriad :: Transposable a => a -> Chord a
-- What is a scale, chord, "sequence" etc?
----------------
| null | https://raw.githubusercontent.com/music-suite/music-suite/7f01fd62334c66418043b7a2d662af127f98685d/sketch/old/NewTTStuff.hs | haskell | TODO relate to Splittable
This is a specification
Compare music21's Stream.chordify
More generally
Position of each value
Note that eraMap for Track
Same as Foldable.toList
Up to meta-data...
More interesting for score...
List functions as voice functions for free
TODO this *only* works with fully polymorphic functions, so combinators where
user arguments can restrict the function (i.e. intersperse) does not work
head last null "length"
head last null "length"
sum product maximum minimum
tail init reverse cycle take drop
"special" lifted functions
TODO ap vs. zip
Which one is the instance?
intercalate :: Voice a -> Voice (Voice a) -> Voice a
Standard levels in a score
parallell composition of
sequential composition of
sequential composition of
parallel composition
Idea: API to "tag" a voice/chord with its level
Similar to music21 "groups"
- TODO represent spanners using (Voice a, Map (Int,Int) s)
Arguably this should be part of Voice
TODO the MVoice/TVoice stuff
TODO Zippers
Inspired by music21 variants
OR
index v n = v !! n `mod` (length n)
------------
What is a scale, chord, "sequence" etc?
-------------- |
sameDurations :: Voice a -> Voice b -> Bool
mergeIfSameDuration :: Voice a -> Voice b -> Maybe (Voice (a, b))
mergeIfSameDurationWith :: (a -> b -> c) -> Voice a -> Voice b -> Maybe (Voice c)
splitAt ::
splitAt :: [Duration] -> Voice a -> [Voice a]
splitTiesVoiceAt : : a = > [ Duration ] - > Voice a - > [ Voice a ]
splitLatterToAssureSameDuration :: Voice b -> Voice b -> Voice b
splitLatterToAssureSameDurationWith :: (b -> (b, b)) -> Voice b -> Voice b -> Voice b
TODO more potential here !
polyToHomophonic :: [Voice a] -> Maybe (Voice [a])
polyToHomophonicForce :: [Voice a] -> Voice [a]
homoToPolyphonic :: Voice [a] -> [Voice a]
joinVoice :: Voice (Voice a) -> a
changeCrossing :: Ord a => Voice a -> Voice a -> (Voice a, Voice a)
changeCrossingBy :: Ord b => (a -> b) -> Voice a -> Voice a -> (Voice a, Voice a)
| If two voices have * exactly * overlapping notes , do something with them ( i.e. swap them )
processExactOverlaps :: (a -> a -> (a, a)) -> Voice a -> Voice a -> (Voice a, Voice a)
processExactOverlaps' :: (a -> b -> Either (a,b) (b,a)) -> Voice a -> Voice b -> (Voice (Either b a), Voice (Either a b))
onsetsRelative :: Time -> Voice a -> [Time]
offsetsRelative :: Time -> Voice a -> [Time]
midpointsRelative :: Time -> Voice a -> [Time]
erasRelative :: Time -> Voice a -> [Span]
onsetMap :: Time -> Voice a -> Map Time a
offsetMap :: Time -> Voice a -> Map Time a
midpointMap :: Time -> Voice a -> Map Time a
eraMap :: Time -> Voice a -> Map Span a
TODO relates to Track ( old " Score " )
durations :: Voice a -> [Duration]
isPossiblyInfinite :: Voice a -> Bool
hasMelodicDissonanceWith :: (a -> a -> Bool) -> Voice a -> Bool
hasIntervalWith :: AffineSpace a => (Diff a -> Bool) -> Voice a -> Bool
hasDurationWith :: (Duration -> Bool) -> Voice a -> Bool
reifyVoice :: Voice a -> Voice (Duration, a)
mapWithIndex :: (Int -> a -> b) -> Voice a -> Voice b
mapWithDuration :: (Duration -> a -> b) -> Voice a -> Voice b
mapWithIndexAndDuration :: (Int -> Duration -> a -> b) -> Voice a -> Voice b
_ :: Iso (Voice ()) [Duration]
asingleton' :: Prism (Voice a) (Duration, a)
asingleton :: Prism (Voice a) a
separateVoicesWith :: (a -> k) -> Voice a -> Map k (Voice a)
freeVoiceR :: (forall a. -> [a] -> a) -> Voice a -> (a, Duration)
freeVoiceRNoDur :: ([a] -> a) -> Voice a -> a
TODO folds and scans ?
freeVoice :: (forall a. -> [a] -> [a]) -> Voice a -> Voice a
freeVoice2 :: (forall a. -> [a] -> [a] -> [a]) -> Voice a -> Voice a -> Voice a
empty :: Voice a
singleton :: a -> Voice a
cons :: a -> Voice a -> Voice a
snoc :: Voice a -> a -> Voice a
append :: Voice a -> Voice a -> Voice a
ap :: Voice (a -> b) -> Voice a -> Voice b
apDur :: Voice (Duration -> Duration -> a -> b) -> Voice a -> Voice b
intersperse :: Duration -> a -> Voice a -> Voice a
subsequences :: Voice a -> [Voice a]
permutations :: Voice a -> [Voice a]
iterate :: (a -> a) -> a -> Voice a
repeat :: a -> Voice a
replicate :: Int -> a -> Voice a
unfoldr :: (b -> Maybe (a, b)) -> b -> Voice a
data ScoreLevel
Differences between Voice and Chord ( except the obviously different composition styles ):
- Voice is a Monoid , Chord just a Semigroup ( ? ? )
- Rationale : We want to separate Note / Chord / Rest
- Scores are always sorted ( i.e. more like ( multi)sets than lists ) ( ? ? )
- TODO is there / Applicative for MultiSet / SortedList ?
Differences between Voice and Chord (except the obviously different composition styles):
- Voice is a Monoid, Chord just a Semigroup (??)
- Rationale: We want to separate Note/Chord/Rest
- Scores are always sorted (i.e. more like (multi)sets than lists) (??)
- TODO is there Monad/Applicative for MultiSet/SortedList?
-}
newtype MVoice = Voice (Maybe a)
newtype PVoice = [Either Duration (Voice a)]
TODO the context stuff
TODO the context stuff
-}
newtype Variant a = { _getVariant :: [a] }
instance Representable Variant where
type Rep = Positive
tabulate f = fmap f [1..]
index v n = cycle v !! n' where n' = fromIntegral n
expandRepeats :: [Voice (Variant a)] -> Voice a
invert :: Transposable a => Chord a -> Chord a
inversions :: Transposable a => Chord a -> [Chord a]
chordToScore :: Chord a -> Score a
arpUp3 :: Chord a -> Score a
arpDown3 :: Chord a -> Score a
alberti3 :: Chord a -> Score a
majorTriad :: Transposable a => a -> Chord a
minorTriad :: Transposable a => a -> Chord a
|
d96190fd6fe7a0eb481b8286b883bf39684ee512b70376a643f71893f3eb7c01 | schlepfilter/frp | keyboard_shortcuts.cljs | (ns examples.rx.keyboard-shortcuts
(:require [clojure.string :as str]
[cats.core :as m]
[cljsjs.mousetrap]
[com.rpl.specter :as s]
[frp.core :as frp]
[frp.clojure.core :as core]))
(def combine
(comp (partial str/join "+")
vector))
(def placeholder
(combine "ctrl" "alt" "d"))
(frp/defe typing addition trigger)
(def registration
(->> typing
(frp/stepper "")
(frp/snapshot addition)
(m/<$> second)
(m/<> (frp/event placeholder (combine "ctrl" "alt" "s") "trash"))
core/distinct))
(def counter
(->> trigger
(m/<> registration)
(core/group-by identity)
(m/<$> (partial s/transform* s/MAP-VALS (comp dec
count)))))
(defn keyboard-shortcuts-component
[counter*]
[:div
[:input {:on-change #(-> %
.-target.value
typing)
:placeholder placeholder}]
[:button {:on-click #(addition)}
"Add"]
[:p "Keyboard shortcuts:"]
(->> counter*
(s/transform s/MAP-VALS str)
(mapv (comp (partial vector :li)
(partial str/join ": ")))
(s/setval s/BEFORE-ELEM :ul))])
(def keyboard-shortcuts
(->> counter
(frp/stepper {})
(m/<$> keyboard-shortcuts-component)))
(frp/run (fn [registration*]
(js/Mousetrap.bind registration* #(trigger registration*)))
registration)
| null | https://raw.githubusercontent.com/schlepfilter/frp/4a889f0aefd3aa17371fe1f0cdfabdad01fece8f/examples/src/examples/rx/keyboard_shortcuts.cljs | clojure | (ns examples.rx.keyboard-shortcuts
(:require [clojure.string :as str]
[cats.core :as m]
[cljsjs.mousetrap]
[com.rpl.specter :as s]
[frp.core :as frp]
[frp.clojure.core :as core]))
(def combine
(comp (partial str/join "+")
vector))
(def placeholder
(combine "ctrl" "alt" "d"))
(frp/defe typing addition trigger)
(def registration
(->> typing
(frp/stepper "")
(frp/snapshot addition)
(m/<$> second)
(m/<> (frp/event placeholder (combine "ctrl" "alt" "s") "trash"))
core/distinct))
(def counter
(->> trigger
(m/<> registration)
(core/group-by identity)
(m/<$> (partial s/transform* s/MAP-VALS (comp dec
count)))))
(defn keyboard-shortcuts-component
[counter*]
[:div
[:input {:on-change #(-> %
.-target.value
typing)
:placeholder placeholder}]
[:button {:on-click #(addition)}
"Add"]
[:p "Keyboard shortcuts:"]
(->> counter*
(s/transform s/MAP-VALS str)
(mapv (comp (partial vector :li)
(partial str/join ": ")))
(s/setval s/BEFORE-ELEM :ul))])
(def keyboard-shortcuts
(->> counter
(frp/stepper {})
(m/<$> keyboard-shortcuts-component)))
(frp/run (fn [registration*]
(js/Mousetrap.bind registration* #(trigger registration*)))
registration)
| |
3a9679335c5ba1ac44382925fb4f5cb0f4c183dbb089c5e12849bd0d106a88a9 | korya/efuns | test2.ml | let switch_knowm x =
let y = None in
match y with
None -> x + 2
| Some z -> x + z
let orororor x1 x2 x3 x4 =
x1 lor (x2 lsl 8) lor (x3 lsl 16) lor (x4 lsl 24)
let deadcode x y z =
let zz = y+z in
let w = y*2 + zz in
(x+1,y+2,z+3)
let loop () =
while true do () done
let set buf pos c =
buf.[pos*2] <- c
let simple x y z t =
x+y*z+t
let common x y z =
while true do
let e = x+y+z in
print_int e
done
open String
let setInt buffer pos int =
unsafe_set buffer pos (Char.unsafe_chr (int land 0xff));
unsafe_set buffer (pos+1) (Char.unsafe_chr ((int lsr 8) land 0xff));
unsafe_set buffer (pos+2) (Char.unsafe_chr ((int lsr 16) land 0xff));
unsafe_set buffer (pos+3) (Char.unsafe_chr ((int lsr 24) land 0xff))
type a =
T of int
| U of int
| V of int
| W of int
| X of int
| Y of int
| Z of int
let pattern x =
match x with
T x -> x+2
| U y -> y+2
| V z -> z+2
| Y _ | Z _ -> 4
| _ -> 3 | null | https://raw.githubusercontent.com/korya/efuns/78b21d9dff45b7eec764c63132c7a564f5367c30/inliner/tests/test2.ml | ocaml | let switch_knowm x =
let y = None in
match y with
None -> x + 2
| Some z -> x + z
let orororor x1 x2 x3 x4 =
x1 lor (x2 lsl 8) lor (x3 lsl 16) lor (x4 lsl 24)
let deadcode x y z =
let zz = y+z in
let w = y*2 + zz in
(x+1,y+2,z+3)
let loop () =
while true do () done
let set buf pos c =
buf.[pos*2] <- c
let simple x y z t =
x+y*z+t
let common x y z =
while true do
let e = x+y+z in
print_int e
done
open String
let setInt buffer pos int =
unsafe_set buffer pos (Char.unsafe_chr (int land 0xff));
unsafe_set buffer (pos+1) (Char.unsafe_chr ((int lsr 8) land 0xff));
unsafe_set buffer (pos+2) (Char.unsafe_chr ((int lsr 16) land 0xff));
unsafe_set buffer (pos+3) (Char.unsafe_chr ((int lsr 24) land 0xff))
type a =
T of int
| U of int
| V of int
| W of int
| X of int
| Y of int
| Z of int
let pattern x =
match x with
T x -> x+2
| U y -> y+2
| V z -> z+2
| Y _ | Z _ -> 4
| _ -> 3 | |
8acde4fc686f5b450fa78483b77bfb56cba3edcf1f395bd346053d0fb49a4dd3 | S8A/htdp-exercises | ex079.rkt | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-beginner-reader.ss" "lang")((modname ex079) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp")) #f)))
A Color is one of :
; — "white"
; — "yellow"
; — "orange"
; — "green"
; — "red"
; — "blue"
; — "black"
Color blue
H is a Number between 0 and 100 .
; interpretation represents a happiness value
(define VERY-SAD 16) ; A low happiness value
(define NORMAL 50) ; A medium happiness value
(define VERY-HAPPY 84) ; A high happiness value
(define-struct person [fstname lstname male?])
; A Person is a structure:
; (make-person String String Boolean)
A male named
A female named
; Q: Is it a good idea to use a field name that looks
; like the name of a predicate?
; A: No.
(define-struct dog [owner name age happiness])
; A Dog is a structure:
; (make-dog Person String PositiveInteger H)
; interpretation (make-dog o n a h) is a dog named n,
; owned by o, of age a, and currently has a happiness
; level of h
(define FIRU (make-dog "Bob" "Firulais" 5 VERY-HAPPY))
; A Weapon is one of:
; — #false
; — Posn
; interpretation #false means the missile hasn't
; been fired yet; a Posn means it is in flight
An ICBM flying at position ( 50 , 2000 )
(define NUKE #false) ; A nuclear bomb that hasn't been fired
| null | https://raw.githubusercontent.com/S8A/htdp-exercises/578e49834a9513f29ef81b7589b28081c5e0b69f/ex079.rkt | racket | about the language level of this file in a form that our tools can easily process.
— "white"
— "yellow"
— "orange"
— "green"
— "red"
— "blue"
— "black"
interpretation represents a happiness value
A low happiness value
A medium happiness value
A high happiness value
A Person is a structure:
(make-person String String Boolean)
Q: Is it a good idea to use a field name that looks
like the name of a predicate?
A: No.
A Dog is a structure:
(make-dog Person String PositiveInteger H)
interpretation (make-dog o n a h) is a dog named n,
owned by o, of age a, and currently has a happiness
level of h
A Weapon is one of:
— #false
— Posn
interpretation #false means the missile hasn't
been fired yet; a Posn means it is in flight
A nuclear bomb that hasn't been fired | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-beginner-reader.ss" "lang")((modname ex079) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp")) #f)))
A Color is one of :
Color blue
H is a Number between 0 and 100 .
(define-struct person [fstname lstname male?])
A male named
A female named
(define-struct dog [owner name age happiness])
(define FIRU (make-dog "Bob" "Firulais" 5 VERY-HAPPY))
An ICBM flying at position ( 50 , 2000 )
|
777fed77c10d302afd03430fb12f504246910cba2a32207ec935bb2afb90dfbe | Workiva/flowgraph | queue.clj | Copyright 2016 - 2019 Workiva Inc.
;;
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 flowgraph.queue
(:require [flowgraph.protocols :as p :refer :all]
[flowgraph.error :refer [raise-queue-err]]
[recide.core :refer [insist]]
[recide.sanex :as sanex]
[clojure.pprint :as pprint])
(:import [java.util.concurrent
BlockingQueue LinkedBlockingQueue PriorityBlockingQueue
BlockingDeque LinkedBlockingDeque])
(:refer-clojure :exclude [pop peek]))
(defn- slurp-juc-queue
"empties the queue, does not block on asynchronous work, returns all items."
[^java.util.concurrent.BlockingQueue juc-queue]
(let [arr-results (.toArray juc-queue)]
(.clear juc-queue)
(seq arr-results)))
(defrecord SimpleQueue [^BlockingQueue juc-queue guard fns]
p/GuardedQueue
(set-guard! [_ g]
(reset! guard g)
(.clear juc-queue))
(ready? [_] (not (.isEmpty juc-queue)))
(pop [this g force?] (pop this g))
(pop [_ g] (if (identical? g @guard) ((:poll fns) juc-queue)
(raise-queue-err :access "guarded queue presented with wrong token."
{:method 'pop, :token g, :expected @guard, ::sanex/sanitary? true})))
(push [_ g item] (if (identical? g @guard) ((:put fns) juc-queue item)
(raise-queue-err :access "guarded queue presented with wrong token."
{:method 'push, :token g, :expected @guard, ::sanex/sanitary? true})))
(push-deferred [_ g deferred-item] (raise-queue-err :unsupported "SimpleQueues don't support push-deferred."
{:method 'push-deferred, :class SimpleQueue, ::sanex/sanitary? true}))
(push-batch [_ g batch] (if (identical? g @guard) (doseq [item batch] ((:put fns) juc-queue item))
(raise-queue-err :access "guarded queue presented with wrong token."
{:method 'push-batch, :token g, :expected @guard, ::sanex/sanitary? true})))
(push-deferred-batch [_ g deferred-item]
(raise-queue-err :unsupported "SimpleQueues don't support push-deferred-batch."
{:method 'push-deferred-batch, :class SimpleQueue, ::sanex/sanitary? true}))
(peek [_] ((:peek fns) juc-queue))
(drain [_ g]
(when (identical? g @guard)
(slurp-juc-queue juc-queue)))
(raw-size [_] (.size juc-queue)))
(defn ->queue-fns [stack?]
(if stack?
{:poll (fn poll-last [^BlockingDeque q] (.pollLast q))
:put (fn put-last [^BlockingDeque q x] (.putLast q x))
:peek (fn peek-last [^BlockingDeque q] (.peekLast q))}
{:poll (fn poll [^BlockingQueue q] (.poll q))
:put (fn put [^BlockingQueue q x] (.put q x))
:peek (fn peek [^BlockingQueue q] (.peek q))}))
(defn- simple-queue
"For when the queue will hold tasks."
[juc-queue stack?]
(let [guard (atom 0)]
(->SimpleQueue juc-queue guard (->queue-fns stack?))))
(defmethod clojure.pprint/simple-dispatch SimpleQueue
[queue]
(clojure.pprint/pprint-logical-block :prefix "#SimpleQueue"
:suffix ""
(clojure.pprint/write-out (-> queue
(assoc :empty? (.isEmpty ^BlockingQueue (:juc-queue queue)))
(dissoc :juc-queue)))
""))
(defmethod print-method SimpleQueue
[queue ^java.io.Writer w]
(.write w (str "#SimpleQueue"
(-> queue
(assoc :empty? (.isEmpty ^BlockingQueue (:juc-queue queue)))
(dissoc :juc-queue)))))
(defrecord DefermentQueue [^BlockingQueue juc-queue current-batch guard fns]
GuardedQueue
(set-guard! [_ g]
(reset! guard g)
(.clear juc-queue)
(reset! current-batch []))
(ready? [this] (locking this
(or (not-empty @current-batch)
(when-let [item ((:peek fns) juc-queue)]
(or (= ::real (first item))
(realized? ^clojure.lang.IDeref (second item)))))))
(pop [this g force?] (pop this g))
(pop [this g]
(if (identical? g @guard)
(when-let [[type item] (locking this
(if (empty? @current-batch)
(when (ready? this)
(let [[type item :as result] ((:poll fns) juc-queue)]
(if (= ::deferred-batch type)
(let [[item & items] @item]
(reset! current-batch items)
[::real item])
result)))
(let [item (first @current-batch)]
(swap! current-batch rest)
[::real item])))]
(condp = type
::real item
::deferred-item @item))
(raise-queue-err :access "guarded queue presented with wrong token"
{:method 'pop, :token g, :expected @guard, ::sanex/sanitary? true})))
(push [_ g item] (if (identical? g @guard) ((:put fns) juc-queue [::real item])
(raise-queue-err :access "guarded queue presented with wrong token"
{:method 'push, :token g, :expected @guard, ::sanex/sanitary? true})))
(push-deferred [_ g deferred-item] (if (identical? g @guard)
((:put fns) juc-queue [::deferred-item deferred-item])
(raise-queue-err :access "guarded queue presented with wrong token"
{:method 'push-deferred, :token g, :expected @guard, ::sanex/sanitary? true})))
(push-batch [_ g batch] (if (identical? g @guard)
(doseq [item batch] ((:put fns) juc-queue [::real item]))
(raise-queue-err :access "guarded queue presented with wrong token"
{:method 'push-batch, :token g, :expected @guard, ::sanex/sanitary? true})))
(push-deferred-batch [_ g deferred-item] (if (identical? g @guard)
((:put fns) juc-queue [::deferred-batch deferred-item])
(raise-queue-err :access "guarded queue presented with wrong token"
{:method 'push-deferred-batch, :token g, :expected @guard, ::sanex/sanitary? true})))
(peek [_] ((:peek fns) juc-queue))
(drain [this g]
(when (identical? g @guard)
(let [raw (concat (map (fn [i] [::real i]) @current-batch) (slurp-juc-queue juc-queue))]
(reset! current-batch [])
(reduce (fn [c [type item]]
(case type
::real (conj c item)
::deferred-batch (into c @item)
::deferred-item (conj c @item)))
[]
raw))))
(raw-size [_] (+ (count @current-batch) (.size juc-queue))))
(defmethod clojure.pprint/simple-dispatch DefermentQueue
[queue]
(clojure.pprint/pprint-logical-block :prefix "#DefermentQueue"
:suffix ""
(clojure.pprint/write-out (-> queue
(assoc :empty? (.isEmpty ^BlockingQueue (:juc-queue queue)))
(dissoc queue :juc-queue)))
""))
(defmethod print-method DefermentQueue
[^BlockingQueue queue ^java.io.Writer w]
(.write w (str "#DefermentQueue"
(-> queue
(assoc :empty? (.isEmpty ^BlockingQueue (:juc-queue queue)))
(dissoc queue :juc-queue)))))
(defn- deferment-queue
"For when the queue will hold promises -- if the computation is asynchronous,
or if the edge into this queue is both coordinated and involves some computation."
[juc-queue stack?]
(->DefermentQueue juc-queue (atom ()) (atom 0) (->queue-fns stack?)))
(defrecord BatchedQueue
[task-queue n todos guard]
GuardedQueue
(set-guard! [_ g]
(reset! guard g)
(reset! todos [])
(set-guard! task-queue g))
(ready? [_]
(or (boolean (seq @todos))
(ready? task-queue)))
(pop [this g force?]
(if force?
(when (identical? g @guard)
(locking this
(let [x (pop task-queue g true)
v @todos]
(reset! todos [])
(if x
(conj v x)
(when (not-empty v) v)))))
(pop this g)))
(pop [this g]
(when (identical? g @guard)
(when-let [x (pop task-queue g)]
(or (locking this
(let [v (swap! todos conj x)]
(when (= n (count v))
(reset! todos [])
v)))
(pop this g)))))
(push [_ g v] (when (identical? g @guard) (push task-queue g v)))
(push-deferred [_ g v] (when (identical? g @guard) (push-deferred task-queue g v)))
(push-batch [_ g v] (when (identical? g @guard) (push-batch task-queue g v)))
(push-deferred-batch [_ g v] (when (identical? g @guard) (push-deferred-batch task-queue g v)))
(peek [_] (peek task-queue))
(drain [_ g] (drain task-queue g))
;; I'm not sure what raw-size should mean here.
(raw-size [_] (+ (min 1 (count @todos)) (raw-size task-queue))))
(defn- batch-a-queue
"For when the queue wants to stick stuff out in a batch."
[task-queue n]
(let [todos (atom [])]
(->BatchedQueue task-queue n todos (atom 0))))
(defrecord CollectingQueue ;; batches 'until' (f last-received-item next-received-item) returns true.
[task-queue f semantics todos guard allow-force?]
GuardedQueue
(set-guard! [_ g]
(reset! guard g)
(dosync (ref-set todos []))
(set-guard! task-queue g))
(ready? [_]
(or (boolean (seq @todos)) 1
(ready? task-queue)))
(pop [this g force?]
(when (identical? g @guard)
(if (and force? allow-force?)
;; if forcing, we act as normal except if there is no next item to apply the until-condition to, we assume it would have been met.
(if-let [x (pop task-queue g)]
(dosync
(if (and (not-empty (ensure todos))
(f x (clojure.core/peek (ensure todos)))) ;; TODO: ensure in current iteration not really necessary
(if (= semantics :exclusive)
(let [v (ensure todos)]
(ref-set todos [x])
v)
(let [v (ensure todos)]
(ref-set todos [])
(conj v x)))
(do (alter todos conj x)
(pop this g true))))
(dosync (let [v (ensure todos)]
(when-not (empty? v)
(ref-set todos [])
v))))
(when-let [x (pop task-queue g)]
(dosync
(if (and (not-empty (ensure todos))
(f x (clojure.core/peek (ensure todos)))) ;; TODO: ensure in current iteration not really necessary
(if (= semantics :exclusive)
(let [v (ensure todos)]
(ref-set todos [x])
v)
(let [v (ensure todos)]
(ref-set todos [])
(conj v x)))
(do (alter todos conj x)
(pop this g))))))))
(pop [this g] (pop this g false))
(push [_ g v] (push task-queue g v))
(push-deferred [_ g v] (push-deferred task-queue g v))
(push-batch [_ g v] (push-batch task-queue g v))
(push-deferred-batch [_ g v] (push-deferred-batch task-queue g v))
(peek [_] (peek task-queue))
(drain [_ g] (drain task-queue g))
;; I'm not sure what raw-size means here.
(raw-size [_] (+ (raw-size task-queue) (count @todos))))
(defn- collecting-queue
[queue f semantics allow-force?]
(let [todos (ref [])]
(->CollectingQueue queue f semantics todos (atom 0) allow-force?)))
;; If the underlying queue is to be a priority queue, then we create a
PriorityBlockingQueue , else a LinkedBlockingQueue .
;;
;; If the queue is to receive promises or futures, we wrap with
;; promise-queue, else with simple-queue.
;;
;; When the queue is to be batched, we wrap that with batch-a-queue.
(defn queue
[{deferred? :deferred?, ;; false or true
batching? :batching?, ;; false or n
collecting? :collecting? ;; false or n or fn
false or Comparator
collect-inclusive? :collect-inclusive? ;; false or true
allow-force? :allow-force? ;; true or false
stack? :stack?
:or {deferred? false,
batching? false,
collecting? false,
priority-queue? false,
stack? false,
collect-inclusive? false
allow-force? true}}]
(insist (not (and collecting? batching?))) ;; can't have both
(insist (not (and priority-queue? stack?))) ;; ditto
(as-> (cond (boolean priority-queue?) (PriorityBlockingQueue. *thread-capacity*
priority-queue?)
(boolean stack?) (do
(throw (IllegalArgumentException. "Stacks are not yet surfaced in decursus."))
(LinkedBlockingDeque.))
:else (LinkedBlockingQueue.))
queue
(if deferred? (deferment-queue queue stack?) (simple-queue queue stack?))
(if batching? (batch-a-queue queue batching?) queue)
(if (and collecting? (number? collecting?)) (batch-a-queue queue collecting?) queue)
(if (and collecting? (instance? clojure.lang.IFn collecting?))
(if collect-inclusive?
(collecting-queue queue collecting? :inclusive allow-force?)
(collecting-queue queue collecting? :exclusive allow-force?))
queue)))
| null | https://raw.githubusercontent.com/Workiva/flowgraph/0a17a000fb6e8e8dcb072bbd0c0f3409f36ee545/src/flowgraph/queue.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.
I'm not sure what raw-size should mean here.
batches 'until' (f last-received-item next-received-item) returns true.
if forcing, we act as normal except if there is no next item to apply the until-condition to, we assume it would have been met.
TODO: ensure in current iteration not really necessary
TODO: ensure in current iteration not really necessary
I'm not sure what raw-size means here.
If the underlying queue is to be a priority queue, then we create a
If the queue is to receive promises or futures, we wrap with
promise-queue, else with simple-queue.
When the queue is to be batched, we wrap that with batch-a-queue.
false or true
false or n
false or n or fn
false or true
true or false
can't have both
ditto | Copyright 2016 - 2019 Workiva Inc.
distributed under the License is distributed on an " AS IS " BASIS ,
(ns flowgraph.queue
(:require [flowgraph.protocols :as p :refer :all]
[flowgraph.error :refer [raise-queue-err]]
[recide.core :refer [insist]]
[recide.sanex :as sanex]
[clojure.pprint :as pprint])
(:import [java.util.concurrent
BlockingQueue LinkedBlockingQueue PriorityBlockingQueue
BlockingDeque LinkedBlockingDeque])
(:refer-clojure :exclude [pop peek]))
(defn- slurp-juc-queue
"empties the queue, does not block on asynchronous work, returns all items."
[^java.util.concurrent.BlockingQueue juc-queue]
(let [arr-results (.toArray juc-queue)]
(.clear juc-queue)
(seq arr-results)))
(defrecord SimpleQueue [^BlockingQueue juc-queue guard fns]
p/GuardedQueue
(set-guard! [_ g]
(reset! guard g)
(.clear juc-queue))
(ready? [_] (not (.isEmpty juc-queue)))
(pop [this g force?] (pop this g))
(pop [_ g] (if (identical? g @guard) ((:poll fns) juc-queue)
(raise-queue-err :access "guarded queue presented with wrong token."
{:method 'pop, :token g, :expected @guard, ::sanex/sanitary? true})))
(push [_ g item] (if (identical? g @guard) ((:put fns) juc-queue item)
(raise-queue-err :access "guarded queue presented with wrong token."
{:method 'push, :token g, :expected @guard, ::sanex/sanitary? true})))
(push-deferred [_ g deferred-item] (raise-queue-err :unsupported "SimpleQueues don't support push-deferred."
{:method 'push-deferred, :class SimpleQueue, ::sanex/sanitary? true}))
(push-batch [_ g batch] (if (identical? g @guard) (doseq [item batch] ((:put fns) juc-queue item))
(raise-queue-err :access "guarded queue presented with wrong token."
{:method 'push-batch, :token g, :expected @guard, ::sanex/sanitary? true})))
(push-deferred-batch [_ g deferred-item]
(raise-queue-err :unsupported "SimpleQueues don't support push-deferred-batch."
{:method 'push-deferred-batch, :class SimpleQueue, ::sanex/sanitary? true}))
(peek [_] ((:peek fns) juc-queue))
(drain [_ g]
(when (identical? g @guard)
(slurp-juc-queue juc-queue)))
(raw-size [_] (.size juc-queue)))
(defn ->queue-fns [stack?]
(if stack?
{:poll (fn poll-last [^BlockingDeque q] (.pollLast q))
:put (fn put-last [^BlockingDeque q x] (.putLast q x))
:peek (fn peek-last [^BlockingDeque q] (.peekLast q))}
{:poll (fn poll [^BlockingQueue q] (.poll q))
:put (fn put [^BlockingQueue q x] (.put q x))
:peek (fn peek [^BlockingQueue q] (.peek q))}))
(defn- simple-queue
"For when the queue will hold tasks."
[juc-queue stack?]
(let [guard (atom 0)]
(->SimpleQueue juc-queue guard (->queue-fns stack?))))
(defmethod clojure.pprint/simple-dispatch SimpleQueue
[queue]
(clojure.pprint/pprint-logical-block :prefix "#SimpleQueue"
:suffix ""
(clojure.pprint/write-out (-> queue
(assoc :empty? (.isEmpty ^BlockingQueue (:juc-queue queue)))
(dissoc :juc-queue)))
""))
(defmethod print-method SimpleQueue
[queue ^java.io.Writer w]
(.write w (str "#SimpleQueue"
(-> queue
(assoc :empty? (.isEmpty ^BlockingQueue (:juc-queue queue)))
(dissoc :juc-queue)))))
(defrecord DefermentQueue [^BlockingQueue juc-queue current-batch guard fns]
GuardedQueue
(set-guard! [_ g]
(reset! guard g)
(.clear juc-queue)
(reset! current-batch []))
(ready? [this] (locking this
(or (not-empty @current-batch)
(when-let [item ((:peek fns) juc-queue)]
(or (= ::real (first item))
(realized? ^clojure.lang.IDeref (second item)))))))
(pop [this g force?] (pop this g))
(pop [this g]
(if (identical? g @guard)
(when-let [[type item] (locking this
(if (empty? @current-batch)
(when (ready? this)
(let [[type item :as result] ((:poll fns) juc-queue)]
(if (= ::deferred-batch type)
(let [[item & items] @item]
(reset! current-batch items)
[::real item])
result)))
(let [item (first @current-batch)]
(swap! current-batch rest)
[::real item])))]
(condp = type
::real item
::deferred-item @item))
(raise-queue-err :access "guarded queue presented with wrong token"
{:method 'pop, :token g, :expected @guard, ::sanex/sanitary? true})))
(push [_ g item] (if (identical? g @guard) ((:put fns) juc-queue [::real item])
(raise-queue-err :access "guarded queue presented with wrong token"
{:method 'push, :token g, :expected @guard, ::sanex/sanitary? true})))
(push-deferred [_ g deferred-item] (if (identical? g @guard)
((:put fns) juc-queue [::deferred-item deferred-item])
(raise-queue-err :access "guarded queue presented with wrong token"
{:method 'push-deferred, :token g, :expected @guard, ::sanex/sanitary? true})))
(push-batch [_ g batch] (if (identical? g @guard)
(doseq [item batch] ((:put fns) juc-queue [::real item]))
(raise-queue-err :access "guarded queue presented with wrong token"
{:method 'push-batch, :token g, :expected @guard, ::sanex/sanitary? true})))
(push-deferred-batch [_ g deferred-item] (if (identical? g @guard)
((:put fns) juc-queue [::deferred-batch deferred-item])
(raise-queue-err :access "guarded queue presented with wrong token"
{:method 'push-deferred-batch, :token g, :expected @guard, ::sanex/sanitary? true})))
(peek [_] ((:peek fns) juc-queue))
(drain [this g]
(when (identical? g @guard)
(let [raw (concat (map (fn [i] [::real i]) @current-batch) (slurp-juc-queue juc-queue))]
(reset! current-batch [])
(reduce (fn [c [type item]]
(case type
::real (conj c item)
::deferred-batch (into c @item)
::deferred-item (conj c @item)))
[]
raw))))
(raw-size [_] (+ (count @current-batch) (.size juc-queue))))
(defmethod clojure.pprint/simple-dispatch DefermentQueue
[queue]
(clojure.pprint/pprint-logical-block :prefix "#DefermentQueue"
:suffix ""
(clojure.pprint/write-out (-> queue
(assoc :empty? (.isEmpty ^BlockingQueue (:juc-queue queue)))
(dissoc queue :juc-queue)))
""))
(defmethod print-method DefermentQueue
[^BlockingQueue queue ^java.io.Writer w]
(.write w (str "#DefermentQueue"
(-> queue
(assoc :empty? (.isEmpty ^BlockingQueue (:juc-queue queue)))
(dissoc queue :juc-queue)))))
(defn- deferment-queue
"For when the queue will hold promises -- if the computation is asynchronous,
or if the edge into this queue is both coordinated and involves some computation."
[juc-queue stack?]
(->DefermentQueue juc-queue (atom ()) (atom 0) (->queue-fns stack?)))
(defrecord BatchedQueue
[task-queue n todos guard]
GuardedQueue
(set-guard! [_ g]
(reset! guard g)
(reset! todos [])
(set-guard! task-queue g))
(ready? [_]
(or (boolean (seq @todos))
(ready? task-queue)))
(pop [this g force?]
(if force?
(when (identical? g @guard)
(locking this
(let [x (pop task-queue g true)
v @todos]
(reset! todos [])
(if x
(conj v x)
(when (not-empty v) v)))))
(pop this g)))
(pop [this g]
(when (identical? g @guard)
(when-let [x (pop task-queue g)]
(or (locking this
(let [v (swap! todos conj x)]
(when (= n (count v))
(reset! todos [])
v)))
(pop this g)))))
(push [_ g v] (when (identical? g @guard) (push task-queue g v)))
(push-deferred [_ g v] (when (identical? g @guard) (push-deferred task-queue g v)))
(push-batch [_ g v] (when (identical? g @guard) (push-batch task-queue g v)))
(push-deferred-batch [_ g v] (when (identical? g @guard) (push-deferred-batch task-queue g v)))
(peek [_] (peek task-queue))
(drain [_ g] (drain task-queue g))
(raw-size [_] (+ (min 1 (count @todos)) (raw-size task-queue))))
(defn- batch-a-queue
"For when the queue wants to stick stuff out in a batch."
[task-queue n]
(let [todos (atom [])]
(->BatchedQueue task-queue n todos (atom 0))))
[task-queue f semantics todos guard allow-force?]
GuardedQueue
(set-guard! [_ g]
(reset! guard g)
(dosync (ref-set todos []))
(set-guard! task-queue g))
(ready? [_]
(or (boolean (seq @todos)) 1
(ready? task-queue)))
(pop [this g force?]
(when (identical? g @guard)
(if (and force? allow-force?)
(if-let [x (pop task-queue g)]
(dosync
(if (and (not-empty (ensure todos))
(if (= semantics :exclusive)
(let [v (ensure todos)]
(ref-set todos [x])
v)
(let [v (ensure todos)]
(ref-set todos [])
(conj v x)))
(do (alter todos conj x)
(pop this g true))))
(dosync (let [v (ensure todos)]
(when-not (empty? v)
(ref-set todos [])
v))))
(when-let [x (pop task-queue g)]
(dosync
(if (and (not-empty (ensure todos))
(if (= semantics :exclusive)
(let [v (ensure todos)]
(ref-set todos [x])
v)
(let [v (ensure todos)]
(ref-set todos [])
(conj v x)))
(do (alter todos conj x)
(pop this g))))))))
(pop [this g] (pop this g false))
(push [_ g v] (push task-queue g v))
(push-deferred [_ g v] (push-deferred task-queue g v))
(push-batch [_ g v] (push-batch task-queue g v))
(push-deferred-batch [_ g v] (push-deferred-batch task-queue g v))
(peek [_] (peek task-queue))
(drain [_ g] (drain task-queue g))
(raw-size [_] (+ (raw-size task-queue) (count @todos))))
(defn- collecting-queue
[queue f semantics allow-force?]
(let [todos (ref [])]
(->CollectingQueue queue f semantics todos (atom 0) allow-force?)))
PriorityBlockingQueue , else a LinkedBlockingQueue .
(defn queue
false or Comparator
stack? :stack?
:or {deferred? false,
batching? false,
collecting? false,
priority-queue? false,
stack? false,
collect-inclusive? false
allow-force? true}}]
(as-> (cond (boolean priority-queue?) (PriorityBlockingQueue. *thread-capacity*
priority-queue?)
(boolean stack?) (do
(throw (IllegalArgumentException. "Stacks are not yet surfaced in decursus."))
(LinkedBlockingDeque.))
:else (LinkedBlockingQueue.))
queue
(if deferred? (deferment-queue queue stack?) (simple-queue queue stack?))
(if batching? (batch-a-queue queue batching?) queue)
(if (and collecting? (number? collecting?)) (batch-a-queue queue collecting?) queue)
(if (and collecting? (instance? clojure.lang.IFn collecting?))
(if collect-inclusive?
(collecting-queue queue collecting? :inclusive allow-force?)
(collecting-queue queue collecting? :exclusive allow-force?))
queue)))
|
6a95c73f5d46941cab94608f65a2a060998862cd1ff2aad9588da2fc4473e645 | EMSL-NMR-EPR/Haskell-MFAPipe-Executable | Strict.hs | -----------------------------------------------------------------------------
-- |
-- Module : Data.Graph.Inductive.Graph.Extras.Node.Strict
Copyright : 2016 - 17 Pacific Northwest National Laboratory
-- License : ECL-2.0 (see the LICENSE file in the distribution)
--
-- Maintainer :
-- Stability : experimental
-- Portability : portable
--
-- This module exports assorted functions and types that relate to nodes in
-- inductive graphs.
-----------------------------------------------------------------------------
module Data.Graph.Inductive.Graph.Extras.Node.Strict
( module Data.Graph.Inductive.Graph.Extras.Node
, partitionNodes
, partitionLabNodes
) where
import Data.Graph.Inductive.Graph (Graph(), LNode, Node)
import qualified Data.Graph.Inductive.Graph
import Data.Graph.Inductive.Graph.Extras.Node
import Data.Map.Strict (Map)
import qualified Data.Map.Strict
-- | Partition nodes by type.
partitionNodes :: (Graph gr) => gr a b -> Map NodeType [Node]
partitionNodes = partitionUsing Data.Graph.Inductive.Graph.nodes id
# INLINE partitionNodes #
-- | Partition labeled nodes by type.
partitionLabNodes :: (Graph gr) => gr a b -> Map NodeType [LNode a]
partitionLabNodes = partitionUsing Data.Graph.Inductive.Graph.labNodes fst
# INLINE partitionLabNodes #
-- ----------------------------------------------------------------------------
Internal
-- ----------------------------------------------------------------------------
partitionUsing :: (Functor f, Foldable f, Graph gr) => (gr a b -> f c) -> (c -> Node) -> gr a b -> Map NodeType [c]
partitionUsing elems toNode gr =
let
xs0 = elems gr
xs1 = fmap (getNodeType gr . toNode >>= (,)) xs0
in
foldr (uncurry (flip (\x -> Data.Map.Strict.alter (Just . (:) x . maybe [] id)))) Data.Map.Strict.empty xs1
| null | https://raw.githubusercontent.com/EMSL-NMR-EPR/Haskell-MFAPipe-Executable/8a7fd13202d3b6b7380af52d86e851e995a9b53e/fgl-extras/src/Data/Graph/Inductive/Graph/Extras/Node/Strict.hs | haskell | ---------------------------------------------------------------------------
|
Module : Data.Graph.Inductive.Graph.Extras.Node.Strict
License : ECL-2.0 (see the LICENSE file in the distribution)
Maintainer :
Stability : experimental
Portability : portable
This module exports assorted functions and types that relate to nodes in
inductive graphs.
---------------------------------------------------------------------------
| Partition nodes by type.
| Partition labeled nodes by type.
----------------------------------------------------------------------------
---------------------------------------------------------------------------- | Copyright : 2016 - 17 Pacific Northwest National Laboratory
module Data.Graph.Inductive.Graph.Extras.Node.Strict
( module Data.Graph.Inductive.Graph.Extras.Node
, partitionNodes
, partitionLabNodes
) where
import Data.Graph.Inductive.Graph (Graph(), LNode, Node)
import qualified Data.Graph.Inductive.Graph
import Data.Graph.Inductive.Graph.Extras.Node
import Data.Map.Strict (Map)
import qualified Data.Map.Strict
partitionNodes :: (Graph gr) => gr a b -> Map NodeType [Node]
partitionNodes = partitionUsing Data.Graph.Inductive.Graph.nodes id
# INLINE partitionNodes #
partitionLabNodes :: (Graph gr) => gr a b -> Map NodeType [LNode a]
partitionLabNodes = partitionUsing Data.Graph.Inductive.Graph.labNodes fst
# INLINE partitionLabNodes #
Internal
partitionUsing :: (Functor f, Foldable f, Graph gr) => (gr a b -> f c) -> (c -> Node) -> gr a b -> Map NodeType [c]
partitionUsing elems toNode gr =
let
xs0 = elems gr
xs1 = fmap (getNodeType gr . toNode >>= (,)) xs0
in
foldr (uncurry (flip (\x -> Data.Map.Strict.alter (Just . (:) x . maybe [] id)))) Data.Map.Strict.empty xs1
|
e6cd64f5a503862e4d7bd7675e39d6958559229790944f4e120fdfcddcc9eaaf | CloudI/CloudI | proper_tests.erl | -*- coding : utf-8 ; erlang - indent - level : 2 -*-
%%% -------------------------------------------------------------------
Copyright 2010 - 2021 < > ,
< >
and < >
%%%
This file is part of PropEr .
%%%
%%% PropEr is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
%%% (at your option) any later version.
%%%
%%% PropEr 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 PropEr. If not, see </>.
2010 - 2021 , and
%%% @version {@version}
@author
@doc This module contains PropEr 's Unit tests . You need the EUnit
%%% application to compile it.
-module(proper_tests).
deliberately contains one untyped record
-include_lib("proper/include/proper.hrl").
-include_lib("eunit/include/eunit.hrl").
%% NOTE: Possibly here temporarily until the compiler's warnings are fixed.
-export_type([my_native_type/0, type_and_fun/0, type_only/0, id/1, lof/0]).
-export_type([bin4/0, bits42/0, bits5x/0, bits7x/0, untyped/0]).
%%------------------------------------------------------------------------------
%% Helper macros
%%------------------------------------------------------------------------------
NOTE : Never add long_result to Opts for these macros .
state_is_clean() ->
get() =:= [].
assertEqualsOneOf(_X, none) ->
ok;
assertEqualsOneOf(X, List) ->
?assert(lists:any(fun(Y) -> Y =:= X end, List)).
-define(_passes(Test),
?_passes(Test, [])).
-define(_passes(Test, Opts),
?_assertRun(true, Test, Opts, true)).
-define(_errorsOut(ExpReason, Test),
?_errorsOut(ExpReason, Test, [])).
-define(_errorsOut(ExpReason, Test, Opts),
?_assertRun({error,ExpReason}, Test, Opts, true)).
-define(_assertRun(ExpResult, Test, Opts, AlsoLongResult),
?_test(begin
?assertMatch(ExpResult, proper:quickcheck(Test,Opts)),
proper:clean_garbage(),
?assert(state_is_clean()),
case AlsoLongResult of
true ->
?assertMatch(ExpResult,
proper:quickcheck(Test,[long_result|Opts])),
proper:clean_garbage(),
?assert(state_is_clean());
false ->
ok
end
end)).
-define(_assertCheck(ExpShortResult, CExm, Test),
?_assertCheck(ExpShortResult, CExm, Test, [])).
-define(_assertCheck(ExpShortResult, CExm, Test, Opts),
?_test(?assertCheck(ExpShortResult, CExm, Test, Opts))).
-define(assertCheck(ExpShortResult, CExm, Test, Opts),
begin
?assertMatch(ExpShortResult, proper:check(Test,CExm,Opts)),
?assert(state_is_clean())
end).
-define(_fails(Test),
?_fails(Test, [])).
-define(_fails(Test, Opts),
?_assertFailRun(none, Test, Opts)).
-define(_failsWith(ExpCExm, Test),
?_failsWith(ExpCExm, Test, [])).
-define(_failsWith(ExpCExm, Test, Opts),
?_assertFailRun(none, Test, Opts, ExpCExm)).
-define(_failsWithOneOf(AllCExms, Test),
?_failsWithOneOf(AllCExms, Test, [])).
-define(_failsWithOneOf(AllCExms, Test, Opts),
?_assertFailRun(AllCExms, Test, Opts)).
-define(SHRINK_TEST_OPTS, [{start_size,10},{max_shrinks,10000}]).
-define(_shrinksTo(ExpShrunk, Type),
?_assertFailRun(none, ?FORALL(_X,Type,false),
?SHRINK_TEST_OPTS, [ExpShrunk])).
-define(_shrinksToOneOf(AllShrunk, Type),
?_assertFailRun([[X] || X <- AllShrunk], ?FORALL(_X,Type,false),
?SHRINK_TEST_OPTS)).
-define(_nativeShrinksTo(ExpShrunk, TypeStr),
?_assertFailRun(none,
?FORALL(_X,assert_can_translate(?MODULE,TypeStr),false),
?SHRINK_TEST_OPTS, [ExpShrunk])).
-define(_nativeShrinksToOneOf(AllShrunk, TypeStr),
?_assertFailRun([[X] || X <- AllShrunk],
?FORALL(_X,assert_can_translate(?MODULE,TypeStr),false),
?SHRINK_TEST_OPTS)).
-define(_assertFailRun(AllCExms, Test, Opts),
?_test(begin
ShortResult = proper:quickcheck(Test, Opts),
CExm1 = get_cexm(),
?checkNoExpCExp(CExm1, AllCExms, Test, Opts),
?assertEqual(false, ShortResult),
LongResult = proper:quickcheck(Test, [long_result|Opts]),
CExm2 = get_cexm(),
?checkNoExpCExp(CExm2, AllCExms, Test, Opts),
?checkNoExpCExp(LongResult, AllCExms, Test, Opts)
end)).
-define(_assertFailRun(AllCExms, Test, Opts, ExpCExm),
?_test(begin
ShortResult = proper:quickcheck(Test, Opts),
CExm1 = get_cexm(),
?checkCExm(CExm1, AllCExms, Test, Opts, ExpCExm),
?assertEqual(false, ShortResult),
LongResult = proper:quickcheck(Test, [long_result|Opts]),
CExm2 = get_cexm(),
?checkCExm(CExm2, AllCExms, Test, Opts, ExpCExm),
?checkCExm(LongResult, AllCExms, Test, Opts, ExpCExm)
end)).
-define(_cexmMatchesWith(Pattern, Test),
?_test(begin
?assertEqual(false, proper:quickcheck(Test)),
?assertMatch(Pattern, get_cexm())
end)).
get_cexm() ->
CExm = proper:counterexample(),
proper:clean_garbage(),
?assert(state_is_clean()),
CExm.
%%
The two macros below differ in that the first one we do not know the
%% expected counterexample pattern, so there is no need to match against it.
%%
-define(checkNoExpCExp(CExm, AllCExms, Test, Opts),
begin
?assertCheck(false, CExm, Test, Opts),
assertEqualsOneOf(CExm, AllCExms)
end).
-define(checkCExm(CExm, AllCExms, Test, Opts, ExpCExm),
begin
?assertCheck(false, CExm, Test, Opts),
?assertMatch(ExpCExm, CExm),
assertEqualsOneOf(CExm, AllCExms)
end).
-define(_assertTempBecomesN(N, ExpShortResult, Prop),
?_assertTempBecomesN(N, ExpShortResult, Prop, [])).
-define(_assertTempBecomesN(N, ExpShortResult, Prop, Opts),
?_test(begin
?assertMatch(ExpShortResult, proper:quickcheck(Prop, Opts)),
?assertEqual(N, get_temp()),
erase_temp(),
proper:clean_garbage(),
?assert(state_is_clean())
end)).
%%
%% Used when we are only interested in checking that a property fails.
%%
-define(_failsChk(Test, Opts),
?_assertEqual(false, proper:quickcheck(Test, Opts))).
inc_temp() ->
inc_temp(1).
inc_temp(Inc) ->
case get(temp) of
undefined -> put(temp, Inc);
X -> put(temp, X + Inc)
end,
ok.
get_temp() ->
get(temp).
erase_temp() ->
erase(temp),
ok.
non_deterministic(Behaviour) ->
inc_temp(),
N = get_temp(),
{MustReset,Result} = get_result(N, 0, Behaviour),
case MustReset of
true -> erase_temp();
false -> ok
end,
Result.
get_result(N, Sum, [{M,Result}]) ->
{N >= Sum + M, Result};
get_result(N, Sum, [{M,Result} | Rest]) ->
NewSum = Sum + M,
case N =< NewSum of
true -> {false, Result};
false -> get_result(N, NewSum, Rest)
end.
setup_run_commands(Module, Cmds, Env) ->
Module:set_up(),
Res = proper_statem:run_commands(Module, Cmds, Env),
Module:clean_up(),
Res.
%%------------------------------------------------------------------------------
%% Helper functions
%%------------------------------------------------------------------------------
assert_type_works({Type,Are,_Target,Arent,TypeStr}, IsSimple) ->
case Type of
none ->
ok;
_ ->
lists:foreach(fun(X) -> assert_is_instance(X,Type) end, Are),
assert_can_generate(Type, IsSimple),
lists:foreach(fun(X) -> assert_not_is_instance(X,Type) end, Arent)
end,
case TypeStr of
none ->
ok;
_ ->
TransType = assert_can_translate(?MODULE, TypeStr),
lists:foreach(fun(X) -> assert_is_instance(X,TransType) end, Are),
assert_can_generate(TransType, IsSimple),
lists:foreach(fun(X) -> assert_not_is_instance(X,TransType) end,
Arent)
end.
assert_can_translate(Mod, TypeStr) ->
proper_typeserver:start(),
Type = {Mod,TypeStr},
Result1 = proper_typeserver:translate_type(Type),
Result2 = proper_typeserver:translate_type(Type),
proper_typeserver:stop(),
?assert(state_is_clean()),
{ok,Type1} = Result1,
{ok,Type2} = Result2,
?assert(proper_types:equal_types(Type1,Type2)),
Type1.
assert_cant_translate(Mod, TypeStr) ->
proper_typeserver:start(),
Result = proper_typeserver:translate_type({Mod,TypeStr}),
proper_typeserver:stop(),
?assert(state_is_clean()),
?assertMatch({error,_}, Result).
%% TODO: after fixing the type system, use generic reverse function.
assert_is_instance(X, Type) ->
?assert(proper_types:is_inst(X, Type) andalso state_is_clean()).
assert_can_generate(Type, CheckIsInstance) ->
lists:foreach(fun(Size) -> try_generate(Type,Size,CheckIsInstance) end,
[1, 2, 5, 10, 20, 40, 50]).
try_generate(Type, Size, CheckIsInstance) ->
{ok,Instance} = proper_gen:pick(Type, Size),
?assert(state_is_clean()),
case CheckIsInstance of
true -> assert_is_instance(Instance, Type);
false -> ok
end.
assert_seeded_runs_return_same_result(Type) ->
lists:foreach(fun(Size) -> try_generate_seeded(Type, Size) end,
[1, 2, 5, 10, 20, 40, 50]).
try_generate_seeded(Type, Size) ->
Seed = os:timestamp(),
{ok, Instance1} = proper_gen:pick(Type, Size, Seed),
{ok, Instance2} = proper_gen:pick(Type, Size, Seed),
?assert(Instance1 =:= Instance2).
assert_native_can_generate(Mod, TypeStr, CheckIsInstance) ->
assert_can_generate(assert_can_translate(Mod,TypeStr), CheckIsInstance).
assert_cant_generate(Type) ->
?assertEqual(error, proper_gen:pick(Type)),
?assert(state_is_clean()).
assert_cant_generate_cmds(Type, N) ->
?assertEqual(error, proper_gen:pick(?SUCHTHAT(T, Type, length(T) > N))),
?assert(state_is_clean()).
assert_not_is_instance(X, Type) ->
?assert(not proper_types:is_inst(X, Type) andalso state_is_clean()).
assert_function_type_works(FunType) ->
{ok,F} = proper_gen:pick(FunType),
%% TODO: this isn't exception-safe
?assert(proper_types:is_instance(F, FunType)),
assert_is_pure_function(F),
proper:global_state_erase(),
?assert(state_is_clean()).
assert_is_pure_function(F) ->
{arity,Arity} = erlang:fun_info(F, arity),
ArgsList = [lists:duplicate(Arity,0), lists:duplicate(Arity,1),
lists:seq(1,Arity), lists:seq(0,Arity-1)],
lists:foreach(fun(Args) -> ?assertEqual(apply(F,Args),apply(F,Args)) end,
ArgsList).
%%------------------------------------------------------------------------------
%% Unit test arguments
%%------------------------------------------------------------------------------
simple_types_with_data() ->
[{integer(), [-1,0,1,42,-200], 0, [0.3,someatom,<<1>>], "integer()"},
{integer(7,88), [7,8,87,88,23], 7, [1,90,a], "7..88"},
{integer(0,42), [0,11,42], 0, [-1,43], "0..42"},
{integer(-99,0), [-88,-99,0], 0, [1,-1112], "-99..0"},
{integer(-999,-12), [-34,-999,-12], -12, [0,5], "-999..-12"},
{integer(-99,21), [-98,0,21], 0, [-100], "-99..21"},
{integer(0,0), [0], 0, [1,-1,100,-100], "0..0"},
{pos_integer(), [12,1,444], 1, [-12,0], "pos_integer()"},
{non_neg_integer(), [42,0], 0, [-9,rr], "non_neg_integer()"},
{neg_integer(), [-222,-1], -1, [0,1111], "neg_integer()"},
{float(), [17.65,-1.12], 0.0, [11,atomm,<<>>], "float()"},
{float(7.4,88.0), [7.4,88.0], 7.4, [-1.0,3.2], none},
{float(0.0,42.1), [0.1,42.1], 0.0, [-0.1], none},
{float(-99.9,0.0), [-0.01,-90.0], 0.0, [someatom,-12,-100.0,0.1], none},
{float(-999.08,-12.12), [-12.12,-12.2], -12.12, [-1111.0,1000.0], none},
{float(-71.8,99.0), [-71.8,99.0,0.0,11.1], 0.0, [100.0,-71.9], none},
{float(0.0,0.0), [0.0], 0.0, [0.1,-0.1], none},
{non_neg_float(), [88.8,98.9,0.0], 0.0, [-12,1,-0.01], none},
{atom(), [elvis,'Another Atom',''], '', ["not_an_atom",12,12.2], "atom()"},
{binary(), [<<>>,<<12,21>>], <<>>, [<<1,2:3>>,binary_atom,42], "binary()"},
{binary(), [], <<>>, [], "<<_:_*8>>"},
{binary(3), [<<41,42,43>>], <<0,0,0>>, [<<1,2,3,4>>], "<<_:24>>"},
{binary(0), [<<>>], <<>>, [<<1>>], "<<_:0>>"},
{bitstring(), [<<>>,<<87,76,65,5:4>>], <<>>, [{12,3},11], "bitstring()"},
{bitstring(), [], <<>>, [], "<<_:_*1>>"},
{bitstring(18), [<<0,1,2:2>>,<<1,32,123:2>>], <<0,0,0:2>>, [<<12,1,1:3>>],
"<<_:18, _:_*0>>"},
{bitstring(32), [<<120,120,120,120>>], <<0,0,0,0>>, [7,8], "<<_:32>>"},
{bitstring(0), [<<>>], <<>>, [<<1>>], "<<>>"},
{list(integer()), [[],[2,42],[0,1,1,2,3,5,8,13,21,34,55,89,144]], [],
[[4,4.2],{12,1},<<12,113>>], "[integer()]"},
{list(atom()), [[on,the,third,day,'of',christmas,my,true,love,sent,to,me]],
[], [['not',1,list,'of',atoms],not_a_list], "[atom()]"},
{list(union([integer(),atom()])), [[3,french,hens,2],[turtle,doves]], [],
[{'and',1}], "[integer() | atom()]"},
{vector(5,atom()), [[partridge,in,a,pear,tree],[a,b,c,d,e]],
['','','','',''], [[a,b,c,d],[a,b,c,d,e,f]], none},
{vector(2,float()), [[0.0,1.1],[4.4,-5.5]], [0.0,0.0], [[1,1]], none},
{vector(0,integer()), [[]], [], [[1],[2]], none},
{union([good,bad,ugly]), [good,bad,ugly], good, [clint,"eastwood"],
"good | bad | ugly"},
{union([integer(),atom()]), [twenty_one,21], 0, ["21",<<21>>],
"integer() | atom()"},
{weighted_union([{10,luck},{20,skill},{15,concentrated_power_of_will},
{5,pleasure},{50,pain},{100,remember_the_name}]),
[skill,pain,pleasure], luck, [clear,20,50], none},
{{integer(0,42),list(atom())}, [{42,[a,b]},{21,[c,de,f]},{0,[]}], {0,[]},
[{-1,[a]},{12},{21,[b,c],12}], "{0..42,[atom()]}"},
{tuple(), [{a,42},{2.56,<<42>>,{a}},{},{a,{a,17},3.14,{{}}}], {},
[#{a => 17},[{}],42], "tuple()"},
{tuple([atom(),integer()]), [{the,1}], {'',0}, [{"a",0.0}],
"{atom(),integer()}"},
{{}, [{}], {}, [[],{1,2}], "{}"},
{loose_tuple(integer()), [{1,44,-1},{},{99,-99}], {}, [4,{hello,2},[1,2]],
none},
{loose_tuple(union([atom(),float()])), [{a,4.4,b},{},{'',c},{1.2,-3.4}],
{}, [an_atom,0.4,{hello,2},[aa,bb,3.1]], none},
{loose_tuple(list(integer())), [{[1,-1],[],[2,3,-12]},{}], {},
[[[1,2],[3,4]],{1,12},{[1,99,0.0],[]}], none},
{loose_tuple(loose_tuple(integer())), [{},{{}},{{1,2},{-1,11},{}}], {},
[{123},[{12},{24}]], none},
{exactly({[writing],unit,[tests,is],{2},boring}),
[{[writing],unit,[tests,is],{2},boring}],
{[writing],unit,[tests,is],{2},boring}, [no,its,'not','!'], none},
{[], [[]], [], [[a],[1,2,3]], "[]"},
{fixed_list([neg_integer(),pos_integer()]), [[-12,32],[-1,1]], [-1,1],
[[0,0]], none},
{[atom(),integer(),atom(),float()], [[forty_two,42,forty_two,42.0]],
['',0,'',0.0], [[proper,is,licensed],[under,the,gpl]], none},
{[42 | list(integer())], [[42],[42,44,22]], [42], [[],[11,12]], none},
{number(), [12,32.3,-9,-77.7], 0, [manolis,papadakis], "number()"},
{boolean(), [true,false], false, [unknown], "boolean()"},
{string(), ["hello","","world"], "", ['hello'], "string()"},
{arity(), [0,2,17,42,255], 0, [-1,256], "arity()"},
{timeout(), [0,42,infinity,666], 0, [-1,infinite,3.14], "timeout()"},
{?LAZY(integer()), [0,2,99], 0, [1.1], "integer()"},
{?LAZY(list(float())), [[0.0,1.2,1.99],[]], [], [1.1,[1,2]], "[float()]"},
{zerostream(10), [[0,0,0],[],[0,0,0,0,0,0,0]], [], [[1,0,0],[0.1]], none},
{?SHRINK(pos_integer(),[0]), [1,12,0], 0, [-1,-9,6.0], none},
{?SHRINK(float(),[integer(),atom()]), [1.0,0.0,someatom,'',42,0], 0,
[<<>>,"hello"], none},
{noshrink(?SHRINK(42,[0,1])), [42,0,1], 42, [-1], "42 | 0 | 1"},
{non_empty(list(integer())), [[1,2,3],[3,42],[11]], [0], [[],[0.1]],
"[integer(),...]"},
{default(42,float()), [4.1,-99.0,0.0,42], 42, [43,44], "42 | float()"},
{?SUCHTHAT(X,non_neg_integer(),X rem 4 =:= 1), [1,5,37,89], 1, [4,-12,11],
none},
{?SUCHTHATMAYBE(X,non_neg_integer(),X rem 4 =:= 1), [1,2,3,4,5,37,89], 0,
[1.1,2.2,-12], "non_neg_integer()"},
{?SUCHTHAT(L, non_empty(list(non_neg_integer())), hd(L) < 5),
[[1], [1,2,3,4], [0,2]], [0], [[], "Fail","something", [5]], none},
{any(), [1,-12,0,99.9,-42.2,0.0,an_atom,'',<<>>,<<1,2>>,<<1,2,3:5>>,[],
[42,<<>>],{},{tag,12},{tag,[vals,12,12.2],[],<<>>}],
0, [], "any()"},
{list(any()), [[<<>>,a,1,-42.0,{11.8,[]}]], [], [{1,aa},<<>>], "[any()]"},
{deeplist(), [[[],[]], [[[]],[]]], [], [[a]], "deeplist()"},
{none, [[234,<<1>>,[<<78>>,[]],0],[]], [], [21,3.1,[7.1],<<22>>],
"iolist()"},
{none, [[234,<<1>>,[<<78>>,[]],0],[],<<21,15>>], <<>>, [21,3.1,[7.1]],
"iodata()"}].
%% TODO: These rely on the intermediate form of the instances.
constructed_types_with_data() ->
[{?LET({A,B},{bitstring(3),binary()},<<A/bits,B/bits>>),
[{'$used',{<<1:3>>,<<3,4>>},<<32,96,4:3>>}], <<0:3>>, [],
"<<_:3,_:_*8>>"},
{?LET(X,range(1,5),X*X), [{'$used',1,1},{'$used',5,25}], 1,
[4,{'$used',3,8},{'$used',0,0}], none},
{?LET(L,non_empty(list(atom())),oneof(L)),
[{'$used',[aa],aa},{'$used',[aa,bb],aa},{'$used',[aa,bb],bb}], '',
[{'$used',[],''},{'$used',[aa,bb],cc}], none},
{?LET(X,pos_integer(),?LET(Y,range(0,X),X-Y)),
[{'$used',3,{'$used',2,1}},{'$used',9,{'$used',9,0}},
{'$used',5,{'$used',0,5}}], 1,
[{'$used',0,{'$used',0,0}},{'$used',3,{'$used',4,-1}},
{'$used',7,{'$used',6,2}}], none},
{?LET(Y,?LET(X,integer(),X*X),-Y),
[{'$used',{'$used',-9,81},-81},{'$used',{'$used',2,4},-4}], 0,
[{'$used',{'$used',1,2},-2},{'$used',{'$used',3,9},9}], none},
{?SUCHTHAT(Y,?LET(X,oneof([1,2,3]),X+X),Y>3),
[{'$used',2,4},{'$used',3,6}], 4, [{'$used',1,2}], none},
{?LET(X,?SUCHTHAT(Y,pos_integer(),Y=/=0),X*X),
[{'$used',3,9},{'$used',1,1},{'$used',11,121}], 1,
[{'$used',-1,1},{'$used',0,0}], none},
{tree(integer()), [{'$used',[null,null],{node,42,null,null}},
{'$used',[{'$used',[null,null],{node,2,null,null}},
{'$used',[null,null],{node,3,null,null}}],
{node,-1,{node,2,null,null},{node,3,null,null}}},
{'$to_part',null},
{'$to_part',{'$used',[null,null],{node,7,null,null}}}],
null, [{'$used',[null,null],{node,1.1,null,null}}], "tree(integer())"},
{?LETSHRINK(L,[],{tag,L}), [{'$used',[],{tag,[]}}], {tag,[]}, [], none},
{?LETSHRINK(L,non_empty(list(atom())),{tag,L}),
[{'$used',[aa],{tag,[aa]}},{'$to_part',aa}], '', [], none},
{a(), [aleaf, {'$used',[aleaf],{anode,aleaf,bleaf}},
{'$used',[aleaf],{anode,aleaf,{'$to_part',bleaf}}}],
aleaf, [], "a()"},
{b(), [bleaf, {'$used',[bleaf],{bnode,aleaf,bleaf}},
{'$used',[bleaf],{bnode,{'$to_part',aleaf},bleaf}}],
bleaf, [], "b()"},
{gen_tree(integer()),
[{'$used',[null,null],{12,[null,null]}},{'$to_part',null}],
null, [{'$used',[],{42,[]}}], "gen_tree(integer())"},
{none, [{'$used',[],{tag,[]}}, {'$used',[null,null],{tag,[null,null]}},
{'$used',[{'$used',[],{tag,[]}},{'$to_part',null}],
{tag,[{tag,[]},null]}}, {'$to_part',{'$used',[],{tag,[]}}}],
null, [], "g()"},
{none, [{'$used',[null],{tag,[{ok,null}]}}, {'$to_part',null},
{'$used',[null,null],{tag,[{ok,null},{ok,null}]}}],
null, [], "h()"},
{none, [{'$used',[null,null,{'$used',[null],{tag,null,[]}}],
{tag,null,[null,{tag,null,[]}]}}, {'$to_part',null}],
null, [], "i()"},
{none, [{'$used',[{'$to_part',null},{'$used',[null],{one,null}},null,null],
{tag,null,{one,null},[null,null],[null]}}], null, [], "j()"},
{none, [{tag,[]}, {tag,[{null,null}]},
{tag,[{{tag,[]},null},{null,{tag,[]}}]}],
null, [{'$to_part',null}], "k()"},
{none, [{'$used',[null,null,{'$used',[null,null],{tag,null,[null]}}],
{tag,null,[null,{tag,null,[null]}]}}, {'$to_part',null}],
null, [{'$used',[null],{tag,null,[]}}], "l()"},
{utf8(), [{'$used',{'$used',0,[]},<<>>}, {'$used',{'$used',1,[0]},<<0>>},
{'$used',{'$used',1,[127]},<<127>>},
{'$used',{'$used',1,[353]},<<197,161>>}],
<<>>, [{'$used',{'$used',1,[128]},<<128>>}], none},
{utf8(0), [{'$used',{'$used',0,[]},<<>>}], <<>>, [], none},
{utf8(1), [{'$used',{'$used',0,[]},<<>>},
{'$used',{'$used',1,[127]},<<127>>},
{'$used',{'$used',1,[353]},<<197,161>>}], <<>>, [], none},
{utf8(2), [{'$used',{'$used',1,[353]},<<197,161>>},
{'$used',{'$used',2,[127,353]},<<127,197,161>>}],
<<>>, [], none},
{utf8(inf, 1), [{'$used',{'$used',0,[]},<<>>},
{'$used',{'$used',1,[0]},<<0>>},
{'$used',{'$used',2,[0,0]},<<0,0>>},
{'$used',{'$used',3,[0,0,0]},<<0,0,0>>}], <<>>, [], none},
{utf8(inf, 2), [{'$used',{'$used',3,[0,0,0]},<<0,0,0>>},
{'$used',{'$used',1,[353]},<<197,161>>}],
<<>>, [], none}].
function_types() ->
[{function([],atom()), "fun(() -> atom())"},
{function([integer(),integer()],atom()),
"fun((integer(),integer()) -> atom())"},
{function(5,union([a,b])), "fun((_,_,_,_,_) -> a | b)"},
{function(0,function(1,integer())),
"fun(() -> fun((_) -> integer()))"}].
remote_native_types() ->
[{types_test1,["#rec1{}","rec1()","exp1()","type1()","type2(atom())",
"rem1()","rem2()","types_test1:exp1()",
"types_test2:exp1(float())","types_test2:exp2()"]},
{types_test2,["exp1(#rec1{})","exp2()","#rec1{}","types_test1:exp1()",
"types_test2:exp1(binary())","types_test2:exp2()"]}].
impossible_types() ->
[?SUCHTHAT(X, pos_integer(), X =< 0),
?SUCHTHAT(X, non_neg_integer(), X < 0),
?SUCHTHAT(X, neg_integer(), X >= 0),
?SUCHTHAT(X, integer(1,10), X > 20),
?SUCHTHAT(X, float(0.0,10.0), X < 0.0),
?SUCHTHAT(L, vector(12,integer()), length(L) =/= 12),
?SUCHTHAT(B, binary(), lists:member(256,binary_to_list(B))),
?SUCHTHAT(X, exactly('Lelouch'), X =:= 'vi Brittania'),
?SUCHTHAT(X, utf8(), unicode:characters_to_list(X) =:= [16#D800]),
?SUCHTHAT(X, utf8(1, 1), size(X) > 1),
%% Nested constraints, of which the inner one fails
?SUCHTHAT(X, ?SUCHTHAT(Y, pos_integer(), Y < 0), X > 0),
%% Nested constraints, of which the outer one fails
?SUCHTHAT(X, ?SUCHTHAT(Y, pos_integer(), Y > 0), X < 0),
Nested constraints , one strict and one non - strict , where the
%% inner one fails
?SUCHTHATMAYBE(_X, ?SUCHTHAT(Y, pos_integer(), Y < 0), true),
Nested constraints , one strict and one non - strict , where the
%% outer one fails
?SUCHTHAT(X, ?SUCHTHATMAYBE(Y, pos_integer(), Y < 0), X < 0),
Two failing constraints within a ? LET macro , where both
%% constraints are used as a 'raw type'
?LET({X,Y}, {?SUCHTHAT(X1, pos_integer(), X1 < 0),
?SUCHTHAT(Y1, pos_integer(), Y1 < 0)}, {X,Y})
].
impossible_native_types() ->
[{types_test1, ["1.1","no_such_module:type1()","no_such_type()"]},
{types_test2, ["types_test1:type1()","function()","fun((...) -> atom())",
"pid()","port()","ref()"]}].
recursive_native_types() ->
[{rec_test1, ["a()","b()","a()|b()","d()","f()","deeplist()",
"mylist(float())","aa()","bb()","expc()"]},
{rec_test2, ["a()","expa()","rec()"]}].
impossible_recursive_native_types() ->
[{rec_test1, ["c()","e()","cc()","#rec{}","expb()"]},
{rec_test2, ["b()","#rec{}","aa()"]}].
symb_calls() ->
[{[3,2,1], "lists:reverse([1,2,3])", [], {call,lists,reverse,[[1,2,3]]}},
{[a,b,c,d], "erlang:'++'([a,b],[c,d])",
[{a,some_value}], {call,erlang,'++',[[a,b],[c,d]]}},
{42, "erlang:'*'(erlang:'+'(3,3),erlang:'-'(8,1))",
[{b,dummy_value},{e,another_dummy}],
{call,erlang,'*',[{call,erlang,'+',[3,3]},{call,erlang,'-',[8,1]}]}},
{something, "something",
[{a,somebody},{b,put},{c,something},{d,in_my_drink}], {var,c}},
{{var,b}, "{var,b}", [{a,not_this},{c,neither_this}], {var,b}},
{42, "erlang:'+'(40,2)", [{m,40},{n,2}],
{call,erlang,'+',[{var,m},{var,n}]}},
{[i,am,{var,iron},man],
"erlang:'++'(lists:reverse([am,i]),erlang:'++'([{var,iron}],[man]))",
[{a,man},{b,woman}],
{call,erlang,'++',[{call,lists,reverse,[[am,i]]},
{call,erlang,'++',[[{var,iron}],[{var,a}]]}]}}].
undefined_symb_calls() ->
[{call,erlang,error,[an_error]},
{call,erlang,throw,[a_throw]},
{call,erlang,exit,[an_exit]},
{call,lists,reverse,[<<12,13>>]},
{call,erlang,'+',[1,2,3]}].
combinations() ->
[{[{1,[1,3,5,7,9,10]}, {2,[2,4,6,8,11]}], 5, 11, [1,2,3,4,5,6,7,8,9,10,11], 2, 2,
[{1,[1,3,5,7,8,11]}, {2,[2,4,6,9,10]}]},
{[{1,[1,3,5]}, {2,[7,8,9]}, {3,[2,4,6]}], 3, 9, [1,3,5,7,8,9], 3, 2,
[{1,[6,8,9]}, {2,[1,3,5]}, {3,[2,4,7]}]}].
first_comb() ->
[{10,3,3,[{1,[7,8,9,10]}, {2,[4,5,6]}, {3,[1,2,3]}]},
{11,5,2,[{1,[6,7,8,9,10,11]}, {2,[1,2,3,4,5]}]},
{12,3,4,[{1,[10,11,12]}, {2,[7,8,9]}, {3,[4,5,6]}, {4,[1,2,3]}]}].
lists_to_zip() ->
[{[],[],[]},
{[], [dummy, atom], []},
{[1, 42, 1, 42, 1, 2 ,3], [], []},
{[a, b, c], lists:seq(1,6), [{a,1}, {b,2}, {c,3}]},
{[a, b, c], lists:seq(1,3), [{a,1}, {b,2}, {c,3}]},
{[a, d, d, d, d], lists:seq(1,3), [{a,1}, {d,2}, {d,3}]}].
command_names() ->
[{[{set,{var,1},{call,erlang,put,[a,0]}},
{set,{var,3},{call,erlang,erase,[a]}},
{set,{var,4},{call,erlang,get,[b]}}],
[{erlang,put,2},
{erlang,erase,1},
{erlang,get,1}]},
{[{set,{var,1},{call,foo,bar,[]}},
{set,{var,2},{call,bar,foo,[a,{var,1}]}},
{set,{var,3},{call,bar,foo,[a,[[3,4]]]}}],
[{foo,bar,0},
{bar,foo,2},
{bar,foo,2}]},
{[],[]}].
valid_command_sequences() ->
%% {module, initial_state, command_sequence, symbolic_state_after,
%% dynamic_state_after,initial_environment}
[{pdict_statem, [], [{init,[]},
{set,{var,1},{call,erlang,put,[a,0]}},
{set,{var,2},{call,erlang,put,[b,1]}},
{set,{var,3},{call,erlang,erase,[a]}},
{set,{var,4},{call,erlang,get,[b]}},
{set,{var,5},{call,erlang,erase,[b]}},
{set,{var,6},{call,erlang,put,[a,4]}},
{set,{var,7},{call,erlang,put,[a,42]}}],
[{a,42}], [{a,42}], []},
{pdict_statem, [], [{init,[]},
{set,{var,1},{call,erlang,put,[b,5]}},
{set,{var,2},{call,erlang,erase,[b]}},
{set,{var,3},{call,erlang,put,[a,5]}}],
[{a,5}], [{a,5}], []},
{pdict_statem, [], [{init,[]},
{set,{var,1},{call,erlang,put,[a,{var,start_value}]}},
{set,{var,2},{call,erlang,put,[b,{var,another_start_value}]}},
{set,{var,3},{call,erlang,get,[b]}},
{set,{var,4},{call,erlang,get,[b]}}],
[{b,{var,another_start_value}}, {a,{var,start_value}}], [{b,-1}, {a, 0}],
[{start_value, 0}, {another_start_value, -1}]}].
symbolic_init_invalid_sequences() ->
%% {module, command_sequence, environment, shrunk}
[{pdict_statem, [{init,[{a,{call,foo,bar,[some_arg]}}]},
{set,{var,1},{call,erlang,put,[b,42]}},
{set,{var,2},{call,erlang,get,[b]}}],
[{some_arg, 0}],
[{init,[{a,{call,foo,bar,[some_arg]}}]}]}].
invalid_precondition() ->
%% {module, command_sequence, environment, shrunk}
[{pdict_statem, [{init,[]},
{set,{var,1},{call,erlang,put,[a,0]}},
{set,{var,2},{call,erlang,put,[b,1]}},
{set,{var,3},{call,erlang,erase,[a]}},
{set,{var,4},{call,erlang,get,[a]}}],
[], [{set,{var,4},{call,erlang,get,[a]}}]}].
invalid_var() ->
[{pdict_statem, [{init,[]},
{set,{var,2},{call,erlang,put,[b,{var,1}]}}]},
{pdict_statem, [{init,[]},
{set,{var,1},{call,erlang,put,[b,9]}},
{set,{var,5},{call,erlang,put,[a,3]}},
{set,{var,6},{call,erlang,get,[{var,2}]}}]}].
arguments_not_defined() ->
[{[simple,atoms,are,valid,{var,42}], []},
{[{var,1}], [{var,2},{var,3},{var,4}]},
{[hello,world,[hello,world,{var,6}]], []},
{[{1,2,3,{var,1},{var,2}},not_really], []},
{[[[[42,{var,42}]]]], []},
{[{43,41,{1,{var,42}}},why_not], []}].
all_data() ->
[1, 42.0, "$hello", "world\n", [smelly, cat, {smells,bad}],
'$this_should_be_copied', '$this_one_too', 'but$ this$ not',
or_this].
dollar_data() ->
['$this_should_be_copied', '$this_one_too'].
%%------------------------------------------------------------------------------
%% Unit tests
%%------------------------------------------------------------------------------
TODO : write tests for old datatypes , use old tests
TODO : check output redirection , quiet , verbose , to_file , on_output/2 ( maybe
%% by writing to a string in the process dictionary), statistics printing,
%% standard verbose behaviour
%% TODO: fix compiler warnings
TODO : LET and LETSHRINK testing ( these need their intermediate form for
%% standalone instance testing and shrinking) - update needed after
%% fixing the internal shrinking in LETs, use recursive datatypes, like
trees , for testing , also test with noshrink and LAZY
TODO : use size=100 for is_instance testing ?
TODO : : check that the same type is returned for consecutive calls ,
%% even with no caching (no_caching option?)
TODO : : recursive types containing functions
TODO : ? LET , ? LETSHRINK : only the top - level base type can be a native type
TODO : Test with native types : ? , noshrink , ? LAZY , ? SHRINK ,
%% resize, ?SIZED
%% TODO: no debug_info at compile time => call, not type
%% no debug_info at runtime => won't find type
%% no module in code path at runtime => won't find type
%% TODO: try some more expressions with a ?FORALL underneath
%% TODO: various constructors like '|' (+ record notation) are parser-rejected
%% TODO: test nonempty recursive lists
%% TODO: test list-recursive with instances
TODO : more ADT tests : check bad declarations , bad variable use , multi - clause ,
is_subtype , unacceptable range , unexported opaque , no - specs opaque ,
%% unexported/unspecced functions, unbound variables, check as constructed
%% TODO: module, check_spec, check_module_specs, retest_spec (long result mode
%% too, other options pass)
%% TODO: proper_typeserver:is_instance (with existing types too, plus types we
%% can't produce, such as impropers) (also check that everything we
%% produce based on a type is an instance)
%% TODO: check that functions that throw exceptions pass
%% TODO: property inside a ?TIMEOUT returning false
%% TODO: some branch of a ?FORALL has a collect while another doesn't
%% TODO: symbolic functions returning functions are evaluated?
%% TODO: pure_check
%% TODO: spec_timeout option
%% TODO: defined option precedence
TODO : conversion of maybe_improper_list
%% TODO: debug option to output tests passed, fail reason, etc.
%% TODO: test expected distribution of random functions
simple_types_test_() ->
[?_test(assert_type_works(TD, true)) || TD <- simple_types_with_data()].
constructed_types_test_() ->
[?_test(assert_type_works(TD, false))
|| TD <- constructed_types_with_data()].
%% TODO: specific test-starting instances would be useful here
%% (start from valid Xs)
shrinks_to_test_() ->
All = simple_types_with_data() ++ constructed_types_with_data(),
[?_shrinksTo(Target, Type)
|| {Type,_Xs,Target,_Ys,_TypeStr} <- All, Type =/= none].
native_shrinks_to_test_() ->
All = simple_types_with_data() ++ constructed_types_with_data(),
[?_nativeShrinksTo(Target, TypeStr)
|| {_Type,_Xs,Target,_Ys,TypeStr} <- All, TypeStr =/= none].
cant_generate_test_() ->
[?_test(assert_cant_generate(Type)) || Type <- impossible_types()].
proper_exported_types_test_() ->
[?_assertEqual({[],12}, proper_exported_types_test:not_handled())].
%%------------------------------------------------------------------------------
%% Verify that failing constraints are correctly reported
%%------------------------------------------------------------------------------
cant_generate_constraints_test_() ->
[%% An impossible generator specified in the same function
?_errorsOut({cant_generate, [{?MODULE, cant_generate_constraints_test_, 0}]},
?FORALL(_, ?SUCHTHAT(X, pos_integer(), X =< 0), true)),
%% An impossible generator specified in a separate function
?_errorsOut({cant_generate, [{?MODULE, impossible, 0}]},
?FORALL(_X, impossible(), true)),
%% An impossible generator in presence of multiple constraints
?_errorsOut({cant_generate, [{?MODULE, possible, 0},
{?MODULE, possible_made_impossible, 0}]},
?FORALL(_X, possible_made_impossible(), true)),
%% An impossible generator in presence of multiple, duplicated constraints
?_errorsOut({cant_generate, [{?MODULE, possible, 0},
{?MODULE, possible_made_impossible_2, 0}]},
?FORALL(_X, possible_made_impossible_2(), true))
].
possible() ->
?SUCHTHAT(X, pos_integer(), X > 0).
impossible() ->
?SUCHTHAT(X, pos_integer(), X =< 0).
possible_made_impossible() ->
?SUCHTHAT(X, possible(), X =< 0).
possible_made_impossible_2() ->
?SUCHTHAT(Y, ?SUCHTHAT(X, possible(), X =< 0), Y =< 0).
%%------------------------------------------------------------------------------
native_cant_translate_test_() ->
[?_test(assert_cant_translate(Mod,TypeStr))
|| {Mod,Strings} <- impossible_native_types(), TypeStr <- Strings].
remote_native_types_test_() ->
[?_test(assert_can_translate(Mod,TypeStr))
|| {Mod,Strings} <- remote_native_types(), TypeStr <- Strings].
recursive_native_types_test_() ->
[?_test(assert_native_can_generate(Mod,TypeStr,false))
|| {Mod,Strings} <- recursive_native_types(), TypeStr <- Strings].
recursive_native_cant_translate_test_() ->
[?_test(assert_cant_translate(Mod,TypeStr))
|| {Mod,Strings} <- impossible_recursive_native_types(),
TypeStr <- Strings].
random_functions_test_() ->
[[?_test(assert_function_type_works(FunType)),
?_test(assert_function_type_works(assert_can_translate(proper,TypeStr)))]
|| {FunType,TypeStr} <- function_types()].
parse_transform_test_() ->
[?_passes(auto_export_test1:prop_1()),
?_assertError(undef, auto_export_test2:prop_1()),
?_assertError(undef, no_native_parse_test:prop_1()),
?_passes(let_tests:prop_1()),
?_failsWith([3*42], let_tests:prop_2())].
native_type_props_test_() ->
[?_passes(?FORALL({X,Y}, {my_native_type(),my_proper_type()},
is_integer(X) andalso is_atom(Y))),
?_passes(?FORALL([X,Y,Z],
[my_native_type(),my_proper_type(),my_native_type()],
is_integer(X) andalso is_atom(Y) andalso is_integer(Z))),
?_passes(?FORALL([Y,X,{Z,W}],
[my_proper_type() | [my_native_type()]] ++
[{my_native_type(),my_proper_type()}],
is_integer(X) andalso is_atom(Y) andalso is_integer(Z)
andalso is_atom(W))),
?_passes(?FORALL([X|Y], [my_native_type()|my_native_type()],
is_integer(X) andalso is_integer(Y))),
?_passes(?FORALL(X, type_and_fun(), is_atom(X))),
?_passes(?FORALL(X, type_only(), is_integer(X))),
?_passes(?FORALL(L, [integer()], length(L) =:= 1)),
?_fails(?FORALL(L, id([integer()]), length(L) =:= 1)),
?_passes(?FORALL(_, types_test1:exp1(), true)),
?_assertError(undef, ?FORALL(_,types_test1:rec1(),true)),
?_assertError(undef, ?FORALL(_,no_such_module:some_call(),true)),
{setup, fun() -> code:purge(to_remove),
code:delete(to_remove),
code:purge(to_remove),
file:rename("tests/to_remove.beam",
"tests/to_remove.bak") end,
fun(_) -> file:rename("tests/to_remove.bak",
"tests/to_remove.beam") end,
?_passes(?FORALL(_, to_remove:exp1(), true))},
?_passes(rec_props_test1:prop_1()),
?_passes(rec_props_test2:prop_2()),
?_passes(?FORALL(L, vector(2,my_native_type()),
length(L) =:= 2
andalso lists:all(fun erlang:is_integer/1, L))),
?_passes(?FORALL(F, function(0,my_native_type()), is_integer(F()))),
?_passes(?FORALL(X, union([my_proper_type(),my_native_type()]),
is_integer(X) orelse is_atom(X))),
?_assertError(undef, begin
Vector5 = fun(T) -> vector(5,T) end,
?FORALL(V, Vector5(types_test1:exp1()),
length(V) =:= 5)
end),
?_passes(?FORALL(X, ?SUCHTHAT(Y,types_test1:exp1(),is_atom(Y)),
is_atom(X))),
?_passes(?FORALL(L,non_empty(lof()),length(L) > 0)),
?_passes(?FORALL(X, ?LET(L,lof(),lists:min([99999.9|L])),
is_float(X))),
?_shrinksTo(0, ?LETSHRINK([X],[my_native_type()],{'tag',X})),
{"Shrinking tuples",
[{"All elements are generators",
[?_shrinksTo({0,0}, proper_types:tuple([proper_types:integer(), proper_types:integer()])),
?_shrinksTo({0,0}, {proper_types:integer(), proper_types:integer()})]},
{"Some elements are generators",
[?_shrinksTo({0,0}, proper_types:tuple([proper_types:integer(), 0])),
?_shrinksTo({0,2}, proper_types:tuple([proper_types:integer(), 2])),
?_shrinksTo({0,0}, {proper_types:integer(), 0}),
?_shrinksTo({0,2}, {proper_types:integer(), 2})]},
{"All elements are consts",
[?_shrinksTo({3,2}, proper_types:tuple([3, 2])),
?_shrinksTo({3,2}, {3, 2})]}]},
{"Shrinking fixed lists",
[{"All elements are generators",
[?_shrinksTo([0,0], proper_types:fixed_list([proper_types:integer(), proper_types:integer()])),
?_shrinksTo([0,0], [proper_types:integer(), proper_types:integer()]),
?_shrinksTo([0|0], [proper_types:integer()|proper_types:integer()])]},
{"Some elements are generators",
[?_shrinksTo([0,0], proper_types:fixed_list([proper_types:integer(), 0])),
?_shrinksTo([0,2], proper_types:fixed_list([proper_types:integer(), 2])),
?_shrinksTo([0|2], proper_types:fixed_list([proper_types:integer()|2])),
?_shrinksTo([0,0], [proper_types:integer(), 0]),
?_shrinksTo([0,2], [proper_types:integer(), 2]),
?_shrinksTo([12,42], [12,42|list(integer())])]},
{"All elements are consts",
[?_shrinksTo([3|2], proper_types:fixed_list([3|2])),
?_shrinksTo([3,2], proper_types:fixed_list([3, 2])),
?_shrinksTo([3,2], [3, 2])]}]},
?_passes(weird_types:prop_export_all_works()),
?_passes(weird_types:prop_no_auto_import_works()),
?_passes(?FORALL(B, utf8(), unicode:characters_to_binary(B) =:= B)),
?_passes(?FORALL(B, utf8(1), length(unicode:characters_to_list(B)) =< 1)),
?_passes(?FORALL(B, utf8(1, 1), size(B) =< 1)),
?_passes(?FORALL(B, utf8(2, 1), size(B) =< 2)),
?_passes(?FORALL(B, utf8(4), size(B) =< 16)),
?_passes(?FORALL(B, utf8(),
length(unicode:characters_to_list(B)) =< size(B)))
].
-type bin4() :: <<_:32>>.
-type bits42() :: <<_:42>>.
-type bits5x() :: <<_:_*5>>.
-type bits7x() :: <<_:_*7>>.
-record(untyped, {a, b = 12}).
-type untyped() :: #untyped{}.
true_props_test_() ->
[?_passes(?FORALL(X,integer(),X < X + 1)),
?_passes(?FORALL(A,atom(),list_to_atom(atom_to_list(A)) =:= A)),
?_passes(?FORALL(B,bin4(),byte_size(B) =:= 4)),
?_passes(?FORALL(B,bits42(),bit_size(B) =:= 42)),
?_passes(?FORALL(B,bits5x(),bit_size(B) =/= 42)),
?_passes(?FORALL(B,bits7x(),bit_size(B) rem 7 =:= 0)),
?_passes(?FORALL(L,list(integer()),is_sorted(L,quicksort(L)))),
?_passes(?FORALL(L,ulist(integer()),is_sorted(L,lists:usort(L)))),
?_passes(?FORALL(L,non_empty(list(integer())),L =/= [])),
?_passes(?FORALL({I,L}, {integer(),list(integer())},
?IMPLIES(no_duplicates(L),
not lists:member(I,lists:delete(I,L))))),
?_passes(?FORALL(L, ?SIZED(Size,resize(Size div 5,list(integer()))),
length(L) =< 20), [{max_size,100}]),
%% TODO: check that the samples are collected correctly
?_passes(?FORALL(L, list(integer()),
collect(length(L), collect(L =:= [],
lists:reverse(lists:reverse(L)) =:= L)))),
?_passes(?FORALL(L, list(integer()),
aggregate(smaller_lengths_than_my_own(L), true))),
?_assertTempBecomesN(300, true,
numtests(300,?FORALL(_,1,begin inc_temp(),true end))),
?_assertTempBecomesN(30, true, ?FORALL(X, ?SIZED(Size,Size),
begin inc_temp(X),true end),
[{numtests,12},{max_size,4}]),
?_assertTempBecomesN(12, true,
?FORALL(X, ?SIZED(Size,Size),
begin inc_temp(X),true end),
[{numtests,3},{start_size,4},{max_size,4}]),
?_assertTempBecomesN(30, true,
?FORALL_TARGETED(X, ?USERNF(?SIZED(Size,Size),
fun (_, _) -> ?SIZED(Size, Size) end),
begin inc_temp(X),true end),
[{numtests,12},{max_size,4}]),
?_assertTempBecomesN(12, true,
?FORALL_TARGETED(X, ?USERNF(?SIZED(Size,Size),
fun (_, _) -> ?SIZED(Size, Size) end),
begin inc_temp(X),true end),
[{numtests,3},{start_size,4},{max_size,4}]),
?_passes(?FORALL(X, integer(), ?IMPLIES(abs(X) > 1, X * X > X))),
?_passes(?FORALL(X, integer(), ?IMPLIES(X >= 0, true))),
?_passes(?FORALL({X,Lim}, {int(),?SIZED(Size,Size)}, abs(X) =< Lim)),
?_passes(?FORALL({X,Lim}, {nat(),?SIZED(Size,Size)}, X =< Lim)),
?_passes(?FORALL(L, orderedlist(integer()), is_sorted(L))),
?_passes(conjunction([
{one, ?FORALL(_, integer(), true)},
{two, ?FORALL(X, integer(), collect(X > 0, true))},
{three, conjunction([{a,true},{b,true}])}
])),
?_passes(?FORALL(X, untyped(), is_record(X, untyped))),
?_passes(fun_tests:prop_fun_bool())].
true_stateful_test_() ->
[?_passes(improper_lists_statem:prop_simple()),
?_passes(symb_statem:prop_simple()),
?_passes(symb_statem_maps:prop_simple()),
?_passes(more_commands_test:prop_commands_passes(), [{numtests,42}]),
{timeout, 10, ?_passes(ets_statem_test:prop_ets())},
{timeout, 20, ?_passes(ets_statem_test:prop_parallel_ets())},
{timeout, 20, ?_passes(pdict_fsm:prop_pdict())},
{timeout, 20, ?_passes(symb_statem:prop_parallel_simple())},
{timeout, 20, ?_passes(symb_statem_maps:prop_parallel_simple())},
{timeout, 42, ?_passes(targeted_statem:prop_random(), [{numtests,500}])},
{timeout, 42, ?_passes(targeted_fsm:prop_random(), [{numtests,500}])}].
false_props_test_() ->
[?_failsWith([[Same,Same]],
?FORALL(L,list(integer()),is_sorted(L,lists:usort(L)))),
?_failsWith([[Same2,Same2],Same2],
?FORALL(L, non_empty(list(union([a,b,c,d]))),
?FORALL(X, elements(L),
not lists:member(X,lists:delete(X,L))))),
?_failsWith(['\000\000\000\000'],
?FORALL(A, atom(), length(atom_to_list(A)) < 4)),
%% TODO: check that these only run once
?_failsWith([1], ?FORALL(X, non_neg_integer(),
case X > 0 of
true -> throw(not_zero);
false -> true
end)),
?_fails(?FORALL(_, 1, lists:min([]) > 0)),
?_failsWith([[12,42]], ?FORALL(L, [12,42|list(integer())],
case lists:member(42, L) of
true -> erlang:exit(you_got_it);
false -> true
end)),
TODO : Check that the following two tests shrink properly on _ N
?_cexmMatchesWith([{_,_N}], fun_tests:prop_fun_int_int()),
?_cexmMatchesWith([{_,_,[_N]}], fun_tests:prop_lists_map_filter()),
?_fails(?FORALL(_, integer(), ?TIMEOUT(100,timer:sleep(150) =:= ok))),
?_failsWith([20], ?FORALL(X, pos_integer(), ?TRAPEXIT(creator(X) =:= ok))),
?_assertTempBecomesN(7, false,
?FORALL(X, ?SIZED(Size,integer(Size,Size)),
begin inc_temp(), X < 5 end),
[{numtests,5}, {max_size,5}]),
it runs 2 more times : one while shrinking ( recursing into the property )
%% and one when the minimal input is rechecked
?_assertTempBecomesN(2, false,
?FORALL(L, list(atom()),
?WHENFAIL(inc_temp(), length(L) < 5))),
?_assertTempBecomesN(3, false,
?FORALL(S, ?SIZED(Size,Size),
begin inc_temp(), S =< 20 end),
[{numtests,3},{max_size,40},noshrink]),
?_failsWithOneOf([[{true,false}],[{false,true}]],
?FORALL({B1,B2}, {boolean(),boolean()}, equals(B1,B2))),
?_failsWith([2,1],
?FORALL(X, integer(1,10), ?FORALL(Y, integer(1,10), X =< Y))),
?_failsWith([1,2],
?FORALL(Y, integer(1,10), ?FORALL(X, integer(1,10), X =< Y))),
?_failsWithOneOf([[[0,1]],[[0,-1]],[[1,0]],[[-1,0]]],
?FORALL(L, list(integer()), lists:reverse(L) =:= L)),
?_failsWith([[1,2,3,4,5,6,7,8,9,10]],
?FORALL(_L, shuffle(lists:seq(1,10)), false)),
%% TODO: check that these don't shrink
?_fails(?FORALL(_, integer(0,0), false)),
?_fails(?FORALL(_, float(0.0,0.0), false)),
?_fails(fails(?FORALL(_, integer(), false))),
?_failsWith([16], ?FORALL(X, ?LET(Y,integer(),Y*Y), X < 15)),
?_failsWith([0.0],
?FORALL(_, ?LETSHRINK([A,B], [float(),atom()], {A,B}), false)),
?_failsWith([], conjunction([{some,true},{thing,false}])),
?_failsWith([{2,1},[{group,[[{sub_group,[1]}]]},{stupid,[1]}]],
?FORALL({X,Y}, {pos_integer(),pos_integer()},
conjunction([
{add_next, ?IMPLIES(X > Y, X + 1 > Y)},
{symmetry,
conjunction([
{add_sym, collect(X+Y, X+Y =:= Y+X)},
{sub_sym,
?WHENFAIL(io:format("'-' isn't symmetric!~n",[]),
X-Y =:= Y-X)}
])},
{group,
conjunction([
{add_group,
?WHENFAIL(io:format("This shouldn't happen!~n",[]),
?FORALL(Z, pos_integer(),
(X+Y)+Z =:= X+(Y+Z)))},
{sub_group,
?WHENFAIL(io:format("'-' doesn't group!~n",[]),
?FORALL(W, pos_integer(),
(X-Y)-W =:= X-(Y-W)))}
])},
{stupid, ?FORALL(_, pos_integer(), throw(woot))}
]))),
?_failsWith([[a,a,a,a,a]], shrinking_gotchas:prop_shrink_list_same_elem()),
?_fails(more_commands_test:prop_more_commands_fails(), [{numtests,42}]),
?_failsWith([500], targeted_shrinking_test:prop_int()),
?_failsWith([500], targeted_shrinking_test:prop_let_int()),
?_failsWith([500], targeted_shrinking_test:prop_int_shrink_outer()),
?_failsWith([500], targeted_shrinking_test:prop_int_shrink_inner()),
{timeout, 20, ?_fails(ets_counter:prop_ets_counter())},
?_fails(post_false:prop_simple())].
false_stateful_test_() ->
Opts = [{numtests,1000}],
[{timeout, 42, ?_fails(targeted_statem:prop_targeted(), Opts)},
{timeout, 42, ?_fails(targeted_statem:prop_targeted_init(), Opts)},
{timeout, 42, ?_fails(targeted_fsm:prop_targeted(), Opts)},
{timeout, 42, ?_fails(targeted_fsm:prop_targeted_init(), Opts)}].
exception_props_test_() ->
[?_fails(error_statem:prop_simple())].
error_props_test_() ->
[?_errorsOut({cant_generate,[{?MODULE,error_props_test_,0}]},
?FORALL(_, ?SUCHTHAT(X, pos_integer(), X =< 0), true)),
?_errorsOut(cant_satisfy,
?FORALL(X, pos_integer(), ?IMPLIES(X =< 0, true))),
?_errorsOut(type_mismatch,
?FORALL({X,Y}, [integer(),integer()], X < Y)),
?_assertCheck({error,rejected}, [2],
?FORALL(X, integer(), ?IMPLIES(X > 5, X < 6))),
?_assertCheck({error,too_many_instances}, [1,ab],
?FORALL(X, pos_integer(), X < 0)),
?_errorsOut({cant_generate,[{proper_statem,commands_gen,4}]},
prec_false:prop_simple()),
?_errorsOut({cant_generate,[{nogen_statem,impossible_arg,0}]},
nogen_statem:prop_simple()),
?_errorsOut(non_boolean_result, ?FORALL(_, integer(), not_a_boolean)),
?_errorsOut(non_boolean_result,
?FORALL(_, ?SHRINK(42,[0]),
non_deterministic([{2,false},{1,not_a_boolean}]))),
?_assertRun(false,
?FORALL(_, ?SHRINK(42,[0]),
non_deterministic([{4,false},{1,true}])),
[], false),
?_assertRun(false,
?FORALL(_, ?SHRINK(42,[0]),
non_deterministic([{3,false},{1,true},{1,false}])),
[], false),
?_assertRun(false,
?FORALL(_, ?LAZY(non_deterministic([{1,1},{1,2},{1,3},{1,4}])),
false), [], false)].
eval_test_() ->
[?_assertEqual(Result, eval(Vars,SymbCall))
|| {Result,_Repr,Vars,SymbCall} <- symb_calls()].
pretty_print_test_() ->
[?_assert(equal_ignoring_ws(Repr, proper_symb:pretty_print(Vars,SymbCall)))
|| {_Result,Repr,Vars,SymbCall} <- symb_calls()].
not_defined_test_() ->
[?_assertNot(defined(SymbCall))
|| SymbCall <- undefined_symb_calls()].
options_test_() ->
[?_assertEqual({error,{erroneous_option,{numtests,0}}},
proper:module(command_props, [{numtests,0}])),
?_assertEqual({error,{unrecognized_option,gazonk}},
proper:quickcheck(rec_props_test1:prop_1(), [42,gazonk])),
?_assertTempBecomesN(300, true,
?FORALL(_, 1, begin inc_temp(), true end),
[{numtests,300}]),
?_assertTempBecomesN(300, true,
?FORALL(_, 1, begin inc_temp(), true end),
[300]),
?_failsWith([42], ?FORALL(T, any(), T < 42),
[any_to_integer,verbose,nocolors]),
?_failsWith([42], ?FORALL(I, integer(), I < 42),
[{numtests,4711}, {on_output,fun print_in_magenta/2}]),
?_failsWith([42], ?FORALL(_, ?SHRINK(42,[0,1]), false), [noshrink]),
?_failsWith([42], ?FORALL(_, ?SHRINK(42,[0,1]), false), [{max_shrinks,0}]),
?_fails(?FORALL(_, integer(), false), [fails]),
?_assertRun({error,{cant_generate,[{?MODULE,options_test_,0}]}},
?FORALL(_, ?SUCHTHAT(X, pos_integer(), X > 42), true),
[{constraint_tries,1}], true),
?_failsWith([12],
?FORALL(_, ?SIZED(Size, integer(Size, Size)), false),
[{start_size,12}])].
print_in_magenta(S, L) ->
io:format("\033[1;35m"++S++"\033[0m", L).
setup_prop() ->
?SETUP(fun () ->
put(setup_token, true),
fun () ->
erase(setup_token),
ok
end
end,
?FORALL(_, exactly(ok), get(setup_token))).
failing_setup_prop() ->
?SETUP(fun () ->
put(setup_token, true),
fun () ->
erase(setup_token),
ok
end
end,
?FORALL(_, exactly(ok), not get(setup_token))).
double_setup_prop() ->
?SETUP(fun () ->
put(setup_token2, true),
fun () ->
erase(setup_token2),
ok
end
end,
?SETUP(fun () ->
put(setup_token, true),
fun () ->
erase(setup_token),
ok
end
end,
?FORALL(_, exactly(ok),
get(setup_token) andalso get(setup_token2)))).
setup_test_() ->
[?_passes(setup_prop(), [10]),
?_assert(proper:quickcheck(setup_prop(), 10)
andalso undefined =:= get(setup_token)),
?_fails(failing_setup_prop(), [10]),
?_assert(not proper:quickcheck(failing_setup_prop(), [10, noshrink, quiet])
andalso undefined =:= get(setup_token)),
?_assert(proper:check(setup_prop(), [ok], 10)),
?_assert(proper:check(setup_prop(), [ok], 10)
andalso undefined =:= get(setup_token)),
?_assert(not proper:check(failing_setup_prop(), [ok], 10)),
?_assert(not proper:check(failing_setup_prop(), [ok], 10)
andalso undefined =:= get(setup_token)),
?_passes(double_setup_prop(), [10]),
?_assert(proper:quickcheck(double_setup_prop(), 10)
andalso undefined =:= get(setup_token)
andalso undefined =:= get(setup_token2)),
?_assert(proper:check(double_setup_prop(), [ok], 10)),
?_assert(true = proper:check(double_setup_prop(), [ok], 10)
andalso undefined =:= get(setup_token)
andalso undefined =:= get(setup_token2))].
adts1_test_() ->
for ' old laptop
?_passes(?FORALL({X,S},{integer(),sets:set(integer())},
sets:is_element(X,sets:add_element(X,S))), [20])}.
adts2_test_() ->
for 18.x ( and onwards ? )
?_passes(?FORALL({X,Y,D},
{integer(),float(),dict:dict(integer(),float())},
dict:fetch(X,dict:store(X,Y,eval(D))) =:= Y), [30])}.
adts3_test_() ->
{timeout, 60,
?_fails(?FORALL({X,D},
{boolean(),dict:dict(boolean(),integer())},
dict:erase(X, dict:store(X,42,D)) =:= D))}.
parameter_test_() ->
?_passes(?FORALL(List, [zero1(),zero2(),zero3(),zero4()],
begin
[?assertEqual(undefined, proper_types:parameter(P))
|| P <- [x1,x2,y2,x3,y3,x4,y4,v,w,z]],
lists:all(fun is_zero/1, List)
end)).
parameter_targeted_test_() ->
BaseType = ?LAZY(proper_types:parameter(param)),
UserNF = ?USERNF(BaseType, fun (_, _) -> BaseType end),
Type = proper_types:with_parameter(param, 1, UserNF),
?_passes(?FORALL_TARGETED(X, Type, X =:= 1)).
zip_test_() ->
[?_assertEqual(proper_statem:zip(X, Y), Expected)
|| {X,Y,Expected} <- lists_to_zip()].
command_names_test_() ->
[?_assertEqual(proper_statem:command_names(Cmds), Expected)
|| {Cmds,Expected} <- command_names()].
command_names_parallel1_test_() ->
[?_assertEqual(proper_statem:command_names({Cmds,[]}), Expected)
|| {Cmds,Expected} <- command_names()].
command_names_parallel2_test_() ->
[?_assertEqual(proper_statem:command_names({[],[Cmds]}), Expected)
|| {Cmds,Expected} <- command_names()].
command_names_parallel3_test_() ->
[?_assertEqual(proper_statem:command_names({Cmds,[Cmds]}), Expected++Expected)
|| {Cmds,Expected} <- command_names()].
command_names_parallel4_test_() ->
[?_assertEqual(proper_statem:command_names({Cmds,[Cmds,Cmds]}), Expected++Expected++Expected)
|| {Cmds,Expected} <- command_names()].
valid_cmds_test_() ->
[?_assert(proper_statem:is_valid(Mod, State, Cmds, Env))
|| {Mod,State,Cmds,_,_,Env} <- valid_command_sequences()].
invalid_cmds_test_() ->
[?_assertNot(proper_statem:is_valid(Mod, Mod:initial_state(), Cmds, []))
|| {Mod,Cmds,_,_} <- invalid_precondition()] ++
[?_assertNot(proper_statem:is_valid(Mod, Mod:initial_state(), Cmds, []))
|| {Mod,Cmds} <- invalid_var()].
state_after_test_() ->
[?_assertEqual(proper_statem:state_after(Mod, Cmds), StateAfter)
|| {Mod,_,Cmds,StateAfter,_,_} <- valid_command_sequences()].
cannot_generate_commands_test_() ->
[?_test(assert_cant_generate_cmds(proper_statem:commands(Mod), 6))
|| Mod <- [prec_false]].
can_generate_commands0_test_() ->
[?_test(assert_can_generate(proper_statem:commands(Mod), false))
|| Mod <- [pdict_statem]].
can_generate_commands1_test_() ->
[?_test(assert_can_generate(proper_statem:commands(Mod, StartState), false))
|| {Mod,StartState} <- [{pdict_statem,[{a,1},{b,1},{c,100}]}]].
can_generate_parallel_commands0_test_() ->
{timeout, 20,
[?_test(assert_can_generate(proper_statem:parallel_commands(Mod), false))
|| Mod <- [ets_counter]]}.
can_generate_parallel_commands1_test_() ->
{timeout, 20,
[?_test(assert_can_generate(
proper_statem:parallel_commands(Mod, Mod:initial_state()),
false))
|| Mod <- [ets_counter]]}.
seeded_runs_return_same_result_test_() ->
[?_test(assert_seeded_runs_return_same_result(proper_statem:commands(Mod)))
|| Mod <- [pdict_statem]].
run_valid_commands_test_() ->
[?_assertMatch({_H,DynState,ok}, setup_run_commands(Mod, Cmds, Env))
|| {Mod,_,Cmds,_,DynState,Env} <- valid_command_sequences()].
run_init_error_test_() ->
[?_assertMatch({_H,_S,initialization_error},
setup_run_commands(Mod, Cmds, Env))
|| {Mod,Cmds,Env,_Shrunk} <- symbolic_init_invalid_sequences()].
run_precondition_false_test_() ->
[?_assertMatch({_H,_S,{precondition,false}},
setup_run_commands(Mod, Cmds, Env))
|| {Mod,Cmds,Env,_Shrunk} <- invalid_precondition()].
run_postcondition_false_test_() ->
Mod = post_false,
Cmds = [{set,{var,1},{call,Mod,foo,[]}},
{set,{var,2},{call,Mod,bar,[]}},
{set,{var,3},{call,Mod,foo,[]}},
{set,{var,4},{call,Mod,bar,[]}},
{set,{var,5},{call,Mod,bar,[]}},
{set,{var,6},{call,Mod,foo,[]}}],
State = {state,5}, PostF = {postcondition,false},
[?_assertMatch({_H1,State,PostF}, run_commands(Mod, Cmds))].
run_statem_exceptions_test_() ->
Mod = error_statem,
Cmds = [{set,{var,1},{call,Mod,foo,[42]}}],
State = {state,0},
[?_assertMatch({_H,State,{exception,throw,badarg,_}},
run_commands(Mod, Cmds))].
get_next_test_() ->
[?_assertEqual(Expected,
proper_statem:get_next(L, Len, MaxIndex, Available, W, N))
|| {L, Len, MaxIndex, Available, W, N, Expected} <- combinations()].
mk_first_comb_test_() ->
[?_assertEqual(Expected, proper_statem:mk_first_comb(N, Len, W))
|| {N, Len, W, Expected} <- first_comb()].
args_not_defined_test() ->
[?_assertNot(proper_statem:args_defined(Args, SymbEnv))
|| {Args, SymbEnv} <- arguments_not_defined()].
command_props_test_() ->
{timeout, 150, [?_assertEqual([], proper:module(command_props))]}.
%% TODO: is_instance check fails because of ?LET in fsm_commands/1?
can_generate_fsm_commands_test_() ->
[?_test(assert_can_generate(proper_fsm:commands(Mod), false))
|| Mod <- [pdict_fsm, numbers_fsm]].
transition_target_test_() ->
{timeout, 20, [?_assertEqual([], proper:module(numbers_fsm))]}.
dollar_only_cp_test_() ->
?_assertEqual(
dollar_data(),
[K || K <- all_data(),
is_atom(K),
re:run(atom_to_list(K), ["^[$]"], [{capture,none}]) =:= match]).
sampleshrink_test_() ->
Gen = non_empty(?LET({N,Lst}, {range(0,5),list(a)}, lists:sublist(Lst, N))),
[{"Test type with restrain",
[{"Try another way to call shrinking (not sampleshrink)",
?_shrinksTo([a], Gen)},
?_test(proper_gen:sampleshrink(Gen))]}].
%%------------------------------------------------------------------------------
%% Performance tests
%%------------------------------------------------------------------------------
max_size_test() ->
%% issue a call to load the test module and ensure that the test exists
?assert(lists:member({prop_identity,0},
perf_max_size:module_info(exports))),
run some tests with a small and a big max_size option
{Ts,true} = timer:tc(fun() -> max_size_test_aux(42) end),
{Tb,true} = timer:tc(fun() -> max_size_test_aux(16#ffffffff) end),
ensure that the test with the big max_size option does not take
%% much longer than the small one to complete
?assert(2*Ts >= Tb).
max_size_test_aux(Size) ->
proper:quickcheck(perf_max_size:prop_identity(), [5,{max_size,Size}]).
%%------------------------------------------------------------------------------
Erlang abstract code tests
%%------------------------------------------------------------------------------
erlang_abstract_code_test_() ->
M = erlang_abstract_code_test,
Props = [bits, expr, guard, term, module],
Opts = [{numtests, 200}, noshrink],
{timeout, 42,
[?_assertEqual(true, proper:quickcheck(M:Prop(), Opts)) || Prop <- Props]}.
%%------------------------------------------------------------------------------
%% Helper predicates
%%------------------------------------------------------------------------------
no_duplicates(L) ->
length(lists:usort(L)) =:= length(L).
is_sorted([]) -> true;
is_sorted([_]) -> true;
is_sorted([A | [B|_] = T]) when A =< B -> is_sorted(T);
is_sorted(_) -> false.
same_elements(L1, L2) ->
length(L1) =:= length(L2) andalso same_elems(L1, L2).
same_elems([], []) ->
true;
same_elems([H|T], L) ->
lists:member(H, L) andalso same_elems(T, lists:delete(H, L));
same_elems(_, _) ->
false.
is_sorted(Old, New) ->
same_elements(Old, New) andalso is_sorted(New).
equal_ignoring_ws(Str1, Str2) ->
WhiteSpace = [32,9,10],
equal_ignoring_chars(Str1, Str2, WhiteSpace).
equal_ignoring_chars([], [], _Ignore) ->
true;
equal_ignoring_chars([Ch1|Rest1], [Ch2|Rest2], Ignore) when Ch1 =:= Ch2 ->
equal_ignoring_chars(Rest1, Rest2, Ignore);
equal_ignoring_chars([Ch1|Rest1] = Str1, [Ch2|Rest2] = Str2, Ignore) ->
case lists:member(Ch1, Ignore) of
true ->
equal_ignoring_chars(Rest1, Str2, Ignore);
false ->
case lists:member(Ch2, Ignore) of
true ->
equal_ignoring_chars(Str1, Rest2, Ignore);
false ->
false
end
end.
smaller_lengths_than_my_own(L) ->
lists:seq(0, length(L)).
is_zero(X) -> X =:= 0.
%%------------------------------------------------------------------------------
%% Functions to test
%%------------------------------------------------------------------------------
partition(Pivot, List) ->
partition_tr(Pivot, List, [], []).
partition_tr(_Pivot, [], Lower, Higher) ->
{Lower, Higher};
partition_tr(Pivot, [H|T], Lower, Higher) ->
case H =< Pivot of
true -> partition_tr(Pivot, T, [H|Lower], Higher);
false -> partition_tr(Pivot, T, Lower, [H|Higher])
end.
quicksort([]) -> [];
quicksort([H|T]) ->
{Lower, Higher} = partition(H, T),
quicksort(Lower) ++ [H] ++ quicksort(Higher).
creator(X) ->
Self = self(),
spawn_link(fun() -> destroyer(X,Self) end),
receive
_ -> ok
end.
destroyer(X, Father) ->
case X < 20 of
true -> Father ! not_yet;
false -> exit(this_is_the_end)
end.
%%------------------------------------------------------------------------------
Datatypes to test
%%------------------------------------------------------------------------------
%% TODO: remove this if you make 'shuffle' a default constructor
shuffle([]) ->
[];
shuffle(L) ->
?LET(X, elements(L), [X | shuffle(lists:delete(X,L))]).
ulist(ElemType) ->
?LET(L, list(ElemType), L--(L--lists:usort(L))).
zerostream(ExpectedMeanLen) ->
?LAZY(frequency([
{1, []},
{ExpectedMeanLen, [0 | zerostream(ExpectedMeanLen)]}
])).
-type my_native_type() :: integer().
my_proper_type() -> atom().
-type type_and_fun() :: integer().
type_and_fun() -> atom().
-type type_only() :: integer().
-type id(X) :: X.
-type lof() :: [float()].
-type deeplist() :: [deeplist()].
deeplist() ->
?SIZED(Size, deeplist(Size)).
deeplist(0) ->
[];
deeplist(Size) ->
?LAZY(proper_types:distlist(Size, fun deeplist/1, false)).
-type tree(T) :: 'null' | {'node',T,tree(T),tree(T)}.
tree(ElemType) ->
?SIZED(Size, tree(ElemType,Size)).
tree(_ElemType, 0) ->
null;
tree(ElemType, Size) ->
LeftTree = tree(ElemType, Size div 2),
RightTree = tree(ElemType, Size div 2),
frequency([
{1, tree(ElemType,0)},
{5, ?LETSHRINK([L,R], [LeftTree,RightTree], {node,ElemType,L,R})}
]).
-type a() :: 'aleaf' | {'anode',a(),b()}.
-type b() :: 'bleaf' | {'bnode',a(),b()}.
a() ->
?SIZED(Size, a(Size)).
a(0) ->
aleaf;
a(Size) ->
union([
?LAZY(a(0)),
?LAZY(?LETSHRINK([A], [a(Size div 2)], {anode,A,b(Size)}))
]).
b() ->
?SIZED(Size, b(Size)).
b(0) ->
bleaf;
b(Size) ->
union([
?LAZY(b(0)),
?LAZY(?LETSHRINK([B], [b(Size div 2)], {bnode,a(Size),B}))
]).
-type gen_tree(T) :: 'null' | {T,[gen_tree(T),...]}.
gen_tree(ElemType) ->
?SIZED(Size, gen_tree(ElemType,Size)).
gen_tree(_ElemType, 0) ->
null;
gen_tree(ElemType, Size) ->
SubGen = fun(S) -> gen_tree(ElemType,S) end,
oneof([
?LAZY(gen_tree(ElemType,0)),
?LAZY(?LETSHRINK(Children, proper_types:distlist(Size, SubGen, true),
{ElemType,Children}))
]).
-type g() :: 'null' | {'tag',[g()]}.
-type h() :: 'null' | {'tag',[{'ok',h()}]}.
-type i() :: 'null' | {'tag',i(),[i()]}.
-type j() :: 'null' | {'one',j()} | {'tag',j(),j(),[j()],[j()]}.
-type k() :: 'null' | {'tag',[{k(),k()}]}.
-type l() :: 'null' | {'tag',l(),[l(),...]}.
zero1() ->
proper_types:with_parameter(
x1, 0, ?SUCHTHAT(I, range(-1, 1), I =:= proper_types:parameter(x1))).
zero2() ->
proper_types:with_parameters(
[{x2,41}],
?LET(X,
proper_types:with_parameter(
y2, 43,
?SUCHTHAT(
I, range(41, 43),
I > proper_types:parameter(x2)
andalso I < proper_types:parameter(y2))),
X - 42)).
zero3() ->
?SUCHTHAT(I, range(-1, 1),
I > proper_types:parameter(x3, -1)
andalso I < proper_types:parameter(y3, 1)).
zero4() ->
proper_types:with_parameters(
[{x4,-2}, {y4,2}],
proper_types:with_parameters(
[{x4,-1}, {y4,1}],
?SUCHTHAT(I, range(-1, 1),
I > proper_types:parameter(x4)
andalso I < proper_types:parameter(y4)))).
%%------------------------------------------------------------------------------
%% Old Tests and datatypes
%%------------------------------------------------------------------------------
% nelist(ElemType) ->
% [ElemType | list(ElemType)].
%
% uvector(0, _ElemType) ->
% [];
% uvector(N, ElemType) ->
% ?LET(Rest,
% uvector(N-1, ElemType),
% ?LET(Elem,
? , ElemType , not lists : member(E , Rest ) ) ,
% [Elem | Rest])).
%
% subset(Generators) ->
? ,
% [{boolean(),G} || G <- Generators],
% [G || {true,G} <- Keep]).
%
% unique(ElemTypes) ->
% ?LET(Values,
% list(ElemTypes),
% lists:usort(Values)).
%
% ulist2(ElemType) ->
? SUCHTHAT(L , list(ElemType ) , no_duplicates(L ) ) .
%
kvlist(KeyType , ValueType ) - >
% ?LET(Keys,
% list(KeyType),
[ { K , ValueType } || K < - Keys ] ) .
%
% tree_member(_X, {node,_X,_L,_R}) -> true;
% tree_member(X, {node,_Y,L,R}) -> tree_member(X, L) orelse tree_member(X, R);
% tree_member(_X, {empty}) -> false.
%
symbdict(KeyType , ValueType ) - >
? SIZED(Size , symbdict(Size , KeyType , ValueType ) ) .
%
symbdict(0 , _ KeyType , _ ValueType ) - >
% {call,dict,new,[]};
symbdict(Size , KeyType , ValueType ) - >
% ?LAZY(
% frequency([
{ 1,symbdict(0 , KeyType , ValueType ) } ,
{ 4,?LETSHRINK([Smaller ] , [ symbdict(Size - 1 , KeyType , ValueType ) ] ,
{ call , dict , append,[KeyType , ValueType , Smaller ] } ) }
% ])
% ).
%
% test(15) ->
% ?FORALL(T,
? ,
% non_empty(list(integer())),
% ?LET(Y,
% elements(L),
% {Y,L})),
erlang : element(1,T ) = /= 42 ) ;
% test(18) ->
? FORALL(L , kvlist(atom(),integer ( ) ) , not lists : ) ) ;
% test(19) ->
% ?FORALL(T, tree(integer()), not tree_member(42, T));
% test(20) ->
% ?FORALL(X,
? , non_empty(list(integer ( ) ) ) , list(oneof(L ) ) ) ,
length(X ) < 10 ) ;
% test(27) ->
% ?FORALL(SD,
% symbdict(integer(),integer()),
not dict : is_key(42 , eval(SD ) ) ) ;
% test(29) ->
? , L } ,
% {function(1,integer(1,100)), list(integer())},
lists : all(fun(X ) - > F(X ) = /= 42 end , L ) ) ;
correct_smaller_length_aggregation(Tests , ) - >
{ Zeros , Larger } = lists : partition(fun(X ) - > X = : = 0 end , ) ,
% length(Zeros) =:= Tests
andalso correct_smaller_length_aggregation(Tests , Larger , 1 ) .
%
correct_smaller_length_aggregation(0 , SmallerLens , _
% SmallerLens =:= [];
correct_smaller_length_aggregation(NotMoreThan , SmallerLens , ) - >
{ Lens , Larger } = lists : partition(fun(X ) - > X = : = , ) ,
% Num = length(Lens),
% Num =< NotMoreThan
% andalso correct_smaller_length_aggregation(Num, Larger, Len+1).
| null | https://raw.githubusercontent.com/CloudI/CloudI/c47b4f94525dfaf7c33328c2e50f8611c11a9565/src/external/proper/test/proper_tests.erl | erlang | -------------------------------------------------------------------
PropEr is free software: you can redistribute it and/or modify
(at your option) any later version.
PropEr 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 PropEr. If not, see </>.
@version {@version}
application to compile it.
NOTE: Possibly here temporarily until the compiler's warnings are fixed.
------------------------------------------------------------------------------
Helper macros
------------------------------------------------------------------------------
expected counterexample pattern, so there is no need to match against it.
Used when we are only interested in checking that a property fails.
------------------------------------------------------------------------------
Helper functions
------------------------------------------------------------------------------
TODO: after fixing the type system, use generic reverse function.
TODO: this isn't exception-safe
------------------------------------------------------------------------------
Unit test arguments
------------------------------------------------------------------------------
TODO: These rely on the intermediate form of the instances.
Nested constraints, of which the inner one fails
Nested constraints, of which the outer one fails
inner one fails
outer one fails
constraints are used as a 'raw type'
{module, initial_state, command_sequence, symbolic_state_after,
dynamic_state_after,initial_environment}
{module, command_sequence, environment, shrunk}
{module, command_sequence, environment, shrunk}
------------------------------------------------------------------------------
Unit tests
------------------------------------------------------------------------------
by writing to a string in the process dictionary), statistics printing,
standard verbose behaviour
TODO: fix compiler warnings
standalone instance testing and shrinking) - update needed after
fixing the internal shrinking in LETs, use recursive datatypes, like
even with no caching (no_caching option?)
resize, ?SIZED
TODO: no debug_info at compile time => call, not type
no debug_info at runtime => won't find type
no module in code path at runtime => won't find type
TODO: try some more expressions with a ?FORALL underneath
TODO: various constructors like '|' (+ record notation) are parser-rejected
TODO: test nonempty recursive lists
TODO: test list-recursive with instances
unexported/unspecced functions, unbound variables, check as constructed
TODO: module, check_spec, check_module_specs, retest_spec (long result mode
too, other options pass)
TODO: proper_typeserver:is_instance (with existing types too, plus types we
can't produce, such as impropers) (also check that everything we
produce based on a type is an instance)
TODO: check that functions that throw exceptions pass
TODO: property inside a ?TIMEOUT returning false
TODO: some branch of a ?FORALL has a collect while another doesn't
TODO: symbolic functions returning functions are evaluated?
TODO: pure_check
TODO: spec_timeout option
TODO: defined option precedence
TODO: debug option to output tests passed, fail reason, etc.
TODO: test expected distribution of random functions
TODO: specific test-starting instances would be useful here
(start from valid Xs)
------------------------------------------------------------------------------
Verify that failing constraints are correctly reported
------------------------------------------------------------------------------
An impossible generator specified in the same function
An impossible generator specified in a separate function
An impossible generator in presence of multiple constraints
An impossible generator in presence of multiple, duplicated constraints
------------------------------------------------------------------------------
TODO: check that the samples are collected correctly
TODO: check that these only run once
and one when the minimal input is rechecked
TODO: check that these don't shrink
TODO: is_instance check fails because of ?LET in fsm_commands/1?
------------------------------------------------------------------------------
Performance tests
------------------------------------------------------------------------------
issue a call to load the test module and ensure that the test exists
much longer than the small one to complete
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Helper predicates
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Functions to test
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
TODO: remove this if you make 'shuffle' a default constructor
------------------------------------------------------------------------------
Old Tests and datatypes
------------------------------------------------------------------------------
nelist(ElemType) ->
[ElemType | list(ElemType)].
uvector(0, _ElemType) ->
[];
uvector(N, ElemType) ->
?LET(Rest,
uvector(N-1, ElemType),
?LET(Elem,
[Elem | Rest])).
subset(Generators) ->
[{boolean(),G} || G <- Generators],
[G || {true,G} <- Keep]).
unique(ElemTypes) ->
?LET(Values,
list(ElemTypes),
lists:usort(Values)).
ulist2(ElemType) ->
?LET(Keys,
list(KeyType),
tree_member(_X, {node,_X,_L,_R}) -> true;
tree_member(X, {node,_Y,L,R}) -> tree_member(X, L) orelse tree_member(X, R);
tree_member(_X, {empty}) -> false.
{call,dict,new,[]};
?LAZY(
frequency([
])
).
test(15) ->
?FORALL(T,
non_empty(list(integer())),
?LET(Y,
elements(L),
{Y,L})),
test(18) ->
test(19) ->
?FORALL(T, tree(integer()), not tree_member(42, T));
test(20) ->
?FORALL(X,
test(27) ->
?FORALL(SD,
symbdict(integer(),integer()),
test(29) ->
{function(1,integer(1,100)), list(integer())},
length(Zeros) =:= Tests
SmallerLens =:= [];
Num = length(Lens),
Num =< NotMoreThan
andalso correct_smaller_length_aggregation(Num, Larger, Len+1). | -*- coding : utf-8 ; erlang - indent - level : 2 -*-
Copyright 2010 - 2021 < > ,
< >
and < >
This file is part of PropEr .
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
2010 - 2021 , and
@author
@doc This module contains PropEr 's Unit tests . You need the EUnit
-module(proper_tests).
deliberately contains one untyped record
-include_lib("proper/include/proper.hrl").
-include_lib("eunit/include/eunit.hrl").
-export_type([my_native_type/0, type_and_fun/0, type_only/0, id/1, lof/0]).
-export_type([bin4/0, bits42/0, bits5x/0, bits7x/0, untyped/0]).
NOTE : Never add long_result to Opts for these macros .
state_is_clean() ->
get() =:= [].
assertEqualsOneOf(_X, none) ->
ok;
assertEqualsOneOf(X, List) ->
?assert(lists:any(fun(Y) -> Y =:= X end, List)).
-define(_passes(Test),
?_passes(Test, [])).
-define(_passes(Test, Opts),
?_assertRun(true, Test, Opts, true)).
-define(_errorsOut(ExpReason, Test),
?_errorsOut(ExpReason, Test, [])).
-define(_errorsOut(ExpReason, Test, Opts),
?_assertRun({error,ExpReason}, Test, Opts, true)).
-define(_assertRun(ExpResult, Test, Opts, AlsoLongResult),
?_test(begin
?assertMatch(ExpResult, proper:quickcheck(Test,Opts)),
proper:clean_garbage(),
?assert(state_is_clean()),
case AlsoLongResult of
true ->
?assertMatch(ExpResult,
proper:quickcheck(Test,[long_result|Opts])),
proper:clean_garbage(),
?assert(state_is_clean());
false ->
ok
end
end)).
-define(_assertCheck(ExpShortResult, CExm, Test),
?_assertCheck(ExpShortResult, CExm, Test, [])).
-define(_assertCheck(ExpShortResult, CExm, Test, Opts),
?_test(?assertCheck(ExpShortResult, CExm, Test, Opts))).
-define(assertCheck(ExpShortResult, CExm, Test, Opts),
begin
?assertMatch(ExpShortResult, proper:check(Test,CExm,Opts)),
?assert(state_is_clean())
end).
-define(_fails(Test),
?_fails(Test, [])).
-define(_fails(Test, Opts),
?_assertFailRun(none, Test, Opts)).
-define(_failsWith(ExpCExm, Test),
?_failsWith(ExpCExm, Test, [])).
-define(_failsWith(ExpCExm, Test, Opts),
?_assertFailRun(none, Test, Opts, ExpCExm)).
-define(_failsWithOneOf(AllCExms, Test),
?_failsWithOneOf(AllCExms, Test, [])).
-define(_failsWithOneOf(AllCExms, Test, Opts),
?_assertFailRun(AllCExms, Test, Opts)).
-define(SHRINK_TEST_OPTS, [{start_size,10},{max_shrinks,10000}]).
-define(_shrinksTo(ExpShrunk, Type),
?_assertFailRun(none, ?FORALL(_X,Type,false),
?SHRINK_TEST_OPTS, [ExpShrunk])).
-define(_shrinksToOneOf(AllShrunk, Type),
?_assertFailRun([[X] || X <- AllShrunk], ?FORALL(_X,Type,false),
?SHRINK_TEST_OPTS)).
-define(_nativeShrinksTo(ExpShrunk, TypeStr),
?_assertFailRun(none,
?FORALL(_X,assert_can_translate(?MODULE,TypeStr),false),
?SHRINK_TEST_OPTS, [ExpShrunk])).
-define(_nativeShrinksToOneOf(AllShrunk, TypeStr),
?_assertFailRun([[X] || X <- AllShrunk],
?FORALL(_X,assert_can_translate(?MODULE,TypeStr),false),
?SHRINK_TEST_OPTS)).
-define(_assertFailRun(AllCExms, Test, Opts),
?_test(begin
ShortResult = proper:quickcheck(Test, Opts),
CExm1 = get_cexm(),
?checkNoExpCExp(CExm1, AllCExms, Test, Opts),
?assertEqual(false, ShortResult),
LongResult = proper:quickcheck(Test, [long_result|Opts]),
CExm2 = get_cexm(),
?checkNoExpCExp(CExm2, AllCExms, Test, Opts),
?checkNoExpCExp(LongResult, AllCExms, Test, Opts)
end)).
-define(_assertFailRun(AllCExms, Test, Opts, ExpCExm),
?_test(begin
ShortResult = proper:quickcheck(Test, Opts),
CExm1 = get_cexm(),
?checkCExm(CExm1, AllCExms, Test, Opts, ExpCExm),
?assertEqual(false, ShortResult),
LongResult = proper:quickcheck(Test, [long_result|Opts]),
CExm2 = get_cexm(),
?checkCExm(CExm2, AllCExms, Test, Opts, ExpCExm),
?checkCExm(LongResult, AllCExms, Test, Opts, ExpCExm)
end)).
-define(_cexmMatchesWith(Pattern, Test),
?_test(begin
?assertEqual(false, proper:quickcheck(Test)),
?assertMatch(Pattern, get_cexm())
end)).
get_cexm() ->
CExm = proper:counterexample(),
proper:clean_garbage(),
?assert(state_is_clean()),
CExm.
The two macros below differ in that the first one we do not know the
-define(checkNoExpCExp(CExm, AllCExms, Test, Opts),
begin
?assertCheck(false, CExm, Test, Opts),
assertEqualsOneOf(CExm, AllCExms)
end).
-define(checkCExm(CExm, AllCExms, Test, Opts, ExpCExm),
begin
?assertCheck(false, CExm, Test, Opts),
?assertMatch(ExpCExm, CExm),
assertEqualsOneOf(CExm, AllCExms)
end).
-define(_assertTempBecomesN(N, ExpShortResult, Prop),
?_assertTempBecomesN(N, ExpShortResult, Prop, [])).
-define(_assertTempBecomesN(N, ExpShortResult, Prop, Opts),
?_test(begin
?assertMatch(ExpShortResult, proper:quickcheck(Prop, Opts)),
?assertEqual(N, get_temp()),
erase_temp(),
proper:clean_garbage(),
?assert(state_is_clean())
end)).
-define(_failsChk(Test, Opts),
?_assertEqual(false, proper:quickcheck(Test, Opts))).
inc_temp() ->
inc_temp(1).
inc_temp(Inc) ->
case get(temp) of
undefined -> put(temp, Inc);
X -> put(temp, X + Inc)
end,
ok.
get_temp() ->
get(temp).
erase_temp() ->
erase(temp),
ok.
non_deterministic(Behaviour) ->
inc_temp(),
N = get_temp(),
{MustReset,Result} = get_result(N, 0, Behaviour),
case MustReset of
true -> erase_temp();
false -> ok
end,
Result.
get_result(N, Sum, [{M,Result}]) ->
{N >= Sum + M, Result};
get_result(N, Sum, [{M,Result} | Rest]) ->
NewSum = Sum + M,
case N =< NewSum of
true -> {false, Result};
false -> get_result(N, NewSum, Rest)
end.
setup_run_commands(Module, Cmds, Env) ->
Module:set_up(),
Res = proper_statem:run_commands(Module, Cmds, Env),
Module:clean_up(),
Res.
assert_type_works({Type,Are,_Target,Arent,TypeStr}, IsSimple) ->
case Type of
none ->
ok;
_ ->
lists:foreach(fun(X) -> assert_is_instance(X,Type) end, Are),
assert_can_generate(Type, IsSimple),
lists:foreach(fun(X) -> assert_not_is_instance(X,Type) end, Arent)
end,
case TypeStr of
none ->
ok;
_ ->
TransType = assert_can_translate(?MODULE, TypeStr),
lists:foreach(fun(X) -> assert_is_instance(X,TransType) end, Are),
assert_can_generate(TransType, IsSimple),
lists:foreach(fun(X) -> assert_not_is_instance(X,TransType) end,
Arent)
end.
assert_can_translate(Mod, TypeStr) ->
proper_typeserver:start(),
Type = {Mod,TypeStr},
Result1 = proper_typeserver:translate_type(Type),
Result2 = proper_typeserver:translate_type(Type),
proper_typeserver:stop(),
?assert(state_is_clean()),
{ok,Type1} = Result1,
{ok,Type2} = Result2,
?assert(proper_types:equal_types(Type1,Type2)),
Type1.
assert_cant_translate(Mod, TypeStr) ->
proper_typeserver:start(),
Result = proper_typeserver:translate_type({Mod,TypeStr}),
proper_typeserver:stop(),
?assert(state_is_clean()),
?assertMatch({error,_}, Result).
assert_is_instance(X, Type) ->
?assert(proper_types:is_inst(X, Type) andalso state_is_clean()).
assert_can_generate(Type, CheckIsInstance) ->
lists:foreach(fun(Size) -> try_generate(Type,Size,CheckIsInstance) end,
[1, 2, 5, 10, 20, 40, 50]).
try_generate(Type, Size, CheckIsInstance) ->
{ok,Instance} = proper_gen:pick(Type, Size),
?assert(state_is_clean()),
case CheckIsInstance of
true -> assert_is_instance(Instance, Type);
false -> ok
end.
assert_seeded_runs_return_same_result(Type) ->
lists:foreach(fun(Size) -> try_generate_seeded(Type, Size) end,
[1, 2, 5, 10, 20, 40, 50]).
try_generate_seeded(Type, Size) ->
Seed = os:timestamp(),
{ok, Instance1} = proper_gen:pick(Type, Size, Seed),
{ok, Instance2} = proper_gen:pick(Type, Size, Seed),
?assert(Instance1 =:= Instance2).
assert_native_can_generate(Mod, TypeStr, CheckIsInstance) ->
assert_can_generate(assert_can_translate(Mod,TypeStr), CheckIsInstance).
assert_cant_generate(Type) ->
?assertEqual(error, proper_gen:pick(Type)),
?assert(state_is_clean()).
assert_cant_generate_cmds(Type, N) ->
?assertEqual(error, proper_gen:pick(?SUCHTHAT(T, Type, length(T) > N))),
?assert(state_is_clean()).
assert_not_is_instance(X, Type) ->
?assert(not proper_types:is_inst(X, Type) andalso state_is_clean()).
assert_function_type_works(FunType) ->
{ok,F} = proper_gen:pick(FunType),
?assert(proper_types:is_instance(F, FunType)),
assert_is_pure_function(F),
proper:global_state_erase(),
?assert(state_is_clean()).
assert_is_pure_function(F) ->
{arity,Arity} = erlang:fun_info(F, arity),
ArgsList = [lists:duplicate(Arity,0), lists:duplicate(Arity,1),
lists:seq(1,Arity), lists:seq(0,Arity-1)],
lists:foreach(fun(Args) -> ?assertEqual(apply(F,Args),apply(F,Args)) end,
ArgsList).
simple_types_with_data() ->
[{integer(), [-1,0,1,42,-200], 0, [0.3,someatom,<<1>>], "integer()"},
{integer(7,88), [7,8,87,88,23], 7, [1,90,a], "7..88"},
{integer(0,42), [0,11,42], 0, [-1,43], "0..42"},
{integer(-99,0), [-88,-99,0], 0, [1,-1112], "-99..0"},
{integer(-999,-12), [-34,-999,-12], -12, [0,5], "-999..-12"},
{integer(-99,21), [-98,0,21], 0, [-100], "-99..21"},
{integer(0,0), [0], 0, [1,-1,100,-100], "0..0"},
{pos_integer(), [12,1,444], 1, [-12,0], "pos_integer()"},
{non_neg_integer(), [42,0], 0, [-9,rr], "non_neg_integer()"},
{neg_integer(), [-222,-1], -1, [0,1111], "neg_integer()"},
{float(), [17.65,-1.12], 0.0, [11,atomm,<<>>], "float()"},
{float(7.4,88.0), [7.4,88.0], 7.4, [-1.0,3.2], none},
{float(0.0,42.1), [0.1,42.1], 0.0, [-0.1], none},
{float(-99.9,0.0), [-0.01,-90.0], 0.0, [someatom,-12,-100.0,0.1], none},
{float(-999.08,-12.12), [-12.12,-12.2], -12.12, [-1111.0,1000.0], none},
{float(-71.8,99.0), [-71.8,99.0,0.0,11.1], 0.0, [100.0,-71.9], none},
{float(0.0,0.0), [0.0], 0.0, [0.1,-0.1], none},
{non_neg_float(), [88.8,98.9,0.0], 0.0, [-12,1,-0.01], none},
{atom(), [elvis,'Another Atom',''], '', ["not_an_atom",12,12.2], "atom()"},
{binary(), [<<>>,<<12,21>>], <<>>, [<<1,2:3>>,binary_atom,42], "binary()"},
{binary(), [], <<>>, [], "<<_:_*8>>"},
{binary(3), [<<41,42,43>>], <<0,0,0>>, [<<1,2,3,4>>], "<<_:24>>"},
{binary(0), [<<>>], <<>>, [<<1>>], "<<_:0>>"},
{bitstring(), [<<>>,<<87,76,65,5:4>>], <<>>, [{12,3},11], "bitstring()"},
{bitstring(), [], <<>>, [], "<<_:_*1>>"},
{bitstring(18), [<<0,1,2:2>>,<<1,32,123:2>>], <<0,0,0:2>>, [<<12,1,1:3>>],
"<<_:18, _:_*0>>"},
{bitstring(32), [<<120,120,120,120>>], <<0,0,0,0>>, [7,8], "<<_:32>>"},
{bitstring(0), [<<>>], <<>>, [<<1>>], "<<>>"},
{list(integer()), [[],[2,42],[0,1,1,2,3,5,8,13,21,34,55,89,144]], [],
[[4,4.2],{12,1},<<12,113>>], "[integer()]"},
{list(atom()), [[on,the,third,day,'of',christmas,my,true,love,sent,to,me]],
[], [['not',1,list,'of',atoms],not_a_list], "[atom()]"},
{list(union([integer(),atom()])), [[3,french,hens,2],[turtle,doves]], [],
[{'and',1}], "[integer() | atom()]"},
{vector(5,atom()), [[partridge,in,a,pear,tree],[a,b,c,d,e]],
['','','','',''], [[a,b,c,d],[a,b,c,d,e,f]], none},
{vector(2,float()), [[0.0,1.1],[4.4,-5.5]], [0.0,0.0], [[1,1]], none},
{vector(0,integer()), [[]], [], [[1],[2]], none},
{union([good,bad,ugly]), [good,bad,ugly], good, [clint,"eastwood"],
"good | bad | ugly"},
{union([integer(),atom()]), [twenty_one,21], 0, ["21",<<21>>],
"integer() | atom()"},
{weighted_union([{10,luck},{20,skill},{15,concentrated_power_of_will},
{5,pleasure},{50,pain},{100,remember_the_name}]),
[skill,pain,pleasure], luck, [clear,20,50], none},
{{integer(0,42),list(atom())}, [{42,[a,b]},{21,[c,de,f]},{0,[]}], {0,[]},
[{-1,[a]},{12},{21,[b,c],12}], "{0..42,[atom()]}"},
{tuple(), [{a,42},{2.56,<<42>>,{a}},{},{a,{a,17},3.14,{{}}}], {},
[#{a => 17},[{}],42], "tuple()"},
{tuple([atom(),integer()]), [{the,1}], {'',0}, [{"a",0.0}],
"{atom(),integer()}"},
{{}, [{}], {}, [[],{1,2}], "{}"},
{loose_tuple(integer()), [{1,44,-1},{},{99,-99}], {}, [4,{hello,2},[1,2]],
none},
{loose_tuple(union([atom(),float()])), [{a,4.4,b},{},{'',c},{1.2,-3.4}],
{}, [an_atom,0.4,{hello,2},[aa,bb,3.1]], none},
{loose_tuple(list(integer())), [{[1,-1],[],[2,3,-12]},{}], {},
[[[1,2],[3,4]],{1,12},{[1,99,0.0],[]}], none},
{loose_tuple(loose_tuple(integer())), [{},{{}},{{1,2},{-1,11},{}}], {},
[{123},[{12},{24}]], none},
{exactly({[writing],unit,[tests,is],{2},boring}),
[{[writing],unit,[tests,is],{2},boring}],
{[writing],unit,[tests,is],{2},boring}, [no,its,'not','!'], none},
{[], [[]], [], [[a],[1,2,3]], "[]"},
{fixed_list([neg_integer(),pos_integer()]), [[-12,32],[-1,1]], [-1,1],
[[0,0]], none},
{[atom(),integer(),atom(),float()], [[forty_two,42,forty_two,42.0]],
['',0,'',0.0], [[proper,is,licensed],[under,the,gpl]], none},
{[42 | list(integer())], [[42],[42,44,22]], [42], [[],[11,12]], none},
{number(), [12,32.3,-9,-77.7], 0, [manolis,papadakis], "number()"},
{boolean(), [true,false], false, [unknown], "boolean()"},
{string(), ["hello","","world"], "", ['hello'], "string()"},
{arity(), [0,2,17,42,255], 0, [-1,256], "arity()"},
{timeout(), [0,42,infinity,666], 0, [-1,infinite,3.14], "timeout()"},
{?LAZY(integer()), [0,2,99], 0, [1.1], "integer()"},
{?LAZY(list(float())), [[0.0,1.2,1.99],[]], [], [1.1,[1,2]], "[float()]"},
{zerostream(10), [[0,0,0],[],[0,0,0,0,0,0,0]], [], [[1,0,0],[0.1]], none},
{?SHRINK(pos_integer(),[0]), [1,12,0], 0, [-1,-9,6.0], none},
{?SHRINK(float(),[integer(),atom()]), [1.0,0.0,someatom,'',42,0], 0,
[<<>>,"hello"], none},
{noshrink(?SHRINK(42,[0,1])), [42,0,1], 42, [-1], "42 | 0 | 1"},
{non_empty(list(integer())), [[1,2,3],[3,42],[11]], [0], [[],[0.1]],
"[integer(),...]"},
{default(42,float()), [4.1,-99.0,0.0,42], 42, [43,44], "42 | float()"},
{?SUCHTHAT(X,non_neg_integer(),X rem 4 =:= 1), [1,5,37,89], 1, [4,-12,11],
none},
{?SUCHTHATMAYBE(X,non_neg_integer(),X rem 4 =:= 1), [1,2,3,4,5,37,89], 0,
[1.1,2.2,-12], "non_neg_integer()"},
{?SUCHTHAT(L, non_empty(list(non_neg_integer())), hd(L) < 5),
[[1], [1,2,3,4], [0,2]], [0], [[], "Fail","something", [5]], none},
{any(), [1,-12,0,99.9,-42.2,0.0,an_atom,'',<<>>,<<1,2>>,<<1,2,3:5>>,[],
[42,<<>>],{},{tag,12},{tag,[vals,12,12.2],[],<<>>}],
0, [], "any()"},
{list(any()), [[<<>>,a,1,-42.0,{11.8,[]}]], [], [{1,aa},<<>>], "[any()]"},
{deeplist(), [[[],[]], [[[]],[]]], [], [[a]], "deeplist()"},
{none, [[234,<<1>>,[<<78>>,[]],0],[]], [], [21,3.1,[7.1],<<22>>],
"iolist()"},
{none, [[234,<<1>>,[<<78>>,[]],0],[],<<21,15>>], <<>>, [21,3.1,[7.1]],
"iodata()"}].
constructed_types_with_data() ->
[{?LET({A,B},{bitstring(3),binary()},<<A/bits,B/bits>>),
[{'$used',{<<1:3>>,<<3,4>>},<<32,96,4:3>>}], <<0:3>>, [],
"<<_:3,_:_*8>>"},
{?LET(X,range(1,5),X*X), [{'$used',1,1},{'$used',5,25}], 1,
[4,{'$used',3,8},{'$used',0,0}], none},
{?LET(L,non_empty(list(atom())),oneof(L)),
[{'$used',[aa],aa},{'$used',[aa,bb],aa},{'$used',[aa,bb],bb}], '',
[{'$used',[],''},{'$used',[aa,bb],cc}], none},
{?LET(X,pos_integer(),?LET(Y,range(0,X),X-Y)),
[{'$used',3,{'$used',2,1}},{'$used',9,{'$used',9,0}},
{'$used',5,{'$used',0,5}}], 1,
[{'$used',0,{'$used',0,0}},{'$used',3,{'$used',4,-1}},
{'$used',7,{'$used',6,2}}], none},
{?LET(Y,?LET(X,integer(),X*X),-Y),
[{'$used',{'$used',-9,81},-81},{'$used',{'$used',2,4},-4}], 0,
[{'$used',{'$used',1,2},-2},{'$used',{'$used',3,9},9}], none},
{?SUCHTHAT(Y,?LET(X,oneof([1,2,3]),X+X),Y>3),
[{'$used',2,4},{'$used',3,6}], 4, [{'$used',1,2}], none},
{?LET(X,?SUCHTHAT(Y,pos_integer(),Y=/=0),X*X),
[{'$used',3,9},{'$used',1,1},{'$used',11,121}], 1,
[{'$used',-1,1},{'$used',0,0}], none},
{tree(integer()), [{'$used',[null,null],{node,42,null,null}},
{'$used',[{'$used',[null,null],{node,2,null,null}},
{'$used',[null,null],{node,3,null,null}}],
{node,-1,{node,2,null,null},{node,3,null,null}}},
{'$to_part',null},
{'$to_part',{'$used',[null,null],{node,7,null,null}}}],
null, [{'$used',[null,null],{node,1.1,null,null}}], "tree(integer())"},
{?LETSHRINK(L,[],{tag,L}), [{'$used',[],{tag,[]}}], {tag,[]}, [], none},
{?LETSHRINK(L,non_empty(list(atom())),{tag,L}),
[{'$used',[aa],{tag,[aa]}},{'$to_part',aa}], '', [], none},
{a(), [aleaf, {'$used',[aleaf],{anode,aleaf,bleaf}},
{'$used',[aleaf],{anode,aleaf,{'$to_part',bleaf}}}],
aleaf, [], "a()"},
{b(), [bleaf, {'$used',[bleaf],{bnode,aleaf,bleaf}},
{'$used',[bleaf],{bnode,{'$to_part',aleaf},bleaf}}],
bleaf, [], "b()"},
{gen_tree(integer()),
[{'$used',[null,null],{12,[null,null]}},{'$to_part',null}],
null, [{'$used',[],{42,[]}}], "gen_tree(integer())"},
{none, [{'$used',[],{tag,[]}}, {'$used',[null,null],{tag,[null,null]}},
{'$used',[{'$used',[],{tag,[]}},{'$to_part',null}],
{tag,[{tag,[]},null]}}, {'$to_part',{'$used',[],{tag,[]}}}],
null, [], "g()"},
{none, [{'$used',[null],{tag,[{ok,null}]}}, {'$to_part',null},
{'$used',[null,null],{tag,[{ok,null},{ok,null}]}}],
null, [], "h()"},
{none, [{'$used',[null,null,{'$used',[null],{tag,null,[]}}],
{tag,null,[null,{tag,null,[]}]}}, {'$to_part',null}],
null, [], "i()"},
{none, [{'$used',[{'$to_part',null},{'$used',[null],{one,null}},null,null],
{tag,null,{one,null},[null,null],[null]}}], null, [], "j()"},
{none, [{tag,[]}, {tag,[{null,null}]},
{tag,[{{tag,[]},null},{null,{tag,[]}}]}],
null, [{'$to_part',null}], "k()"},
{none, [{'$used',[null,null,{'$used',[null,null],{tag,null,[null]}}],
{tag,null,[null,{tag,null,[null]}]}}, {'$to_part',null}],
null, [{'$used',[null],{tag,null,[]}}], "l()"},
{utf8(), [{'$used',{'$used',0,[]},<<>>}, {'$used',{'$used',1,[0]},<<0>>},
{'$used',{'$used',1,[127]},<<127>>},
{'$used',{'$used',1,[353]},<<197,161>>}],
<<>>, [{'$used',{'$used',1,[128]},<<128>>}], none},
{utf8(0), [{'$used',{'$used',0,[]},<<>>}], <<>>, [], none},
{utf8(1), [{'$used',{'$used',0,[]},<<>>},
{'$used',{'$used',1,[127]},<<127>>},
{'$used',{'$used',1,[353]},<<197,161>>}], <<>>, [], none},
{utf8(2), [{'$used',{'$used',1,[353]},<<197,161>>},
{'$used',{'$used',2,[127,353]},<<127,197,161>>}],
<<>>, [], none},
{utf8(inf, 1), [{'$used',{'$used',0,[]},<<>>},
{'$used',{'$used',1,[0]},<<0>>},
{'$used',{'$used',2,[0,0]},<<0,0>>},
{'$used',{'$used',3,[0,0,0]},<<0,0,0>>}], <<>>, [], none},
{utf8(inf, 2), [{'$used',{'$used',3,[0,0,0]},<<0,0,0>>},
{'$used',{'$used',1,[353]},<<197,161>>}],
<<>>, [], none}].
function_types() ->
[{function([],atom()), "fun(() -> atom())"},
{function([integer(),integer()],atom()),
"fun((integer(),integer()) -> atom())"},
{function(5,union([a,b])), "fun((_,_,_,_,_) -> a | b)"},
{function(0,function(1,integer())),
"fun(() -> fun((_) -> integer()))"}].
remote_native_types() ->
[{types_test1,["#rec1{}","rec1()","exp1()","type1()","type2(atom())",
"rem1()","rem2()","types_test1:exp1()",
"types_test2:exp1(float())","types_test2:exp2()"]},
{types_test2,["exp1(#rec1{})","exp2()","#rec1{}","types_test1:exp1()",
"types_test2:exp1(binary())","types_test2:exp2()"]}].
impossible_types() ->
[?SUCHTHAT(X, pos_integer(), X =< 0),
?SUCHTHAT(X, non_neg_integer(), X < 0),
?SUCHTHAT(X, neg_integer(), X >= 0),
?SUCHTHAT(X, integer(1,10), X > 20),
?SUCHTHAT(X, float(0.0,10.0), X < 0.0),
?SUCHTHAT(L, vector(12,integer()), length(L) =/= 12),
?SUCHTHAT(B, binary(), lists:member(256,binary_to_list(B))),
?SUCHTHAT(X, exactly('Lelouch'), X =:= 'vi Brittania'),
?SUCHTHAT(X, utf8(), unicode:characters_to_list(X) =:= [16#D800]),
?SUCHTHAT(X, utf8(1, 1), size(X) > 1),
?SUCHTHAT(X, ?SUCHTHAT(Y, pos_integer(), Y < 0), X > 0),
?SUCHTHAT(X, ?SUCHTHAT(Y, pos_integer(), Y > 0), X < 0),
Nested constraints , one strict and one non - strict , where the
?SUCHTHATMAYBE(_X, ?SUCHTHAT(Y, pos_integer(), Y < 0), true),
Nested constraints , one strict and one non - strict , where the
?SUCHTHAT(X, ?SUCHTHATMAYBE(Y, pos_integer(), Y < 0), X < 0),
Two failing constraints within a ? LET macro , where both
?LET({X,Y}, {?SUCHTHAT(X1, pos_integer(), X1 < 0),
?SUCHTHAT(Y1, pos_integer(), Y1 < 0)}, {X,Y})
].
impossible_native_types() ->
[{types_test1, ["1.1","no_such_module:type1()","no_such_type()"]},
{types_test2, ["types_test1:type1()","function()","fun((...) -> atom())",
"pid()","port()","ref()"]}].
recursive_native_types() ->
[{rec_test1, ["a()","b()","a()|b()","d()","f()","deeplist()",
"mylist(float())","aa()","bb()","expc()"]},
{rec_test2, ["a()","expa()","rec()"]}].
impossible_recursive_native_types() ->
[{rec_test1, ["c()","e()","cc()","#rec{}","expb()"]},
{rec_test2, ["b()","#rec{}","aa()"]}].
symb_calls() ->
[{[3,2,1], "lists:reverse([1,2,3])", [], {call,lists,reverse,[[1,2,3]]}},
{[a,b,c,d], "erlang:'++'([a,b],[c,d])",
[{a,some_value}], {call,erlang,'++',[[a,b],[c,d]]}},
{42, "erlang:'*'(erlang:'+'(3,3),erlang:'-'(8,1))",
[{b,dummy_value},{e,another_dummy}],
{call,erlang,'*',[{call,erlang,'+',[3,3]},{call,erlang,'-',[8,1]}]}},
{something, "something",
[{a,somebody},{b,put},{c,something},{d,in_my_drink}], {var,c}},
{{var,b}, "{var,b}", [{a,not_this},{c,neither_this}], {var,b}},
{42, "erlang:'+'(40,2)", [{m,40},{n,2}],
{call,erlang,'+',[{var,m},{var,n}]}},
{[i,am,{var,iron},man],
"erlang:'++'(lists:reverse([am,i]),erlang:'++'([{var,iron}],[man]))",
[{a,man},{b,woman}],
{call,erlang,'++',[{call,lists,reverse,[[am,i]]},
{call,erlang,'++',[[{var,iron}],[{var,a}]]}]}}].
undefined_symb_calls() ->
[{call,erlang,error,[an_error]},
{call,erlang,throw,[a_throw]},
{call,erlang,exit,[an_exit]},
{call,lists,reverse,[<<12,13>>]},
{call,erlang,'+',[1,2,3]}].
combinations() ->
[{[{1,[1,3,5,7,9,10]}, {2,[2,4,6,8,11]}], 5, 11, [1,2,3,4,5,6,7,8,9,10,11], 2, 2,
[{1,[1,3,5,7,8,11]}, {2,[2,4,6,9,10]}]},
{[{1,[1,3,5]}, {2,[7,8,9]}, {3,[2,4,6]}], 3, 9, [1,3,5,7,8,9], 3, 2,
[{1,[6,8,9]}, {2,[1,3,5]}, {3,[2,4,7]}]}].
first_comb() ->
[{10,3,3,[{1,[7,8,9,10]}, {2,[4,5,6]}, {3,[1,2,3]}]},
{11,5,2,[{1,[6,7,8,9,10,11]}, {2,[1,2,3,4,5]}]},
{12,3,4,[{1,[10,11,12]}, {2,[7,8,9]}, {3,[4,5,6]}, {4,[1,2,3]}]}].
lists_to_zip() ->
[{[],[],[]},
{[], [dummy, atom], []},
{[1, 42, 1, 42, 1, 2 ,3], [], []},
{[a, b, c], lists:seq(1,6), [{a,1}, {b,2}, {c,3}]},
{[a, b, c], lists:seq(1,3), [{a,1}, {b,2}, {c,3}]},
{[a, d, d, d, d], lists:seq(1,3), [{a,1}, {d,2}, {d,3}]}].
command_names() ->
[{[{set,{var,1},{call,erlang,put,[a,0]}},
{set,{var,3},{call,erlang,erase,[a]}},
{set,{var,4},{call,erlang,get,[b]}}],
[{erlang,put,2},
{erlang,erase,1},
{erlang,get,1}]},
{[{set,{var,1},{call,foo,bar,[]}},
{set,{var,2},{call,bar,foo,[a,{var,1}]}},
{set,{var,3},{call,bar,foo,[a,[[3,4]]]}}],
[{foo,bar,0},
{bar,foo,2},
{bar,foo,2}]},
{[],[]}].
valid_command_sequences() ->
[{pdict_statem, [], [{init,[]},
{set,{var,1},{call,erlang,put,[a,0]}},
{set,{var,2},{call,erlang,put,[b,1]}},
{set,{var,3},{call,erlang,erase,[a]}},
{set,{var,4},{call,erlang,get,[b]}},
{set,{var,5},{call,erlang,erase,[b]}},
{set,{var,6},{call,erlang,put,[a,4]}},
{set,{var,7},{call,erlang,put,[a,42]}}],
[{a,42}], [{a,42}], []},
{pdict_statem, [], [{init,[]},
{set,{var,1},{call,erlang,put,[b,5]}},
{set,{var,2},{call,erlang,erase,[b]}},
{set,{var,3},{call,erlang,put,[a,5]}}],
[{a,5}], [{a,5}], []},
{pdict_statem, [], [{init,[]},
{set,{var,1},{call,erlang,put,[a,{var,start_value}]}},
{set,{var,2},{call,erlang,put,[b,{var,another_start_value}]}},
{set,{var,3},{call,erlang,get,[b]}},
{set,{var,4},{call,erlang,get,[b]}}],
[{b,{var,another_start_value}}, {a,{var,start_value}}], [{b,-1}, {a, 0}],
[{start_value, 0}, {another_start_value, -1}]}].
symbolic_init_invalid_sequences() ->
[{pdict_statem, [{init,[{a,{call,foo,bar,[some_arg]}}]},
{set,{var,1},{call,erlang,put,[b,42]}},
{set,{var,2},{call,erlang,get,[b]}}],
[{some_arg, 0}],
[{init,[{a,{call,foo,bar,[some_arg]}}]}]}].
invalid_precondition() ->
[{pdict_statem, [{init,[]},
{set,{var,1},{call,erlang,put,[a,0]}},
{set,{var,2},{call,erlang,put,[b,1]}},
{set,{var,3},{call,erlang,erase,[a]}},
{set,{var,4},{call,erlang,get,[a]}}],
[], [{set,{var,4},{call,erlang,get,[a]}}]}].
invalid_var() ->
[{pdict_statem, [{init,[]},
{set,{var,2},{call,erlang,put,[b,{var,1}]}}]},
{pdict_statem, [{init,[]},
{set,{var,1},{call,erlang,put,[b,9]}},
{set,{var,5},{call,erlang,put,[a,3]}},
{set,{var,6},{call,erlang,get,[{var,2}]}}]}].
arguments_not_defined() ->
[{[simple,atoms,are,valid,{var,42}], []},
{[{var,1}], [{var,2},{var,3},{var,4}]},
{[hello,world,[hello,world,{var,6}]], []},
{[{1,2,3,{var,1},{var,2}},not_really], []},
{[[[[42,{var,42}]]]], []},
{[{43,41,{1,{var,42}}},why_not], []}].
all_data() ->
[1, 42.0, "$hello", "world\n", [smelly, cat, {smells,bad}],
'$this_should_be_copied', '$this_one_too', 'but$ this$ not',
or_this].
dollar_data() ->
['$this_should_be_copied', '$this_one_too'].
TODO : write tests for old datatypes , use old tests
TODO : check output redirection , quiet , verbose , to_file , on_output/2 ( maybe
TODO : LET and LETSHRINK testing ( these need their intermediate form for
trees , for testing , also test with noshrink and LAZY
TODO : use size=100 for is_instance testing ?
TODO : : check that the same type is returned for consecutive calls ,
TODO : : recursive types containing functions
TODO : ? LET , ? LETSHRINK : only the top - level base type can be a native type
TODO : Test with native types : ? , noshrink , ? LAZY , ? SHRINK ,
TODO : more ADT tests : check bad declarations , bad variable use , multi - clause ,
is_subtype , unacceptable range , unexported opaque , no - specs opaque ,
TODO : conversion of maybe_improper_list
simple_types_test_() ->
[?_test(assert_type_works(TD, true)) || TD <- simple_types_with_data()].
constructed_types_test_() ->
[?_test(assert_type_works(TD, false))
|| TD <- constructed_types_with_data()].
shrinks_to_test_() ->
All = simple_types_with_data() ++ constructed_types_with_data(),
[?_shrinksTo(Target, Type)
|| {Type,_Xs,Target,_Ys,_TypeStr} <- All, Type =/= none].
native_shrinks_to_test_() ->
All = simple_types_with_data() ++ constructed_types_with_data(),
[?_nativeShrinksTo(Target, TypeStr)
|| {_Type,_Xs,Target,_Ys,TypeStr} <- All, TypeStr =/= none].
cant_generate_test_() ->
[?_test(assert_cant_generate(Type)) || Type <- impossible_types()].
proper_exported_types_test_() ->
[?_assertEqual({[],12}, proper_exported_types_test:not_handled())].
cant_generate_constraints_test_() ->
?_errorsOut({cant_generate, [{?MODULE, cant_generate_constraints_test_, 0}]},
?FORALL(_, ?SUCHTHAT(X, pos_integer(), X =< 0), true)),
?_errorsOut({cant_generate, [{?MODULE, impossible, 0}]},
?FORALL(_X, impossible(), true)),
?_errorsOut({cant_generate, [{?MODULE, possible, 0},
{?MODULE, possible_made_impossible, 0}]},
?FORALL(_X, possible_made_impossible(), true)),
?_errorsOut({cant_generate, [{?MODULE, possible, 0},
{?MODULE, possible_made_impossible_2, 0}]},
?FORALL(_X, possible_made_impossible_2(), true))
].
possible() ->
?SUCHTHAT(X, pos_integer(), X > 0).
impossible() ->
?SUCHTHAT(X, pos_integer(), X =< 0).
possible_made_impossible() ->
?SUCHTHAT(X, possible(), X =< 0).
possible_made_impossible_2() ->
?SUCHTHAT(Y, ?SUCHTHAT(X, possible(), X =< 0), Y =< 0).
native_cant_translate_test_() ->
[?_test(assert_cant_translate(Mod,TypeStr))
|| {Mod,Strings} <- impossible_native_types(), TypeStr <- Strings].
remote_native_types_test_() ->
[?_test(assert_can_translate(Mod,TypeStr))
|| {Mod,Strings} <- remote_native_types(), TypeStr <- Strings].
recursive_native_types_test_() ->
[?_test(assert_native_can_generate(Mod,TypeStr,false))
|| {Mod,Strings} <- recursive_native_types(), TypeStr <- Strings].
recursive_native_cant_translate_test_() ->
[?_test(assert_cant_translate(Mod,TypeStr))
|| {Mod,Strings} <- impossible_recursive_native_types(),
TypeStr <- Strings].
random_functions_test_() ->
[[?_test(assert_function_type_works(FunType)),
?_test(assert_function_type_works(assert_can_translate(proper,TypeStr)))]
|| {FunType,TypeStr} <- function_types()].
parse_transform_test_() ->
[?_passes(auto_export_test1:prop_1()),
?_assertError(undef, auto_export_test2:prop_1()),
?_assertError(undef, no_native_parse_test:prop_1()),
?_passes(let_tests:prop_1()),
?_failsWith([3*42], let_tests:prop_2())].
native_type_props_test_() ->
[?_passes(?FORALL({X,Y}, {my_native_type(),my_proper_type()},
is_integer(X) andalso is_atom(Y))),
?_passes(?FORALL([X,Y,Z],
[my_native_type(),my_proper_type(),my_native_type()],
is_integer(X) andalso is_atom(Y) andalso is_integer(Z))),
?_passes(?FORALL([Y,X,{Z,W}],
[my_proper_type() | [my_native_type()]] ++
[{my_native_type(),my_proper_type()}],
is_integer(X) andalso is_atom(Y) andalso is_integer(Z)
andalso is_atom(W))),
?_passes(?FORALL([X|Y], [my_native_type()|my_native_type()],
is_integer(X) andalso is_integer(Y))),
?_passes(?FORALL(X, type_and_fun(), is_atom(X))),
?_passes(?FORALL(X, type_only(), is_integer(X))),
?_passes(?FORALL(L, [integer()], length(L) =:= 1)),
?_fails(?FORALL(L, id([integer()]), length(L) =:= 1)),
?_passes(?FORALL(_, types_test1:exp1(), true)),
?_assertError(undef, ?FORALL(_,types_test1:rec1(),true)),
?_assertError(undef, ?FORALL(_,no_such_module:some_call(),true)),
{setup, fun() -> code:purge(to_remove),
code:delete(to_remove),
code:purge(to_remove),
file:rename("tests/to_remove.beam",
"tests/to_remove.bak") end,
fun(_) -> file:rename("tests/to_remove.bak",
"tests/to_remove.beam") end,
?_passes(?FORALL(_, to_remove:exp1(), true))},
?_passes(rec_props_test1:prop_1()),
?_passes(rec_props_test2:prop_2()),
?_passes(?FORALL(L, vector(2,my_native_type()),
length(L) =:= 2
andalso lists:all(fun erlang:is_integer/1, L))),
?_passes(?FORALL(F, function(0,my_native_type()), is_integer(F()))),
?_passes(?FORALL(X, union([my_proper_type(),my_native_type()]),
is_integer(X) orelse is_atom(X))),
?_assertError(undef, begin
Vector5 = fun(T) -> vector(5,T) end,
?FORALL(V, Vector5(types_test1:exp1()),
length(V) =:= 5)
end),
?_passes(?FORALL(X, ?SUCHTHAT(Y,types_test1:exp1(),is_atom(Y)),
is_atom(X))),
?_passes(?FORALL(L,non_empty(lof()),length(L) > 0)),
?_passes(?FORALL(X, ?LET(L,lof(),lists:min([99999.9|L])),
is_float(X))),
?_shrinksTo(0, ?LETSHRINK([X],[my_native_type()],{'tag',X})),
{"Shrinking tuples",
[{"All elements are generators",
[?_shrinksTo({0,0}, proper_types:tuple([proper_types:integer(), proper_types:integer()])),
?_shrinksTo({0,0}, {proper_types:integer(), proper_types:integer()})]},
{"Some elements are generators",
[?_shrinksTo({0,0}, proper_types:tuple([proper_types:integer(), 0])),
?_shrinksTo({0,2}, proper_types:tuple([proper_types:integer(), 2])),
?_shrinksTo({0,0}, {proper_types:integer(), 0}),
?_shrinksTo({0,2}, {proper_types:integer(), 2})]},
{"All elements are consts",
[?_shrinksTo({3,2}, proper_types:tuple([3, 2])),
?_shrinksTo({3,2}, {3, 2})]}]},
{"Shrinking fixed lists",
[{"All elements are generators",
[?_shrinksTo([0,0], proper_types:fixed_list([proper_types:integer(), proper_types:integer()])),
?_shrinksTo([0,0], [proper_types:integer(), proper_types:integer()]),
?_shrinksTo([0|0], [proper_types:integer()|proper_types:integer()])]},
{"Some elements are generators",
[?_shrinksTo([0,0], proper_types:fixed_list([proper_types:integer(), 0])),
?_shrinksTo([0,2], proper_types:fixed_list([proper_types:integer(), 2])),
?_shrinksTo([0|2], proper_types:fixed_list([proper_types:integer()|2])),
?_shrinksTo([0,0], [proper_types:integer(), 0]),
?_shrinksTo([0,2], [proper_types:integer(), 2]),
?_shrinksTo([12,42], [12,42|list(integer())])]},
{"All elements are consts",
[?_shrinksTo([3|2], proper_types:fixed_list([3|2])),
?_shrinksTo([3,2], proper_types:fixed_list([3, 2])),
?_shrinksTo([3,2], [3, 2])]}]},
?_passes(weird_types:prop_export_all_works()),
?_passes(weird_types:prop_no_auto_import_works()),
?_passes(?FORALL(B, utf8(), unicode:characters_to_binary(B) =:= B)),
?_passes(?FORALL(B, utf8(1), length(unicode:characters_to_list(B)) =< 1)),
?_passes(?FORALL(B, utf8(1, 1), size(B) =< 1)),
?_passes(?FORALL(B, utf8(2, 1), size(B) =< 2)),
?_passes(?FORALL(B, utf8(4), size(B) =< 16)),
?_passes(?FORALL(B, utf8(),
length(unicode:characters_to_list(B)) =< size(B)))
].
-type bin4() :: <<_:32>>.
-type bits42() :: <<_:42>>.
-type bits5x() :: <<_:_*5>>.
-type bits7x() :: <<_:_*7>>.
-record(untyped, {a, b = 12}).
-type untyped() :: #untyped{}.
true_props_test_() ->
[?_passes(?FORALL(X,integer(),X < X + 1)),
?_passes(?FORALL(A,atom(),list_to_atom(atom_to_list(A)) =:= A)),
?_passes(?FORALL(B,bin4(),byte_size(B) =:= 4)),
?_passes(?FORALL(B,bits42(),bit_size(B) =:= 42)),
?_passes(?FORALL(B,bits5x(),bit_size(B) =/= 42)),
?_passes(?FORALL(B,bits7x(),bit_size(B) rem 7 =:= 0)),
?_passes(?FORALL(L,list(integer()),is_sorted(L,quicksort(L)))),
?_passes(?FORALL(L,ulist(integer()),is_sorted(L,lists:usort(L)))),
?_passes(?FORALL(L,non_empty(list(integer())),L =/= [])),
?_passes(?FORALL({I,L}, {integer(),list(integer())},
?IMPLIES(no_duplicates(L),
not lists:member(I,lists:delete(I,L))))),
?_passes(?FORALL(L, ?SIZED(Size,resize(Size div 5,list(integer()))),
length(L) =< 20), [{max_size,100}]),
?_passes(?FORALL(L, list(integer()),
collect(length(L), collect(L =:= [],
lists:reverse(lists:reverse(L)) =:= L)))),
?_passes(?FORALL(L, list(integer()),
aggregate(smaller_lengths_than_my_own(L), true))),
?_assertTempBecomesN(300, true,
numtests(300,?FORALL(_,1,begin inc_temp(),true end))),
?_assertTempBecomesN(30, true, ?FORALL(X, ?SIZED(Size,Size),
begin inc_temp(X),true end),
[{numtests,12},{max_size,4}]),
?_assertTempBecomesN(12, true,
?FORALL(X, ?SIZED(Size,Size),
begin inc_temp(X),true end),
[{numtests,3},{start_size,4},{max_size,4}]),
?_assertTempBecomesN(30, true,
?FORALL_TARGETED(X, ?USERNF(?SIZED(Size,Size),
fun (_, _) -> ?SIZED(Size, Size) end),
begin inc_temp(X),true end),
[{numtests,12},{max_size,4}]),
?_assertTempBecomesN(12, true,
?FORALL_TARGETED(X, ?USERNF(?SIZED(Size,Size),
fun (_, _) -> ?SIZED(Size, Size) end),
begin inc_temp(X),true end),
[{numtests,3},{start_size,4},{max_size,4}]),
?_passes(?FORALL(X, integer(), ?IMPLIES(abs(X) > 1, X * X > X))),
?_passes(?FORALL(X, integer(), ?IMPLIES(X >= 0, true))),
?_passes(?FORALL({X,Lim}, {int(),?SIZED(Size,Size)}, abs(X) =< Lim)),
?_passes(?FORALL({X,Lim}, {nat(),?SIZED(Size,Size)}, X =< Lim)),
?_passes(?FORALL(L, orderedlist(integer()), is_sorted(L))),
?_passes(conjunction([
{one, ?FORALL(_, integer(), true)},
{two, ?FORALL(X, integer(), collect(X > 0, true))},
{three, conjunction([{a,true},{b,true}])}
])),
?_passes(?FORALL(X, untyped(), is_record(X, untyped))),
?_passes(fun_tests:prop_fun_bool())].
true_stateful_test_() ->
[?_passes(improper_lists_statem:prop_simple()),
?_passes(symb_statem:prop_simple()),
?_passes(symb_statem_maps:prop_simple()),
?_passes(more_commands_test:prop_commands_passes(), [{numtests,42}]),
{timeout, 10, ?_passes(ets_statem_test:prop_ets())},
{timeout, 20, ?_passes(ets_statem_test:prop_parallel_ets())},
{timeout, 20, ?_passes(pdict_fsm:prop_pdict())},
{timeout, 20, ?_passes(symb_statem:prop_parallel_simple())},
{timeout, 20, ?_passes(symb_statem_maps:prop_parallel_simple())},
{timeout, 42, ?_passes(targeted_statem:prop_random(), [{numtests,500}])},
{timeout, 42, ?_passes(targeted_fsm:prop_random(), [{numtests,500}])}].
false_props_test_() ->
[?_failsWith([[Same,Same]],
?FORALL(L,list(integer()),is_sorted(L,lists:usort(L)))),
?_failsWith([[Same2,Same2],Same2],
?FORALL(L, non_empty(list(union([a,b,c,d]))),
?FORALL(X, elements(L),
not lists:member(X,lists:delete(X,L))))),
?_failsWith(['\000\000\000\000'],
?FORALL(A, atom(), length(atom_to_list(A)) < 4)),
?_failsWith([1], ?FORALL(X, non_neg_integer(),
case X > 0 of
true -> throw(not_zero);
false -> true
end)),
?_fails(?FORALL(_, 1, lists:min([]) > 0)),
?_failsWith([[12,42]], ?FORALL(L, [12,42|list(integer())],
case lists:member(42, L) of
true -> erlang:exit(you_got_it);
false -> true
end)),
TODO : Check that the following two tests shrink properly on _ N
?_cexmMatchesWith([{_,_N}], fun_tests:prop_fun_int_int()),
?_cexmMatchesWith([{_,_,[_N]}], fun_tests:prop_lists_map_filter()),
?_fails(?FORALL(_, integer(), ?TIMEOUT(100,timer:sleep(150) =:= ok))),
?_failsWith([20], ?FORALL(X, pos_integer(), ?TRAPEXIT(creator(X) =:= ok))),
?_assertTempBecomesN(7, false,
?FORALL(X, ?SIZED(Size,integer(Size,Size)),
begin inc_temp(), X < 5 end),
[{numtests,5}, {max_size,5}]),
it runs 2 more times : one while shrinking ( recursing into the property )
?_assertTempBecomesN(2, false,
?FORALL(L, list(atom()),
?WHENFAIL(inc_temp(), length(L) < 5))),
?_assertTempBecomesN(3, false,
?FORALL(S, ?SIZED(Size,Size),
begin inc_temp(), S =< 20 end),
[{numtests,3},{max_size,40},noshrink]),
?_failsWithOneOf([[{true,false}],[{false,true}]],
?FORALL({B1,B2}, {boolean(),boolean()}, equals(B1,B2))),
?_failsWith([2,1],
?FORALL(X, integer(1,10), ?FORALL(Y, integer(1,10), X =< Y))),
?_failsWith([1,2],
?FORALL(Y, integer(1,10), ?FORALL(X, integer(1,10), X =< Y))),
?_failsWithOneOf([[[0,1]],[[0,-1]],[[1,0]],[[-1,0]]],
?FORALL(L, list(integer()), lists:reverse(L) =:= L)),
?_failsWith([[1,2,3,4,5,6,7,8,9,10]],
?FORALL(_L, shuffle(lists:seq(1,10)), false)),
?_fails(?FORALL(_, integer(0,0), false)),
?_fails(?FORALL(_, float(0.0,0.0), false)),
?_fails(fails(?FORALL(_, integer(), false))),
?_failsWith([16], ?FORALL(X, ?LET(Y,integer(),Y*Y), X < 15)),
?_failsWith([0.0],
?FORALL(_, ?LETSHRINK([A,B], [float(),atom()], {A,B}), false)),
?_failsWith([], conjunction([{some,true},{thing,false}])),
?_failsWith([{2,1},[{group,[[{sub_group,[1]}]]},{stupid,[1]}]],
?FORALL({X,Y}, {pos_integer(),pos_integer()},
conjunction([
{add_next, ?IMPLIES(X > Y, X + 1 > Y)},
{symmetry,
conjunction([
{add_sym, collect(X+Y, X+Y =:= Y+X)},
{sub_sym,
?WHENFAIL(io:format("'-' isn't symmetric!~n",[]),
X-Y =:= Y-X)}
])},
{group,
conjunction([
{add_group,
?WHENFAIL(io:format("This shouldn't happen!~n",[]),
?FORALL(Z, pos_integer(),
(X+Y)+Z =:= X+(Y+Z)))},
{sub_group,
?WHENFAIL(io:format("'-' doesn't group!~n",[]),
?FORALL(W, pos_integer(),
(X-Y)-W =:= X-(Y-W)))}
])},
{stupid, ?FORALL(_, pos_integer(), throw(woot))}
]))),
?_failsWith([[a,a,a,a,a]], shrinking_gotchas:prop_shrink_list_same_elem()),
?_fails(more_commands_test:prop_more_commands_fails(), [{numtests,42}]),
?_failsWith([500], targeted_shrinking_test:prop_int()),
?_failsWith([500], targeted_shrinking_test:prop_let_int()),
?_failsWith([500], targeted_shrinking_test:prop_int_shrink_outer()),
?_failsWith([500], targeted_shrinking_test:prop_int_shrink_inner()),
{timeout, 20, ?_fails(ets_counter:prop_ets_counter())},
?_fails(post_false:prop_simple())].
false_stateful_test_() ->
Opts = [{numtests,1000}],
[{timeout, 42, ?_fails(targeted_statem:prop_targeted(), Opts)},
{timeout, 42, ?_fails(targeted_statem:prop_targeted_init(), Opts)},
{timeout, 42, ?_fails(targeted_fsm:prop_targeted(), Opts)},
{timeout, 42, ?_fails(targeted_fsm:prop_targeted_init(), Opts)}].
exception_props_test_() ->
[?_fails(error_statem:prop_simple())].
error_props_test_() ->
[?_errorsOut({cant_generate,[{?MODULE,error_props_test_,0}]},
?FORALL(_, ?SUCHTHAT(X, pos_integer(), X =< 0), true)),
?_errorsOut(cant_satisfy,
?FORALL(X, pos_integer(), ?IMPLIES(X =< 0, true))),
?_errorsOut(type_mismatch,
?FORALL({X,Y}, [integer(),integer()], X < Y)),
?_assertCheck({error,rejected}, [2],
?FORALL(X, integer(), ?IMPLIES(X > 5, X < 6))),
?_assertCheck({error,too_many_instances}, [1,ab],
?FORALL(X, pos_integer(), X < 0)),
?_errorsOut({cant_generate,[{proper_statem,commands_gen,4}]},
prec_false:prop_simple()),
?_errorsOut({cant_generate,[{nogen_statem,impossible_arg,0}]},
nogen_statem:prop_simple()),
?_errorsOut(non_boolean_result, ?FORALL(_, integer(), not_a_boolean)),
?_errorsOut(non_boolean_result,
?FORALL(_, ?SHRINK(42,[0]),
non_deterministic([{2,false},{1,not_a_boolean}]))),
?_assertRun(false,
?FORALL(_, ?SHRINK(42,[0]),
non_deterministic([{4,false},{1,true}])),
[], false),
?_assertRun(false,
?FORALL(_, ?SHRINK(42,[0]),
non_deterministic([{3,false},{1,true},{1,false}])),
[], false),
?_assertRun(false,
?FORALL(_, ?LAZY(non_deterministic([{1,1},{1,2},{1,3},{1,4}])),
false), [], false)].
eval_test_() ->
[?_assertEqual(Result, eval(Vars,SymbCall))
|| {Result,_Repr,Vars,SymbCall} <- symb_calls()].
pretty_print_test_() ->
[?_assert(equal_ignoring_ws(Repr, proper_symb:pretty_print(Vars,SymbCall)))
|| {_Result,Repr,Vars,SymbCall} <- symb_calls()].
not_defined_test_() ->
[?_assertNot(defined(SymbCall))
|| SymbCall <- undefined_symb_calls()].
options_test_() ->
[?_assertEqual({error,{erroneous_option,{numtests,0}}},
proper:module(command_props, [{numtests,0}])),
?_assertEqual({error,{unrecognized_option,gazonk}},
proper:quickcheck(rec_props_test1:prop_1(), [42,gazonk])),
?_assertTempBecomesN(300, true,
?FORALL(_, 1, begin inc_temp(), true end),
[{numtests,300}]),
?_assertTempBecomesN(300, true,
?FORALL(_, 1, begin inc_temp(), true end),
[300]),
?_failsWith([42], ?FORALL(T, any(), T < 42),
[any_to_integer,verbose,nocolors]),
?_failsWith([42], ?FORALL(I, integer(), I < 42),
[{numtests,4711}, {on_output,fun print_in_magenta/2}]),
?_failsWith([42], ?FORALL(_, ?SHRINK(42,[0,1]), false), [noshrink]),
?_failsWith([42], ?FORALL(_, ?SHRINK(42,[0,1]), false), [{max_shrinks,0}]),
?_fails(?FORALL(_, integer(), false), [fails]),
?_assertRun({error,{cant_generate,[{?MODULE,options_test_,0}]}},
?FORALL(_, ?SUCHTHAT(X, pos_integer(), X > 42), true),
[{constraint_tries,1}], true),
?_failsWith([12],
?FORALL(_, ?SIZED(Size, integer(Size, Size)), false),
[{start_size,12}])].
print_in_magenta(S, L) ->
io:format("\033[1;35m"++S++"\033[0m", L).
setup_prop() ->
?SETUP(fun () ->
put(setup_token, true),
fun () ->
erase(setup_token),
ok
end
end,
?FORALL(_, exactly(ok), get(setup_token))).
failing_setup_prop() ->
?SETUP(fun () ->
put(setup_token, true),
fun () ->
erase(setup_token),
ok
end
end,
?FORALL(_, exactly(ok), not get(setup_token))).
double_setup_prop() ->
?SETUP(fun () ->
put(setup_token2, true),
fun () ->
erase(setup_token2),
ok
end
end,
?SETUP(fun () ->
put(setup_token, true),
fun () ->
erase(setup_token),
ok
end
end,
?FORALL(_, exactly(ok),
get(setup_token) andalso get(setup_token2)))).
setup_test_() ->
[?_passes(setup_prop(), [10]),
?_assert(proper:quickcheck(setup_prop(), 10)
andalso undefined =:= get(setup_token)),
?_fails(failing_setup_prop(), [10]),
?_assert(not proper:quickcheck(failing_setup_prop(), [10, noshrink, quiet])
andalso undefined =:= get(setup_token)),
?_assert(proper:check(setup_prop(), [ok], 10)),
?_assert(proper:check(setup_prop(), [ok], 10)
andalso undefined =:= get(setup_token)),
?_assert(not proper:check(failing_setup_prop(), [ok], 10)),
?_assert(not proper:check(failing_setup_prop(), [ok], 10)
andalso undefined =:= get(setup_token)),
?_passes(double_setup_prop(), [10]),
?_assert(proper:quickcheck(double_setup_prop(), 10)
andalso undefined =:= get(setup_token)
andalso undefined =:= get(setup_token2)),
?_assert(proper:check(double_setup_prop(), [ok], 10)),
?_assert(true = proper:check(double_setup_prop(), [ok], 10)
andalso undefined =:= get(setup_token)
andalso undefined =:= get(setup_token2))].
adts1_test_() ->
for ' old laptop
?_passes(?FORALL({X,S},{integer(),sets:set(integer())},
sets:is_element(X,sets:add_element(X,S))), [20])}.
adts2_test_() ->
for 18.x ( and onwards ? )
?_passes(?FORALL({X,Y,D},
{integer(),float(),dict:dict(integer(),float())},
dict:fetch(X,dict:store(X,Y,eval(D))) =:= Y), [30])}.
adts3_test_() ->
{timeout, 60,
?_fails(?FORALL({X,D},
{boolean(),dict:dict(boolean(),integer())},
dict:erase(X, dict:store(X,42,D)) =:= D))}.
parameter_test_() ->
?_passes(?FORALL(List, [zero1(),zero2(),zero3(),zero4()],
begin
[?assertEqual(undefined, proper_types:parameter(P))
|| P <- [x1,x2,y2,x3,y3,x4,y4,v,w,z]],
lists:all(fun is_zero/1, List)
end)).
parameter_targeted_test_() ->
BaseType = ?LAZY(proper_types:parameter(param)),
UserNF = ?USERNF(BaseType, fun (_, _) -> BaseType end),
Type = proper_types:with_parameter(param, 1, UserNF),
?_passes(?FORALL_TARGETED(X, Type, X =:= 1)).
zip_test_() ->
[?_assertEqual(proper_statem:zip(X, Y), Expected)
|| {X,Y,Expected} <- lists_to_zip()].
command_names_test_() ->
[?_assertEqual(proper_statem:command_names(Cmds), Expected)
|| {Cmds,Expected} <- command_names()].
command_names_parallel1_test_() ->
[?_assertEqual(proper_statem:command_names({Cmds,[]}), Expected)
|| {Cmds,Expected} <- command_names()].
command_names_parallel2_test_() ->
[?_assertEqual(proper_statem:command_names({[],[Cmds]}), Expected)
|| {Cmds,Expected} <- command_names()].
command_names_parallel3_test_() ->
[?_assertEqual(proper_statem:command_names({Cmds,[Cmds]}), Expected++Expected)
|| {Cmds,Expected} <- command_names()].
command_names_parallel4_test_() ->
[?_assertEqual(proper_statem:command_names({Cmds,[Cmds,Cmds]}), Expected++Expected++Expected)
|| {Cmds,Expected} <- command_names()].
valid_cmds_test_() ->
[?_assert(proper_statem:is_valid(Mod, State, Cmds, Env))
|| {Mod,State,Cmds,_,_,Env} <- valid_command_sequences()].
invalid_cmds_test_() ->
[?_assertNot(proper_statem:is_valid(Mod, Mod:initial_state(), Cmds, []))
|| {Mod,Cmds,_,_} <- invalid_precondition()] ++
[?_assertNot(proper_statem:is_valid(Mod, Mod:initial_state(), Cmds, []))
|| {Mod,Cmds} <- invalid_var()].
state_after_test_() ->
[?_assertEqual(proper_statem:state_after(Mod, Cmds), StateAfter)
|| {Mod,_,Cmds,StateAfter,_,_} <- valid_command_sequences()].
cannot_generate_commands_test_() ->
[?_test(assert_cant_generate_cmds(proper_statem:commands(Mod), 6))
|| Mod <- [prec_false]].
can_generate_commands0_test_() ->
[?_test(assert_can_generate(proper_statem:commands(Mod), false))
|| Mod <- [pdict_statem]].
can_generate_commands1_test_() ->
[?_test(assert_can_generate(proper_statem:commands(Mod, StartState), false))
|| {Mod,StartState} <- [{pdict_statem,[{a,1},{b,1},{c,100}]}]].
can_generate_parallel_commands0_test_() ->
{timeout, 20,
[?_test(assert_can_generate(proper_statem:parallel_commands(Mod), false))
|| Mod <- [ets_counter]]}.
can_generate_parallel_commands1_test_() ->
{timeout, 20,
[?_test(assert_can_generate(
proper_statem:parallel_commands(Mod, Mod:initial_state()),
false))
|| Mod <- [ets_counter]]}.
seeded_runs_return_same_result_test_() ->
[?_test(assert_seeded_runs_return_same_result(proper_statem:commands(Mod)))
|| Mod <- [pdict_statem]].
run_valid_commands_test_() ->
[?_assertMatch({_H,DynState,ok}, setup_run_commands(Mod, Cmds, Env))
|| {Mod,_,Cmds,_,DynState,Env} <- valid_command_sequences()].
run_init_error_test_() ->
[?_assertMatch({_H,_S,initialization_error},
setup_run_commands(Mod, Cmds, Env))
|| {Mod,Cmds,Env,_Shrunk} <- symbolic_init_invalid_sequences()].
run_precondition_false_test_() ->
[?_assertMatch({_H,_S,{precondition,false}},
setup_run_commands(Mod, Cmds, Env))
|| {Mod,Cmds,Env,_Shrunk} <- invalid_precondition()].
run_postcondition_false_test_() ->
Mod = post_false,
Cmds = [{set,{var,1},{call,Mod,foo,[]}},
{set,{var,2},{call,Mod,bar,[]}},
{set,{var,3},{call,Mod,foo,[]}},
{set,{var,4},{call,Mod,bar,[]}},
{set,{var,5},{call,Mod,bar,[]}},
{set,{var,6},{call,Mod,foo,[]}}],
State = {state,5}, PostF = {postcondition,false},
[?_assertMatch({_H1,State,PostF}, run_commands(Mod, Cmds))].
run_statem_exceptions_test_() ->
Mod = error_statem,
Cmds = [{set,{var,1},{call,Mod,foo,[42]}}],
State = {state,0},
[?_assertMatch({_H,State,{exception,throw,badarg,_}},
run_commands(Mod, Cmds))].
get_next_test_() ->
[?_assertEqual(Expected,
proper_statem:get_next(L, Len, MaxIndex, Available, W, N))
|| {L, Len, MaxIndex, Available, W, N, Expected} <- combinations()].
mk_first_comb_test_() ->
[?_assertEqual(Expected, proper_statem:mk_first_comb(N, Len, W))
|| {N, Len, W, Expected} <- first_comb()].
args_not_defined_test() ->
[?_assertNot(proper_statem:args_defined(Args, SymbEnv))
|| {Args, SymbEnv} <- arguments_not_defined()].
command_props_test_() ->
{timeout, 150, [?_assertEqual([], proper:module(command_props))]}.
can_generate_fsm_commands_test_() ->
[?_test(assert_can_generate(proper_fsm:commands(Mod), false))
|| Mod <- [pdict_fsm, numbers_fsm]].
transition_target_test_() ->
{timeout, 20, [?_assertEqual([], proper:module(numbers_fsm))]}.
dollar_only_cp_test_() ->
?_assertEqual(
dollar_data(),
[K || K <- all_data(),
is_atom(K),
re:run(atom_to_list(K), ["^[$]"], [{capture,none}]) =:= match]).
sampleshrink_test_() ->
Gen = non_empty(?LET({N,Lst}, {range(0,5),list(a)}, lists:sublist(Lst, N))),
[{"Test type with restrain",
[{"Try another way to call shrinking (not sampleshrink)",
?_shrinksTo([a], Gen)},
?_test(proper_gen:sampleshrink(Gen))]}].
max_size_test() ->
?assert(lists:member({prop_identity,0},
perf_max_size:module_info(exports))),
run some tests with a small and a big max_size option
{Ts,true} = timer:tc(fun() -> max_size_test_aux(42) end),
{Tb,true} = timer:tc(fun() -> max_size_test_aux(16#ffffffff) end),
ensure that the test with the big max_size option does not take
?assert(2*Ts >= Tb).
max_size_test_aux(Size) ->
proper:quickcheck(perf_max_size:prop_identity(), [5,{max_size,Size}]).
Erlang abstract code tests
erlang_abstract_code_test_() ->
M = erlang_abstract_code_test,
Props = [bits, expr, guard, term, module],
Opts = [{numtests, 200}, noshrink],
{timeout, 42,
[?_assertEqual(true, proper:quickcheck(M:Prop(), Opts)) || Prop <- Props]}.
no_duplicates(L) ->
length(lists:usort(L)) =:= length(L).
is_sorted([]) -> true;
is_sorted([_]) -> true;
is_sorted([A | [B|_] = T]) when A =< B -> is_sorted(T);
is_sorted(_) -> false.
same_elements(L1, L2) ->
length(L1) =:= length(L2) andalso same_elems(L1, L2).
same_elems([], []) ->
true;
same_elems([H|T], L) ->
lists:member(H, L) andalso same_elems(T, lists:delete(H, L));
same_elems(_, _) ->
false.
is_sorted(Old, New) ->
same_elements(Old, New) andalso is_sorted(New).
equal_ignoring_ws(Str1, Str2) ->
WhiteSpace = [32,9,10],
equal_ignoring_chars(Str1, Str2, WhiteSpace).
equal_ignoring_chars([], [], _Ignore) ->
true;
equal_ignoring_chars([Ch1|Rest1], [Ch2|Rest2], Ignore) when Ch1 =:= Ch2 ->
equal_ignoring_chars(Rest1, Rest2, Ignore);
equal_ignoring_chars([Ch1|Rest1] = Str1, [Ch2|Rest2] = Str2, Ignore) ->
case lists:member(Ch1, Ignore) of
true ->
equal_ignoring_chars(Rest1, Str2, Ignore);
false ->
case lists:member(Ch2, Ignore) of
true ->
equal_ignoring_chars(Str1, Rest2, Ignore);
false ->
false
end
end.
smaller_lengths_than_my_own(L) ->
lists:seq(0, length(L)).
is_zero(X) -> X =:= 0.
partition(Pivot, List) ->
partition_tr(Pivot, List, [], []).
partition_tr(_Pivot, [], Lower, Higher) ->
{Lower, Higher};
partition_tr(Pivot, [H|T], Lower, Higher) ->
case H =< Pivot of
true -> partition_tr(Pivot, T, [H|Lower], Higher);
false -> partition_tr(Pivot, T, Lower, [H|Higher])
end.
quicksort([]) -> [];
quicksort([H|T]) ->
{Lower, Higher} = partition(H, T),
quicksort(Lower) ++ [H] ++ quicksort(Higher).
creator(X) ->
Self = self(),
spawn_link(fun() -> destroyer(X,Self) end),
receive
_ -> ok
end.
destroyer(X, Father) ->
case X < 20 of
true -> Father ! not_yet;
false -> exit(this_is_the_end)
end.
Datatypes to test
shuffle([]) ->
[];
shuffle(L) ->
?LET(X, elements(L), [X | shuffle(lists:delete(X,L))]).
ulist(ElemType) ->
?LET(L, list(ElemType), L--(L--lists:usort(L))).
zerostream(ExpectedMeanLen) ->
?LAZY(frequency([
{1, []},
{ExpectedMeanLen, [0 | zerostream(ExpectedMeanLen)]}
])).
-type my_native_type() :: integer().
my_proper_type() -> atom().
-type type_and_fun() :: integer().
type_and_fun() -> atom().
-type type_only() :: integer().
-type id(X) :: X.
-type lof() :: [float()].
-type deeplist() :: [deeplist()].
deeplist() ->
?SIZED(Size, deeplist(Size)).
deeplist(0) ->
[];
deeplist(Size) ->
?LAZY(proper_types:distlist(Size, fun deeplist/1, false)).
-type tree(T) :: 'null' | {'node',T,tree(T),tree(T)}.
tree(ElemType) ->
?SIZED(Size, tree(ElemType,Size)).
tree(_ElemType, 0) ->
null;
tree(ElemType, Size) ->
LeftTree = tree(ElemType, Size div 2),
RightTree = tree(ElemType, Size div 2),
frequency([
{1, tree(ElemType,0)},
{5, ?LETSHRINK([L,R], [LeftTree,RightTree], {node,ElemType,L,R})}
]).
-type a() :: 'aleaf' | {'anode',a(),b()}.
-type b() :: 'bleaf' | {'bnode',a(),b()}.
a() ->
?SIZED(Size, a(Size)).
a(0) ->
aleaf;
a(Size) ->
union([
?LAZY(a(0)),
?LAZY(?LETSHRINK([A], [a(Size div 2)], {anode,A,b(Size)}))
]).
b() ->
?SIZED(Size, b(Size)).
b(0) ->
bleaf;
b(Size) ->
union([
?LAZY(b(0)),
?LAZY(?LETSHRINK([B], [b(Size div 2)], {bnode,a(Size),B}))
]).
-type gen_tree(T) :: 'null' | {T,[gen_tree(T),...]}.
gen_tree(ElemType) ->
?SIZED(Size, gen_tree(ElemType,Size)).
gen_tree(_ElemType, 0) ->
null;
gen_tree(ElemType, Size) ->
SubGen = fun(S) -> gen_tree(ElemType,S) end,
oneof([
?LAZY(gen_tree(ElemType,0)),
?LAZY(?LETSHRINK(Children, proper_types:distlist(Size, SubGen, true),
{ElemType,Children}))
]).
-type g() :: 'null' | {'tag',[g()]}.
-type h() :: 'null' | {'tag',[{'ok',h()}]}.
-type i() :: 'null' | {'tag',i(),[i()]}.
-type j() :: 'null' | {'one',j()} | {'tag',j(),j(),[j()],[j()]}.
-type k() :: 'null' | {'tag',[{k(),k()}]}.
-type l() :: 'null' | {'tag',l(),[l(),...]}.
zero1() ->
proper_types:with_parameter(
x1, 0, ?SUCHTHAT(I, range(-1, 1), I =:= proper_types:parameter(x1))).
zero2() ->
proper_types:with_parameters(
[{x2,41}],
?LET(X,
proper_types:with_parameter(
y2, 43,
?SUCHTHAT(
I, range(41, 43),
I > proper_types:parameter(x2)
andalso I < proper_types:parameter(y2))),
X - 42)).
zero3() ->
?SUCHTHAT(I, range(-1, 1),
I > proper_types:parameter(x3, -1)
andalso I < proper_types:parameter(y3, 1)).
zero4() ->
proper_types:with_parameters(
[{x4,-2}, {y4,2}],
proper_types:with_parameters(
[{x4,-1}, {y4,1}],
?SUCHTHAT(I, range(-1, 1),
I > proper_types:parameter(x4)
andalso I < proper_types:parameter(y4)))).
? , ElemType , not lists : member(E , Rest ) ) ,
? ,
? SUCHTHAT(L , list(ElemType ) , no_duplicates(L ) ) .
kvlist(KeyType , ValueType ) - >
[ { K , ValueType } || K < - Keys ] ) .
symbdict(KeyType , ValueType ) - >
? SIZED(Size , symbdict(Size , KeyType , ValueType ) ) .
symbdict(0 , _ KeyType , _ ValueType ) - >
symbdict(Size , KeyType , ValueType ) - >
{ 1,symbdict(0 , KeyType , ValueType ) } ,
{ 4,?LETSHRINK([Smaller ] , [ symbdict(Size - 1 , KeyType , ValueType ) ] ,
{ call , dict , append,[KeyType , ValueType , Smaller ] } ) }
? ,
erlang : element(1,T ) = /= 42 ) ;
? FORALL(L , kvlist(atom(),integer ( ) ) , not lists : ) ) ;
? , non_empty(list(integer ( ) ) ) , list(oneof(L ) ) ) ,
length(X ) < 10 ) ;
not dict : is_key(42 , eval(SD ) ) ) ;
? , L } ,
lists : all(fun(X ) - > F(X ) = /= 42 end , L ) ) ;
correct_smaller_length_aggregation(Tests , ) - >
{ Zeros , Larger } = lists : partition(fun(X ) - > X = : = 0 end , ) ,
andalso correct_smaller_length_aggregation(Tests , Larger , 1 ) .
correct_smaller_length_aggregation(0 , SmallerLens , _
correct_smaller_length_aggregation(NotMoreThan , SmallerLens , ) - >
{ Lens , Larger } = lists : partition(fun(X ) - > X = : = , ) ,
|
1d1863f610d864d69b7785584ccbc5c9c615f4022ae5956487975bd031717ca5 | sorawee/helpful | suggest.rkt | #lang racket/base
(provide suggest)
(require racket/match
racket/list
racket/string
levenshtein
"doc.rkt")
;; find-closest :: string? (listof string?) -> (or/c string? #f)
(define (find-closest id xs)
(match xs
;; in a #lang that has empty namespace, empty xs might be possible
['() #f]
[_ (argmin (λ (x) (string-levenshtein id x)) xs)]))
;; get-locals :: identifier? -> (hash/c symbol? #t)
(define (get-locals x)
(for/hasheq ([v (in-list (syntax-bound-symbols x))]
#:do [(define local?
(match (identifier-binding (datum->syntax x v))
['lexical #t]
[(list (app module-path-index-split mp _) _ _ _ _ _ _)
(not mp)]
[_ #f]))]
#:when local?)
(values v #t)))
get - all - vars : : identifier ? - > ( symbol ? )
(define (get-all-vars x)
(define locals (get-locals x))
(define-values (pre post)
(partition (λ (x) (hash-ref locals x #f)) (syntax-bound-symbols x)))
;; prioritize non-required identifiers
(append (sort pre symbol<?) (sort post symbol<?)))
;; import->string :: (listof symbol?) #:before-first string? -> string?
(define (import->string import #:before-first [before-first ""])
(string-join (for/list ([x (in-list import)])
(format "`~a'" x))
" or "
#:before-first before-first))
imports->string : : ( listof ( listof symbol ? ) ) - > string ?
(define (imports->string imports)
(string-join
(for/list ([import (in-list imports)])
(import->string import #:before-first " "))
"\n"))
;; suggest :: identifier? #:closest? boolean? #:import? boolean? -> none/c
(define (suggest x
#:closest? [closest? #t]
#:import? [import? #t])
(define closest
(and closest?
(find-closest (symbol->string (syntax-e x))
(map symbol->string (get-all-vars x)))))
(define imports (and import? (find-entry (syntax-e x))))
(cond
[(or closest imports)
(raise-syntax-error
#f "unbound identifier" x #f null
(format
"\n ~a~a~a"
(cond
[closest (format "suggestion: do you mean `~a'?" closest)]
[else ""])
(cond
[(and closest imports) "\n alternative suggestion: "]
[imports "suggestion: "]
[else ""])
(match imports
[#f ""]
[(list import)
(format "do you want to import ~a, which provides the identifier?"
(import->string import))]
[_
(format
"do you want to import ~a, which provides the identifier?\n~a"
"one of the following modules"
(imports->string imports))]))
#:exn exn:fail:syntax:unbound)]
[else
(raise-syntax-error
#f "unbound identifier" x
#:exn exn:fail:syntax:unbound)]))
| null | https://raw.githubusercontent.com/sorawee/helpful/47e4bf05db259208321105f653ea4bc975cd42cb/suggest.rkt | racket | find-closest :: string? (listof string?) -> (or/c string? #f)
in a #lang that has empty namespace, empty xs might be possible
get-locals :: identifier? -> (hash/c symbol? #t)
prioritize non-required identifiers
import->string :: (listof symbol?) #:before-first string? -> string?
suggest :: identifier? #:closest? boolean? #:import? boolean? -> none/c | #lang racket/base
(provide suggest)
(require racket/match
racket/list
racket/string
levenshtein
"doc.rkt")
(define (find-closest id xs)
(match xs
['() #f]
[_ (argmin (λ (x) (string-levenshtein id x)) xs)]))
(define (get-locals x)
(for/hasheq ([v (in-list (syntax-bound-symbols x))]
#:do [(define local?
(match (identifier-binding (datum->syntax x v))
['lexical #t]
[(list (app module-path-index-split mp _) _ _ _ _ _ _)
(not mp)]
[_ #f]))]
#:when local?)
(values v #t)))
get - all - vars : : identifier ? - > ( symbol ? )
(define (get-all-vars x)
(define locals (get-locals x))
(define-values (pre post)
(partition (λ (x) (hash-ref locals x #f)) (syntax-bound-symbols x)))
(append (sort pre symbol<?) (sort post symbol<?)))
(define (import->string import #:before-first [before-first ""])
(string-join (for/list ([x (in-list import)])
(format "`~a'" x))
" or "
#:before-first before-first))
imports->string : : ( listof ( listof symbol ? ) ) - > string ?
(define (imports->string imports)
(string-join
(for/list ([import (in-list imports)])
(import->string import #:before-first " "))
"\n"))
(define (suggest x
#:closest? [closest? #t]
#:import? [import? #t])
(define closest
(and closest?
(find-closest (symbol->string (syntax-e x))
(map symbol->string (get-all-vars x)))))
(define imports (and import? (find-entry (syntax-e x))))
(cond
[(or closest imports)
(raise-syntax-error
#f "unbound identifier" x #f null
(format
"\n ~a~a~a"
(cond
[closest (format "suggestion: do you mean `~a'?" closest)]
[else ""])
(cond
[(and closest imports) "\n alternative suggestion: "]
[imports "suggestion: "]
[else ""])
(match imports
[#f ""]
[(list import)
(format "do you want to import ~a, which provides the identifier?"
(import->string import))]
[_
(format
"do you want to import ~a, which provides the identifier?\n~a"
"one of the following modules"
(imports->string imports))]))
#:exn exn:fail:syntax:unbound)]
[else
(raise-syntax-error
#f "unbound identifier" x
#:exn exn:fail:syntax:unbound)]))
|
9c8e8b00bf3d0db71ccda9b8625ed0044c586fdb54922e544a5609878bf6f191 | haskell-numerics/random-fu | Weibull.hs | # LANGUAGE MultiParamTypeClasses , FlexibleInstances , UndecidableInstances , FlexibleContexts #
module Data.Random.Distribution.Weibull where
import Data.Random.Distribution
import Data.Random.Distribution.Uniform
data Weibull a = Weibull { weibullLambda :: !a, weibullK :: !a }
deriving (Eq, Show)
instance (Floating a, Distribution StdUniform a) => Distribution Weibull a where
rvarT (Weibull lambda k) = do
u <- rvarT StdUniform
return (lambda * (negate (log u)) ** recip k)
instance (Real a, Distribution Weibull a) => CDF Weibull a where
cdf (Weibull lambda k) x = 1 - exp (negate ((realToFrac x / realToFrac lambda) ** realToFrac k))
| null | https://raw.githubusercontent.com/haskell-numerics/random-fu/18a6ba6b29c7ca3b3ff34ea6ca0eca910da72726/random-fu/src/Data/Random/Distribution/Weibull.hs | haskell | # LANGUAGE MultiParamTypeClasses , FlexibleInstances , UndecidableInstances , FlexibleContexts #
module Data.Random.Distribution.Weibull where
import Data.Random.Distribution
import Data.Random.Distribution.Uniform
data Weibull a = Weibull { weibullLambda :: !a, weibullK :: !a }
deriving (Eq, Show)
instance (Floating a, Distribution StdUniform a) => Distribution Weibull a where
rvarT (Weibull lambda k) = do
u <- rvarT StdUniform
return (lambda * (negate (log u)) ** recip k)
instance (Real a, Distribution Weibull a) => CDF Weibull a where
cdf (Weibull lambda k) x = 1 - exp (negate ((realToFrac x / realToFrac lambda) ** realToFrac k))
| |
64ec33a106f54e384bd1ec3fab045260e2cde4fd6e90f5f87264a57cfbf10a37 | brendanhay/gogol | Product.hs | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE PatternSynonyms #
# LANGUAGE RecordWildCards #
{-# LANGUAGE StrictData #-}
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - duplicate - exports #
# OPTIONS_GHC -fno - warn - name - shadowing #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
-- |
Module : . AppsCalendar . Internal . Product
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
-- Stability : auto-generated
Portability : non - portable ( GHC extensions )
module Gogol.AppsCalendar.Internal.Product
*
Acl (..),
newAcl,
-- * AclRule
AclRule (..),
newAclRule,
-- * AclRule_Scope
AclRule_Scope (..),
newAclRule_Scope,
-- * Calendar
Calendar (..),
newCalendar,
* CalendarList
CalendarList (..),
newCalendarList,
-- * CalendarListEntry
CalendarListEntry (..),
newCalendarListEntry,
-- * CalendarListEntry_NotificationSettings
CalendarListEntry_NotificationSettings (..),
newCalendarListEntry_NotificationSettings,
* CalendarNotification
CalendarNotification (..),
newCalendarNotification,
-- * Channel
Channel (..),
newChannel,
-- * Channel_Params
Channel_Params (..),
newChannel_Params,
-- * ColorDefinition
ColorDefinition (..),
newColorDefinition,
-- * Colors
Colors (..),
newColors,
* Colors_Calendar
Colors_Calendar (..),
newColors_Calendar,
-- * Colors_Event
Colors_Event (..),
newColors_Event,
* ConferenceData
ConferenceData (..),
newConferenceData,
-- * ConferenceParameters
ConferenceParameters (..),
newConferenceParameters,
-- * ConferenceParametersAddOnParameters
ConferenceParametersAddOnParameters (..),
newConferenceParametersAddOnParameters,
-- * ConferenceParametersAddOnParameters_Parameters
ConferenceParametersAddOnParameters_Parameters (..),
newConferenceParametersAddOnParameters_Parameters,
-- * ConferenceProperties
ConferenceProperties (..),
newConferenceProperties,
* ConferenceRequestStatus
ConferenceRequestStatus (..),
newConferenceRequestStatus,
-- * ConferenceSolution
ConferenceSolution (..),
newConferenceSolution,
-- * ConferenceSolutionKey
ConferenceSolutionKey (..),
newConferenceSolutionKey,
* CreateConferenceRequest
CreateConferenceRequest (..),
newCreateConferenceRequest,
-- * EntryPoint
EntryPoint (..),
newEntryPoint,
-- * Error'
Error' (..),
newError,
-- * Event
Event (..),
newEvent,
-- * Event_Creator
Event_Creator (..),
newEvent_Creator,
* Event_ExtendedProperties
Event_ExtendedProperties (..),
newEvent_ExtendedProperties,
-- * Event_ExtendedProperties_Private
Event_ExtendedProperties_Private (..),
newEvent_ExtendedProperties_Private,
-- * Event_ExtendedProperties_Shared
Event_ExtendedProperties_Shared (..),
newEvent_ExtendedProperties_Shared,
-- * Event_Gadget
Event_Gadget (..),
newEvent_Gadget,
-- * Event_Gadget_Preferences
Event_Gadget_Preferences (..),
newEvent_Gadget_Preferences,
-- * Event_Organizer
Event_Organizer (..),
newEvent_Organizer,
-- * Event_Reminders
Event_Reminders (..),
newEvent_Reminders,
-- * Event_Source
Event_Source (..),
newEvent_Source,
-- * EventAttachment
EventAttachment (..),
newEventAttachment,
* EventAttendee
EventAttendee (..),
newEventAttendee,
-- * EventDateTime
EventDateTime (..),
newEventDateTime,
-- * EventReminder
EventReminder (..),
newEventReminder,
-- * Events
Events (..),
newEvents,
-- * FreeBusyCalendar
FreeBusyCalendar (..),
newFreeBusyCalendar,
-- * FreeBusyGroup
FreeBusyGroup (..),
newFreeBusyGroup,
-- * FreeBusyRequest
FreeBusyRequest (..),
newFreeBusyRequest,
*
FreeBusyRequestItem (..),
newFreeBusyRequestItem,
*
FreeBusyResponse (..),
newFreeBusyResponse,
-- * FreeBusyResponse_Calendars
FreeBusyResponse_Calendars (..),
newFreeBusyResponse_Calendars,
-- * FreeBusyResponse_Groups
FreeBusyResponse_Groups (..),
newFreeBusyResponse_Groups,
-- * Setting
Setting (..),
newSetting,
-- * Settings
Settings (..),
newSettings,
-- * TimePeriod
TimePeriod (..),
newTimePeriod,
)
where
import Gogol.AppsCalendar.Internal.Sum
import qualified Gogol.Prelude as Core
--
-- /See:/ 'newAcl' smart constructor.
data Acl = Acl
{ -- | ETag of the collection.
etag :: (Core.Maybe Core.Text),
-- | List of rules on the access control list.
items :: (Core.Maybe [AclRule]),
-- | Type of the collection (\"calendar#acl\").
kind :: Core.Text,
| Token used to access the next page of this result . Omitted if no further results are available , in which case nextSyncToken is provided .
nextPageToken :: (Core.Maybe Core.Text),
| Token used at a later point in time to retrieve only the entries that have changed since this result was returned . Omitted if further results are available , in which case is provided .
nextSyncToken :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' ' with the minimum fields required to make a request .
newAcl ::
Acl
newAcl =
Acl
{ etag = Core.Nothing,
items = Core.Nothing,
kind = "calendar#acl",
nextPageToken = Core.Nothing,
nextSyncToken = Core.Nothing
}
instance Core.FromJSON Acl where
parseJSON =
Core.withObject
"Acl"
( \o ->
Acl
Core.<$> (o Core..:? "etag")
Core.<*> (o Core..:? "items")
Core.<*> (o Core..:? "kind" Core..!= "calendar#acl")
Core.<*> (o Core..:? "nextPageToken")
Core.<*> (o Core..:? "nextSyncToken")
)
instance Core.ToJSON Acl where
toJSON Acl {..} =
Core.object
( Core.catMaybes
[ ("etag" Core..=) Core.<$> etag,
("items" Core..=) Core.<$> items,
Core.Just ("kind" Core..= kind),
("nextPageToken" Core..=) Core.<$> nextPageToken,
("nextSyncToken" Core..=) Core.<$> nextSyncToken
]
)
--
-- /See:/ 'newAclRule' smart constructor.
data AclRule = AclRule
{ -- | ETag of the resource.
etag :: (Core.Maybe Core.Text),
| Identifier of the Access Control List ( ACL ) rule . See calendars .
id :: (Core.Maybe Core.Text),
-- | Type of the resource (\"calendar#aclRule\").
kind :: Core.Text,
-- | The role assigned to the scope. Possible values are:
- \"none\ " - Provides no access . - \"freeBusyReader\ " - Provides read access to free\/busy information . - \"reader\ " - Provides read access to the calendar . Private events will appear to users with reader access , but event details will be hidden . - \"writer\ " - Provides read and write access to the calendar . Private events will appear to users with writer access , and event details will be visible . - \"owner\ " - Provides ownership of the calendar . This role has all of the permissions of the writer role with the additional ability to see and manipulate ACLs .
role' :: (Core.Maybe Core.Text),
| The extent to which calendar access is granted by this ACL rule .
scope :: (Core.Maybe AclRule_Scope)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'AclRule' with the minimum fields required to make a request.
newAclRule ::
AclRule
newAclRule =
AclRule
{ etag = Core.Nothing,
id = Core.Nothing,
kind = "calendar#aclRule",
role' = Core.Nothing,
scope = Core.Nothing
}
instance Core.FromJSON AclRule where
parseJSON =
Core.withObject
"AclRule"
( \o ->
AclRule
Core.<$> (o Core..:? "etag")
Core.<*> (o Core..:? "id")
Core.<*> (o Core..:? "kind" Core..!= "calendar#aclRule")
Core.<*> (o Core..:? "role")
Core.<*> (o Core..:? "scope")
)
instance Core.ToJSON AclRule where
toJSON AclRule {..} =
Core.object
( Core.catMaybes
[ ("etag" Core..=) Core.<$> etag,
("id" Core..=) Core.<$> id,
Core.Just ("kind" Core..= kind),
("role" Core..=) Core.<$> role',
("scope" Core..=) Core.<$> scope
]
)
| The extent to which calendar access is granted by this ACL rule .
--
-- /See:/ 'newAclRule_Scope' smart constructor.
data AclRule_Scope = AclRule_Scope
{ -- | The type of the scope. Possible values are:
-- - \"default\" - The public scope. This is the default value. - \"user\" - Limits the scope to a single user. - \"group\" - Limits the scope to a group. - \"domain\" - Limits the scope to a domain. Note: The permissions granted to the \"default\", or public, scope apply to any user, authenticated or not.
type' :: (Core.Maybe Core.Text),
-- | The email address of a user or group, or the name of a domain, depending on the scope type. Omitted for type \"default\".
value :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' AclRule_Scope ' with the minimum fields required to make a request .
newAclRule_Scope ::
AclRule_Scope
newAclRule_Scope = AclRule_Scope {type' = Core.Nothing, value = Core.Nothing}
instance Core.FromJSON AclRule_Scope where
parseJSON =
Core.withObject
"AclRule_Scope"
( \o ->
AclRule_Scope
Core.<$> (o Core..:? "type") Core.<*> (o Core..:? "value")
)
instance Core.ToJSON AclRule_Scope where
toJSON AclRule_Scope {..} =
Core.object
( Core.catMaybes
[ ("type" Core..=) Core.<$> type',
("value" Core..=) Core.<$> value
]
)
--
/See:/ ' newCalendar ' smart constructor .
data Calendar = Calendar
{ -- | Conferencing properties for this calendar, for example what types of conferences are allowed.
conferenceProperties :: (Core.Maybe ConferenceProperties),
-- | Description of the calendar. Optional.
description :: (Core.Maybe Core.Text),
-- | ETag of the resource.
etag :: (Core.Maybe Core.Text),
| Identifier of the calendar . To retrieve IDs call the calendarList.list ( ) method .
id :: (Core.Maybe Core.Text),
-- | Type of the resource (\"calendar#calendar\").
kind :: Core.Text,
-- | Geographic location of the calendar as free-form text. Optional.
location :: (Core.Maybe Core.Text),
-- | Title of the calendar.
summary :: (Core.Maybe Core.Text),
-- | The time zone of the calendar. (Formatted as an IANA Time Zone Database name, e.g. \"Europe\/Zurich\".) Optional.
timeZone :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Calendar' with the minimum fields required to make a request.
newCalendar ::
Calendar
newCalendar =
Calendar
{ conferenceProperties = Core.Nothing,
description = Core.Nothing,
etag = Core.Nothing,
id = Core.Nothing,
kind = "calendar#calendar",
location = Core.Nothing,
summary = Core.Nothing,
timeZone = Core.Nothing
}
instance Core.FromJSON Calendar where
parseJSON =
Core.withObject
"Calendar"
( \o ->
Calendar
Core.<$> (o Core..:? "conferenceProperties")
Core.<*> (o Core..:? "description")
Core.<*> (o Core..:? "etag")
Core.<*> (o Core..:? "id")
Core.<*> (o Core..:? "kind" Core..!= "calendar#calendar")
Core.<*> (o Core..:? "location")
Core.<*> (o Core..:? "summary")
Core.<*> (o Core..:? "timeZone")
)
instance Core.ToJSON Calendar where
toJSON Calendar {..} =
Core.object
( Core.catMaybes
[ ("conferenceProperties" Core..=)
Core.<$> conferenceProperties,
("description" Core..=) Core.<$> description,
("etag" Core..=) Core.<$> etag,
("id" Core..=) Core.<$> id,
Core.Just ("kind" Core..= kind),
("location" Core..=) Core.<$> location,
("summary" Core..=) Core.<$> summary,
("timeZone" Core..=) Core.<$> timeZone
]
)
--
-- /See:/ 'newCalendarList' smart constructor.
data CalendarList = CalendarList
{ -- | ETag of the collection.
etag :: (Core.Maybe Core.Text),
-- | Calendars that are present on the user\'s calendar list.
items :: (Core.Maybe [CalendarListEntry]),
-- | Type of the collection (\"calendar#calendarList\").
kind :: Core.Text,
| Token used to access the next page of this result . Omitted if no further results are available , in which case nextSyncToken is provided .
nextPageToken :: (Core.Maybe Core.Text),
| Token used at a later point in time to retrieve only the entries that have changed since this result was returned . Omitted if further results are available , in which case is provided .
nextSyncToken :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'CalendarList' with the minimum fields required to make a request.
newCalendarList ::
CalendarList
newCalendarList =
CalendarList
{ etag = Core.Nothing,
items = Core.Nothing,
kind = "calendar#calendarList",
nextPageToken = Core.Nothing,
nextSyncToken = Core.Nothing
}
instance Core.FromJSON CalendarList where
parseJSON =
Core.withObject
"CalendarList"
( \o ->
CalendarList
Core.<$> (o Core..:? "etag")
Core.<*> (o Core..:? "items")
Core.<*> (o Core..:? "kind" Core..!= "calendar#calendarList")
Core.<*> (o Core..:? "nextPageToken")
Core.<*> (o Core..:? "nextSyncToken")
)
instance Core.ToJSON CalendarList where
toJSON CalendarList {..} =
Core.object
( Core.catMaybes
[ ("etag" Core..=) Core.<$> etag,
("items" Core..=) Core.<$> items,
Core.Just ("kind" Core..= kind),
("nextPageToken" Core..=) Core.<$> nextPageToken,
("nextSyncToken" Core..=) Core.<$> nextSyncToken
]
)
--
-- /See:/ 'newCalendarListEntry' smart constructor.
data CalendarListEntry = CalendarListEntry
{ -- | The effective access role that the authenticated user has on the calendar. Read-only. Possible values are:
- \"freeBusyReader\ " - Provides read access to free\/busy information . - \"reader\ " - Provides read access to the calendar . Private events will appear to users with reader access , but event details will be hidden . - \"writer\ " - Provides read and write access to the calendar . Private events will appear to users with writer access , and event details will be visible . - \"owner\ " - Provides ownership of the calendar . This role has all of the permissions of the writer role with the additional ability to see and manipulate ACLs .
accessRole :: (Core.Maybe Core.Text),
-- | The main color of the calendar in the hexadecimal format \"#0088aa\". This property supersedes the index-based colorId property. To set or change this property, you need to specify colorRgbFormat=true in the parameters of the insert, update and patch methods. Optional.
backgroundColor :: (Core.Maybe Core.Text),
| The color of the calendar . This is an ID referring to an entry in the calendar section of the colors definition ( see the colors endpoint ) . This property is superseded by the backgroundColor and foregroundColor properties and can be ignored when using these properties . Optional .
colorId :: (Core.Maybe Core.Text),
-- | Conferencing properties for this calendar, for example what types of conferences are allowed.
conferenceProperties :: (Core.Maybe ConferenceProperties),
-- | The default reminders that the authenticated user has for this calendar.
defaultReminders :: (Core.Maybe [EventReminder]),
-- | Whether this calendar list entry has been deleted from the calendar list. Read-only. Optional. The default is False.
deleted :: Core.Bool,
-- | Description of the calendar. Optional. Read-only.
description :: (Core.Maybe Core.Text),
-- | ETag of the resource.
etag :: (Core.Maybe Core.Text),
-- | The foreground color of the calendar in the hexadecimal format \"#ffffff\". This property supersedes the index-based colorId property. To set or change this property, you need to specify colorRgbFormat=true in the parameters of the insert, update and patch methods. Optional.
foregroundColor :: (Core.Maybe Core.Text),
-- | Whether the calendar has been hidden from the list. Optional. The attribute is only returned when the calendar is hidden, in which case the value is true.
hidden :: Core.Bool,
-- | Identifier of the calendar.
id :: (Core.Maybe Core.Text),
-- | Type of the resource (\"calendar#calendarListEntry\").
kind :: Core.Text,
-- | Geographic location of the calendar as free-form text. Optional. Read-only.
location :: (Core.Maybe Core.Text),
-- | The notifications that the authenticated user is receiving for this calendar.
notificationSettings :: (Core.Maybe CalendarListEntry_NotificationSettings),
-- | Whether the calendar is the primary calendar of the authenticated user. Read-only. Optional. The default is False.
primary :: Core.Bool,
-- | Whether the calendar content shows up in the calendar UI. Optional. The default is False.
selected :: Core.Bool,
-- | Title of the calendar. Read-only.
summary :: (Core.Maybe Core.Text),
-- | The summary that the authenticated user has set for this calendar. Optional.
summaryOverride :: (Core.Maybe Core.Text),
-- | The time zone of the calendar. Optional. Read-only.
timeZone :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'CalendarListEntry' with the minimum fields required to make a request.
newCalendarListEntry ::
CalendarListEntry
newCalendarListEntry =
CalendarListEntry
{ accessRole = Core.Nothing,
backgroundColor = Core.Nothing,
colorId = Core.Nothing,
conferenceProperties = Core.Nothing,
defaultReminders = Core.Nothing,
deleted = Core.False,
description = Core.Nothing,
etag = Core.Nothing,
foregroundColor = Core.Nothing,
hidden = Core.False,
id = Core.Nothing,
kind = "calendar#calendarListEntry",
location = Core.Nothing,
notificationSettings = Core.Nothing,
primary = Core.False,
selected = Core.False,
summary = Core.Nothing,
summaryOverride = Core.Nothing,
timeZone = Core.Nothing
}
instance Core.FromJSON CalendarListEntry where
parseJSON =
Core.withObject
"CalendarListEntry"
( \o ->
CalendarListEntry
Core.<$> (o Core..:? "accessRole")
Core.<*> (o Core..:? "backgroundColor")
Core.<*> (o Core..:? "colorId")
Core.<*> (o Core..:? "conferenceProperties")
Core.<*> (o Core..:? "defaultReminders")
Core.<*> (o Core..:? "deleted" Core..!= Core.False)
Core.<*> (o Core..:? "description")
Core.<*> (o Core..:? "etag")
Core.<*> (o Core..:? "foregroundColor")
Core.<*> (o Core..:? "hidden" Core..!= Core.False)
Core.<*> (o Core..:? "id")
Core.<*> ( o Core..:? "kind"
Core..!= "calendar#calendarListEntry"
)
Core.<*> (o Core..:? "location")
Core.<*> (o Core..:? "notificationSettings")
Core.<*> (o Core..:? "primary" Core..!= Core.False)
Core.<*> (o Core..:? "selected" Core..!= Core.False)
Core.<*> (o Core..:? "summary")
Core.<*> (o Core..:? "summaryOverride")
Core.<*> (o Core..:? "timeZone")
)
instance Core.ToJSON CalendarListEntry where
toJSON CalendarListEntry {..} =
Core.object
( Core.catMaybes
[ ("accessRole" Core..=) Core.<$> accessRole,
("backgroundColor" Core..=) Core.<$> backgroundColor,
("colorId" Core..=) Core.<$> colorId,
("conferenceProperties" Core..=)
Core.<$> conferenceProperties,
("defaultReminders" Core..=)
Core.<$> defaultReminders,
Core.Just ("deleted" Core..= deleted),
("description" Core..=) Core.<$> description,
("etag" Core..=) Core.<$> etag,
("foregroundColor" Core..=) Core.<$> foregroundColor,
Core.Just ("hidden" Core..= hidden),
("id" Core..=) Core.<$> id,
Core.Just ("kind" Core..= kind),
("location" Core..=) Core.<$> location,
("notificationSettings" Core..=)
Core.<$> notificationSettings,
Core.Just ("primary" Core..= primary),
Core.Just ("selected" Core..= selected),
("summary" Core..=) Core.<$> summary,
("summaryOverride" Core..=) Core.<$> summaryOverride,
("timeZone" Core..=) Core.<$> timeZone
]
)
-- | The notifications that the authenticated user is receiving for this calendar.
--
-- /See:/ 'newCalendarListEntry_NotificationSettings' smart constructor.
newtype CalendarListEntry_NotificationSettings = CalendarListEntry_NotificationSettings
{ -- | The list of notifications set for this calendar.
notifications :: (Core.Maybe [CalendarNotification])
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'CalendarListEntry_NotificationSettings' with the minimum fields required to make a request.
newCalendarListEntry_NotificationSettings ::
CalendarListEntry_NotificationSettings
newCalendarListEntry_NotificationSettings =
CalendarListEntry_NotificationSettings {notifications = Core.Nothing}
instance
Core.FromJSON
CalendarListEntry_NotificationSettings
where
parseJSON =
Core.withObject
"CalendarListEntry_NotificationSettings"
( \o ->
CalendarListEntry_NotificationSettings
Core.<$> (o Core..:? "notifications")
)
instance
Core.ToJSON
CalendarListEntry_NotificationSettings
where
toJSON CalendarListEntry_NotificationSettings {..} =
Core.object
( Core.catMaybes
[("notifications" Core..=) Core.<$> notifications]
)
--
-- /See:/ 'newCalendarNotification' smart constructor.
data CalendarNotification = CalendarNotification
{ -- | The method used to deliver the notification. The possible value is:
-- - \"email\" - Notifications are sent via email.
-- Required when adding a notification.
method :: (Core.Maybe Core.Text),
-- | The type of notification. Possible values are:
- \"eventCreation\ " - Notification sent when a new event is put on the calendar . - \"eventChange\ " - Notification sent when an event is changed . - \"eventCancellation\ " - Notification sent when an event is cancelled . - \"eventResponse\ " - Notification sent when an attendee responds to the event invitation . - \"agenda\ " - An agenda with the events of the day ( sent out in the morning ) .
-- Required when adding a notification.
type' :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' CalendarNotification ' with the minimum fields required to make a request .
newCalendarNotification ::
CalendarNotification
newCalendarNotification =
CalendarNotification {method = Core.Nothing, type' = Core.Nothing}
instance Core.FromJSON CalendarNotification where
parseJSON =
Core.withObject
"CalendarNotification"
( \o ->
CalendarNotification
Core.<$> (o Core..:? "method") Core.<*> (o Core..:? "type")
)
instance Core.ToJSON CalendarNotification where
toJSON CalendarNotification {..} =
Core.object
( Core.catMaybes
[ ("method" Core..=) Core.<$> method,
("type" Core..=) Core.<$> type'
]
)
--
/See:/ ' newChannel ' smart constructor .
data Channel = Channel
{ -- | The address where notifications are delivered for this channel.
address :: (Core.Maybe Core.Text),
-- | Date and time of notification channel expiration, expressed as a Unix timestamp, in milliseconds. Optional.
expiration :: (Core.Maybe Core.Int64),
-- | A UUID or similar unique string that identifies this channel.
id :: (Core.Maybe Core.Text),
-- | Identifies this as a notification channel used to watch for changes to a resource, which is \"api#channel\".
kind :: Core.Text,
-- | Additional parameters controlling delivery channel behavior. Optional.
params :: (Core.Maybe Channel_Params),
| A Boolean value to indicate whether payload is wanted . Optional .
payload :: (Core.Maybe Core.Bool),
-- | An opaque ID that identifies the resource being watched on this channel. Stable across different API versions.
resourceId :: (Core.Maybe Core.Text),
-- | A version-specific identifier for the watched resource.
resourceUri :: (Core.Maybe Core.Text),
-- | An arbitrary string delivered to the target address with each notification delivered over this channel. Optional.
token :: (Core.Maybe Core.Text),
| The type of delivery mechanism used for this channel . Valid values are " ( or \"webhook\ " ) . Both values refer to a channel where Http requests are used to deliver messages .
type' :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Channel' with the minimum fields required to make a request.
newChannel ::
Channel
newChannel =
Channel
{ address = Core.Nothing,
expiration = Core.Nothing,
id = Core.Nothing,
kind = "api#channel",
params = Core.Nothing,
payload = Core.Nothing,
resourceId = Core.Nothing,
resourceUri = Core.Nothing,
token = Core.Nothing,
type' = Core.Nothing
}
instance Core.FromJSON Channel where
parseJSON =
Core.withObject
"Channel"
( \o ->
Channel
Core.<$> (o Core..:? "address")
Core.<*> ( o Core..:? "expiration"
Core.<&> Core.fmap Core.fromAsText
)
Core.<*> (o Core..:? "id")
Core.<*> (o Core..:? "kind" Core..!= "api#channel")
Core.<*> (o Core..:? "params")
Core.<*> (o Core..:? "payload")
Core.<*> (o Core..:? "resourceId")
Core.<*> (o Core..:? "resourceUri")
Core.<*> (o Core..:? "token")
Core.<*> (o Core..:? "type")
)
instance Core.ToJSON Channel where
toJSON Channel {..} =
Core.object
( Core.catMaybes
[ ("address" Core..=) Core.<$> address,
("expiration" Core..=) Core.. Core.AsText
Core.<$> expiration,
("id" Core..=) Core.<$> id,
Core.Just ("kind" Core..= kind),
("params" Core..=) Core.<$> params,
("payload" Core..=) Core.<$> payload,
("resourceId" Core..=) Core.<$> resourceId,
("resourceUri" Core..=) Core.<$> resourceUri,
("token" Core..=) Core.<$> token,
("type" Core..=) Core.<$> type'
]
)
-- | Additional parameters controlling delivery channel behavior. Optional.
--
-- /See:/ 'newChannel_Params' smart constructor.
newtype Channel_Params = Channel_Params
{ -- | Declares a new parameter by name.
additional :: (Core.HashMap Core.Text Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Channel_Params' with the minimum fields required to make a request.
newChannel_Params ::
-- | Declares a new parameter by name. See 'additional'.
Core.HashMap Core.Text Core.Text ->
Channel_Params
newChannel_Params additional = Channel_Params {additional = additional}
instance Core.FromJSON Channel_Params where
parseJSON =
Core.withObject
"Channel_Params"
( \o ->
Channel_Params Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Channel_Params where
toJSON Channel_Params {..} = Core.toJSON additional
--
-- /See:/ 'newColorDefinition' smart constructor.
data ColorDefinition = ColorDefinition
{ -- | The background color associated with this color definition.
background :: (Core.Maybe Core.Text),
-- | The foreground color that can be used to write on top of a background with \'background\' color.
foreground :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'ColorDefinition' with the minimum fields required to make a request.
newColorDefinition ::
ColorDefinition
newColorDefinition =
ColorDefinition {background = Core.Nothing, foreground = Core.Nothing}
instance Core.FromJSON ColorDefinition where
parseJSON =
Core.withObject
"ColorDefinition"
( \o ->
ColorDefinition
Core.<$> (o Core..:? "background")
Core.<*> (o Core..:? "foreground")
)
instance Core.ToJSON ColorDefinition where
toJSON ColorDefinition {..} =
Core.object
( Core.catMaybes
[ ("background" Core..=) Core.<$> background,
("foreground" Core..=) Core.<$> foreground
]
)
--
/See:/ ' newColors ' smart constructor .
data Colors = Colors
| A global palette of calendar colors , mapping from the color ID to its definition . A calendarListEntry resource refers to one of these color IDs in its colorId field . Read - only .
calendar :: (Core.Maybe Colors_Calendar),
| A global palette of event colors , mapping from the color ID to its definition . An event resource may refer to one of these color IDs in its colorId field . Read - only .
event :: (Core.Maybe Colors_Event),
-- | Type of the resource (\"calendar#colors\").
kind :: Core.Text,
-- | Last modification time of the color palette (as a RFC3339 timestamp). Read-only.
updated :: (Core.Maybe Core.DateTime)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Colors' with the minimum fields required to make a request.
newColors ::
Colors
newColors =
Colors
{ calendar = Core.Nothing,
event = Core.Nothing,
kind = "calendar#colors",
updated = Core.Nothing
}
instance Core.FromJSON Colors where
parseJSON =
Core.withObject
"Colors"
( \o ->
Colors
Core.<$> (o Core..:? "calendar")
Core.<*> (o Core..:? "event")
Core.<*> (o Core..:? "kind" Core..!= "calendar#colors")
Core.<*> (o Core..:? "updated")
)
instance Core.ToJSON Colors where
toJSON Colors {..} =
Core.object
( Core.catMaybes
[ ("calendar" Core..=) Core.<$> calendar,
("event" Core..=) Core.<$> event,
Core.Just ("kind" Core..= kind),
("updated" Core..=) Core.<$> updated
]
)
| A global palette of calendar colors , mapping from the color ID to its definition . A calendarListEntry resource refers to one of these color IDs in its colorId field . Read - only .
--
/See:/ ' ' smart constructor .
newtype Colors_Calendar = Colors_Calendar
{ -- | A calendar color definition.
additional :: (Core.HashMap Core.Text ColorDefinition)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' Colors_Calendar ' with the minimum fields required to make a request .
newColors_Calendar ::
-- | A calendar color definition. See 'additional'.
Core.HashMap Core.Text ColorDefinition ->
Colors_Calendar
newColors_Calendar additional = Colors_Calendar {additional = additional}
instance Core.FromJSON Colors_Calendar where
parseJSON =
Core.withObject
"Colors_Calendar"
( \o ->
Colors_Calendar Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Colors_Calendar where
toJSON Colors_Calendar {..} = Core.toJSON additional
| A global palette of event colors , mapping from the color ID to its definition . An event resource may refer to one of these color IDs in its colorId field . Read - only .
--
-- /See:/ 'newColors_Event' smart constructor.
newtype Colors_Event = Colors_Event
{ -- | An event color definition.
additional :: (Core.HashMap Core.Text ColorDefinition)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Colors_Event' with the minimum fields required to make a request.
newColors_Event ::
-- | An event color definition. See 'additional'.
Core.HashMap Core.Text ColorDefinition ->
Colors_Event
newColors_Event additional = Colors_Event {additional = additional}
instance Core.FromJSON Colors_Event where
parseJSON =
Core.withObject
"Colors_Event"
( \o ->
Colors_Event Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Colors_Event where
toJSON Colors_Event {..} = Core.toJSON additional
--
-- /See:/ 'newConferenceData' smart constructor.
data ConferenceData = ConferenceData
{ -- | The ID of the conference. Can be used by developers to keep track of conferences, should not be displayed to users. The ID value is formed differently for each conference solution type:
- eventHangout : ID is not set . ( This conference type is deprecated . ) - eventNamedHangout : ID is the name of the Hangout . ( This conference type is deprecated . ) - hangoutsMeet : ID is the 10 - letter meeting code , for example . - addOn : ID is defined by the third - party provider . Optional .
conferenceId :: (Core.Maybe Core.Text),
| The conference solution , such as Google Meet . Unset for a conference with a failed create request . Either conferenceSolution and at least one entryPoint , or createRequest is required .
conferenceSolution :: (Core.Maybe ConferenceSolution),
| A request to generate a new conference and attach it to the event . The data is generated asynchronously . To see whether the data is present check the status field . Either conferenceSolution and at least one entryPoint , or createRequest is required .
createRequest :: (Core.Maybe CreateConferenceRequest),
| Information about individual conference entry points , such as URLs or phone numbers . All of them must belong to the same conference . Either conferenceSolution and at least one entryPoint , or createRequest is required .
entryPoints :: (Core.Maybe [EntryPoint]),
| Additional notes ( such as instructions from the domain administrator , legal notices ) to display to the user . Can contain HTML . The maximum length is 2048 characters . Optional .
notes :: (Core.Maybe Core.Text),
-- | Additional properties related to a conference. An example would be a solution-specific setting for enabling video streaming.
parameters :: (Core.Maybe ConferenceParameters),
| The signature of the conference data . Generated on server side . Unset for a conference with a failed create request . Optional for a conference with a pending create request .
signature :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' ConferenceData ' with the minimum fields required to make a request .
newConferenceData ::
ConferenceData
newConferenceData =
ConferenceData
{ conferenceId = Core.Nothing,
conferenceSolution = Core.Nothing,
createRequest = Core.Nothing,
entryPoints = Core.Nothing,
notes = Core.Nothing,
parameters = Core.Nothing,
signature = Core.Nothing
}
instance Core.FromJSON ConferenceData where
parseJSON =
Core.withObject
"ConferenceData"
( \o ->
ConferenceData
Core.<$> (o Core..:? "conferenceId")
Core.<*> (o Core..:? "conferenceSolution")
Core.<*> (o Core..:? "createRequest")
Core.<*> (o Core..:? "entryPoints")
Core.<*> (o Core..:? "notes")
Core.<*> (o Core..:? "parameters")
Core.<*> (o Core..:? "signature")
)
instance Core.ToJSON ConferenceData where
toJSON ConferenceData {..} =
Core.object
( Core.catMaybes
[ ("conferenceId" Core..=) Core.<$> conferenceId,
("conferenceSolution" Core..=)
Core.<$> conferenceSolution,
("createRequest" Core..=) Core.<$> createRequest,
("entryPoints" Core..=) Core.<$> entryPoints,
("notes" Core..=) Core.<$> notes,
("parameters" Core..=) Core.<$> parameters,
("signature" Core..=) Core.<$> signature
]
)
--
-- /See:/ 'newConferenceParameters' smart constructor.
newtype ConferenceParameters = ConferenceParameters
{ -- | Additional add-on specific data.
addOnParameters :: (Core.Maybe ConferenceParametersAddOnParameters)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' ConferenceParameters ' with the minimum fields required to make a request .
newConferenceParameters ::
ConferenceParameters
newConferenceParameters = ConferenceParameters {addOnParameters = Core.Nothing}
instance Core.FromJSON ConferenceParameters where
parseJSON =
Core.withObject
"ConferenceParameters"
( \o ->
ConferenceParameters
Core.<$> (o Core..:? "addOnParameters")
)
instance Core.ToJSON ConferenceParameters where
toJSON ConferenceParameters {..} =
Core.object
( Core.catMaybes
[ ("addOnParameters" Core..=)
Core.<$> addOnParameters
]
)
--
/See:/ ' newConferenceParametersAddOnParameters ' smart constructor .
newtype ConferenceParametersAddOnParameters = ConferenceParametersAddOnParameters
{ -- |
parameters :: (Core.Maybe ConferenceParametersAddOnParameters_Parameters)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'ConferenceParametersAddOnParameters' with the minimum fields required to make a request.
newConferenceParametersAddOnParameters ::
ConferenceParametersAddOnParameters
newConferenceParametersAddOnParameters =
ConferenceParametersAddOnParameters {parameters = Core.Nothing}
instance
Core.FromJSON
ConferenceParametersAddOnParameters
where
parseJSON =
Core.withObject
"ConferenceParametersAddOnParameters"
( \o ->
ConferenceParametersAddOnParameters
Core.<$> (o Core..:? "parameters")
)
instance
Core.ToJSON
ConferenceParametersAddOnParameters
where
toJSON ConferenceParametersAddOnParameters {..} =
Core.object
( Core.catMaybes
[("parameters" Core..=) Core.<$> parameters]
)
--
-- /See:/ 'newConferenceParametersAddOnParameters_Parameters' smart constructor.
newtype ConferenceParametersAddOnParameters_Parameters = ConferenceParametersAddOnParameters_Parameters
{ -- |
additional :: (Core.HashMap Core.Text Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'ConferenceParametersAddOnParameters_Parameters' with the minimum fields required to make a request.
newConferenceParametersAddOnParameters_Parameters ::
-- | See 'additional'.
Core.HashMap Core.Text Core.Text ->
ConferenceParametersAddOnParameters_Parameters
newConferenceParametersAddOnParameters_Parameters additional =
ConferenceParametersAddOnParameters_Parameters {additional = additional}
instance
Core.FromJSON
ConferenceParametersAddOnParameters_Parameters
where
parseJSON =
Core.withObject
"ConferenceParametersAddOnParameters_Parameters"
( \o ->
ConferenceParametersAddOnParameters_Parameters
Core.<$> (Core.parseJSONObject o)
)
instance
Core.ToJSON
ConferenceParametersAddOnParameters_Parameters
where
toJSON
ConferenceParametersAddOnParameters_Parameters {..} =
Core.toJSON additional
--
-- /See:/ 'newConferenceProperties' smart constructor.
newtype ConferenceProperties = ConferenceProperties
{ -- | The types of conference solutions that are supported for this calendar. The possible values are:
-- - \"eventHangout\" - \"eventNamedHangout\" - \"hangoutsMeet\" Optional.
allowedConferenceSolutionTypes :: (Core.Maybe [Core.Text])
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'ConferenceProperties' with the minimum fields required to make a request.
newConferenceProperties ::
ConferenceProperties
newConferenceProperties =
ConferenceProperties {allowedConferenceSolutionTypes = Core.Nothing}
instance Core.FromJSON ConferenceProperties where
parseJSON =
Core.withObject
"ConferenceProperties"
( \o ->
ConferenceProperties
Core.<$> (o Core..:? "allowedConferenceSolutionTypes")
)
instance Core.ToJSON ConferenceProperties where
toJSON ConferenceProperties {..} =
Core.object
( Core.catMaybes
[ ("allowedConferenceSolutionTypes" Core..=)
Core.<$> allowedConferenceSolutionTypes
]
)
--
/See:/ ' newConferenceRequestStatus ' smart constructor .
newtype ConferenceRequestStatus = ConferenceRequestStatus
{ -- | The current status of the conference create request. Read-only. The possible values are:
-- - \"pending\": the conference create request is still being processed. - \"success\": the conference create request succeeded, the entry points are populated. - \"failure\": the conference create request failed, there are no entry points.
statusCode :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' ConferenceRequestStatus ' with the minimum fields required to make a request .
newConferenceRequestStatus ::
ConferenceRequestStatus
newConferenceRequestStatus = ConferenceRequestStatus {statusCode = Core.Nothing}
instance Core.FromJSON ConferenceRequestStatus where
parseJSON =
Core.withObject
"ConferenceRequestStatus"
( \o ->
ConferenceRequestStatus
Core.<$> (o Core..:? "statusCode")
)
instance Core.ToJSON ConferenceRequestStatus where
toJSON ConferenceRequestStatus {..} =
Core.object
( Core.catMaybes
[("statusCode" Core..=) Core.<$> statusCode]
)
--
-- /See:/ 'newConferenceSolution' smart constructor.
data ConferenceSolution = ConferenceSolution
{ -- | The user-visible icon for this solution.
iconUri :: (Core.Maybe Core.Text),
-- | The key which can uniquely identify the conference solution for this event.
key :: (Core.Maybe ConferenceSolutionKey),
-- | The user-visible name of this solution. Not localized.
name :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' ConferenceSolution ' with the minimum fields required to make a request .
newConferenceSolution ::
ConferenceSolution
newConferenceSolution =
ConferenceSolution
{ iconUri = Core.Nothing,
key = Core.Nothing,
name = Core.Nothing
}
instance Core.FromJSON ConferenceSolution where
parseJSON =
Core.withObject
"ConferenceSolution"
( \o ->
ConferenceSolution
Core.<$> (o Core..:? "iconUri")
Core.<*> (o Core..:? "key")
Core.<*> (o Core..:? "name")
)
instance Core.ToJSON ConferenceSolution where
toJSON ConferenceSolution {..} =
Core.object
( Core.catMaybes
[ ("iconUri" Core..=) Core.<$> iconUri,
("key" Core..=) Core.<$> key,
("name" Core..=) Core.<$> name
]
)
--
-- /See:/ 'newConferenceSolutionKey' smart constructor.
newtype ConferenceSolutionKey = ConferenceSolutionKey
{ -- | The conference solution type. If a client encounters an unfamiliar or empty type, it should still be able to display the entry points. However, it should disallow modifications. The possible values are:
- \"eventHangout\ " for Hangouts for consumers ( deprecated ; existing events may show this conference solution type but new conferences can not be created ) - \"eventNamedHangout\ " for classic Hangouts for Google Workspace users ( deprecated ; existing events may show this conference solution type but new conferences can not be created ) - \"hangoutsMeet\ " for Google Meet ( http:\/\/meet.google.com ) - \"addOn\ " for 3P conference providers
type' :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'ConferenceSolutionKey' with the minimum fields required to make a request.
newConferenceSolutionKey ::
ConferenceSolutionKey
newConferenceSolutionKey = ConferenceSolutionKey {type' = Core.Nothing}
instance Core.FromJSON ConferenceSolutionKey where
parseJSON =
Core.withObject
"ConferenceSolutionKey"
( \o ->
ConferenceSolutionKey Core.<$> (o Core..:? "type")
)
instance Core.ToJSON ConferenceSolutionKey where
toJSON ConferenceSolutionKey {..} =
Core.object
(Core.catMaybes [("type" Core..=) Core.<$> type'])
--
/See:/ ' newCreateConferenceRequest ' smart constructor .
data CreateConferenceRequest = CreateConferenceRequest
{ -- | The conference solution, such as Hangouts or Google Meet.
conferenceSolutionKey :: (Core.Maybe ConferenceSolutionKey),
-- | The client-generated unique ID for this request. Clients should regenerate this ID for every new request. If an ID provided is the same as for the previous request, the request is ignored.
requestId :: (Core.Maybe Core.Text),
-- | The status of the conference create request.
status :: (Core.Maybe ConferenceRequestStatus)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' CreateConferenceRequest ' with the minimum fields required to make a request .
newCreateConferenceRequest ::
CreateConferenceRequest
newCreateConferenceRequest =
CreateConferenceRequest
{ conferenceSolutionKey = Core.Nothing,
requestId = Core.Nothing,
status = Core.Nothing
}
instance Core.FromJSON CreateConferenceRequest where
parseJSON =
Core.withObject
"CreateConferenceRequest"
( \o ->
CreateConferenceRequest
Core.<$> (o Core..:? "conferenceSolutionKey")
Core.<*> (o Core..:? "requestId")
Core.<*> (o Core..:? "status")
)
instance Core.ToJSON CreateConferenceRequest where
toJSON CreateConferenceRequest {..} =
Core.object
( Core.catMaybes
[ ("conferenceSolutionKey" Core..=)
Core.<$> conferenceSolutionKey,
("requestId" Core..=) Core.<$> requestId,
("status" Core..=) Core.<$> status
]
)
--
/See:/ ' newEntryPoint ' smart constructor .
data EntryPoint = EntryPoint
| The access code to access the conference . The maximum length is 128 characters . When creating new conference data , populate only the subset of { meetingCode , accessCode , passcode , password , pin } fields that match the terminology that the conference provider uses . Only the populated fields should be displayed . Optional .
accessCode :: (Core.Maybe Core.Text),
| Features of the entry point , such as being toll or toll - free . One entry point can have multiple features . However , toll and toll - free can not be both set on the same entry point .
entryPointFeatures :: (Core.Maybe [Core.Text]),
-- | The type of the conference entry point. Possible values are:
- \"video\ " - joining a conference over HTTP . A conference can have zero or one video entry point . - \"phone\ " - joining a conference by dialing a phone number . A conference can have zero or more phone entry points . - \"sip\ " - joining a conference over SIP . A conference can have zero or one sip entry point . - \"more\ " - further conference joining instructions , for example additional phone numbers . A conference can have zero or one more entry point . A conference with only a more entry point is not a valid conference .
entryPointType :: (Core.Maybe Core.Text),
| The label for the URI . Visible to end users . Not localized . The maximum length is 512 characters . Examples :
- for video : meet.google.com\/aaa - bbbb - ccc - for phone : +1 123 268 2601 - for sip : 12345678\@altostrat.com - for more : should not be filled
-- Optional.
label :: (Core.Maybe Core.Text),
| The meeting code to access the conference . The maximum length is 128 characters . When creating new conference data , populate only the subset of { meetingCode , accessCode , passcode , password , pin } fields that match the terminology that the conference provider uses . Only the populated fields should be displayed . Optional .
meetingCode :: (Core.Maybe Core.Text),
| The passcode to access the conference . The maximum length is 128 characters . When creating new conference data , populate only the subset of { meetingCode , accessCode , passcode , password , pin } fields that match the terminology that the conference provider uses . Only the populated fields should be displayed .
passcode :: (Core.Maybe Core.Text),
| The password to access the conference . The maximum length is 128 characters . When creating new conference data , populate only the subset of { meetingCode , accessCode , passcode , password , pin } fields that match the terminology that the conference provider uses . Only the populated fields should be displayed . Optional .
password :: (Core.Maybe Core.Text),
| The PIN to access the conference . The maximum length is 128 characters . When creating new conference data , populate only the subset of { meetingCode , accessCode , passcode , password , pin } fields that match the terminology that the conference provider uses . Only the populated fields should be displayed . Optional .
pin :: (Core.Maybe Core.Text),
| The CLDR\/ISO 3166 region code for the country associated with this phone access . Example : \"SE\ " for Sweden . Calendar backend will populate this field only for EntryPointType . PHONE .
regionCode :: (Core.Maybe Core.Text),
| The URI of the entry point . The maximum length is 1300 characters . Format :
- for video , http : or https : schema is required . - for phone , tel : schema is required . The URI should include the entire dial sequence ( e.g. , tel:+12345678900,,,123456789;1234 ) . - for sip , sip : schema is required , e.g. , sip:12345678\@myprovider.com . - for more , http : or https : schema is required .
uri :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' EntryPoint ' with the minimum fields required to make a request .
newEntryPoint ::
EntryPoint
newEntryPoint =
EntryPoint
{ accessCode = Core.Nothing,
entryPointFeatures = Core.Nothing,
entryPointType = Core.Nothing,
label = Core.Nothing,
meetingCode = Core.Nothing,
passcode = Core.Nothing,
password = Core.Nothing,
pin = Core.Nothing,
regionCode = Core.Nothing,
uri = Core.Nothing
}
instance Core.FromJSON EntryPoint where
parseJSON =
Core.withObject
"EntryPoint"
( \o ->
EntryPoint
Core.<$> (o Core..:? "accessCode")
Core.<*> (o Core..:? "entryPointFeatures")
Core.<*> (o Core..:? "entryPointType")
Core.<*> (o Core..:? "label")
Core.<*> (o Core..:? "meetingCode")
Core.<*> (o Core..:? "passcode")
Core.<*> (o Core..:? "password")
Core.<*> (o Core..:? "pin")
Core.<*> (o Core..:? "regionCode")
Core.<*> (o Core..:? "uri")
)
instance Core.ToJSON EntryPoint where
toJSON EntryPoint {..} =
Core.object
( Core.catMaybes
[ ("accessCode" Core..=) Core.<$> accessCode,
("entryPointFeatures" Core..=)
Core.<$> entryPointFeatures,
("entryPointType" Core..=) Core.<$> entryPointType,
("label" Core..=) Core.<$> label,
("meetingCode" Core..=) Core.<$> meetingCode,
("passcode" Core..=) Core.<$> passcode,
("password" Core..=) Core.<$> password,
("pin" Core..=) Core.<$> pin,
("regionCode" Core..=) Core.<$> regionCode,
("uri" Core..=) Core.<$> uri
]
)
--
-- /See:/ 'newError' smart constructor.
data Error' = Error'
{ -- | Domain, or broad category, of the error.
domain :: (Core.Maybe Core.Text),
-- | Specific reason for the error. Some of the possible values are:
- \"groupTooBig\ " - The group of users requested is too large for a single query . - \"tooManyCalendarsRequested\ " - The number of calendars requested is too large for a single query . - \"notFound\ " - The requested resource was not found . - \"internalError\ " - The API service has encountered an internal error . Additional error types may be added in the future , so clients should gracefully handle additional error statuses not included in this list .
reason :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Error' with the minimum fields required to make a request.
newError ::
Error'
newError = Error' {domain = Core.Nothing, reason = Core.Nothing}
instance Core.FromJSON Error' where
parseJSON =
Core.withObject
"Error'"
( \o ->
Error'
Core.<$> (o Core..:? "domain") Core.<*> (o Core..:? "reason")
)
instance Core.ToJSON Error' where
toJSON Error' {..} =
Core.object
( Core.catMaybes
[ ("domain" Core..=) Core.<$> domain,
("reason" Core..=) Core.<$> reason
]
)
--
-- /See:/ 'newEvent' smart constructor.
data Event = Event
{ -- | Whether anyone can invite themselves to the event (deprecated). Optional. The default is False.
anyoneCanAddSelf :: Core.Bool,
| File attachments for the event . Currently only Google Drive attachments are supported . In order to modify attachments the supportsAttachments request parameter should be set to true . There can be at most 25 attachments per event ,
attachments :: (Core.Maybe [EventAttachment]),
-- | The attendees of the event. See the Events with attendees guide for more information on scheduling events with other calendar users. Service accounts need to use domain-wide delegation of authority to populate the attendee list.
attendees :: (Core.Maybe [EventAttendee]),
| Whether attendees may have been omitted from the event\ 's representation . When retrieving an event , this may be due to a restriction specified by the maxAttendee query parameter . When updating an event , this can be used to only update the participant\ 's response . Optional . The default is False .
attendeesOmitted :: Core.Bool,
-- | The color of the event. This is an ID referring to an entry in the event section of the colors definition (see the colors endpoint). Optional.
colorId :: (Core.Maybe Core.Text),
| The conference - related information , such as details of a Google Meet conference . To create new conference details use the createRequest field . To persist your changes , remember to set the conferenceDataVersion request parameter to 1 for all event modification requests .
conferenceData :: (Core.Maybe ConferenceData),
-- | Creation time of the event (as a RFC3339 timestamp). Read-only.
created :: (Core.Maybe Core.DateTime),
-- | The creator of the event. Read-only.
creator :: (Core.Maybe Event_Creator),
-- | Description of the event. Can contain HTML. Optional.
description :: (Core.Maybe Core.Text),
| The ( exclusive ) end time of the event . For a recurring event , this is the end time of the first instance .
end :: (Core.Maybe EventDateTime),
-- | Whether the end time is actually unspecified. An end time is still provided for compatibility reasons, even if this attribute is set to True. The default is False.
endTimeUnspecified :: Core.Bool,
-- | ETag of the resource.
etag :: (Core.Maybe Core.Text),
-- | Specific type of the event. Read-only. Possible values are:
-- - \"default\" - A regular event or not further specified. - \"outOfOffice\" - An out-of-office event. - \"focusTime\" - A focus-time event.
eventType :: Core.Text,
-- | Extended properties of the event.
extendedProperties :: (Core.Maybe Event_ExtendedProperties),
-- | A gadget that extends this event. Gadgets are deprecated; this structure is instead only used for returning birthday calendar metadata.
gadget :: (Core.Maybe Event_Gadget),
-- | Whether attendees other than the organizer can invite others to the event. Optional. The default is True.
guestsCanInviteOthers :: Core.Bool,
-- | Whether attendees other than the organizer can modify the event. Optional. The default is False.
guestsCanModify :: Core.Bool,
-- | Whether attendees other than the organizer can see who the event\'s attendees are. Optional. The default is True.
guestsCanSeeOtherGuests :: Core.Bool,
-- | An absolute link to the Google Hangout associated with this event. Read-only.
hangoutLink :: (Core.Maybe Core.Text),
-- | An absolute link to this event in the Google Calendar Web UI. Read-only.
htmlLink :: (Core.Maybe Core.Text),
| Event unique identifier as defined in RFC5545 . It is used to uniquely identify events accross calendaring systems and must be supplied when importing events via the import method . Note that the icalUID and the i d are not identical and only one of them should be supplied at event creation time . One difference in their semantics is that in recurring events , all occurrences of one event have different ids while they all share the same icalUIDs .
iCalUID :: (Core.Maybe Core.Text),
-- | Opaque identifier of the event. When creating new single or recurring events, you can specify their IDs. Provided IDs must follow these rules:
- characters allowed in the ID are those used in base32hex encoding , i.e. lowercase letters a - v and digits 0 - 9 , see section 3.1.2 in RFC2938 - the length of the ID must be between 5 and 1024 characters - the ID must be unique per calendar Due to the globally distributed nature of the system , we can not guarantee that ID collisions will be detected at event creation time . To minimize the risk of collisions we recommend using an established UUID algorithm such as one described in RFC4122 . If you do not specify an ID , it will be automatically generated by the server . Note that the icalUID and the i d are not identical and only one of them should be supplied at event creation time . One difference in their semantics is that in recurring events , all occurrences of one event have different ids while they all share the same icalUIDs .
id :: (Core.Maybe Core.Text),
-- | Type of the resource (\"calendar#event\").
kind :: Core.Text,
-- | Geographic location of the event as free-form text. Optional.
location :: (Core.Maybe Core.Text),
| Whether this is a locked event copy where no changes can be made to the main event fields \"summary\ " , \"description\ " , \"location\ " , \"start\ " , \"end\ " or \"recurrence\ " . The default is False . Read - Only .
locked :: Core.Bool,
-- | The organizer of the event. If the organizer is also an attendee, this is indicated with a separate entry in attendees with the organizer field set to True. To change the organizer, use the move operation. Read-only, except when importing an event.
organizer :: (Core.Maybe Event_Organizer),
-- | For an instance of a recurring event, this is the time at which this event would start according to the recurrence data in the recurring event identified by recurringEventId. It uniquely identifies the instance within the recurring event series even if the instance was moved to a different time. Immutable.
originalStartTime :: (Core.Maybe EventDateTime),
-- | If set to True, Event propagation is disabled. Note that it is not the same thing as Private event properties. Optional. Immutable. The default is False.
privateCopy :: Core.Bool,
| List of RRULE , EXRULE , RDATE and EXDATE lines for a recurring event , as specified in RFC5545 . Note that DTSTART and DTEND lines are not allowed in this field ; event start and end times are specified in the start and end fields . This field is omitted for single events or instances of recurring events .
recurrence :: (Core.Maybe [Core.Text]),
-- | For an instance of a recurring event, this is the id of the recurring event to which this instance belongs. Immutable.
recurringEventId :: (Core.Maybe Core.Text),
-- | Information about the event\'s reminders for the authenticated user.
reminders :: (Core.Maybe Event_Reminders),
-- | Sequence number as per iCalendar.
sequence :: (Core.Maybe Core.Int32),
-- | Source from which the event was created. For example, a web page, an email message or any document identifiable by an URL with HTTP or HTTPS scheme. Can only be seen or modified by the creator of the event.
source :: (Core.Maybe Event_Source),
| The ( inclusive ) start time of the event . For a recurring event , this is the start time of the first instance .
start :: (Core.Maybe EventDateTime),
-- | Status of the event. Optional. Possible values are:
- \"confirmed\ " - The event is confirmed . This is the default status . - \"tentative\ " - The event is tentatively confirmed . - \"cancelled\ " - The event is cancelled ( deleted ) . The list method returns cancelled events only on incremental sync ( when syncToken or updatedMin are specified ) or if the showDeleted flag is set to true . The get method always returns them . A cancelled status represents two different states depending on the event type :
-- - Cancelled exceptions of an uncancelled recurring event indicate that this instance should no longer be presented to the user. Clients should store these events for the lifetime of the parent recurring event. Cancelled exceptions are only guaranteed to have values for the id, recurringEventId and originalStartTime fields populated. The other fields might be empty.
-- - All other cancelled events represent deleted events. Clients should remove their locally synced copies. Such cancelled events will eventually disappear, so do not rely on them being available indefinitely. Deleted events are only guaranteed to have the id field populated. On the organizer\'s calendar, cancelled events continue to expose event details (summary, location, etc.) so that they can be restored (undeleted). Similarly, the events to which the user was invited and that they manually removed continue to provide details. However, incremental sync requests with showDeleted set to false will not return these details. If an event changes its organizer (for example via the move operation) and the original organizer is not on the attendee list, it will leave behind a cancelled event where only the id field is guaranteed to be populated.
status :: (Core.Maybe Core.Text),
-- | Title of the event.
summary :: (Core.Maybe Core.Text),
-- | Whether the event blocks time on the calendar. Optional. Possible values are:
-- - \"opaque\" - Default value. The event does block time on the calendar. This is equivalent to setting Show me as to Busy in the Calendar UI. - \"transparent\" - The event does not block time on the calendar. This is equivalent to setting Show me as to Available in the Calendar UI.
transparency :: Core.Text,
-- | Last modification time of the event (as a RFC3339 timestamp). Read-only.
updated :: (Core.Maybe Core.DateTime),
-- | Visibility of the event. Optional. Possible values are:
-- - \"default\" - Uses the default visibility for events on the calendar. This is the default value. - \"public\" - The event is public and event details are visible to all readers of the calendar. - \"private\" - The event is private and only event attendees may view event details. - \"confidential\" - The event is private. This value is provided for compatibility reasons.
visibility :: Core.Text
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Event' with the minimum fields required to make a request.
newEvent ::
Event
newEvent =
Event
{ anyoneCanAddSelf = Core.False,
attachments = Core.Nothing,
attendees = Core.Nothing,
attendeesOmitted = Core.False,
colorId = Core.Nothing,
conferenceData = Core.Nothing,
created = Core.Nothing,
creator = Core.Nothing,
description = Core.Nothing,
end = Core.Nothing,
endTimeUnspecified = Core.False,
etag = Core.Nothing,
eventType = "default",
extendedProperties = Core.Nothing,
gadget = Core.Nothing,
guestsCanInviteOthers = Core.True,
guestsCanModify = Core.False,
guestsCanSeeOtherGuests = Core.True,
hangoutLink = Core.Nothing,
htmlLink = Core.Nothing,
iCalUID = Core.Nothing,
id = Core.Nothing,
kind = "calendar#event",
location = Core.Nothing,
locked = Core.False,
organizer = Core.Nothing,
originalStartTime = Core.Nothing,
privateCopy = Core.False,
recurrence = Core.Nothing,
recurringEventId = Core.Nothing,
reminders = Core.Nothing,
sequence = Core.Nothing,
source = Core.Nothing,
start = Core.Nothing,
status = Core.Nothing,
summary = Core.Nothing,
transparency = "opaque",
updated = Core.Nothing,
visibility = "default"
}
instance Core.FromJSON Event where
parseJSON =
Core.withObject
"Event"
( \o ->
Event
Core.<$> (o Core..:? "anyoneCanAddSelf" Core..!= Core.False)
Core.<*> (o Core..:? "attachments")
Core.<*> (o Core..:? "attendees")
Core.<*> (o Core..:? "attendeesOmitted" Core..!= Core.False)
Core.<*> (o Core..:? "colorId")
Core.<*> (o Core..:? "conferenceData")
Core.<*> (o Core..:? "created")
Core.<*> (o Core..:? "creator")
Core.<*> (o Core..:? "description")
Core.<*> (o Core..:? "end")
Core.<*> (o Core..:? "endTimeUnspecified" Core..!= Core.False)
Core.<*> (o Core..:? "etag")
Core.<*> (o Core..:? "eventType" Core..!= "default")
Core.<*> (o Core..:? "extendedProperties")
Core.<*> (o Core..:? "gadget")
Core.<*> ( o Core..:? "guestsCanInviteOthers"
Core..!= Core.True
)
Core.<*> (o Core..:? "guestsCanModify" Core..!= Core.False)
Core.<*> ( o Core..:? "guestsCanSeeOtherGuests"
Core..!= Core.True
)
Core.<*> (o Core..:? "hangoutLink")
Core.<*> (o Core..:? "htmlLink")
Core.<*> (o Core..:? "iCalUID")
Core.<*> (o Core..:? "id")
Core.<*> (o Core..:? "kind" Core..!= "calendar#event")
Core.<*> (o Core..:? "location")
Core.<*> (o Core..:? "locked" Core..!= Core.False)
Core.<*> (o Core..:? "organizer")
Core.<*> (o Core..:? "originalStartTime")
Core.<*> (o Core..:? "privateCopy" Core..!= Core.False)
Core.<*> (o Core..:? "recurrence")
Core.<*> (o Core..:? "recurringEventId")
Core.<*> (o Core..:? "reminders")
Core.<*> (o Core..:? "sequence")
Core.<*> (o Core..:? "source")
Core.<*> (o Core..:? "start")
Core.<*> (o Core..:? "status")
Core.<*> (o Core..:? "summary")
Core.<*> (o Core..:? "transparency" Core..!= "opaque")
Core.<*> (o Core..:? "updated")
Core.<*> (o Core..:? "visibility" Core..!= "default")
)
instance Core.ToJSON Event where
toJSON Event {..} =
Core.object
( Core.catMaybes
[ Core.Just
("anyoneCanAddSelf" Core..= anyoneCanAddSelf),
("attachments" Core..=) Core.<$> attachments,
("attendees" Core..=) Core.<$> attendees,
Core.Just
("attendeesOmitted" Core..= attendeesOmitted),
("colorId" Core..=) Core.<$> colorId,
("conferenceData" Core..=) Core.<$> conferenceData,
("created" Core..=) Core.<$> created,
("creator" Core..=) Core.<$> creator,
("description" Core..=) Core.<$> description,
("end" Core..=) Core.<$> end,
Core.Just
("endTimeUnspecified" Core..= endTimeUnspecified),
("etag" Core..=) Core.<$> etag,
Core.Just ("eventType" Core..= eventType),
("extendedProperties" Core..=)
Core.<$> extendedProperties,
("gadget" Core..=) Core.<$> gadget,
Core.Just
( "guestsCanInviteOthers"
Core..= guestsCanInviteOthers
),
Core.Just
("guestsCanModify" Core..= guestsCanModify),
Core.Just
( "guestsCanSeeOtherGuests"
Core..= guestsCanSeeOtherGuests
),
("hangoutLink" Core..=) Core.<$> hangoutLink,
("htmlLink" Core..=) Core.<$> htmlLink,
("iCalUID" Core..=) Core.<$> iCalUID,
("id" Core..=) Core.<$> id,
Core.Just ("kind" Core..= kind),
("location" Core..=) Core.<$> location,
Core.Just ("locked" Core..= locked),
("organizer" Core..=) Core.<$> organizer,
("originalStartTime" Core..=)
Core.<$> originalStartTime,
Core.Just ("privateCopy" Core..= privateCopy),
("recurrence" Core..=) Core.<$> recurrence,
("recurringEventId" Core..=)
Core.<$> recurringEventId,
("reminders" Core..=) Core.<$> reminders,
("sequence" Core..=) Core.<$> sequence,
("source" Core..=) Core.<$> source,
("start" Core..=) Core.<$> start,
("status" Core..=) Core.<$> status,
("summary" Core..=) Core.<$> summary,
Core.Just ("transparency" Core..= transparency),
("updated" Core..=) Core.<$> updated,
Core.Just ("visibility" Core..= visibility)
]
)
-- | The creator of the event. Read-only.
--
-- /See:/ 'newEvent_Creator' smart constructor.
data Event_Creator = Event_Creator
{ -- | The creator\'s name, if available.
displayName :: (Core.Maybe Core.Text),
-- | The creator\'s email address, if available.
email :: (Core.Maybe Core.Text),
-- | The creator\'s Profile ID, if available.
id :: (Core.Maybe Core.Text),
-- | Whether the creator corresponds to the calendar on which this copy of the event appears. Read-only. The default is False.
self :: Core.Bool
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Event_Creator' with the minimum fields required to make a request.
newEvent_Creator ::
Event_Creator
newEvent_Creator =
Event_Creator
{ displayName = Core.Nothing,
email = Core.Nothing,
id = Core.Nothing,
self = Core.False
}
instance Core.FromJSON Event_Creator where
parseJSON =
Core.withObject
"Event_Creator"
( \o ->
Event_Creator
Core.<$> (o Core..:? "displayName")
Core.<*> (o Core..:? "email")
Core.<*> (o Core..:? "id")
Core.<*> (o Core..:? "self" Core..!= Core.False)
)
instance Core.ToJSON Event_Creator where
toJSON Event_Creator {..} =
Core.object
( Core.catMaybes
[ ("displayName" Core..=) Core.<$> displayName,
("email" Core..=) Core.<$> email,
("id" Core..=) Core.<$> id,
Core.Just ("self" Core..= self)
]
)
-- | Extended properties of the event.
--
-- /See:/ 'newEvent_ExtendedProperties' smart constructor.
data Event_ExtendedProperties = Event_ExtendedProperties
{ -- | Properties that are private to the copy of the event that appears on this calendar.
private :: (Core.Maybe Event_ExtendedProperties_Private),
| Properties that are shared between copies of the event on other attendees\ ' calendars .
shared :: (Core.Maybe Event_ExtendedProperties_Shared)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' Event_ExtendedProperties ' with the minimum fields required to make a request .
newEvent_ExtendedProperties ::
Event_ExtendedProperties
newEvent_ExtendedProperties =
Event_ExtendedProperties {private = Core.Nothing, shared = Core.Nothing}
instance Core.FromJSON Event_ExtendedProperties where
parseJSON =
Core.withObject
"Event_ExtendedProperties"
( \o ->
Event_ExtendedProperties
Core.<$> (o Core..:? "private")
Core.<*> (o Core..:? "shared")
)
instance Core.ToJSON Event_ExtendedProperties where
toJSON Event_ExtendedProperties {..} =
Core.object
( Core.catMaybes
[ ("private" Core..=) Core.<$> private,
("shared" Core..=) Core.<$> shared
]
)
-- | Properties that are private to the copy of the event that appears on this calendar.
--
-- /See:/ 'newEvent_ExtendedProperties_Private' smart constructor.
newtype Event_ExtendedProperties_Private = Event_ExtendedProperties_Private
{ -- | The name of the private property and the corresponding value.
additional :: (Core.HashMap Core.Text Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Event_ExtendedProperties_Private' with the minimum fields required to make a request.
newEvent_ExtendedProperties_Private ::
-- | The name of the private property and the corresponding value. See 'additional'.
Core.HashMap Core.Text Core.Text ->
Event_ExtendedProperties_Private
newEvent_ExtendedProperties_Private additional =
Event_ExtendedProperties_Private {additional = additional}
instance
Core.FromJSON
Event_ExtendedProperties_Private
where
parseJSON =
Core.withObject
"Event_ExtendedProperties_Private"
( \o ->
Event_ExtendedProperties_Private
Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Event_ExtendedProperties_Private where
toJSON Event_ExtendedProperties_Private {..} =
Core.toJSON additional
| Properties that are shared between copies of the event on other attendees\ ' calendars .
--
-- /See:/ 'newEvent_ExtendedProperties_Shared' smart constructor.
newtype Event_ExtendedProperties_Shared = Event_ExtendedProperties_Shared
{ -- | The name of the shared property and the corresponding value.
additional :: (Core.HashMap Core.Text Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Event_ExtendedProperties_Shared' with the minimum fields required to make a request.
newEvent_ExtendedProperties_Shared ::
-- | The name of the shared property and the corresponding value. See 'additional'.
Core.HashMap Core.Text Core.Text ->
Event_ExtendedProperties_Shared
newEvent_ExtendedProperties_Shared additional =
Event_ExtendedProperties_Shared {additional = additional}
instance
Core.FromJSON
Event_ExtendedProperties_Shared
where
parseJSON =
Core.withObject
"Event_ExtendedProperties_Shared"
( \o ->
Event_ExtendedProperties_Shared
Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Event_ExtendedProperties_Shared where
toJSON Event_ExtendedProperties_Shared {..} =
Core.toJSON additional
-- | A gadget that extends this event. Gadgets are deprecated; this structure is instead only used for returning birthday calendar metadata.
--
-- /See:/ 'newEvent_Gadget' smart constructor.
data Event_Gadget = Event_Gadget
{ -- | The gadget\'s display mode. Deprecated. Possible values are:
-- - \"icon\" - The gadget displays next to the event\'s title in the calendar view. - \"chip\" - The gadget displays when the event is clicked.
display :: (Core.Maybe Core.Text),
-- | The gadget\'s height in pixels. The height must be an integer greater than 0. Optional. Deprecated.
height :: (Core.Maybe Core.Int32),
-- | The gadget\'s icon URL. The URL scheme must be HTTPS. Deprecated.
iconLink :: (Core.Maybe Core.Text),
-- | The gadget\'s URL. The URL scheme must be HTTPS. Deprecated.
link :: (Core.Maybe Core.Text),
-- | Preferences.
preferences :: (Core.Maybe Event_Gadget_Preferences),
-- | The gadget\'s title. Deprecated.
title :: (Core.Maybe Core.Text),
-- | The gadget\'s type. Deprecated.
type' :: (Core.Maybe Core.Text),
-- | The gadget\'s width in pixels. The width must be an integer greater than 0. Optional. Deprecated.
width :: (Core.Maybe Core.Int32)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Event_Gadget' with the minimum fields required to make a request.
newEvent_Gadget ::
Event_Gadget
newEvent_Gadget =
Event_Gadget
{ display = Core.Nothing,
height = Core.Nothing,
iconLink = Core.Nothing,
link = Core.Nothing,
preferences = Core.Nothing,
title = Core.Nothing,
type' = Core.Nothing,
width = Core.Nothing
}
instance Core.FromJSON Event_Gadget where
parseJSON =
Core.withObject
"Event_Gadget"
( \o ->
Event_Gadget
Core.<$> (o Core..:? "display")
Core.<*> (o Core..:? "height")
Core.<*> (o Core..:? "iconLink")
Core.<*> (o Core..:? "link")
Core.<*> (o Core..:? "preferences")
Core.<*> (o Core..:? "title")
Core.<*> (o Core..:? "type")
Core.<*> (o Core..:? "width")
)
instance Core.ToJSON Event_Gadget where
toJSON Event_Gadget {..} =
Core.object
( Core.catMaybes
[ ("display" Core..=) Core.<$> display,
("height" Core..=) Core.<$> height,
("iconLink" Core..=) Core.<$> iconLink,
("link" Core..=) Core.<$> link,
("preferences" Core..=) Core.<$> preferences,
("title" Core..=) Core.<$> title,
("type" Core..=) Core.<$> type',
("width" Core..=) Core.<$> width
]
)
-- | Preferences.
--
-- /See:/ 'newEvent_Gadget_Preferences' smart constructor.
newtype Event_Gadget_Preferences = Event_Gadget_Preferences
{ -- | The preference name and corresponding value.
additional :: (Core.HashMap Core.Text Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Event_Gadget_Preferences' with the minimum fields required to make a request.
newEvent_Gadget_Preferences ::
-- | The preference name and corresponding value. See 'additional'.
Core.HashMap Core.Text Core.Text ->
Event_Gadget_Preferences
newEvent_Gadget_Preferences additional =
Event_Gadget_Preferences {additional = additional}
instance Core.FromJSON Event_Gadget_Preferences where
parseJSON =
Core.withObject
"Event_Gadget_Preferences"
( \o ->
Event_Gadget_Preferences
Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Event_Gadget_Preferences where
toJSON Event_Gadget_Preferences {..} =
Core.toJSON additional
-- | The organizer of the event. If the organizer is also an attendee, this is indicated with a separate entry in attendees with the organizer field set to True. To change the organizer, use the move operation. Read-only, except when importing an event.
--
-- /See:/ 'newEvent_Organizer' smart constructor.
data Event_Organizer = Event_Organizer
{ -- | The organizer\'s name, if available.
displayName :: (Core.Maybe Core.Text),
| The organizer\ 's email address , if available . It must be a valid email address as per RFC5322 .
email :: (Core.Maybe Core.Text),
-- | The organizer\'s Profile ID, if available.
id :: (Core.Maybe Core.Text),
-- | Whether the organizer corresponds to the calendar on which this copy of the event appears. Read-only. The default is False.
self :: Core.Bool
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Event_Organizer' with the minimum fields required to make a request.
newEvent_Organizer ::
Event_Organizer
newEvent_Organizer =
Event_Organizer
{ displayName = Core.Nothing,
email = Core.Nothing,
id = Core.Nothing,
self = Core.False
}
instance Core.FromJSON Event_Organizer where
parseJSON =
Core.withObject
"Event_Organizer"
( \o ->
Event_Organizer
Core.<$> (o Core..:? "displayName")
Core.<*> (o Core..:? "email")
Core.<*> (o Core..:? "id")
Core.<*> (o Core..:? "self" Core..!= Core.False)
)
instance Core.ToJSON Event_Organizer where
toJSON Event_Organizer {..} =
Core.object
( Core.catMaybes
[ ("displayName" Core..=) Core.<$> displayName,
("email" Core..=) Core.<$> email,
("id" Core..=) Core.<$> id,
Core.Just ("self" Core..= self)
]
)
-- | Information about the event\'s reminders for the authenticated user.
--
-- /See:/ 'newEvent_Reminders' smart constructor.
data Event_Reminders = Event_Reminders
| If the event doesn\'t use the default reminders , this lists the reminders specific to the event , or , if not set , indicates that no reminders are set for this event . The maximum number of override reminders is 5 .
overrides :: (Core.Maybe [EventReminder]),
-- | Whether the default reminders of the calendar apply to the event.
useDefault :: (Core.Maybe Core.Bool)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Event_Reminders' with the minimum fields required to make a request.
newEvent_Reminders ::
Event_Reminders
newEvent_Reminders =
Event_Reminders {overrides = Core.Nothing, useDefault = Core.Nothing}
instance Core.FromJSON Event_Reminders where
parseJSON =
Core.withObject
"Event_Reminders"
( \o ->
Event_Reminders
Core.<$> (o Core..:? "overrides")
Core.<*> (o Core..:? "useDefault")
)
instance Core.ToJSON Event_Reminders where
toJSON Event_Reminders {..} =
Core.object
( Core.catMaybes
[ ("overrides" Core..=) Core.<$> overrides,
("useDefault" Core..=) Core.<$> useDefault
]
)
-- | Source from which the event was created. For example, a web page, an email message or any document identifiable by an URL with HTTP or HTTPS scheme. Can only be seen or modified by the creator of the event.
--
-- /See:/ 'newEvent_Source' smart constructor.
data Event_Source = Event_Source
{ -- | Title of the source; for example a title of a web page or an email subject.
title :: (Core.Maybe Core.Text),
-- | URL of the source pointing to a resource. The URL scheme must be HTTP or HTTPS.
url :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Event_Source' with the minimum fields required to make a request.
newEvent_Source ::
Event_Source
newEvent_Source = Event_Source {title = Core.Nothing, url = Core.Nothing}
instance Core.FromJSON Event_Source where
parseJSON =
Core.withObject
"Event_Source"
( \o ->
Event_Source
Core.<$> (o Core..:? "title") Core.<*> (o Core..:? "url")
)
instance Core.ToJSON Event_Source where
toJSON Event_Source {..} =
Core.object
( Core.catMaybes
[ ("title" Core..=) Core.<$> title,
("url" Core..=) Core.<$> url
]
)
--
-- /See:/ 'newEventAttachment' smart constructor.
data EventAttachment = EventAttachment
| ID of the attached file . Read - only . For Google Drive files , this is the ID of the corresponding Files resource entry in the Drive API .
fileId :: (Core.Maybe Core.Text),
| URL link to the attachment . For adding Google Drive file attachments use the same format as in alternateLink property of the Files resource in the Drive API . Required when adding an attachment .
fileUrl :: (Core.Maybe Core.Text),
-- | URL link to the attachment\'s icon. Read-only.
iconLink :: (Core.Maybe Core.Text),
-- | Internet media type (MIME type) of the attachment.
mimeType :: (Core.Maybe Core.Text),
-- | Attachment title.
title :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'EventAttachment' with the minimum fields required to make a request.
newEventAttachment ::
EventAttachment
newEventAttachment =
EventAttachment
{ fileId = Core.Nothing,
fileUrl = Core.Nothing,
iconLink = Core.Nothing,
mimeType = Core.Nothing,
title = Core.Nothing
}
instance Core.FromJSON EventAttachment where
parseJSON =
Core.withObject
"EventAttachment"
( \o ->
EventAttachment
Core.<$> (o Core..:? "fileId")
Core.<*> (o Core..:? "fileUrl")
Core.<*> (o Core..:? "iconLink")
Core.<*> (o Core..:? "mimeType")
Core.<*> (o Core..:? "title")
)
instance Core.ToJSON EventAttachment where
toJSON EventAttachment {..} =
Core.object
( Core.catMaybes
[ ("fileId" Core..=) Core.<$> fileId,
("fileUrl" Core..=) Core.<$> fileUrl,
("iconLink" Core..=) Core.<$> iconLink,
("mimeType" Core..=) Core.<$> mimeType,
("title" Core..=) Core.<$> title
]
)
--
-- /See:/ 'newEventAttendee' smart constructor.
data EventAttendee = EventAttendee
{ -- | Number of additional guests. Optional. The default is 0.
additionalGuests :: Core.Int32,
-- | The attendee\'s response comment. Optional.
comment :: (Core.Maybe Core.Text),
-- | The attendee\'s name, if available. Optional.
displayName :: (Core.Maybe Core.Text),
| The attendee\ 's email address , if available . This field must be present when adding an attendee . It must be a valid email address as per RFC5322 . Required when adding an attendee .
email :: (Core.Maybe Core.Text),
-- | The attendee\'s Profile ID, if available.
id :: (Core.Maybe Core.Text),
-- | Whether this is an optional attendee. Optional. The default is False.
optional :: Core.Bool,
-- | Whether the attendee is the organizer of the event. Read-only. The default is False.
organizer :: (Core.Maybe Core.Bool),
| Whether the attendee is a resource . Can only be set when the attendee is added to the event for the first time . Subsequent modifications are ignored . Optional . The default is False .
resource :: Core.Bool,
-- | The attendee\'s response status. Possible values are:
-- - \"needsAction\" - The attendee has not responded to the invitation. - \"declined\" - The attendee has declined the invitation. - \"tentative\" - The attendee has tentatively accepted the invitation. - \"accepted\" - The attendee has accepted the invitation.
responseStatus :: (Core.Maybe Core.Text),
-- | Whether this entry represents the calendar on which this copy of the event appears. Read-only. The default is False.
self :: Core.Bool
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' EventAttendee ' with the minimum fields required to make a request .
newEventAttendee ::
EventAttendee
newEventAttendee =
EventAttendee
{ additionalGuests = 0,
comment = Core.Nothing,
displayName = Core.Nothing,
email = Core.Nothing,
id = Core.Nothing,
optional = Core.False,
organizer = Core.Nothing,
resource = Core.False,
responseStatus = Core.Nothing,
self = Core.False
}
instance Core.FromJSON EventAttendee where
parseJSON =
Core.withObject
"EventAttendee"
( \o ->
EventAttendee
Core.<$> (o Core..:? "additionalGuests" Core..!= 0)
Core.<*> (o Core..:? "comment")
Core.<*> (o Core..:? "displayName")
Core.<*> (o Core..:? "email")
Core.<*> (o Core..:? "id")
Core.<*> (o Core..:? "optional" Core..!= Core.False)
Core.<*> (o Core..:? "organizer")
Core.<*> (o Core..:? "resource" Core..!= Core.False)
Core.<*> (o Core..:? "responseStatus")
Core.<*> (o Core..:? "self" Core..!= Core.False)
)
instance Core.ToJSON EventAttendee where
toJSON EventAttendee {..} =
Core.object
( Core.catMaybes
[ Core.Just
("additionalGuests" Core..= additionalGuests),
("comment" Core..=) Core.<$> comment,
("displayName" Core..=) Core.<$> displayName,
("email" Core..=) Core.<$> email,
("id" Core..=) Core.<$> id,
Core.Just ("optional" Core..= optional),
("organizer" Core..=) Core.<$> organizer,
Core.Just ("resource" Core..= resource),
("responseStatus" Core..=) Core.<$> responseStatus,
Core.Just ("self" Core..= self)
]
)
--
-- /See:/ 'newEventDateTime' smart constructor.
data EventDateTime = EventDateTime
| The date , in the format \"yyyy - mm - dd\ " , if this is an all - day event .
date :: (Core.Maybe Core.Date),
| The time , as a combined date - time value ( formatted according to ) . A time zone offset is required unless a time zone is explicitly specified in timeZone .
dateTime :: (Core.Maybe Core.DateTime),
-- | The time zone in which the time is specified. (Formatted as an IANA Time Zone Database name, e.g. \"Europe\/Zurich\".) For recurring events this field is required and specifies the time zone in which the recurrence is expanded. For single events this field is optional and indicates a custom time zone for the event start\/end.
timeZone :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'EventDateTime' with the minimum fields required to make a request.
newEventDateTime ::
EventDateTime
newEventDateTime =
EventDateTime
{ date = Core.Nothing,
dateTime = Core.Nothing,
timeZone = Core.Nothing
}
instance Core.FromJSON EventDateTime where
parseJSON =
Core.withObject
"EventDateTime"
( \o ->
EventDateTime
Core.<$> (o Core..:? "date")
Core.<*> (o Core..:? "dateTime")
Core.<*> (o Core..:? "timeZone")
)
instance Core.ToJSON EventDateTime where
toJSON EventDateTime {..} =
Core.object
( Core.catMaybes
[ ("date" Core..=) Core.<$> date,
("dateTime" Core..=) Core.<$> dateTime,
("timeZone" Core..=) Core.<$> timeZone
]
)
--
-- /See:/ 'newEventReminder' smart constructor.
data EventReminder = EventReminder
{ -- | The method used by this reminder. Possible values are:
-- - \"email\" - Reminders are sent via email. - \"popup\" - Reminders are sent via a UI popup.
-- Required when adding a reminder.
method :: (Core.Maybe Core.Text),
| Number of minutes before the start of the event when the reminder should trigger . Valid values are between 0 and 40320 ( 4 weeks in minutes ) . Required when adding a reminder .
minutes :: (Core.Maybe Core.Int32)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'EventReminder' with the minimum fields required to make a request.
newEventReminder ::
EventReminder
newEventReminder = EventReminder {method = Core.Nothing, minutes = Core.Nothing}
instance Core.FromJSON EventReminder where
parseJSON =
Core.withObject
"EventReminder"
( \o ->
EventReminder
Core.<$> (o Core..:? "method")
Core.<*> (o Core..:? "minutes")
)
instance Core.ToJSON EventReminder where
toJSON EventReminder {..} =
Core.object
( Core.catMaybes
[ ("method" Core..=) Core.<$> method,
("minutes" Core..=) Core.<$> minutes
]
)
--
-- /See:/ 'newEvents' smart constructor.
data Events = Events
{ -- | The user\'s access role for this calendar. Read-only. Possible values are:
- \"none\ " - The user has no access . - \"freeBusyReader\ " - The user has read access to free\/busy information . - \"reader\ " - The user has read access to the calendar . Private events will appear to users with reader access , but event details will be hidden . - \"writer\ " - The user has read and write access to the calendar . Private events will appear to users with writer access , and event details will be visible . - \"owner\ " - The user has ownership of the calendar . This role has all of the permissions of the writer role with the additional ability to see and manipulate ACLs .
accessRole :: (Core.Maybe Core.Text),
-- | The default reminders on the calendar for the authenticated user. These reminders apply to all events on this calendar that do not explicitly override them (i.e. do not have reminders.useDefault set to True).
defaultReminders :: (Core.Maybe [EventReminder]),
-- | Description of the calendar. Read-only.
description :: (Core.Maybe Core.Text),
-- | ETag of the collection.
etag :: (Core.Maybe Core.Text),
-- | List of events on the calendar.
items :: (Core.Maybe [Event]),
| Type of the collection ( \"calendar#events\ " ) .
kind :: Core.Text,
| Token used to access the next page of this result . Omitted if no further results are available , in which case nextSyncToken is provided .
nextPageToken :: (Core.Maybe Core.Text),
| Token used at a later point in time to retrieve only the entries that have changed since this result was returned . Omitted if further results are available , in which case is provided .
nextSyncToken :: (Core.Maybe Core.Text),
-- | Title of the calendar. Read-only.
summary :: (Core.Maybe Core.Text),
-- | The time zone of the calendar. Read-only.
timeZone :: (Core.Maybe Core.Text),
-- | Last modification time of the calendar (as a RFC3339 timestamp). Read-only.
updated :: (Core.Maybe Core.DateTime)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Events' with the minimum fields required to make a request.
newEvents ::
Events
newEvents =
Events
{ accessRole = Core.Nothing,
defaultReminders = Core.Nothing,
description = Core.Nothing,
etag = Core.Nothing,
items = Core.Nothing,
kind = "calendar#events",
nextPageToken = Core.Nothing,
nextSyncToken = Core.Nothing,
summary = Core.Nothing,
timeZone = Core.Nothing,
updated = Core.Nothing
}
instance Core.FromJSON Events where
parseJSON =
Core.withObject
"Events"
( \o ->
Events
Core.<$> (o Core..:? "accessRole")
Core.<*> (o Core..:? "defaultReminders")
Core.<*> (o Core..:? "description")
Core.<*> (o Core..:? "etag")
Core.<*> (o Core..:? "items")
Core.<*> (o Core..:? "kind" Core..!= "calendar#events")
Core.<*> (o Core..:? "nextPageToken")
Core.<*> (o Core..:? "nextSyncToken")
Core.<*> (o Core..:? "summary")
Core.<*> (o Core..:? "timeZone")
Core.<*> (o Core..:? "updated")
)
instance Core.ToJSON Events where
toJSON Events {..} =
Core.object
( Core.catMaybes
[ ("accessRole" Core..=) Core.<$> accessRole,
("defaultReminders" Core..=)
Core.<$> defaultReminders,
("description" Core..=) Core.<$> description,
("etag" Core..=) Core.<$> etag,
("items" Core..=) Core.<$> items,
Core.Just ("kind" Core..= kind),
("nextPageToken" Core..=) Core.<$> nextPageToken,
("nextSyncToken" Core..=) Core.<$> nextSyncToken,
("summary" Core..=) Core.<$> summary,
("timeZone" Core..=) Core.<$> timeZone,
("updated" Core..=) Core.<$> updated
]
)
--
-- /See:/ 'newFreeBusyCalendar' smart constructor.
data FreeBusyCalendar = FreeBusyCalendar
{ -- | List of time ranges during which this calendar should be regarded as busy.
busy :: (Core.Maybe [TimePeriod]),
-- | Optional error(s) (if computation for the calendar failed).
errors :: (Core.Maybe [Error'])
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'FreeBusyCalendar' with the minimum fields required to make a request.
newFreeBusyCalendar ::
FreeBusyCalendar
newFreeBusyCalendar =
FreeBusyCalendar {busy = Core.Nothing, errors = Core.Nothing}
instance Core.FromJSON FreeBusyCalendar where
parseJSON =
Core.withObject
"FreeBusyCalendar"
( \o ->
FreeBusyCalendar
Core.<$> (o Core..:? "busy") Core.<*> (o Core..:? "errors")
)
instance Core.ToJSON FreeBusyCalendar where
toJSON FreeBusyCalendar {..} =
Core.object
( Core.catMaybes
[ ("busy" Core..=) Core.<$> busy,
("errors" Core..=) Core.<$> errors
]
)
--
-- /See:/ 'newFreeBusyGroup' smart constructor.
data FreeBusyGroup = FreeBusyGroup
{ -- | List of calendars\' identifiers within a group.
calendars :: (Core.Maybe [Core.Text]),
-- | Optional error(s) (if computation for the group failed).
errors :: (Core.Maybe [Error'])
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'FreeBusyGroup' with the minimum fields required to make a request.
newFreeBusyGroup ::
FreeBusyGroup
newFreeBusyGroup =
FreeBusyGroup {calendars = Core.Nothing, errors = Core.Nothing}
instance Core.FromJSON FreeBusyGroup where
parseJSON =
Core.withObject
"FreeBusyGroup"
( \o ->
FreeBusyGroup
Core.<$> (o Core..:? "calendars")
Core.<*> (o Core..:? "errors")
)
instance Core.ToJSON FreeBusyGroup where
toJSON FreeBusyGroup {..} =
Core.object
( Core.catMaybes
[ ("calendars" Core..=) Core.<$> calendars,
("errors" Core..=) Core.<$> errors
]
)
--
-- /See:/ 'newFreeBusyRequest' smart constructor.
data FreeBusyRequest = FreeBusyRequest
| Maximal number of calendars for which FreeBusy information is to be provided . Optional . Maximum value is 50 .
calendarExpansionMax :: (Core.Maybe Core.Int32),
| Maximal number of calendar identifiers to be provided for a single group . Optional . An error is returned for a group with more members than this value . Maximum value is 100 .
groupExpansionMax :: (Core.Maybe Core.Int32),
-- | List of calendars and\/or groups to query.
items :: (Core.Maybe [FreeBusyRequestItem]),
-- | The end of the interval for the query formatted as per RFC3339.
timeMax :: (Core.Maybe Core.DateTime),
-- | The start of the interval for the query formatted as per RFC3339.
timeMin :: (Core.Maybe Core.DateTime),
-- | Time zone used in the response. Optional. The default is UTC.
timeZone :: Core.Text
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'FreeBusyRequest' with the minimum fields required to make a request.
newFreeBusyRequest ::
FreeBusyRequest
newFreeBusyRequest =
FreeBusyRequest
{ calendarExpansionMax = Core.Nothing,
groupExpansionMax = Core.Nothing,
items = Core.Nothing,
timeMax = Core.Nothing,
timeMin = Core.Nothing,
timeZone = "UTC"
}
instance Core.FromJSON FreeBusyRequest where
parseJSON =
Core.withObject
"FreeBusyRequest"
( \o ->
FreeBusyRequest
Core.<$> (o Core..:? "calendarExpansionMax")
Core.<*> (o Core..:? "groupExpansionMax")
Core.<*> (o Core..:? "items")
Core.<*> (o Core..:? "timeMax")
Core.<*> (o Core..:? "timeMin")
Core.<*> (o Core..:? "timeZone" Core..!= "UTC")
)
instance Core.ToJSON FreeBusyRequest where
toJSON FreeBusyRequest {..} =
Core.object
( Core.catMaybes
[ ("calendarExpansionMax" Core..=)
Core.<$> calendarExpansionMax,
("groupExpansionMax" Core..=)
Core.<$> groupExpansionMax,
("items" Core..=) Core.<$> items,
("timeMax" Core..=) Core.<$> timeMax,
("timeMin" Core..=) Core.<$> timeMin,
Core.Just ("timeZone" Core..= timeZone)
]
)
--
-- /See:/ 'newFreeBusyRequestItem' smart constructor.
newtype FreeBusyRequestItem = FreeBusyRequestItem
{ -- | The identifier of a calendar or a group.
id :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' ' with the minimum fields required to make a request .
newFreeBusyRequestItem ::
FreeBusyRequestItem
newFreeBusyRequestItem = FreeBusyRequestItem {id = Core.Nothing}
instance Core.FromJSON FreeBusyRequestItem where
parseJSON =
Core.withObject
"FreeBusyRequestItem"
( \o ->
FreeBusyRequestItem Core.<$> (o Core..:? "id")
)
instance Core.ToJSON FreeBusyRequestItem where
toJSON FreeBusyRequestItem {..} =
Core.object
(Core.catMaybes [("id" Core..=) Core.<$> id])
--
-- /See:/ 'newFreeBusyResponse' smart constructor.
data FreeBusyResponse = FreeBusyResponse
{ -- | List of free\/busy information for calendars.
calendars :: (Core.Maybe FreeBusyResponse_Calendars),
-- | Expansion of groups.
groups :: (Core.Maybe FreeBusyResponse_Groups),
-- | Type of the resource (\"calendar#freeBusy\").
kind :: Core.Text,
-- | The end of the interval.
timeMax :: (Core.Maybe Core.DateTime),
-- | The start of the interval.
timeMin :: (Core.Maybe Core.DateTime)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'FreeBusyResponse' with the minimum fields required to make a request.
newFreeBusyResponse ::
FreeBusyResponse
newFreeBusyResponse =
FreeBusyResponse
{ calendars = Core.Nothing,
groups = Core.Nothing,
kind = "calendar#freeBusy",
timeMax = Core.Nothing,
timeMin = Core.Nothing
}
instance Core.FromJSON FreeBusyResponse where
parseJSON =
Core.withObject
"FreeBusyResponse"
( \o ->
FreeBusyResponse
Core.<$> (o Core..:? "calendars")
Core.<*> (o Core..:? "groups")
Core.<*> (o Core..:? "kind" Core..!= "calendar#freeBusy")
Core.<*> (o Core..:? "timeMax")
Core.<*> (o Core..:? "timeMin")
)
instance Core.ToJSON FreeBusyResponse where
toJSON FreeBusyResponse {..} =
Core.object
( Core.catMaybes
[ ("calendars" Core..=) Core.<$> calendars,
("groups" Core..=) Core.<$> groups,
Core.Just ("kind" Core..= kind),
("timeMax" Core..=) Core.<$> timeMax,
("timeMin" Core..=) Core.<$> timeMin
]
)
-- | List of free\/busy information for calendars.
--
-- /See:/ 'newFreeBusyResponse_Calendars' smart constructor.
newtype FreeBusyResponse_Calendars = FreeBusyResponse_Calendars
{ -- | Free\/busy expansions for a single calendar.
additional :: (Core.HashMap Core.Text FreeBusyCalendar)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'FreeBusyResponse_Calendars' with the minimum fields required to make a request.
newFreeBusyResponse_Calendars ::
-- | Free\/busy expansions for a single calendar. See 'additional'.
Core.HashMap Core.Text FreeBusyCalendar ->
FreeBusyResponse_Calendars
newFreeBusyResponse_Calendars additional =
FreeBusyResponse_Calendars {additional = additional}
instance Core.FromJSON FreeBusyResponse_Calendars where
parseJSON =
Core.withObject
"FreeBusyResponse_Calendars"
( \o ->
FreeBusyResponse_Calendars
Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON FreeBusyResponse_Calendars where
toJSON FreeBusyResponse_Calendars {..} =
Core.toJSON additional
-- | Expansion of groups.
--
-- /See:/ 'newFreeBusyResponse_Groups' smart constructor.
newtype FreeBusyResponse_Groups = FreeBusyResponse_Groups
{ -- | List of calendars that are members of this group.
additional :: (Core.HashMap Core.Text FreeBusyGroup)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'FreeBusyResponse_Groups' with the minimum fields required to make a request.
newFreeBusyResponse_Groups ::
-- | List of calendars that are members of this group. See 'additional'.
Core.HashMap Core.Text FreeBusyGroup ->
FreeBusyResponse_Groups
newFreeBusyResponse_Groups additional =
FreeBusyResponse_Groups {additional = additional}
instance Core.FromJSON FreeBusyResponse_Groups where
parseJSON =
Core.withObject
"FreeBusyResponse_Groups"
( \o ->
FreeBusyResponse_Groups
Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON FreeBusyResponse_Groups where
toJSON FreeBusyResponse_Groups {..} =
Core.toJSON additional
--
-- /See:/ 'newSetting' smart constructor.
data Setting = Setting
{ -- | ETag of the resource.
etag :: (Core.Maybe Core.Text),
-- | The id of the user setting.
id :: (Core.Maybe Core.Text),
-- | Type of the resource (\"calendar#setting\").
kind :: Core.Text,
| Value of the user setting . The format of the value depends on the ID of the setting . It must always be a UTF-8 string of length up to 1024 characters .
value :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Setting' with the minimum fields required to make a request.
newSetting ::
Setting
newSetting =
Setting
{ etag = Core.Nothing,
id = Core.Nothing,
kind = "calendar#setting",
value = Core.Nothing
}
instance Core.FromJSON Setting where
parseJSON =
Core.withObject
"Setting"
( \o ->
Setting
Core.<$> (o Core..:? "etag")
Core.<*> (o Core..:? "id")
Core.<*> (o Core..:? "kind" Core..!= "calendar#setting")
Core.<*> (o Core..:? "value")
)
instance Core.ToJSON Setting where
toJSON Setting {..} =
Core.object
( Core.catMaybes
[ ("etag" Core..=) Core.<$> etag,
("id" Core..=) Core.<$> id,
Core.Just ("kind" Core..= kind),
("value" Core..=) Core.<$> value
]
)
--
/See:/ ' newSettings ' smart constructor .
data Settings = Settings
{ -- | Etag of the collection.
etag :: (Core.Maybe Core.Text),
-- | List of user settings.
items :: (Core.Maybe [Setting]),
-- | Type of the collection (\"calendar#settings\").
kind :: Core.Text,
| Token used to access the next page of this result . Omitted if no further results are available , in which case nextSyncToken is provided .
nextPageToken :: (Core.Maybe Core.Text),
| Token used at a later point in time to retrieve only the entries that have changed since this result was returned . Omitted if further results are available , in which case is provided .
nextSyncToken :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Settings' with the minimum fields required to make a request.
newSettings ::
Settings
newSettings =
Settings
{ etag = Core.Nothing,
items = Core.Nothing,
kind = "calendar#settings",
nextPageToken = Core.Nothing,
nextSyncToken = Core.Nothing
}
instance Core.FromJSON Settings where
parseJSON =
Core.withObject
"Settings"
( \o ->
Settings
Core.<$> (o Core..:? "etag")
Core.<*> (o Core..:? "items")
Core.<*> (o Core..:? "kind" Core..!= "calendar#settings")
Core.<*> (o Core..:? "nextPageToken")
Core.<*> (o Core..:? "nextSyncToken")
)
instance Core.ToJSON Settings where
toJSON Settings {..} =
Core.object
( Core.catMaybes
[ ("etag" Core..=) Core.<$> etag,
("items" Core..=) Core.<$> items,
Core.Just ("kind" Core..= kind),
("nextPageToken" Core..=) Core.<$> nextPageToken,
("nextSyncToken" Core..=) Core.<$> nextSyncToken
]
)
--
-- /See:/ 'newTimePeriod' smart constructor.
data TimePeriod = TimePeriod
{ -- | The (exclusive) end of the time period.
end :: (Core.Maybe Core.DateTime),
-- | The (inclusive) start of the time period.
start :: (Core.Maybe Core.DateTime)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'TimePeriod' with the minimum fields required to make a request.
newTimePeriod ::
TimePeriod
newTimePeriod = TimePeriod {end = Core.Nothing, start = Core.Nothing}
instance Core.FromJSON TimePeriod where
parseJSON =
Core.withObject
"TimePeriod"
( \o ->
TimePeriod
Core.<$> (o Core..:? "end") Core.<*> (o Core..:? "start")
)
instance Core.ToJSON TimePeriod where
toJSON TimePeriod {..} =
Core.object
( Core.catMaybes
[ ("end" Core..=) Core.<$> end,
("start" Core..=) Core.<$> start
]
)
| null | https://raw.githubusercontent.com/brendanhay/gogol/8cbceeaaba36a3c08712b2e272606161500fbe91/lib/services/gogol-apps-calendar/gen/Gogol/AppsCalendar/Internal/Product.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE StrictData #
|
Stability : auto-generated
* AclRule
* AclRule_Scope
* Calendar
* CalendarListEntry
* CalendarListEntry_NotificationSettings
* Channel
* Channel_Params
* ColorDefinition
* Colors
* Colors_Event
* ConferenceParameters
* ConferenceParametersAddOnParameters
* ConferenceParametersAddOnParameters_Parameters
* ConferenceProperties
* ConferenceSolution
* ConferenceSolutionKey
* EntryPoint
* Error'
* Event
* Event_Creator
* Event_ExtendedProperties_Private
* Event_ExtendedProperties_Shared
* Event_Gadget
* Event_Gadget_Preferences
* Event_Organizer
* Event_Reminders
* Event_Source
* EventAttachment
* EventDateTime
* EventReminder
* Events
* FreeBusyCalendar
* FreeBusyGroup
* FreeBusyRequest
* FreeBusyResponse_Calendars
* FreeBusyResponse_Groups
* Setting
* Settings
* TimePeriod
/See:/ 'newAcl' smart constructor.
| ETag of the collection.
| List of rules on the access control list.
| Type of the collection (\"calendar#acl\").
/See:/ 'newAclRule' smart constructor.
| ETag of the resource.
| Type of the resource (\"calendar#aclRule\").
| The role assigned to the scope. Possible values are:
| Creates a value of 'AclRule' with the minimum fields required to make a request.
/See:/ 'newAclRule_Scope' smart constructor.
| The type of the scope. Possible values are:
- \"default\" - The public scope. This is the default value. - \"user\" - Limits the scope to a single user. - \"group\" - Limits the scope to a group. - \"domain\" - Limits the scope to a domain. Note: The permissions granted to the \"default\", or public, scope apply to any user, authenticated or not.
| The email address of a user or group, or the name of a domain, depending on the scope type. Omitted for type \"default\".
| Conferencing properties for this calendar, for example what types of conferences are allowed.
| Description of the calendar. Optional.
| ETag of the resource.
| Type of the resource (\"calendar#calendar\").
| Geographic location of the calendar as free-form text. Optional.
| Title of the calendar.
| The time zone of the calendar. (Formatted as an IANA Time Zone Database name, e.g. \"Europe\/Zurich\".) Optional.
| Creates a value of 'Calendar' with the minimum fields required to make a request.
/See:/ 'newCalendarList' smart constructor.
| ETag of the collection.
| Calendars that are present on the user\'s calendar list.
| Type of the collection (\"calendar#calendarList\").
| Creates a value of 'CalendarList' with the minimum fields required to make a request.
/See:/ 'newCalendarListEntry' smart constructor.
| The effective access role that the authenticated user has on the calendar. Read-only. Possible values are:
| The main color of the calendar in the hexadecimal format \"#0088aa\". This property supersedes the index-based colorId property. To set or change this property, you need to specify colorRgbFormat=true in the parameters of the insert, update and patch methods. Optional.
| Conferencing properties for this calendar, for example what types of conferences are allowed.
| The default reminders that the authenticated user has for this calendar.
| Whether this calendar list entry has been deleted from the calendar list. Read-only. Optional. The default is False.
| Description of the calendar. Optional. Read-only.
| ETag of the resource.
| The foreground color of the calendar in the hexadecimal format \"#ffffff\". This property supersedes the index-based colorId property. To set or change this property, you need to specify colorRgbFormat=true in the parameters of the insert, update and patch methods. Optional.
| Whether the calendar has been hidden from the list. Optional. The attribute is only returned when the calendar is hidden, in which case the value is true.
| Identifier of the calendar.
| Type of the resource (\"calendar#calendarListEntry\").
| Geographic location of the calendar as free-form text. Optional. Read-only.
| The notifications that the authenticated user is receiving for this calendar.
| Whether the calendar is the primary calendar of the authenticated user. Read-only. Optional. The default is False.
| Whether the calendar content shows up in the calendar UI. Optional. The default is False.
| Title of the calendar. Read-only.
| The summary that the authenticated user has set for this calendar. Optional.
| The time zone of the calendar. Optional. Read-only.
| Creates a value of 'CalendarListEntry' with the minimum fields required to make a request.
| The notifications that the authenticated user is receiving for this calendar.
/See:/ 'newCalendarListEntry_NotificationSettings' smart constructor.
| The list of notifications set for this calendar.
| Creates a value of 'CalendarListEntry_NotificationSettings' with the minimum fields required to make a request.
/See:/ 'newCalendarNotification' smart constructor.
| The method used to deliver the notification. The possible value is:
- \"email\" - Notifications are sent via email.
Required when adding a notification.
| The type of notification. Possible values are:
Required when adding a notification.
| The address where notifications are delivered for this channel.
| Date and time of notification channel expiration, expressed as a Unix timestamp, in milliseconds. Optional.
| A UUID or similar unique string that identifies this channel.
| Identifies this as a notification channel used to watch for changes to a resource, which is \"api#channel\".
| Additional parameters controlling delivery channel behavior. Optional.
| An opaque ID that identifies the resource being watched on this channel. Stable across different API versions.
| A version-specific identifier for the watched resource.
| An arbitrary string delivered to the target address with each notification delivered over this channel. Optional.
| Creates a value of 'Channel' with the minimum fields required to make a request.
| Additional parameters controlling delivery channel behavior. Optional.
/See:/ 'newChannel_Params' smart constructor.
| Declares a new parameter by name.
| Creates a value of 'Channel_Params' with the minimum fields required to make a request.
| Declares a new parameter by name. See 'additional'.
/See:/ 'newColorDefinition' smart constructor.
| The background color associated with this color definition.
| The foreground color that can be used to write on top of a background with \'background\' color.
| Creates a value of 'ColorDefinition' with the minimum fields required to make a request.
| Type of the resource (\"calendar#colors\").
| Last modification time of the color palette (as a RFC3339 timestamp). Read-only.
| Creates a value of 'Colors' with the minimum fields required to make a request.
| A calendar color definition.
| A calendar color definition. See 'additional'.
/See:/ 'newColors_Event' smart constructor.
| An event color definition.
| Creates a value of 'Colors_Event' with the minimum fields required to make a request.
| An event color definition. See 'additional'.
/See:/ 'newConferenceData' smart constructor.
| The ID of the conference. Can be used by developers to keep track of conferences, should not be displayed to users. The ID value is formed differently for each conference solution type:
| Additional properties related to a conference. An example would be a solution-specific setting for enabling video streaming.
/See:/ 'newConferenceParameters' smart constructor.
| Additional add-on specific data.
|
| Creates a value of 'ConferenceParametersAddOnParameters' with the minimum fields required to make a request.
/See:/ 'newConferenceParametersAddOnParameters_Parameters' smart constructor.
|
| Creates a value of 'ConferenceParametersAddOnParameters_Parameters' with the minimum fields required to make a request.
| See 'additional'.
/See:/ 'newConferenceProperties' smart constructor.
| The types of conference solutions that are supported for this calendar. The possible values are:
- \"eventHangout\" - \"eventNamedHangout\" - \"hangoutsMeet\" Optional.
| Creates a value of 'ConferenceProperties' with the minimum fields required to make a request.
| The current status of the conference create request. Read-only. The possible values are:
- \"pending\": the conference create request is still being processed. - \"success\": the conference create request succeeded, the entry points are populated. - \"failure\": the conference create request failed, there are no entry points.
/See:/ 'newConferenceSolution' smart constructor.
| The user-visible icon for this solution.
| The key which can uniquely identify the conference solution for this event.
| The user-visible name of this solution. Not localized.
/See:/ 'newConferenceSolutionKey' smart constructor.
| The conference solution type. If a client encounters an unfamiliar or empty type, it should still be able to display the entry points. However, it should disallow modifications. The possible values are:
| Creates a value of 'ConferenceSolutionKey' with the minimum fields required to make a request.
| The conference solution, such as Hangouts or Google Meet.
| The client-generated unique ID for this request. Clients should regenerate this ID for every new request. If an ID provided is the same as for the previous request, the request is ignored.
| The status of the conference create request.
| The type of the conference entry point. Possible values are:
Optional.
/See:/ 'newError' smart constructor.
| Domain, or broad category, of the error.
| Specific reason for the error. Some of the possible values are:
| Creates a value of 'Error' with the minimum fields required to make a request.
/See:/ 'newEvent' smart constructor.
| Whether anyone can invite themselves to the event (deprecated). Optional. The default is False.
| The attendees of the event. See the Events with attendees guide for more information on scheduling events with other calendar users. Service accounts need to use domain-wide delegation of authority to populate the attendee list.
| The color of the event. This is an ID referring to an entry in the event section of the colors definition (see the colors endpoint). Optional.
| Creation time of the event (as a RFC3339 timestamp). Read-only.
| The creator of the event. Read-only.
| Description of the event. Can contain HTML. Optional.
| Whether the end time is actually unspecified. An end time is still provided for compatibility reasons, even if this attribute is set to True. The default is False.
| ETag of the resource.
| Specific type of the event. Read-only. Possible values are:
- \"default\" - A regular event or not further specified. - \"outOfOffice\" - An out-of-office event. - \"focusTime\" - A focus-time event.
| Extended properties of the event.
| A gadget that extends this event. Gadgets are deprecated; this structure is instead only used for returning birthday calendar metadata.
| Whether attendees other than the organizer can invite others to the event. Optional. The default is True.
| Whether attendees other than the organizer can modify the event. Optional. The default is False.
| Whether attendees other than the organizer can see who the event\'s attendees are. Optional. The default is True.
| An absolute link to the Google Hangout associated with this event. Read-only.
| An absolute link to this event in the Google Calendar Web UI. Read-only.
| Opaque identifier of the event. When creating new single or recurring events, you can specify their IDs. Provided IDs must follow these rules:
| Type of the resource (\"calendar#event\").
| Geographic location of the event as free-form text. Optional.
| The organizer of the event. If the organizer is also an attendee, this is indicated with a separate entry in attendees with the organizer field set to True. To change the organizer, use the move operation. Read-only, except when importing an event.
| For an instance of a recurring event, this is the time at which this event would start according to the recurrence data in the recurring event identified by recurringEventId. It uniquely identifies the instance within the recurring event series even if the instance was moved to a different time. Immutable.
| If set to True, Event propagation is disabled. Note that it is not the same thing as Private event properties. Optional. Immutable. The default is False.
| For an instance of a recurring event, this is the id of the recurring event to which this instance belongs. Immutable.
| Information about the event\'s reminders for the authenticated user.
| Sequence number as per iCalendar.
| Source from which the event was created. For example, a web page, an email message or any document identifiable by an URL with HTTP or HTTPS scheme. Can only be seen or modified by the creator of the event.
| Status of the event. Optional. Possible values are:
- Cancelled exceptions of an uncancelled recurring event indicate that this instance should no longer be presented to the user. Clients should store these events for the lifetime of the parent recurring event. Cancelled exceptions are only guaranteed to have values for the id, recurringEventId and originalStartTime fields populated. The other fields might be empty.
- All other cancelled events represent deleted events. Clients should remove their locally synced copies. Such cancelled events will eventually disappear, so do not rely on them being available indefinitely. Deleted events are only guaranteed to have the id field populated. On the organizer\'s calendar, cancelled events continue to expose event details (summary, location, etc.) so that they can be restored (undeleted). Similarly, the events to which the user was invited and that they manually removed continue to provide details. However, incremental sync requests with showDeleted set to false will not return these details. If an event changes its organizer (for example via the move operation) and the original organizer is not on the attendee list, it will leave behind a cancelled event where only the id field is guaranteed to be populated.
| Title of the event.
| Whether the event blocks time on the calendar. Optional. Possible values are:
- \"opaque\" - Default value. The event does block time on the calendar. This is equivalent to setting Show me as to Busy in the Calendar UI. - \"transparent\" - The event does not block time on the calendar. This is equivalent to setting Show me as to Available in the Calendar UI.
| Last modification time of the event (as a RFC3339 timestamp). Read-only.
| Visibility of the event. Optional. Possible values are:
- \"default\" - Uses the default visibility for events on the calendar. This is the default value. - \"public\" - The event is public and event details are visible to all readers of the calendar. - \"private\" - The event is private and only event attendees may view event details. - \"confidential\" - The event is private. This value is provided for compatibility reasons.
| Creates a value of 'Event' with the minimum fields required to make a request.
| The creator of the event. Read-only.
/See:/ 'newEvent_Creator' smart constructor.
| The creator\'s name, if available.
| The creator\'s email address, if available.
| The creator\'s Profile ID, if available.
| Whether the creator corresponds to the calendar on which this copy of the event appears. Read-only. The default is False.
| Creates a value of 'Event_Creator' with the minimum fields required to make a request.
| Extended properties of the event.
/See:/ 'newEvent_ExtendedProperties' smart constructor.
| Properties that are private to the copy of the event that appears on this calendar.
| Properties that are private to the copy of the event that appears on this calendar.
/See:/ 'newEvent_ExtendedProperties_Private' smart constructor.
| The name of the private property and the corresponding value.
| Creates a value of 'Event_ExtendedProperties_Private' with the minimum fields required to make a request.
| The name of the private property and the corresponding value. See 'additional'.
/See:/ 'newEvent_ExtendedProperties_Shared' smart constructor.
| The name of the shared property and the corresponding value.
| Creates a value of 'Event_ExtendedProperties_Shared' with the minimum fields required to make a request.
| The name of the shared property and the corresponding value. See 'additional'.
| A gadget that extends this event. Gadgets are deprecated; this structure is instead only used for returning birthday calendar metadata.
/See:/ 'newEvent_Gadget' smart constructor.
| The gadget\'s display mode. Deprecated. Possible values are:
- \"icon\" - The gadget displays next to the event\'s title in the calendar view. - \"chip\" - The gadget displays when the event is clicked.
| The gadget\'s height in pixels. The height must be an integer greater than 0. Optional. Deprecated.
| The gadget\'s icon URL. The URL scheme must be HTTPS. Deprecated.
| The gadget\'s URL. The URL scheme must be HTTPS. Deprecated.
| Preferences.
| The gadget\'s title. Deprecated.
| The gadget\'s type. Deprecated.
| The gadget\'s width in pixels. The width must be an integer greater than 0. Optional. Deprecated.
| Creates a value of 'Event_Gadget' with the minimum fields required to make a request.
| Preferences.
/See:/ 'newEvent_Gadget_Preferences' smart constructor.
| The preference name and corresponding value.
| Creates a value of 'Event_Gadget_Preferences' with the minimum fields required to make a request.
| The preference name and corresponding value. See 'additional'.
| The organizer of the event. If the organizer is also an attendee, this is indicated with a separate entry in attendees with the organizer field set to True. To change the organizer, use the move operation. Read-only, except when importing an event.
/See:/ 'newEvent_Organizer' smart constructor.
| The organizer\'s name, if available.
| The organizer\'s Profile ID, if available.
| Whether the organizer corresponds to the calendar on which this copy of the event appears. Read-only. The default is False.
| Creates a value of 'Event_Organizer' with the minimum fields required to make a request.
| Information about the event\'s reminders for the authenticated user.
/See:/ 'newEvent_Reminders' smart constructor.
| Whether the default reminders of the calendar apply to the event.
| Creates a value of 'Event_Reminders' with the minimum fields required to make a request.
| Source from which the event was created. For example, a web page, an email message or any document identifiable by an URL with HTTP or HTTPS scheme. Can only be seen or modified by the creator of the event.
/See:/ 'newEvent_Source' smart constructor.
| Title of the source; for example a title of a web page or an email subject.
| URL of the source pointing to a resource. The URL scheme must be HTTP or HTTPS.
| Creates a value of 'Event_Source' with the minimum fields required to make a request.
/See:/ 'newEventAttachment' smart constructor.
| URL link to the attachment\'s icon. Read-only.
| Internet media type (MIME type) of the attachment.
| Attachment title.
| Creates a value of 'EventAttachment' with the minimum fields required to make a request.
/See:/ 'newEventAttendee' smart constructor.
| Number of additional guests. Optional. The default is 0.
| The attendee\'s response comment. Optional.
| The attendee\'s name, if available. Optional.
| The attendee\'s Profile ID, if available.
| Whether this is an optional attendee. Optional. The default is False.
| Whether the attendee is the organizer of the event. Read-only. The default is False.
| The attendee\'s response status. Possible values are:
- \"needsAction\" - The attendee has not responded to the invitation. - \"declined\" - The attendee has declined the invitation. - \"tentative\" - The attendee has tentatively accepted the invitation. - \"accepted\" - The attendee has accepted the invitation.
| Whether this entry represents the calendar on which this copy of the event appears. Read-only. The default is False.
/See:/ 'newEventDateTime' smart constructor.
| The time zone in which the time is specified. (Formatted as an IANA Time Zone Database name, e.g. \"Europe\/Zurich\".) For recurring events this field is required and specifies the time zone in which the recurrence is expanded. For single events this field is optional and indicates a custom time zone for the event start\/end.
| Creates a value of 'EventDateTime' with the minimum fields required to make a request.
/See:/ 'newEventReminder' smart constructor.
| The method used by this reminder. Possible values are:
- \"email\" - Reminders are sent via email. - \"popup\" - Reminders are sent via a UI popup.
Required when adding a reminder.
| Creates a value of 'EventReminder' with the minimum fields required to make a request.
/See:/ 'newEvents' smart constructor.
| The user\'s access role for this calendar. Read-only. Possible values are:
| The default reminders on the calendar for the authenticated user. These reminders apply to all events on this calendar that do not explicitly override them (i.e. do not have reminders.useDefault set to True).
| Description of the calendar. Read-only.
| ETag of the collection.
| List of events on the calendar.
| Title of the calendar. Read-only.
| The time zone of the calendar. Read-only.
| Last modification time of the calendar (as a RFC3339 timestamp). Read-only.
| Creates a value of 'Events' with the minimum fields required to make a request.
/See:/ 'newFreeBusyCalendar' smart constructor.
| List of time ranges during which this calendar should be regarded as busy.
| Optional error(s) (if computation for the calendar failed).
| Creates a value of 'FreeBusyCalendar' with the minimum fields required to make a request.
/See:/ 'newFreeBusyGroup' smart constructor.
| List of calendars\' identifiers within a group.
| Optional error(s) (if computation for the group failed).
| Creates a value of 'FreeBusyGroup' with the minimum fields required to make a request.
/See:/ 'newFreeBusyRequest' smart constructor.
| List of calendars and\/or groups to query.
| The end of the interval for the query formatted as per RFC3339.
| The start of the interval for the query formatted as per RFC3339.
| Time zone used in the response. Optional. The default is UTC.
| Creates a value of 'FreeBusyRequest' with the minimum fields required to make a request.
/See:/ 'newFreeBusyRequestItem' smart constructor.
| The identifier of a calendar or a group.
/See:/ 'newFreeBusyResponse' smart constructor.
| List of free\/busy information for calendars.
| Expansion of groups.
| Type of the resource (\"calendar#freeBusy\").
| The end of the interval.
| The start of the interval.
| Creates a value of 'FreeBusyResponse' with the minimum fields required to make a request.
| List of free\/busy information for calendars.
/See:/ 'newFreeBusyResponse_Calendars' smart constructor.
| Free\/busy expansions for a single calendar.
| Creates a value of 'FreeBusyResponse_Calendars' with the minimum fields required to make a request.
| Free\/busy expansions for a single calendar. See 'additional'.
| Expansion of groups.
/See:/ 'newFreeBusyResponse_Groups' smart constructor.
| List of calendars that are members of this group.
| Creates a value of 'FreeBusyResponse_Groups' with the minimum fields required to make a request.
| List of calendars that are members of this group. See 'additional'.
/See:/ 'newSetting' smart constructor.
| ETag of the resource.
| The id of the user setting.
| Type of the resource (\"calendar#setting\").
| Creates a value of 'Setting' with the minimum fields required to make a request.
| Etag of the collection.
| List of user settings.
| Type of the collection (\"calendar#settings\").
| Creates a value of 'Settings' with the minimum fields required to make a request.
/See:/ 'newTimePeriod' smart constructor.
| The (exclusive) end of the time period.
| The (inclusive) start of the time period.
| Creates a value of 'TimePeriod' with the minimum fields required to make a request. | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
# LANGUAGE PatternSynonyms #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - duplicate - exports #
# OPTIONS_GHC -fno - warn - name - shadowing #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
Module : . AppsCalendar . Internal . Product
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
Portability : non - portable ( GHC extensions )
module Gogol.AppsCalendar.Internal.Product
*
Acl (..),
newAcl,
AclRule (..),
newAclRule,
AclRule_Scope (..),
newAclRule_Scope,
Calendar (..),
newCalendar,
* CalendarList
CalendarList (..),
newCalendarList,
CalendarListEntry (..),
newCalendarListEntry,
CalendarListEntry_NotificationSettings (..),
newCalendarListEntry_NotificationSettings,
* CalendarNotification
CalendarNotification (..),
newCalendarNotification,
Channel (..),
newChannel,
Channel_Params (..),
newChannel_Params,
ColorDefinition (..),
newColorDefinition,
Colors (..),
newColors,
* Colors_Calendar
Colors_Calendar (..),
newColors_Calendar,
Colors_Event (..),
newColors_Event,
* ConferenceData
ConferenceData (..),
newConferenceData,
ConferenceParameters (..),
newConferenceParameters,
ConferenceParametersAddOnParameters (..),
newConferenceParametersAddOnParameters,
ConferenceParametersAddOnParameters_Parameters (..),
newConferenceParametersAddOnParameters_Parameters,
ConferenceProperties (..),
newConferenceProperties,
* ConferenceRequestStatus
ConferenceRequestStatus (..),
newConferenceRequestStatus,
ConferenceSolution (..),
newConferenceSolution,
ConferenceSolutionKey (..),
newConferenceSolutionKey,
* CreateConferenceRequest
CreateConferenceRequest (..),
newCreateConferenceRequest,
EntryPoint (..),
newEntryPoint,
Error' (..),
newError,
Event (..),
newEvent,
Event_Creator (..),
newEvent_Creator,
* Event_ExtendedProperties
Event_ExtendedProperties (..),
newEvent_ExtendedProperties,
Event_ExtendedProperties_Private (..),
newEvent_ExtendedProperties_Private,
Event_ExtendedProperties_Shared (..),
newEvent_ExtendedProperties_Shared,
Event_Gadget (..),
newEvent_Gadget,
Event_Gadget_Preferences (..),
newEvent_Gadget_Preferences,
Event_Organizer (..),
newEvent_Organizer,
Event_Reminders (..),
newEvent_Reminders,
Event_Source (..),
newEvent_Source,
EventAttachment (..),
newEventAttachment,
* EventAttendee
EventAttendee (..),
newEventAttendee,
EventDateTime (..),
newEventDateTime,
EventReminder (..),
newEventReminder,
Events (..),
newEvents,
FreeBusyCalendar (..),
newFreeBusyCalendar,
FreeBusyGroup (..),
newFreeBusyGroup,
FreeBusyRequest (..),
newFreeBusyRequest,
*
FreeBusyRequestItem (..),
newFreeBusyRequestItem,
*
FreeBusyResponse (..),
newFreeBusyResponse,
FreeBusyResponse_Calendars (..),
newFreeBusyResponse_Calendars,
FreeBusyResponse_Groups (..),
newFreeBusyResponse_Groups,
Setting (..),
newSetting,
Settings (..),
newSettings,
TimePeriod (..),
newTimePeriod,
)
where
import Gogol.AppsCalendar.Internal.Sum
import qualified Gogol.Prelude as Core
data Acl = Acl
etag :: (Core.Maybe Core.Text),
items :: (Core.Maybe [AclRule]),
kind :: Core.Text,
| Token used to access the next page of this result . Omitted if no further results are available , in which case nextSyncToken is provided .
nextPageToken :: (Core.Maybe Core.Text),
| Token used at a later point in time to retrieve only the entries that have changed since this result was returned . Omitted if further results are available , in which case is provided .
nextSyncToken :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' ' with the minimum fields required to make a request .
newAcl ::
Acl
newAcl =
Acl
{ etag = Core.Nothing,
items = Core.Nothing,
kind = "calendar#acl",
nextPageToken = Core.Nothing,
nextSyncToken = Core.Nothing
}
instance Core.FromJSON Acl where
parseJSON =
Core.withObject
"Acl"
( \o ->
Acl
Core.<$> (o Core..:? "etag")
Core.<*> (o Core..:? "items")
Core.<*> (o Core..:? "kind" Core..!= "calendar#acl")
Core.<*> (o Core..:? "nextPageToken")
Core.<*> (o Core..:? "nextSyncToken")
)
instance Core.ToJSON Acl where
toJSON Acl {..} =
Core.object
( Core.catMaybes
[ ("etag" Core..=) Core.<$> etag,
("items" Core..=) Core.<$> items,
Core.Just ("kind" Core..= kind),
("nextPageToken" Core..=) Core.<$> nextPageToken,
("nextSyncToken" Core..=) Core.<$> nextSyncToken
]
)
data AclRule = AclRule
etag :: (Core.Maybe Core.Text),
| Identifier of the Access Control List ( ACL ) rule . See calendars .
id :: (Core.Maybe Core.Text),
kind :: Core.Text,
- \"none\ " - Provides no access . - \"freeBusyReader\ " - Provides read access to free\/busy information . - \"reader\ " - Provides read access to the calendar . Private events will appear to users with reader access , but event details will be hidden . - \"writer\ " - Provides read and write access to the calendar . Private events will appear to users with writer access , and event details will be visible . - \"owner\ " - Provides ownership of the calendar . This role has all of the permissions of the writer role with the additional ability to see and manipulate ACLs .
role' :: (Core.Maybe Core.Text),
| The extent to which calendar access is granted by this ACL rule .
scope :: (Core.Maybe AclRule_Scope)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newAclRule ::
AclRule
newAclRule =
AclRule
{ etag = Core.Nothing,
id = Core.Nothing,
kind = "calendar#aclRule",
role' = Core.Nothing,
scope = Core.Nothing
}
instance Core.FromJSON AclRule where
parseJSON =
Core.withObject
"AclRule"
( \o ->
AclRule
Core.<$> (o Core..:? "etag")
Core.<*> (o Core..:? "id")
Core.<*> (o Core..:? "kind" Core..!= "calendar#aclRule")
Core.<*> (o Core..:? "role")
Core.<*> (o Core..:? "scope")
)
instance Core.ToJSON AclRule where
toJSON AclRule {..} =
Core.object
( Core.catMaybes
[ ("etag" Core..=) Core.<$> etag,
("id" Core..=) Core.<$> id,
Core.Just ("kind" Core..= kind),
("role" Core..=) Core.<$> role',
("scope" Core..=) Core.<$> scope
]
)
| The extent to which calendar access is granted by this ACL rule .
data AclRule_Scope = AclRule_Scope
type' :: (Core.Maybe Core.Text),
value :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' AclRule_Scope ' with the minimum fields required to make a request .
newAclRule_Scope ::
AclRule_Scope
newAclRule_Scope = AclRule_Scope {type' = Core.Nothing, value = Core.Nothing}
instance Core.FromJSON AclRule_Scope where
parseJSON =
Core.withObject
"AclRule_Scope"
( \o ->
AclRule_Scope
Core.<$> (o Core..:? "type") Core.<*> (o Core..:? "value")
)
instance Core.ToJSON AclRule_Scope where
toJSON AclRule_Scope {..} =
Core.object
( Core.catMaybes
[ ("type" Core..=) Core.<$> type',
("value" Core..=) Core.<$> value
]
)
/See:/ ' newCalendar ' smart constructor .
data Calendar = Calendar
conferenceProperties :: (Core.Maybe ConferenceProperties),
description :: (Core.Maybe Core.Text),
etag :: (Core.Maybe Core.Text),
| Identifier of the calendar . To retrieve IDs call the calendarList.list ( ) method .
id :: (Core.Maybe Core.Text),
kind :: Core.Text,
location :: (Core.Maybe Core.Text),
summary :: (Core.Maybe Core.Text),
timeZone :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newCalendar ::
Calendar
newCalendar =
Calendar
{ conferenceProperties = Core.Nothing,
description = Core.Nothing,
etag = Core.Nothing,
id = Core.Nothing,
kind = "calendar#calendar",
location = Core.Nothing,
summary = Core.Nothing,
timeZone = Core.Nothing
}
instance Core.FromJSON Calendar where
parseJSON =
Core.withObject
"Calendar"
( \o ->
Calendar
Core.<$> (o Core..:? "conferenceProperties")
Core.<*> (o Core..:? "description")
Core.<*> (o Core..:? "etag")
Core.<*> (o Core..:? "id")
Core.<*> (o Core..:? "kind" Core..!= "calendar#calendar")
Core.<*> (o Core..:? "location")
Core.<*> (o Core..:? "summary")
Core.<*> (o Core..:? "timeZone")
)
instance Core.ToJSON Calendar where
toJSON Calendar {..} =
Core.object
( Core.catMaybes
[ ("conferenceProperties" Core..=)
Core.<$> conferenceProperties,
("description" Core..=) Core.<$> description,
("etag" Core..=) Core.<$> etag,
("id" Core..=) Core.<$> id,
Core.Just ("kind" Core..= kind),
("location" Core..=) Core.<$> location,
("summary" Core..=) Core.<$> summary,
("timeZone" Core..=) Core.<$> timeZone
]
)
data CalendarList = CalendarList
etag :: (Core.Maybe Core.Text),
items :: (Core.Maybe [CalendarListEntry]),
kind :: Core.Text,
| Token used to access the next page of this result . Omitted if no further results are available , in which case nextSyncToken is provided .
nextPageToken :: (Core.Maybe Core.Text),
| Token used at a later point in time to retrieve only the entries that have changed since this result was returned . Omitted if further results are available , in which case is provided .
nextSyncToken :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newCalendarList ::
CalendarList
newCalendarList =
CalendarList
{ etag = Core.Nothing,
items = Core.Nothing,
kind = "calendar#calendarList",
nextPageToken = Core.Nothing,
nextSyncToken = Core.Nothing
}
instance Core.FromJSON CalendarList where
parseJSON =
Core.withObject
"CalendarList"
( \o ->
CalendarList
Core.<$> (o Core..:? "etag")
Core.<*> (o Core..:? "items")
Core.<*> (o Core..:? "kind" Core..!= "calendar#calendarList")
Core.<*> (o Core..:? "nextPageToken")
Core.<*> (o Core..:? "nextSyncToken")
)
instance Core.ToJSON CalendarList where
toJSON CalendarList {..} =
Core.object
( Core.catMaybes
[ ("etag" Core..=) Core.<$> etag,
("items" Core..=) Core.<$> items,
Core.Just ("kind" Core..= kind),
("nextPageToken" Core..=) Core.<$> nextPageToken,
("nextSyncToken" Core..=) Core.<$> nextSyncToken
]
)
data CalendarListEntry = CalendarListEntry
- \"freeBusyReader\ " - Provides read access to free\/busy information . - \"reader\ " - Provides read access to the calendar . Private events will appear to users with reader access , but event details will be hidden . - \"writer\ " - Provides read and write access to the calendar . Private events will appear to users with writer access , and event details will be visible . - \"owner\ " - Provides ownership of the calendar . This role has all of the permissions of the writer role with the additional ability to see and manipulate ACLs .
accessRole :: (Core.Maybe Core.Text),
backgroundColor :: (Core.Maybe Core.Text),
| The color of the calendar . This is an ID referring to an entry in the calendar section of the colors definition ( see the colors endpoint ) . This property is superseded by the backgroundColor and foregroundColor properties and can be ignored when using these properties . Optional .
colorId :: (Core.Maybe Core.Text),
conferenceProperties :: (Core.Maybe ConferenceProperties),
defaultReminders :: (Core.Maybe [EventReminder]),
deleted :: Core.Bool,
description :: (Core.Maybe Core.Text),
etag :: (Core.Maybe Core.Text),
foregroundColor :: (Core.Maybe Core.Text),
hidden :: Core.Bool,
id :: (Core.Maybe Core.Text),
kind :: Core.Text,
location :: (Core.Maybe Core.Text),
notificationSettings :: (Core.Maybe CalendarListEntry_NotificationSettings),
primary :: Core.Bool,
selected :: Core.Bool,
summary :: (Core.Maybe Core.Text),
summaryOverride :: (Core.Maybe Core.Text),
timeZone :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newCalendarListEntry ::
CalendarListEntry
newCalendarListEntry =
CalendarListEntry
{ accessRole = Core.Nothing,
backgroundColor = Core.Nothing,
colorId = Core.Nothing,
conferenceProperties = Core.Nothing,
defaultReminders = Core.Nothing,
deleted = Core.False,
description = Core.Nothing,
etag = Core.Nothing,
foregroundColor = Core.Nothing,
hidden = Core.False,
id = Core.Nothing,
kind = "calendar#calendarListEntry",
location = Core.Nothing,
notificationSettings = Core.Nothing,
primary = Core.False,
selected = Core.False,
summary = Core.Nothing,
summaryOverride = Core.Nothing,
timeZone = Core.Nothing
}
instance Core.FromJSON CalendarListEntry where
parseJSON =
Core.withObject
"CalendarListEntry"
( \o ->
CalendarListEntry
Core.<$> (o Core..:? "accessRole")
Core.<*> (o Core..:? "backgroundColor")
Core.<*> (o Core..:? "colorId")
Core.<*> (o Core..:? "conferenceProperties")
Core.<*> (o Core..:? "defaultReminders")
Core.<*> (o Core..:? "deleted" Core..!= Core.False)
Core.<*> (o Core..:? "description")
Core.<*> (o Core..:? "etag")
Core.<*> (o Core..:? "foregroundColor")
Core.<*> (o Core..:? "hidden" Core..!= Core.False)
Core.<*> (o Core..:? "id")
Core.<*> ( o Core..:? "kind"
Core..!= "calendar#calendarListEntry"
)
Core.<*> (o Core..:? "location")
Core.<*> (o Core..:? "notificationSettings")
Core.<*> (o Core..:? "primary" Core..!= Core.False)
Core.<*> (o Core..:? "selected" Core..!= Core.False)
Core.<*> (o Core..:? "summary")
Core.<*> (o Core..:? "summaryOverride")
Core.<*> (o Core..:? "timeZone")
)
instance Core.ToJSON CalendarListEntry where
toJSON CalendarListEntry {..} =
Core.object
( Core.catMaybes
[ ("accessRole" Core..=) Core.<$> accessRole,
("backgroundColor" Core..=) Core.<$> backgroundColor,
("colorId" Core..=) Core.<$> colorId,
("conferenceProperties" Core..=)
Core.<$> conferenceProperties,
("defaultReminders" Core..=)
Core.<$> defaultReminders,
Core.Just ("deleted" Core..= deleted),
("description" Core..=) Core.<$> description,
("etag" Core..=) Core.<$> etag,
("foregroundColor" Core..=) Core.<$> foregroundColor,
Core.Just ("hidden" Core..= hidden),
("id" Core..=) Core.<$> id,
Core.Just ("kind" Core..= kind),
("location" Core..=) Core.<$> location,
("notificationSettings" Core..=)
Core.<$> notificationSettings,
Core.Just ("primary" Core..= primary),
Core.Just ("selected" Core..= selected),
("summary" Core..=) Core.<$> summary,
("summaryOverride" Core..=) Core.<$> summaryOverride,
("timeZone" Core..=) Core.<$> timeZone
]
)
newtype CalendarListEntry_NotificationSettings = CalendarListEntry_NotificationSettings
notifications :: (Core.Maybe [CalendarNotification])
}
deriving (Core.Eq, Core.Show, Core.Generic)
newCalendarListEntry_NotificationSettings ::
CalendarListEntry_NotificationSettings
newCalendarListEntry_NotificationSettings =
CalendarListEntry_NotificationSettings {notifications = Core.Nothing}
instance
Core.FromJSON
CalendarListEntry_NotificationSettings
where
parseJSON =
Core.withObject
"CalendarListEntry_NotificationSettings"
( \o ->
CalendarListEntry_NotificationSettings
Core.<$> (o Core..:? "notifications")
)
instance
Core.ToJSON
CalendarListEntry_NotificationSettings
where
toJSON CalendarListEntry_NotificationSettings {..} =
Core.object
( Core.catMaybes
[("notifications" Core..=) Core.<$> notifications]
)
data CalendarNotification = CalendarNotification
method :: (Core.Maybe Core.Text),
- \"eventCreation\ " - Notification sent when a new event is put on the calendar . - \"eventChange\ " - Notification sent when an event is changed . - \"eventCancellation\ " - Notification sent when an event is cancelled . - \"eventResponse\ " - Notification sent when an attendee responds to the event invitation . - \"agenda\ " - An agenda with the events of the day ( sent out in the morning ) .
type' :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' CalendarNotification ' with the minimum fields required to make a request .
newCalendarNotification ::
CalendarNotification
newCalendarNotification =
CalendarNotification {method = Core.Nothing, type' = Core.Nothing}
instance Core.FromJSON CalendarNotification where
parseJSON =
Core.withObject
"CalendarNotification"
( \o ->
CalendarNotification
Core.<$> (o Core..:? "method") Core.<*> (o Core..:? "type")
)
instance Core.ToJSON CalendarNotification where
toJSON CalendarNotification {..} =
Core.object
( Core.catMaybes
[ ("method" Core..=) Core.<$> method,
("type" Core..=) Core.<$> type'
]
)
/See:/ ' newChannel ' smart constructor .
data Channel = Channel
address :: (Core.Maybe Core.Text),
expiration :: (Core.Maybe Core.Int64),
id :: (Core.Maybe Core.Text),
kind :: Core.Text,
params :: (Core.Maybe Channel_Params),
| A Boolean value to indicate whether payload is wanted . Optional .
payload :: (Core.Maybe Core.Bool),
resourceId :: (Core.Maybe Core.Text),
resourceUri :: (Core.Maybe Core.Text),
token :: (Core.Maybe Core.Text),
| The type of delivery mechanism used for this channel . Valid values are " ( or \"webhook\ " ) . Both values refer to a channel where Http requests are used to deliver messages .
type' :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newChannel ::
Channel
newChannel =
Channel
{ address = Core.Nothing,
expiration = Core.Nothing,
id = Core.Nothing,
kind = "api#channel",
params = Core.Nothing,
payload = Core.Nothing,
resourceId = Core.Nothing,
resourceUri = Core.Nothing,
token = Core.Nothing,
type' = Core.Nothing
}
instance Core.FromJSON Channel where
parseJSON =
Core.withObject
"Channel"
( \o ->
Channel
Core.<$> (o Core..:? "address")
Core.<*> ( o Core..:? "expiration"
Core.<&> Core.fmap Core.fromAsText
)
Core.<*> (o Core..:? "id")
Core.<*> (o Core..:? "kind" Core..!= "api#channel")
Core.<*> (o Core..:? "params")
Core.<*> (o Core..:? "payload")
Core.<*> (o Core..:? "resourceId")
Core.<*> (o Core..:? "resourceUri")
Core.<*> (o Core..:? "token")
Core.<*> (o Core..:? "type")
)
instance Core.ToJSON Channel where
toJSON Channel {..} =
Core.object
( Core.catMaybes
[ ("address" Core..=) Core.<$> address,
("expiration" Core..=) Core.. Core.AsText
Core.<$> expiration,
("id" Core..=) Core.<$> id,
Core.Just ("kind" Core..= kind),
("params" Core..=) Core.<$> params,
("payload" Core..=) Core.<$> payload,
("resourceId" Core..=) Core.<$> resourceId,
("resourceUri" Core..=) Core.<$> resourceUri,
("token" Core..=) Core.<$> token,
("type" Core..=) Core.<$> type'
]
)
newtype Channel_Params = Channel_Params
additional :: (Core.HashMap Core.Text Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newChannel_Params ::
Core.HashMap Core.Text Core.Text ->
Channel_Params
newChannel_Params additional = Channel_Params {additional = additional}
instance Core.FromJSON Channel_Params where
parseJSON =
Core.withObject
"Channel_Params"
( \o ->
Channel_Params Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Channel_Params where
toJSON Channel_Params {..} = Core.toJSON additional
data ColorDefinition = ColorDefinition
background :: (Core.Maybe Core.Text),
foreground :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newColorDefinition ::
ColorDefinition
newColorDefinition =
ColorDefinition {background = Core.Nothing, foreground = Core.Nothing}
instance Core.FromJSON ColorDefinition where
parseJSON =
Core.withObject
"ColorDefinition"
( \o ->
ColorDefinition
Core.<$> (o Core..:? "background")
Core.<*> (o Core..:? "foreground")
)
instance Core.ToJSON ColorDefinition where
toJSON ColorDefinition {..} =
Core.object
( Core.catMaybes
[ ("background" Core..=) Core.<$> background,
("foreground" Core..=) Core.<$> foreground
]
)
/See:/ ' newColors ' smart constructor .
data Colors = Colors
| A global palette of calendar colors , mapping from the color ID to its definition . A calendarListEntry resource refers to one of these color IDs in its colorId field . Read - only .
calendar :: (Core.Maybe Colors_Calendar),
| A global palette of event colors , mapping from the color ID to its definition . An event resource may refer to one of these color IDs in its colorId field . Read - only .
event :: (Core.Maybe Colors_Event),
kind :: Core.Text,
updated :: (Core.Maybe Core.DateTime)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newColors ::
Colors
newColors =
Colors
{ calendar = Core.Nothing,
event = Core.Nothing,
kind = "calendar#colors",
updated = Core.Nothing
}
instance Core.FromJSON Colors where
parseJSON =
Core.withObject
"Colors"
( \o ->
Colors
Core.<$> (o Core..:? "calendar")
Core.<*> (o Core..:? "event")
Core.<*> (o Core..:? "kind" Core..!= "calendar#colors")
Core.<*> (o Core..:? "updated")
)
instance Core.ToJSON Colors where
toJSON Colors {..} =
Core.object
( Core.catMaybes
[ ("calendar" Core..=) Core.<$> calendar,
("event" Core..=) Core.<$> event,
Core.Just ("kind" Core..= kind),
("updated" Core..=) Core.<$> updated
]
)
| A global palette of calendar colors , mapping from the color ID to its definition . A calendarListEntry resource refers to one of these color IDs in its colorId field . Read - only .
/See:/ ' ' smart constructor .
newtype Colors_Calendar = Colors_Calendar
additional :: (Core.HashMap Core.Text ColorDefinition)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' Colors_Calendar ' with the minimum fields required to make a request .
newColors_Calendar ::
Core.HashMap Core.Text ColorDefinition ->
Colors_Calendar
newColors_Calendar additional = Colors_Calendar {additional = additional}
instance Core.FromJSON Colors_Calendar where
parseJSON =
Core.withObject
"Colors_Calendar"
( \o ->
Colors_Calendar Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Colors_Calendar where
toJSON Colors_Calendar {..} = Core.toJSON additional
| A global palette of event colors , mapping from the color ID to its definition . An event resource may refer to one of these color IDs in its colorId field . Read - only .
newtype Colors_Event = Colors_Event
additional :: (Core.HashMap Core.Text ColorDefinition)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newColors_Event ::
Core.HashMap Core.Text ColorDefinition ->
Colors_Event
newColors_Event additional = Colors_Event {additional = additional}
instance Core.FromJSON Colors_Event where
parseJSON =
Core.withObject
"Colors_Event"
( \o ->
Colors_Event Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Colors_Event where
toJSON Colors_Event {..} = Core.toJSON additional
data ConferenceData = ConferenceData
- eventHangout : ID is not set . ( This conference type is deprecated . ) - eventNamedHangout : ID is the name of the Hangout . ( This conference type is deprecated . ) - hangoutsMeet : ID is the 10 - letter meeting code , for example . - addOn : ID is defined by the third - party provider . Optional .
conferenceId :: (Core.Maybe Core.Text),
| The conference solution , such as Google Meet . Unset for a conference with a failed create request . Either conferenceSolution and at least one entryPoint , or createRequest is required .
conferenceSolution :: (Core.Maybe ConferenceSolution),
| A request to generate a new conference and attach it to the event . The data is generated asynchronously . To see whether the data is present check the status field . Either conferenceSolution and at least one entryPoint , or createRequest is required .
createRequest :: (Core.Maybe CreateConferenceRequest),
| Information about individual conference entry points , such as URLs or phone numbers . All of them must belong to the same conference . Either conferenceSolution and at least one entryPoint , or createRequest is required .
entryPoints :: (Core.Maybe [EntryPoint]),
| Additional notes ( such as instructions from the domain administrator , legal notices ) to display to the user . Can contain HTML . The maximum length is 2048 characters . Optional .
notes :: (Core.Maybe Core.Text),
parameters :: (Core.Maybe ConferenceParameters),
| The signature of the conference data . Generated on server side . Unset for a conference with a failed create request . Optional for a conference with a pending create request .
signature :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' ConferenceData ' with the minimum fields required to make a request .
newConferenceData ::
ConferenceData
newConferenceData =
ConferenceData
{ conferenceId = Core.Nothing,
conferenceSolution = Core.Nothing,
createRequest = Core.Nothing,
entryPoints = Core.Nothing,
notes = Core.Nothing,
parameters = Core.Nothing,
signature = Core.Nothing
}
instance Core.FromJSON ConferenceData where
parseJSON =
Core.withObject
"ConferenceData"
( \o ->
ConferenceData
Core.<$> (o Core..:? "conferenceId")
Core.<*> (o Core..:? "conferenceSolution")
Core.<*> (o Core..:? "createRequest")
Core.<*> (o Core..:? "entryPoints")
Core.<*> (o Core..:? "notes")
Core.<*> (o Core..:? "parameters")
Core.<*> (o Core..:? "signature")
)
instance Core.ToJSON ConferenceData where
toJSON ConferenceData {..} =
Core.object
( Core.catMaybes
[ ("conferenceId" Core..=) Core.<$> conferenceId,
("conferenceSolution" Core..=)
Core.<$> conferenceSolution,
("createRequest" Core..=) Core.<$> createRequest,
("entryPoints" Core..=) Core.<$> entryPoints,
("notes" Core..=) Core.<$> notes,
("parameters" Core..=) Core.<$> parameters,
("signature" Core..=) Core.<$> signature
]
)
newtype ConferenceParameters = ConferenceParameters
addOnParameters :: (Core.Maybe ConferenceParametersAddOnParameters)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' ConferenceParameters ' with the minimum fields required to make a request .
newConferenceParameters ::
ConferenceParameters
newConferenceParameters = ConferenceParameters {addOnParameters = Core.Nothing}
instance Core.FromJSON ConferenceParameters where
parseJSON =
Core.withObject
"ConferenceParameters"
( \o ->
ConferenceParameters
Core.<$> (o Core..:? "addOnParameters")
)
instance Core.ToJSON ConferenceParameters where
toJSON ConferenceParameters {..} =
Core.object
( Core.catMaybes
[ ("addOnParameters" Core..=)
Core.<$> addOnParameters
]
)
/See:/ ' newConferenceParametersAddOnParameters ' smart constructor .
newtype ConferenceParametersAddOnParameters = ConferenceParametersAddOnParameters
parameters :: (Core.Maybe ConferenceParametersAddOnParameters_Parameters)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newConferenceParametersAddOnParameters ::
ConferenceParametersAddOnParameters
newConferenceParametersAddOnParameters =
ConferenceParametersAddOnParameters {parameters = Core.Nothing}
instance
Core.FromJSON
ConferenceParametersAddOnParameters
where
parseJSON =
Core.withObject
"ConferenceParametersAddOnParameters"
( \o ->
ConferenceParametersAddOnParameters
Core.<$> (o Core..:? "parameters")
)
instance
Core.ToJSON
ConferenceParametersAddOnParameters
where
toJSON ConferenceParametersAddOnParameters {..} =
Core.object
( Core.catMaybes
[("parameters" Core..=) Core.<$> parameters]
)
newtype ConferenceParametersAddOnParameters_Parameters = ConferenceParametersAddOnParameters_Parameters
additional :: (Core.HashMap Core.Text Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newConferenceParametersAddOnParameters_Parameters ::
Core.HashMap Core.Text Core.Text ->
ConferenceParametersAddOnParameters_Parameters
newConferenceParametersAddOnParameters_Parameters additional =
ConferenceParametersAddOnParameters_Parameters {additional = additional}
instance
Core.FromJSON
ConferenceParametersAddOnParameters_Parameters
where
parseJSON =
Core.withObject
"ConferenceParametersAddOnParameters_Parameters"
( \o ->
ConferenceParametersAddOnParameters_Parameters
Core.<$> (Core.parseJSONObject o)
)
instance
Core.ToJSON
ConferenceParametersAddOnParameters_Parameters
where
toJSON
ConferenceParametersAddOnParameters_Parameters {..} =
Core.toJSON additional
newtype ConferenceProperties = ConferenceProperties
allowedConferenceSolutionTypes :: (Core.Maybe [Core.Text])
}
deriving (Core.Eq, Core.Show, Core.Generic)
newConferenceProperties ::
ConferenceProperties
newConferenceProperties =
ConferenceProperties {allowedConferenceSolutionTypes = Core.Nothing}
instance Core.FromJSON ConferenceProperties where
parseJSON =
Core.withObject
"ConferenceProperties"
( \o ->
ConferenceProperties
Core.<$> (o Core..:? "allowedConferenceSolutionTypes")
)
instance Core.ToJSON ConferenceProperties where
toJSON ConferenceProperties {..} =
Core.object
( Core.catMaybes
[ ("allowedConferenceSolutionTypes" Core..=)
Core.<$> allowedConferenceSolutionTypes
]
)
/See:/ ' newConferenceRequestStatus ' smart constructor .
newtype ConferenceRequestStatus = ConferenceRequestStatus
statusCode :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' ConferenceRequestStatus ' with the minimum fields required to make a request .
newConferenceRequestStatus ::
ConferenceRequestStatus
newConferenceRequestStatus = ConferenceRequestStatus {statusCode = Core.Nothing}
instance Core.FromJSON ConferenceRequestStatus where
parseJSON =
Core.withObject
"ConferenceRequestStatus"
( \o ->
ConferenceRequestStatus
Core.<$> (o Core..:? "statusCode")
)
instance Core.ToJSON ConferenceRequestStatus where
toJSON ConferenceRequestStatus {..} =
Core.object
( Core.catMaybes
[("statusCode" Core..=) Core.<$> statusCode]
)
data ConferenceSolution = ConferenceSolution
iconUri :: (Core.Maybe Core.Text),
key :: (Core.Maybe ConferenceSolutionKey),
name :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' ConferenceSolution ' with the minimum fields required to make a request .
newConferenceSolution ::
ConferenceSolution
newConferenceSolution =
ConferenceSolution
{ iconUri = Core.Nothing,
key = Core.Nothing,
name = Core.Nothing
}
instance Core.FromJSON ConferenceSolution where
parseJSON =
Core.withObject
"ConferenceSolution"
( \o ->
ConferenceSolution
Core.<$> (o Core..:? "iconUri")
Core.<*> (o Core..:? "key")
Core.<*> (o Core..:? "name")
)
instance Core.ToJSON ConferenceSolution where
toJSON ConferenceSolution {..} =
Core.object
( Core.catMaybes
[ ("iconUri" Core..=) Core.<$> iconUri,
("key" Core..=) Core.<$> key,
("name" Core..=) Core.<$> name
]
)
newtype ConferenceSolutionKey = ConferenceSolutionKey
- \"eventHangout\ " for Hangouts for consumers ( deprecated ; existing events may show this conference solution type but new conferences can not be created ) - \"eventNamedHangout\ " for classic Hangouts for Google Workspace users ( deprecated ; existing events may show this conference solution type but new conferences can not be created ) - \"hangoutsMeet\ " for Google Meet ( http:\/\/meet.google.com ) - \"addOn\ " for 3P conference providers
type' :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newConferenceSolutionKey ::
ConferenceSolutionKey
newConferenceSolutionKey = ConferenceSolutionKey {type' = Core.Nothing}
instance Core.FromJSON ConferenceSolutionKey where
parseJSON =
Core.withObject
"ConferenceSolutionKey"
( \o ->
ConferenceSolutionKey Core.<$> (o Core..:? "type")
)
instance Core.ToJSON ConferenceSolutionKey where
toJSON ConferenceSolutionKey {..} =
Core.object
(Core.catMaybes [("type" Core..=) Core.<$> type'])
/See:/ ' newCreateConferenceRequest ' smart constructor .
data CreateConferenceRequest = CreateConferenceRequest
conferenceSolutionKey :: (Core.Maybe ConferenceSolutionKey),
requestId :: (Core.Maybe Core.Text),
status :: (Core.Maybe ConferenceRequestStatus)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' CreateConferenceRequest ' with the minimum fields required to make a request .
newCreateConferenceRequest ::
CreateConferenceRequest
newCreateConferenceRequest =
CreateConferenceRequest
{ conferenceSolutionKey = Core.Nothing,
requestId = Core.Nothing,
status = Core.Nothing
}
instance Core.FromJSON CreateConferenceRequest where
parseJSON =
Core.withObject
"CreateConferenceRequest"
( \o ->
CreateConferenceRequest
Core.<$> (o Core..:? "conferenceSolutionKey")
Core.<*> (o Core..:? "requestId")
Core.<*> (o Core..:? "status")
)
instance Core.ToJSON CreateConferenceRequest where
toJSON CreateConferenceRequest {..} =
Core.object
( Core.catMaybes
[ ("conferenceSolutionKey" Core..=)
Core.<$> conferenceSolutionKey,
("requestId" Core..=) Core.<$> requestId,
("status" Core..=) Core.<$> status
]
)
/See:/ ' newEntryPoint ' smart constructor .
data EntryPoint = EntryPoint
| The access code to access the conference . The maximum length is 128 characters . When creating new conference data , populate only the subset of { meetingCode , accessCode , passcode , password , pin } fields that match the terminology that the conference provider uses . Only the populated fields should be displayed . Optional .
accessCode :: (Core.Maybe Core.Text),
| Features of the entry point , such as being toll or toll - free . One entry point can have multiple features . However , toll and toll - free can not be both set on the same entry point .
entryPointFeatures :: (Core.Maybe [Core.Text]),
- \"video\ " - joining a conference over HTTP . A conference can have zero or one video entry point . - \"phone\ " - joining a conference by dialing a phone number . A conference can have zero or more phone entry points . - \"sip\ " - joining a conference over SIP . A conference can have zero or one sip entry point . - \"more\ " - further conference joining instructions , for example additional phone numbers . A conference can have zero or one more entry point . A conference with only a more entry point is not a valid conference .
entryPointType :: (Core.Maybe Core.Text),
| The label for the URI . Visible to end users . Not localized . The maximum length is 512 characters . Examples :
- for video : meet.google.com\/aaa - bbbb - ccc - for phone : +1 123 268 2601 - for sip : 12345678\@altostrat.com - for more : should not be filled
label :: (Core.Maybe Core.Text),
| The meeting code to access the conference . The maximum length is 128 characters . When creating new conference data , populate only the subset of { meetingCode , accessCode , passcode , password , pin } fields that match the terminology that the conference provider uses . Only the populated fields should be displayed . Optional .
meetingCode :: (Core.Maybe Core.Text),
| The passcode to access the conference . The maximum length is 128 characters . When creating new conference data , populate only the subset of { meetingCode , accessCode , passcode , password , pin } fields that match the terminology that the conference provider uses . Only the populated fields should be displayed .
passcode :: (Core.Maybe Core.Text),
| The password to access the conference . The maximum length is 128 characters . When creating new conference data , populate only the subset of { meetingCode , accessCode , passcode , password , pin } fields that match the terminology that the conference provider uses . Only the populated fields should be displayed . Optional .
password :: (Core.Maybe Core.Text),
| The PIN to access the conference . The maximum length is 128 characters . When creating new conference data , populate only the subset of { meetingCode , accessCode , passcode , password , pin } fields that match the terminology that the conference provider uses . Only the populated fields should be displayed . Optional .
pin :: (Core.Maybe Core.Text),
| The CLDR\/ISO 3166 region code for the country associated with this phone access . Example : \"SE\ " for Sweden . Calendar backend will populate this field only for EntryPointType . PHONE .
regionCode :: (Core.Maybe Core.Text),
| The URI of the entry point . The maximum length is 1300 characters . Format :
- for video , http : or https : schema is required . - for phone , tel : schema is required . The URI should include the entire dial sequence ( e.g. , tel:+12345678900,,,123456789;1234 ) . - for sip , sip : schema is required , e.g. , sip:12345678\@myprovider.com . - for more , http : or https : schema is required .
uri :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' EntryPoint ' with the minimum fields required to make a request .
newEntryPoint ::
EntryPoint
newEntryPoint =
EntryPoint
{ accessCode = Core.Nothing,
entryPointFeatures = Core.Nothing,
entryPointType = Core.Nothing,
label = Core.Nothing,
meetingCode = Core.Nothing,
passcode = Core.Nothing,
password = Core.Nothing,
pin = Core.Nothing,
regionCode = Core.Nothing,
uri = Core.Nothing
}
instance Core.FromJSON EntryPoint where
parseJSON =
Core.withObject
"EntryPoint"
( \o ->
EntryPoint
Core.<$> (o Core..:? "accessCode")
Core.<*> (o Core..:? "entryPointFeatures")
Core.<*> (o Core..:? "entryPointType")
Core.<*> (o Core..:? "label")
Core.<*> (o Core..:? "meetingCode")
Core.<*> (o Core..:? "passcode")
Core.<*> (o Core..:? "password")
Core.<*> (o Core..:? "pin")
Core.<*> (o Core..:? "regionCode")
Core.<*> (o Core..:? "uri")
)
instance Core.ToJSON EntryPoint where
toJSON EntryPoint {..} =
Core.object
( Core.catMaybes
[ ("accessCode" Core..=) Core.<$> accessCode,
("entryPointFeatures" Core..=)
Core.<$> entryPointFeatures,
("entryPointType" Core..=) Core.<$> entryPointType,
("label" Core..=) Core.<$> label,
("meetingCode" Core..=) Core.<$> meetingCode,
("passcode" Core..=) Core.<$> passcode,
("password" Core..=) Core.<$> password,
("pin" Core..=) Core.<$> pin,
("regionCode" Core..=) Core.<$> regionCode,
("uri" Core..=) Core.<$> uri
]
)
data Error' = Error'
domain :: (Core.Maybe Core.Text),
- \"groupTooBig\ " - The group of users requested is too large for a single query . - \"tooManyCalendarsRequested\ " - The number of calendars requested is too large for a single query . - \"notFound\ " - The requested resource was not found . - \"internalError\ " - The API service has encountered an internal error . Additional error types may be added in the future , so clients should gracefully handle additional error statuses not included in this list .
reason :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newError ::
Error'
newError = Error' {domain = Core.Nothing, reason = Core.Nothing}
instance Core.FromJSON Error' where
parseJSON =
Core.withObject
"Error'"
( \o ->
Error'
Core.<$> (o Core..:? "domain") Core.<*> (o Core..:? "reason")
)
instance Core.ToJSON Error' where
toJSON Error' {..} =
Core.object
( Core.catMaybes
[ ("domain" Core..=) Core.<$> domain,
("reason" Core..=) Core.<$> reason
]
)
data Event = Event
anyoneCanAddSelf :: Core.Bool,
| File attachments for the event . Currently only Google Drive attachments are supported . In order to modify attachments the supportsAttachments request parameter should be set to true . There can be at most 25 attachments per event ,
attachments :: (Core.Maybe [EventAttachment]),
attendees :: (Core.Maybe [EventAttendee]),
| Whether attendees may have been omitted from the event\ 's representation . When retrieving an event , this may be due to a restriction specified by the maxAttendee query parameter . When updating an event , this can be used to only update the participant\ 's response . Optional . The default is False .
attendeesOmitted :: Core.Bool,
colorId :: (Core.Maybe Core.Text),
| The conference - related information , such as details of a Google Meet conference . To create new conference details use the createRequest field . To persist your changes , remember to set the conferenceDataVersion request parameter to 1 for all event modification requests .
conferenceData :: (Core.Maybe ConferenceData),
created :: (Core.Maybe Core.DateTime),
creator :: (Core.Maybe Event_Creator),
description :: (Core.Maybe Core.Text),
| The ( exclusive ) end time of the event . For a recurring event , this is the end time of the first instance .
end :: (Core.Maybe EventDateTime),
endTimeUnspecified :: Core.Bool,
etag :: (Core.Maybe Core.Text),
eventType :: Core.Text,
extendedProperties :: (Core.Maybe Event_ExtendedProperties),
gadget :: (Core.Maybe Event_Gadget),
guestsCanInviteOthers :: Core.Bool,
guestsCanModify :: Core.Bool,
guestsCanSeeOtherGuests :: Core.Bool,
hangoutLink :: (Core.Maybe Core.Text),
htmlLink :: (Core.Maybe Core.Text),
| Event unique identifier as defined in RFC5545 . It is used to uniquely identify events accross calendaring systems and must be supplied when importing events via the import method . Note that the icalUID and the i d are not identical and only one of them should be supplied at event creation time . One difference in their semantics is that in recurring events , all occurrences of one event have different ids while they all share the same icalUIDs .
iCalUID :: (Core.Maybe Core.Text),
- characters allowed in the ID are those used in base32hex encoding , i.e. lowercase letters a - v and digits 0 - 9 , see section 3.1.2 in RFC2938 - the length of the ID must be between 5 and 1024 characters - the ID must be unique per calendar Due to the globally distributed nature of the system , we can not guarantee that ID collisions will be detected at event creation time . To minimize the risk of collisions we recommend using an established UUID algorithm such as one described in RFC4122 . If you do not specify an ID , it will be automatically generated by the server . Note that the icalUID and the i d are not identical and only one of them should be supplied at event creation time . One difference in their semantics is that in recurring events , all occurrences of one event have different ids while they all share the same icalUIDs .
id :: (Core.Maybe Core.Text),
kind :: Core.Text,
location :: (Core.Maybe Core.Text),
| Whether this is a locked event copy where no changes can be made to the main event fields \"summary\ " , \"description\ " , \"location\ " , \"start\ " , \"end\ " or \"recurrence\ " . The default is False . Read - Only .
locked :: Core.Bool,
organizer :: (Core.Maybe Event_Organizer),
originalStartTime :: (Core.Maybe EventDateTime),
privateCopy :: Core.Bool,
| List of RRULE , EXRULE , RDATE and EXDATE lines for a recurring event , as specified in RFC5545 . Note that DTSTART and DTEND lines are not allowed in this field ; event start and end times are specified in the start and end fields . This field is omitted for single events or instances of recurring events .
recurrence :: (Core.Maybe [Core.Text]),
recurringEventId :: (Core.Maybe Core.Text),
reminders :: (Core.Maybe Event_Reminders),
sequence :: (Core.Maybe Core.Int32),
source :: (Core.Maybe Event_Source),
| The ( inclusive ) start time of the event . For a recurring event , this is the start time of the first instance .
start :: (Core.Maybe EventDateTime),
- \"confirmed\ " - The event is confirmed . This is the default status . - \"tentative\ " - The event is tentatively confirmed . - \"cancelled\ " - The event is cancelled ( deleted ) . The list method returns cancelled events only on incremental sync ( when syncToken or updatedMin are specified ) or if the showDeleted flag is set to true . The get method always returns them . A cancelled status represents two different states depending on the event type :
status :: (Core.Maybe Core.Text),
summary :: (Core.Maybe Core.Text),
transparency :: Core.Text,
updated :: (Core.Maybe Core.DateTime),
visibility :: Core.Text
}
deriving (Core.Eq, Core.Show, Core.Generic)
newEvent ::
Event
newEvent =
Event
{ anyoneCanAddSelf = Core.False,
attachments = Core.Nothing,
attendees = Core.Nothing,
attendeesOmitted = Core.False,
colorId = Core.Nothing,
conferenceData = Core.Nothing,
created = Core.Nothing,
creator = Core.Nothing,
description = Core.Nothing,
end = Core.Nothing,
endTimeUnspecified = Core.False,
etag = Core.Nothing,
eventType = "default",
extendedProperties = Core.Nothing,
gadget = Core.Nothing,
guestsCanInviteOthers = Core.True,
guestsCanModify = Core.False,
guestsCanSeeOtherGuests = Core.True,
hangoutLink = Core.Nothing,
htmlLink = Core.Nothing,
iCalUID = Core.Nothing,
id = Core.Nothing,
kind = "calendar#event",
location = Core.Nothing,
locked = Core.False,
organizer = Core.Nothing,
originalStartTime = Core.Nothing,
privateCopy = Core.False,
recurrence = Core.Nothing,
recurringEventId = Core.Nothing,
reminders = Core.Nothing,
sequence = Core.Nothing,
source = Core.Nothing,
start = Core.Nothing,
status = Core.Nothing,
summary = Core.Nothing,
transparency = "opaque",
updated = Core.Nothing,
visibility = "default"
}
instance Core.FromJSON Event where
parseJSON =
Core.withObject
"Event"
( \o ->
Event
Core.<$> (o Core..:? "anyoneCanAddSelf" Core..!= Core.False)
Core.<*> (o Core..:? "attachments")
Core.<*> (o Core..:? "attendees")
Core.<*> (o Core..:? "attendeesOmitted" Core..!= Core.False)
Core.<*> (o Core..:? "colorId")
Core.<*> (o Core..:? "conferenceData")
Core.<*> (o Core..:? "created")
Core.<*> (o Core..:? "creator")
Core.<*> (o Core..:? "description")
Core.<*> (o Core..:? "end")
Core.<*> (o Core..:? "endTimeUnspecified" Core..!= Core.False)
Core.<*> (o Core..:? "etag")
Core.<*> (o Core..:? "eventType" Core..!= "default")
Core.<*> (o Core..:? "extendedProperties")
Core.<*> (o Core..:? "gadget")
Core.<*> ( o Core..:? "guestsCanInviteOthers"
Core..!= Core.True
)
Core.<*> (o Core..:? "guestsCanModify" Core..!= Core.False)
Core.<*> ( o Core..:? "guestsCanSeeOtherGuests"
Core..!= Core.True
)
Core.<*> (o Core..:? "hangoutLink")
Core.<*> (o Core..:? "htmlLink")
Core.<*> (o Core..:? "iCalUID")
Core.<*> (o Core..:? "id")
Core.<*> (o Core..:? "kind" Core..!= "calendar#event")
Core.<*> (o Core..:? "location")
Core.<*> (o Core..:? "locked" Core..!= Core.False)
Core.<*> (o Core..:? "organizer")
Core.<*> (o Core..:? "originalStartTime")
Core.<*> (o Core..:? "privateCopy" Core..!= Core.False)
Core.<*> (o Core..:? "recurrence")
Core.<*> (o Core..:? "recurringEventId")
Core.<*> (o Core..:? "reminders")
Core.<*> (o Core..:? "sequence")
Core.<*> (o Core..:? "source")
Core.<*> (o Core..:? "start")
Core.<*> (o Core..:? "status")
Core.<*> (o Core..:? "summary")
Core.<*> (o Core..:? "transparency" Core..!= "opaque")
Core.<*> (o Core..:? "updated")
Core.<*> (o Core..:? "visibility" Core..!= "default")
)
instance Core.ToJSON Event where
toJSON Event {..} =
Core.object
( Core.catMaybes
[ Core.Just
("anyoneCanAddSelf" Core..= anyoneCanAddSelf),
("attachments" Core..=) Core.<$> attachments,
("attendees" Core..=) Core.<$> attendees,
Core.Just
("attendeesOmitted" Core..= attendeesOmitted),
("colorId" Core..=) Core.<$> colorId,
("conferenceData" Core..=) Core.<$> conferenceData,
("created" Core..=) Core.<$> created,
("creator" Core..=) Core.<$> creator,
("description" Core..=) Core.<$> description,
("end" Core..=) Core.<$> end,
Core.Just
("endTimeUnspecified" Core..= endTimeUnspecified),
("etag" Core..=) Core.<$> etag,
Core.Just ("eventType" Core..= eventType),
("extendedProperties" Core..=)
Core.<$> extendedProperties,
("gadget" Core..=) Core.<$> gadget,
Core.Just
( "guestsCanInviteOthers"
Core..= guestsCanInviteOthers
),
Core.Just
("guestsCanModify" Core..= guestsCanModify),
Core.Just
( "guestsCanSeeOtherGuests"
Core..= guestsCanSeeOtherGuests
),
("hangoutLink" Core..=) Core.<$> hangoutLink,
("htmlLink" Core..=) Core.<$> htmlLink,
("iCalUID" Core..=) Core.<$> iCalUID,
("id" Core..=) Core.<$> id,
Core.Just ("kind" Core..= kind),
("location" Core..=) Core.<$> location,
Core.Just ("locked" Core..= locked),
("organizer" Core..=) Core.<$> organizer,
("originalStartTime" Core..=)
Core.<$> originalStartTime,
Core.Just ("privateCopy" Core..= privateCopy),
("recurrence" Core..=) Core.<$> recurrence,
("recurringEventId" Core..=)
Core.<$> recurringEventId,
("reminders" Core..=) Core.<$> reminders,
("sequence" Core..=) Core.<$> sequence,
("source" Core..=) Core.<$> source,
("start" Core..=) Core.<$> start,
("status" Core..=) Core.<$> status,
("summary" Core..=) Core.<$> summary,
Core.Just ("transparency" Core..= transparency),
("updated" Core..=) Core.<$> updated,
Core.Just ("visibility" Core..= visibility)
]
)
data Event_Creator = Event_Creator
displayName :: (Core.Maybe Core.Text),
email :: (Core.Maybe Core.Text),
id :: (Core.Maybe Core.Text),
self :: Core.Bool
}
deriving (Core.Eq, Core.Show, Core.Generic)
newEvent_Creator ::
Event_Creator
newEvent_Creator =
Event_Creator
{ displayName = Core.Nothing,
email = Core.Nothing,
id = Core.Nothing,
self = Core.False
}
instance Core.FromJSON Event_Creator where
parseJSON =
Core.withObject
"Event_Creator"
( \o ->
Event_Creator
Core.<$> (o Core..:? "displayName")
Core.<*> (o Core..:? "email")
Core.<*> (o Core..:? "id")
Core.<*> (o Core..:? "self" Core..!= Core.False)
)
instance Core.ToJSON Event_Creator where
toJSON Event_Creator {..} =
Core.object
( Core.catMaybes
[ ("displayName" Core..=) Core.<$> displayName,
("email" Core..=) Core.<$> email,
("id" Core..=) Core.<$> id,
Core.Just ("self" Core..= self)
]
)
data Event_ExtendedProperties = Event_ExtendedProperties
private :: (Core.Maybe Event_ExtendedProperties_Private),
| Properties that are shared between copies of the event on other attendees\ ' calendars .
shared :: (Core.Maybe Event_ExtendedProperties_Shared)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' Event_ExtendedProperties ' with the minimum fields required to make a request .
newEvent_ExtendedProperties ::
Event_ExtendedProperties
newEvent_ExtendedProperties =
Event_ExtendedProperties {private = Core.Nothing, shared = Core.Nothing}
instance Core.FromJSON Event_ExtendedProperties where
parseJSON =
Core.withObject
"Event_ExtendedProperties"
( \o ->
Event_ExtendedProperties
Core.<$> (o Core..:? "private")
Core.<*> (o Core..:? "shared")
)
instance Core.ToJSON Event_ExtendedProperties where
toJSON Event_ExtendedProperties {..} =
Core.object
( Core.catMaybes
[ ("private" Core..=) Core.<$> private,
("shared" Core..=) Core.<$> shared
]
)
newtype Event_ExtendedProperties_Private = Event_ExtendedProperties_Private
additional :: (Core.HashMap Core.Text Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newEvent_ExtendedProperties_Private ::
Core.HashMap Core.Text Core.Text ->
Event_ExtendedProperties_Private
newEvent_ExtendedProperties_Private additional =
Event_ExtendedProperties_Private {additional = additional}
instance
Core.FromJSON
Event_ExtendedProperties_Private
where
parseJSON =
Core.withObject
"Event_ExtendedProperties_Private"
( \o ->
Event_ExtendedProperties_Private
Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Event_ExtendedProperties_Private where
toJSON Event_ExtendedProperties_Private {..} =
Core.toJSON additional
| Properties that are shared between copies of the event on other attendees\ ' calendars .
newtype Event_ExtendedProperties_Shared = Event_ExtendedProperties_Shared
additional :: (Core.HashMap Core.Text Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newEvent_ExtendedProperties_Shared ::
Core.HashMap Core.Text Core.Text ->
Event_ExtendedProperties_Shared
newEvent_ExtendedProperties_Shared additional =
Event_ExtendedProperties_Shared {additional = additional}
instance
Core.FromJSON
Event_ExtendedProperties_Shared
where
parseJSON =
Core.withObject
"Event_ExtendedProperties_Shared"
( \o ->
Event_ExtendedProperties_Shared
Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Event_ExtendedProperties_Shared where
toJSON Event_ExtendedProperties_Shared {..} =
Core.toJSON additional
data Event_Gadget = Event_Gadget
display :: (Core.Maybe Core.Text),
height :: (Core.Maybe Core.Int32),
iconLink :: (Core.Maybe Core.Text),
link :: (Core.Maybe Core.Text),
preferences :: (Core.Maybe Event_Gadget_Preferences),
title :: (Core.Maybe Core.Text),
type' :: (Core.Maybe Core.Text),
width :: (Core.Maybe Core.Int32)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newEvent_Gadget ::
Event_Gadget
newEvent_Gadget =
Event_Gadget
{ display = Core.Nothing,
height = Core.Nothing,
iconLink = Core.Nothing,
link = Core.Nothing,
preferences = Core.Nothing,
title = Core.Nothing,
type' = Core.Nothing,
width = Core.Nothing
}
instance Core.FromJSON Event_Gadget where
parseJSON =
Core.withObject
"Event_Gadget"
( \o ->
Event_Gadget
Core.<$> (o Core..:? "display")
Core.<*> (o Core..:? "height")
Core.<*> (o Core..:? "iconLink")
Core.<*> (o Core..:? "link")
Core.<*> (o Core..:? "preferences")
Core.<*> (o Core..:? "title")
Core.<*> (o Core..:? "type")
Core.<*> (o Core..:? "width")
)
instance Core.ToJSON Event_Gadget where
toJSON Event_Gadget {..} =
Core.object
( Core.catMaybes
[ ("display" Core..=) Core.<$> display,
("height" Core..=) Core.<$> height,
("iconLink" Core..=) Core.<$> iconLink,
("link" Core..=) Core.<$> link,
("preferences" Core..=) Core.<$> preferences,
("title" Core..=) Core.<$> title,
("type" Core..=) Core.<$> type',
("width" Core..=) Core.<$> width
]
)
newtype Event_Gadget_Preferences = Event_Gadget_Preferences
additional :: (Core.HashMap Core.Text Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newEvent_Gadget_Preferences ::
Core.HashMap Core.Text Core.Text ->
Event_Gadget_Preferences
newEvent_Gadget_Preferences additional =
Event_Gadget_Preferences {additional = additional}
instance Core.FromJSON Event_Gadget_Preferences where
parseJSON =
Core.withObject
"Event_Gadget_Preferences"
( \o ->
Event_Gadget_Preferences
Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Event_Gadget_Preferences where
toJSON Event_Gadget_Preferences {..} =
Core.toJSON additional
data Event_Organizer = Event_Organizer
displayName :: (Core.Maybe Core.Text),
| The organizer\ 's email address , if available . It must be a valid email address as per RFC5322 .
email :: (Core.Maybe Core.Text),
id :: (Core.Maybe Core.Text),
self :: Core.Bool
}
deriving (Core.Eq, Core.Show, Core.Generic)
newEvent_Organizer ::
Event_Organizer
newEvent_Organizer =
Event_Organizer
{ displayName = Core.Nothing,
email = Core.Nothing,
id = Core.Nothing,
self = Core.False
}
instance Core.FromJSON Event_Organizer where
parseJSON =
Core.withObject
"Event_Organizer"
( \o ->
Event_Organizer
Core.<$> (o Core..:? "displayName")
Core.<*> (o Core..:? "email")
Core.<*> (o Core..:? "id")
Core.<*> (o Core..:? "self" Core..!= Core.False)
)
instance Core.ToJSON Event_Organizer where
toJSON Event_Organizer {..} =
Core.object
( Core.catMaybes
[ ("displayName" Core..=) Core.<$> displayName,
("email" Core..=) Core.<$> email,
("id" Core..=) Core.<$> id,
Core.Just ("self" Core..= self)
]
)
data Event_Reminders = Event_Reminders
| If the event doesn\'t use the default reminders , this lists the reminders specific to the event , or , if not set , indicates that no reminders are set for this event . The maximum number of override reminders is 5 .
overrides :: (Core.Maybe [EventReminder]),
useDefault :: (Core.Maybe Core.Bool)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newEvent_Reminders ::
Event_Reminders
newEvent_Reminders =
Event_Reminders {overrides = Core.Nothing, useDefault = Core.Nothing}
instance Core.FromJSON Event_Reminders where
parseJSON =
Core.withObject
"Event_Reminders"
( \o ->
Event_Reminders
Core.<$> (o Core..:? "overrides")
Core.<*> (o Core..:? "useDefault")
)
instance Core.ToJSON Event_Reminders where
toJSON Event_Reminders {..} =
Core.object
( Core.catMaybes
[ ("overrides" Core..=) Core.<$> overrides,
("useDefault" Core..=) Core.<$> useDefault
]
)
data Event_Source = Event_Source
title :: (Core.Maybe Core.Text),
url :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newEvent_Source ::
Event_Source
newEvent_Source = Event_Source {title = Core.Nothing, url = Core.Nothing}
instance Core.FromJSON Event_Source where
parseJSON =
Core.withObject
"Event_Source"
( \o ->
Event_Source
Core.<$> (o Core..:? "title") Core.<*> (o Core..:? "url")
)
instance Core.ToJSON Event_Source where
toJSON Event_Source {..} =
Core.object
( Core.catMaybes
[ ("title" Core..=) Core.<$> title,
("url" Core..=) Core.<$> url
]
)
data EventAttachment = EventAttachment
| ID of the attached file . Read - only . For Google Drive files , this is the ID of the corresponding Files resource entry in the Drive API .
fileId :: (Core.Maybe Core.Text),
| URL link to the attachment . For adding Google Drive file attachments use the same format as in alternateLink property of the Files resource in the Drive API . Required when adding an attachment .
fileUrl :: (Core.Maybe Core.Text),
iconLink :: (Core.Maybe Core.Text),
mimeType :: (Core.Maybe Core.Text),
title :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newEventAttachment ::
EventAttachment
newEventAttachment =
EventAttachment
{ fileId = Core.Nothing,
fileUrl = Core.Nothing,
iconLink = Core.Nothing,
mimeType = Core.Nothing,
title = Core.Nothing
}
instance Core.FromJSON EventAttachment where
parseJSON =
Core.withObject
"EventAttachment"
( \o ->
EventAttachment
Core.<$> (o Core..:? "fileId")
Core.<*> (o Core..:? "fileUrl")
Core.<*> (o Core..:? "iconLink")
Core.<*> (o Core..:? "mimeType")
Core.<*> (o Core..:? "title")
)
instance Core.ToJSON EventAttachment where
toJSON EventAttachment {..} =
Core.object
( Core.catMaybes
[ ("fileId" Core..=) Core.<$> fileId,
("fileUrl" Core..=) Core.<$> fileUrl,
("iconLink" Core..=) Core.<$> iconLink,
("mimeType" Core..=) Core.<$> mimeType,
("title" Core..=) Core.<$> title
]
)
data EventAttendee = EventAttendee
additionalGuests :: Core.Int32,
comment :: (Core.Maybe Core.Text),
displayName :: (Core.Maybe Core.Text),
| The attendee\ 's email address , if available . This field must be present when adding an attendee . It must be a valid email address as per RFC5322 . Required when adding an attendee .
email :: (Core.Maybe Core.Text),
id :: (Core.Maybe Core.Text),
optional :: Core.Bool,
organizer :: (Core.Maybe Core.Bool),
| Whether the attendee is a resource . Can only be set when the attendee is added to the event for the first time . Subsequent modifications are ignored . Optional . The default is False .
resource :: Core.Bool,
responseStatus :: (Core.Maybe Core.Text),
self :: Core.Bool
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' EventAttendee ' with the minimum fields required to make a request .
newEventAttendee ::
EventAttendee
newEventAttendee =
EventAttendee
{ additionalGuests = 0,
comment = Core.Nothing,
displayName = Core.Nothing,
email = Core.Nothing,
id = Core.Nothing,
optional = Core.False,
organizer = Core.Nothing,
resource = Core.False,
responseStatus = Core.Nothing,
self = Core.False
}
instance Core.FromJSON EventAttendee where
parseJSON =
Core.withObject
"EventAttendee"
( \o ->
EventAttendee
Core.<$> (o Core..:? "additionalGuests" Core..!= 0)
Core.<*> (o Core..:? "comment")
Core.<*> (o Core..:? "displayName")
Core.<*> (o Core..:? "email")
Core.<*> (o Core..:? "id")
Core.<*> (o Core..:? "optional" Core..!= Core.False)
Core.<*> (o Core..:? "organizer")
Core.<*> (o Core..:? "resource" Core..!= Core.False)
Core.<*> (o Core..:? "responseStatus")
Core.<*> (o Core..:? "self" Core..!= Core.False)
)
instance Core.ToJSON EventAttendee where
toJSON EventAttendee {..} =
Core.object
( Core.catMaybes
[ Core.Just
("additionalGuests" Core..= additionalGuests),
("comment" Core..=) Core.<$> comment,
("displayName" Core..=) Core.<$> displayName,
("email" Core..=) Core.<$> email,
("id" Core..=) Core.<$> id,
Core.Just ("optional" Core..= optional),
("organizer" Core..=) Core.<$> organizer,
Core.Just ("resource" Core..= resource),
("responseStatus" Core..=) Core.<$> responseStatus,
Core.Just ("self" Core..= self)
]
)
data EventDateTime = EventDateTime
| The date , in the format \"yyyy - mm - dd\ " , if this is an all - day event .
date :: (Core.Maybe Core.Date),
| The time , as a combined date - time value ( formatted according to ) . A time zone offset is required unless a time zone is explicitly specified in timeZone .
dateTime :: (Core.Maybe Core.DateTime),
timeZone :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newEventDateTime ::
EventDateTime
newEventDateTime =
EventDateTime
{ date = Core.Nothing,
dateTime = Core.Nothing,
timeZone = Core.Nothing
}
instance Core.FromJSON EventDateTime where
parseJSON =
Core.withObject
"EventDateTime"
( \o ->
EventDateTime
Core.<$> (o Core..:? "date")
Core.<*> (o Core..:? "dateTime")
Core.<*> (o Core..:? "timeZone")
)
instance Core.ToJSON EventDateTime where
toJSON EventDateTime {..} =
Core.object
( Core.catMaybes
[ ("date" Core..=) Core.<$> date,
("dateTime" Core..=) Core.<$> dateTime,
("timeZone" Core..=) Core.<$> timeZone
]
)
data EventReminder = EventReminder
method :: (Core.Maybe Core.Text),
| Number of minutes before the start of the event when the reminder should trigger . Valid values are between 0 and 40320 ( 4 weeks in minutes ) . Required when adding a reminder .
minutes :: (Core.Maybe Core.Int32)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newEventReminder ::
EventReminder
newEventReminder = EventReminder {method = Core.Nothing, minutes = Core.Nothing}
instance Core.FromJSON EventReminder where
parseJSON =
Core.withObject
"EventReminder"
( \o ->
EventReminder
Core.<$> (o Core..:? "method")
Core.<*> (o Core..:? "minutes")
)
instance Core.ToJSON EventReminder where
toJSON EventReminder {..} =
Core.object
( Core.catMaybes
[ ("method" Core..=) Core.<$> method,
("minutes" Core..=) Core.<$> minutes
]
)
data Events = Events
- \"none\ " - The user has no access . - \"freeBusyReader\ " - The user has read access to free\/busy information . - \"reader\ " - The user has read access to the calendar . Private events will appear to users with reader access , but event details will be hidden . - \"writer\ " - The user has read and write access to the calendar . Private events will appear to users with writer access , and event details will be visible . - \"owner\ " - The user has ownership of the calendar . This role has all of the permissions of the writer role with the additional ability to see and manipulate ACLs .
accessRole :: (Core.Maybe Core.Text),
defaultReminders :: (Core.Maybe [EventReminder]),
description :: (Core.Maybe Core.Text),
etag :: (Core.Maybe Core.Text),
items :: (Core.Maybe [Event]),
| Type of the collection ( \"calendar#events\ " ) .
kind :: Core.Text,
| Token used to access the next page of this result . Omitted if no further results are available , in which case nextSyncToken is provided .
nextPageToken :: (Core.Maybe Core.Text),
| Token used at a later point in time to retrieve only the entries that have changed since this result was returned . Omitted if further results are available , in which case is provided .
nextSyncToken :: (Core.Maybe Core.Text),
summary :: (Core.Maybe Core.Text),
timeZone :: (Core.Maybe Core.Text),
updated :: (Core.Maybe Core.DateTime)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newEvents ::
Events
newEvents =
Events
{ accessRole = Core.Nothing,
defaultReminders = Core.Nothing,
description = Core.Nothing,
etag = Core.Nothing,
items = Core.Nothing,
kind = "calendar#events",
nextPageToken = Core.Nothing,
nextSyncToken = Core.Nothing,
summary = Core.Nothing,
timeZone = Core.Nothing,
updated = Core.Nothing
}
instance Core.FromJSON Events where
parseJSON =
Core.withObject
"Events"
( \o ->
Events
Core.<$> (o Core..:? "accessRole")
Core.<*> (o Core..:? "defaultReminders")
Core.<*> (o Core..:? "description")
Core.<*> (o Core..:? "etag")
Core.<*> (o Core..:? "items")
Core.<*> (o Core..:? "kind" Core..!= "calendar#events")
Core.<*> (o Core..:? "nextPageToken")
Core.<*> (o Core..:? "nextSyncToken")
Core.<*> (o Core..:? "summary")
Core.<*> (o Core..:? "timeZone")
Core.<*> (o Core..:? "updated")
)
instance Core.ToJSON Events where
toJSON Events {..} =
Core.object
( Core.catMaybes
[ ("accessRole" Core..=) Core.<$> accessRole,
("defaultReminders" Core..=)
Core.<$> defaultReminders,
("description" Core..=) Core.<$> description,
("etag" Core..=) Core.<$> etag,
("items" Core..=) Core.<$> items,
Core.Just ("kind" Core..= kind),
("nextPageToken" Core..=) Core.<$> nextPageToken,
("nextSyncToken" Core..=) Core.<$> nextSyncToken,
("summary" Core..=) Core.<$> summary,
("timeZone" Core..=) Core.<$> timeZone,
("updated" Core..=) Core.<$> updated
]
)
data FreeBusyCalendar = FreeBusyCalendar
busy :: (Core.Maybe [TimePeriod]),
errors :: (Core.Maybe [Error'])
}
deriving (Core.Eq, Core.Show, Core.Generic)
newFreeBusyCalendar ::
FreeBusyCalendar
newFreeBusyCalendar =
FreeBusyCalendar {busy = Core.Nothing, errors = Core.Nothing}
instance Core.FromJSON FreeBusyCalendar where
parseJSON =
Core.withObject
"FreeBusyCalendar"
( \o ->
FreeBusyCalendar
Core.<$> (o Core..:? "busy") Core.<*> (o Core..:? "errors")
)
instance Core.ToJSON FreeBusyCalendar where
toJSON FreeBusyCalendar {..} =
Core.object
( Core.catMaybes
[ ("busy" Core..=) Core.<$> busy,
("errors" Core..=) Core.<$> errors
]
)
data FreeBusyGroup = FreeBusyGroup
calendars :: (Core.Maybe [Core.Text]),
errors :: (Core.Maybe [Error'])
}
deriving (Core.Eq, Core.Show, Core.Generic)
newFreeBusyGroup ::
FreeBusyGroup
newFreeBusyGroup =
FreeBusyGroup {calendars = Core.Nothing, errors = Core.Nothing}
instance Core.FromJSON FreeBusyGroup where
parseJSON =
Core.withObject
"FreeBusyGroup"
( \o ->
FreeBusyGroup
Core.<$> (o Core..:? "calendars")
Core.<*> (o Core..:? "errors")
)
instance Core.ToJSON FreeBusyGroup where
toJSON FreeBusyGroup {..} =
Core.object
( Core.catMaybes
[ ("calendars" Core..=) Core.<$> calendars,
("errors" Core..=) Core.<$> errors
]
)
data FreeBusyRequest = FreeBusyRequest
| Maximal number of calendars for which FreeBusy information is to be provided . Optional . Maximum value is 50 .
calendarExpansionMax :: (Core.Maybe Core.Int32),
| Maximal number of calendar identifiers to be provided for a single group . Optional . An error is returned for a group with more members than this value . Maximum value is 100 .
groupExpansionMax :: (Core.Maybe Core.Int32),
items :: (Core.Maybe [FreeBusyRequestItem]),
timeMax :: (Core.Maybe Core.DateTime),
timeMin :: (Core.Maybe Core.DateTime),
timeZone :: Core.Text
}
deriving (Core.Eq, Core.Show, Core.Generic)
newFreeBusyRequest ::
FreeBusyRequest
newFreeBusyRequest =
FreeBusyRequest
{ calendarExpansionMax = Core.Nothing,
groupExpansionMax = Core.Nothing,
items = Core.Nothing,
timeMax = Core.Nothing,
timeMin = Core.Nothing,
timeZone = "UTC"
}
instance Core.FromJSON FreeBusyRequest where
parseJSON =
Core.withObject
"FreeBusyRequest"
( \o ->
FreeBusyRequest
Core.<$> (o Core..:? "calendarExpansionMax")
Core.<*> (o Core..:? "groupExpansionMax")
Core.<*> (o Core..:? "items")
Core.<*> (o Core..:? "timeMax")
Core.<*> (o Core..:? "timeMin")
Core.<*> (o Core..:? "timeZone" Core..!= "UTC")
)
instance Core.ToJSON FreeBusyRequest where
toJSON FreeBusyRequest {..} =
Core.object
( Core.catMaybes
[ ("calendarExpansionMax" Core..=)
Core.<$> calendarExpansionMax,
("groupExpansionMax" Core..=)
Core.<$> groupExpansionMax,
("items" Core..=) Core.<$> items,
("timeMax" Core..=) Core.<$> timeMax,
("timeMin" Core..=) Core.<$> timeMin,
Core.Just ("timeZone" Core..= timeZone)
]
)
newtype FreeBusyRequestItem = FreeBusyRequestItem
id :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' ' with the minimum fields required to make a request .
newFreeBusyRequestItem ::
FreeBusyRequestItem
newFreeBusyRequestItem = FreeBusyRequestItem {id = Core.Nothing}
instance Core.FromJSON FreeBusyRequestItem where
parseJSON =
Core.withObject
"FreeBusyRequestItem"
( \o ->
FreeBusyRequestItem Core.<$> (o Core..:? "id")
)
instance Core.ToJSON FreeBusyRequestItem where
toJSON FreeBusyRequestItem {..} =
Core.object
(Core.catMaybes [("id" Core..=) Core.<$> id])
data FreeBusyResponse = FreeBusyResponse
calendars :: (Core.Maybe FreeBusyResponse_Calendars),
groups :: (Core.Maybe FreeBusyResponse_Groups),
kind :: Core.Text,
timeMax :: (Core.Maybe Core.DateTime),
timeMin :: (Core.Maybe Core.DateTime)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newFreeBusyResponse ::
FreeBusyResponse
newFreeBusyResponse =
FreeBusyResponse
{ calendars = Core.Nothing,
groups = Core.Nothing,
kind = "calendar#freeBusy",
timeMax = Core.Nothing,
timeMin = Core.Nothing
}
instance Core.FromJSON FreeBusyResponse where
parseJSON =
Core.withObject
"FreeBusyResponse"
( \o ->
FreeBusyResponse
Core.<$> (o Core..:? "calendars")
Core.<*> (o Core..:? "groups")
Core.<*> (o Core..:? "kind" Core..!= "calendar#freeBusy")
Core.<*> (o Core..:? "timeMax")
Core.<*> (o Core..:? "timeMin")
)
instance Core.ToJSON FreeBusyResponse where
toJSON FreeBusyResponse {..} =
Core.object
( Core.catMaybes
[ ("calendars" Core..=) Core.<$> calendars,
("groups" Core..=) Core.<$> groups,
Core.Just ("kind" Core..= kind),
("timeMax" Core..=) Core.<$> timeMax,
("timeMin" Core..=) Core.<$> timeMin
]
)
newtype FreeBusyResponse_Calendars = FreeBusyResponse_Calendars
additional :: (Core.HashMap Core.Text FreeBusyCalendar)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newFreeBusyResponse_Calendars ::
Core.HashMap Core.Text FreeBusyCalendar ->
FreeBusyResponse_Calendars
newFreeBusyResponse_Calendars additional =
FreeBusyResponse_Calendars {additional = additional}
instance Core.FromJSON FreeBusyResponse_Calendars where
parseJSON =
Core.withObject
"FreeBusyResponse_Calendars"
( \o ->
FreeBusyResponse_Calendars
Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON FreeBusyResponse_Calendars where
toJSON FreeBusyResponse_Calendars {..} =
Core.toJSON additional
newtype FreeBusyResponse_Groups = FreeBusyResponse_Groups
additional :: (Core.HashMap Core.Text FreeBusyGroup)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newFreeBusyResponse_Groups ::
Core.HashMap Core.Text FreeBusyGroup ->
FreeBusyResponse_Groups
newFreeBusyResponse_Groups additional =
FreeBusyResponse_Groups {additional = additional}
instance Core.FromJSON FreeBusyResponse_Groups where
parseJSON =
Core.withObject
"FreeBusyResponse_Groups"
( \o ->
FreeBusyResponse_Groups
Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON FreeBusyResponse_Groups where
toJSON FreeBusyResponse_Groups {..} =
Core.toJSON additional
data Setting = Setting
etag :: (Core.Maybe Core.Text),
id :: (Core.Maybe Core.Text),
kind :: Core.Text,
| Value of the user setting . The format of the value depends on the ID of the setting . It must always be a UTF-8 string of length up to 1024 characters .
value :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newSetting ::
Setting
newSetting =
Setting
{ etag = Core.Nothing,
id = Core.Nothing,
kind = "calendar#setting",
value = Core.Nothing
}
instance Core.FromJSON Setting where
parseJSON =
Core.withObject
"Setting"
( \o ->
Setting
Core.<$> (o Core..:? "etag")
Core.<*> (o Core..:? "id")
Core.<*> (o Core..:? "kind" Core..!= "calendar#setting")
Core.<*> (o Core..:? "value")
)
instance Core.ToJSON Setting where
toJSON Setting {..} =
Core.object
( Core.catMaybes
[ ("etag" Core..=) Core.<$> etag,
("id" Core..=) Core.<$> id,
Core.Just ("kind" Core..= kind),
("value" Core..=) Core.<$> value
]
)
/See:/ ' newSettings ' smart constructor .
data Settings = Settings
etag :: (Core.Maybe Core.Text),
items :: (Core.Maybe [Setting]),
kind :: Core.Text,
| Token used to access the next page of this result . Omitted if no further results are available , in which case nextSyncToken is provided .
nextPageToken :: (Core.Maybe Core.Text),
| Token used at a later point in time to retrieve only the entries that have changed since this result was returned . Omitted if further results are available , in which case is provided .
nextSyncToken :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newSettings ::
Settings
newSettings =
Settings
{ etag = Core.Nothing,
items = Core.Nothing,
kind = "calendar#settings",
nextPageToken = Core.Nothing,
nextSyncToken = Core.Nothing
}
instance Core.FromJSON Settings where
parseJSON =
Core.withObject
"Settings"
( \o ->
Settings
Core.<$> (o Core..:? "etag")
Core.<*> (o Core..:? "items")
Core.<*> (o Core..:? "kind" Core..!= "calendar#settings")
Core.<*> (o Core..:? "nextPageToken")
Core.<*> (o Core..:? "nextSyncToken")
)
instance Core.ToJSON Settings where
toJSON Settings {..} =
Core.object
( Core.catMaybes
[ ("etag" Core..=) Core.<$> etag,
("items" Core..=) Core.<$> items,
Core.Just ("kind" Core..= kind),
("nextPageToken" Core..=) Core.<$> nextPageToken,
("nextSyncToken" Core..=) Core.<$> nextSyncToken
]
)
data TimePeriod = TimePeriod
end :: (Core.Maybe Core.DateTime),
start :: (Core.Maybe Core.DateTime)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newTimePeriod ::
TimePeriod
newTimePeriod = TimePeriod {end = Core.Nothing, start = Core.Nothing}
instance Core.FromJSON TimePeriod where
parseJSON =
Core.withObject
"TimePeriod"
( \o ->
TimePeriod
Core.<$> (o Core..:? "end") Core.<*> (o Core..:? "start")
)
instance Core.ToJSON TimePeriod where
toJSON TimePeriod {..} =
Core.object
( Core.catMaybes
[ ("end" Core..=) Core.<$> end,
("start" Core..=) Core.<$> start
]
)
|
88ccbdd8cb7dbedc43364e7c1a387efadb455950adeea18c506fc60f0208c808 | cloojure/tupelo | uuid.clj | (ns tst.tupelo.uuid
(:use tupelo.core tupelo.test)
(:refer-clojure :exclude [rand])
(:require
[tupelo.uuid :as uuid]))
(verify
(is= "00000000-0000-0000-0000-000000000000"
(uuid/null-str)
(str (uuid/null)))
(is= "cafebabe-1953-0510-0970-0123456789ff"
(uuid/dummy-str)
(str (uuid/dummy)))
(is (uuid? (uuid/null)))
(is (uuid? (uuid/dummy)))
(is (uuid/uuid-str? (uuid/null-str)))
(is (uuid/uuid-str? (uuid/dummy-str)))
(isnt (uuid/uuid-str? "cafebabe-1953-0510-0970-0123456789fff"))
(isnt (uuid/uuid-str? "cafebabe-1953-0510-09700-123456789ff"))
(isnt (uuid/uuid-str? "cafebabe-1953-0510-066x-0123456789ff"))
(isnt (uuid/uuid-str? "cafebabe-1953-0510-0123456789ff"))
(isnt (uuid/uuid-str? "cafebabe-1953-0510|0970-0123456789ff"))
(isnt (uuid/uuid-str? 5))
(isnt (uuid/uuid-str? :nope))
(isnt (uuid/uuid-str? nil))
; we return uuids as an object or a string
(is= java.util.UUID (type (uuid/rand)))
(is (string? (uuid/rand-str)))
(is (with-exception-default false
2 uuids are never equal
(assert (not= (uuid/rand) (uuid/rand)))
(assert (not= (uuid/rand-str) (uuid/rand-str))))
true)) ; if no failures, we pass the test
; demonstrate uuid/with-null usage for testing
(uuid/with-null
(is= (uuid/rand-str) "00000000-0000-0000-0000-000000000000")
(is= (uuid/rand-str) "00000000-0000-0000-0000-000000000000")
(is= (uuid/rand-str) "00000000-0000-0000-0000-000000000000"))
; demonstrate uuid/with-counted for testing
(uuid/with-counted
(is= (uuid/rand-str) "00000000-aaaa-bbbb-cccc-ddddeeeeffff")
(is= (uuid/rand-str) "00000001-aaaa-bbbb-cccc-ddddeeeeffff")
(is= (uuid/rand-str) "00000002-aaaa-bbbb-cccc-ddddeeeeffff")
(let [r1 (uuid/rand)
r2 (uuid/rand-str)]
(is= (type r1) java.util.UUID)
(is= (type r2) java.lang.String)
(is= (str r1) "00000003-aaaa-bbbb-cccc-ddddeeeeffff")
(is= r2 "00000004-aaaa-bbbb-cccc-ddddeeeeffff")
(is (uuid/uuid-str? r2))))
; demonstrate uuid/counted (manual)
(uuid/counted-reset!)
(is= (uuid/counted-str) "00000000-aaaa-bbbb-cccc-ddddeeeeffff")
(is= (uuid/counted-str) "00000001-aaaa-bbbb-cccc-ddddeeeeffff")
(is= (uuid/counted-str) "00000002-aaaa-bbbb-cccc-ddddeeeeffff")
(uuid/counted-reset!)
(is= (uuid/counted-str) "00000000-aaaa-bbbb-cccc-ddddeeeeffff")
(is= (uuid/counted-str) "00000001-aaaa-bbbb-cccc-ddddeeeeffff")
)
| null | https://raw.githubusercontent.com/cloojure/tupelo/dbb4b12fd6f379803a74a6bdcf54726597ec0fdf/test/clj/tst/tupelo/uuid.clj | clojure | we return uuids as an object or a string
if no failures, we pass the test
demonstrate uuid/with-null usage for testing
demonstrate uuid/with-counted for testing
demonstrate uuid/counted (manual) | (ns tst.tupelo.uuid
(:use tupelo.core tupelo.test)
(:refer-clojure :exclude [rand])
(:require
[tupelo.uuid :as uuid]))
(verify
(is= "00000000-0000-0000-0000-000000000000"
(uuid/null-str)
(str (uuid/null)))
(is= "cafebabe-1953-0510-0970-0123456789ff"
(uuid/dummy-str)
(str (uuid/dummy)))
(is (uuid? (uuid/null)))
(is (uuid? (uuid/dummy)))
(is (uuid/uuid-str? (uuid/null-str)))
(is (uuid/uuid-str? (uuid/dummy-str)))
(isnt (uuid/uuid-str? "cafebabe-1953-0510-0970-0123456789fff"))
(isnt (uuid/uuid-str? "cafebabe-1953-0510-09700-123456789ff"))
(isnt (uuid/uuid-str? "cafebabe-1953-0510-066x-0123456789ff"))
(isnt (uuid/uuid-str? "cafebabe-1953-0510-0123456789ff"))
(isnt (uuid/uuid-str? "cafebabe-1953-0510|0970-0123456789ff"))
(isnt (uuid/uuid-str? 5))
(isnt (uuid/uuid-str? :nope))
(isnt (uuid/uuid-str? nil))
(is= java.util.UUID (type (uuid/rand)))
(is (string? (uuid/rand-str)))
(is (with-exception-default false
2 uuids are never equal
(assert (not= (uuid/rand) (uuid/rand)))
(assert (not= (uuid/rand-str) (uuid/rand-str))))
(uuid/with-null
(is= (uuid/rand-str) "00000000-0000-0000-0000-000000000000")
(is= (uuid/rand-str) "00000000-0000-0000-0000-000000000000")
(is= (uuid/rand-str) "00000000-0000-0000-0000-000000000000"))
(uuid/with-counted
(is= (uuid/rand-str) "00000000-aaaa-bbbb-cccc-ddddeeeeffff")
(is= (uuid/rand-str) "00000001-aaaa-bbbb-cccc-ddddeeeeffff")
(is= (uuid/rand-str) "00000002-aaaa-bbbb-cccc-ddddeeeeffff")
(let [r1 (uuid/rand)
r2 (uuid/rand-str)]
(is= (type r1) java.util.UUID)
(is= (type r2) java.lang.String)
(is= (str r1) "00000003-aaaa-bbbb-cccc-ddddeeeeffff")
(is= r2 "00000004-aaaa-bbbb-cccc-ddddeeeeffff")
(is (uuid/uuid-str? r2))))
(uuid/counted-reset!)
(is= (uuid/counted-str) "00000000-aaaa-bbbb-cccc-ddddeeeeffff")
(is= (uuid/counted-str) "00000001-aaaa-bbbb-cccc-ddddeeeeffff")
(is= (uuid/counted-str) "00000002-aaaa-bbbb-cccc-ddddeeeeffff")
(uuid/counted-reset!)
(is= (uuid/counted-str) "00000000-aaaa-bbbb-cccc-ddddeeeeffff")
(is= (uuid/counted-str) "00000001-aaaa-bbbb-cccc-ddddeeeeffff")
)
|
832c2706d8bcfbe4264e23895cfdffce6b5f49905874a2b682ad1edac9430596 | kiranlak/austin-sbst | symbolic.ml | open Cil
open Utils
module Log = LogManager
type symbolic_state = {s : exp ExpHashtbl.t; u : exp ExpHashtbl.t}
let symStack : (lval option * symbolic_state) list ref = ref []
let state : symbolic_state ref = ref {s=ExpHashtbl.create 100; u=ExpHashtbl.create 10}
class rewriteVisitor = object(this)
inherit nopCilVisitor
method vexpr (e:exp) =
match e with
| Lval(Mem _, NoOffset) ->
(
try
let e' = ExpHashtbl.find !state.s e in
match (stripCasts e') with
| AddrOf(l) -> ChangeTo (Lval(l))
| _ -> ChangeTo e'
with
| Not_found -> DoChildren
)
| Lval(l) | StartOf(l) ->
(
try
let e' = ExpHashtbl.find !state.s e in
ChangeTo e'
with
| Not_found -> DoChildren
)
| _ -> DoChildren
end
let rewriteExpression (e:exp) =
let vis = new rewriteVisitor in
visitCilExpr vis e
class isUndefVisitor (result : bool ref) = object
inherit nopCilVisitor
method vexpr (e:exp) =
if (ExpHashtbl.mem !state.u e) then (
result := true;
SkipChildren
) else
DoChildren
end
let isExpUndefined (e:exp) =
let isUndef = ref false in
let vis = new isUndefVisitor isUndef in
ignore(visitCilExpr vis e);
!isUndef
let makeExpUndefined (e:exp) (_state: symbolic_state) =
ExpHashtbl.remove _state.s e;
ExpHashtbl.replace _state.u e e
let unassign (l:lval) (_state: symbolic_state) =
makeExpUndefined (Lval(l)) _state
let assign (l:lval) (e:exp) =
let e' = rewriteExpression e in
if (isExpUndefined e') then (
Log.debug (Printf.sprintf "not updating lval %s because %s is considered undefined\n"
(Pretty.sprint 255 (Cil.d_lval()l))
(Pretty.sprint 255 (Cil.d_exp()e')));
unassign l !state
) else (
ExpHashtbl.replace !state.s (Lval(l)) e'
)
let call (lo:lval option) (fd:fundec) (args:exp list) =
let new_state : symbolic_state = {s=ExpHashtbl.create 100; u=ExpHashtbl.create 10} in
List.iter2(
fun vi arg ->
let new_arg = rewriteExpression arg in
if (isExpUndefined new_arg) then (
ExpHashtbl.add new_state.u (Lval(var vi)) (Lval(var vi))
) else (
ExpHashtbl.add new_state.s (Lval(var vi)) new_arg
)
)fd.sformals args;
(* push current state onto stack *)
symStack := (lo,!state)::!symStack;
state := new_state
let return (eo:exp option) =
if(List.length !symStack) > 0 then (
let lo, old_state = List.hd !symStack in
symStack := List.tl !symStack;
(
match lo, eo with
| Some(l),Some(e) ->
let e' = rewriteExpression e in
if (isExpUndefined e') then
unassign l old_state
else
ExpHashtbl.replace old_state.s (Lval(l)) e'
| _ -> ()
);
state := old_state
)
let pruneState (tokeep : lval list) =
let new_state = {s=ExpHashtbl.create 100;u=ExpHashtbl.create 10} in
ExpHashtbl.iter(
fun key value ->
if (List.exists (fun l -> Utils.compareExp key (Lval(l)))tokeep) then
ExpHashtbl.add new_state.s key value;
)!state.s;
state := new_state
let currentState_to_string () =
ExpHashtbl.fold(
fun key value res ->
res ^ (Printf.sprintf "%s -> %s\n"
(Pretty.sprint 255 (Cil.d_exp()key))
(Pretty.sprint 255 (Cil.d_exp()value)))
)!state.s "symbolic state:\n"
let printCurrentState () =
Log.log (Printf.sprintf "%s" (currentState_to_string ()))
type atomicAlia = exp list (* each expr is joined by LAnd *)
type stmtConj = int*int*(atomicAlia list) (* each atomicAlia is joined by LOr *)
type pathCondition = {mutable conjuncts : stmtConj list; mutable pathExpression : exp}
let getStmtConditions (_,_,con) = con
let pc = {conjuncts = [];pathExpression = one}
let isUniqueStmtConjExpr (_,_,atomic) =
let f1 = List.flatten atomic in
not(List.exists(
fun (_,_,atomic') ->
let f2 = List.flatten atomic' in
if (List.length f1) <> (List.length f2) then false
else (
List.exists2( fun e1 e2 -> Utils.compareExp e1 e2 ) f1 f2
)
)pc.conjuncts)
let updatePathCondition (conj:stmtConj) =
if isUniqueStmtConjExpr conj then (
pc.conjuncts <- (pc.conjuncts @ [conj])
)
let printPathCondition () =
let concatenateAtomicConditions (conditions:exp list) =
List.fold_left(
fun res con ->
if res = Cil.one then
con
else
BinOp(LAnd, res, con, intType)
)Cil.one conditions
in
let concatenateStmtConj (atomicConditions:atomicAlia list) =
List.fold_left(
fun res alist ->
let atomicExpr = concatenateAtomicConditions alist in
if res = Cil.one then
atomicExpr
else
BinOp(LOr, res, atomicExpr, intType)
)Cil.one atomicConditions
in
let pc_expr =
List.fold_left(
fun cum_expr (_,_,atomics) ->
let con = concatenateStmtConj atomics in
if cum_expr = Cil.one then
con
else
BinOp(LAnd, cum_expr, con, intType)
)Cil.one pc.conjuncts
in
Log.log (Printf.sprintf "Path Condition: %s\n" (Pretty.sprint 255 (Cil.d_exp () pc_expr)))
let reset() =
symStack := [];
ExpHashtbl.clear !state.s;
ExpHashtbl.clear !state.u;
pc.conjuncts <- [];
pc.pathExpression <- one
let saveCurrentStateToFile () =
let outchan = open_out_bin (ConfigFile.find Options.keySymState) in
Marshal.to_channel outchan !state [];
close_out outchan
let loadStateFromFile () =
let fname = (ConfigFile.find Options.keySymState) in
assert(Sys.file_exists fname);
let inchan = open_in_bin fname in
state := (Marshal.from_channel inchan : symbolic_state);
close_in inchan
let savePathConditiontoFile () =
let outchan = open_out_bin (ConfigFile.find Options.keySymPath) in
Marshal.to_channel outchan pc [];
close_out outchan
let loadPathConditionfromFile () =
let fname = (ConfigFile.find Options.keySymPath) in
assert(Sys.file_exists fname);
let inchan = open_in_bin fname in
let saved = (Marshal.from_channel inchan : pathCondition) in
close_in inchan;
pc.conjuncts <- saved.conjuncts;
pc.pathExpression <- saved.pathExpression
| null | https://raw.githubusercontent.com/kiranlak/austin-sbst/9c8aac72692dca952302e0e4fdb9ff381bba58ae/AustinOcaml/symbolic/symbolic.ml | ocaml | push current state onto stack
each expr is joined by LAnd
each atomicAlia is joined by LOr | open Cil
open Utils
module Log = LogManager
type symbolic_state = {s : exp ExpHashtbl.t; u : exp ExpHashtbl.t}
let symStack : (lval option * symbolic_state) list ref = ref []
let state : symbolic_state ref = ref {s=ExpHashtbl.create 100; u=ExpHashtbl.create 10}
class rewriteVisitor = object(this)
inherit nopCilVisitor
method vexpr (e:exp) =
match e with
| Lval(Mem _, NoOffset) ->
(
try
let e' = ExpHashtbl.find !state.s e in
match (stripCasts e') with
| AddrOf(l) -> ChangeTo (Lval(l))
| _ -> ChangeTo e'
with
| Not_found -> DoChildren
)
| Lval(l) | StartOf(l) ->
(
try
let e' = ExpHashtbl.find !state.s e in
ChangeTo e'
with
| Not_found -> DoChildren
)
| _ -> DoChildren
end
let rewriteExpression (e:exp) =
let vis = new rewriteVisitor in
visitCilExpr vis e
class isUndefVisitor (result : bool ref) = object
inherit nopCilVisitor
method vexpr (e:exp) =
if (ExpHashtbl.mem !state.u e) then (
result := true;
SkipChildren
) else
DoChildren
end
let isExpUndefined (e:exp) =
let isUndef = ref false in
let vis = new isUndefVisitor isUndef in
ignore(visitCilExpr vis e);
!isUndef
let makeExpUndefined (e:exp) (_state: symbolic_state) =
ExpHashtbl.remove _state.s e;
ExpHashtbl.replace _state.u e e
let unassign (l:lval) (_state: symbolic_state) =
makeExpUndefined (Lval(l)) _state
let assign (l:lval) (e:exp) =
let e' = rewriteExpression e in
if (isExpUndefined e') then (
Log.debug (Printf.sprintf "not updating lval %s because %s is considered undefined\n"
(Pretty.sprint 255 (Cil.d_lval()l))
(Pretty.sprint 255 (Cil.d_exp()e')));
unassign l !state
) else (
ExpHashtbl.replace !state.s (Lval(l)) e'
)
let call (lo:lval option) (fd:fundec) (args:exp list) =
let new_state : symbolic_state = {s=ExpHashtbl.create 100; u=ExpHashtbl.create 10} in
List.iter2(
fun vi arg ->
let new_arg = rewriteExpression arg in
if (isExpUndefined new_arg) then (
ExpHashtbl.add new_state.u (Lval(var vi)) (Lval(var vi))
) else (
ExpHashtbl.add new_state.s (Lval(var vi)) new_arg
)
)fd.sformals args;
symStack := (lo,!state)::!symStack;
state := new_state
let return (eo:exp option) =
if(List.length !symStack) > 0 then (
let lo, old_state = List.hd !symStack in
symStack := List.tl !symStack;
(
match lo, eo with
| Some(l),Some(e) ->
let e' = rewriteExpression e in
if (isExpUndefined e') then
unassign l old_state
else
ExpHashtbl.replace old_state.s (Lval(l)) e'
| _ -> ()
);
state := old_state
)
let pruneState (tokeep : lval list) =
let new_state = {s=ExpHashtbl.create 100;u=ExpHashtbl.create 10} in
ExpHashtbl.iter(
fun key value ->
if (List.exists (fun l -> Utils.compareExp key (Lval(l)))tokeep) then
ExpHashtbl.add new_state.s key value;
)!state.s;
state := new_state
let currentState_to_string () =
ExpHashtbl.fold(
fun key value res ->
res ^ (Printf.sprintf "%s -> %s\n"
(Pretty.sprint 255 (Cil.d_exp()key))
(Pretty.sprint 255 (Cil.d_exp()value)))
)!state.s "symbolic state:\n"
let printCurrentState () =
Log.log (Printf.sprintf "%s" (currentState_to_string ()))
type pathCondition = {mutable conjuncts : stmtConj list; mutable pathExpression : exp}
let getStmtConditions (_,_,con) = con
let pc = {conjuncts = [];pathExpression = one}
let isUniqueStmtConjExpr (_,_,atomic) =
let f1 = List.flatten atomic in
not(List.exists(
fun (_,_,atomic') ->
let f2 = List.flatten atomic' in
if (List.length f1) <> (List.length f2) then false
else (
List.exists2( fun e1 e2 -> Utils.compareExp e1 e2 ) f1 f2
)
)pc.conjuncts)
let updatePathCondition (conj:stmtConj) =
if isUniqueStmtConjExpr conj then (
pc.conjuncts <- (pc.conjuncts @ [conj])
)
let printPathCondition () =
let concatenateAtomicConditions (conditions:exp list) =
List.fold_left(
fun res con ->
if res = Cil.one then
con
else
BinOp(LAnd, res, con, intType)
)Cil.one conditions
in
let concatenateStmtConj (atomicConditions:atomicAlia list) =
List.fold_left(
fun res alist ->
let atomicExpr = concatenateAtomicConditions alist in
if res = Cil.one then
atomicExpr
else
BinOp(LOr, res, atomicExpr, intType)
)Cil.one atomicConditions
in
let pc_expr =
List.fold_left(
fun cum_expr (_,_,atomics) ->
let con = concatenateStmtConj atomics in
if cum_expr = Cil.one then
con
else
BinOp(LAnd, cum_expr, con, intType)
)Cil.one pc.conjuncts
in
Log.log (Printf.sprintf "Path Condition: %s\n" (Pretty.sprint 255 (Cil.d_exp () pc_expr)))
let reset() =
symStack := [];
ExpHashtbl.clear !state.s;
ExpHashtbl.clear !state.u;
pc.conjuncts <- [];
pc.pathExpression <- one
let saveCurrentStateToFile () =
let outchan = open_out_bin (ConfigFile.find Options.keySymState) in
Marshal.to_channel outchan !state [];
close_out outchan
let loadStateFromFile () =
let fname = (ConfigFile.find Options.keySymState) in
assert(Sys.file_exists fname);
let inchan = open_in_bin fname in
state := (Marshal.from_channel inchan : symbolic_state);
close_in inchan
let savePathConditiontoFile () =
let outchan = open_out_bin (ConfigFile.find Options.keySymPath) in
Marshal.to_channel outchan pc [];
close_out outchan
let loadPathConditionfromFile () =
let fname = (ConfigFile.find Options.keySymPath) in
assert(Sys.file_exists fname);
let inchan = open_in_bin fname in
let saved = (Marshal.from_channel inchan : pathCondition) in
close_in inchan;
pc.conjuncts <- saved.conjuncts;
pc.pathExpression <- saved.pathExpression
|
0ada0108f6b9790e95ff8719248c67d9ea4a560ae361302db873ee134967b1c7 | slagyr/gaeshi | mail_spec.clj | (ns gaeshi.mail-spec
(:use
[speclj.core]
[gaeshi.mail]
[gaeshi.spec-helpers.mail])
(:import
[com.google.appengine.api.mail MailService]))
(describe "Mail"
(it "converts a simple map into a message"
(let [message (map->message {:bcc ""
:cc ""
:html "<html/>"
:reply-to ""
:from ""
:subject "Test Subject"
:text "Some Text"
:to ""})]
(should= [""] (.getBcc message))
(should= [""] (.getCc message))
(should= "<html/>" (.getHtmlBody message))
(should= "" (.getReplyTo message))
(should= "" (.getSender message))
(should= "Test Subject" (.getSubject message))
(should= "Some Text" (.getTextBody message))
(should= [""] (.getTo message))))
(it "creates message with multiple recipients"
(let [message (map->message {:bcc ["" ""]
:cc ["" ""]
:to ["" ""]})]
(should= ["" ""] (.getBcc message))
(should= ["" ""] (.getCc message))
(should= ["" ""] (.getTo message))))
(it "creates message will nil recipients if there are none"
(let [message (map->message {:bcc nil
:cc []})]
(should= [] (.getBcc message))
(should= [] (.getCc message))
(should= [] (.getTo message))))
(it "creates messages with attachments"
(let [message (map->message {:attachments [{:filename "one.txt" :data (.getBytes "Hello")}]})
attachments (.getAttachments message)]
(should= 1 (count attachments))
(should= "one.txt" (.getFileName (first attachments)))
(should= "Hello" (String. (.getData (first attachments))))))
(it "converts message back into maps"
(let [message-map {:attachments [{:filename "one.txt" :data (.getBytes "Hello")}]
:bcc [""]
:cc [""]
:html "<html/>"
:reply-to ""
:from ""
:subject "Test Subject"
:text "Some Text"
:to [""]}
message (map->message message-map)
result (message->map message)]
(should= message-map result)))
(it "the mail service is a singleton"
(should-not= nil (mail-service))
(should= (mail-service) (mail-service)))
(context "with mock service"
(with-fake-mail)
(it "sends a message"
(send-mail {:to "" :from "" :text "Howdy!"})
(should= 1 (count (sent-messages)))
(let [message (first (sent-messages))]
(should= [""] (:to message))
(should= "" (:from message))
(should= "Howdy!" (:text message))))
(it "sends a message to admins"
(send-mail-to-admins {:from "" :text "Oh noes!"})
(should= 1 (count (sent-messages-to-admins)))
(let [message (first (sent-messages-to-admins))]
(should= "" (:from message))
(should= "Oh noes!" (:text message))))
)
)
| null | https://raw.githubusercontent.com/slagyr/gaeshi/a5677ed1c8d9269d412f07a7ab33bbc40aa7011a/gaeshi/spec/gaeshi/mail_spec.clj | clojure | (ns gaeshi.mail-spec
(:use
[speclj.core]
[gaeshi.mail]
[gaeshi.spec-helpers.mail])
(:import
[com.google.appengine.api.mail MailService]))
(describe "Mail"
(it "converts a simple map into a message"
(let [message (map->message {:bcc ""
:cc ""
:html "<html/>"
:reply-to ""
:from ""
:subject "Test Subject"
:text "Some Text"
:to ""})]
(should= [""] (.getBcc message))
(should= [""] (.getCc message))
(should= "<html/>" (.getHtmlBody message))
(should= "" (.getReplyTo message))
(should= "" (.getSender message))
(should= "Test Subject" (.getSubject message))
(should= "Some Text" (.getTextBody message))
(should= [""] (.getTo message))))
(it "creates message with multiple recipients"
(let [message (map->message {:bcc ["" ""]
:cc ["" ""]
:to ["" ""]})]
(should= ["" ""] (.getBcc message))
(should= ["" ""] (.getCc message))
(should= ["" ""] (.getTo message))))
(it "creates message will nil recipients if there are none"
(let [message (map->message {:bcc nil
:cc []})]
(should= [] (.getBcc message))
(should= [] (.getCc message))
(should= [] (.getTo message))))
(it "creates messages with attachments"
(let [message (map->message {:attachments [{:filename "one.txt" :data (.getBytes "Hello")}]})
attachments (.getAttachments message)]
(should= 1 (count attachments))
(should= "one.txt" (.getFileName (first attachments)))
(should= "Hello" (String. (.getData (first attachments))))))
(it "converts message back into maps"
(let [message-map {:attachments [{:filename "one.txt" :data (.getBytes "Hello")}]
:bcc [""]
:cc [""]
:html "<html/>"
:reply-to ""
:from ""
:subject "Test Subject"
:text "Some Text"
:to [""]}
message (map->message message-map)
result (message->map message)]
(should= message-map result)))
(it "the mail service is a singleton"
(should-not= nil (mail-service))
(should= (mail-service) (mail-service)))
(context "with mock service"
(with-fake-mail)
(it "sends a message"
(send-mail {:to "" :from "" :text "Howdy!"})
(should= 1 (count (sent-messages)))
(let [message (first (sent-messages))]
(should= [""] (:to message))
(should= "" (:from message))
(should= "Howdy!" (:text message))))
(it "sends a message to admins"
(send-mail-to-admins {:from "" :text "Oh noes!"})
(should= 1 (count (sent-messages-to-admins)))
(let [message (first (sent-messages-to-admins))]
(should= "" (:from message))
(should= "Oh noes!" (:text message))))
)
)
| |
bb8455e2544027a1fdf2e3ee18952e53fbd173984c2d53719caf81f207b97f1b | ucsd-progsys/dsolve | miscutil.ml | (***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
(* $Id: misc.ml,v 1.35 2007/02/23 13:44:51 ertai Exp $ *)
(* Errors *)
exception Fatal_error
let fatal_error msg =
prerr_string ">> Fatal error: "; prerr_endline msg; raise Fatal_error
(* Exceptions *)
let try_finally f1 f2 =
try
let result = f1 () in
f2 ();
result
with x -> f2 (); raise x
;;
(* List functions *)
let rec map_end f l1 l2 =
match l1 with
[] -> l2
| hd::tl -> f hd :: map_end f tl l2
let rec map_left_right f = function
[] -> []
| hd::tl -> let res = f hd in res :: map_left_right f tl
let rec map_filter f = function
[] -> []
| hd::tl ->
let rest = map_filter f tl in
match f hd with
Some x -> x::rest
| None -> rest
let rec for_all2 pred l1 l2 =
match (l1, l2) with
([], []) -> true
| (hd1::tl1, hd2::tl2) -> pred hd1 hd2 && for_all2 pred tl1 tl2
| (_, _) -> false
let rec replicate_list elem n =
if n <= 0 then [] else elem :: replicate_list elem (n-1)
let rec list_remove x = function
[] -> []
| hd :: tl ->
if hd = x then tl else hd :: list_remove x tl
let rec split_last = function
[] -> assert false
| [x] -> ([], x)
| hd :: tl ->
let (lst, last) = split_last tl in
(hd :: lst, last)
let rec samelist pred l1 l2 =
match (l1, l2) with
| ([], []) -> true
| (hd1 :: tl1, hd2 :: tl2) -> pred hd1 hd2 && samelist pred tl1 tl2
| (_, _) -> false
let rec split3 = function
| [] -> ([], [], [])
| (x, y, z) :: rest ->
let (rx, ry, rz) = split3 rest in (x :: rx, y :: ry, z :: rz)
let mapi f l =
let rec map_rec n = function
| [] -> []
| h :: rest -> f h n :: map_rec (n + 1) rest
in map_rec 0 l
(* Options *)
let may f = function
Some x -> f x
| None -> ()
let may_map f = function
Some x -> Some (f x)
| None -> None
(* File functions *)
let find_in_path path name =
if not (Filename.is_implicit name) then
if Sys.file_exists name then name else raise Not_found
else begin
let rec try_dir = function
[] -> raise Not_found
| dir::rem ->
let fullname = Filename.concat dir name in
if Sys.file_exists fullname then fullname else try_dir rem
in try_dir path
end
let find_in_path_uncap path name =
let uname = String.uncapitalize name in
let rec try_dir = function
[] -> raise Not_found
| dir::rem ->
let fullname = Filename.concat dir name
and ufullname = Filename.concat dir uname in
if Sys.file_exists ufullname then ufullname
else if Sys.file_exists fullname then fullname
else try_dir rem
in try_dir path
let remove_file filename =
try
Sys.remove filename
with Sys_error msg ->
()
(* Expand a -I option: if it starts with +, make it relative to the standard
library directory *)
let expand_directory alt s =
if String.length s > 0 && s.[0] = '+'
then Filename.concat alt
(String.sub s 1 (String.length s - 1))
else s
(* Hashtable functions *)
let create_hashtable size init =
let tbl = Hashtbl.create size in
List.iter (fun (key, data) -> Hashtbl.add tbl key data) init;
tbl
(* File copy *)
let copy_file ic oc =
let buff = String.create 0x1000 in
let rec copy () =
let n = input ic buff 0 0x1000 in
if n = 0 then () else (output oc buff 0 n; copy())
in copy()
let copy_file_chunk ic oc len =
let buff = String.create 0x1000 in
let rec copy n =
if n <= 0 then () else begin
let r = input ic buff 0 (min n 0x1000) in
if r = 0 then raise End_of_file else (output oc buff 0 r; copy(n-r))
end
in copy len
Integer operations
let rec log2 n =
if n <= 1 then 0 else 1 + log2(n asr 1)
let align n a =
if n >= 0 then (n + a - 1) land (-a) else n land (-a)
let no_overflow_add a b = (a lxor b) lor (a lxor (lnot (a+b))) < 0
let no_overflow_sub a b = (a lxor (lnot b)) lor (b lxor (a-b)) < 0
let no_overflow_lsl a = min_int asr 1 <= a && a <= max_int asr 1
(* String operations *)
let chop_extension_if_any fname =
try Filename.chop_extension fname with Invalid_argument _ -> fname
let get_extension fname =
try
let dotpos = String.rindex fname '.' + 1 in
Some (String.sub fname dotpos (String.length fname - dotpos))
with _ ->
None
let chop_extensions file =
let dirname = Filename.dirname file and basename = Filename.basename file in
try
let pos = String.index basename '.' in
let basename = String.sub basename 0 pos in
if Filename.is_implicit file && dirname = Filename.current_dir_name then
basename
else
Filename.concat dirname basename
with Not_found -> file
let search_substring pat str start =
let rec search i j =
if j >= String.length pat then i
else if i + j >= String.length str then raise Not_found
else if str.[i + j] = pat.[j] then search i (j+1)
else search (i+1) 0
in search start 0
let rev_split_words s =
let rec split1 res i =
if i >= String.length s then res else begin
match s.[i] with
' ' | '\t' | '\r' | '\n' -> split1 res (i+1)
| _ -> split2 res i (i+1)
end
and split2 res i j =
if j >= String.length s then String.sub s i (j-i) :: res else begin
match s.[j] with
' ' | '\t' | '\r' | '\n' -> split1 (String.sub s i (j-i) :: res) (j+1)
| _ -> split2 res i (j+1)
end
in split1 [] 0
let do_memo memo f args key =
try Hashtbl.find memo key with Not_found ->
let rv = f args in
let _ = Hashtbl.replace memo key rv in
rv
let rec repeat_fn f i =
if i = 0 then ()
else (f (); repeat_fn f (i-1))
let rec format_list_of_strings ppf (delim, ls) =
if List.length ls > 1 then
Format.fprintf ppf "@[%s%s@\n%a@]" (List.hd ls) delim format_list_of_strings (delim, List.tl ls)
else if List.length ls = 1 then
Format.fprintf ppf "@[%s%s@\n@]" (List.hd ls) delim
else
Format.fprintf ppf ""
| null | https://raw.githubusercontent.com/ucsd-progsys/dsolve/bfbbb8ed9bbf352d74561e9f9127ab07b7882c0c/utils/miscutil.ml | ocaml | *********************************************************************
Objective Caml
*********************************************************************
$Id: misc.ml,v 1.35 2007/02/23 13:44:51 ertai Exp $
Errors
Exceptions
List functions
Options
File functions
Expand a -I option: if it starts with +, make it relative to the standard
library directory
Hashtable functions
File copy
String operations | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
exception Fatal_error
let fatal_error msg =
prerr_string ">> Fatal error: "; prerr_endline msg; raise Fatal_error
let try_finally f1 f2 =
try
let result = f1 () in
f2 ();
result
with x -> f2 (); raise x
;;
let rec map_end f l1 l2 =
match l1 with
[] -> l2
| hd::tl -> f hd :: map_end f tl l2
let rec map_left_right f = function
[] -> []
| hd::tl -> let res = f hd in res :: map_left_right f tl
let rec map_filter f = function
[] -> []
| hd::tl ->
let rest = map_filter f tl in
match f hd with
Some x -> x::rest
| None -> rest
let rec for_all2 pred l1 l2 =
match (l1, l2) with
([], []) -> true
| (hd1::tl1, hd2::tl2) -> pred hd1 hd2 && for_all2 pred tl1 tl2
| (_, _) -> false
let rec replicate_list elem n =
if n <= 0 then [] else elem :: replicate_list elem (n-1)
let rec list_remove x = function
[] -> []
| hd :: tl ->
if hd = x then tl else hd :: list_remove x tl
let rec split_last = function
[] -> assert false
| [x] -> ([], x)
| hd :: tl ->
let (lst, last) = split_last tl in
(hd :: lst, last)
let rec samelist pred l1 l2 =
match (l1, l2) with
| ([], []) -> true
| (hd1 :: tl1, hd2 :: tl2) -> pred hd1 hd2 && samelist pred tl1 tl2
| (_, _) -> false
let rec split3 = function
| [] -> ([], [], [])
| (x, y, z) :: rest ->
let (rx, ry, rz) = split3 rest in (x :: rx, y :: ry, z :: rz)
let mapi f l =
let rec map_rec n = function
| [] -> []
| h :: rest -> f h n :: map_rec (n + 1) rest
in map_rec 0 l
let may f = function
Some x -> f x
| None -> ()
let may_map f = function
Some x -> Some (f x)
| None -> None
let find_in_path path name =
if not (Filename.is_implicit name) then
if Sys.file_exists name then name else raise Not_found
else begin
let rec try_dir = function
[] -> raise Not_found
| dir::rem ->
let fullname = Filename.concat dir name in
if Sys.file_exists fullname then fullname else try_dir rem
in try_dir path
end
let find_in_path_uncap path name =
let uname = String.uncapitalize name in
let rec try_dir = function
[] -> raise Not_found
| dir::rem ->
let fullname = Filename.concat dir name
and ufullname = Filename.concat dir uname in
if Sys.file_exists ufullname then ufullname
else if Sys.file_exists fullname then fullname
else try_dir rem
in try_dir path
let remove_file filename =
try
Sys.remove filename
with Sys_error msg ->
()
let expand_directory alt s =
if String.length s > 0 && s.[0] = '+'
then Filename.concat alt
(String.sub s 1 (String.length s - 1))
else s
let create_hashtable size init =
let tbl = Hashtbl.create size in
List.iter (fun (key, data) -> Hashtbl.add tbl key data) init;
tbl
let copy_file ic oc =
let buff = String.create 0x1000 in
let rec copy () =
let n = input ic buff 0 0x1000 in
if n = 0 then () else (output oc buff 0 n; copy())
in copy()
let copy_file_chunk ic oc len =
let buff = String.create 0x1000 in
let rec copy n =
if n <= 0 then () else begin
let r = input ic buff 0 (min n 0x1000) in
if r = 0 then raise End_of_file else (output oc buff 0 r; copy(n-r))
end
in copy len
Integer operations
let rec log2 n =
if n <= 1 then 0 else 1 + log2(n asr 1)
let align n a =
if n >= 0 then (n + a - 1) land (-a) else n land (-a)
let no_overflow_add a b = (a lxor b) lor (a lxor (lnot (a+b))) < 0
let no_overflow_sub a b = (a lxor (lnot b)) lor (b lxor (a-b)) < 0
let no_overflow_lsl a = min_int asr 1 <= a && a <= max_int asr 1
let chop_extension_if_any fname =
try Filename.chop_extension fname with Invalid_argument _ -> fname
let get_extension fname =
try
let dotpos = String.rindex fname '.' + 1 in
Some (String.sub fname dotpos (String.length fname - dotpos))
with _ ->
None
let chop_extensions file =
let dirname = Filename.dirname file and basename = Filename.basename file in
try
let pos = String.index basename '.' in
let basename = String.sub basename 0 pos in
if Filename.is_implicit file && dirname = Filename.current_dir_name then
basename
else
Filename.concat dirname basename
with Not_found -> file
let search_substring pat str start =
let rec search i j =
if j >= String.length pat then i
else if i + j >= String.length str then raise Not_found
else if str.[i + j] = pat.[j] then search i (j+1)
else search (i+1) 0
in search start 0
let rev_split_words s =
let rec split1 res i =
if i >= String.length s then res else begin
match s.[i] with
' ' | '\t' | '\r' | '\n' -> split1 res (i+1)
| _ -> split2 res i (i+1)
end
and split2 res i j =
if j >= String.length s then String.sub s i (j-i) :: res else begin
match s.[j] with
' ' | '\t' | '\r' | '\n' -> split1 (String.sub s i (j-i) :: res) (j+1)
| _ -> split2 res i (j+1)
end
in split1 [] 0
let do_memo memo f args key =
try Hashtbl.find memo key with Not_found ->
let rv = f args in
let _ = Hashtbl.replace memo key rv in
rv
let rec repeat_fn f i =
if i = 0 then ()
else (f (); repeat_fn f (i-1))
let rec format_list_of_strings ppf (delim, ls) =
if List.length ls > 1 then
Format.fprintf ppf "@[%s%s@\n%a@]" (List.hd ls) delim format_list_of_strings (delim, List.tl ls)
else if List.length ls = 1 then
Format.fprintf ppf "@[%s%s@\n@]" (List.hd ls) delim
else
Format.fprintf ppf ""
|
9696d11d984423fb1f3effbafdf01c5f8a4ec08cee4fce62fcca5d978828b0df | rm-hull/project-euler | euler004.clj | EULER # 004
;; ==========
;; A palindromic number reads the same both ways. The largest
palindrome made from the product of two 2 - digit numbers is
9009 = 91 x 99 .
;;
Find the largest palindrome made from the product of two
3 - digit numbers .
;;
(ns euler004
(:use [util.palindromes]))
(defn solve []
(reduce max
(for [a (range 100 1000)
b (range a 1000)
:let [sum (* a b)]
:when (is-palindrome? sum)]
sum)))
(time (solve))
| null | https://raw.githubusercontent.com/rm-hull/project-euler/04e689e87a1844cfd83229bb4628051e3ac6a325/src/euler004.clj | clojure | ==========
A palindromic number reads the same both ways. The largest
| EULER # 004
palindrome made from the product of two 2 - digit numbers is
9009 = 91 x 99 .
Find the largest palindrome made from the product of two
3 - digit numbers .
(ns euler004
(:use [util.palindromes]))
(defn solve []
(reduce max
(for [a (range 100 1000)
b (range a 1000)
:let [sum (* a b)]
:when (is-palindrome? sum)]
sum)))
(time (solve))
|
6f409e6136ab140872c6bd1e8fd936a3b7d64e4a12197e28c6d4fb554d1a9c7b | tommaisey/aeon | playhead.scm | ;;-----------------------------------------------------------------
(define bpm 115)
(define playback-thread #f)
(define playback-chunk 1/8) ; 1/8th beat for now
(define playback-thread-semaphore (make-semaphore))
(define playback-latency 0.2)
State used to mitigate timing jitter in callbacks :
(define last-process-time #f) ;; time of last callback, utc
(define last-process-beat 0) ;; time of last callback, beats
(define jitter-overlap 1/32) ;; extra time to render each block
musical time that has been sent to SC
;; Find out how many beats have elapsed since the last process-chunk.
(define (beats-since-last-process utc-time)
(if (not last-process-time) 0
(secs->measures (- utc-time last-process-time) bpm)))
;; Called regularly by the playback thread. It renders events in
;; chunks whose length are determined by playback-chunk, plus a
;; little extra ('jitter-overlap') to allow for the callback to
;; happen late.
(define (process-chunk)
(let ([t (sc/utc)])
;; Make a dispatcher for all the events rendered from a pattern.
(define (pattern-player beat-now start end)
(lambda (p)
(for-each (lambda (e) (play-event e beat-now t))
(context-events-next (render-arc p start end)))))
(guard (x [else (handle-error x)])
(let* ([now (+ last-process-beat (beats-since-last-process t))]
[start (or rendered-point now)]
[end (+ now playback-chunk jitter-overlap)]
[player (pattern-player now start end)])
(iterate-patterns pattern-dict player)
(update-recording now (make-arc start end) t)
(set! last-process-time t)
(set! last-process-beat now)
(set! rendered-point end)))))
;; TODO: clear only the offending pattern on error
(define (handle-error condition)
(let ([p (current-output-port)])
(display-condition condition p)
(newline p)
(flush-output-port p)
(clear-patterns pattern-dict)))
;; Only creates new thread if one isn't already in playback-thread.
(define (start-thread semaphore)
(when (not playback-thread)
(set! playback-thread
(start-suspendable-thread
process-chunk (* playback-chunk (bpm->spm bpm)) semaphore))))
(define (play)
(start-thread playback-thread-semaphore)
(stop-waiting playback-thread-semaphore))
(define (pause)
(start-waiting playback-thread-semaphore)
(so/send sc3 sc/clear-sched)
(cancel-recording)
(set! rendered-point #f)
(set! last-process-time #f))
(define* (rewind [/opt (keep-playing #t)])
(pause)
(set! last-process-beat 0)
(when keep-playing (play)))
(define (playing?)
(not (waiting? playback-thread-semaphore)))
(define (set-bpm! n)
(set! bpm n)
(play-event (make-event 0
:tempo (bpm->mps n)
:control "tempo"
:group send-effect-group) 0))
| null | https://raw.githubusercontent.com/tommaisey/aeon/12e8ff92bd5efed2923aecf974fa12d39835abc6/runtime/playhead.scm | scheme | -----------------------------------------------------------------
1/8th beat for now
time of last callback, utc
time of last callback, beats
extra time to render each block
Find out how many beats have elapsed since the last process-chunk.
Called regularly by the playback thread. It renders events in
chunks whose length are determined by playback-chunk, plus a
little extra ('jitter-overlap') to allow for the callback to
happen late.
Make a dispatcher for all the events rendered from a pattern.
TODO: clear only the offending pattern on error
Only creates new thread if one isn't already in playback-thread. | (define bpm 115)
(define playback-thread #f)
(define playback-thread-semaphore (make-semaphore))
(define playback-latency 0.2)
State used to mitigate timing jitter in callbacks :
musical time that has been sent to SC
(define (beats-since-last-process utc-time)
(if (not last-process-time) 0
(secs->measures (- utc-time last-process-time) bpm)))
(define (process-chunk)
(let ([t (sc/utc)])
(define (pattern-player beat-now start end)
(lambda (p)
(for-each (lambda (e) (play-event e beat-now t))
(context-events-next (render-arc p start end)))))
(guard (x [else (handle-error x)])
(let* ([now (+ last-process-beat (beats-since-last-process t))]
[start (or rendered-point now)]
[end (+ now playback-chunk jitter-overlap)]
[player (pattern-player now start end)])
(iterate-patterns pattern-dict player)
(update-recording now (make-arc start end) t)
(set! last-process-time t)
(set! last-process-beat now)
(set! rendered-point end)))))
(define (handle-error condition)
(let ([p (current-output-port)])
(display-condition condition p)
(newline p)
(flush-output-port p)
(clear-patterns pattern-dict)))
(define (start-thread semaphore)
(when (not playback-thread)
(set! playback-thread
(start-suspendable-thread
process-chunk (* playback-chunk (bpm->spm bpm)) semaphore))))
(define (play)
(start-thread playback-thread-semaphore)
(stop-waiting playback-thread-semaphore))
(define (pause)
(start-waiting playback-thread-semaphore)
(so/send sc3 sc/clear-sched)
(cancel-recording)
(set! rendered-point #f)
(set! last-process-time #f))
(define* (rewind [/opt (keep-playing #t)])
(pause)
(set! last-process-beat 0)
(when keep-playing (play)))
(define (playing?)
(not (waiting? playback-thread-semaphore)))
(define (set-bpm! n)
(set! bpm n)
(play-event (make-event 0
:tempo (bpm->mps n)
:control "tempo"
:group send-effect-group) 0))
|
11dd50eb1e07e492a3ee32aa2799f0ded5c9068a8c54fe8980e82c7311feb6d1 | patrikja/AFPcourse | Signal.hs | -- | A very simple library for manipulating continuous signals.
module Signal
( module SignalImpl
, module Signal
, module Control.Applicative
) where
import Control.Applicative
-- Alternative implementation:
> import Signal . Shallow as SignalImpl
import Signal.Deep as SignalImpl
| TODO : Fix Haddock Ticket # 121 ( could be part of lab 3 for eager students )
-- <>
-- | 'Signal' is an applicative functor
instance Functor Signal where
fmap = mapS
instance Applicative Signal where
pure = constS
(<*>) = ($$)
| null | https://raw.githubusercontent.com/patrikja/AFPcourse/1a079ae80ba2dbb36f3f79f0fc96a502c0f670b6/L2/src/Signal.hs | haskell | | A very simple library for manipulating continuous signals.
Alternative implementation:
<>
| 'Signal' is an applicative functor | module Signal
( module SignalImpl
, module Signal
, module Control.Applicative
) where
import Control.Applicative
> import Signal . Shallow as SignalImpl
import Signal.Deep as SignalImpl
| TODO : Fix Haddock Ticket # 121 ( could be part of lab 3 for eager students )
instance Functor Signal where
fmap = mapS
instance Applicative Signal where
pure = constS
(<*>) = ($$)
|
9ca4f9217423ed1d0b66fea1f67025f5f1080c261fbfaf227ddee114752be07d | tfausak/patrol | BrowserContext.hs | module Patrol.Type.BrowserContext where
import qualified Data.Aeson as Aeson
import qualified Data.Text as Text
import qualified Patrol.Extra.Aeson as Aeson
-- | <-payloads/types/#browsercontext>
data BrowserContext = BrowserContext
{ name :: Text.Text,
version :: Text.Text
}
deriving (Eq, Show)
instance Aeson.ToJSON BrowserContext where
toJSON browserContext =
Aeson.intoObject
[ Aeson.pair "name" $ name browserContext,
Aeson.pair "version" $ version browserContext
]
empty :: BrowserContext
empty =
BrowserContext
{ name = Text.empty,
version = Text.empty
}
| null | https://raw.githubusercontent.com/tfausak/patrol/1cae55b3840b328cda7de85ea424333fcab434cb/source/library/Patrol/Type/BrowserContext.hs | haskell | | <-payloads/types/#browsercontext> | module Patrol.Type.BrowserContext where
import qualified Data.Aeson as Aeson
import qualified Data.Text as Text
import qualified Patrol.Extra.Aeson as Aeson
data BrowserContext = BrowserContext
{ name :: Text.Text,
version :: Text.Text
}
deriving (Eq, Show)
instance Aeson.ToJSON BrowserContext where
toJSON browserContext =
Aeson.intoObject
[ Aeson.pair "name" $ name browserContext,
Aeson.pair "version" $ version browserContext
]
empty :: BrowserContext
empty =
BrowserContext
{ name = Text.empty,
version = Text.empty
}
|
4a40271fcbc7e6a57540b5040b7132f0633db7a9372750c54d7c917f8b190b96 | acieroid/scala-am | matmul.scm | ;; Benchmark that compare recursive concurrent matrix multiplication with naive sequential matrix multiplication
(define N (expt 2 42))
(define (build-vector n init f)
(letrec ((v (make-vector n init))
(loop (lambda (i)
(if (< i n)
(begin
(vector-set! v i (f i))
(loop (+ i 1)))
v))))
(loop 0)))
(define (random-matrix w h)
(build-vector N (vector)
(lambda (i)
(build-vector N 0 (lambda (j) (random 100))))))
(define (extract-matrix M size fromx fromy)
(build-vector size (vector)
(lambda (i)
(build-vector size 0 (lambda (j)
(vector-ref (vector-ref M (+ fromx i)) (+ fromy j)))))))
(define (split-matrix M)
(let ((half (/ (vector-length M) 2)))
(let ((M11 (extract-matrix M half 0 0))
(M12 (extract-matrix M half half 0))
(M21 (extract-matrix M half 0 half))
(M22 (extract-matrix M half half half)))
(list M11 M12 M21 M22))))
(define (combine-matrices size M11 M12 M21 M22)
(let ((half (vector-length M11)))
(build-vector size (vector)
(lambda (i)
(build-vector size 0
(lambda (j)
(if (and (< i half) (< j half))
(vector-ref (vector-ref M11 i) j)
(if (and (>= i half) (< j half))
(vector-ref (vector-ref M12 (- i half)) j)
(if (and (< i half) (>= j half))
(vector-ref (vector-ref M21 i) (- j half))
(vector-ref (vector-ref M22 (- i half)) (- j half)))))))))))
(define (matrix+ A B)
(build-vector (vector-length A) (vector)
(lambda (i)
(build-vector (vector-length (vector-ref A i)) 0
(lambda (j)
(+ (vector-ref (vector-ref A i) j)
(vector-ref (vector-ref B i) j)))))))
(define (matrix-multiply B A)
(if (= (vector-length A) 1)
(vector (vector (* (vector-ref (vector-ref A 0) 0) (vector-ref (vector-ref B 0) 0))))
(let* ((A-sub (split-matrix A))
(A11 (car A-sub))
(A12 (cadr A-sub))
(A21 (caddr A-sub))
(A22 (cadddr A-sub))
(B-sub (split-matrix B))
(B11 (car B-sub))
(B12 (cadr B-sub))
(B21 (caddr B-sub))
(B22 (cadddr B-sub))
(C11t (future (matrix+ (matrix-multiply A11 B11) (matrix-multiply A12 B21))))
(C12t (future (matrix+ (matrix-multiply A11 B12) (matrix-multiply A12 B22))))
(C21t (future (matrix+ (matrix-multiply A21 B11) (matrix-multiply A22 B21))))
(C22t (future (matrix+ (matrix-multiply A21 B12) (matrix-multiply A22 B22)))))
(combine-matrices (vector-length A) (deref C11t) (deref C12t) (deref C21t) (deref C22t)))))
(define (matrix-multiply-seq A B)
(let* ((n (vector-length A))
(C (build-vector n (vector) (lambda (i) (make-vector n 0)))))
(letrec ((loopi
(lambda (i)
(if (= i n)
C
(letrec ((loopj
(lambda (j)
(if (= j n)
'done
(letrec ((loopk
(lambda (k)
(if (= k n)
'done
(begin
(vector-set! (vector-ref C i) j
(+ (vector-ref (vector-ref C i) j)
(* (vector-ref (vector-ref A i) k)
(vector-ref (vector-ref B k) j))))
(loopk (+ k 1)))))))
(loopk 0)
(loopj (+ j 1)))))))
(loopj 0)
(loopi (+ i 1)))))))
(loopi 0))))
(define (check-equality M1 M2)
(and (= (vector-length M1) (vector-length M2))
(letrec ((loop-elements (lambda (i j)
(if (= j (vector-length (vector-ref M1 i)))
#t
(if (= (vector-ref (vector-ref M1 i) j) (vector-ref (vector-ref M2 i) j))
(loop-elements i (+ j 1))
#f))))
(loop-line (lambda (i)
(if (= i (vector-length M1))
#t
(if (and (= (vector-length (vector-ref M1 i)) (vector-length (vector-ref M2 i)))
(loop-elements i 0))
(loop-line (+ i 1))
#f)))))
(loop-line 0))))
(define A (random-matrix N N))
(define B (random-matrix N N))
(define C (matrix-multiply A B))
(define C2 (matrix-multiply-seq A B))
(check-equality C C2)
| null | https://raw.githubusercontent.com/acieroid/scala-am/13ef3befbfc664b77f31f56847c30d60f4ee7dfe/test/concurrentScheme/futures/matmul.scm | scheme | Benchmark that compare recursive concurrent matrix multiplication with naive sequential matrix multiplication | (define N (expt 2 42))
(define (build-vector n init f)
(letrec ((v (make-vector n init))
(loop (lambda (i)
(if (< i n)
(begin
(vector-set! v i (f i))
(loop (+ i 1)))
v))))
(loop 0)))
(define (random-matrix w h)
(build-vector N (vector)
(lambda (i)
(build-vector N 0 (lambda (j) (random 100))))))
(define (extract-matrix M size fromx fromy)
(build-vector size (vector)
(lambda (i)
(build-vector size 0 (lambda (j)
(vector-ref (vector-ref M (+ fromx i)) (+ fromy j)))))))
(define (split-matrix M)
(let ((half (/ (vector-length M) 2)))
(let ((M11 (extract-matrix M half 0 0))
(M12 (extract-matrix M half half 0))
(M21 (extract-matrix M half 0 half))
(M22 (extract-matrix M half half half)))
(list M11 M12 M21 M22))))
(define (combine-matrices size M11 M12 M21 M22)
(let ((half (vector-length M11)))
(build-vector size (vector)
(lambda (i)
(build-vector size 0
(lambda (j)
(if (and (< i half) (< j half))
(vector-ref (vector-ref M11 i) j)
(if (and (>= i half) (< j half))
(vector-ref (vector-ref M12 (- i half)) j)
(if (and (< i half) (>= j half))
(vector-ref (vector-ref M21 i) (- j half))
(vector-ref (vector-ref M22 (- i half)) (- j half)))))))))))
(define (matrix+ A B)
(build-vector (vector-length A) (vector)
(lambda (i)
(build-vector (vector-length (vector-ref A i)) 0
(lambda (j)
(+ (vector-ref (vector-ref A i) j)
(vector-ref (vector-ref B i) j)))))))
(define (matrix-multiply B A)
(if (= (vector-length A) 1)
(vector (vector (* (vector-ref (vector-ref A 0) 0) (vector-ref (vector-ref B 0) 0))))
(let* ((A-sub (split-matrix A))
(A11 (car A-sub))
(A12 (cadr A-sub))
(A21 (caddr A-sub))
(A22 (cadddr A-sub))
(B-sub (split-matrix B))
(B11 (car B-sub))
(B12 (cadr B-sub))
(B21 (caddr B-sub))
(B22 (cadddr B-sub))
(C11t (future (matrix+ (matrix-multiply A11 B11) (matrix-multiply A12 B21))))
(C12t (future (matrix+ (matrix-multiply A11 B12) (matrix-multiply A12 B22))))
(C21t (future (matrix+ (matrix-multiply A21 B11) (matrix-multiply A22 B21))))
(C22t (future (matrix+ (matrix-multiply A21 B12) (matrix-multiply A22 B22)))))
(combine-matrices (vector-length A) (deref C11t) (deref C12t) (deref C21t) (deref C22t)))))
(define (matrix-multiply-seq A B)
(let* ((n (vector-length A))
(C (build-vector n (vector) (lambda (i) (make-vector n 0)))))
(letrec ((loopi
(lambda (i)
(if (= i n)
C
(letrec ((loopj
(lambda (j)
(if (= j n)
'done
(letrec ((loopk
(lambda (k)
(if (= k n)
'done
(begin
(vector-set! (vector-ref C i) j
(+ (vector-ref (vector-ref C i) j)
(* (vector-ref (vector-ref A i) k)
(vector-ref (vector-ref B k) j))))
(loopk (+ k 1)))))))
(loopk 0)
(loopj (+ j 1)))))))
(loopj 0)
(loopi (+ i 1)))))))
(loopi 0))))
(define (check-equality M1 M2)
(and (= (vector-length M1) (vector-length M2))
(letrec ((loop-elements (lambda (i j)
(if (= j (vector-length (vector-ref M1 i)))
#t
(if (= (vector-ref (vector-ref M1 i) j) (vector-ref (vector-ref M2 i) j))
(loop-elements i (+ j 1))
#f))))
(loop-line (lambda (i)
(if (= i (vector-length M1))
#t
(if (and (= (vector-length (vector-ref M1 i)) (vector-length (vector-ref M2 i)))
(loop-elements i 0))
(loop-line (+ i 1))
#f)))))
(loop-line 0))))
(define A (random-matrix N N))
(define B (random-matrix N N))
(define C (matrix-multiply A B))
(define C2 (matrix-multiply-seq A B))
(check-equality C C2)
|
d89ebac6993e8d38175af69b08cb74790a0920ceb6249da028bd9234259a66bd | datacraft-sciences/confuse | binary_class_metrics.clj | (ns confuse.binary-class-metrics
(:require [clojure.core.matrix :as m]
[clojure.core.matrix.impl.pprint :refer [pm]]
[clojure.core.matrix.dataset :as cd]))
(defn- accuracy-helper
[pred-ac-seq filtfn]
(let [denom (count pred-ac-seq)
pred-ac-same (-> (filter filtfn pred-ac-seq) count double)]
(/ pred-ac-same denom)))
(defn counts
([actual predicted filt1]
(first (reduce (fn [[acc1] x]
(let [ac1 (if (filt1 x) (inc acc1) acc1)]
[ac1]))
[0] (mapv vector predicted actual))))
([actual predicted filt1 filt2]
(let [[numer denom] (reduce (fn [[acc1 acc2] x]
(let [ac1 (if (filt1 x) (inc acc1) acc1)
ac2 (if (filt2 x) (inc acc2) acc2)]
[ac1 ac2]))
[0 0] (mapv vector predicted actual))]
(double (/ numer denom)))))
(defn accuracy
"Accepts a vector where each element is a vector with 2 elements, the predicted
and actual class. "
[actual predicted]
(counts actual predicted (fn [[a b]] (= a b))
identity))
(comment
(s/fdef accuracy
:args (s/every #(= 2 (count %)))
:ret double?)
(stest/instrument `accuracy))
(defn true-positives
"returns the count of true positives, defined as predicted positive class and actual positive class"
([actual predicted] (true-positives actual predicted 1))
([actual predicted positive-class]
(counts actual predicted
(fn [[a b]] (= a b positive-class)))))
(defn true-positive-rate
"returns the true positive rate, defined as the count of correctly predicted positives divided by count of actual positives,
Also known as sensitivity and recall"
[actual predicted positive-class]
(counts actual predicted (fn [[pred ac]] (= pred ac positive-class))
(fn [[pred ac]] (= ac positive-class))))
(defn sensitivity
"returns sensitivity, defined as the count of correctly predicted positives divided by count of actual positives. Also known as true positive rate or recall"
[actual predicted positive-class]
(true-positive-rate actual predicted positive-class))
(defn recall
"returns sensitivity, defined as the count of correctly predicted positives divided by count of actual positives. Also known as true positive rate or sensitivity "
[actual predicted positive-class]
(true-positive-rate actual predicted positive-class))
(defn true-negatives
"returns the count of true positives, defined as count of predicted negative class and actual negative class"
[actual predicted positive-class]
(counts actual predicted (fn [[pred ac]] (and (not= pred positive-class)
(not= ac positive-class)))))
(defn true-negative-rate
"returns the true negative rate, defined as the count of correctly predicted negatives divided by count of actual negatives "
[actual predicted positive-class]
(counts actual predicted
(fn [[pred ac]] (and (not= pred positive-class)
(not= ac positive-class)))
(fn [[pred ac]] (not= ac positive-class))))
(defn specificity
"returns the specificity, also known as true negative rate, defined as the count of correctly predicted negatives divided by count of actual negatives "
[actual predicted positive-class]
(true-negative-rate actual predicted positive-class))
(defn false-positives
"returns the count of false positives, defined as the count of predicted positive class and actual negative class"
[actual predicted positive-class]
(counts actual predicted
(fn [[pred ac]] (and (= pred positive-class)
(not= ac positive-class)))))
(defn false-positive-rate
"returns the false positive rate, defined as count of actual positives predicted as a negative, divided by count of actual negatives.
Also known as fall-out."
[actual predicted positive-class]
(counts actual predicted
(fn [[pred ac]] (and (= pred positive-class) (not= ac positive-class)))
(fn [[pred ac]] (and (not= pred positive-class) (not= ac positive-class)))))
(defn false-negatives
"returns the count of false negatives, defined as the count of predicted negative class and actual positive class"
[actual predicted positive-class]
(counts actual predicted
(fn [[pred ac]] (and (not= pred positive-class)
(= ac positive-class)))))
(defn false-negative-rate
"returns the false negative rate, defined as count of actual positive and predicted negative, divided by count of actual positives"
[actual predicted positive-class]
(counts actual predicted
(fn [[pred ac]] (and (not= pred positive-class)
(= ac positive-class)))
(fn [[pred ac]] (= ac positive-class))))
(defn precision
"returns Precision, defined as the count of true positives over the count of true positives plus the count of false positives."
[actual predicted positive-class]
(counts actual predicted
(fn [[pred ac]] (= ac pred positive-class))
(fn [[pred ac]] (= pred positive-class))))
(defn recall
"Returns the recall"
[actual predicted positive-class]
(true-positive-rate actual predicted positive-class))
(defn f1-score
"returns the F1 score, defined as the harmonic mean of precision and recall."
[actual predicted positive-class]
(let [prec (precision actual predicted positive-class)
recall (recall actual predicted positive-class)]
(* 2 (/ (* prec recall) (+ prec recall)))))
(defn misclassification-rate
"returns the misclassification rate, defined as (1 - accuracy) "
[actual predicted]
(- 1 (accuracy actual predicted)))
(defn mcc
"returns the Matthews Correlation Coefficient"
[actual predicted positive-class]
(let [
tp (true-positives actual predicted positive-class)
tn (true-negatives actual predicted positive-class)
fp (false-positives actual predicted positive-class)
fn_ (false-negatives actual predicted positive-class)
cov-x-y (- (* tp tn) (* fp fn_))
cov-x-x (Math/sqrt (* (+ tp fp) (+ tp fn_) (+ tn fp ) (+ tn fn_)))
]
(if (= cov-x-x 0.0)
0.0
(/ cov-x-y cov-x-x))))
(defn- conf-mat
[freq classes]
(let [mapkeys (vec (for [i classes j classes] [i j]))]
(merge-with + freq (zipmap mapkeys (repeat 0)))))
(defn confusion-matrix
"returns a map representing the confusion matrix. The keys are a vector with [predicted, actual] and the values are the counts."
(
[actual predicted]
(let [freq (frequencies (mapv vector predicted actual ) )
classes (sort (set (mapv second (keys freq))))]
(conf-mat freq classes)))
([actual predicted classes]
(let [freq (frequencies (mapv vector predicted actual ))]
(conf-mat freq classes))))
(defn confusion-matrix-str
"returns a string representation given a confusion matrix as a map argument"
[conf-mat]
(let [classes (sort (set (mapv second (keys conf-mat))))
nc (count classes)
order (partition nc nc (for [i classes j classes] [j i]))]
(cd/dataset (into ["-"] classes)
(mapv #(into [%2] (mapv (fn [i] (get conf-mat i 0)) %1)) order classes))))
| null | https://raw.githubusercontent.com/datacraft-sciences/confuse/d6c908cde9d5e47aa2b32bb416b352fa44aa72b7/src/confuse/binary_class_metrics.clj | clojure | (ns confuse.binary-class-metrics
(:require [clojure.core.matrix :as m]
[clojure.core.matrix.impl.pprint :refer [pm]]
[clojure.core.matrix.dataset :as cd]))
(defn- accuracy-helper
[pred-ac-seq filtfn]
(let [denom (count pred-ac-seq)
pred-ac-same (-> (filter filtfn pred-ac-seq) count double)]
(/ pred-ac-same denom)))
(defn counts
([actual predicted filt1]
(first (reduce (fn [[acc1] x]
(let [ac1 (if (filt1 x) (inc acc1) acc1)]
[ac1]))
[0] (mapv vector predicted actual))))
([actual predicted filt1 filt2]
(let [[numer denom] (reduce (fn [[acc1 acc2] x]
(let [ac1 (if (filt1 x) (inc acc1) acc1)
ac2 (if (filt2 x) (inc acc2) acc2)]
[ac1 ac2]))
[0 0] (mapv vector predicted actual))]
(double (/ numer denom)))))
(defn accuracy
"Accepts a vector where each element is a vector with 2 elements, the predicted
and actual class. "
[actual predicted]
(counts actual predicted (fn [[a b]] (= a b))
identity))
(comment
(s/fdef accuracy
:args (s/every #(= 2 (count %)))
:ret double?)
(stest/instrument `accuracy))
(defn true-positives
"returns the count of true positives, defined as predicted positive class and actual positive class"
([actual predicted] (true-positives actual predicted 1))
([actual predicted positive-class]
(counts actual predicted
(fn [[a b]] (= a b positive-class)))))
(defn true-positive-rate
"returns the true positive rate, defined as the count of correctly predicted positives divided by count of actual positives,
Also known as sensitivity and recall"
[actual predicted positive-class]
(counts actual predicted (fn [[pred ac]] (= pred ac positive-class))
(fn [[pred ac]] (= ac positive-class))))
(defn sensitivity
"returns sensitivity, defined as the count of correctly predicted positives divided by count of actual positives. Also known as true positive rate or recall"
[actual predicted positive-class]
(true-positive-rate actual predicted positive-class))
(defn recall
"returns sensitivity, defined as the count of correctly predicted positives divided by count of actual positives. Also known as true positive rate or sensitivity "
[actual predicted positive-class]
(true-positive-rate actual predicted positive-class))
(defn true-negatives
"returns the count of true positives, defined as count of predicted negative class and actual negative class"
[actual predicted positive-class]
(counts actual predicted (fn [[pred ac]] (and (not= pred positive-class)
(not= ac positive-class)))))
(defn true-negative-rate
"returns the true negative rate, defined as the count of correctly predicted negatives divided by count of actual negatives "
[actual predicted positive-class]
(counts actual predicted
(fn [[pred ac]] (and (not= pred positive-class)
(not= ac positive-class)))
(fn [[pred ac]] (not= ac positive-class))))
(defn specificity
"returns the specificity, also known as true negative rate, defined as the count of correctly predicted negatives divided by count of actual negatives "
[actual predicted positive-class]
(true-negative-rate actual predicted positive-class))
(defn false-positives
"returns the count of false positives, defined as the count of predicted positive class and actual negative class"
[actual predicted positive-class]
(counts actual predicted
(fn [[pred ac]] (and (= pred positive-class)
(not= ac positive-class)))))
(defn false-positive-rate
"returns the false positive rate, defined as count of actual positives predicted as a negative, divided by count of actual negatives.
Also known as fall-out."
[actual predicted positive-class]
(counts actual predicted
(fn [[pred ac]] (and (= pred positive-class) (not= ac positive-class)))
(fn [[pred ac]] (and (not= pred positive-class) (not= ac positive-class)))))
(defn false-negatives
"returns the count of false negatives, defined as the count of predicted negative class and actual positive class"
[actual predicted positive-class]
(counts actual predicted
(fn [[pred ac]] (and (not= pred positive-class)
(= ac positive-class)))))
(defn false-negative-rate
"returns the false negative rate, defined as count of actual positive and predicted negative, divided by count of actual positives"
[actual predicted positive-class]
(counts actual predicted
(fn [[pred ac]] (and (not= pred positive-class)
(= ac positive-class)))
(fn [[pred ac]] (= ac positive-class))))
(defn precision
"returns Precision, defined as the count of true positives over the count of true positives plus the count of false positives."
[actual predicted positive-class]
(counts actual predicted
(fn [[pred ac]] (= ac pred positive-class))
(fn [[pred ac]] (= pred positive-class))))
(defn recall
"Returns the recall"
[actual predicted positive-class]
(true-positive-rate actual predicted positive-class))
(defn f1-score
"returns the F1 score, defined as the harmonic mean of precision and recall."
[actual predicted positive-class]
(let [prec (precision actual predicted positive-class)
recall (recall actual predicted positive-class)]
(* 2 (/ (* prec recall) (+ prec recall)))))
(defn misclassification-rate
"returns the misclassification rate, defined as (1 - accuracy) "
[actual predicted]
(- 1 (accuracy actual predicted)))
(defn mcc
"returns the Matthews Correlation Coefficient"
[actual predicted positive-class]
(let [
tp (true-positives actual predicted positive-class)
tn (true-negatives actual predicted positive-class)
fp (false-positives actual predicted positive-class)
fn_ (false-negatives actual predicted positive-class)
cov-x-y (- (* tp tn) (* fp fn_))
cov-x-x (Math/sqrt (* (+ tp fp) (+ tp fn_) (+ tn fp ) (+ tn fn_)))
]
(if (= cov-x-x 0.0)
0.0
(/ cov-x-y cov-x-x))))
(defn- conf-mat
[freq classes]
(let [mapkeys (vec (for [i classes j classes] [i j]))]
(merge-with + freq (zipmap mapkeys (repeat 0)))))
(defn confusion-matrix
"returns a map representing the confusion matrix. The keys are a vector with [predicted, actual] and the values are the counts."
(
[actual predicted]
(let [freq (frequencies (mapv vector predicted actual ) )
classes (sort (set (mapv second (keys freq))))]
(conf-mat freq classes)))
([actual predicted classes]
(let [freq (frequencies (mapv vector predicted actual ))]
(conf-mat freq classes))))
(defn confusion-matrix-str
"returns a string representation given a confusion matrix as a map argument"
[conf-mat]
(let [classes (sort (set (mapv second (keys conf-mat))))
nc (count classes)
order (partition nc nc (for [i classes j classes] [j i]))]
(cd/dataset (into ["-"] classes)
(mapv #(into [%2] (mapv (fn [i] (get conf-mat i 0)) %1)) order classes))))
| |
0db98d56bc8ccfe28fa0ed54aaa46d54282070e69d7ef64eb365903775c93e4e | wies/grasshopper | symbExec.ml | * { 5 Symbolic execution based verifier }
open Util
open Grass
open GrassUtil
open Prog
open Printf
let simplify proc prog =
prog |>
dump_if 0 |>
Analyzer.infer_accesses true |>
Simplifier.elim_loops |>
Simplifier.elim_global_deps |>
dump_if 1
exception NotYetImplemented
let todo () = raise NotYetImplemented
exception SymbExecFail of string
let raise_err str = raise (SymbExecFail str)
let lineSep = "\n--------------------\n"
let fresh_array_length () = mk_free_const Int (fresh_ident "array_length")
let fresh_array_map srt = mk_free_const (Map ([Int], srt)) (fresh_ident "array_map")
TODO use consts instead ? And use idents instead of terms in spatial_pred
let fresh_const srt = mk_var srt (fresh_ident "v")
(** ----------- Symbolic state and manipulators ---------- *)
type spatial_pred =
| PointsTo of term * (ident * term) list (** x |-> [f1: E1, ..] *)
| Pred of ident * term list
| Arr of term * term * term (** Array(address, length, map) *)
| Conj of spatial_pred list list (** Conjunction of spatial states *)
* A symbolic state is a ( pure formula , a list of spatial predicates ) .
Note : program vars are represented as FreeSymb constants ,
existential vars are represented as Var variables .
Note: program vars are represented as FreeSymb constants,
existential vars are represented as Var variables.
*)
type state = {
pure: form;
spatial: spatial_pred list
}
let mk_pure_state p = { pure = p; spatial = [] }
let mk_spatial_state sp = { pure = mk_true; spatial = sp }
let empty_state = { pure = mk_true; spatial = [] }
let map_state_pure fn state =
{ state with pure = fn state.pure }
let map_state_spatial fn state =
{ state with spatial = fn state.spatial }
let map_state pfn sfn state =
{ pure = pfn state.pure; spatial = sfn state.spatial }
let strengthen_pure_state fs state =
map_state_pure (fun pure -> smk_and (pure :: fs)) state
* Conjoin two states
let add_state s1 s2 =
{ pure = smk_and [s1.pure; s2.pure];
spatial = s1.spatial @ s2.spatial
}
* Equalities derived so far in the symbolic execution , as a map : ident - > term ,
kept so that they can be substituted into the command and the post .
Invariant : if map is { x1 : E1 , ... } then xi are distinct and xi is not in Ej for i ! = ASSUMES : vars and constants do not share names !
TODO : can we make it ident IdMap.t now ?
kept so that they can be substituted into the command and the post.
Invariant: if map is {x1: E1, ...} then xi are distinct and xi is not in Ej for i != j.
ASSUMES: vars and constants do not share names!
TODO: can we make it ident IdMap.t now?
*)
type equalities = term IdMap.t
(** The state of the symbolic execution engine *)
type symb_exec_state = {
se_state: state;
se_prog: program;
se_proc: proc_decl;
se_fields: IdSet.t;
se_eqs: equalities;
}
let empty_eqs = IdMap.empty
let update_se_state st state = { st with se_state = state }
(* TODO use Format formatters for these *)
let rec string_of_spatial_pred = function
| PointsTo (x, fs) ->
sprintf "%s |-> (%s)" (string_of_term x)
(fs |> List.map (fun (id, t) -> (string_of_ident id) ^ ": " ^ (string_of_term t))
|> String.concat ", ")
| Pred (id, ts) ->
sprintf "%s(%s)" (string_of_ident id)
(ts |> List.map string_of_term |> String.concat ", ")
| Arr (x, l, m) ->
sprintf "arr(%s, %s, %s)" (string_of_term x) (string_of_term l) (string_of_term m)
| Conj fss ->
List.map (function
| [p] -> string_of_spatial_pred p
| ps -> "(" ^ string_of_spatial_pred_list ps ^ ")"
) fss
|> String.concat " && "
and string_of_spatial_pred_list sps =
sps |> List.map string_of_spatial_pred |> String.concat " * "
let string_of_state (s: state) =
let spatial =
match s.spatial with
| [] -> "emp"
| spatial -> string_of_spatial_pred_list spatial
in
let pure = s.pure
|> filter_annotations (fun _ -> false)
|> string_of_form
(* |> String.map (function | '\n' -> ' ' | c -> c) *)
in
sprintf "Pure: %s\nSpatial: %s" pure spatial
let string_of_equalities eqs =
IdMap.bindings eqs
|> List.map (fun (x, t) -> (string_of_ident x) ^ " = " ^ (string_of_term t))
|> String.concat ", "
|> sprintf "{%s}"
let string_of_se_state st =
sprintf "Eqs: %s\n%s" (string_of_equalities st.se_eqs) (string_of_state st.se_state)
* Finds a points - to predicate at location [ loc ] in [ spatial ] , including in dirty regions .
If found , returns [ ( Some fs , repl_fn_rd , repl_fn_wr ) ] such that
[ loc ] |- > [ fs ] appears in [ spatial ]
[ repl_fn_rd fs ' ] returns [ spatial ] with [ fs ] replaced by [ fs ' ]
and [ repl_fn_wr fs ' ] returns [ spatial ] with [ fs ] replaced by [ fs ' ] ,
but if [ fs ] appears in a , then it drops all other conjuncts
If found, returns [(Some fs, repl_fn_rd, repl_fn_wr)] such that
[loc] |-> [fs] appears in [spatial]
[repl_fn_rd fs'] returns [spatial] with [fs] replaced by [fs']
and [repl_fn_wr fs'] returns [spatial] with [fs] replaced by [fs'],
but if [fs] appears in a Conj, then it drops all other conjuncts *)
let rec find_ptsto loc spatial =
match spatial with
| [] ->
let repl_fn = (fun fs' -> spatial) in
None, repl_fn, repl_fn
| PointsTo (x, fs) :: spatial' when x = loc ->
let repl_fn = (fun fs' -> PointsTo (x, fs') :: spatial') in
Some fs, repl_fn, repl_fn
| Conj spss as sp :: spatial' ->
let rec find_conj spss1 = function
| sps :: spss2 ->
(match find_ptsto loc sps with
| Some fs, repl_fn_rd, repl_fn_wr ->
let repl_fn_rd = (fun fs' -> Conj (repl_fn_rd fs' :: spss1 @ spss2) :: spatial') in
let repl_fn_wr = (fun fs' -> repl_fn_wr fs' @ spatial') in
Some fs, repl_fn_rd, repl_fn_wr
| None, _, _ ->
find_conj (sps :: spss1) spss2)
| [] -> todo ()
in
(match find_conj [] spss with
| Some _, _, _ as res -> res
| None, _, _ ->
let res, repl_fn_rd, repl_fn_wr = find_ptsto loc spatial' in
res, (fun fs' -> sp :: repl_fn_rd fs'), (fun fs' -> sp :: repl_fn_wr fs')
)
| sp :: spatial' ->
let res, repl_fn_rd, repl_fn_wr = find_ptsto loc spatial' in
res, (fun fs' -> sp :: repl_fn_rd fs'), (fun fs' -> sp :: repl_fn_wr fs')
* Finds an array predicate at location [ loc ] in [ spatial ] , including in dirty regions .
If found , returns [ ( Some m , repl_fn_wr ) ] such that
[ arr(loc , _ , m ) ] appears in [ spatial ]
and [ repl_fn_wr m ' ] returns [ spatial ] with [ m ] replaced by [ m ' ] ,
but if [ loc ] appears in a , then it drops all other conjuncts
If found, returns [(Some m, repl_fn_wr)] such that
[arr(loc, _, m)] appears in [spatial]
and [repl_fn_wr m'] returns [spatial] with [m] replaced by [m'],
but if [loc] appears in a Conj, then it drops all other conjuncts *)
let rec find_array loc spatial =
match spatial with
| [] ->
let repl_fn = (fun fs' -> spatial) in
None, repl_fn
| Arr (x, l, m) :: spatial' when x = loc ->
let repl_fn = (fun m' -> Arr(x, l, m') :: spatial') in
Some (l, m), repl_fn
| Conj spss as sp :: spatial' ->
let rec find_conj spss1 = function
| sps :: spss2 ->
(match find_array loc sps with
| Some lm, repl_fn_wr ->
let repl_fn_wr = (fun fs' -> repl_fn_wr fs' @ spatial') in
Some lm, repl_fn_wr
| None, _ ->
find_conj (sps :: spss1) spss2)
| [] -> todo ()
in
(match find_conj [] spss with
| Some _, _ as res -> res
| None, _ ->
let res, repl_fn_wr = find_array loc spatial' in
res, (fun fs' -> sp :: repl_fn_wr fs')
)
| sp :: spatial' ->
let res, repl_fn_wr = find_array loc spatial' in
res, (fun fs' -> sp :: repl_fn_wr fs')
Special find_ptsto for extracting and removing a PointsTo from spatial '
let find_ptsto_spatial' x =
find_map_res (function PointsTo(x', fs') when x = x' -> Some fs' | _ -> None)
(* Special find_ptsto for extracting and removing an Arr from spatial' *)
let find_arr_spatial' x =
find_map_res (function Arr(x', l, m) when x = x' -> Some (l, m) | _ -> None)
* Evaluate term at [ state ] by looking up all field reads .
[ old_state ] is the state with which to evaluate old(x ) terms .
[ spatial ' ] is the list of spatial needed to evaluate everything in [ t ] .
[old_state] is the state with which to evaluate old(x) terms.
[spatial'] is the list of spatial preds needed to evaluate everything in [t]. *)
let rec eval_term fields (old_state, (state: state), spatial') = function
| Var _ as t -> t, (old_state, state, spatial')
| App (Read, [App (FreeSym fld, [], _); loc], srt)
when IdSet.mem fld fields -> (* Field reads *)
let loc, (old_state, state, spatial') = eval_term fields (old_state, state, spatial') loc in
(match find_ptsto loc state.spatial with
| Some fs, mk_spatial, _ ->
(* lookup fld in fs, so that loc |-> fs' and (fld, e) is in fs' *)
let e, fs' =
try List.assoc fld fs, fs
with Not_found ->
let e = fresh_const srt in e, (fld, e) :: fs
in
let state' = map_state_spatial (fun _ -> mk_spatial fs') state in
e, (old_state, state', spatial')
| None, _, _ ->
(match find_ptsto_spatial' loc spatial' with
| Some (fs, spatial') ->
(* lookup fld in fs, so that loc |-> fs' and (fld, e) is in fs' *)
let e, fs' =
try List.assoc fld fs, fs
with Not_found ->
let e = fresh_const srt in e, (fld, e) :: fs
in
e, (old_state, state, PointsTo (loc, fs') :: spatial')
| None -> (* Add loc to spatial' to indicate we need an acc(loc) in the future *)
let e = fresh_const srt in
e, (old_state, state, PointsTo (loc, [fld, e]) :: spatial')))
| App (Read, [a; idx], srt)
when sort_of a = Loc (Array srt) ->
(* Array reads *)
let a, (old_state, state, spatial') = eval_term fields (old_state, state, spatial') a in
let idx, (old_state, state, spatial') = eval_term fields (old_state, state, spatial') idx in
let m, spatial' =
(match find_array a state.spatial with
| Some (_, m), _ -> m, spatial'
| None, _ -> (* If you can't find a in spatial, look in/add it to spatial' *)
(match find_arr_spatial' a spatial' with
| Some ((l, m), spatial') ->
m, Arr (a, l, m) :: spatial'
| None ->
let l = fresh_array_length () in
let m = fresh_array_map srt in
m, Arr (a, l, m) :: spatial'))
in
mk_read m [idx], (old_state, state, spatial')
| App (Length, [a], _) ->
let a, (old_state, state, spatial') = eval_term fields (old_state, state, spatial') a in
let l, spatial' =
(match find_array a state.spatial with
| Some (l, _), _ -> l, spatial'
| None, _ -> (* If you can't find a in spatial, look in/add it to spatial' *)
(match find_arr_spatial' a spatial' with
| Some ((l, m), spatial') ->
l, Arr (a, l, m) :: spatial'
| None ->
let l = fresh_array_length () in
let srt = match (sort_of a) with | Loc Array s -> s | _ -> assert false in
let m = fresh_array_map srt in
l, Arr (a, l, m) :: spatial'))
in
l, (old_state, state, spatial')
| App (ArrayMap, [a], _) ->
let a, (old_state, state, spatial') = eval_term fields (old_state, state, spatial') a in
let m, spatial' =
(match find_array a state.spatial with
| Some (_, m), _ -> m, spatial'
| None, _ -> (* If you can't find a in spatial, look in/add it to spatial' *)
(match find_arr_spatial' a spatial' with
| Some ((l, m), spatial') ->
m, Arr (a, l, m) :: spatial'
| None ->
let l = fresh_array_length () in
let srt = match (sort_of a) with | Loc Array s -> s | _ -> assert false in
let m = fresh_array_map srt in
m, Arr (a, l, m) :: spatial'))
in
m, (old_state, state, spatial')
| App (Old, [t], srt) as t' ->
(* Eval t using old_state as state *)
(match old_state with
| Some old_state ->
let t, (_, old_state, spatial') = eval_term fields (None, old_state, spatial') t in
t, (Some old_state, state, spatial')
| None -> raise_err @@ "Unexpected old term: " ^ (string_of_term t'))
| App (s, ts, srt) ->
let ts, (old_state, state, spatial') = fold_left_map (eval_term fields) (old_state, state, spatial') ts in
App (s, ts, srt), (old_state, state, spatial')
let eval_term_no_olds fields state term =
match eval_term fields (None, state, []) term with
| term, (_, state, []) -> term, state
| _, (_, _, x :: _) ->
raise_err @@ "Possible invalid heap lookup. Couldn't find: " ^ (string_of_spatial_pred x)
(** Convert a specification into a symbolic state.
This also moves field read terms from pure formula to points-to predicates.
Assumes [fields] is a set of field identifiers, all other maps are treated as
functions.
*)
let state_of_spec_list fields old_state specs : state * state =
let eval_term = eval_term fields in
let add (pure, spatial) = add_state { pure = pure; spatial = spatial } in
(* [spatial'] is a list of outstanding spatial_preds needed to eval [state] *)
let convert_form (old_state, state, spatial') f =
let f, (old_state, (state: state), spatial') =
fold_map_terms eval_term (old_state, state, spatial') f
in
(old_state, add (f, []) state, spatial')
in
let rec convert_sl_form (old_state, (state: state), spatial') f =
let fail () = failwith @@ "Unsupported formula " ^ (Sl.string_of_form f) in
match f with
| Sl.Pure (f, _) -> convert_form (old_state, state, spatial') f
| Sl.Atom (Sl.Emp, ts, _) -> old_state, state, spatial'
| Sl.Atom (Sl.Region, [(App (SetEnum, [x], Set Loc Array srt))], _) -> (* arr(x) *)
let x, (old_state, state, spatial') = eval_term (old_state, state, spatial') x in
First check if we 've already created it in spatial '
let l, m, spatial' =
(match find_arr_spatial' x spatial' with
| Some ((l, m), spatial') ->
l, m, spatial'
| None ->
let l = fresh_array_length () in
let m = fresh_array_map srt in
l, m, spatial')
in
let len_axiom = mk_leq (mk_int 0) l in
old_state, add (len_axiom, [Arr (x, l, m)]) state, spatial'
| Sl.Atom (Sl.Region, [(App (SetEnum, [x], Set Loc _))], _) -> (* acc(x) *)
let x, (old_state, state, spatial') = eval_term (old_state, state, spatial') x in
First check if we 've already created it in spatial '
let sp, spatial' =
(match find_ptsto_spatial' x spatial' with
| Some (fs, spatial') -> PointsTo (x, fs), spatial'
| None -> PointsTo (x, []), spatial')
in
old_state, add (mk_true, [sp]) state, spatial'
| Sl.Atom (Sl.Region, ts, _) -> fail ()
| Sl.Atom (Sl.Pred p, ts, _) ->
old_state, add (mk_true, [Pred (p, ts)]) state, spatial'
| Sl.SepOp (Sl.SepStar, f1, f2, _) ->
List.fold_left convert_sl_form (old_state, state, spatial') [f1; f2]
| Sl.SepOp (Sl.SepIncl, _, _, _) -> fail ()
| Sl.SepOp (Sl.SepPlus, _, _, _) -> fail ()
| Sl.BoolOp (And, fs, _) ->
let old_state, conj_states, spatial' =
List.fold_left (fun (old_state, conj_states, spatial') f ->
let old_state, state', spatial' =
convert_sl_form (old_state, empty_state, spatial') f
in
old_state, state' :: conj_states, spatial')
(old_state, [], spatial') fs
in
let pures, spatials =
conj_states |>
List.map (function {pure = p; spatial = s; _ } -> (p, s)) |>
List.split
in
let spatials = List.filter (function [] -> false | _ -> true) spatials in
(match spatials with
| [] -> old_state, add (smk_and pures, []) state, spatial'
| [sp] -> old_state, add (smk_and pures, sp) state, spatial'
| _ -> old_state, add (smk_and pures, [Conj spatials]) state, spatial')
| Sl.BoolOp _ -> fail ()
| Sl.Binder (b, vs, f, _) ->
let old_state, state1, spatial' =
convert_sl_form (old_state, mk_spatial_state state.spatial, spatial') f
in
if state1.spatial = state.spatial then
old_state, add (smk_binder b vs state1.pure, []) state, spatial'
else
failwith @@ "Confused by spatial under binder: " ^ (Sl.string_of_form f)
in
(* Convert all the specs into a state *)
let (old_state, state, spatial') =
List.fold_left (fun (old_state, state, spatial') spec ->
let f =
match spec.spec_form with
| SL f -> f
| FOL f -> Sl.Pure (f, None)
in
convert_sl_form (old_state, state, spatial') f
) (old_state, empty_state, []) specs
in
(* Make sure there's nothing left in spatial' *)
(match spatial' with
| [] -> ()
| (PointsTo(x, _) | Arr (x, _, _)) :: _ ->
raise_err @@ "Possible invalid heap lookup to address: " ^ (string_of_term x)
| _ -> todo ());
Opt.get_or_else empty_state old_state, state
(** Substitute both vars and constants in a term according to [sm]. *)
let subst_term sm = subst_consts_term sm >> subst_term sm
(** Substitute both vars and constants in a form according to [sm]. *)
let subst_form sm = subst_consts sm >> subst sm
let rec subst_spatial_pred sm = function
| PointsTo (id, fs) ->
PointsTo (subst_term sm id, List.map (fun (id, t) -> id, subst_term sm t) fs)
| Pred (id, ts) ->
Pred (id, List.map (subst_term sm) ts)
| Arr (x, l, m) ->
Arr (subst_term sm x, subst_term sm l, subst_term sm m)
| Conj spss ->
Conj (List.map (List.map (subst_spatial_pred sm)) spss)
* Substitute all ( Vars and constants ) in derived equalities [ eqs ] ,
according to substitution [ sm ]
TODO check this preserves equalities invariant !
according to substitution [sm]
TODO check this preserves equalities invariant! *)
let subst_eqs sm eqs =
eqs |> IdMap.bindings
|> List.fold_left (fun eqs (id, t) ->
let t' = subst_term sm t in
match IdMap.find_opt id sm with
| Some (Var (id', _))
| Some (App (FreeSym id', _, _)) -> IdMap.add id' t' eqs
| None -> IdMap.add id t' eqs
| _ -> failwith "huh?"
) IdMap.empty
(** Substitute all variables and constants in state [(pure, spatial)] with terms
according to substitution map [sm]. *)
let subst_state sm {pure = pure; spatial = spatial; _} : state =
{ pure = subst_form sm pure;
spatial = List.map (subst_spatial_pred sm) spatial }
(** Substitute all variables and constants in state [st] with terms
according to substitution map [sm]. *)
let subst_se_state sm st =
{st with se_eqs = subst_eqs sm st.se_eqs; se_state = subst_state sm st.se_state}
* Given two lists of idents and terms , create an equalities / subst map out of them .
let mk_eqs ids terms =
List.fold_left2 (fun eqs id t -> IdMap.add id t eqs) empty_eqs ids terms
* Add [ i d ] = [ t ] to equalities [ eqs ] while preserving invariant .
let add_eq id t eqs =
(* Apply current substitutions to t *)
let t = subst_term eqs t in
(* Make sure things are not added twice *)
if IdMap.mem id eqs then
failwith @@ sprintf "Tried to add %s twice to eqs %s"
(string_of_ident id) (string_of_equalities eqs)
else
let eqs = subst_eqs (IdMap.singleton id t) eqs in
IdMap.add id t eqs
(** ----------- Re-arrangement and normalization rules ---------- *)
* Normalize a by some kind of sorting
let sort_conj = function
| Conj spss ->
Conj (spss |> List.map (List.stable_sort compare) |> List.stable_sort compare)
| sp -> sp
* Find equalities of the form const = = const in [ state ] and add to [ eqs ]
let find_equalities eqs state =
let rec find_eq sm = function
| Atom (App (Eq, [(App (FreeSym id, [], _)); App (FreeSym _, [], _) as t2], _), _) ->
add_eq id t2 sm
| BoolOp (And, fs) ->
List.fold_left find_eq sm fs
| Binder (_, [], f, _) -> find_eq sm f
| _ -> sm
in
find_eq eqs state.pure
(** Find equalities of the form var == exp in [pure] and return id -> exp map. *)
let find_var_equalities (pure: form) =
let rec find_eq sm = function
| Atom (App (Eq, [Var (id, _); Var _ as t2], _), _)
| Atom (App (Eq, [Var (id, _); App (FreeSym _, [], _) as t2], _), _)
| Atom (App (Eq, [App (FreeSym _, [], _) as t2; Var (id, _)], _), _) ->
if IdMap.mem id sm then sm (* TODO you really need to fix this.. *)
else add_eq id t2 sm
| BoolOp (And, fs) ->
List.fold_left find_eq sm fs
| Binder (_, [], f, _) -> find_eq sm f
| _ -> sm
in
find_eq IdMap.empty pure
let rec remove_trivial_equalities = function
| Atom (App (Eq, [t1; t2], _), _) as f -> if t1 = t2 then mk_true else f
| BoolOp (op, fs) -> smk_op op (List.map remove_trivial_equalities fs)
| Binder (b, vs, f, anns) -> Binder (b, vs, remove_trivial_equalities f, anns)
| f -> f
let apply_equalities eqs state =
state |>
subst_state eqs |>
map_state_pure remove_trivial_equalities
let remove_useless_existentials state : state =
(* Note: can also use GrassUtil.foralls_to_exists for this *)
apply_equalities (find_var_equalities state.pure) state
(** Kill useless existential vars in state [st], find equalities between constants,
add to [st.se_eqs] and simplify. *)
let simplify_state st =
let state =
st.se_state |>
map_state_pure nnf |>
remove_useless_existentials
in
let eqs = find_equalities st.se_eqs state in
{st with se_eqs = eqs; se_state = apply_equalities eqs state}
(** Add implicit disequalities from spatial to pure. Assumes normalized by eq. *)
let add_neq_constraints st =
let rec f acc locs = function
| PointsTo (x, _) :: sps | Arr (x, _, _) :: sps ->
let acc1 = TermSet.fold (fun y acc ->
if sort_of x = sort_of y then mk_neq x y :: acc else acc)
locs acc
in
f acc1 (TermSet.add x locs) sps
| Pred _ :: sps ->
f acc locs sps
| Conj spss :: sps ->
let acc, locs =
List.fold_left (fun (acc, locs') sps ->
let acc, locs1 = f acc locs sps in
acc, TermSet.union locs' locs1)
(acc, locs) spss
in
f acc locs sps
| [] -> acc, locs
in
let { pure = pure; spatial = spatial; _ } = st.se_state in
let neqs, locs = f [] TermSet.empty spatial in
(* Also add x != nil for every location x *)
let get_sort x = match sort_of x with
| Loc s -> s
| s ->
failwith @@ sprintf "Spatial location %s has non Loc sort %s"
(string_of_term x) (string_of_sort s)
in
let neqs =
TermSet.fold (fun x acc -> mk_neq x (mk_null (get_sort x)) :: acc) locs neqs
in
let new_se_state = strengthen_pure_state neqs st.se_state in
update_se_state st new_se_state
(** ----------- Symbolic Execution ---------- *)
(* Returns None if the entailment holds, otherwise Some (list of error messages, model) *)
let check_pure_entail st p1 p2 =
let { pure = p2; _ } = apply_equalities st.se_eqs (mk_pure_state p2) in
if p1 = p2 || p2 = mk_true then None
Dump it to an SMT solver
let axioms = (* Collect all program axioms *)
Util.flat_map
(fun sf ->
let name =
Printf.sprintf "%s_%d_%d"
sf.spec_name sf.spec_pos.sp_start_line sf.spec_pos.sp_start_col
in
match sf.spec_form with FOL f -> [mk_name name f] | SL _ -> [])
st.se_prog.prog_axioms
Apply equalities in eqs
in
let p2 = Verifier.annotate_aux_msg "Related location" p2 in
(* Close the formulas: assuming all free variables are existential *)
let close f = smk_exists (IdSrtSet.elements (sorted_free_vars f)) f in
let labels, f =
smk_and [p1; mk_not p2] |> close |> nnf |> Verifier.finalize_form st.se_prog
(* Add definitions of all referenced predicates and functions *)
|> fun f -> f :: Verifier.pred_axioms st.se_prog
(* Add axioms *)
|> (fun fs -> smk_and (fs @ axioms))
(* Add labels *)
|> Verifier.add_labels
in
let name = fresh_ident "form" |> string_of_ident in
Debug.debug (fun () ->
sprintf "\n\nCalling prover with name %s\n" name);
match Prover.get_model ~session_name:name f with
| None -> None
| Some model -> Some (Verifier.get_err_msg_from_labels model labels, model)
* Returns ( fr , inst ) s.t . state1 |= state2 * fr , and
inst accumulates an instantiation for existential variables in state2 .
Assumes that both states have been normalized w.r.t eqs and inst .
inst accumulates an instantiation for existential variables in state2.
Assumes that both states have been normalized w.r.t eqs and inst. *)
let rec find_frame st ?(inst=empty_eqs) state1 state2 =
Debug.debugl 1 (fun () ->
sprintf "\nFinding frame with %s for:\n%s\n|=\n%s &*& ??\n"
(string_of_equalities inst)
(string_of_spatial_pred_list state1.spatial) (string_of_spatial_pred_list state2.spatial)
);
let match_up_sp inst sp2 sp1 =
match sp2, sp1 with
| sp2, sp1 when (sort_conj sp2) = (sort_conj sp1) ->
match equal elements ( for , do some normalization )
Some inst
| PointsTo (x, fs2), PointsTo (x', fs1) when x = x' ->
let match_up_fields inst fs1 fs2 =
let fs1, fs2 = List.sort compare fs1, List.sort compare fs2 in
let rec match_up inst = function
| (_, []) -> Some inst
| (fe1 :: fs1', fe2 :: fs2') when fe1 = fe2 -> (* Remove equal stuff *)
match_up inst (fs1', fs2')
| ((f1, e1) :: fs1', (f2, e2) :: fs2') when f1 = f2 ->
(* e1 != e2, so only okay if e2 is ex. var *)
(* add e2 -> e1 to inst and sub in fs2' to make sure e2 has uniform value *)
(match e2 with
| Var (e2_id, _) ->
let sm = IdMap.singleton e2_id e1 in
let fs2' = List.map (fun (f, e) -> (f, subst_term sm e)) fs2' in
assert (IdMap.mem e2_id inst |> not);
match_up (IdMap.add e2_id e1 inst) (fs1', fs2')
| App (FreeSym e2_id, [], _) ->
print_endline @@ ":: " ^ (string_of_term e1) ^ " " ^ (string_of_term e2);
failwith "TODO"
| _ -> None)
| ((f1, e1) :: fs1', (f2, e2) :: fs2')
when compare (f1, e1) (f2, e2) < 0 ->
RHS does n't need to have all fields , so drop ( f1 , e1 )
match_up inst (fs1', (f2, e2) :: fs2')
| (fs1, (f2, e2)::fs2') ->
f2 not in LHS , so only okay if e2 is an ex . var
(match e2 with
| Var (e, s) ->
(* So create new const c, add e -> c to inst, and sub fs2' with inst *)
let c = fresh_const s in
let fs2' = fs2' |>
List.map (fun (f, t) -> (f, subst_term (IdMap.singleton e c) t))
in
match_up (IdMap.add e c inst) (fs1, fs2')
| _ -> None)
in
match_up inst (fs1, fs2)
in
match_up_fields inst fs1 fs2
| Arr (x2, l2, m2), Arr (x1, l1, m1) when x1 = x2 ->
(match l2, m2 with
| App (FreeSym l2_id, [], _), App (FreeSym m2_id, [], _)
| Var (l2_id, _), Var (m2_id, _) ->
let inst = inst |> IdMap.add l2_id l1 |> IdMap.add m2_id m1 in
Some inst
| _ -> None)
| Conj spss2, Conj spss1 ->
let match_up_conjunct inst sps2 sps1 =
(match check_entailment st ~inst:inst (mk_spatial_state sps1) (mk_spatial_state sps2) with
| Ok inst -> Some inst
| Error _ -> None)
in
let match_up_conj inst spss2 spss1 =
List.fold_left (fun acc sps2 ->
match acc with
| Some (inst, spss1) ->
find_map_res (match_up_conjunct inst sps2) spss1
| None -> None)
(Some (inst, spss1)) spss2
in
(match match_up_conj inst spss2 spss1 with
Only allow when spss1 and spss2 are same len . TODO ? ! ? !
| _ -> None)
| _ -> None
in
Sort sps2 so that acc(v)/arr(v ) where v is a var ( i.e. like x.next ) are in the end
let sps2 =
state2.spatial |> List.partition
(function PointsTo (Var _, _) | Arr (Var _, _, _) -> false | _ -> true)
|> (fun (x, y) -> x @ y)
in
match sps2 with
| [] ->
let st = {st with se_eqs = IdMap.union (fun _ -> failwith "") st.se_eqs inst} in
(* Check if p2 is implied by p1 *)
(match check_pure_entail st state1.pure state2.pure with
| None ->
Ok (state1.spatial, inst)
| Some errs -> Error errs)
| sp2 :: sps2' ->
(match find_map_res (match_up_sp inst sp2) state1.spatial with
| Some (inst, sps1') ->
let state1' = { state1 with spatial = sps1' } in
let state2' = subst_state inst { state2 with spatial = sps2' } in
find_frame st ~inst:inst state1' state2'
TODO get errors ?
(** Returns [Ok inst] if [state1] |= [state2], else [Error (error messages)]. *)
and check_entailment st ?(inst=empty_eqs) state1 state2 =
let st1 = simplify_state { st with se_state = state1 } in
let eqs, state1 = st1.se_eqs, st1.se_state in
let state2 =
state2 |>
apply_equalities eqs |>
apply_equalities inst |>
remove_useless_existentials
in
Debug.debug (fun () ->
sprintf "\nChecking entailment:\n%s\n|=\n%s\n"
(string_of_se_state st1) (string_of_state state2)
);
(* Check if find_frame returns empt *)
match find_frame st ~inst:inst state1 state2 with
| Ok ([], inst) -> Ok inst
| Ok _ ->
Error (["The frame was not empty for this entailment check"], Model.empty)
| Error errs -> Error errs
* Finds a call site for a function that 's completely contained inside a conjunct .
If found , [ find_frame_conj p e state1 state2 ] returns a function [ repl_fn ] s.t .
[ repl_fn sm state2 ' ] is the result of replacing [ state2 ] inside [ state1 ] with [ state2 ' ] ,
and applying the substitution map [ sm ] on the remaining parts of [ state1 ] .
If found, [find_frame_conj p e state1 state2] returns a function [repl_fn] s.t.
[repl_fn sm state2'] is the result of replacing [state2] inside [state1] with [state2'],
and applying the substitution map [sm] on the remaining parts of [state1].
*)
let find_frame_conj st state1 state2 =
let rec find_frame_inside_conj = function
| [] -> Error ([], Model.empty)
| sps :: spss ->
(match find_frame st { state1 with spatial = sps } state2 with
| Ok (frame, inst) ->
let repl_fn = (fun sm foo_post ->
let frame = List.map (subst_spatial_pred sm) frame in
let spss = List.map (List.map (subst_spatial_pred sm)) spss in
(foo_post @ frame) :: spss)
in
Ok (repl_fn, inst)
| Error errs1 ->
(match find_frame_inside_conj spss with
| Ok (repl_fn, inst) ->
let repl_fn = (fun sm foo_post ->
let sps = List.map (subst_spatial_pred sm) sps in
sps :: (repl_fn sm foo_post))
in
Ok (repl_fn, inst)
| Error ([], _) -> Error errs1
| Error errs -> Error errs))
in
let rec find_frame_conj = function
| [] -> Error ([], Model.empty)
| Conj spss :: spatial' ->
(match find_frame_inside_conj spss with
| Ok (repl_fn, inst) ->
let repl_fn = (fun sm foo_post ->
Conj (repl_fn sm foo_post) :: (List.map (subst_spatial_pred sm) spatial'))
in
Ok (repl_fn, inst)
| Error errs ->
(match find_frame_conj spatial' with
| Ok (repl_fn, inst) ->
let repl_fn =
(fun sm foo_post ->
let spss = List.map (List.map (subst_spatial_pred sm)) spss in
Conj spss :: (repl_fn sm foo_post))
in
Ok (repl_fn, inst)
| Error ([], _) -> Error errs
| Error errs -> Error errs))
| sp :: spatial' ->
(match find_frame_conj spatial' with
| Ok (repl_fn, inst) ->
let repl_fn =
(fun sm foo_post -> (subst_spatial_pred sm sp) :: (repl_fn sm foo_post))
in
Ok (repl_fn, inst)
| Error errs -> Error errs)
in
find_frame_conj state1.spatial
* Finds a call site for a function that 's completely contained inside a dirty
region .
[ state2 ] must have only PointsTo / Arr - no predicates allowed .
region.
[state2] must have only PointsTo/Arr - no predicates allowed.*)
let find_frame_dirty st state1 state2 =
let find_inside_dirty = function
| sp -> Error ([], Model.empty)
in
(* Cycle through sp1 looking for a dirty that works, keeping seen stuff in sp1a *)
let rec find_dirty sp1a = function
| sp :: sp1b ->
(match find_inside_dirty sp with
| Error ([], m) -> find_dirty (sp :: sp1a) sp1b
| Error (msgs, m) -> Error (msgs, m)
| Ok (rf, inst) -> assert false)
| [] -> Error ([], Model.empty)
in
match List.exists (function PointsTo _ | Arr _ -> false | _ -> true) state2.spatial with
| true -> Error ([], Model.empty) (* Only PointsTos allowed *)
| false -> find_dirty [] state1.spatial
(** Matches up arrays in pre and post of a function call and adds a pure formula to post
that enforces that the lengths are the same. *)
let force_array_lengths_equal pre post =
let length_axiom =
List.fold_left (fun acc -> function
| Arr (a, l, m) ->
let f =
match List.find_opt (function Arr (a', l', _) -> a = a' | _ -> false) pre.spatial with
| Some (Arr (_, l', _)) -> mk_eq l l'
| _ -> mk_true
in
f :: acc
| _ -> acc)
[] post.spatial
in
strengthen_pure_state length_axiom post
(** Check that we have permission to the array, and that index is in bounds *)
let check_array_acc st arr idx =
let state = st.se_state in
match find_array arr state.spatial with
| Some (l, _), _ ->
let idx_in_bds = smk_and [(mk_leq (mk_int 0) idx); (mk_lt idx l)] in
Debug.debug (fun () -> "\n\nChecking array index is in bounds:\n");
(match check_pure_entail st state.pure idx_in_bds with
| None -> ()
| Some errs -> raise_err "Possible array index out of bounds error")
| None, _ ->
raise_err "Possible invalid array read"
(** Check that all array read terms in [t] are safe on state [st] *)
let check_array_reads st t =
let rec check = function
| Var _ as t -> t
| App (Read, [a; idx], srt)
| App ( Read , [ f ; App ( Read , [ App ( ArrayCells , [ a ] , _ ) ; idx ] , _ ) ] , srt )
when sort_of a = Loc (Array srt) ->
(* Array reads *)
let a, _ = eval_term_no_olds st.se_fields st.se_state a in
let idx, _ = eval_term_no_olds st.se_fields st.se_state idx in
check_array_acc st a idx;
App (Read, [check a; check idx], srt)
| App (s, ts, srt) -> App (s, List.map check ts, srt)
in
check t
* Process term by substituting eqs , looking up field reads .
(* TODO: this is because assume/assert may have array reads under binders which have guards.
So for now we are not checking them. Better way to do this? *)
let process_no_array st t =
let t = subst_term st.se_eqs t in
let t, state = eval_term_no_olds st.se_fields st.se_state t in
t, {st with se_state = state}
* Process term by substituting eqs , looking up field reads , and checking array reads .
let process st t =
let t = t |> subst_term st.se_eqs |> check_array_reads st in
let t, state = eval_term_no_olds st.se_fields st.se_state t in
t, {st with se_state = state}
(** Symbolically execute commands [comms] on state [st] and check [postcond]. *)
let rec symb_exec st postcond comms =
(* Some helpers *)
let lookup_type id = (find_var st.se_prog st.se_proc id).var_sort in
let mk_var_like srt id =
let id' = fresh_ident (name id) in
mk_free_const srt id'
in
let mk_var_like_id id = mk_var_like (lookup_type id) id in
let mk_const_term id = mk_free_const (lookup_type id) id in
let mk_error msg errs model pos =
[(pos, String.concat "\n\n" (msg :: errs), model)]
in
let pos = match comms with
| Basic (_, pp) :: _ -> pp.pp_pos
| _ -> dummy_position
in
First , simplify_state the pre state
let st = simplify_state st in
(* If flag is set, check that current state isn't unsat *)
if !Config.check_unsat then begin
Debug.debug (fun () -> "Checking if current state is unsat:\n");
let st' = add_neq_constraints st in
try
(match find_frame st st'.se_state (mk_pure_state mk_false) with
| Ok _ ->
print_endline @@ (string_of_src_pos pos) ^ "\nWarning: Intermediate state was unsat"
| Error _ ->
Debug.debug (fun () -> "State is satisfiable.\n"))
with _ ->
print_endline @@ (string_of_src_pos pos) ^ "\nWarning: unsat check hit exception"
end;
let se = function
| [] ->
Debug.debug (fun () ->
sprintf "%sExecuting check postcondition: %s%sCurrent state:\n%s\n"
lineSep (string_of_state postcond)
lineSep (string_of_se_state st)
);
TODO do this better
let st = add_neq_constraints st in
First , check if current state is unsat
(try
(match find_frame st st.se_state (mk_pure_state mk_false) with
Unsat , so forget checking postcondition
[]
| Error _ ->
(match check_entailment st st.se_state postcond with
| Ok _ -> []
| Error (errs, m) ->
TODO to get line numbers , convert returns into asserts
mk_error "A postcondition may not hold" errs m dummy_position))
with _ ->
print_endline @@ (string_of_src_pos pos) ^ "\nWarning: unsat check hit exception";
(match check_entailment st st.se_state postcond with
| Ok _ -> []
| Error (errs, m) ->
TODO to get line numbers , convert returns into asserts
mk_error "A postcondition may not hold" errs m dummy_position))
| (Basic (Assign {assign_lhs=[_];
assign_rhs=[App (Write, [arr; idx; rhs], Loc (Array _))]}, pp) as comm) :: comms' ->
| ( Basic ( Assign { assign_lhs=[f ] ;
( Write , [ array_state ;
App ( Read , [ App ( ArrayCells , [ arr ] , _ ) ; idx ] , _ ) ; rhs ] , srt ) ] } , pp )
as comm ) : : comms '
when array_state = Grassifier.array_state true ( sort_of rhs )
|| array_state = Grassifier.array_state false ( sort_of rhs ) - >
assign_rhs=[App (Write, [array_state;
App (Read, [App (ArrayCells, [arr], _); idx], _); rhs], srt)]}, pp)
as comm) :: comms'
when array_state = Grassifier.array_state true (sort_of rhs)
|| array_state = Grassifier.array_state false (sort_of rhs) ->*)
Debug.debug (fun () ->
sprintf "%sExecuting array write: %d: %s%sCurrent state:\n%s\n"
lineSep (pp.pp_pos.sp_start_line) (string_of_format pr_cmd comm)
lineSep (string_of_se_state st)
);
let arr, st = process st arr in
let idx, st = process st idx in
let rhs, st = process st rhs in
(* Check that we have permission to the array, and that index is in bounds *)
check_array_acc st arr idx;
(* Find the map for arr and bump it up *)
(match find_array arr st.se_state.spatial with
| Some (_, (App (FreeSym m_id, [], _) as m)), mk_spatial' ->
let m' = mk_var_like (sort_of m) m_id in
let sm = IdMap.singleton m_id m' in
let idx, rhs = idx |> subst_term sm, rhs |> subst_term sm in
let st = subst_se_state sm st in
let pure = smk_and [mk_eq m (mk_write m' [idx] rhs); st.se_state.pure] in
let st' = update_se_state st { pure = pure; spatial = mk_spatial' m } in
symb_exec st' postcond comms'
| Some _, _ -> failwith "Array map was not a const term"
| None, _ ->
[(pp.pp_pos, "Possible invalid array write", Model.empty)])
| Basic (Assign {assign_lhs=[fld];
assign_rhs=[App (Write, [App (FreeSym fld', [], _);
loc; rhs], srt)]}, pp) as comm :: comms'
when fld = fld' && IdSet.mem fld st.se_fields ->
Debug.debug (fun () ->
sprintf "%sExecuting mutate: %d: %s%sCurrent state:\n%s\n"
lineSep (pp.pp_pos.sp_start_line) (string_of_format pr_cmd comm)
lineSep (string_of_se_state st)
);
First , process / check loc and rhs
let loc, st = process st loc in
let rhs, st = process st rhs in
(* Find the node to mutate *)
(match find_ptsto loc st.se_state.spatial with
| Some fs, _, mk_spatial' ->
(* mutate fs to fs' so that it contains (fld, rhs) *)
let fs' =
if List.exists (fst >> (=) fld) fs
then List.map (fun (f, e) -> (f, if f = fld then rhs else e)) fs
else (fld, rhs) :: fs
in
let st' = update_se_state st { pure = st.se_state.pure; spatial = mk_spatial' fs' } in
symb_exec st' postcond comms'
| None, _, _ ->
[(pp.pp_pos, "Possible invalid heap mutation", Model.empty)])
| Basic (Assign {assign_lhs=ids; assign_rhs=ts}, pp) as comm :: comms' ->
Debug.debug (fun () ->
sprintf "%sExecuting assignment: %d: %s%sCurrent state:\n%s\n"
lineSep (pp.pp_pos.sp_start_line) (string_of_format pr_cmd comm)
lineSep (string_of_se_state st)
);
TODO simultaneous assignments ca n't touch heap , so do all at once
let st =
List.combine ids ts
|> List.fold_left (fun st (id, rhs) ->
First , substitute / eval / check rhs
let rhs, st = process st rhs in
let sm = IdMap.singleton id (mk_var_like_id id) in
let rhs' = subst_term sm rhs in
let st = subst_se_state sm st in
let state' = add_state (mk_pure_state (mk_eq (mk_const_term id) rhs')) st.se_state in
update_se_state st state'
) st
in
symb_exec st postcond comms'
| Basic (Call {call_lhs=lhs; call_name=foo; call_args=args}, pp) as comm :: comms' ->
Debug.debug (fun () ->
sprintf "%sExecuting procedure call: %d: %s%sCurrent state:\n%s\n"
lineSep (pp.pp_pos.sp_start_line) (string_of_format pr_cmd comm)
lineSep (string_of_se_state st)
);
First , substitute eqs and eval args
let args, st = args |> fold_left_map process st in
Debug.debug (fun () -> sprintf "\nOn args: %s\n" (string_of_format pr_term_list args));
(* Look up pre/post of foo *)
let c = (find_proc st.se_prog foo).proc_contract in
let foo_pre, foo_post =
let _, pre = c.contr_precond |> state_of_spec_list st.se_fields None in
let pre, post = c.contr_postcond |> state_of_spec_list st.se_fields (Some pre) in
(* Since nothing can change array lengths, make them equal *)
let post = force_array_lengths_equal pre post in
remove_useless_existentials pre, remove_useless_existentials post
in
let foo_pre =
(* Substitute formal params -> actual params in foo_pre/post *)
foo_pre |> subst_state (mk_eqs c.contr_formals args)
in
Replace lhs vars with fresh vars . For every part of new state
let sm =
lhs |> List.fold_left (fun sm id ->
IdMap.add id (mk_var_like_id id) sm)
IdMap.empty
in
Substitute formal params - > actual params & return vars - > lhs vars in foo_post
let foo_post =
(* args will be part of foo_post, so substitute here too *)
let args = List.map (subst_term sm) args in
let sm = mk_eqs c.contr_formals args in
let sm = List.fold_left2 (fun sm r l -> IdMap.add r (mk_const_term l) sm)
sm c.contr_returns lhs
in
foo_post |> subst_state sm
in
(* Add derived equalities before checking for frame & entailment *)
TODO do this by keeping disequalities in state ?
let st = add_neq_constraints st in
let foo_pre = apply_equalities st.se_eqs foo_pre in
Debug.debug (fun () ->
sprintf "\nPrecondition:\n%s\n\nPostcondition:\n%s\n"
(string_of_state foo_pre) (string_of_state foo_post)
);
let repl_fn =
match find_frame st st.se_state foo_pre with
| Ok (frame, inst) ->
let frame = List.map (subst_spatial_pred sm) frame in
Ok ((fun sm foo_post -> foo_post @ frame), inst)
| Error ([], m) ->
(match find_frame_dirty st st.se_state foo_pre with
| Error ([], m) ->
(* Try to see if a lemma can be applied inside a conjunct *)
if (find_proc st.se_prog foo).proc_is_lemma then
find_frame_conj st st.se_state foo_pre
else Error ([], m)
| e -> e)
| Error (msgs, m) as e -> e
in
Then , create vars for old vals of all x in lhs , and substitute in eqs & frame
(match repl_fn with
| Ok (repl_fn, inst) ->
let eqs = subst_eqs sm st.se_eqs in
let pure = st.se_state.pure |> subst_form sm in
let state = { pure = smk_and [pure; foo_post.pure]; spatial = repl_fn sm foo_post.spatial } in
(* This is to apply equalities derived during frame inference *)
let state = subst_state inst state in
symb_exec {st with se_eqs = eqs; se_state = state} postcond comms'
| Error (errs, m) ->
mk_error "The precondition of this procedure call may not hold" errs m pp.pp_pos)
| Seq (comms, _) :: comms' ->
symb_exec st postcond (comms @ comms')
| Basic (Havoc {havoc_args=vars}, pp) as comm :: comms' ->
(* Just substitute all occurrances of v for new var v' in symbolic state *)
Debug.debug (fun () ->
sprintf "%sExecuting havoc: %d: %s%sCurrent state:\n%s\n"
lineSep (pp.pp_pos.sp_start_line) (string_of_format pr_cmd comm)
lineSep (string_of_se_state st)
);
let sm =
List.fold_left (fun sm v -> IdMap.add v (mk_var_like_id v) sm)
IdMap.empty vars
in
let st = subst_se_state sm st in
symb_exec st postcond comms'
| Basic (Assume {spec_form=FOL spec}, pp) as comm :: comms' ->
(* Pure assume statements are just added to pure part of state *)
Debug.debug (fun () ->
sprintf "%sExecuting assume: %d: %s%sCurrent state:\n%s\n"
lineSep (pp.pp_pos.sp_start_line) (string_of_format pr_cmd comm)
lineSep (string_of_se_state st)
);
let spec, st = fold_map_terms process_no_array st spec in
symb_exec {st with se_state = add_state (mk_pure_state spec) st.se_state} postcond comms'
| Choice (comms, _) :: comms' ->
List.fold_left (fun errors comm ->
match errors with
| [] ->
symb_exec st postcond (comm :: comms')
| _ -> errors)
[] comms
| Basic (Assert spec, pp) as comm :: comms' ->
Debug.debug (fun () ->
sprintf "%sExecuting assert: %d: %s%sCurrent state:\n%s\n"
lineSep (pp.pp_pos.sp_start_line) (string_of_format pr_cmd comm)
lineSep (string_of_se_state st)
);
(match spec.spec_form with
| SL _ ->
let _, spec_st = state_of_spec_list st.se_fields None [spec] in
let st' = add_neq_constraints st in
(match check_entailment st st'.se_state spec_st with
| Ok _ ->
symb_exec st postcond comms'
| Error (errs, m) -> mk_error "This assertion may not hold" errs m pp.pp_pos)
| FOL spec_form ->
let spec, st = fold_map_terms process_no_array st spec_form in
let st' = add_neq_constraints st in
(match find_frame st st'.se_state (mk_pure_state spec) with
| Ok _ ->
symb_exec {st with se_state = add_state (mk_pure_state spec) st.se_state} postcond comms'
| Error (errs, m) -> mk_error "This assertion may not hold" errs m pp.pp_pos))
| Basic (Return {return_args=xs}, pp) as comm :: _ ->
Debug.debug (fun () ->
sprintf "%sExecuting return: %d: %s%sCurrent state:\n%s\n"
lineSep (pp.pp_pos.sp_start_line) (string_of_format pr_cmd comm)
lineSep (string_of_se_state st)
);
(* Substitute xs for return vars in postcond and throw away rest of comms *)
let xs, st = fold_left_map process st xs in
let ret_vars = st.se_proc.proc_contract.contr_returns in
let sm =
List.combine ret_vars xs
|> List.fold_left (fun sm (v, x) -> IdMap.add v x sm) IdMap.empty in
let postcond = subst_state sm postcond in
symb_exec st postcond []
| Basic (Split spec, pp) as comm :: comms' ->
Debug.debug (fun () ->
sprintf "%sExecuting split: %d: %s%sCurrent state:\n%s\n"
lineSep (pp.pp_pos.sp_start_line) (string_of_format pr_cmd comm)
lineSep (string_of_se_state st)
);
First assert the spec , then assume spec as new state
let _, spec_st = state_of_spec_list st.se_fields None [spec] in
let st' = add_neq_constraints st in
(match check_entailment st st'.se_state spec_st with
| Ok _ ->
symb_exec {st with se_eqs = empty_eqs; se_state = spec_st} postcond comms'
| Error (errs, m) -> mk_error "This split may not hold" errs m pp.pp_pos)
| Basic (New {new_lhs=id; new_sort=srt; new_args=ts}, pp) as comm :: comms' ->
Debug.debug
(fun () ->
sprintf "%sExecuting new command: %d: %s%sCurrent state:\n%s\n"
lineSep (pp.pp_pos.sp_start_line) (string_of_format pr_cmd comm)
lineSep (string_of_se_state st)
);
let sm = IdMap.singleton id (mk_var_like_id id) in
let vts = List.map (fun t -> fresh_const (sort_of t)) ts in
let st =
List.combine vts ts
|> List.fold_left (fun st (v, t) ->
First , eval / check t
let t, st = process st t in
let t' = subst_term sm t in
{st with se_state = add_state (mk_pure_state (mk_eq v t')) st.se_state}
) st
in
let st = subst_se_state sm st in
let new_cell = match srt with
| Loc (FreeSrt _) -> PointsTo (mk_const_term id, [])
| Loc (Array srt) ->
let m = fresh_const (Map ([Int], srt)) in
let l = List.hd vts in
let length_ok = mk_leq (mk_int 0) l in
Debug.debug (fun () -> "\n\nChecking that array length is nonnegative:\n");
(match check_pure_entail st (st.se_state.pure) length_ok with
| None -> ()
| Some errs -> raise_err "Possibly attempting to create an array of negative length");
Arr (mk_const_term id, List.hd vts, m)
| _ -> failwith "unexpected new command"
in
let st = {st with se_state = add_state (mk_spatial_state [new_cell]) st.se_state} in
symb_exec st postcond comms'
| Basic (Assume _, _) :: _ -> failwith "TODO Assume SL command"
| Basic (Dispose _, _) :: _ -> failwith "TODO Dispose command"
| Loop _ :: _ -> failwith "TODO Loop command"
in
try
se comms
with SymbExecFail msg ->
mk_error msg [] Model.empty pos
(** Check procedure [proc] in program [prog] using symbolic execution. *)
(* TODO: take care of aux_axioms *)
let check spl_prog prog aux_axioms proc =
Debug.info (fun () ->
"Checking procedure " ^ string_of_ident (name_of_proc proc) ^ "...\n");
(* Extract the list of field names from the spl_prog. *)
let flds =
IdMap.fold (fun _ tdecl flds ->
match tdecl.SplSyntax.t_def with
| SplSyntax.StructTypeDef vs ->
IdMap.fold (fun id _ flds -> IdSet.add id flds) vs flds
| _ -> flds
) spl_prog.SplSyntax.type_decls IdSet.empty
in
Make sure FOL predicates are not of the form SL ( Pure fol_formula ) )
let prog = prog |>
map_preds (fun pred ->
{pred with pred_body =
pred.pred_body
|> Opt.map (fun spec -> {spec with spec_form =
match spec.spec_form with
| SL (Sl.Pure (f, pos)) -> FOL f
| f -> f }
)}
)
in
let errors = match proc.proc_body with
| Some comm ->
let pre =
try
Ok (state_of_spec_list flds None proc.proc_contract.contr_precond |> snd)
with SymbExecFail msg ->
Error [(proc.proc_contract.contr_pos, "In precondition: " ^ msg, Model.empty)]
in
(match pre with
| Ok pre ->
let prepost =
try
Ok (state_of_spec_list flds (Some pre) proc.proc_contract.contr_postcond)
with SymbExecFail msg ->
Error [(proc.proc_contract.contr_pos, "In postcondition: " ^ msg, Model.empty)]
in
(match prepost with
| Ok (pre, post) ->
Debug.debug (fun () ->
sprintf "\nPrecondition:\n%s\n\nPostcondition:\n%s\n"
(string_of_state pre) (string_of_state post)
);
let st =
{se_state = pre; se_prog = prog; se_proc = proc;
se_fields = flds; se_eqs = empty_eqs}
in
symb_exec st post [comm]
| Error errs -> errs)
| Error errs -> errs)
| None ->
[]
in aux_axioms, errors
| null | https://raw.githubusercontent.com/wies/grasshopper/108473b0a678f0d93fffec6da2ad6bcdce5bddb9/src/verifier/symbExec.ml | ocaml | * ----------- Symbolic state and manipulators ----------
* x |-> [f1: E1, ..]
* Array(address, length, map)
* Conjunction of spatial states
* The state of the symbolic execution engine
TODO use Format formatters for these
|> String.map (function | '\n' -> ' ' | c -> c)
Special find_ptsto for extracting and removing an Arr from spatial'
Field reads
lookup fld in fs, so that loc |-> fs' and (fld, e) is in fs'
lookup fld in fs, so that loc |-> fs' and (fld, e) is in fs'
Add loc to spatial' to indicate we need an acc(loc) in the future
Array reads
If you can't find a in spatial, look in/add it to spatial'
If you can't find a in spatial, look in/add it to spatial'
If you can't find a in spatial, look in/add it to spatial'
Eval t using old_state as state
* Convert a specification into a symbolic state.
This also moves field read terms from pure formula to points-to predicates.
Assumes [fields] is a set of field identifiers, all other maps are treated as
functions.
[spatial'] is a list of outstanding spatial_preds needed to eval [state]
arr(x)
acc(x)
Convert all the specs into a state
Make sure there's nothing left in spatial'
* Substitute both vars and constants in a term according to [sm].
* Substitute both vars and constants in a form according to [sm].
* Substitute all variables and constants in state [(pure, spatial)] with terms
according to substitution map [sm].
* Substitute all variables and constants in state [st] with terms
according to substitution map [sm].
Apply current substitutions to t
Make sure things are not added twice
* ----------- Re-arrangement and normalization rules ----------
* Find equalities of the form var == exp in [pure] and return id -> exp map.
TODO you really need to fix this..
Note: can also use GrassUtil.foralls_to_exists for this
* Kill useless existential vars in state [st], find equalities between constants,
add to [st.se_eqs] and simplify.
* Add implicit disequalities from spatial to pure. Assumes normalized by eq.
Also add x != nil for every location x
* ----------- Symbolic Execution ----------
Returns None if the entailment holds, otherwise Some (list of error messages, model)
Collect all program axioms
Close the formulas: assuming all free variables are existential
Add definitions of all referenced predicates and functions
Add axioms
Add labels
Remove equal stuff
e1 != e2, so only okay if e2 is ex. var
add e2 -> e1 to inst and sub in fs2' to make sure e2 has uniform value
So create new const c, add e -> c to inst, and sub fs2' with inst
Check if p2 is implied by p1
* Returns [Ok inst] if [state1] |= [state2], else [Error (error messages)].
Check if find_frame returns empt
Cycle through sp1 looking for a dirty that works, keeping seen stuff in sp1a
Only PointsTos allowed
* Matches up arrays in pre and post of a function call and adds a pure formula to post
that enforces that the lengths are the same.
* Check that we have permission to the array, and that index is in bounds
* Check that all array read terms in [t] are safe on state [st]
Array reads
TODO: this is because assume/assert may have array reads under binders which have guards.
So for now we are not checking them. Better way to do this?
* Symbolically execute commands [comms] on state [st] and check [postcond].
Some helpers
If flag is set, check that current state isn't unsat
Check that we have permission to the array, and that index is in bounds
Find the map for arr and bump it up
Find the node to mutate
mutate fs to fs' so that it contains (fld, rhs)
Look up pre/post of foo
Since nothing can change array lengths, make them equal
Substitute formal params -> actual params in foo_pre/post
args will be part of foo_post, so substitute here too
Add derived equalities before checking for frame & entailment
Try to see if a lemma can be applied inside a conjunct
This is to apply equalities derived during frame inference
Just substitute all occurrances of v for new var v' in symbolic state
Pure assume statements are just added to pure part of state
Substitute xs for return vars in postcond and throw away rest of comms
* Check procedure [proc] in program [prog] using symbolic execution.
TODO: take care of aux_axioms
Extract the list of field names from the spl_prog. | * { 5 Symbolic execution based verifier }
open Util
open Grass
open GrassUtil
open Prog
open Printf
let simplify proc prog =
prog |>
dump_if 0 |>
Analyzer.infer_accesses true |>
Simplifier.elim_loops |>
Simplifier.elim_global_deps |>
dump_if 1
exception NotYetImplemented
let todo () = raise NotYetImplemented
exception SymbExecFail of string
let raise_err str = raise (SymbExecFail str)
let lineSep = "\n--------------------\n"
let fresh_array_length () = mk_free_const Int (fresh_ident "array_length")
let fresh_array_map srt = mk_free_const (Map ([Int], srt)) (fresh_ident "array_map")
TODO use consts instead ? And use idents instead of terms in spatial_pred
let fresh_const srt = mk_var srt (fresh_ident "v")
type spatial_pred =
| Pred of ident * term list
* A symbolic state is a ( pure formula , a list of spatial predicates ) .
Note : program vars are represented as FreeSymb constants ,
existential vars are represented as Var variables .
Note: program vars are represented as FreeSymb constants,
existential vars are represented as Var variables.
*)
type state = {
pure: form;
spatial: spatial_pred list
}
let mk_pure_state p = { pure = p; spatial = [] }
let mk_spatial_state sp = { pure = mk_true; spatial = sp }
let empty_state = { pure = mk_true; spatial = [] }
let map_state_pure fn state =
{ state with pure = fn state.pure }
let map_state_spatial fn state =
{ state with spatial = fn state.spatial }
let map_state pfn sfn state =
{ pure = pfn state.pure; spatial = sfn state.spatial }
let strengthen_pure_state fs state =
map_state_pure (fun pure -> smk_and (pure :: fs)) state
* Conjoin two states
let add_state s1 s2 =
{ pure = smk_and [s1.pure; s2.pure];
spatial = s1.spatial @ s2.spatial
}
* Equalities derived so far in the symbolic execution , as a map : ident - > term ,
kept so that they can be substituted into the command and the post .
Invariant : if map is { x1 : E1 , ... } then xi are distinct and xi is not in Ej for i ! = ASSUMES : vars and constants do not share names !
TODO : can we make it ident IdMap.t now ?
kept so that they can be substituted into the command and the post.
Invariant: if map is {x1: E1, ...} then xi are distinct and xi is not in Ej for i != j.
ASSUMES: vars and constants do not share names!
TODO: can we make it ident IdMap.t now?
*)
type equalities = term IdMap.t
type symb_exec_state = {
se_state: state;
se_prog: program;
se_proc: proc_decl;
se_fields: IdSet.t;
se_eqs: equalities;
}
let empty_eqs = IdMap.empty
let update_se_state st state = { st with se_state = state }
let rec string_of_spatial_pred = function
| PointsTo (x, fs) ->
sprintf "%s |-> (%s)" (string_of_term x)
(fs |> List.map (fun (id, t) -> (string_of_ident id) ^ ": " ^ (string_of_term t))
|> String.concat ", ")
| Pred (id, ts) ->
sprintf "%s(%s)" (string_of_ident id)
(ts |> List.map string_of_term |> String.concat ", ")
| Arr (x, l, m) ->
sprintf "arr(%s, %s, %s)" (string_of_term x) (string_of_term l) (string_of_term m)
| Conj fss ->
List.map (function
| [p] -> string_of_spatial_pred p
| ps -> "(" ^ string_of_spatial_pred_list ps ^ ")"
) fss
|> String.concat " && "
and string_of_spatial_pred_list sps =
sps |> List.map string_of_spatial_pred |> String.concat " * "
let string_of_state (s: state) =
let spatial =
match s.spatial with
| [] -> "emp"
| spatial -> string_of_spatial_pred_list spatial
in
let pure = s.pure
|> filter_annotations (fun _ -> false)
|> string_of_form
in
sprintf "Pure: %s\nSpatial: %s" pure spatial
let string_of_equalities eqs =
IdMap.bindings eqs
|> List.map (fun (x, t) -> (string_of_ident x) ^ " = " ^ (string_of_term t))
|> String.concat ", "
|> sprintf "{%s}"
let string_of_se_state st =
sprintf "Eqs: %s\n%s" (string_of_equalities st.se_eqs) (string_of_state st.se_state)
* Finds a points - to predicate at location [ loc ] in [ spatial ] , including in dirty regions .
If found , returns [ ( Some fs , repl_fn_rd , repl_fn_wr ) ] such that
[ loc ] |- > [ fs ] appears in [ spatial ]
[ repl_fn_rd fs ' ] returns [ spatial ] with [ fs ] replaced by [ fs ' ]
and [ repl_fn_wr fs ' ] returns [ spatial ] with [ fs ] replaced by [ fs ' ] ,
but if [ fs ] appears in a , then it drops all other conjuncts
If found, returns [(Some fs, repl_fn_rd, repl_fn_wr)] such that
[loc] |-> [fs] appears in [spatial]
[repl_fn_rd fs'] returns [spatial] with [fs] replaced by [fs']
and [repl_fn_wr fs'] returns [spatial] with [fs] replaced by [fs'],
but if [fs] appears in a Conj, then it drops all other conjuncts *)
let rec find_ptsto loc spatial =
match spatial with
| [] ->
let repl_fn = (fun fs' -> spatial) in
None, repl_fn, repl_fn
| PointsTo (x, fs) :: spatial' when x = loc ->
let repl_fn = (fun fs' -> PointsTo (x, fs') :: spatial') in
Some fs, repl_fn, repl_fn
| Conj spss as sp :: spatial' ->
let rec find_conj spss1 = function
| sps :: spss2 ->
(match find_ptsto loc sps with
| Some fs, repl_fn_rd, repl_fn_wr ->
let repl_fn_rd = (fun fs' -> Conj (repl_fn_rd fs' :: spss1 @ spss2) :: spatial') in
let repl_fn_wr = (fun fs' -> repl_fn_wr fs' @ spatial') in
Some fs, repl_fn_rd, repl_fn_wr
| None, _, _ ->
find_conj (sps :: spss1) spss2)
| [] -> todo ()
in
(match find_conj [] spss with
| Some _, _, _ as res -> res
| None, _, _ ->
let res, repl_fn_rd, repl_fn_wr = find_ptsto loc spatial' in
res, (fun fs' -> sp :: repl_fn_rd fs'), (fun fs' -> sp :: repl_fn_wr fs')
)
| sp :: spatial' ->
let res, repl_fn_rd, repl_fn_wr = find_ptsto loc spatial' in
res, (fun fs' -> sp :: repl_fn_rd fs'), (fun fs' -> sp :: repl_fn_wr fs')
* Finds an array predicate at location [ loc ] in [ spatial ] , including in dirty regions .
If found , returns [ ( Some m , repl_fn_wr ) ] such that
[ arr(loc , _ , m ) ] appears in [ spatial ]
and [ repl_fn_wr m ' ] returns [ spatial ] with [ m ] replaced by [ m ' ] ,
but if [ loc ] appears in a , then it drops all other conjuncts
If found, returns [(Some m, repl_fn_wr)] such that
[arr(loc, _, m)] appears in [spatial]
and [repl_fn_wr m'] returns [spatial] with [m] replaced by [m'],
but if [loc] appears in a Conj, then it drops all other conjuncts *)
let rec find_array loc spatial =
match spatial with
| [] ->
let repl_fn = (fun fs' -> spatial) in
None, repl_fn
| Arr (x, l, m) :: spatial' when x = loc ->
let repl_fn = (fun m' -> Arr(x, l, m') :: spatial') in
Some (l, m), repl_fn
| Conj spss as sp :: spatial' ->
let rec find_conj spss1 = function
| sps :: spss2 ->
(match find_array loc sps with
| Some lm, repl_fn_wr ->
let repl_fn_wr = (fun fs' -> repl_fn_wr fs' @ spatial') in
Some lm, repl_fn_wr
| None, _ ->
find_conj (sps :: spss1) spss2)
| [] -> todo ()
in
(match find_conj [] spss with
| Some _, _ as res -> res
| None, _ ->
let res, repl_fn_wr = find_array loc spatial' in
res, (fun fs' -> sp :: repl_fn_wr fs')
)
| sp :: spatial' ->
let res, repl_fn_wr = find_array loc spatial' in
res, (fun fs' -> sp :: repl_fn_wr fs')
Special find_ptsto for extracting and removing a PointsTo from spatial '
let find_ptsto_spatial' x =
find_map_res (function PointsTo(x', fs') when x = x' -> Some fs' | _ -> None)
let find_arr_spatial' x =
find_map_res (function Arr(x', l, m) when x = x' -> Some (l, m) | _ -> None)
* Evaluate term at [ state ] by looking up all field reads .
[ old_state ] is the state with which to evaluate old(x ) terms .
[ spatial ' ] is the list of spatial needed to evaluate everything in [ t ] .
[old_state] is the state with which to evaluate old(x) terms.
[spatial'] is the list of spatial preds needed to evaluate everything in [t]. *)
let rec eval_term fields (old_state, (state: state), spatial') = function
| Var _ as t -> t, (old_state, state, spatial')
| App (Read, [App (FreeSym fld, [], _); loc], srt)
let loc, (old_state, state, spatial') = eval_term fields (old_state, state, spatial') loc in
(match find_ptsto loc state.spatial with
| Some fs, mk_spatial, _ ->
let e, fs' =
try List.assoc fld fs, fs
with Not_found ->
let e = fresh_const srt in e, (fld, e) :: fs
in
let state' = map_state_spatial (fun _ -> mk_spatial fs') state in
e, (old_state, state', spatial')
| None, _, _ ->
(match find_ptsto_spatial' loc spatial' with
| Some (fs, spatial') ->
let e, fs' =
try List.assoc fld fs, fs
with Not_found ->
let e = fresh_const srt in e, (fld, e) :: fs
in
e, (old_state, state, PointsTo (loc, fs') :: spatial')
let e = fresh_const srt in
e, (old_state, state, PointsTo (loc, [fld, e]) :: spatial')))
| App (Read, [a; idx], srt)
when sort_of a = Loc (Array srt) ->
let a, (old_state, state, spatial') = eval_term fields (old_state, state, spatial') a in
let idx, (old_state, state, spatial') = eval_term fields (old_state, state, spatial') idx in
let m, spatial' =
(match find_array a state.spatial with
| Some (_, m), _ -> m, spatial'
(match find_arr_spatial' a spatial' with
| Some ((l, m), spatial') ->
m, Arr (a, l, m) :: spatial'
| None ->
let l = fresh_array_length () in
let m = fresh_array_map srt in
m, Arr (a, l, m) :: spatial'))
in
mk_read m [idx], (old_state, state, spatial')
| App (Length, [a], _) ->
let a, (old_state, state, spatial') = eval_term fields (old_state, state, spatial') a in
let l, spatial' =
(match find_array a state.spatial with
| Some (l, _), _ -> l, spatial'
(match find_arr_spatial' a spatial' with
| Some ((l, m), spatial') ->
l, Arr (a, l, m) :: spatial'
| None ->
let l = fresh_array_length () in
let srt = match (sort_of a) with | Loc Array s -> s | _ -> assert false in
let m = fresh_array_map srt in
l, Arr (a, l, m) :: spatial'))
in
l, (old_state, state, spatial')
| App (ArrayMap, [a], _) ->
let a, (old_state, state, spatial') = eval_term fields (old_state, state, spatial') a in
let m, spatial' =
(match find_array a state.spatial with
| Some (_, m), _ -> m, spatial'
(match find_arr_spatial' a spatial' with
| Some ((l, m), spatial') ->
m, Arr (a, l, m) :: spatial'
| None ->
let l = fresh_array_length () in
let srt = match (sort_of a) with | Loc Array s -> s | _ -> assert false in
let m = fresh_array_map srt in
m, Arr (a, l, m) :: spatial'))
in
m, (old_state, state, spatial')
| App (Old, [t], srt) as t' ->
(match old_state with
| Some old_state ->
let t, (_, old_state, spatial') = eval_term fields (None, old_state, spatial') t in
t, (Some old_state, state, spatial')
| None -> raise_err @@ "Unexpected old term: " ^ (string_of_term t'))
| App (s, ts, srt) ->
let ts, (old_state, state, spatial') = fold_left_map (eval_term fields) (old_state, state, spatial') ts in
App (s, ts, srt), (old_state, state, spatial')
let eval_term_no_olds fields state term =
match eval_term fields (None, state, []) term with
| term, (_, state, []) -> term, state
| _, (_, _, x :: _) ->
raise_err @@ "Possible invalid heap lookup. Couldn't find: " ^ (string_of_spatial_pred x)
let state_of_spec_list fields old_state specs : state * state =
let eval_term = eval_term fields in
let add (pure, spatial) = add_state { pure = pure; spatial = spatial } in
let convert_form (old_state, state, spatial') f =
let f, (old_state, (state: state), spatial') =
fold_map_terms eval_term (old_state, state, spatial') f
in
(old_state, add (f, []) state, spatial')
in
let rec convert_sl_form (old_state, (state: state), spatial') f =
let fail () = failwith @@ "Unsupported formula " ^ (Sl.string_of_form f) in
match f with
| Sl.Pure (f, _) -> convert_form (old_state, state, spatial') f
| Sl.Atom (Sl.Emp, ts, _) -> old_state, state, spatial'
let x, (old_state, state, spatial') = eval_term (old_state, state, spatial') x in
First check if we 've already created it in spatial '
let l, m, spatial' =
(match find_arr_spatial' x spatial' with
| Some ((l, m), spatial') ->
l, m, spatial'
| None ->
let l = fresh_array_length () in
let m = fresh_array_map srt in
l, m, spatial')
in
let len_axiom = mk_leq (mk_int 0) l in
old_state, add (len_axiom, [Arr (x, l, m)]) state, spatial'
let x, (old_state, state, spatial') = eval_term (old_state, state, spatial') x in
First check if we 've already created it in spatial '
let sp, spatial' =
(match find_ptsto_spatial' x spatial' with
| Some (fs, spatial') -> PointsTo (x, fs), spatial'
| None -> PointsTo (x, []), spatial')
in
old_state, add (mk_true, [sp]) state, spatial'
| Sl.Atom (Sl.Region, ts, _) -> fail ()
| Sl.Atom (Sl.Pred p, ts, _) ->
old_state, add (mk_true, [Pred (p, ts)]) state, spatial'
| Sl.SepOp (Sl.SepStar, f1, f2, _) ->
List.fold_left convert_sl_form (old_state, state, spatial') [f1; f2]
| Sl.SepOp (Sl.SepIncl, _, _, _) -> fail ()
| Sl.SepOp (Sl.SepPlus, _, _, _) -> fail ()
| Sl.BoolOp (And, fs, _) ->
let old_state, conj_states, spatial' =
List.fold_left (fun (old_state, conj_states, spatial') f ->
let old_state, state', spatial' =
convert_sl_form (old_state, empty_state, spatial') f
in
old_state, state' :: conj_states, spatial')
(old_state, [], spatial') fs
in
let pures, spatials =
conj_states |>
List.map (function {pure = p; spatial = s; _ } -> (p, s)) |>
List.split
in
let spatials = List.filter (function [] -> false | _ -> true) spatials in
(match spatials with
| [] -> old_state, add (smk_and pures, []) state, spatial'
| [sp] -> old_state, add (smk_and pures, sp) state, spatial'
| _ -> old_state, add (smk_and pures, [Conj spatials]) state, spatial')
| Sl.BoolOp _ -> fail ()
| Sl.Binder (b, vs, f, _) ->
let old_state, state1, spatial' =
convert_sl_form (old_state, mk_spatial_state state.spatial, spatial') f
in
if state1.spatial = state.spatial then
old_state, add (smk_binder b vs state1.pure, []) state, spatial'
else
failwith @@ "Confused by spatial under binder: " ^ (Sl.string_of_form f)
in
let (old_state, state, spatial') =
List.fold_left (fun (old_state, state, spatial') spec ->
let f =
match spec.spec_form with
| SL f -> f
| FOL f -> Sl.Pure (f, None)
in
convert_sl_form (old_state, state, spatial') f
) (old_state, empty_state, []) specs
in
(match spatial' with
| [] -> ()
| (PointsTo(x, _) | Arr (x, _, _)) :: _ ->
raise_err @@ "Possible invalid heap lookup to address: " ^ (string_of_term x)
| _ -> todo ());
Opt.get_or_else empty_state old_state, state
let subst_term sm = subst_consts_term sm >> subst_term sm
let subst_form sm = subst_consts sm >> subst sm
let rec subst_spatial_pred sm = function
| PointsTo (id, fs) ->
PointsTo (subst_term sm id, List.map (fun (id, t) -> id, subst_term sm t) fs)
| Pred (id, ts) ->
Pred (id, List.map (subst_term sm) ts)
| Arr (x, l, m) ->
Arr (subst_term sm x, subst_term sm l, subst_term sm m)
| Conj spss ->
Conj (List.map (List.map (subst_spatial_pred sm)) spss)
* Substitute all ( Vars and constants ) in derived equalities [ eqs ] ,
according to substitution [ sm ]
TODO check this preserves equalities invariant !
according to substitution [sm]
TODO check this preserves equalities invariant! *)
let subst_eqs sm eqs =
eqs |> IdMap.bindings
|> List.fold_left (fun eqs (id, t) ->
let t' = subst_term sm t in
match IdMap.find_opt id sm with
| Some (Var (id', _))
| Some (App (FreeSym id', _, _)) -> IdMap.add id' t' eqs
| None -> IdMap.add id t' eqs
| _ -> failwith "huh?"
) IdMap.empty
let subst_state sm {pure = pure; spatial = spatial; _} : state =
{ pure = subst_form sm pure;
spatial = List.map (subst_spatial_pred sm) spatial }
let subst_se_state sm st =
{st with se_eqs = subst_eqs sm st.se_eqs; se_state = subst_state sm st.se_state}
* Given two lists of idents and terms , create an equalities / subst map out of them .
let mk_eqs ids terms =
List.fold_left2 (fun eqs id t -> IdMap.add id t eqs) empty_eqs ids terms
* Add [ i d ] = [ t ] to equalities [ eqs ] while preserving invariant .
let add_eq id t eqs =
let t = subst_term eqs t in
if IdMap.mem id eqs then
failwith @@ sprintf "Tried to add %s twice to eqs %s"
(string_of_ident id) (string_of_equalities eqs)
else
let eqs = subst_eqs (IdMap.singleton id t) eqs in
IdMap.add id t eqs
* Normalize a by some kind of sorting
let sort_conj = function
| Conj spss ->
Conj (spss |> List.map (List.stable_sort compare) |> List.stable_sort compare)
| sp -> sp
* Find equalities of the form const = = const in [ state ] and add to [ eqs ]
let find_equalities eqs state =
let rec find_eq sm = function
| Atom (App (Eq, [(App (FreeSym id, [], _)); App (FreeSym _, [], _) as t2], _), _) ->
add_eq id t2 sm
| BoolOp (And, fs) ->
List.fold_left find_eq sm fs
| Binder (_, [], f, _) -> find_eq sm f
| _ -> sm
in
find_eq eqs state.pure
let find_var_equalities (pure: form) =
let rec find_eq sm = function
| Atom (App (Eq, [Var (id, _); Var _ as t2], _), _)
| Atom (App (Eq, [Var (id, _); App (FreeSym _, [], _) as t2], _), _)
| Atom (App (Eq, [App (FreeSym _, [], _) as t2; Var (id, _)], _), _) ->
else add_eq id t2 sm
| BoolOp (And, fs) ->
List.fold_left find_eq sm fs
| Binder (_, [], f, _) -> find_eq sm f
| _ -> sm
in
find_eq IdMap.empty pure
let rec remove_trivial_equalities = function
| Atom (App (Eq, [t1; t2], _), _) as f -> if t1 = t2 then mk_true else f
| BoolOp (op, fs) -> smk_op op (List.map remove_trivial_equalities fs)
| Binder (b, vs, f, anns) -> Binder (b, vs, remove_trivial_equalities f, anns)
| f -> f
let apply_equalities eqs state =
state |>
subst_state eqs |>
map_state_pure remove_trivial_equalities
let remove_useless_existentials state : state =
apply_equalities (find_var_equalities state.pure) state
let simplify_state st =
let state =
st.se_state |>
map_state_pure nnf |>
remove_useless_existentials
in
let eqs = find_equalities st.se_eqs state in
{st with se_eqs = eqs; se_state = apply_equalities eqs state}
let add_neq_constraints st =
let rec f acc locs = function
| PointsTo (x, _) :: sps | Arr (x, _, _) :: sps ->
let acc1 = TermSet.fold (fun y acc ->
if sort_of x = sort_of y then mk_neq x y :: acc else acc)
locs acc
in
f acc1 (TermSet.add x locs) sps
| Pred _ :: sps ->
f acc locs sps
| Conj spss :: sps ->
let acc, locs =
List.fold_left (fun (acc, locs') sps ->
let acc, locs1 = f acc locs sps in
acc, TermSet.union locs' locs1)
(acc, locs) spss
in
f acc locs sps
| [] -> acc, locs
in
let { pure = pure; spatial = spatial; _ } = st.se_state in
let neqs, locs = f [] TermSet.empty spatial in
let get_sort x = match sort_of x with
| Loc s -> s
| s ->
failwith @@ sprintf "Spatial location %s has non Loc sort %s"
(string_of_term x) (string_of_sort s)
in
let neqs =
TermSet.fold (fun x acc -> mk_neq x (mk_null (get_sort x)) :: acc) locs neqs
in
let new_se_state = strengthen_pure_state neqs st.se_state in
update_se_state st new_se_state
let check_pure_entail st p1 p2 =
let { pure = p2; _ } = apply_equalities st.se_eqs (mk_pure_state p2) in
if p1 = p2 || p2 = mk_true then None
Dump it to an SMT solver
Util.flat_map
(fun sf ->
let name =
Printf.sprintf "%s_%d_%d"
sf.spec_name sf.spec_pos.sp_start_line sf.spec_pos.sp_start_col
in
match sf.spec_form with FOL f -> [mk_name name f] | SL _ -> [])
st.se_prog.prog_axioms
Apply equalities in eqs
in
let p2 = Verifier.annotate_aux_msg "Related location" p2 in
let close f = smk_exists (IdSrtSet.elements (sorted_free_vars f)) f in
let labels, f =
smk_and [p1; mk_not p2] |> close |> nnf |> Verifier.finalize_form st.se_prog
|> fun f -> f :: Verifier.pred_axioms st.se_prog
|> (fun fs -> smk_and (fs @ axioms))
|> Verifier.add_labels
in
let name = fresh_ident "form" |> string_of_ident in
Debug.debug (fun () ->
sprintf "\n\nCalling prover with name %s\n" name);
match Prover.get_model ~session_name:name f with
| None -> None
| Some model -> Some (Verifier.get_err_msg_from_labels model labels, model)
* Returns ( fr , inst ) s.t . state1 |= state2 * fr , and
inst accumulates an instantiation for existential variables in state2 .
Assumes that both states have been normalized w.r.t eqs and inst .
inst accumulates an instantiation for existential variables in state2.
Assumes that both states have been normalized w.r.t eqs and inst. *)
let rec find_frame st ?(inst=empty_eqs) state1 state2 =
Debug.debugl 1 (fun () ->
sprintf "\nFinding frame with %s for:\n%s\n|=\n%s &*& ??\n"
(string_of_equalities inst)
(string_of_spatial_pred_list state1.spatial) (string_of_spatial_pred_list state2.spatial)
);
let match_up_sp inst sp2 sp1 =
match sp2, sp1 with
| sp2, sp1 when (sort_conj sp2) = (sort_conj sp1) ->
match equal elements ( for , do some normalization )
Some inst
| PointsTo (x, fs2), PointsTo (x', fs1) when x = x' ->
let match_up_fields inst fs1 fs2 =
let fs1, fs2 = List.sort compare fs1, List.sort compare fs2 in
let rec match_up inst = function
| (_, []) -> Some inst
match_up inst (fs1', fs2')
| ((f1, e1) :: fs1', (f2, e2) :: fs2') when f1 = f2 ->
(match e2 with
| Var (e2_id, _) ->
let sm = IdMap.singleton e2_id e1 in
let fs2' = List.map (fun (f, e) -> (f, subst_term sm e)) fs2' in
assert (IdMap.mem e2_id inst |> not);
match_up (IdMap.add e2_id e1 inst) (fs1', fs2')
| App (FreeSym e2_id, [], _) ->
print_endline @@ ":: " ^ (string_of_term e1) ^ " " ^ (string_of_term e2);
failwith "TODO"
| _ -> None)
| ((f1, e1) :: fs1', (f2, e2) :: fs2')
when compare (f1, e1) (f2, e2) < 0 ->
RHS does n't need to have all fields , so drop ( f1 , e1 )
match_up inst (fs1', (f2, e2) :: fs2')
| (fs1, (f2, e2)::fs2') ->
f2 not in LHS , so only okay if e2 is an ex . var
(match e2 with
| Var (e, s) ->
let c = fresh_const s in
let fs2' = fs2' |>
List.map (fun (f, t) -> (f, subst_term (IdMap.singleton e c) t))
in
match_up (IdMap.add e c inst) (fs1, fs2')
| _ -> None)
in
match_up inst (fs1, fs2)
in
match_up_fields inst fs1 fs2
| Arr (x2, l2, m2), Arr (x1, l1, m1) when x1 = x2 ->
(match l2, m2 with
| App (FreeSym l2_id, [], _), App (FreeSym m2_id, [], _)
| Var (l2_id, _), Var (m2_id, _) ->
let inst = inst |> IdMap.add l2_id l1 |> IdMap.add m2_id m1 in
Some inst
| _ -> None)
| Conj spss2, Conj spss1 ->
let match_up_conjunct inst sps2 sps1 =
(match check_entailment st ~inst:inst (mk_spatial_state sps1) (mk_spatial_state sps2) with
| Ok inst -> Some inst
| Error _ -> None)
in
let match_up_conj inst spss2 spss1 =
List.fold_left (fun acc sps2 ->
match acc with
| Some (inst, spss1) ->
find_map_res (match_up_conjunct inst sps2) spss1
| None -> None)
(Some (inst, spss1)) spss2
in
(match match_up_conj inst spss2 spss1 with
Only allow when spss1 and spss2 are same len . TODO ? ! ? !
| _ -> None)
| _ -> None
in
Sort sps2 so that acc(v)/arr(v ) where v is a var ( i.e. like x.next ) are in the end
let sps2 =
state2.spatial |> List.partition
(function PointsTo (Var _, _) | Arr (Var _, _, _) -> false | _ -> true)
|> (fun (x, y) -> x @ y)
in
match sps2 with
| [] ->
let st = {st with se_eqs = IdMap.union (fun _ -> failwith "") st.se_eqs inst} in
(match check_pure_entail st state1.pure state2.pure with
| None ->
Ok (state1.spatial, inst)
| Some errs -> Error errs)
| sp2 :: sps2' ->
(match find_map_res (match_up_sp inst sp2) state1.spatial with
| Some (inst, sps1') ->
let state1' = { state1 with spatial = sps1' } in
let state2' = subst_state inst { state2 with spatial = sps2' } in
find_frame st ~inst:inst state1' state2'
TODO get errors ?
and check_entailment st ?(inst=empty_eqs) state1 state2 =
let st1 = simplify_state { st with se_state = state1 } in
let eqs, state1 = st1.se_eqs, st1.se_state in
let state2 =
state2 |>
apply_equalities eqs |>
apply_equalities inst |>
remove_useless_existentials
in
Debug.debug (fun () ->
sprintf "\nChecking entailment:\n%s\n|=\n%s\n"
(string_of_se_state st1) (string_of_state state2)
);
match find_frame st ~inst:inst state1 state2 with
| Ok ([], inst) -> Ok inst
| Ok _ ->
Error (["The frame was not empty for this entailment check"], Model.empty)
| Error errs -> Error errs
* Finds a call site for a function that 's completely contained inside a conjunct .
If found , [ find_frame_conj p e state1 state2 ] returns a function [ repl_fn ] s.t .
[ repl_fn sm state2 ' ] is the result of replacing [ state2 ] inside [ state1 ] with [ state2 ' ] ,
and applying the substitution map [ sm ] on the remaining parts of [ state1 ] .
If found, [find_frame_conj p e state1 state2] returns a function [repl_fn] s.t.
[repl_fn sm state2'] is the result of replacing [state2] inside [state1] with [state2'],
and applying the substitution map [sm] on the remaining parts of [state1].
*)
let find_frame_conj st state1 state2 =
let rec find_frame_inside_conj = function
| [] -> Error ([], Model.empty)
| sps :: spss ->
(match find_frame st { state1 with spatial = sps } state2 with
| Ok (frame, inst) ->
let repl_fn = (fun sm foo_post ->
let frame = List.map (subst_spatial_pred sm) frame in
let spss = List.map (List.map (subst_spatial_pred sm)) spss in
(foo_post @ frame) :: spss)
in
Ok (repl_fn, inst)
| Error errs1 ->
(match find_frame_inside_conj spss with
| Ok (repl_fn, inst) ->
let repl_fn = (fun sm foo_post ->
let sps = List.map (subst_spatial_pred sm) sps in
sps :: (repl_fn sm foo_post))
in
Ok (repl_fn, inst)
| Error ([], _) -> Error errs1
| Error errs -> Error errs))
in
let rec find_frame_conj = function
| [] -> Error ([], Model.empty)
| Conj spss :: spatial' ->
(match find_frame_inside_conj spss with
| Ok (repl_fn, inst) ->
let repl_fn = (fun sm foo_post ->
Conj (repl_fn sm foo_post) :: (List.map (subst_spatial_pred sm) spatial'))
in
Ok (repl_fn, inst)
| Error errs ->
(match find_frame_conj spatial' with
| Ok (repl_fn, inst) ->
let repl_fn =
(fun sm foo_post ->
let spss = List.map (List.map (subst_spatial_pred sm)) spss in
Conj spss :: (repl_fn sm foo_post))
in
Ok (repl_fn, inst)
| Error ([], _) -> Error errs
| Error errs -> Error errs))
| sp :: spatial' ->
(match find_frame_conj spatial' with
| Ok (repl_fn, inst) ->
let repl_fn =
(fun sm foo_post -> (subst_spatial_pred sm sp) :: (repl_fn sm foo_post))
in
Ok (repl_fn, inst)
| Error errs -> Error errs)
in
find_frame_conj state1.spatial
* Finds a call site for a function that 's completely contained inside a dirty
region .
[ state2 ] must have only PointsTo / Arr - no predicates allowed .
region.
[state2] must have only PointsTo/Arr - no predicates allowed.*)
let find_frame_dirty st state1 state2 =
let find_inside_dirty = function
| sp -> Error ([], Model.empty)
in
let rec find_dirty sp1a = function
| sp :: sp1b ->
(match find_inside_dirty sp with
| Error ([], m) -> find_dirty (sp :: sp1a) sp1b
| Error (msgs, m) -> Error (msgs, m)
| Ok (rf, inst) -> assert false)
| [] -> Error ([], Model.empty)
in
match List.exists (function PointsTo _ | Arr _ -> false | _ -> true) state2.spatial with
| false -> find_dirty [] state1.spatial
let force_array_lengths_equal pre post =
let length_axiom =
List.fold_left (fun acc -> function
| Arr (a, l, m) ->
let f =
match List.find_opt (function Arr (a', l', _) -> a = a' | _ -> false) pre.spatial with
| Some (Arr (_, l', _)) -> mk_eq l l'
| _ -> mk_true
in
f :: acc
| _ -> acc)
[] post.spatial
in
strengthen_pure_state length_axiom post
let check_array_acc st arr idx =
let state = st.se_state in
match find_array arr state.spatial with
| Some (l, _), _ ->
let idx_in_bds = smk_and [(mk_leq (mk_int 0) idx); (mk_lt idx l)] in
Debug.debug (fun () -> "\n\nChecking array index is in bounds:\n");
(match check_pure_entail st state.pure idx_in_bds with
| None -> ()
| Some errs -> raise_err "Possible array index out of bounds error")
| None, _ ->
raise_err "Possible invalid array read"
let check_array_reads st t =
let rec check = function
| Var _ as t -> t
| App (Read, [a; idx], srt)
| App ( Read , [ f ; App ( Read , [ App ( ArrayCells , [ a ] , _ ) ; idx ] , _ ) ] , srt )
when sort_of a = Loc (Array srt) ->
let a, _ = eval_term_no_olds st.se_fields st.se_state a in
let idx, _ = eval_term_no_olds st.se_fields st.se_state idx in
check_array_acc st a idx;
App (Read, [check a; check idx], srt)
| App (s, ts, srt) -> App (s, List.map check ts, srt)
in
check t
* Process term by substituting eqs , looking up field reads .
let process_no_array st t =
let t = subst_term st.se_eqs t in
let t, state = eval_term_no_olds st.se_fields st.se_state t in
t, {st with se_state = state}
* Process term by substituting eqs , looking up field reads , and checking array reads .
let process st t =
let t = t |> subst_term st.se_eqs |> check_array_reads st in
let t, state = eval_term_no_olds st.se_fields st.se_state t in
t, {st with se_state = state}
let rec symb_exec st postcond comms =
let lookup_type id = (find_var st.se_prog st.se_proc id).var_sort in
let mk_var_like srt id =
let id' = fresh_ident (name id) in
mk_free_const srt id'
in
let mk_var_like_id id = mk_var_like (lookup_type id) id in
let mk_const_term id = mk_free_const (lookup_type id) id in
let mk_error msg errs model pos =
[(pos, String.concat "\n\n" (msg :: errs), model)]
in
let pos = match comms with
| Basic (_, pp) :: _ -> pp.pp_pos
| _ -> dummy_position
in
First , simplify_state the pre state
let st = simplify_state st in
if !Config.check_unsat then begin
Debug.debug (fun () -> "Checking if current state is unsat:\n");
let st' = add_neq_constraints st in
try
(match find_frame st st'.se_state (mk_pure_state mk_false) with
| Ok _ ->
print_endline @@ (string_of_src_pos pos) ^ "\nWarning: Intermediate state was unsat"
| Error _ ->
Debug.debug (fun () -> "State is satisfiable.\n"))
with _ ->
print_endline @@ (string_of_src_pos pos) ^ "\nWarning: unsat check hit exception"
end;
let se = function
| [] ->
Debug.debug (fun () ->
sprintf "%sExecuting check postcondition: %s%sCurrent state:\n%s\n"
lineSep (string_of_state postcond)
lineSep (string_of_se_state st)
);
TODO do this better
let st = add_neq_constraints st in
First , check if current state is unsat
(try
(match find_frame st st.se_state (mk_pure_state mk_false) with
Unsat , so forget checking postcondition
[]
| Error _ ->
(match check_entailment st st.se_state postcond with
| Ok _ -> []
| Error (errs, m) ->
TODO to get line numbers , convert returns into asserts
mk_error "A postcondition may not hold" errs m dummy_position))
with _ ->
print_endline @@ (string_of_src_pos pos) ^ "\nWarning: unsat check hit exception";
(match check_entailment st st.se_state postcond with
| Ok _ -> []
| Error (errs, m) ->
TODO to get line numbers , convert returns into asserts
mk_error "A postcondition may not hold" errs m dummy_position))
| (Basic (Assign {assign_lhs=[_];
assign_rhs=[App (Write, [arr; idx; rhs], Loc (Array _))]}, pp) as comm) :: comms' ->
| ( Basic ( Assign { assign_lhs=[f ] ;
( Write , [ array_state ;
App ( Read , [ App ( ArrayCells , [ arr ] , _ ) ; idx ] , _ ) ; rhs ] , srt ) ] } , pp )
as comm ) : : comms '
when array_state = Grassifier.array_state true ( sort_of rhs )
|| array_state = Grassifier.array_state false ( sort_of rhs ) - >
assign_rhs=[App (Write, [array_state;
App (Read, [App (ArrayCells, [arr], _); idx], _); rhs], srt)]}, pp)
as comm) :: comms'
when array_state = Grassifier.array_state true (sort_of rhs)
|| array_state = Grassifier.array_state false (sort_of rhs) ->*)
Debug.debug (fun () ->
sprintf "%sExecuting array write: %d: %s%sCurrent state:\n%s\n"
lineSep (pp.pp_pos.sp_start_line) (string_of_format pr_cmd comm)
lineSep (string_of_se_state st)
);
let arr, st = process st arr in
let idx, st = process st idx in
let rhs, st = process st rhs in
check_array_acc st arr idx;
(match find_array arr st.se_state.spatial with
| Some (_, (App (FreeSym m_id, [], _) as m)), mk_spatial' ->
let m' = mk_var_like (sort_of m) m_id in
let sm = IdMap.singleton m_id m' in
let idx, rhs = idx |> subst_term sm, rhs |> subst_term sm in
let st = subst_se_state sm st in
let pure = smk_and [mk_eq m (mk_write m' [idx] rhs); st.se_state.pure] in
let st' = update_se_state st { pure = pure; spatial = mk_spatial' m } in
symb_exec st' postcond comms'
| Some _, _ -> failwith "Array map was not a const term"
| None, _ ->
[(pp.pp_pos, "Possible invalid array write", Model.empty)])
| Basic (Assign {assign_lhs=[fld];
assign_rhs=[App (Write, [App (FreeSym fld', [], _);
loc; rhs], srt)]}, pp) as comm :: comms'
when fld = fld' && IdSet.mem fld st.se_fields ->
Debug.debug (fun () ->
sprintf "%sExecuting mutate: %d: %s%sCurrent state:\n%s\n"
lineSep (pp.pp_pos.sp_start_line) (string_of_format pr_cmd comm)
lineSep (string_of_se_state st)
);
First , process / check loc and rhs
let loc, st = process st loc in
let rhs, st = process st rhs in
(match find_ptsto loc st.se_state.spatial with
| Some fs, _, mk_spatial' ->
let fs' =
if List.exists (fst >> (=) fld) fs
then List.map (fun (f, e) -> (f, if f = fld then rhs else e)) fs
else (fld, rhs) :: fs
in
let st' = update_se_state st { pure = st.se_state.pure; spatial = mk_spatial' fs' } in
symb_exec st' postcond comms'
| None, _, _ ->
[(pp.pp_pos, "Possible invalid heap mutation", Model.empty)])
| Basic (Assign {assign_lhs=ids; assign_rhs=ts}, pp) as comm :: comms' ->
Debug.debug (fun () ->
sprintf "%sExecuting assignment: %d: %s%sCurrent state:\n%s\n"
lineSep (pp.pp_pos.sp_start_line) (string_of_format pr_cmd comm)
lineSep (string_of_se_state st)
);
TODO simultaneous assignments ca n't touch heap , so do all at once
let st =
List.combine ids ts
|> List.fold_left (fun st (id, rhs) ->
First , substitute / eval / check rhs
let rhs, st = process st rhs in
let sm = IdMap.singleton id (mk_var_like_id id) in
let rhs' = subst_term sm rhs in
let st = subst_se_state sm st in
let state' = add_state (mk_pure_state (mk_eq (mk_const_term id) rhs')) st.se_state in
update_se_state st state'
) st
in
symb_exec st postcond comms'
| Basic (Call {call_lhs=lhs; call_name=foo; call_args=args}, pp) as comm :: comms' ->
Debug.debug (fun () ->
sprintf "%sExecuting procedure call: %d: %s%sCurrent state:\n%s\n"
lineSep (pp.pp_pos.sp_start_line) (string_of_format pr_cmd comm)
lineSep (string_of_se_state st)
);
First , substitute eqs and eval args
let args, st = args |> fold_left_map process st in
Debug.debug (fun () -> sprintf "\nOn args: %s\n" (string_of_format pr_term_list args));
let c = (find_proc st.se_prog foo).proc_contract in
let foo_pre, foo_post =
let _, pre = c.contr_precond |> state_of_spec_list st.se_fields None in
let pre, post = c.contr_postcond |> state_of_spec_list st.se_fields (Some pre) in
let post = force_array_lengths_equal pre post in
remove_useless_existentials pre, remove_useless_existentials post
in
let foo_pre =
foo_pre |> subst_state (mk_eqs c.contr_formals args)
in
Replace lhs vars with fresh vars . For every part of new state
let sm =
lhs |> List.fold_left (fun sm id ->
IdMap.add id (mk_var_like_id id) sm)
IdMap.empty
in
Substitute formal params - > actual params & return vars - > lhs vars in foo_post
let foo_post =
let args = List.map (subst_term sm) args in
let sm = mk_eqs c.contr_formals args in
let sm = List.fold_left2 (fun sm r l -> IdMap.add r (mk_const_term l) sm)
sm c.contr_returns lhs
in
foo_post |> subst_state sm
in
TODO do this by keeping disequalities in state ?
let st = add_neq_constraints st in
let foo_pre = apply_equalities st.se_eqs foo_pre in
Debug.debug (fun () ->
sprintf "\nPrecondition:\n%s\n\nPostcondition:\n%s\n"
(string_of_state foo_pre) (string_of_state foo_post)
);
let repl_fn =
match find_frame st st.se_state foo_pre with
| Ok (frame, inst) ->
let frame = List.map (subst_spatial_pred sm) frame in
Ok ((fun sm foo_post -> foo_post @ frame), inst)
| Error ([], m) ->
(match find_frame_dirty st st.se_state foo_pre with
| Error ([], m) ->
if (find_proc st.se_prog foo).proc_is_lemma then
find_frame_conj st st.se_state foo_pre
else Error ([], m)
| e -> e)
| Error (msgs, m) as e -> e
in
Then , create vars for old vals of all x in lhs , and substitute in eqs & frame
(match repl_fn with
| Ok (repl_fn, inst) ->
let eqs = subst_eqs sm st.se_eqs in
let pure = st.se_state.pure |> subst_form sm in
let state = { pure = smk_and [pure; foo_post.pure]; spatial = repl_fn sm foo_post.spatial } in
let state = subst_state inst state in
symb_exec {st with se_eqs = eqs; se_state = state} postcond comms'
| Error (errs, m) ->
mk_error "The precondition of this procedure call may not hold" errs m pp.pp_pos)
| Seq (comms, _) :: comms' ->
symb_exec st postcond (comms @ comms')
| Basic (Havoc {havoc_args=vars}, pp) as comm :: comms' ->
Debug.debug (fun () ->
sprintf "%sExecuting havoc: %d: %s%sCurrent state:\n%s\n"
lineSep (pp.pp_pos.sp_start_line) (string_of_format pr_cmd comm)
lineSep (string_of_se_state st)
);
let sm =
List.fold_left (fun sm v -> IdMap.add v (mk_var_like_id v) sm)
IdMap.empty vars
in
let st = subst_se_state sm st in
symb_exec st postcond comms'
| Basic (Assume {spec_form=FOL spec}, pp) as comm :: comms' ->
Debug.debug (fun () ->
sprintf "%sExecuting assume: %d: %s%sCurrent state:\n%s\n"
lineSep (pp.pp_pos.sp_start_line) (string_of_format pr_cmd comm)
lineSep (string_of_se_state st)
);
let spec, st = fold_map_terms process_no_array st spec in
symb_exec {st with se_state = add_state (mk_pure_state spec) st.se_state} postcond comms'
| Choice (comms, _) :: comms' ->
List.fold_left (fun errors comm ->
match errors with
| [] ->
symb_exec st postcond (comm :: comms')
| _ -> errors)
[] comms
| Basic (Assert spec, pp) as comm :: comms' ->
Debug.debug (fun () ->
sprintf "%sExecuting assert: %d: %s%sCurrent state:\n%s\n"
lineSep (pp.pp_pos.sp_start_line) (string_of_format pr_cmd comm)
lineSep (string_of_se_state st)
);
(match spec.spec_form with
| SL _ ->
let _, spec_st = state_of_spec_list st.se_fields None [spec] in
let st' = add_neq_constraints st in
(match check_entailment st st'.se_state spec_st with
| Ok _ ->
symb_exec st postcond comms'
| Error (errs, m) -> mk_error "This assertion may not hold" errs m pp.pp_pos)
| FOL spec_form ->
let spec, st = fold_map_terms process_no_array st spec_form in
let st' = add_neq_constraints st in
(match find_frame st st'.se_state (mk_pure_state spec) with
| Ok _ ->
symb_exec {st with se_state = add_state (mk_pure_state spec) st.se_state} postcond comms'
| Error (errs, m) -> mk_error "This assertion may not hold" errs m pp.pp_pos))
| Basic (Return {return_args=xs}, pp) as comm :: _ ->
Debug.debug (fun () ->
sprintf "%sExecuting return: %d: %s%sCurrent state:\n%s\n"
lineSep (pp.pp_pos.sp_start_line) (string_of_format pr_cmd comm)
lineSep (string_of_se_state st)
);
let xs, st = fold_left_map process st xs in
let ret_vars = st.se_proc.proc_contract.contr_returns in
let sm =
List.combine ret_vars xs
|> List.fold_left (fun sm (v, x) -> IdMap.add v x sm) IdMap.empty in
let postcond = subst_state sm postcond in
symb_exec st postcond []
| Basic (Split spec, pp) as comm :: comms' ->
Debug.debug (fun () ->
sprintf "%sExecuting split: %d: %s%sCurrent state:\n%s\n"
lineSep (pp.pp_pos.sp_start_line) (string_of_format pr_cmd comm)
lineSep (string_of_se_state st)
);
First assert the spec , then assume spec as new state
let _, spec_st = state_of_spec_list st.se_fields None [spec] in
let st' = add_neq_constraints st in
(match check_entailment st st'.se_state spec_st with
| Ok _ ->
symb_exec {st with se_eqs = empty_eqs; se_state = spec_st} postcond comms'
| Error (errs, m) -> mk_error "This split may not hold" errs m pp.pp_pos)
| Basic (New {new_lhs=id; new_sort=srt; new_args=ts}, pp) as comm :: comms' ->
Debug.debug
(fun () ->
sprintf "%sExecuting new command: %d: %s%sCurrent state:\n%s\n"
lineSep (pp.pp_pos.sp_start_line) (string_of_format pr_cmd comm)
lineSep (string_of_se_state st)
);
let sm = IdMap.singleton id (mk_var_like_id id) in
let vts = List.map (fun t -> fresh_const (sort_of t)) ts in
let st =
List.combine vts ts
|> List.fold_left (fun st (v, t) ->
First , eval / check t
let t, st = process st t in
let t' = subst_term sm t in
{st with se_state = add_state (mk_pure_state (mk_eq v t')) st.se_state}
) st
in
let st = subst_se_state sm st in
let new_cell = match srt with
| Loc (FreeSrt _) -> PointsTo (mk_const_term id, [])
| Loc (Array srt) ->
let m = fresh_const (Map ([Int], srt)) in
let l = List.hd vts in
let length_ok = mk_leq (mk_int 0) l in
Debug.debug (fun () -> "\n\nChecking that array length is nonnegative:\n");
(match check_pure_entail st (st.se_state.pure) length_ok with
| None -> ()
| Some errs -> raise_err "Possibly attempting to create an array of negative length");
Arr (mk_const_term id, List.hd vts, m)
| _ -> failwith "unexpected new command"
in
let st = {st with se_state = add_state (mk_spatial_state [new_cell]) st.se_state} in
symb_exec st postcond comms'
| Basic (Assume _, _) :: _ -> failwith "TODO Assume SL command"
| Basic (Dispose _, _) :: _ -> failwith "TODO Dispose command"
| Loop _ :: _ -> failwith "TODO Loop command"
in
try
se comms
with SymbExecFail msg ->
mk_error msg [] Model.empty pos
let check spl_prog prog aux_axioms proc =
Debug.info (fun () ->
"Checking procedure " ^ string_of_ident (name_of_proc proc) ^ "...\n");
let flds =
IdMap.fold (fun _ tdecl flds ->
match tdecl.SplSyntax.t_def with
| SplSyntax.StructTypeDef vs ->
IdMap.fold (fun id _ flds -> IdSet.add id flds) vs flds
| _ -> flds
) spl_prog.SplSyntax.type_decls IdSet.empty
in
Make sure FOL predicates are not of the form SL ( Pure fol_formula ) )
let prog = prog |>
map_preds (fun pred ->
{pred with pred_body =
pred.pred_body
|> Opt.map (fun spec -> {spec with spec_form =
match spec.spec_form with
| SL (Sl.Pure (f, pos)) -> FOL f
| f -> f }
)}
)
in
let errors = match proc.proc_body with
| Some comm ->
let pre =
try
Ok (state_of_spec_list flds None proc.proc_contract.contr_precond |> snd)
with SymbExecFail msg ->
Error [(proc.proc_contract.contr_pos, "In precondition: " ^ msg, Model.empty)]
in
(match pre with
| Ok pre ->
let prepost =
try
Ok (state_of_spec_list flds (Some pre) proc.proc_contract.contr_postcond)
with SymbExecFail msg ->
Error [(proc.proc_contract.contr_pos, "In postcondition: " ^ msg, Model.empty)]
in
(match prepost with
| Ok (pre, post) ->
Debug.debug (fun () ->
sprintf "\nPrecondition:\n%s\n\nPostcondition:\n%s\n"
(string_of_state pre) (string_of_state post)
);
let st =
{se_state = pre; se_prog = prog; se_proc = proc;
se_fields = flds; se_eqs = empty_eqs}
in
symb_exec st post [comm]
| Error errs -> errs)
| Error errs -> errs)
| None ->
[]
in aux_axioms, errors
|
3e821090767232623b9aa666f6c38c20ce41cedef5a27655279da8457448ab35 | ddmcdonald/sparser | day-in-month.lisp | ;;; -*- Mode:LISP; Syntax:Common-Lisp; Package:SPARSER -*-
copyright ( c ) 1991 Content Technologies Inc.
;;; copyright (c) 1992-1993,2021 David D. McDonald -- all rights reserved
;;;
;;; File: "day-in-month"
Module : " : time : "
version : February 2021
initiated 7/31 v1.8.6
1.0 ( 12/15/92 v2.3 ) setting up for new semantics
1.1 ( ) actually doing it
(in-package :sparser)
;;;------------
;;; the object
;;;------------
(define-category day-of-the-month
:specializes time
:instantiates self
:binds ((month . month)
(number . number)
(day-of-the-week . weekday))
:index (:temporary :sequential-keys month number))
;;;-------
;;; rules
;;;-------
(def-cfr day-of-the-month (month number)
:form np
:referent (:instantiate-individual day-of-the-month
:with (month left-edge
number right-edge)))
(def-cfr day-of-the-month (month ordinal)
:form np
:referent (:instantiate-individual day-of-the-month
:with (month left-edge
number right-edge)))
| null | https://raw.githubusercontent.com/ddmcdonald/sparser/304bd02d0cf7337ca25c8f1d44b1d7912759460f/Sparser/code/s/grammar/model/core/time/day-in-month.lisp | lisp | -*- Mode:LISP; Syntax:Common-Lisp; Package:SPARSER -*-
copyright (c) 1992-1993,2021 David D. McDonald -- all rights reserved
File: "day-in-month"
------------
the object
------------
-------
rules
------- | copyright ( c ) 1991 Content Technologies Inc.
Module : " : time : "
version : February 2021
initiated 7/31 v1.8.6
1.0 ( 12/15/92 v2.3 ) setting up for new semantics
1.1 ( ) actually doing it
(in-package :sparser)
(define-category day-of-the-month
:specializes time
:instantiates self
:binds ((month . month)
(number . number)
(day-of-the-week . weekday))
:index (:temporary :sequential-keys month number))
(def-cfr day-of-the-month (month number)
:form np
:referent (:instantiate-individual day-of-the-month
:with (month left-edge
number right-edge)))
(def-cfr day-of-the-month (month ordinal)
:form np
:referent (:instantiate-individual day-of-the-month
:with (month left-edge
number right-edge)))
|
da0e0f67d88e287a1a8ad4e9a91438a21c703e607b914a2eb46b3f30c51917af | vseloved/cl-nlp | decision-tree.lisp | ( c ) 2015 - 2017 Vsevolod Dyomkin
(in-package #:nlp.learning)
(named-readtables:in-readtable rutilsx-readtable)
(defclass decision-tree ()
((decision-fn :accessor tree-decision-fn :initarg :decision-fn)
(decision-fn-dbg :accessor tree-decision-fn-dbg :initarg :decision-fn-dbg)
(repr :accessor tree-repr :initarg :repr)
(classes :accessor tree-classes :initarg :classes)
(max-depth :accessor tree-max-depth :initform nil :initarg :max-depth)
(min-size :accessor tree-min-size :initform 0 :initarg :min-size)))
(defclass c4.5-tree (decision-tree)
())
(defclass cart-tree (decision-tree)
())
;;; main methods
(defparameter *dtree-max-depth* 10)
(defmethod rank ((model decision-tree) fs &key classes)
(with ((rez (call (if *dtree-debug*
(tree-decision-fn-dbg model)
(tree-decision-fn model))
fs))
(has-alts (listp (second rez))))
(unless has-alts
(:= rez (list rez)))
(pairs->ht rez)))
(defmethod train ((model c4.5-tree) data
&key idx-count (idxs (range 0 (length @data#0.fs)))
classes verbose fast)
(let ((tree (tree-train 'info-gain data
:binary nil
:min-size (tree-min-size model)
:max-depth (tree-max-depth model)
:idxs idxs :idx-count idx-count
:verbose verbose
:fast fast)))
(:= @model.repr tree
@model.classes classes)
(:= @model.decision-fn (eval `(lambda (%) ,tree))
@model.decision-fn-dbg (let ((*dtree-debug* t))
(eval `(lambda (%) ,tree))))
model))
(defmethod train ((model cart-tree) data
&key idx-count (idxs (range 0 (length @data#0.fs)))
classes verbose fast)
(with ((tree (tree-train ^(- 1 (gini-split-idx %)) data
:binary t
:min-size (tree-min-size model)
:max-depth (tree-max-depth model)
:idxs idxs :idx-count idx-count
:verbose verbose
:fast fast))
(depth (cart-depth tree)))
(:= @model.repr tree
@model.classes classes)
(:= @model.decision-fn (eval (if (> depth *dtree-max-depth*)
(cart-fn tree)
`(lambda (%) ,tree)))
@model.decision-fn-dbg (if (> depth *dtree-max-depth*)
(cart-fn tree :debug t)
(let ((*dtree-debug* t))
(eval `(lambda (%) ,tree)))))
model))
(defmethod save-model ((model cart-tree) path)
(gzip-stream:with-open-gzip-file (out path :direction :output
:if-does-not-exist :create
:if-exists :supersede)
(call-next-method model out)))
(defmacro node-repr (node &rest clauses)
`(cond ((eql t ,node) "__T__")
((eql nil ,node) "__F__")
,@clauses
(t (fmt "~S" ,node))))
(defmethod save-model ((model cart-tree) (out stream))
(with (((fs ops vals) (cart->vecs @model.repr)))
(format out "~{~A~^ ~}~%" (map 'list ^(or % -1)
fs))
(format out "~{~A~^ ~}~%" (map 'list ^(case %
(eql 0)
(<= 1)
(t 2))
ops))
(format out "~{~A~^~%~}~%"
(map 'list ^(node-repr %
((listp %) (fmt "~A ~A"
(node-repr (? % 0))
(? % 1))))
vals))))
(defmethod load-model ((model cart-tree) path &key)
(gzip-stream:with-open-gzip-file (in path)
(call-next-method model in)))
(defmethod load-model ((model cart-tree) (in stream) &key)
(with ((fs (map 'vector 'parse-integer
(split #\Space (read-line in))))
(ops (map 'vector ^(case %
(0 'eql)
(1 '<=))
(mapcar 'parse-integer (split #\Space (read-line in)))))
(vals (make-array (length fs)))
(*read-eval* nil))
(dotimes (i (length fs))
(let ((val (read-line in)))
(:= (? vals i)
(if (? ops i)
(switch (val :test 'equal)
("__T__" t)
("__F__" nil)
(otherwise
(if (member (char val 0)
'(#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9 #\-))
(read-from-string val)
val)))
(unless (string= "0" val)
(with (((k v) (split #\Space val)))
(pair (cond ((string= k "__F__") nil)
((string= k "__T__") t)
(t (read-from-string k)))
(read-from-string v))))))))
(let ((tree (vecs->cart fs ops vals)))
(:= @model.repr tree
@model.decision-fn (%cart-fn fs ops vals)
@model.decision-fn-dbg (%cart-fn fs ops vals :debug t)))
model))
;;; debug
(defparameter *dtree-debug* nil)
(defun print-dtree-debug-info (idx cur op val rez)
"Format current decision of the tree indormation:
IDX - current feature, CUR - its value, OP - test operation,
VAL - test value, REZ - test result."
(format *debug-io* "~{~C~}f(~A)=~A ~A ~A => ~A~%"
(loop :repeat (if (numberp *dtree-debug*)
(:+ *dtree-debug*)
(:= *dtree-debug* 0))
:collect #\Tab)
idx cur op val rez))
;;; cart transforms
(defun cart-depth (cart)
"Depth of a decision TREE."
(cond ((atom cart) 0)
((atom (second cart)) 1)
(t (1+ (reduce 'max (mapcar 'cart-depth (cddr cart)))))))
(defun cart-fn (cart &key debug)
"Generate a decision function for a CART decision tree."
(with (((fs ops vals) (cart->vecs cart)))
(%cart-fn fs ops vals :debug debug)))
(defun %cart-fn (fs ops vals &key debug)
"Generate a decision function for a CART decision tree."
(lambda (%)
(let ((i 0))
(loop (if-it (? ops i)
(with ((val (? vals i))
(idx (? fs i))
(cur (? % idx))
(rez (call it cur val)))
(when debug (print-dtree-debug-info idx cur it val rez))
(:= i (+ (* i 2)
(if rez 1 2))))
(progn
(when debug (:= *dtree-debug* t))
(return (? vals i))))))))
(defun cart->vecs (cart)
"Produce 3 arrays (features, operations, values) from a CART tree."
(with ((depth (cart-depth cart))
(q (make-queue))
(fs (make-array (1- (expt 2 depth)) :initial-element nil))
(ops (make-array (1- (expt 2 depth)) :initial-element nil))
(vals (make-array (1- (expt 2 depth)) :initial-element 0)))
(push-queue (pair cart 0) q)
(loop :for (tree i) := (pop-queue q) :while tree :do
(when (listp tree)
(case (first tree)
(if
(with (((_ op f val) (second tree)))
(:= (? ops i) op
(? fs i) f
(? vals i) val))
(push-queue (pair (third tree) (+ (* 2 i) 1)) q)
(push-queue (pair (fourth tree) (+ (* 2 i) 2)) q))
(pair
(:= (? vals i) (rest tree))))))
(list fs
ops
vals)))
(defun vecs->cart (fs ops vals &optional (i 0))
"Produce a CART tree from 3 arrays (features, operations, values)."
(let ((f (? fs i))
(o (? ops i))
(v (? vals i)))
(if o
`(if (%= ,o ,f ,v)
,(vecs->cart fs ops vals (+ (* i 2) 1))
,(vecs->cart fs ops vals (+ (* i 2) 2)))
`(pair ,@v))))
;;; training
(defun normed-dist (data)
(with ((dist (maptab ^(length %%)
(partition-by 'ex-gold data)))
(total (reduce '+ (ht-vals dist)))
(key max (keymax dist)))
`(pair ,key ,(float (/ max total)))))
(defun tree-train (criterion data
&key (min-size 0) (depth 1) max-depth
(idxs (range 0 (length @data#0.fs)))
idx-count ; for RF classifier to sample dimensions
binary
(fast t)
verbose)
"Train a decision tree from DATA using a CRITERION function."
(format *debug-io* ".")
(cond
;; no data
((endp data) nil)
;; single class
((single (uniq (mapcar 'ex-gold data)))
`(pair ,(? data 0 'gold) 1.0))
;; no indices, min-size or max-depth reached
((or (endp idxs)
(when max-depth (>= depth max-depth))
(<= (length data) min-size))
(normed-dist data))
;; general case
(t (with ((idx binary? split-point test
(if fast
(fast-bin-split-idx criterion data
(if idx-count
(sample idxs idx-count
:with-replacement? nil)
idxs)
:verbose verbose)
(split-idx criterion data
(if idx-count
(sample idxs idx-count
:with-replacement? nil)
idxs)
:binary binary :verbose verbose))))
(cond ((null idx)
(normed-dist data))
(binary?
`(if (%= ,test ,idx ,split-point)
,@(mapcar (lambda (side)
(tree-train criterion side
:depth (1+ depth)
:max-depth max-depth
:idxs idxs
:idx-count idx-count
:min-size min-size
:fast fast
:binary binary
:verbose verbose))
(split-at split-point data idx :test test))))
for categorical data once we use the dimension ( idx )
;; we won't return to it
(t
(let ((idxs (remove idx idxs)))
`(case (? % ,idx)
,@(sort (mapcar (lambda (cat-vals)
`(,(lt cat-vals)
,(tree-train criterion (rt cat-vals)
:depth (1+ depth)
:max-depth max-depth
:idxs idxs
:idx-count idx-count
:min-size min-size
:fast fast
:verbose verbose)))
(ht->pairs (partition-by idx data)))
;; putting T case (if present) last
^(not (eql % t)) :key 'first)))))))))
(defun split-idx (criterion data idxs &key binary verbose)
"Determine the dimension of IDXS that fits the DATA best
according to CRITERION.
BINARY enforces eql/<= test (for 1-vs-many and numerical values).
Also return as other values:
- is there a binary split?
- split point
- split test (<= or eql)
- gain score"
(let ((best-gain 0)
best-idx
best-test
gains
split-point
binary?)
(dolist (idx idxs)
(flet ((@idx (ex) (? @ex.fs idx)))
(with ((vals (mapcar #'@idx data))
(numeric? nil)
(point gain
(cond
((typep (first vals) '(or float ratio))
(:= numeric? t)
(let ((left ())
(right (safe-sort data '< :key #'@idx)))
(argmax (lambda (split-point)
(appendf left
(loop :for tail :on right
:for item := (? tail 0)
:while (<= (@idx item)
split-point)
:collect item
:finally (:= right tail)))
(call criterion (list left right)))
(with ((vals (uniq vals :raw t))
(len (ht-count vals))
(vals (sort (keys vals) '<))
(i 0)
(step (/ len 100)))
(if (> len 100)
(loop :for val :in vals
:when (> (:+ i) step)
:do (:= i 0)
:and :collect val)
vals)))))
(binary
(argmax ^(call criterion (split-at % data idx))
(uniq vals)))
(t
(values nil ; there's no split-point for non-binary splits
(call criterion data :idx idx ))))))
(when verbose (format *debug-io* "~&idx=~A gain=~A~%" idx (float gain)))
(push gain gains)
(when (> gain best-gain)
(:= best-idx idx
best-gain gain
binary? (or binary numeric?)
split-point point
best-test (if numeric? '<= 'eql))))))
(unless (> (ht-count (uniq gains :raw t)) 1)
(void best-idx))
(when verbose
(with (((left right) (split-at split-point data best-idx :test best-test)))
(format *debug-io* "~&best-idx=~A gain=~A split-point=~A test=~A split=~$/~$~%"
best-idx (float best-gain) split-point best-test
(float (/ (length left) (length data)))
(float (/ (length right) (length data))))))
(values best-idx
binary?
split-point
best-test
best-gain)))
(defun fast-bin-split-idx (criterion data idxs &key verbose)
"Determine the dimension of IDXS that fits the DATA best
according to CRITERION.
Also return as other values:
- is there a binary split?
- split point
- split test (<= or eql)
- gain score"
(let ((best-gain 0)
best-idx
best-test
gains
split-point)
(dolist (idx idxs)
(flet ((@idx (ex) (? @ex.fs idx)))
(with ((numeric? (typep (@idx (first data)) '(or float ratio)))
(point gain (if numeric?
(with ((sorted (safe-sort (coerce data 'vector)
'< :key #'@idx))
(beg 0)
(end (length sorted))
(m (floor (- end beg) 2))
(mg (call criterion
(list (slice sorted 0 m)
(slice sorted m)))))
(dotimes (i (floor (log (length sorted) 2)))
(with ((l (floor (- end beg) 4))
(r (+ l m))
((lg rg) (mapcar ^(call criterion %)
`((,(slice sorted 0 l)
,(slice sorted l))
(,(slice sorted 0 r)
,(slice sorted r))))))
(cond ((< mg (min lg rg))
(return))
((< lg rg)
(:= end m))
(t
(:= beg m)))))
(values (? sorted m 'fs idx)
mg))
(argmax ^(call criterion (split-at % data idx))
(uniq data :test 'eql)))))
(when verbose
(format *debug-io* "~&idx=~A gain=~A~%" idx (float gain)))
(push gain gains)
(when (> gain best-gain)
(:= best-idx idx
best-gain gain
split-point point
best-test (if numeric? '<= 'eql))))))
(with (((&optional left right) (when best-idx
(split-at split-point data best-idx
:test best-test))))
(unless (and left right)
(void best-idx))
(when verbose
(format *debug-io* "~&best-idx=~A gain=~A split-point=~A test=~A split=~$/~$~%"
best-idx (float best-gain) split-point best-test
(when best-idx (float (/ (length left) (length data))))
(when best-idx (float (/ (length right) (length data)))))))
(values best-idx
t
split-point
best-test
best-gain)))
(defun split-at (point data idx &key (key 'ex-fs) (test 'eql))
"Split DATA at POINT in dimension IDX."
(let (left right)
(dolist (ex data)
(if (call test (? (call key ex) idx) point)
(push ex left)
(push ex right)))
(list (reverse left)
(reverse right))))
;;; split criteria
(defun info-gain (exs &key idx (key 'ex-gold))
"Info gain criterion for examples EXS either in dimension IDX or by KEY."
(if idx
(- (entropy exs :key key)
(entropy exs :idx idx :key key))
(if (some 'null exs)
0
(- (entropy (reduce 'append exs) :key key)
(entropy exs :key key :already-split? t)))))
(defun weighted-info-gain (exs split &key (key 'ex-gold))
"Weighted info gain criterion for examples EXS either
in dimension IDX or by KEY."
(/ (info-gain exs :key key)
(split-info split)))
(defun gini-idx (exs)
"Gini impurity index of examples EXS."
(let ((len (length exs)))
(- 1 (sum ^(expt (/ % len) 2)
(mapcar 'length (vals (partition-by 'ex-gold exs)))))))
(defun gini-split-idx (exs)
"Gini split index of examples EXS."
(float
(with (((data1 data2) exs)
(len1 (length data1))
(len2 (length data2))
(len (+ len1 len2)))
(+ (* (/ len1 len) (gini-idx data1))
(* (/ len2 len) (gini-idx data2))))))
;;; entropy calculations
(defun entropy (exs &key idx (key 'ex-gold) already-split?)
"Entropy calculated for examples EXS based:
- either on a given dimension IDX
- or for ALREADY-SPLIT? data
- or based on KEY selection"
(float
(cond
((atom exs) (if (member exs '(0 1)) 0
(- (+ (* exs (log exs 2))
(* (- 1 exs) (log (- 1 exs) 2))))))
(idx (let ((size (length exs)))
(sum ^(let ((len (length (rt %))))
(* (/ len size)
(entropy (/ (count t (rt %) :key key)
len))))
(pairs (partition-by idx exs)))))
(already-split?
(let ((size (sum 'length exs)))
(sum ^(* (/ (length %) size)
(entropy % :key key))
exs)))
(key (entropy (/ (count t exs :key key)
(length exs))))
(t (- (sum ^(* % (log % 2))
(remove-if 'zerop exs)))))))
(defun split-info (exs &optional idx)
"Entropy of examples EXS best split in dimension IDX."
(let ((size (if idx
(length exs)
(sum 'length exs))))
(entropy (mapcar ^(/ (length %) size)
(if idx
(vals (partition-by idx exs))
exs))
:key nil)))
;;; utils
(defmacro %= (test idx val)
"Generates a comparator function TEST to compare a given dimension IDX to VAL."
(if *dtree-debug*
(with-gensyms (cur rez)
`(with ((,cur (? % ',idx))
(,rez (,test ,cur ,val)))
(print-dtree-debug-info ',idx ,cur ',test ,val ,rez)
,rez))
`(,test (? % ',idx) ,val)))
(defun partition-by (idx-or-fn seq)
"Partition a SEQ in 2 either using a test function or a dimension
given in IDX-OR-FN."
(let ((fn (if (or (functionp idx-or-fn)
(symbolp idx-or-fn))
idx-or-fn
^(? @%.fs idx-or-fn)))
(rez #h(equal)))
(etypecase seq
(list (dolist (item seq)
(push item (? rez (call fn item)))))
(vector (dovec (item seq)
(push item (? rez (call fn item))))))
rez))
(defun all-permutations (list)
"Generate all permutations of a LIST."
(cond ((null list) nil)
((null (rest list)) (list list))
(t (loop :for element :in list
:append (mapcar ^(cons element %)
(all-permutations (remove element list)))))))
;;; simple queue utils
(defstruct queue
head tail)
(defun push-queue (item q)
(push item @q.head))
(defun pop-queue (q)
(let (non-empty)
(if @q.tail
(:= non-empty t)
(loop :for item := (pop @q.head) :while item :do
(:= non-empty t)
(push item @q.tail)))
(values (pop @q.tail)
non-empty)))
| null | https://raw.githubusercontent.com/vseloved/cl-nlp/f180b6c3c0b9a3614ae43f53a11bc500767307d0/src/learning/decision-tree.lisp | lisp | main methods
debug
cart transforms
training
for RF classifier to sample dimensions
no data
single class
no indices, min-size or max-depth reached
general case
we won't return to it
putting T case (if present) last
there's no split-point for non-binary splits
split criteria
entropy calculations
utils
simple queue utils | ( c ) 2015 - 2017 Vsevolod Dyomkin
(in-package #:nlp.learning)
(named-readtables:in-readtable rutilsx-readtable)
(defclass decision-tree ()
((decision-fn :accessor tree-decision-fn :initarg :decision-fn)
(decision-fn-dbg :accessor tree-decision-fn-dbg :initarg :decision-fn-dbg)
(repr :accessor tree-repr :initarg :repr)
(classes :accessor tree-classes :initarg :classes)
(max-depth :accessor tree-max-depth :initform nil :initarg :max-depth)
(min-size :accessor tree-min-size :initform 0 :initarg :min-size)))
(defclass c4.5-tree (decision-tree)
())
(defclass cart-tree (decision-tree)
())
(defparameter *dtree-max-depth* 10)
(defmethod rank ((model decision-tree) fs &key classes)
(with ((rez (call (if *dtree-debug*
(tree-decision-fn-dbg model)
(tree-decision-fn model))
fs))
(has-alts (listp (second rez))))
(unless has-alts
(:= rez (list rez)))
(pairs->ht rez)))
(defmethod train ((model c4.5-tree) data
&key idx-count (idxs (range 0 (length @data#0.fs)))
classes verbose fast)
(let ((tree (tree-train 'info-gain data
:binary nil
:min-size (tree-min-size model)
:max-depth (tree-max-depth model)
:idxs idxs :idx-count idx-count
:verbose verbose
:fast fast)))
(:= @model.repr tree
@model.classes classes)
(:= @model.decision-fn (eval `(lambda (%) ,tree))
@model.decision-fn-dbg (let ((*dtree-debug* t))
(eval `(lambda (%) ,tree))))
model))
(defmethod train ((model cart-tree) data
&key idx-count (idxs (range 0 (length @data#0.fs)))
classes verbose fast)
(with ((tree (tree-train ^(- 1 (gini-split-idx %)) data
:binary t
:min-size (tree-min-size model)
:max-depth (tree-max-depth model)
:idxs idxs :idx-count idx-count
:verbose verbose
:fast fast))
(depth (cart-depth tree)))
(:= @model.repr tree
@model.classes classes)
(:= @model.decision-fn (eval (if (> depth *dtree-max-depth*)
(cart-fn tree)
`(lambda (%) ,tree)))
@model.decision-fn-dbg (if (> depth *dtree-max-depth*)
(cart-fn tree :debug t)
(let ((*dtree-debug* t))
(eval `(lambda (%) ,tree)))))
model))
(defmethod save-model ((model cart-tree) path)
(gzip-stream:with-open-gzip-file (out path :direction :output
:if-does-not-exist :create
:if-exists :supersede)
(call-next-method model out)))
(defmacro node-repr (node &rest clauses)
`(cond ((eql t ,node) "__T__")
((eql nil ,node) "__F__")
,@clauses
(t (fmt "~S" ,node))))
(defmethod save-model ((model cart-tree) (out stream))
(with (((fs ops vals) (cart->vecs @model.repr)))
(format out "~{~A~^ ~}~%" (map 'list ^(or % -1)
fs))
(format out "~{~A~^ ~}~%" (map 'list ^(case %
(eql 0)
(<= 1)
(t 2))
ops))
(format out "~{~A~^~%~}~%"
(map 'list ^(node-repr %
((listp %) (fmt "~A ~A"
(node-repr (? % 0))
(? % 1))))
vals))))
(defmethod load-model ((model cart-tree) path &key)
(gzip-stream:with-open-gzip-file (in path)
(call-next-method model in)))
(defmethod load-model ((model cart-tree) (in stream) &key)
(with ((fs (map 'vector 'parse-integer
(split #\Space (read-line in))))
(ops (map 'vector ^(case %
(0 'eql)
(1 '<=))
(mapcar 'parse-integer (split #\Space (read-line in)))))
(vals (make-array (length fs)))
(*read-eval* nil))
(dotimes (i (length fs))
(let ((val (read-line in)))
(:= (? vals i)
(if (? ops i)
(switch (val :test 'equal)
("__T__" t)
("__F__" nil)
(otherwise
(if (member (char val 0)
'(#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9 #\-))
(read-from-string val)
val)))
(unless (string= "0" val)
(with (((k v) (split #\Space val)))
(pair (cond ((string= k "__F__") nil)
((string= k "__T__") t)
(t (read-from-string k)))
(read-from-string v))))))))
(let ((tree (vecs->cart fs ops vals)))
(:= @model.repr tree
@model.decision-fn (%cart-fn fs ops vals)
@model.decision-fn-dbg (%cart-fn fs ops vals :debug t)))
model))
(defparameter *dtree-debug* nil)
(defun print-dtree-debug-info (idx cur op val rez)
"Format current decision of the tree indormation:
IDX - current feature, CUR - its value, OP - test operation,
VAL - test value, REZ - test result."
(format *debug-io* "~{~C~}f(~A)=~A ~A ~A => ~A~%"
(loop :repeat (if (numberp *dtree-debug*)
(:+ *dtree-debug*)
(:= *dtree-debug* 0))
:collect #\Tab)
idx cur op val rez))
(defun cart-depth (cart)
"Depth of a decision TREE."
(cond ((atom cart) 0)
((atom (second cart)) 1)
(t (1+ (reduce 'max (mapcar 'cart-depth (cddr cart)))))))
(defun cart-fn (cart &key debug)
"Generate a decision function for a CART decision tree."
(with (((fs ops vals) (cart->vecs cart)))
(%cart-fn fs ops vals :debug debug)))
(defun %cart-fn (fs ops vals &key debug)
"Generate a decision function for a CART decision tree."
(lambda (%)
(let ((i 0))
(loop (if-it (? ops i)
(with ((val (? vals i))
(idx (? fs i))
(cur (? % idx))
(rez (call it cur val)))
(when debug (print-dtree-debug-info idx cur it val rez))
(:= i (+ (* i 2)
(if rez 1 2))))
(progn
(when debug (:= *dtree-debug* t))
(return (? vals i))))))))
(defun cart->vecs (cart)
"Produce 3 arrays (features, operations, values) from a CART tree."
(with ((depth (cart-depth cart))
(q (make-queue))
(fs (make-array (1- (expt 2 depth)) :initial-element nil))
(ops (make-array (1- (expt 2 depth)) :initial-element nil))
(vals (make-array (1- (expt 2 depth)) :initial-element 0)))
(push-queue (pair cart 0) q)
(loop :for (tree i) := (pop-queue q) :while tree :do
(when (listp tree)
(case (first tree)
(if
(with (((_ op f val) (second tree)))
(:= (? ops i) op
(? fs i) f
(? vals i) val))
(push-queue (pair (third tree) (+ (* 2 i) 1)) q)
(push-queue (pair (fourth tree) (+ (* 2 i) 2)) q))
(pair
(:= (? vals i) (rest tree))))))
(list fs
ops
vals)))
(defun vecs->cart (fs ops vals &optional (i 0))
"Produce a CART tree from 3 arrays (features, operations, values)."
(let ((f (? fs i))
(o (? ops i))
(v (? vals i)))
(if o
`(if (%= ,o ,f ,v)
,(vecs->cart fs ops vals (+ (* i 2) 1))
,(vecs->cart fs ops vals (+ (* i 2) 2)))
`(pair ,@v))))
(defun normed-dist (data)
(with ((dist (maptab ^(length %%)
(partition-by 'ex-gold data)))
(total (reduce '+ (ht-vals dist)))
(key max (keymax dist)))
`(pair ,key ,(float (/ max total)))))
(defun tree-train (criterion data
&key (min-size 0) (depth 1) max-depth
(idxs (range 0 (length @data#0.fs)))
binary
(fast t)
verbose)
"Train a decision tree from DATA using a CRITERION function."
(format *debug-io* ".")
(cond
((endp data) nil)
((single (uniq (mapcar 'ex-gold data)))
`(pair ,(? data 0 'gold) 1.0))
((or (endp idxs)
(when max-depth (>= depth max-depth))
(<= (length data) min-size))
(normed-dist data))
(t (with ((idx binary? split-point test
(if fast
(fast-bin-split-idx criterion data
(if idx-count
(sample idxs idx-count
:with-replacement? nil)
idxs)
:verbose verbose)
(split-idx criterion data
(if idx-count
(sample idxs idx-count
:with-replacement? nil)
idxs)
:binary binary :verbose verbose))))
(cond ((null idx)
(normed-dist data))
(binary?
`(if (%= ,test ,idx ,split-point)
,@(mapcar (lambda (side)
(tree-train criterion side
:depth (1+ depth)
:max-depth max-depth
:idxs idxs
:idx-count idx-count
:min-size min-size
:fast fast
:binary binary
:verbose verbose))
(split-at split-point data idx :test test))))
for categorical data once we use the dimension ( idx )
(t
(let ((idxs (remove idx idxs)))
`(case (? % ,idx)
,@(sort (mapcar (lambda (cat-vals)
`(,(lt cat-vals)
,(tree-train criterion (rt cat-vals)
:depth (1+ depth)
:max-depth max-depth
:idxs idxs
:idx-count idx-count
:min-size min-size
:fast fast
:verbose verbose)))
(ht->pairs (partition-by idx data)))
^(not (eql % t)) :key 'first)))))))))
(defun split-idx (criterion data idxs &key binary verbose)
"Determine the dimension of IDXS that fits the DATA best
according to CRITERION.
BINARY enforces eql/<= test (for 1-vs-many and numerical values).
Also return as other values:
- is there a binary split?
- split point
- split test (<= or eql)
- gain score"
(let ((best-gain 0)
best-idx
best-test
gains
split-point
binary?)
(dolist (idx idxs)
(flet ((@idx (ex) (? @ex.fs idx)))
(with ((vals (mapcar #'@idx data))
(numeric? nil)
(point gain
(cond
((typep (first vals) '(or float ratio))
(:= numeric? t)
(let ((left ())
(right (safe-sort data '< :key #'@idx)))
(argmax (lambda (split-point)
(appendf left
(loop :for tail :on right
:for item := (? tail 0)
:while (<= (@idx item)
split-point)
:collect item
:finally (:= right tail)))
(call criterion (list left right)))
(with ((vals (uniq vals :raw t))
(len (ht-count vals))
(vals (sort (keys vals) '<))
(i 0)
(step (/ len 100)))
(if (> len 100)
(loop :for val :in vals
:when (> (:+ i) step)
:do (:= i 0)
:and :collect val)
vals)))))
(binary
(argmax ^(call criterion (split-at % data idx))
(uniq vals)))
(t
(call criterion data :idx idx ))))))
(when verbose (format *debug-io* "~&idx=~A gain=~A~%" idx (float gain)))
(push gain gains)
(when (> gain best-gain)
(:= best-idx idx
best-gain gain
binary? (or binary numeric?)
split-point point
best-test (if numeric? '<= 'eql))))))
(unless (> (ht-count (uniq gains :raw t)) 1)
(void best-idx))
(when verbose
(with (((left right) (split-at split-point data best-idx :test best-test)))
(format *debug-io* "~&best-idx=~A gain=~A split-point=~A test=~A split=~$/~$~%"
best-idx (float best-gain) split-point best-test
(float (/ (length left) (length data)))
(float (/ (length right) (length data))))))
(values best-idx
binary?
split-point
best-test
best-gain)))
(defun fast-bin-split-idx (criterion data idxs &key verbose)
"Determine the dimension of IDXS that fits the DATA best
according to CRITERION.
Also return as other values:
- is there a binary split?
- split point
- split test (<= or eql)
- gain score"
(let ((best-gain 0)
best-idx
best-test
gains
split-point)
(dolist (idx idxs)
(flet ((@idx (ex) (? @ex.fs idx)))
(with ((numeric? (typep (@idx (first data)) '(or float ratio)))
(point gain (if numeric?
(with ((sorted (safe-sort (coerce data 'vector)
'< :key #'@idx))
(beg 0)
(end (length sorted))
(m (floor (- end beg) 2))
(mg (call criterion
(list (slice sorted 0 m)
(slice sorted m)))))
(dotimes (i (floor (log (length sorted) 2)))
(with ((l (floor (- end beg) 4))
(r (+ l m))
((lg rg) (mapcar ^(call criterion %)
`((,(slice sorted 0 l)
,(slice sorted l))
(,(slice sorted 0 r)
,(slice sorted r))))))
(cond ((< mg (min lg rg))
(return))
((< lg rg)
(:= end m))
(t
(:= beg m)))))
(values (? sorted m 'fs idx)
mg))
(argmax ^(call criterion (split-at % data idx))
(uniq data :test 'eql)))))
(when verbose
(format *debug-io* "~&idx=~A gain=~A~%" idx (float gain)))
(push gain gains)
(when (> gain best-gain)
(:= best-idx idx
best-gain gain
split-point point
best-test (if numeric? '<= 'eql))))))
(with (((&optional left right) (when best-idx
(split-at split-point data best-idx
:test best-test))))
(unless (and left right)
(void best-idx))
(when verbose
(format *debug-io* "~&best-idx=~A gain=~A split-point=~A test=~A split=~$/~$~%"
best-idx (float best-gain) split-point best-test
(when best-idx (float (/ (length left) (length data))))
(when best-idx (float (/ (length right) (length data)))))))
(values best-idx
t
split-point
best-test
best-gain)))
(defun split-at (point data idx &key (key 'ex-fs) (test 'eql))
"Split DATA at POINT in dimension IDX."
(let (left right)
(dolist (ex data)
(if (call test (? (call key ex) idx) point)
(push ex left)
(push ex right)))
(list (reverse left)
(reverse right))))
(defun info-gain (exs &key idx (key 'ex-gold))
"Info gain criterion for examples EXS either in dimension IDX or by KEY."
(if idx
(- (entropy exs :key key)
(entropy exs :idx idx :key key))
(if (some 'null exs)
0
(- (entropy (reduce 'append exs) :key key)
(entropy exs :key key :already-split? t)))))
(defun weighted-info-gain (exs split &key (key 'ex-gold))
"Weighted info gain criterion for examples EXS either
in dimension IDX or by KEY."
(/ (info-gain exs :key key)
(split-info split)))
(defun gini-idx (exs)
"Gini impurity index of examples EXS."
(let ((len (length exs)))
(- 1 (sum ^(expt (/ % len) 2)
(mapcar 'length (vals (partition-by 'ex-gold exs)))))))
(defun gini-split-idx (exs)
"Gini split index of examples EXS."
(float
(with (((data1 data2) exs)
(len1 (length data1))
(len2 (length data2))
(len (+ len1 len2)))
(+ (* (/ len1 len) (gini-idx data1))
(* (/ len2 len) (gini-idx data2))))))
(defun entropy (exs &key idx (key 'ex-gold) already-split?)
"Entropy calculated for examples EXS based:
- either on a given dimension IDX
- or for ALREADY-SPLIT? data
- or based on KEY selection"
(float
(cond
((atom exs) (if (member exs '(0 1)) 0
(- (+ (* exs (log exs 2))
(* (- 1 exs) (log (- 1 exs) 2))))))
(idx (let ((size (length exs)))
(sum ^(let ((len (length (rt %))))
(* (/ len size)
(entropy (/ (count t (rt %) :key key)
len))))
(pairs (partition-by idx exs)))))
(already-split?
(let ((size (sum 'length exs)))
(sum ^(* (/ (length %) size)
(entropy % :key key))
exs)))
(key (entropy (/ (count t exs :key key)
(length exs))))
(t (- (sum ^(* % (log % 2))
(remove-if 'zerop exs)))))))
(defun split-info (exs &optional idx)
"Entropy of examples EXS best split in dimension IDX."
(let ((size (if idx
(length exs)
(sum 'length exs))))
(entropy (mapcar ^(/ (length %) size)
(if idx
(vals (partition-by idx exs))
exs))
:key nil)))
(defmacro %= (test idx val)
"Generates a comparator function TEST to compare a given dimension IDX to VAL."
(if *dtree-debug*
(with-gensyms (cur rez)
`(with ((,cur (? % ',idx))
(,rez (,test ,cur ,val)))
(print-dtree-debug-info ',idx ,cur ',test ,val ,rez)
,rez))
`(,test (? % ',idx) ,val)))
(defun partition-by (idx-or-fn seq)
"Partition a SEQ in 2 either using a test function or a dimension
given in IDX-OR-FN."
(let ((fn (if (or (functionp idx-or-fn)
(symbolp idx-or-fn))
idx-or-fn
^(? @%.fs idx-or-fn)))
(rez #h(equal)))
(etypecase seq
(list (dolist (item seq)
(push item (? rez (call fn item)))))
(vector (dovec (item seq)
(push item (? rez (call fn item))))))
rez))
(defun all-permutations (list)
"Generate all permutations of a LIST."
(cond ((null list) nil)
((null (rest list)) (list list))
(t (loop :for element :in list
:append (mapcar ^(cons element %)
(all-permutations (remove element list)))))))
(defstruct queue
head tail)
(defun push-queue (item q)
(push item @q.head))
(defun pop-queue (q)
(let (non-empty)
(if @q.tail
(:= non-empty t)
(loop :for item := (pop @q.head) :while item :do
(:= non-empty t)
(push item @q.tail)))
(values (pop @q.tail)
non-empty)))
|
9f2561cb139fcf5b624ca6228c537a362d7715e627501be51ee958bb8f07dad3 | openmusic-project/openmusic | cffi-abcl.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
cffi-abcl.lisp --- CFFI - SYS implementation for ABCL / JNA .
;;;
Copyright ( C ) 2009 ,
Copyright ( C ) 2012 , < >
;;;
;;; Permission is hereby granted, free of charge, to any person
;;; obtaining a copy of this software and associated documentation
files ( the " Software " ) , to deal in the Software without
;;; restriction, including without limitation the rights to use, copy,
;;; modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software , and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software .
;;;
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;;; DEALINGS IN THE SOFTWARE.
;;;
This implementation requires the Java Native Access ( JNA ) library .
;;; </>
;;;
JNA may be automatically loaded into the current JVM process from
;;; abcl-1.1.0-dev via the contrib mechanism.
(eval-when (:compile-toplevel :load-toplevel :execute)
(require 'abcl-contrib)
(require 'jna)
(require 'jss))
;;; This is a preliminary version that will have to be cleaned up,
optimized , etc . Nevertheless , it passes all of the relevant CFFI
;;; tests except MAKE-POINTER.HIGH. Shareable Vectors are not
;;; implemented yet.
# Administrivia
(defpackage #:cffi-sys
(:use #:cl #:java)
(:import-from #:alexandria #:hash-table-values #:length= #:format-symbol)
(:export
#:canonicalize-symbol-name-case
#:foreign-pointer
#:pointerp
#:pointer-eq
#:null-pointer
#:null-pointer-p
#:inc-pointer
#:make-pointer
#:pointer-address
#:%foreign-alloc
#:foreign-free
#:with-foreign-pointer
#:%foreign-funcall
#:%foreign-funcall-pointer
#:%foreign-type-alignment
#:%foreign-type-size
#:%load-foreign-library
#:%close-foreign-library
#:native-namestring
#:%mem-ref
#:%mem-set
;; #:make-shareable-byte-vector
;; #:with-pointer-to-vector-data
#:%foreign-symbol-pointer
#:%defcallback
#:%callback
#:with-pointer-to-vector-data
#:make-shareable-byte-vector))
(in-package #:cffi-sys)
# Loading and Closing Foreign Libraries
(defparameter *loaded-libraries* (make-hash-table))
(defun %load-foreign-library (name path)
"Load a foreign library, signals a simple error on failure."
(flet ((load-and-register (name path)
(let ((lib (jstatic "getInstance" "com.sun.jna.NativeLibrary" path)))
(setf (gethash name *loaded-libraries*) lib)
lib))
(foreign-library-type-p (type)
(find type '("so" "dll" "dylib") :test #'string=))
(java-error (e)
(error (jcall (jmethod "java.lang.Exception" "getMessage")
(java-exception-cause e)))))
(handler-case
(load-and-register name path)
(java-exception (e)
From JNA
;; ``[The name] can be short form (e.g. "c"), an explicit
;; version (e.g. "libc.so.6"), or the full path to the library
;; (e.g. "/lib/libc.so.6")''
;;
;; Try to deal with the occurance "libXXX" and "libXXX.so" as
;; "libXXX.so.6" and "XXX" should have succesfully loaded.
(let ((p (pathname path)))
(if (and (not (pathname-directory p))
(= (search "lib" (pathname-name p)) 0))
(let ((short-name (if (foreign-library-type-p (pathname-type p))
(subseq (pathname-name p) 3)
(pathname-name p))))
(handler-case
(load-and-register name short-name)
(java-exception (e) (java-error e))))
(java-error e)))))))
;;; FIXME. Should remove libraries from the hash table.
(defun %close-foreign-library (handle)
"Closes a foreign library."
#+#:ignore (setf *loaded-libraries* (remove handle *loaded-libraries*))
(jcall (jmethod "com.sun.jna.NativeLibrary" "dispose") handle))
;;;
(defun private-jfield (class-name field-name instance)
(let ((field (find field-name
(jcall (jmethod "java.lang.Class" "getDeclaredFields")
(jclass class-name))
:key #'jfield-name
:test #'string=)))
(jcall (jmethod "java.lang.reflect.Field" "setAccessible" "boolean")
field +true+)
(jcall (jmethod "java.lang.reflect.Field" "get" "java.lang.Object")
field instance)))
;;; XXX: doesn't match jmethod-arguments.
(defun private-jmethod (class-name method-name)
(let ((method (find method-name
(jcall (jmethod "java.lang.Class" "getDeclaredMethods")
(jclass class-name))
:key #'jmethod-name
:test #'string=)))
(jcall (jmethod "java.lang.reflect.Method" "setAccessible" "boolean")
method +true+)
method))
(defun private-jconstructor (class-name &rest params)
(let* ((param-classes (mapcar #'jclass params))
(cons (find-if (lambda (x &aux (cons-params (jconstructor-params x)))
(and (length= param-classes cons-params)
(loop for param in param-classes
and param-x across cons-params
always (string= (jclass-name param)
(jclass-name param-x)))))
(jcall (jmethod "java.lang.Class"
"getDeclaredConstructors")
(jclass class-name)))))
(jcall (jmethod "java.lang.reflect.Constructor" "setAccessible" "boolean")
cons +true+)
cons))
;;;# Symbol Case
(defun canonicalize-symbol-name-case (name)
(string-upcase name))
;;;# Pointers
(deftype foreign-pointer ()
'(satisfies pointerp))
(defun pointerp (ptr)
"Return true if PTR is a foreign pointer."
(let ((jclass (jclass-of ptr)))
(when jclass
(jclass-superclass-p (jclass "com.sun.jna.Pointer") jclass))))
(defun make-pointer (address)
"Return a pointer pointing to ADDRESS."
(jnew (private-jconstructor "com.sun.jna.Pointer" "long") address))
(defun pointer-address (pointer)
"Return the address pointed to by PTR."
(private-jfield "com.sun.jna.Pointer" "peer" pointer))
(defun pointer-eq (ptr1 ptr2)
"Return true if PTR1 and PTR2 point to the same address."
(= (pointer-address ptr1) (pointer-address ptr2)))
(defun null-pointer ()
"Construct and return a null pointer."
(make-pointer 0))
(defun null-pointer-p (ptr)
"Return true if PTR is a null pointer."
(and (pointerp ptr)
(zerop (pointer-address ptr))))
(defun inc-pointer (ptr offset)
"Return a fresh pointer pointing OFFSET bytes past PTR."
(make-pointer (+ (pointer-address ptr) offset)))
;;;# Allocation
(defun %foreign-alloc (size)
"Allocate SIZE bytes on the heap and return a pointer."
(make-pointer
(jcall (private-jmethod "com.sun.jna.Memory" "malloc")
nil size)))
(defun foreign-free (ptr)
"Free a PTR allocated by FOREIGN-ALLOC."
(jcall (private-jmethod "com.sun.jna.Memory" "free")
nil (pointer-address ptr)))
;;; TODO: stack allocation.
(defmacro with-foreign-pointer ((var size &optional size-var) &body body)
"Bind VAR to SIZE bytes of foreign memory during BODY. The pointer
in VAR is invalid beyond the dynamic extent of BODY, and may be
stack-allocated if supported by the implementation. If SIZE-VAR is
supplied, it will be bound to SIZE during BODY."
(unless size-var
(setf size-var (gensym "SIZE")))
`(let* ((,size-var ,size)
(,var (%foreign-alloc ,size-var)))
(unwind-protect
(progn ,@body)
(foreign-free ,var))))
;;;# Shareable Vectors
;;;
;;; This interface is very experimental. WITH-POINTER-TO-VECTOR-DATA
;;; should be defined to perform a copy-in/copy-out if the Lisp
;;; implementation can't do this.
(defun make-shareable-byte-vector (size)
"Create a Lisp vector of SIZE bytes can passed to
WITH-POINTER-TO-VECTOR-DATA."
(make-array size :element-type '(unsigned-byte 8)))
(defun copy-to-foreign-vector (vector foreign-pointer)
(loop for i below (length vector)
do (%mem-set (aref vector i) foreign-pointer :char
i)))
(defun copy-from-foreign-vector (vector foreign-pointer)
(loop for i below (length vector)
do (setf (aref vector i)
(%mem-ref foreign-pointer :char i))))
(defmacro with-pointer-to-vector-data ((ptr-var vector) &body body)
"Bind PTR-VAR to a foreign pointer to the data in VECTOR."
(let ((vector-sym (gensym "VECTOR")))
`(let ((,vector-sym ,vector))
(with-foreign-pointer (,ptr-var (length ,vector-sym))
(copy-to-foreign-vector ,vector-sym ,ptr-var)
(unwind-protect
(progn ,@body)
(copy-from-foreign-vector ,vector-sym ,ptr-var))))))
;;;# Dereferencing
(defun foreign-type-to-java-class (type)
(jclass
(ecase type
((:int :unsigned-int) "java.lang.Integer")
((:long :unsigned-long) "com.sun.jna.NativeLong")
((:long-long :unsigned-long-long) "java.lang.Long")
(:pointer "com.sun.jna.Pointer") ;; void * is pointer?
(:float "java.lang.Float")
(:double "java.lang.Double")
((:char :unsigned-char) "java.lang.Byte")
((:short :unsigned-short) "java.lang.Short"))))
(defun %foreign-type-size (type)
"Return the size in bytes of a foreign type."
(jstatic "getNativeSize" "com.sun.jna.Native"
(foreign-type-to-java-class type)))
FIXME .
(defun %foreign-type-alignment (type)
"Return the alignment in bytes of a foreign type."
(%foreign-type-size type))
(defun unsigned-type-p (type)
(case type
((:unsigned-char
:unsigned-int
:unsigned-short
:unsigned-long
:unsigned-long-long) t)
(t nil)))
(defun jna-getter (type)
(ecase type
((:char :unsigned-char) "getByte")
(:double "getDouble")
(:float "getFloat")
((:int :unsigned-int) "getInt")
((:long :unsigned-long) "getNativeLong")
((:long-long :unsigned-long-long) "getLong")
(:pointer "getPointer")
((:short :unsigned-short) "getShort")))
(defun lispify-value (value type)
(when (and (eq type :pointer) (or (null value) (eq +null+ value)))
(return-from lispify-value (null-pointer)))
(when (or (eq type :long) (eq type :unsigned-long))
(setq value (jcall (jmethod "com.sun.jna.NativeLong" "longValue") value)))
(let ((bit-size (* 8 (%foreign-type-size type))))
(if (and (unsigned-type-p type) (logbitp (1- bit-size) value))
(lognot (logxor value (1- (expt 2 bit-size))))
value)))
(defun %mem-ref (ptr type &optional (offset 0))
(lispify-value
(jcall (jmethod "com.sun.jna.Pointer" (jna-getter type) "long")
ptr offset)
type))
(defun jna-setter (type)
(ecase type
((:char :unsigned-char) "setByte")
(:double "setDouble")
(:float "setFloat")
((:int :unsigned-int) "setInt")
((:long :unsigned-long) "setNativeLong")
((:long-long :unsigned-long-long) "setLong")
(:pointer "setPointer")
((:short :unsigned-short) "setShort")))
(defun jna-setter-arg-type (type)
(ecase type
((:char :unsigned-char) "byte")
(:double "double")
(:float "float")
((:int :unsigned-int) "int")
((:long :unsigned-long) "com.sun.jna.NativeLong")
((:long-long :unsigned-long-long) "long")
(:pointer "com.sun.jna.Pointer")
((:short :unsigned-short) "short")))
(defun %mem-set (value ptr type &optional (offset 0))
(let* ((bit-size (* 8 (%foreign-type-size type)))
(val (if (and (unsigned-type-p type) (logbitp (1- bit-size) value))
(lognot (logxor value (1- (expt 2 bit-size))))
value)))
(jcall (jmethod "com.sun.jna.Pointer"
(jna-setter type) "long" (jna-setter-arg-type type))
ptr
offset
(if (or (eq type :long) (eq type :unsigned-long))
(jnew (jconstructor "com.sun.jna.NativeLong" "long") val)
val)))
value)
;;;# Foreign Globals
(defun %foreign-symbol-pointer (name library)
"Returns a pointer to a foreign symbol NAME."
(flet ((find-it (library)
(ignore-errors
(make-pointer
(jcall
(private-jmethod "com.sun.jna.NativeLibrary" "getSymbolAddress")
library name)))))
(if (eq library :default)
(or (find-it
(jstatic "getProcess" "com.sun.jna.NativeLibrary"))
;; The above should find it, but I'm not exactly sure, so
;; let's still do it manually just in case.
(loop for lib being the hash-values of *loaded-libraries*
thereis (find-it lib)))
(find-it (gethash library *loaded-libraries*)))))
;;;# Calling Foreign Functions
(defun find-foreign-function (name library)
(flet ((find-it (library)
(ignore-errors
(jcall (jmethod "com.sun.jna.NativeLibrary" "getFunction"
"java.lang.String")
library name))))
(if (eq library :default)
(or (find-it
(jstatic "getProcess" "com.sun.jna.NativeLibrary"))
;; The above should find it, but I'm not exactly sure, so
;; let's still do it manually just in case.
(loop for lib being the hash-values of *loaded-libraries*
thereis (find-it lib)))
(find-it (gethash library *loaded-libraries*)))))
(defun convert-calling-convention (convention)
(ecase convention
(:stdcall "ALT_CONVENTION")
(:cdecl "C_CONVENTION")))
(defun make-function-pointer (pointer convention)
(jnew (private-jconstructor "com.sun.jna.Function"
"com.sun.jna.Pointer" "int")
pointer
(jfield "com.sun.jna.Function"
(convert-calling-convention convention))))
(defun lisp-value-to-java (value foreign-type)
(if (eq foreign-type :pointer)
value
(jnew (ecase foreign-type
((:int :unsigned-int) (jconstructor "java.lang.Integer" "int"))
((:long-long :unsigned-long-long)
(jconstructor "java.lang.Long" "long"))
((:long :unsigned-long)
(jconstructor "com.sun.jna.NativeLong" "long"))
((:short :unsigned-short) (jconstructor "java.lang.Short" "short"))
((:char :unsigned-char) (jconstructor "java.lang.Byte" "byte"))
(:float (jconstructor "java.lang.Float" "float"))
(:double (jconstructor "java.lang.Double" "double")))
value)))
(defun %%foreign-funcall (function args arg-types return-type)
(let ((jargs (jnew-array "java.lang.Object" (length args))))
(loop for arg in args and type in arg-types and i from 0
do (setf (jarray-ref jargs i)
(lisp-value-to-java arg type)))
(if (eq return-type :void)
(progn
(jcall (jmethod "com.sun.jna.Function" "invoke" "[Ljava.lang.Object;")
function jargs)
(values))
(lispify-value
(jcall (jmethod "com.sun.jna.Function" "invoke"
"java.lang.Class" "[Ljava.lang.Object;")
function
(foreign-type-to-java-class return-type)
jargs)
return-type))))
(defun foreign-funcall-type-and-args (args)
(let ((return-type :void))
(loop for (type arg) on args by #'cddr
if arg collect type into types
and collect arg into fargs
else do (setf return-type type)
finally (return (values types fargs return-type)))))
(defmacro %foreign-funcall (name args &key library convention)
(declare (ignore convention))
(multiple-value-bind (types fargs rettype)
(foreign-funcall-type-and-args args)
`(%%foreign-funcall (find-foreign-function ',name ',library)
(list ,@fargs) ',types ',rettype)))
(defmacro %foreign-funcall-pointer (ptr args &key convention)
(multiple-value-bind (types fargs rettype)
(foreign-funcall-type-and-args args)
`(%%foreign-funcall (make-function-pointer ,ptr ',convention)
(list ,@fargs) ',types ',rettype)))
;;;# Callbacks
(defun foreign-to-callback-type (type)
(ecase type
((:int :unsigned-int)
:int)
((:long :unsigned-long)
(jvm::make-jvm-class-name "com.sun.jna.NativeLong"))
((:long-long :unsigned-long-long)
(jvm::make-jvm-class-name "java.lang.Long"))
(:pointer
(jvm::make-jvm-class-name "com.sun.jna.Pointer"))
(:float
:float)
(:double
:double)
((:char :unsigned-char)
:int)
((:short :unsigned-short)
:int)
(:wchar_t
:int)
(:void
:void)))
(defvar *callbacks* (make-hash-table))
(defmacro convert-args-to-lisp-values (arg-names &rest body)
(let ((gensym-args (loop for name in arg-names
collect (format-symbol t '#:callback-arg-~a- name))))
`(lambda (,@gensym-args)
(let ,(loop for arg in arg-names
for gensym-arg in gensym-args
collecting `(,arg (if (typep ,gensym-arg 'java:java-object)
(java:jobject-lisp-value ,gensym-arg)
,gensym-arg)))
,body))))
(defmacro %defcallback (name return-type arg-names arg-types body
&key convention)
(declare (ignore convention)) ;; I'm always up for ignoring convention, but this is probably wrong.
`(setf (gethash ',name *callbacks*)
(jinterface-implementation
(ensure-callback-interface ',return-type ',arg-types)
"callback"
`,(convert-args-to-lisp-values ,arg-names ,@body))))
;; (lambda (,@arg-names) ,body))))
(jvm::define-class-name +callback-object+ "com.sun.jna.Callback")
(defconstant
+dynamic-callback-package+
"org/armedbear/jna/dynamic/callbacks"
"The slash-delimited Java package in which we create classes dynamically to specify callback interfaces.")
(defun ensure-callback-interface (returns args)
"Ensure that the jvm interface for the callback exists in the current JVM.
Returns the fully dot qualified name of the interface."
(let* ((jvm-returns (foreign-to-callback-type returns))
(jvm-args (mapcar #'foreign-to-callback-type args))
(interface-name (qualified-callback-interface-classname jvm-returns jvm-args)))
(handler-case
(jss:find-java-class interface-name)
(java-exception (e)
(when (jinstance-of-p (java:java-exception-cause e)
"java.lang.ClassNotFoundException")
(let ((interface-class-bytes (%define-jna-callback-interface jvm-returns jvm-args))
(simple-interface-name (callback-interface-classname jvm-returns jvm-args)))
(load-class interface-name interface-class-bytes)))))
interface-name))
(defun qualified-callback-interface-classname (returns args)
(format nil "~A.~A"
(substitute #\. #\/ +dynamic-callback-package+)
(callback-interface-classname returns args)))
(defun callback-interface-classname (returns args)
(flet ((stringify (thing)
(typecase thing
(jvm::jvm-class-name
(substitute #\_ #\/
(jvm::class-name-internal thing)))
(t (string thing)))))
(format nil "~A__~{~A~^__~}"
(stringify returns)
(mapcar #'stringify args))))
(defun %define-jna-callback-interface (returns args)
"Returns the Java byte[] array of a class representing a Java
interface descending form +CALLBACK-OBJECT+ which contains the
single function 'callback' which takes ARGS returning RETURNS.
The fully qualified dotted name of the generated class is returned as
the second value."
(let ((name (callback-interface-classname returns args)))
(values
(define-java-interface name +dynamic-callback-package+
`(("callback" ,returns ,args))
`(,+callback-object+))
(qualified-callback-interface-classname returns args))))
(defun define-java-interface (name package methods
&optional (superinterfaces nil))
"Returns the bytes of the Java class interface called NAME in PACKAGE with METHODS.
METHODS is a list of (NAME RETURN-TYPE (ARG-TYPES)) entries. NAME is
a string. The values of RETURN-TYPE and the list of ARG-TYPES for the
defined method follow the are either references to Java objects as
created by JVM::MAKE-JVM-CLASS-NAME, or keywords representing Java
primtive types as contained in JVM::MAP-PRIMITIVE-TYPE.
SUPERINTERFACES optionally contains a list of interfaces that this
interface extends specified as fully qualifed dotted Java names."
(let* ((class-name-string (format nil "~A/~A" package name))
(class-name (jvm::make-jvm-class-name class-name-string))
(class (jvm::make-class-interface-file class-name)))
(dolist (superinterface superinterfaces)
(jvm::class-add-superinterface
class
(if (typep superinterface 'jvm::jvm-class-name)
superinterface
(jvm::make-jvm-class-name superinterface))))
(dolist (method methods)
(let ((name (first method))
(returns (second method))
(args (third method)))
(jvm::class-add-method
class
(jvm::make-jvm-method name returns args
:flags '(:public :abstract)))))
(jvm::finalize-class-file class)
(let ((s (sys::%make-byte-array-output-stream)))
(jvm::write-class-file class s)
(sys::%get-output-stream-bytes s))))
(defun load-class (name bytes)
"Load the byte[] array BYTES as a Java class called NAME."
(#"loadClassFromByteArray" java::*classloader* name bytes))
;;; Test function: unused in CFFI
(defun write-class (class-bytes pathname)
"Write the Java byte[] array CLASS-BYTES to PATHNAME."
(with-open-file (stream pathname
:direction :output
:element-type '(signed-byte 8))
(dotimes (i (jarray-length class-bytes))
(write-byte (jarray-ref class-bytes i) stream))))
(defun %callback (name)
(or (#"getFunctionPointer" 'com.sun.jna.CallbackReference
(gethash name *callbacks*))
(error "Undefined callback: ~S" name)))
(defun native-namestring (pathname)
(namestring pathname))
| null | https://raw.githubusercontent.com/openmusic-project/openmusic/9560c064512a1598cd57bcc9f0151c0815178e6f/OPENMUSIC/code/api/foreign-interface/ffi/CFFI/src/cffi-abcl.lisp | lisp | -*- Mode: lisp; indent-tabs-mode: nil -*-
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
</>
abcl-1.1.0-dev via the contrib mechanism.
This is a preliminary version that will have to be cleaned up,
tests except MAKE-POINTER.HIGH. Shareable Vectors are not
implemented yet.
#:make-shareable-byte-vector
#:with-pointer-to-vector-data
``[The name] can be short form (e.g. "c"), an explicit
version (e.g. "libc.so.6"), or the full path to the library
(e.g. "/lib/libc.so.6")''
Try to deal with the occurance "libXXX" and "libXXX.so" as
"libXXX.so.6" and "XXX" should have succesfully loaded.
FIXME. Should remove libraries from the hash table.
XXX: doesn't match jmethod-arguments.
# Symbol Case
# Pointers
# Allocation
TODO: stack allocation.
# Shareable Vectors
This interface is very experimental. WITH-POINTER-TO-VECTOR-DATA
should be defined to perform a copy-in/copy-out if the Lisp
implementation can't do this.
# Dereferencing
void * is pointer?
# Foreign Globals
The above should find it, but I'm not exactly sure, so
let's still do it manually just in case.
# Calling Foreign Functions
The above should find it, but I'm not exactly sure, so
let's still do it manually just in case.
# Callbacks
I'm always up for ignoring convention, but this is probably wrong.
(lambda (,@arg-names) ,body))))
Test function: unused in CFFI | cffi-abcl.lisp --- CFFI - SYS implementation for ABCL / JNA .
Copyright ( C ) 2009 ,
Copyright ( C ) 2012 , < >
files ( the " Software " ) , to deal in the Software without
of the Software , and to permit persons to whom the Software is
included in all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
This implementation requires the Java Native Access ( JNA ) library .
JNA may be automatically loaded into the current JVM process from
(eval-when (:compile-toplevel :load-toplevel :execute)
(require 'abcl-contrib)
(require 'jna)
(require 'jss))
optimized , etc . Nevertheless , it passes all of the relevant CFFI
# Administrivia
(defpackage #:cffi-sys
(:use #:cl #:java)
(:import-from #:alexandria #:hash-table-values #:length= #:format-symbol)
(:export
#:canonicalize-symbol-name-case
#:foreign-pointer
#:pointerp
#:pointer-eq
#:null-pointer
#:null-pointer-p
#:inc-pointer
#:make-pointer
#:pointer-address
#:%foreign-alloc
#:foreign-free
#:with-foreign-pointer
#:%foreign-funcall
#:%foreign-funcall-pointer
#:%foreign-type-alignment
#:%foreign-type-size
#:%load-foreign-library
#:%close-foreign-library
#:native-namestring
#:%mem-ref
#:%mem-set
#:%foreign-symbol-pointer
#:%defcallback
#:%callback
#:with-pointer-to-vector-data
#:make-shareable-byte-vector))
(in-package #:cffi-sys)
# Loading and Closing Foreign Libraries
(defparameter *loaded-libraries* (make-hash-table))
(defun %load-foreign-library (name path)
"Load a foreign library, signals a simple error on failure."
(flet ((load-and-register (name path)
(let ((lib (jstatic "getInstance" "com.sun.jna.NativeLibrary" path)))
(setf (gethash name *loaded-libraries*) lib)
lib))
(foreign-library-type-p (type)
(find type '("so" "dll" "dylib") :test #'string=))
(java-error (e)
(error (jcall (jmethod "java.lang.Exception" "getMessage")
(java-exception-cause e)))))
(handler-case
(load-and-register name path)
(java-exception (e)
From JNA
(let ((p (pathname path)))
(if (and (not (pathname-directory p))
(= (search "lib" (pathname-name p)) 0))
(let ((short-name (if (foreign-library-type-p (pathname-type p))
(subseq (pathname-name p) 3)
(pathname-name p))))
(handler-case
(load-and-register name short-name)
(java-exception (e) (java-error e))))
(java-error e)))))))
(defun %close-foreign-library (handle)
"Closes a foreign library."
#+#:ignore (setf *loaded-libraries* (remove handle *loaded-libraries*))
(jcall (jmethod "com.sun.jna.NativeLibrary" "dispose") handle))
(defun private-jfield (class-name field-name instance)
(let ((field (find field-name
(jcall (jmethod "java.lang.Class" "getDeclaredFields")
(jclass class-name))
:key #'jfield-name
:test #'string=)))
(jcall (jmethod "java.lang.reflect.Field" "setAccessible" "boolean")
field +true+)
(jcall (jmethod "java.lang.reflect.Field" "get" "java.lang.Object")
field instance)))
(defun private-jmethod (class-name method-name)
(let ((method (find method-name
(jcall (jmethod "java.lang.Class" "getDeclaredMethods")
(jclass class-name))
:key #'jmethod-name
:test #'string=)))
(jcall (jmethod "java.lang.reflect.Method" "setAccessible" "boolean")
method +true+)
method))
(defun private-jconstructor (class-name &rest params)
(let* ((param-classes (mapcar #'jclass params))
(cons (find-if (lambda (x &aux (cons-params (jconstructor-params x)))
(and (length= param-classes cons-params)
(loop for param in param-classes
and param-x across cons-params
always (string= (jclass-name param)
(jclass-name param-x)))))
(jcall (jmethod "java.lang.Class"
"getDeclaredConstructors")
(jclass class-name)))))
(jcall (jmethod "java.lang.reflect.Constructor" "setAccessible" "boolean")
cons +true+)
cons))
(defun canonicalize-symbol-name-case (name)
(string-upcase name))
(deftype foreign-pointer ()
'(satisfies pointerp))
(defun pointerp (ptr)
"Return true if PTR is a foreign pointer."
(let ((jclass (jclass-of ptr)))
(when jclass
(jclass-superclass-p (jclass "com.sun.jna.Pointer") jclass))))
(defun make-pointer (address)
"Return a pointer pointing to ADDRESS."
(jnew (private-jconstructor "com.sun.jna.Pointer" "long") address))
(defun pointer-address (pointer)
"Return the address pointed to by PTR."
(private-jfield "com.sun.jna.Pointer" "peer" pointer))
(defun pointer-eq (ptr1 ptr2)
"Return true if PTR1 and PTR2 point to the same address."
(= (pointer-address ptr1) (pointer-address ptr2)))
(defun null-pointer ()
"Construct and return a null pointer."
(make-pointer 0))
(defun null-pointer-p (ptr)
"Return true if PTR is a null pointer."
(and (pointerp ptr)
(zerop (pointer-address ptr))))
(defun inc-pointer (ptr offset)
"Return a fresh pointer pointing OFFSET bytes past PTR."
(make-pointer (+ (pointer-address ptr) offset)))
(defun %foreign-alloc (size)
"Allocate SIZE bytes on the heap and return a pointer."
(make-pointer
(jcall (private-jmethod "com.sun.jna.Memory" "malloc")
nil size)))
(defun foreign-free (ptr)
"Free a PTR allocated by FOREIGN-ALLOC."
(jcall (private-jmethod "com.sun.jna.Memory" "free")
nil (pointer-address ptr)))
(defmacro with-foreign-pointer ((var size &optional size-var) &body body)
"Bind VAR to SIZE bytes of foreign memory during BODY. The pointer
in VAR is invalid beyond the dynamic extent of BODY, and may be
stack-allocated if supported by the implementation. If SIZE-VAR is
supplied, it will be bound to SIZE during BODY."
(unless size-var
(setf size-var (gensym "SIZE")))
`(let* ((,size-var ,size)
(,var (%foreign-alloc ,size-var)))
(unwind-protect
(progn ,@body)
(foreign-free ,var))))
(defun make-shareable-byte-vector (size)
"Create a Lisp vector of SIZE bytes can passed to
WITH-POINTER-TO-VECTOR-DATA."
(make-array size :element-type '(unsigned-byte 8)))
(defun copy-to-foreign-vector (vector foreign-pointer)
(loop for i below (length vector)
do (%mem-set (aref vector i) foreign-pointer :char
i)))
(defun copy-from-foreign-vector (vector foreign-pointer)
(loop for i below (length vector)
do (setf (aref vector i)
(%mem-ref foreign-pointer :char i))))
(defmacro with-pointer-to-vector-data ((ptr-var vector) &body body)
"Bind PTR-VAR to a foreign pointer to the data in VECTOR."
(let ((vector-sym (gensym "VECTOR")))
`(let ((,vector-sym ,vector))
(with-foreign-pointer (,ptr-var (length ,vector-sym))
(copy-to-foreign-vector ,vector-sym ,ptr-var)
(unwind-protect
(progn ,@body)
(copy-from-foreign-vector ,vector-sym ,ptr-var))))))
(defun foreign-type-to-java-class (type)
(jclass
(ecase type
((:int :unsigned-int) "java.lang.Integer")
((:long :unsigned-long) "com.sun.jna.NativeLong")
((:long-long :unsigned-long-long) "java.lang.Long")
(:float "java.lang.Float")
(:double "java.lang.Double")
((:char :unsigned-char) "java.lang.Byte")
((:short :unsigned-short) "java.lang.Short"))))
(defun %foreign-type-size (type)
"Return the size in bytes of a foreign type."
(jstatic "getNativeSize" "com.sun.jna.Native"
(foreign-type-to-java-class type)))
FIXME .
(defun %foreign-type-alignment (type)
"Return the alignment in bytes of a foreign type."
(%foreign-type-size type))
(defun unsigned-type-p (type)
(case type
((:unsigned-char
:unsigned-int
:unsigned-short
:unsigned-long
:unsigned-long-long) t)
(t nil)))
(defun jna-getter (type)
(ecase type
((:char :unsigned-char) "getByte")
(:double "getDouble")
(:float "getFloat")
((:int :unsigned-int) "getInt")
((:long :unsigned-long) "getNativeLong")
((:long-long :unsigned-long-long) "getLong")
(:pointer "getPointer")
((:short :unsigned-short) "getShort")))
(defun lispify-value (value type)
(when (and (eq type :pointer) (or (null value) (eq +null+ value)))
(return-from lispify-value (null-pointer)))
(when (or (eq type :long) (eq type :unsigned-long))
(setq value (jcall (jmethod "com.sun.jna.NativeLong" "longValue") value)))
(let ((bit-size (* 8 (%foreign-type-size type))))
(if (and (unsigned-type-p type) (logbitp (1- bit-size) value))
(lognot (logxor value (1- (expt 2 bit-size))))
value)))
(defun %mem-ref (ptr type &optional (offset 0))
(lispify-value
(jcall (jmethod "com.sun.jna.Pointer" (jna-getter type) "long")
ptr offset)
type))
(defun jna-setter (type)
(ecase type
((:char :unsigned-char) "setByte")
(:double "setDouble")
(:float "setFloat")
((:int :unsigned-int) "setInt")
((:long :unsigned-long) "setNativeLong")
((:long-long :unsigned-long-long) "setLong")
(:pointer "setPointer")
((:short :unsigned-short) "setShort")))
(defun jna-setter-arg-type (type)
(ecase type
((:char :unsigned-char) "byte")
(:double "double")
(:float "float")
((:int :unsigned-int) "int")
((:long :unsigned-long) "com.sun.jna.NativeLong")
((:long-long :unsigned-long-long) "long")
(:pointer "com.sun.jna.Pointer")
((:short :unsigned-short) "short")))
(defun %mem-set (value ptr type &optional (offset 0))
(let* ((bit-size (* 8 (%foreign-type-size type)))
(val (if (and (unsigned-type-p type) (logbitp (1- bit-size) value))
(lognot (logxor value (1- (expt 2 bit-size))))
value)))
(jcall (jmethod "com.sun.jna.Pointer"
(jna-setter type) "long" (jna-setter-arg-type type))
ptr
offset
(if (or (eq type :long) (eq type :unsigned-long))
(jnew (jconstructor "com.sun.jna.NativeLong" "long") val)
val)))
value)
(defun %foreign-symbol-pointer (name library)
"Returns a pointer to a foreign symbol NAME."
(flet ((find-it (library)
(ignore-errors
(make-pointer
(jcall
(private-jmethod "com.sun.jna.NativeLibrary" "getSymbolAddress")
library name)))))
(if (eq library :default)
(or (find-it
(jstatic "getProcess" "com.sun.jna.NativeLibrary"))
(loop for lib being the hash-values of *loaded-libraries*
thereis (find-it lib)))
(find-it (gethash library *loaded-libraries*)))))
(defun find-foreign-function (name library)
(flet ((find-it (library)
(ignore-errors
(jcall (jmethod "com.sun.jna.NativeLibrary" "getFunction"
"java.lang.String")
library name))))
(if (eq library :default)
(or (find-it
(jstatic "getProcess" "com.sun.jna.NativeLibrary"))
(loop for lib being the hash-values of *loaded-libraries*
thereis (find-it lib)))
(find-it (gethash library *loaded-libraries*)))))
(defun convert-calling-convention (convention)
(ecase convention
(:stdcall "ALT_CONVENTION")
(:cdecl "C_CONVENTION")))
(defun make-function-pointer (pointer convention)
(jnew (private-jconstructor "com.sun.jna.Function"
"com.sun.jna.Pointer" "int")
pointer
(jfield "com.sun.jna.Function"
(convert-calling-convention convention))))
(defun lisp-value-to-java (value foreign-type)
(if (eq foreign-type :pointer)
value
(jnew (ecase foreign-type
((:int :unsigned-int) (jconstructor "java.lang.Integer" "int"))
((:long-long :unsigned-long-long)
(jconstructor "java.lang.Long" "long"))
((:long :unsigned-long)
(jconstructor "com.sun.jna.NativeLong" "long"))
((:short :unsigned-short) (jconstructor "java.lang.Short" "short"))
((:char :unsigned-char) (jconstructor "java.lang.Byte" "byte"))
(:float (jconstructor "java.lang.Float" "float"))
(:double (jconstructor "java.lang.Double" "double")))
value)))
(defun %%foreign-funcall (function args arg-types return-type)
(let ((jargs (jnew-array "java.lang.Object" (length args))))
(loop for arg in args and type in arg-types and i from 0
do (setf (jarray-ref jargs i)
(lisp-value-to-java arg type)))
(if (eq return-type :void)
(progn
(jcall (jmethod "com.sun.jna.Function" "invoke" "[Ljava.lang.Object;")
function jargs)
(values))
(lispify-value
(jcall (jmethod "com.sun.jna.Function" "invoke"
"java.lang.Class" "[Ljava.lang.Object;")
function
(foreign-type-to-java-class return-type)
jargs)
return-type))))
(defun foreign-funcall-type-and-args (args)
(let ((return-type :void))
(loop for (type arg) on args by #'cddr
if arg collect type into types
and collect arg into fargs
else do (setf return-type type)
finally (return (values types fargs return-type)))))
(defmacro %foreign-funcall (name args &key library convention)
(declare (ignore convention))
(multiple-value-bind (types fargs rettype)
(foreign-funcall-type-and-args args)
`(%%foreign-funcall (find-foreign-function ',name ',library)
(list ,@fargs) ',types ',rettype)))
(defmacro %foreign-funcall-pointer (ptr args &key convention)
(multiple-value-bind (types fargs rettype)
(foreign-funcall-type-and-args args)
`(%%foreign-funcall (make-function-pointer ,ptr ',convention)
(list ,@fargs) ',types ',rettype)))
(defun foreign-to-callback-type (type)
(ecase type
((:int :unsigned-int)
:int)
((:long :unsigned-long)
(jvm::make-jvm-class-name "com.sun.jna.NativeLong"))
((:long-long :unsigned-long-long)
(jvm::make-jvm-class-name "java.lang.Long"))
(:pointer
(jvm::make-jvm-class-name "com.sun.jna.Pointer"))
(:float
:float)
(:double
:double)
((:char :unsigned-char)
:int)
((:short :unsigned-short)
:int)
(:wchar_t
:int)
(:void
:void)))
(defvar *callbacks* (make-hash-table))
(defmacro convert-args-to-lisp-values (arg-names &rest body)
(let ((gensym-args (loop for name in arg-names
collect (format-symbol t '#:callback-arg-~a- name))))
`(lambda (,@gensym-args)
(let ,(loop for arg in arg-names
for gensym-arg in gensym-args
collecting `(,arg (if (typep ,gensym-arg 'java:java-object)
(java:jobject-lisp-value ,gensym-arg)
,gensym-arg)))
,body))))
(defmacro %defcallback (name return-type arg-names arg-types body
&key convention)
`(setf (gethash ',name *callbacks*)
(jinterface-implementation
(ensure-callback-interface ',return-type ',arg-types)
"callback"
`,(convert-args-to-lisp-values ,arg-names ,@body))))
(jvm::define-class-name +callback-object+ "com.sun.jna.Callback")
(defconstant
+dynamic-callback-package+
"org/armedbear/jna/dynamic/callbacks"
"The slash-delimited Java package in which we create classes dynamically to specify callback interfaces.")
(defun ensure-callback-interface (returns args)
"Ensure that the jvm interface for the callback exists in the current JVM.
Returns the fully dot qualified name of the interface."
(let* ((jvm-returns (foreign-to-callback-type returns))
(jvm-args (mapcar #'foreign-to-callback-type args))
(interface-name (qualified-callback-interface-classname jvm-returns jvm-args)))
(handler-case
(jss:find-java-class interface-name)
(java-exception (e)
(when (jinstance-of-p (java:java-exception-cause e)
"java.lang.ClassNotFoundException")
(let ((interface-class-bytes (%define-jna-callback-interface jvm-returns jvm-args))
(simple-interface-name (callback-interface-classname jvm-returns jvm-args)))
(load-class interface-name interface-class-bytes)))))
interface-name))
(defun qualified-callback-interface-classname (returns args)
(format nil "~A.~A"
(substitute #\. #\/ +dynamic-callback-package+)
(callback-interface-classname returns args)))
(defun callback-interface-classname (returns args)
(flet ((stringify (thing)
(typecase thing
(jvm::jvm-class-name
(substitute #\_ #\/
(jvm::class-name-internal thing)))
(t (string thing)))))
(format nil "~A__~{~A~^__~}"
(stringify returns)
(mapcar #'stringify args))))
(defun %define-jna-callback-interface (returns args)
"Returns the Java byte[] array of a class representing a Java
interface descending form +CALLBACK-OBJECT+ which contains the
single function 'callback' which takes ARGS returning RETURNS.
The fully qualified dotted name of the generated class is returned as
the second value."
(let ((name (callback-interface-classname returns args)))
(values
(define-java-interface name +dynamic-callback-package+
`(("callback" ,returns ,args))
`(,+callback-object+))
(qualified-callback-interface-classname returns args))))
(defun define-java-interface (name package methods
&optional (superinterfaces nil))
"Returns the bytes of the Java class interface called NAME in PACKAGE with METHODS.
METHODS is a list of (NAME RETURN-TYPE (ARG-TYPES)) entries. NAME is
a string. The values of RETURN-TYPE and the list of ARG-TYPES for the
defined method follow the are either references to Java objects as
created by JVM::MAKE-JVM-CLASS-NAME, or keywords representing Java
primtive types as contained in JVM::MAP-PRIMITIVE-TYPE.
SUPERINTERFACES optionally contains a list of interfaces that this
interface extends specified as fully qualifed dotted Java names."
(let* ((class-name-string (format nil "~A/~A" package name))
(class-name (jvm::make-jvm-class-name class-name-string))
(class (jvm::make-class-interface-file class-name)))
(dolist (superinterface superinterfaces)
(jvm::class-add-superinterface
class
(if (typep superinterface 'jvm::jvm-class-name)
superinterface
(jvm::make-jvm-class-name superinterface))))
(dolist (method methods)
(let ((name (first method))
(returns (second method))
(args (third method)))
(jvm::class-add-method
class
(jvm::make-jvm-method name returns args
:flags '(:public :abstract)))))
(jvm::finalize-class-file class)
(let ((s (sys::%make-byte-array-output-stream)))
(jvm::write-class-file class s)
(sys::%get-output-stream-bytes s))))
(defun load-class (name bytes)
"Load the byte[] array BYTES as a Java class called NAME."
(#"loadClassFromByteArray" java::*classloader* name bytes))
(defun write-class (class-bytes pathname)
"Write the Java byte[] array CLASS-BYTES to PATHNAME."
(with-open-file (stream pathname
:direction :output
:element-type '(signed-byte 8))
(dotimes (i (jarray-length class-bytes))
(write-byte (jarray-ref class-bytes i) stream))))
(defun %callback (name)
(or (#"getFunctionPointer" 'com.sun.jna.CallbackReference
(gethash name *callbacks*))
(error "Undefined callback: ~S" name)))
(defun native-namestring (pathname)
(namestring pathname))
|
51e6d93ca65ac97131b0de722d09d58579d9770978d234f7b2d3f3b84fd882f0 | habit-lang/alb | Desugaring.hs | # LANGUAGE FunctionalDependencies , FlexibleContexts , FlexibleInstances ,
GeneralizedNewtypeDeriving , MultiParamTypeClasses , TypeSynonymInstances ,
UndecidableInstances , OverloadedStrings #
GeneralizedNewtypeDeriving, MultiParamTypeClasses, TypeSynonymInstances,
UndecidableInstances, OverloadedStrings #-}
module Analyzer.Desugaring (desugarProgram, DesugaringState) where
-- This module eliminates much of the sugar of the surface syntax, generating the implicitly typed
-- intermediate language used for type checking. In the process, we perform some verification, such
-- as checking that variable and constructor names are in scope, equations are valid definitions,
-- etc.
import Control.Monad.Reader
import Control.Monad.State
import Data.Char (isUpper, isAlpha)
import Data.Either (partitionEithers)
import Data.Foldable (foldrM)
import Data.Graph (SCC(..), stronglyConnComp)
import qualified Data.IntSet as Set
import Data.List
import qualified Data.Map as Map
import Data.Maybe (catMaybes)
import Common
import Printer.Common ((<+>), text)
import Printer.Surface
import Printer.IMPEG hiding (paramName)
import qualified Syntax.Surface as S
import Syntax.IMPEG hiding (replacement)
import qualified Syntax.IMPEG.KSubst as K
import Syntax.IMPEG.TSubst
-- DONE: factor out tuples
DONE : factor out isBound
-- DONE: duplicate name checking (leaving it in for now)
-- TODO: add checking for Ctors being in scope
TODO : toScheme as post pass ? ?
-- TODO: nullary??
TODO : as a post - desugar optimization
-- TODO: why can't we have variables in instances? (warn on non-function instance method?)
-- TODO: gen??
-- TODO: rejectDuplicates
----------------------------------------------------------------------------------------------------
-- Translation monad
----------------------------------------------------------------------------------------------------
type ScopeEnv = Map.Map Id (Located Id)
type CtorEnv = ([(Id, Bool)], [Id]) -- (bitdata ctors (id, nullary), struct ctors)
The translation monad , tracks the field map , a set of fixities ( used in rewriting infix
-- expressions to their prefix equivalents), the scope environment, an integer for fresh name
-- generation, and indicates errors a pair of an (optional) source location and error message.
newtype M t = M { runM :: ReaderT CtorEnv Base t }
deriving (Functor, Applicative, Monad, MonadBase, MonadReader CtorEnv)
bindCtors :: CtorEnv -> M t -> M t
bindCtors (bitCtors, structCtors) = local (\(bitCtors', structCtors') ->
(bitCtors ++ bitCtors', structCtors ++ structCtors'))
----------------------------------------------------------------------------------------------------
Desugaring
----------------------------------------------------------------------------------------------------
-- The 'desugar' function is overloaded to perform desugaring on most syntax tree nodes.
class Sugared t u | t -> u
where desugar :: t -> M u
-- We can lift desugaring through standard constructors.
instance Sugared t u => Sugared (Located t) (Located u)
where desugar (At p t) = failAt p (At p `fmap` desugar t)
instance Sugared t u => Sugared (Maybe t) (Maybe u)
where desugar Nothing = return Nothing
desugar (Just t) = Just `fmap` desugar t
instance (Sugared t t', Sugared u u') => Sugared (t, u) (t', u')
where desugar (x, y) = liftM2 (,) (desugar x) (desugar y)
----------------------------------------------------------------------------------------------------
-- Types and Predicates
tupleName :: Int -> Id
tupleName n = fromString ("$Tuple" ++ show n)
instance Sugared S.Type (Type Id)
where desugar (S.TyCon id) = return (TyCon id)
desugar (S.TyVar id) = return (TyVar id)
desugar S.TyWild = failWithS "Unexpected type wildcard"
desugar (S.TyApp t t') = liftM2 TyApp (desugar t) (desugar t')
desugar (S.TyNat l) = return (TyNat l)
desugar e@(S.TyTuple _) = failWith $ text "Internal error: tuple type at desugaring: " <+> ppr e
desugar e@(S.TyTupleCon _) = failWith $ text "Internal error: tuple type constructor at desugaring: " <+> ppr e
desugar (S.TyKinded t k) =
do t' <- desugar t
return (TyKinded t' k)
desugar (S.TyLabel id) = return (TyLabel id)
desugar (S.TySelect t (At p l)) =
desugar (dislocate (app [introduced (S.TyCon "Select"), t, At p (S.TyLabel l)]))
where app = foldl1 (\t t' -> at t (S.TyApp t t'))
desugar e@(S.TyInfix head tail) = failWith $ text "Internal error: infix type at desugaring: " <+> ppr e
instance Sugared S.Pred (PredType PredFN Id)
where desugar (S.Pred t mt f) =
do t' <- desugar t
mt' <- desugar mt
case flattenType t' of
(At _ (TyCon id@(Ident (c:_) _ _)), ts) | isUpper c || not (isAlpha c) ->
return (PredFN id ts mt' f)
_ -> failWithS "Predicate must consist of a tyconsym applied to a list of types"
instance Sugared (S.Qual S.Type) (Qual (PredType PredFN Id) (Type Id))
where desugar (ps S.:=> t) = liftM2 (:=>) (mapM desugar ps) (desugar t)
instance Sugared (S.Qual S.Pred) (Qual (PredType PredFN Id) (PredType PredFN Id))
where desugar (ps S.:=> t) = liftM2 (:=>) (mapM desugar ps) (desugar t)
toScheme ids qty generates a new type scheme that quantifies over all the variables in qty that
-- are not in ids.
toScheme :: [Id] -> Qual (PredType PredFN Id) (Type Id) -> Scheme PredFN Id
toScheme retained qty = Forall vs (gen 0 vs qty)
where vs = nub (tvs qty) \\ retained
toKScheme :: [Id] -> [Id] -> Qual (PredType PredFN Id) (Type Id) -> KScheme (Scheme PredFN Id)
toKScheme retained retainedTyVars qty = ForallK kvs (toScheme retainedTyVars qty)
where kvs = filter (`notElem` retained) (K.vars qty)
----------------------------------------------------------------------------------------------------
-- Expressions
-- Shortcuts for constructing expressions: in particular, this handles inserting valid locations for
-- applications.
(@@) :: Located S.Expr -> Located S.Expr -> Located S.Expr
e @@ e' = at e (S.EApp e e')
infixl 9 @@
app :: Id -> [Located S.Expr] -> S.Expr
app op args = dislocate (foldl (@@) (introduced (S.EVar op)) args)
gfrom :: Pattern PredFN Id -> Expr PredFN Id -> Guard PredFN Id
gfrom p e = GFrom (introduced p) (introduced e)
sfield :: Location -> Id -> Located S.Expr
sfield l f = At l (S.ETyped (At l (S.ECon "Proxy"))
([] S.:=> At l (S.TyApp (At l (S.TyCon "Proxy")) (At l (S.TyLabel f)))))
instance Sugared S.Expr (Expr PredFN Id)
where desugar (S.ELet decls body) =
do decls' <- desugar decls
body' <- desugar body
return (ELet decls' body')
if<- and case<- are handled first by binding the scrutinee to a new value , and then
-- rewriting a normal if/case expression.
desugar (S.EIf (S.ScFrom mid cond) cons alt) =
do name <- maybe (fresh "condition") return mid
liftM2 (EBind name)
(desugar cond)
(introduced `fmap`
desugar (S.EIf (S.ScExpr (introduced (S.EVar name))) cons alt))
desugar (S.ECase (S.ScFrom mid scrutinee) alts) =
do name <- maybe (fresh "scrutinee") return mid
liftM2 (EBind name)
(desugar scrutinee)
(introduced `fmap`
desugar (S.ECase (S.ScExpr (introduced (S.EVar name))) alts))
-- if cond cons alt is rewritten to the match { True <- cond => ^cons | ^alt }; note that
-- we're (now) avoiding the unnecessary check for False in the alternative branch.
desugar (S.EIf (S.ScExpr cond) cons alt) =
do cond' <- desugar cond
cons' <- desugar cons
alt' <- desugar alt
name <- fresh "condition"
return (EMatch (MGuarded (GFrom (introduced (PVar name)) cond')
((MGuarded (gfrom (PCon "True" []) (EVar name)) (MCommit cons')) `MElse`
(MCommit alt'))))
-- We begin a case by binding the scrutinee to a new value; this avoids recomputing it for
-- each guard in the match.
desugar (S.ECase (S.ScExpr scrutinee) alts) =
do name <- fresh "scrutinee"
scrutinee' <- desugar scrutinee
alts' <- foldl1 MElse `fmap` mapM (desugarAlt name) alts
return (EMatch (MGuarded (GFrom (introduced (PVar name)) scrutinee') alts'))
where -- Alternative may bind new names. We begin by constructing replacements for
-- any bound names that would shadow existing definitions; after this,
-- desugaring the alternative is straightforward.
desugarAlt name (p S.:-> rhs) =
do p'@(At l _) <- desugar p
rhs' <- desugar rhs
return (MGuarded (GFrom p' (At l (EVar name))) rhs')
The majority of the work for ELam is actually handled by desugarParameterList ( defined
-- far below) which handles the details of desugaring patterns and introducing new
-- parameter names when necessary.
desugar (S.ELam patterns body) =
do (args', body') <- desugarParameterList patterns (MCommit `fmap` desugar body)
return (dislocate (foldr elam (introduced (EMatch body')) args'))
where elam v body = introduced (ELam v body)
desugar e@(S.EVar id) = return (EVar id)
desugar (S.ECon id) =
do (bitCtors, structCtors) <- ask
case lookup id bitCtors of
Just nullary | nullary -> return (EBitCon id [])
| otherwise -> return (ECon id)
_ | id `elem` structCtors -> return (EStructInit id [])
| otherwise -> return (ECon id)
desugar (S.ELit (S.BitVector value size)) =
return (EBits value size)
desugar (S.ELit (S.Numeric value)) =
dislocate `fmap` desugar (introduced (S.EVar "fromLiteral") @@ introduced proxy)
where proxyType = [] S.:=> introduced (S.TyApp (introduced (S.TyCon "Proxy")) (introduced (S.TyNat value)))
proxy = S.ETyped (introduced (S.ECon "Proxy")) proxyType
desugar e@(S.ETuple _) = failWith $ text "Internal error: tuple expression at desugaring: " <+> ppr e
desugar e@(S.ETupleCon _) = failWith $ text "Internal error: tuple constructor expression at desugaring: " <+> ppr e
desugar (S.EApp (At _ (S.EApp (At _ (S.EVar "||")) lhs)) rhs) =
do name <- fresh "scrutinee"
lhs' <- desugar lhs
rhs' <- desugar rhs
return (EMatch (MGuarded (GFrom (introduced (PVar name)) lhs')
((MGuarded (gfrom (PCon "False" []) (EVar name)) (MCommit rhs'))
`MElse` MCommit (at lhs (EBitCon "True" [])))))
desugar (S.EApp (At _ (S.EApp (At _ (S.EVar "&&")) lhs)) rhs) =
do name <- fresh "scrutinee"
lhs' <- desugar lhs
rhs' <- desugar rhs
return (EMatch (MGuarded (GFrom (introduced (PVar name)) lhs')
((MGuarded (gfrom (PCon "True" []) (EVar name)) (MCommit rhs'))
`MElse` MCommit (at lhs (EBitCon "False" [])))))
desugar (S.EApp e e') = liftM2 EApp (desugar e) (desugar e')
desugar (S.EBind Nothing e rest) =
do v <- fresh "x"
liftM2 (EBind v) (desugar e) (desugar rest)
desugar (S.EBind (Just v) e rest) =
do e' <- desugar e
rest' <- desugar rest
return (EBind v e' rest')
-- e.l is rewritten to the application select e l; similarly, e[l = e'] is rewritten to
-- update e l e'
desugar (S.ESelect e (At p l)) =
desugar (app "select" [e, sfield p l])
desugar (S.EUpdate (At _ (S.ECon id)) []) =
do (bitCtors, structCtors) <- ask
case lookup id bitCtors of
Just _ -> return (EBitCon id [])
_ | id `elem` structCtors -> return (EStructInit id [])
| otherwise -> failWithS ("Constructor "++ fromId id ++" does not support empty update")
desugar (S.EUpdate (At _ (S.ECon id)) fs) =
do fs' <- mapM desugarBinding fs
return (EBitCon id fs')
where desugarBinding (At _ name, e) =
do e' <- desugar e
return (name, e')
desugar (S.EUpdate e fs) =
desugar (dislocate (foldl update e fs))
where update e (At p id, val) =
introduced (S.EVar "update") @@ e @@ sfield p id @@ val
-- Sections are uniformly rewritten to lambdas
desugar (S.ELeftSection lhs (At p opname)) =
do rhs <- fresh "rhs"
desugar (S.ELam [introduced (S.PVar rhs)] (At p (S.EVar opname) @@ lhs @@ introduced (S.EVar rhs)))
desugar (S.ERightSection (At p opname) rhs) =
do lhs <- fresh "lhs"
desugar (S.ELam [introduced (S.PVar lhs)] (At p (S.EVar opname) @@ introduced (S.EVar lhs) @@ rhs))
desugar (S.EStructInit (At _ name) fields) = liftM (EStructInit name) (mapSndM desugar fields)
-- An expression:
-- e :: sigma
-- is equivalent to
-- let x :: sigma; x = e in x
desugar (S.ETyped e ty) =
do v <- fresh "x"
e' <- desugar e
tys <- toKScheme [] [] `fmap` desugar ty
return (ELet (Decls [Explicit (v, [], MCommit e') tys]) (introduced (EVar v)))
desugar e@(S.EInfix head tail) = failWith $ text "Internal error: infix expression at desugaring:" <+> ppr e
-- declsToMatch abstracts the construction of let guards from local declaration blocks. As the
-- construction of the internal match needs to take the symbols and replacements from the outer
-- declaration block into account, we take a computation to construct the inner match instead of the
-- match itself.
declsToMatch :: Maybe S.Decls -> M (Match PredFN Id) -> M (Match PredFN Id)
declsToMatch Nothing c = c
declsToMatch (Just ds) c =
do ds' <- desugar ds
m <- c
return (MGuarded (GLet ds') m)
instance Sugared S.Rhs (Match PredFN Id)
where desugar (S.Unguarded body ds) =
declsToMatch ds (MCommit `fmap` desugar body)
desugar (S.Guarded ps ds) =
declsToMatch ds $
do ps' <- mapM desugar ps
vs <- replicateM (length ps') (fresh "condition")
return (foldl1 MElse [ MGuarded (GFrom (introduced (PVar v)) condition)
(MGuarded (gfrom (PCon "True" []) (EVar v))
(MCommit body))
| (v, (condition, body)) <- zip vs ps' ])
----------------------------------------------------------------------------------------------------
-- Patterns and parameters
-- Note that we don't check pattern variables against the variables in scope or anything; computing
-- replacements is the responsibility of the code that handles the scoping node (such as a case
-- statement, above, or an equation in a declaration block, below).
instance Sugared S.Pattern (Pattern PredFN Id)
where desugar S.PWild = return PWild
desugar (S.PVar id) = return (PVar id)
desugar (S.PTyped p ty) = liftM2 PTyped (desugar p) (toScheme [] `fmap` desugar ty)
-- A literal pattern l is interpreted as a guarded pattern (var | let test = var == l,
-- True <- test) for some new variables var and test. (The introduction of test is
-- necessary to preserve the invariant, required in later stages, that the expression on
-- the right of a PGuarded is a variable.
desugar (S.PLit l) =
do var <- fresh "x"
test <- fresh "test"
l' <- desugar (S.ELit l)
let testExpr = introduced (EApp (introduced (EApp (introduced (EVar "=="))
(introduced (EVar var))))
(introduced l'))
return ((PVar var `PGuarded` GLet (Decls [Implicit [(test, [], MCommit testExpr)]]))
`PGuarded` gfrom (PCon "True" []) (EVar test))
-- x@p is equivalent to the guarded pattern (x | p <- x)
desugar (S.PAs id p) =
do p' <- desugar p
return (PGuarded (PVar id) (GFrom p' (introduced (EVar id))))
-- The surface syntax supports arbitrary application in patterns; this is so that we don't
-- have to sort out function definitions vs constructor applications during parsing.
IMPEG , however , lacks PApp and associates the arguments of a constructor pattern with
the pattern itself . When desugaring a PApp , we desugar each side and then try
flattening the LHS : if the far left argument is a PCon , we add the rest of the patterns
to its arguments ; otherwise , we fail . An additional complication is that IMPEG insists
-- that the arguments to a PCon all be variables; fixing this is separated into
-- buildGuardedPattern.
desugar (S.PCon id) = return (PCon id [])
do ( bitCtors , _ ) < - ask
-- case lookup id bitCtors of
-- Just nullary | nullary -> do v <- fresh "v"
-- return (PCon id [v])
-- _ -> return (PCon id [])
--
desugar e@(S.PTuple _) = failWith $ text "Internal error: tuple pattern at desugaring: " <+> ppr e
desugar e@(S.PTupleCon _) = failWith $ text "Internal error: tuple constructor pattern at desugaring: " <+> ppr e
desugar p@(S.PApp {}) =
case op of
At _ (S.PCon name) -> buildGuardedPattern name =<< mapM desugar ps
_ -> failWith $ text "Pattern must be the application of a constructor to a list of arguments: " <+> ppr p
where (op, ps) = S.flattenPattern (introduced p)
desugar (S.PLabeled ctor fieldPatterns) =
do rejectDuplicates [ At loc f | At loc (S.FieldPattern f p) <- fieldPatterns ]
n <- fresh "n"
foldM (addFieldGuards n) (PCon ctor [n]) fieldPatterns
where
For each field pattern field = p , add guards ( ... | let v = src.field , )
addFieldGuards n pat (At loc (S.FieldPattern field p))
= do v <- fresh "f" -- variable to represent this field name
p' <- desugar p
At _ body <- desugar (At loc (S.EVar "select") @@ At loc (S.EVar n) @@ sfield loc field)
return ((pat `PGuarded` GLet (Decls [Implicit [(v,[],MCommit (At loc body))]]))
`PGuarded` GFrom p' (introduced (EVar v)))
desugar e@(S.PInfix head tail) = failWith $ text "Internal error: infix expressions/types at desugaring: " <+> ppr e
-- buildGuardedPattern takes a nested pattern and constructs an unnested pattern. The basic notion
-- is that given a pattern of the form C (D p), this is equivalent to the guarded pattern (C x | D p
-- <- x) for a fresh variable x. buildGuardedPattern performs this transformation recursively until
there are no nested patterns remaining . One transformation that is not performed yet is to
-- remove guards of the form _ <- e; this ought to be relatively simple to add.
buildGuardedPattern :: Id -> [Located (Pattern PredFN Id)] -> M (Pattern PredFN Id)
buildGuardedPattern name ps =
do (vs, guards) <- unzip `fmap` (mapM toGuard ps)
return (foldl PGuarded (PCon name vs) (catMaybes (zipWith (\v g -> fmap (flip GFrom (introduced (EVar v))) g) vs guards)))
where toGuard (At _ (PVar v)) = return (v, Nothing)
toGuard p = do v <- fresh "p"
return (v, Just p)
That 's fine and all , but when building functions ( either in ELam above or when handling equations
-- below) we need to split a list of patterns into a list of parameters and a match, so we define a
helper function that desugars a list of patterns and an expression into ( a ) a list of variables
and ( b ) a match . The final assembly of these parts is different in the two cases above .
desugarParameterList :: [Located S.Pattern] -> M (Match PredFN Id) -> M ([Id], Match PredFN Id)
desugarParameterList ps c =
do body <- c
foldM desugarPattern ([], body) (reverse ps)
where desugarPattern (args, body) p =
do p' <- desugar p
case p' of
At loc (PVar s) -> return (s : args, body)
_ -> do var <- fresh "x"
return (var : args, MGuarded (GFrom p' (introduced (EVar var))) body)
----------------------------------------------------------------------------------------------------
-- Local declaration blocks
-- The majority of the confusion in this module is in handling declaration blocks. There are
-- several issues that arise at this point:
--
* The first confusion is figuring out what is actually being defined ; all we get from the parser
-- are patterns, which can either correspond to value bindings (a top level application of a
-- constructor to a list of patterns) or function bindings (a top level application of variable
-- to a list of patterns). The possible presence of infix expressions further complicates this:
we 'd like to use the correct fixities when resolving the LHS 's , but as we do n't yet know which
-- values are being defined, we can't compute replacements yet.
--
* Once we 've disentangled the LHS 's , we can determine what the block defines , whether any of
-- those identifiers shadow higher-level bindings, and compute replacements if they do. With the
new bindings and replacements in hand , we can desugar the RHS 's of the equations .
--
-- * Next, we need to combine multiple equations defining functions into single definitions,
-- sticking the different set of patterns together into matches. We don't do this with much
-- intelligence at this point. For example, given the equations:
--
-- f (Just x) (Just y) = ..
-- f (Just x) _ = ..
-- f _ _ = ..,
--
we 'll generate two identical pattern matches against the first parameter .
--
-- * Finally, we need to combine the definitions into group for typechecking. The notion here is
-- that we need to typecheck mutually recursive functions together to be able to compute types at
-- all; however, if we include extra definitions we may compute types that are too restrictive.
-- A further observation is that we can always check explicitly typed bindings separately: in the
-- remainder of the program, we can assume that the signature is valid. To compute theses
groups , we perform an SCC over a graph where declarations are vertices and edges are
-- references without type signatures.
instance Sugared S.Decls (Decls PredFN Id)
where desugar decls =
First , split the equations into their left- and right - hand sides .
let (lhss, rhss) = unzip [(lhs, rhs) | lhs S.:= rhs <- S.equations decls]
-- Split bindings into value and function definitions (and indicate errors for
-- others).
lhss' <- mapM splitPattern lhss
-- Figure out what we're actually defining
-- Now we can finally desugar the right hand sides.
equations <- mapM desugarEquation (zip lhss' rhss)
-- And merge sequential equations defining cases of the same function. This will
-- fail if equations defining the same symbol are interlaced with equations
-- defining different symbols.
(valDefs, fcnDefs) <- partitionEithers `fmap` mergeEquations equations
let valNames = concatMap (bound . fst) valDefs
fcnNames = [id | (id, _, _) <- fcnDefs]
names = valNames ++ fcnNames
signatures <- mapM desugar (S.signatures decls)
let explicitlyTyped = [name | Signature name _ <- signatures]
when (hasDuplicates names) $
failWithS "Duplicate symbol definition"
when (any (`notElem` names) explicitlyTyped) $
failWithS ("Signatures without definition: " ++ intercalate "," (map fromId (filter (`notElem` names) explicitlyTyped)))
Finally , we perform the SCC ...
let simpleGroups = [(Left (p, e), i, bound p, freeVariables e \\ explicitlyTyped) | (i, (p, e)) <- zip [0,2..] valDefs] ++
[(Right (name, args, body), i, [name], freeVariables body \\ (args ++ explicitlyTyped))
| (i, (name, args, body)) <- zip [1,3..] fcnDefs ]
nodes = [(body, i, links)
| (body, i, _, needed) <- simpleGroups
, let links = [j | (_, j, bound, _) <- simpleGroups, not (null (needed `intersect` bound))]]
sccs = stronglyConnComp nodes
-- ... and construct the result.
decls' <- liftM Decls (mapM (makeTypingGroup signatures) sccs)
return decls'
where -- splitPattern is responsible for distinguishing value and function bindings
splitPattern :: Located S.Pattern -> M (Either (Located S.Pattern) (Id, [Located S.Pattern]))
splitPattern p =
case S.flattenPattern p of
(At _ (S.PVar fcn), args) ->
return (Right (fcn, args))
(At _ (S.PCon name), _) ->
return (Left p)
(p, []) ->
return (Left p)
_ -> failWithS "Invalid LHS"
singleton = (:[])
-- desugarEquation actually has surprisingly little work left: we've already
-- distinguished value and function bindings, we've already handled binings and
-- replacements; all that's left is calling the desugar methods for the left-
-- and right-hand sides. In the process, we attempt to desugar "value"
-- definitions with lambdas on the right-hand side to function definitions; this
-- allows recursion in definitions like:
-- f = \ x -> f x
-- which would otherwise be illegal.
desugarEquation :: (Either (Located S.Pattern) (Id, [Located S.Pattern]), S.Rhs)
-> M (Either (Located (Pattern PredFN Id), Match PredFN Id) (Id, [Located (Pattern PredFN Id)], Match PredFN Id))
desugarEquation (Left p, rhs) =
do p' <- desugar p
m <- desugar rhs
case p' of
At _ (PVar name) ->
case commuteLambdas m of
([], _) -> return (Left (p', m))
(ps, body) -> return (Right (name, map (introduced . PVar) ps, body))
_ -> return (Left (p', m))
desugarEquation (Right (name, params), rhs) =
do params' <- mapM desugar params
body <- desugar rhs
return (Right (name, params', body))
We commute lambdas in two cases ; either definitions of the form :
f = { ^ \x - > { p < - x = > m } }
-- or definitions of the form
f = { ^ \x - > m }
-- Note that we won't commute a lambda past a let guard or a pattern match
-- against anything besides the variable in the outermost lambda.
commuteLambdas :: Match PredFN Id -> ([Id], Match PredFN Id)
commuteLambdas (MCommit (At _ (ELam v (At _ (EMatch (MGuarded (GFrom p (At l (EVar v'))) body))))))
| v == v' = (v:ps, MGuarded (GFrom p (At l (EVar v))) body')
where (ps, body') = commuteLambdas body
commuteLambdas (MCommit (At _ (ELam v (At _ (EMatch body))))) = (v:ps, body')
where (ps, body') = commuteLambdas body
commuteLambdas m = ([], m)
hasDuplicates :: Eq t => [t] -> Bool
hasDuplicates [] = False
hasDuplicates (t:ts) = t `elem` ts || hasDuplicates ts
-- mergeEquations is fairly simple: we iterate over the equations, tracking the
-- function defined in the last equation encountered (if any). Multiple
equations defining ( cases of ) the same function are combined using MElse
-- after we check that they have the same number of parameters; value equations
-- are passed through unchanged.
mergeEquations :: [Either (Located (Pattern PredFN Id), Match PredFN Id) (Id, [Located (Pattern PredFN Id)], Match PredFN Id)]
-> M [Either (Located (Pattern PredFN Id), Match PredFN Id) (Function PredFN Id)]
mergeEquations [] = return []
mergeEquations eqns = iter [] Nothing eqns
where iter done Nothing [] = return done
iter done (Just inProgress) [] = return (Right inProgress : done)
iter done Nothing (Left (p, e) : rest) = iter (Left (p, e) : done) Nothing rest
iter done (Just inProgress) (Left (p, e) : rest) = iter (Left (p, e) : Right inProgress : done) Nothing rest
iter done Nothing (Right (name, params, match) : rest) =
do args <- replicateM (length params) (fresh "x")
iter done (Just (name, args, matchFrom args params match)) rest
iter done (Just (nameIP, argsIP, matchIP)) (Right (name, params, match) : rest)
| nameIP == name =
if length argsIP /= length params
then failWithS ("Different arities in equations for " ++ fromId name)
else iter done (Just (nameIP, argsIP, MElse matchIP (matchFrom argsIP params match))) rest
| name `elem` [id | Right (id, _, _) <- done] =
failWithS ("Redefinition of function " ++ fromId name)
| otherwise =
do newArgs <- replicateM (length params) (fresh "x")
iter (Right (nameIP, argsIP, matchIP) : done) (Just (name, newArgs, matchFrom newArgs params match)) rest
matchFrom :: [Id] -> [Located (Pattern PredFN Id)] -> Match PredFN Id -> Match PredFN Id
matchFrom args params match = foldr (\(arg, p@(At l _)) m -> MGuarded (GFrom p (At l (EVar arg))) m) match (zip args params)
signatureFor :: Id -> [Signature PredFN Id] -> Maybe (Signature PredFN Id)
signatureFor name signatures = iter signatures
where iter [] = Nothing
iter (s@(Signature name' _) : rest)
| name == name' = Just s
| otherwise = iter rest
singleFunctionTypingGroup :: (Id, [Id], Match PredFN Id) -> [Signature PredFN Id] -> TypingGroup PredFN Id
singleFunctionTypingGroup (name, params, body) signatures =
case signatureFor name signatures of
Nothing -> Implicit [(name, params, body)]
Just (Signature _ tys) -> Explicit (name, params, body) tys
makeTypingGroup :: [Signature PredFN Id] -> SCC (Either (Located (Pattern PredFN Id), Match PredFN Id) (Function PredFN Id)) -> M (TypingGroup PredFN Id)
makeTypingGroup signatures (AcyclicSCC (Left (p, e))) =
return (Pattern p e (catMaybes [signatureFor name signatures | name <- bound p]))
makeTypingGroup signatures (AcyclicSCC (Right f)) =
return (singleFunctionTypingGroup f signatures)
makeTypingGroup signatures (CyclicSCC nodes) =
case partitionEithers nodes of
([], [f]) -> return (singleFunctionTypingGroup f signatures)
([], fcns) -> return (Implicit fcns)
((At loc _, _) : _, _) -> failAt loc $ failWithS "Recursive value definition"
instance Sugared S.Signature (Signature PredFN Id)
where desugar (S.Signature id ty) =
liftM (Signature id) (toKScheme [] [] `fmap` desugar ty)
----------------------------------------------------------------------------------------------------
-- Top level declarations
-- Both instance and class declarations have the odd invariant that their 'where' blocks can only
-- contain function definitions. Unfortunately, the 'Decls' conversion code will interpret a
-- declaration of the form:
-- x = id
as a pattern binding ( binding ' PVar " x " ' ) rather than a function binding . The following function
desugars pattern bindings of that form to " function " bindings , and indicates errors for any other
-- form of pattern binding.
coercePatternBinding :: String -> TypingGroup PredFN Id -> M (Functions PredFN Id)
coercePatternBinding _ (Pattern (At _ (PVar s)) m _) = return ([(s, [], m)])
coercePatternBinding _ (Explicit f _ ) = return [f]
coercePatternBinding _ (Implicit fs) = return fs
coercePatternBinding s _ = failWithS s
-- Another common pattern in many top level declarations, including classes, type synonyms,
datatypes , etc . , is that we parse the LHS of the definition as a type ( to allow for infixity ,
-- parenthesization, and various other forms of pathological code) but require that it fit a
-- stricter pattern (something applied to a set of (possibly kinded) type variables). This function
serves two roles in that conversion : first , it maps type arguments from ' Type 's to ' TyParam 's ,
and second , looks for duplicate parameters in the process .
validateTypeParameter :: Located (Type Id) -> [Located (Either KId Id)] -> M [Located (Either KId Id)]
validateTypeParameter arg args =
case arg of
At loc (TyVar v)
| v `elem` map paramName args' -> failAt loc $ failWithS ("Duplicate class parameter name '" ++ fromId v ++ "'")
| otherwise -> return (At loc (Right v) : args)
At loc (TyKinded (At _ (TyVar v)) (At _ k))
| v `elem` map paramName args' -> failAt loc $ failWithS ("Duplicate class parameter name '" ++ fromId v ++ "'")
| otherwise -> return (At loc (Left (Kinded v k)) : args)
At loc _ -> failAt loc $ failWith (text "Unexpected class parameter" <+> ppr arg)
where args' = map dislocate args
typeFromTypeParameter :: Located (Either KId Id) -> Located (Type Id)
typeFromTypeParameter (At l (Left (Kinded id k))) = At l (TyKinded (At l (TyVar id)) (At l k))
typeFromTypeParameter (At l (Right id)) = At l (TyVar id)
desugarClassConstraints :: Id -> [Located (Either KId Id)] -> [Located S.ClassConstraint] -> M ([Located ClassConstraint], [Top])
desugarClassConstraints className params constraints = partitionEithers `fmap` mapM desugar' constraints
where desugar' (At loc (S.Superclass p)) =
do n <- fresh "super"
p' <- desugar p
return (Right (Require [(n, At loc p')] [At loc (PredFN className (map typeFromTypeParameter params) Nothing Holds)]))
desugar' (At loc (S.Fundep fd)) =
do (At _ fd') <- desugarFunctionalDependency params (At loc fd)
return (Left (At loc (Fundep fd')))
desugar' (At loc (S.Opaque v)) =
case findIndex (v ==) names of
Nothing -> failWithS "Invalid parameter name in opacity constraint"
Just i -> return (Left (At loc (Opaque i)))
where names = map (paramName . dislocate) params
desugarFunctionalDependency :: [Located (Either KId Id)] -> Located (Fundep Id) -> M (Located (Fundep Int))
desugarFunctionalDependency params (At loc (xs :~> ys)) =
failAt loc $
case (xs', ys') of
(Just xs', Just ys') -> return (At loc (xs' :~> ys'))
_ -> failWithS "Invalid parameter name in functional dependency constraint"
where names = map (paramName . dislocate) params
toIdx s = findIndex (s ==) names
xs' = mapM toIdx xs
ys' = mapM toIdx ys
-- We don't want to use the default implementation of desugar for method signatures because we don't
-- want to quantify over class parameters; e.g., in the definition
class Eq t where (= =) : : t - > t - > Bool
= = 's type should remain t - > t - > Bool , not forall _ 0 - > Bool .
desugarMethodSignature ps (S.Signature name qty) = Signature name `fmap` (toKScheme pkvars pvars `fmap` desugar qty)
where pkvars = K.vars ps
pvars = map (paramName . dislocate) ps
type Top = TopDecl PredFN Id (Either KId Id)
instance Sugared S.Class [Top]
where desugar (S.Class ty determined constraints mdecls) =
do ty' <- desugar ty
case flattenType ty' of
(At _ (TyCon name), []) ->
failWithS "Class without parameters is pointless"
(At _ (TyCon name), params) ->
do params' <- case determined of
Nothing -> return params
Just t -> do t' <- desugar t
return (params ++ [t'])
params'' <- foldrM validateTypeParameter [] params'
(constraints', requirements) <- desugarClassConstraints name params'' constraints
let n = length params''
constraints'' = case determined of
Nothing -> constraints'
Just (At loc _) -> At loc (Fundep ([0..n - 2] :~> [n - 1])) : constraints'
(methods, defaults) <-
case mdecls of
Nothing -> return ([], [])
Just decls ->
do let defaultNames = concatMap lhsBound [lhs | lhs S.:= _ <- S.equations decls]
defaultSignatures = [s | s@(S.Signature name _) <- S.signatures decls, name `elem` defaultNames]
methodNames = [name | S.Signature name _ <- S.signatures decls]
defaultDecls <- desugar decls { S.signatures = defaultSignatures }
defaults <- concatMapM (coercePatternBinding "Class method defaults must be functions")
(groups defaultDecls)
when (any (`notElem` methodNames) defaultNames) $
failWithS ("Default implementation for non-class method: " ++ intercalate ", " (map fromId (filter (`notElem` methodNames) defaultNames)))
signatures' <- mapM (desugarMethodSignature params'') (S.signatures decls)
return (signatures', defaults)
return (Class name params'' constraints'' methods defaults : requirements)
_ -> failWithS "Invalid class LHS (must be a class name applied to a list of parameters)"
where lhsBound :: Located S.Pattern -> [Id]
lhsBound p = case S.flattenPattern p of
(At loc (S.PVar name), []) -> [name]
(At loc (S.PVar fcn), args) -> [fcn]
(At loc (S.PCon name), args) -> concatMap bound args
(p, []) -> bound p
instance Sugared S.Instance (Top, [Primitive PredFN Id])
where desugar (S.Instance chain) =
do name <- fresh "i"
(chain', topDecls) <- unzip `fmap` mapM desugar' chain
let (cl:cls) = [name | (_ :=> At _ (PredFN name _ _ _), _) <- chain']
if all (cl ==) cls
then return (Instance name cl chain', catMaybes topDecls)
else failWithS "Instance refers to different classes"
where desugar' (qs S.:=> At l1 (S.Pred t (Just (At l2 S.TyWild)) Holds), mdecls) =
do name <- fresh "T"
((qp', decls), _) <- desugar' (qs S.:=> At l1 (S.Pred t (Just (At l2 (S.TyCon name))) Holds), mdecls)
return ((qp', decls), Just (PrimType name (KVar name)))
desugar' (qp, mdecls) =
do qp' <- desugar qp
decls <- maybe (return emptyDecls) desugar mdecls
>>= (concatMapM (coercePatternBinding "Instance methods must be functions") . groups)
return ((qp', decls), Nothing)
instance Sugared S.Requirement Top
where desugar (S.Require ps qs) =
do names <- replicateM (length ps) (fresh "require")
ps <- mapM desugar ps
Require (zip names ps) `fmap` mapM desugar qs
desugarInterface :: Id -> [Located (Either KId Id)] -> [Located (PredType PredFN Id)] -> Located (Type Id) -> S.Decls -> M [Top]
desugarInterface name params rhsPreds rhsType interface =
do instName <- fresh "opaque"
Decls ds <- desugar interface
signatures <- mapM (desugarMethodSignature params) (S.signatures interface)
case mapM fromTypingGroup ds of
Nothing ->
failWithS ("Unexpected declaration in opaque type interface")
Just impls ->
let cl = Class name
(params ++ [introduced (Right "t$")])
[introduced (Fundep ([0..n-1] :~> [n])), introduced (Fundep ([n] :~> [0..n-1])), introduced (Opaque n)]
signatures
[]
inst = Instance instName name
[(rhsPreds :=> introduced (PredFN name (map typeFromTypeParameter params ++ [rhsType]) Nothing Holds), impls)]
in return [cl, inst]
where n = length params
fromTypingGroup (Explicit impl@(id, _, _) _) =
Just impl
fromTypingGroup _ =
Nothing
instance Sugared S.Synonym [Top]
where desugar (S.Synonym lhs rhs interface) =
do lhs' <- desugar lhs
ps :=> t <- desugar rhs
case flattenType lhs' of
(At _ (TyCon name), params) ->
do params' <- foldrM validateTypeParameter [] params
case interface of
Nothing ->
do instName <- fresh "synonym"
let n = length params'
vs = tvs t
determined = catMaybes (map (findParam 0 params') vs)
fds | null determined = [introduced (Fundep ([0..n - 1] :~> [n]))]
| otherwise = [introduced (Fundep ([n] :~> determined)), introduced (Fundep ([0..n - 1] :~> [n]))]
cl = Class name (params' ++ [introduced (Right "$t")])
fds [] []
v = introduced (TyVar "$t")
inst = Instance instName name
[(ps :=> introduced (PredFN name (map typeFromTypeParameter params' ++ [t]) Nothing Holds), []),
([] :=> introduced (PredFN name (map typeFromTypeParameter params' ++ [v]) Nothing Fails), [])]
return [cl, inst]
Just ds ->
desugarInterface name params' ps t ds
_ -> failWithS "Invalid synonym LHS"
where findParam _ [] _ = Nothing
findParam n (At _ (Left (Kinded id _)) : rest) id'
| id == id' = Just n
| otherwise = findParam (n + 1) rest id'
findParam n (At _ (Right id) : rest) id'
| id == id' = Just n
| otherwise = findParam (n + 1) rest id'
TODO : generalizing over one ( 1 ) case here ...
desugarCtor :: (Sugared p p', Sugared t t', HasTypeVariables p' Id, HasTypeVariables t' Id) =>
[Id] -> Ctor Id p t -> M (Ctor Id p' t')
desugarCtor enclosing (Ctor name _ quals fields) =
do quals' <- mapM desugar quals
fields' <- mapM desugar fields
let vs = filter (`notElem` enclosing) (nub (concatMap tvs quals' ++ concatMap tvs fields'))
return (Ctor name vs (gen 0 vs quals') (gen 0 vs fields'))
instance Sugared S.Datatype [Top]
where desugar (S.Datatype lhs ctors drv interface) =
do (ps :=> lhs') <- desugar lhs
case flattenType lhs' of
(At loc (TyCon name), params) ->
do params' <- foldrM validateTypeParameter [] params
let pnames = map (paramName . dislocate) params'
ctors' <- mapM (desugarCtor pnames) ctors
case interface of
Nothing -> return [Datatype name params' ps ctors' drv]
Just ds -> do name' <- fresh name
let rhs = foldl (\t p -> at t (TyApp t (typeFromTypeParameter p))) (At loc (TyCon name')) params'
topDecls' <- desugarInterface name params' [] rhs ds
return (Datatype name' params' ps ctors' drv : topDecls')
_ -> failWithS "Invalid datatype LHS"
instance Sugared S.DataField (Type Id)
where desugar (S.DataField _ (At l t)) = desugar t
toMaybeScheme = maybe Nothing (Just . toScheme [])
toMaybeLocatedScheme = maybe Nothing (\(At loc qt) -> Just (At loc (toScheme [] qt)))
unzipLocated :: [Located (a, b)] -> ([Located a], [b])
unzipLocated lps = (as, map dislocate bs)
where (as, bs) = unzipLocated' lps
unzipLocated' :: [Located (a, b)] -> ([Located a], [Located b])
unzipLocated' lps = unzip [(At p t, At p u) | At p (t, u) <- lps]
type Init t = (Id, t, Located (Expr PredFN Id))
desugarCtorWithInit :: (Sugared t (t', Maybe (Init (Located (Type Id)))), HasTypeVariables t' Id)
=> [Id] -> Ctor Id S.Pred t -> M (Ctor Id (PredType PredFN Id) t', [Init (KScheme (Scheme PredFN Id))])
desugarCtorWithInit enclosing (Ctor name _ quals fields) =
do quals' <- mapM desugar quals
(fields', minits) <- unzipLocated `fmap` mapM desugar fields
let vs = filter (`notElem` enclosing) (nub (concatMap tvs quals' ++ concatMap tvs fields'))
inits = catMaybes minits
let initTyss = map (\(_, ty, _) -> toKScheme [] [] (quals' :=> ty)) inits
return (Ctor name vs (gen 0 vs quals') (gen 0 vs fields'), [(id, tys, e) | ((id, _, e), tys) <- zip inits initTyss])
instance Sugared S.Bitdatatype (Top, [TypingGroup PredFN Id])
where desugar (S.Bitdatatype name size ctors drv) =
do size' <- toMaybeScheme `fmap` desugar size
(ctors', inits) <- unzip `fmap` mapM (desugarCtorWithInit []) ctors
return (Bitdatatype name size' ctors' drv,
[Explicit (v, [], MCommit e) tys | (v, tys, e) <- concat inits])
instance Sugared S.BitdataField (BitdataField Id, Maybe (Id, Located (Type Id), Located (Expr PredFN Id)))
where desugar (S.LabeledField name ty Nothing) =
do ty' <- desugar ty
return (LabeledField name ty' Nothing, Nothing)
desugar (S.LabeledField name ty (Just (At loc init))) =
do v <- fresh "init"
ty' <- desugar ty
init' <- desugar init
return (LabeledField name ty' (Just v), Just (v, ty', At loc init'))
desugar (S.ConstantField lit) =
return (ConstantField lit, Nothing)
instance Sugared S.Struct (Top, [TypingGroup PredFN Id])
where desugar (S.Struct name size ctor align drv) =
do size' <- toMaybeScheme `fmap` desugar size
align' <- toMaybeLocatedScheme `fmap` desugar align
(ctor', inits) <- desugarCtorWithInit [] ctor
return (Struct name size' ctor' align' drv,
[Explicit (v, [], MCommit e) tys | (v, tys, e) <- inits])
instance Sugared S.StructRegion (StructRegion Id, Maybe (Id, Located (Type Id), Located (Expr PredFN Id)))
where desugar (S.StructRegion Nothing ty) =
do ty' <- desugar ty
return (StructRegion Nothing ty', Nothing)
desugar (S.StructRegion (Just field) ty) =
do (field', init') <- desugar field
ty'@(At loc _) <- desugar ty
let init'' = do (id, e) <- init'
return (id, At loc (TyApp (At loc (TyCon "Init")) ty'), e)
return (StructRegion (Just field') ty', init'')
instance Sugared S.StructField (StructField, Maybe (Id, Located (Expr PredFN Id)))
where desugar (S.StructField name Nothing) = return (StructField name Nothing, Nothing)
desugar (S.StructField name (Just (At loc init))) =
do v <- fresh "init"
init' <- desugar init
return (StructField name (Just v), Just (v, At loc init'))
instance Sugared S.Area (Top, [TypingGroup PredFN Id])
where desugar (S.Area v namesAndInits ty align mdecls) =
do qty@(ps :=> t) <- desugar ty
let tys = toScheme [] qty
initTy = toKScheme [] [] (ps :=> introduced (TyApp (introduced (TyCon "Init"))
(introduced (TyApp (introduced (TyCon "AreaOf")) t))))
align' <- toMaybeLocatedScheme `fmap` desugar align
Decls groups <-
case mdecls of
Nothing -> return (Decls [])
Just decls -> desugar decls
(ps, inits) <- unzip `fmap` mapM rewriteInit namesAndInits
return ( Area v ps tys align'
, groups ++ [Explicit (v, [], MCommit e) initTy | (v, e) <- inits] )
where rewriteInit (At loc name, Nothing) =
do v <- fresh "init"
return ((At loc name, v), (v, At loc (EVar "initialize")))
rewriteInit (name, Just init) =
do v <- fresh "init"
init' <- desugar init
return ((name, v), (v, init'))
----------------------------------------------------------------------------------------------------
-- Primitives
validatePrimitiveTypeParameter :: Located (Either KId Id) -> M (Located KId)
validatePrimitiveTypeParameter (At l (Right _)) = failAt l $ failWithS "All arguments to primitive types and classes must have kind annotations"
validatePrimitiveTypeParameter (At l (Left id)) = return (At l id)
instance Sugared S.Primitive (Either (Signature PredFN Id, String) (Primitive PredFN Id))
where desugar (S.PrimValue s name _) =
do s' <- desugar s; return $ Left (s', name)
desugar (S.PrimCon s name _) =
do s' <- desugar s; return (Right (PrimCon s' name))
desugar (S.PrimType lhs) =
Right `fmap`
do lhs' <- desugar lhs
case flattenType lhs' of
(At _ (TyCon name), params) ->
do params' <- mapM validatePrimitiveTypeParameter =<< foldrM validateTypeParameter [] params
return (PrimType name (foldr KFun KStar (map (kind . dislocate) params')))
(At _(TyKinded (At _ (TyCon name)) (At _ k)), []) ->
return (PrimType name k)
_ -> failWithS "Invalid primitive type declaration"
desugar (S.PrimClass lhs determined constraints mdecls) =
Right `fmap`
do lhs' <- desugar lhs
case flattenType lhs' of
(At _ (TyCon _), []) ->
failWithS "Primitive class without parameters is primitively pointless"
(At _ (TyCon name), params) ->
do params' <- case determined of
Nothing -> return params
Just t -> do t' <- desugar t
return (params ++ [t'])
params'' <- mapM validatePrimitiveTypeParameter =<< foldrM validateTypeParameter [] params'
let eitheredParams = map (fmap Left) params''
constraints' <- mapM (desugarFunctionalDependency eitheredParams) constraints
let n = length params''
constraints'' = case determined of
Nothing -> constraints'
Just (At loc _) -> At loc ([0..n - 2] :~> [n - 1]) : constraints'
methods <-
case mdecls of
Nothing -> return []
Just decls ->
do when (not (null (S.equations decls))) $ failWithS "Unexpected default method in primitive class declaration"
mapM (desugarMethodSignature eitheredParams) (S.signatures decls)
return (PrimClass name params'' constraints'' methods)
----------------------------------------------------------------------------------------------------
Desugaring programs
The one complication here is that we need to know the order of bitdata fields when desugaring
patterns . Therefore , we start by collecting fields from each bitdata ctor ; afterwards , we can
map ' ' across the program structure as usual .
type DesugaringState = ([(Id, Id)], CtorEnv)
desugarProgram :: Has s DesugaringState => Pass s S.Program (Program PredFN Id (Either KId Id))
desugarProgram = up (\p -> PassM (StateT (f p)))
where f p globals = runReaderT (runM (convertProgram p globals)) ([], [])
pushLocationInwards :: Located [t] -> [Located t]
pushLocationInwards (At l ts) = map (At l) ts
typeDeclNames :: [Located Top] -> [Located Id]
typeDeclNames = catMaybes . map nameFrom
where nameFrom (At l (Datatype name _ _ _ _)) = Just (At l name)
nameFrom (At l (Bitdatatype name _ _ _)) = Just (At l name)
nameFrom (At l (Struct name _ _ _ _)) = Just (At l name)
nameFrom (At l (Area {})) = Nothing
nameFrom (At l (Class name _ _ _ _)) = Just (At l name)
nameFrom (At l (Instance {})) = Nothing
primitiveTypeNames = catMaybes . map nameFrom
where nameFrom (At l (PrimType name _)) = Just (At l name)
nameFrom (At l (PrimClass name _ _ _)) = Just (At l name)
tyconName :: Located S.Type -> M Id
tyconName ty = do ty' <- desugar ty
case flattenType ty' of
(At _ (TyCon name), _) -> return name
_ -> error ("tyconName (" ++ show (ppr ty) ++ ")")
convertProgram :: S.Program -> DesugaringState -> M (Program PredFN Id (Either KId Id), DesugaringState)
convertProgram p (globalMethodNames, (globalBitCtors, globalStructCtors)) =
bindCtors (bitCtorNames, structCtorNames) $
do Decls values <- desugar (S.decls p)
methodNames' <- (++ globalMethodNames) `fmap`
mapM (\(lhs, m) -> do name <- tyconName lhs; return (name, m))
methodNames
classesAndSupers <- (concat . map pushLocationInwards) `fmap` mapM desugar (S.classes p)
(instances, instPrimTypes) <- unzipLocated' `fmap` mapM desugar (S.instances p)
requirements <- mapM desugar (S.requirements p)
synonyms <- (concat . map pushLocationInwards) `fmap` mapM desugar (S.synonyms p)
datatypes <- (concat . map pushLocationInwards) `fmap` mapM desugar (S.datatypes p)
(bitdatatypes, bitdataInits) <- unzipLocated `fmap` mapM desugar (S.bitdatatypes p)
(structures, structureInits) <- unzipLocated `fmap` mapM desugar (S.structures p)
(areas, areaInits) <- unzipLocated `fmap` mapM desugar (S.areas p)
primitives <- mapM desugar (S.primitives p)
let primitiveTypesAndClasses = [At t p | At t (Right p) <- primitives]
primitiveValues = [PrimValue p s | At t (Left (p, s)) <- primitives]
topDecls = classesAndSupers ++ instances ++ requirements ++ synonyms ++ datatypes ++ bitdatatypes ++ structures ++ areas
rejectDuplicates locatedCtorNames
return (Program (Decls (values ++ concat bitdataInits ++ concat structureInits ++ concat areaInits ++ primitiveValues))
topDecls
(primitiveTypesAndClasses ++ concat (map pushLocationInwards instPrimTypes))
, (methodNames', (bitCtorNames, structCtorNames)))
where bitCtorNames = [(name, nullary fields) | At _ (S.Bitdatatype _ _ ctors _) <- S.bitdatatypes p,
Ctor (At _ name) _ _ fields <- ctors]
++ globalBitCtors
nullary fields = null [n | At _ (S.LabeledField n _ _) <- fields]
structCtorNames = [name | At _ (S.Struct _ _ (Ctor _ _ _ regions) _ _) <- S.structures p,
At _ (S.StructRegion (Just (S.StructField (At _ name) _)) _) <- regions]
++ globalStructCtors
methodNames =
[(classLHS, id) | At _ (S.Class classLHS _ _ (Just ds)) <- S.classes p, S.Signature id _ <- S.signatures ds] ++
[(classLHS, id) | At _ (S.PrimClass classLHS _ _ (Just ds)) <- S.primitives p, S.Signature id _ <- S.signatures ds]
allMethodNames = map snd methodNames ++ map snd globalMethodNames
locatedCtorNames =
concat ([map ctorName ctors | At _ (S.Datatype _ ctors _ _) <- S.datatypes p] ++
[map ctorName ctors | At _ (S.Bitdatatype _ _ ctors _) <- S.bitdatatypes p])
ctorNames = map dislocate locatedCtorNames
areaNames =
concat [map dislocate (fst (unzip inits)) | At _ (S.Area _ inits _ _ _) <- S.areas p]
primitiveNames =
[id | At _ (S.PrimValue (S.Signature id _) _ _) <- S.primitives p]
primitiveNamesAndVisibilities =
[(id, visible) | At _ (S.PrimValue (S.Signature id _) _ visible) <- S.primitives p]
-- TODO: consider rewording the text of the error message produced by this function so that it fits
-- with all uses.
rejectDuplicates :: [Located Id] -> M ()
rejectDuplicates ids =
case duplicates ids of
[] -> return ()
ds -> failWithS (unlines [fromId id ++ " appears at both " ++ show l ++ " and " ++ show l' | (id, l, l') <- ds])
where duplicates :: [Located Id] -> [(Id, Location, Location)]
duplicates [] = []
duplicates (At l id : rest) =
case locateDuplicate id rest of
Just l' -> (id, l, l') : rest'
_ -> rest'
where rest' = duplicates rest
locateDuplicate _ [] = Nothing
locateDuplicate id (At l id' : rest)
| id == id' = Just l
| otherwise = locateDuplicate id rest
| null | https://raw.githubusercontent.com/habit-lang/alb/567d4c86194a884cc1ceeffca9663211de2d554c/src/Analyzer/Desugaring.hs | haskell | This module eliminates much of the sugar of the surface syntax, generating the implicitly typed
intermediate language used for type checking. In the process, we perform some verification, such
as checking that variable and constructor names are in scope, equations are valid definitions,
etc.
DONE: factor out tuples
DONE: duplicate name checking (leaving it in for now)
TODO: add checking for Ctors being in scope
TODO: nullary??
TODO: why can't we have variables in instances? (warn on non-function instance method?)
TODO: gen??
TODO: rejectDuplicates
--------------------------------------------------------------------------------------------------
Translation monad
--------------------------------------------------------------------------------------------------
(bitdata ctors (id, nullary), struct ctors)
expressions to their prefix equivalents), the scope environment, an integer for fresh name
generation, and indicates errors a pair of an (optional) source location and error message.
--------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------
The 'desugar' function is overloaded to perform desugaring on most syntax tree nodes.
We can lift desugaring through standard constructors.
--------------------------------------------------------------------------------------------------
Types and Predicates
are not in ids.
--------------------------------------------------------------------------------------------------
Expressions
Shortcuts for constructing expressions: in particular, this handles inserting valid locations for
applications.
rewriting a normal if/case expression.
if cond cons alt is rewritten to the match { True <- cond => ^cons | ^alt }; note that
we're (now) avoiding the unnecessary check for False in the alternative branch.
We begin a case by binding the scrutinee to a new value; this avoids recomputing it for
each guard in the match.
Alternative may bind new names. We begin by constructing replacements for
any bound names that would shadow existing definitions; after this,
desugaring the alternative is straightforward.
far below) which handles the details of desugaring patterns and introducing new
parameter names when necessary.
e.l is rewritten to the application select e l; similarly, e[l = e'] is rewritten to
update e l e'
Sections are uniformly rewritten to lambdas
An expression:
e :: sigma
is equivalent to
let x :: sigma; x = e in x
declsToMatch abstracts the construction of let guards from local declaration blocks. As the
construction of the internal match needs to take the symbols and replacements from the outer
declaration block into account, we take a computation to construct the inner match instead of the
match itself.
--------------------------------------------------------------------------------------------------
Patterns and parameters
Note that we don't check pattern variables against the variables in scope or anything; computing
replacements is the responsibility of the code that handles the scoping node (such as a case
statement, above, or an equation in a declaration block, below).
A literal pattern l is interpreted as a guarded pattern (var | let test = var == l,
True <- test) for some new variables var and test. (The introduction of test is
necessary to preserve the invariant, required in later stages, that the expression on
the right of a PGuarded is a variable.
x@p is equivalent to the guarded pattern (x | p <- x)
The surface syntax supports arbitrary application in patterns; this is so that we don't
have to sort out function definitions vs constructor applications during parsing.
that the arguments to a PCon all be variables; fixing this is separated into
buildGuardedPattern.
case lookup id bitCtors of
Just nullary | nullary -> do v <- fresh "v"
return (PCon id [v])
_ -> return (PCon id [])
variable to represent this field name
buildGuardedPattern takes a nested pattern and constructs an unnested pattern. The basic notion
is that given a pattern of the form C (D p), this is equivalent to the guarded pattern (C x | D p
<- x) for a fresh variable x. buildGuardedPattern performs this transformation recursively until
remove guards of the form _ <- e; this ought to be relatively simple to add.
below) we need to split a list of patterns into a list of parameters and a match, so we define a
--------------------------------------------------------------------------------------------------
Local declaration blocks
The majority of the confusion in this module is in handling declaration blocks. There are
several issues that arise at this point:
are patterns, which can either correspond to value bindings (a top level application of a
constructor to a list of patterns) or function bindings (a top level application of variable
to a list of patterns). The possible presence of infix expressions further complicates this:
values are being defined, we can't compute replacements yet.
those identifiers shadow higher-level bindings, and compute replacements if they do. With the
* Next, we need to combine multiple equations defining functions into single definitions,
sticking the different set of patterns together into matches. We don't do this with much
intelligence at this point. For example, given the equations:
f (Just x) (Just y) = ..
f (Just x) _ = ..
f _ _ = ..,
* Finally, we need to combine the definitions into group for typechecking. The notion here is
that we need to typecheck mutually recursive functions together to be able to compute types at
all; however, if we include extra definitions we may compute types that are too restrictive.
A further observation is that we can always check explicitly typed bindings separately: in the
remainder of the program, we can assume that the signature is valid. To compute theses
references without type signatures.
Split bindings into value and function definitions (and indicate errors for
others).
Figure out what we're actually defining
Now we can finally desugar the right hand sides.
And merge sequential equations defining cases of the same function. This will
fail if equations defining the same symbol are interlaced with equations
defining different symbols.
... and construct the result.
splitPattern is responsible for distinguishing value and function bindings
desugarEquation actually has surprisingly little work left: we've already
distinguished value and function bindings, we've already handled binings and
replacements; all that's left is calling the desugar methods for the left-
and right-hand sides. In the process, we attempt to desugar "value"
definitions with lambdas on the right-hand side to function definitions; this
allows recursion in definitions like:
f = \ x -> f x
which would otherwise be illegal.
or definitions of the form
Note that we won't commute a lambda past a let guard or a pattern match
against anything besides the variable in the outermost lambda.
mergeEquations is fairly simple: we iterate over the equations, tracking the
function defined in the last equation encountered (if any). Multiple
after we check that they have the same number of parameters; value equations
are passed through unchanged.
--------------------------------------------------------------------------------------------------
Top level declarations
Both instance and class declarations have the odd invariant that their 'where' blocks can only
contain function definitions. Unfortunately, the 'Decls' conversion code will interpret a
declaration of the form:
x = id
form of pattern binding.
Another common pattern in many top level declarations, including classes, type synonyms,
parenthesization, and various other forms of pathological code) but require that it fit a
stricter pattern (something applied to a set of (possibly kinded) type variables). This function
We don't want to use the default implementation of desugar for method signatures because we don't
want to quantify over class parameters; e.g., in the definition
--------------------------------------------------------------------------------------------------
Primitives
--------------------------------------------------------------------------------------------------
TODO: consider rewording the text of the error message produced by this function so that it fits
with all uses. | # LANGUAGE FunctionalDependencies , FlexibleContexts , FlexibleInstances ,
GeneralizedNewtypeDeriving , MultiParamTypeClasses , TypeSynonymInstances ,
UndecidableInstances , OverloadedStrings #
GeneralizedNewtypeDeriving, MultiParamTypeClasses, TypeSynonymInstances,
UndecidableInstances, OverloadedStrings #-}
module Analyzer.Desugaring (desugarProgram, DesugaringState) where
import Control.Monad.Reader
import Control.Monad.State
import Data.Char (isUpper, isAlpha)
import Data.Either (partitionEithers)
import Data.Foldable (foldrM)
import Data.Graph (SCC(..), stronglyConnComp)
import qualified Data.IntSet as Set
import Data.List
import qualified Data.Map as Map
import Data.Maybe (catMaybes)
import Common
import Printer.Common ((<+>), text)
import Printer.Surface
import Printer.IMPEG hiding (paramName)
import qualified Syntax.Surface as S
import Syntax.IMPEG hiding (replacement)
import qualified Syntax.IMPEG.KSubst as K
import Syntax.IMPEG.TSubst
DONE : factor out isBound
TODO : toScheme as post pass ? ?
TODO : as a post - desugar optimization
type ScopeEnv = Map.Map Id (Located Id)
The translation monad , tracks the field map , a set of fixities ( used in rewriting infix
newtype M t = M { runM :: ReaderT CtorEnv Base t }
deriving (Functor, Applicative, Monad, MonadBase, MonadReader CtorEnv)
bindCtors :: CtorEnv -> M t -> M t
bindCtors (bitCtors, structCtors) = local (\(bitCtors', structCtors') ->
(bitCtors ++ bitCtors', structCtors ++ structCtors'))
Desugaring
class Sugared t u | t -> u
where desugar :: t -> M u
instance Sugared t u => Sugared (Located t) (Located u)
where desugar (At p t) = failAt p (At p `fmap` desugar t)
instance Sugared t u => Sugared (Maybe t) (Maybe u)
where desugar Nothing = return Nothing
desugar (Just t) = Just `fmap` desugar t
instance (Sugared t t', Sugared u u') => Sugared (t, u) (t', u')
where desugar (x, y) = liftM2 (,) (desugar x) (desugar y)
tupleName :: Int -> Id
tupleName n = fromString ("$Tuple" ++ show n)
instance Sugared S.Type (Type Id)
where desugar (S.TyCon id) = return (TyCon id)
desugar (S.TyVar id) = return (TyVar id)
desugar S.TyWild = failWithS "Unexpected type wildcard"
desugar (S.TyApp t t') = liftM2 TyApp (desugar t) (desugar t')
desugar (S.TyNat l) = return (TyNat l)
desugar e@(S.TyTuple _) = failWith $ text "Internal error: tuple type at desugaring: " <+> ppr e
desugar e@(S.TyTupleCon _) = failWith $ text "Internal error: tuple type constructor at desugaring: " <+> ppr e
desugar (S.TyKinded t k) =
do t' <- desugar t
return (TyKinded t' k)
desugar (S.TyLabel id) = return (TyLabel id)
desugar (S.TySelect t (At p l)) =
desugar (dislocate (app [introduced (S.TyCon "Select"), t, At p (S.TyLabel l)]))
where app = foldl1 (\t t' -> at t (S.TyApp t t'))
desugar e@(S.TyInfix head tail) = failWith $ text "Internal error: infix type at desugaring: " <+> ppr e
instance Sugared S.Pred (PredType PredFN Id)
where desugar (S.Pred t mt f) =
do t' <- desugar t
mt' <- desugar mt
case flattenType t' of
(At _ (TyCon id@(Ident (c:_) _ _)), ts) | isUpper c || not (isAlpha c) ->
return (PredFN id ts mt' f)
_ -> failWithS "Predicate must consist of a tyconsym applied to a list of types"
instance Sugared (S.Qual S.Type) (Qual (PredType PredFN Id) (Type Id))
where desugar (ps S.:=> t) = liftM2 (:=>) (mapM desugar ps) (desugar t)
instance Sugared (S.Qual S.Pred) (Qual (PredType PredFN Id) (PredType PredFN Id))
where desugar (ps S.:=> t) = liftM2 (:=>) (mapM desugar ps) (desugar t)
toScheme ids qty generates a new type scheme that quantifies over all the variables in qty that
toScheme :: [Id] -> Qual (PredType PredFN Id) (Type Id) -> Scheme PredFN Id
toScheme retained qty = Forall vs (gen 0 vs qty)
where vs = nub (tvs qty) \\ retained
toKScheme :: [Id] -> [Id] -> Qual (PredType PredFN Id) (Type Id) -> KScheme (Scheme PredFN Id)
toKScheme retained retainedTyVars qty = ForallK kvs (toScheme retainedTyVars qty)
where kvs = filter (`notElem` retained) (K.vars qty)
(@@) :: Located S.Expr -> Located S.Expr -> Located S.Expr
e @@ e' = at e (S.EApp e e')
infixl 9 @@
app :: Id -> [Located S.Expr] -> S.Expr
app op args = dislocate (foldl (@@) (introduced (S.EVar op)) args)
gfrom :: Pattern PredFN Id -> Expr PredFN Id -> Guard PredFN Id
gfrom p e = GFrom (introduced p) (introduced e)
sfield :: Location -> Id -> Located S.Expr
sfield l f = At l (S.ETyped (At l (S.ECon "Proxy"))
([] S.:=> At l (S.TyApp (At l (S.TyCon "Proxy")) (At l (S.TyLabel f)))))
instance Sugared S.Expr (Expr PredFN Id)
where desugar (S.ELet decls body) =
do decls' <- desugar decls
body' <- desugar body
return (ELet decls' body')
if<- and case<- are handled first by binding the scrutinee to a new value , and then
desugar (S.EIf (S.ScFrom mid cond) cons alt) =
do name <- maybe (fresh "condition") return mid
liftM2 (EBind name)
(desugar cond)
(introduced `fmap`
desugar (S.EIf (S.ScExpr (introduced (S.EVar name))) cons alt))
desugar (S.ECase (S.ScFrom mid scrutinee) alts) =
do name <- maybe (fresh "scrutinee") return mid
liftM2 (EBind name)
(desugar scrutinee)
(introduced `fmap`
desugar (S.ECase (S.ScExpr (introduced (S.EVar name))) alts))
desugar (S.EIf (S.ScExpr cond) cons alt) =
do cond' <- desugar cond
cons' <- desugar cons
alt' <- desugar alt
name <- fresh "condition"
return (EMatch (MGuarded (GFrom (introduced (PVar name)) cond')
((MGuarded (gfrom (PCon "True" []) (EVar name)) (MCommit cons')) `MElse`
(MCommit alt'))))
desugar (S.ECase (S.ScExpr scrutinee) alts) =
do name <- fresh "scrutinee"
scrutinee' <- desugar scrutinee
alts' <- foldl1 MElse `fmap` mapM (desugarAlt name) alts
return (EMatch (MGuarded (GFrom (introduced (PVar name)) scrutinee') alts'))
desugarAlt name (p S.:-> rhs) =
do p'@(At l _) <- desugar p
rhs' <- desugar rhs
return (MGuarded (GFrom p' (At l (EVar name))) rhs')
The majority of the work for ELam is actually handled by desugarParameterList ( defined
desugar (S.ELam patterns body) =
do (args', body') <- desugarParameterList patterns (MCommit `fmap` desugar body)
return (dislocate (foldr elam (introduced (EMatch body')) args'))
where elam v body = introduced (ELam v body)
desugar e@(S.EVar id) = return (EVar id)
desugar (S.ECon id) =
do (bitCtors, structCtors) <- ask
case lookup id bitCtors of
Just nullary | nullary -> return (EBitCon id [])
| otherwise -> return (ECon id)
_ | id `elem` structCtors -> return (EStructInit id [])
| otherwise -> return (ECon id)
desugar (S.ELit (S.BitVector value size)) =
return (EBits value size)
desugar (S.ELit (S.Numeric value)) =
dislocate `fmap` desugar (introduced (S.EVar "fromLiteral") @@ introduced proxy)
where proxyType = [] S.:=> introduced (S.TyApp (introduced (S.TyCon "Proxy")) (introduced (S.TyNat value)))
proxy = S.ETyped (introduced (S.ECon "Proxy")) proxyType
desugar e@(S.ETuple _) = failWith $ text "Internal error: tuple expression at desugaring: " <+> ppr e
desugar e@(S.ETupleCon _) = failWith $ text "Internal error: tuple constructor expression at desugaring: " <+> ppr e
desugar (S.EApp (At _ (S.EApp (At _ (S.EVar "||")) lhs)) rhs) =
do name <- fresh "scrutinee"
lhs' <- desugar lhs
rhs' <- desugar rhs
return (EMatch (MGuarded (GFrom (introduced (PVar name)) lhs')
((MGuarded (gfrom (PCon "False" []) (EVar name)) (MCommit rhs'))
`MElse` MCommit (at lhs (EBitCon "True" [])))))
desugar (S.EApp (At _ (S.EApp (At _ (S.EVar "&&")) lhs)) rhs) =
do name <- fresh "scrutinee"
lhs' <- desugar lhs
rhs' <- desugar rhs
return (EMatch (MGuarded (GFrom (introduced (PVar name)) lhs')
((MGuarded (gfrom (PCon "True" []) (EVar name)) (MCommit rhs'))
`MElse` MCommit (at lhs (EBitCon "False" [])))))
desugar (S.EApp e e') = liftM2 EApp (desugar e) (desugar e')
desugar (S.EBind Nothing e rest) =
do v <- fresh "x"
liftM2 (EBind v) (desugar e) (desugar rest)
desugar (S.EBind (Just v) e rest) =
do e' <- desugar e
rest' <- desugar rest
return (EBind v e' rest')
desugar (S.ESelect e (At p l)) =
desugar (app "select" [e, sfield p l])
desugar (S.EUpdate (At _ (S.ECon id)) []) =
do (bitCtors, structCtors) <- ask
case lookup id bitCtors of
Just _ -> return (EBitCon id [])
_ | id `elem` structCtors -> return (EStructInit id [])
| otherwise -> failWithS ("Constructor "++ fromId id ++" does not support empty update")
desugar (S.EUpdate (At _ (S.ECon id)) fs) =
do fs' <- mapM desugarBinding fs
return (EBitCon id fs')
where desugarBinding (At _ name, e) =
do e' <- desugar e
return (name, e')
desugar (S.EUpdate e fs) =
desugar (dislocate (foldl update e fs))
where update e (At p id, val) =
introduced (S.EVar "update") @@ e @@ sfield p id @@ val
desugar (S.ELeftSection lhs (At p opname)) =
do rhs <- fresh "rhs"
desugar (S.ELam [introduced (S.PVar rhs)] (At p (S.EVar opname) @@ lhs @@ introduced (S.EVar rhs)))
desugar (S.ERightSection (At p opname) rhs) =
do lhs <- fresh "lhs"
desugar (S.ELam [introduced (S.PVar lhs)] (At p (S.EVar opname) @@ introduced (S.EVar lhs) @@ rhs))
desugar (S.EStructInit (At _ name) fields) = liftM (EStructInit name) (mapSndM desugar fields)
desugar (S.ETyped e ty) =
do v <- fresh "x"
e' <- desugar e
tys <- toKScheme [] [] `fmap` desugar ty
return (ELet (Decls [Explicit (v, [], MCommit e') tys]) (introduced (EVar v)))
desugar e@(S.EInfix head tail) = failWith $ text "Internal error: infix expression at desugaring:" <+> ppr e
declsToMatch :: Maybe S.Decls -> M (Match PredFN Id) -> M (Match PredFN Id)
declsToMatch Nothing c = c
declsToMatch (Just ds) c =
do ds' <- desugar ds
m <- c
return (MGuarded (GLet ds') m)
instance Sugared S.Rhs (Match PredFN Id)
where desugar (S.Unguarded body ds) =
declsToMatch ds (MCommit `fmap` desugar body)
desugar (S.Guarded ps ds) =
declsToMatch ds $
do ps' <- mapM desugar ps
vs <- replicateM (length ps') (fresh "condition")
return (foldl1 MElse [ MGuarded (GFrom (introduced (PVar v)) condition)
(MGuarded (gfrom (PCon "True" []) (EVar v))
(MCommit body))
| (v, (condition, body)) <- zip vs ps' ])
instance Sugared S.Pattern (Pattern PredFN Id)
where desugar S.PWild = return PWild
desugar (S.PVar id) = return (PVar id)
desugar (S.PTyped p ty) = liftM2 PTyped (desugar p) (toScheme [] `fmap` desugar ty)
desugar (S.PLit l) =
do var <- fresh "x"
test <- fresh "test"
l' <- desugar (S.ELit l)
let testExpr = introduced (EApp (introduced (EApp (introduced (EVar "=="))
(introduced (EVar var))))
(introduced l'))
return ((PVar var `PGuarded` GLet (Decls [Implicit [(test, [], MCommit testExpr)]]))
`PGuarded` gfrom (PCon "True" []) (EVar test))
desugar (S.PAs id p) =
do p' <- desugar p
return (PGuarded (PVar id) (GFrom p' (introduced (EVar id))))
IMPEG , however , lacks PApp and associates the arguments of a constructor pattern with
the pattern itself . When desugaring a PApp , we desugar each side and then try
flattening the LHS : if the far left argument is a PCon , we add the rest of the patterns
to its arguments ; otherwise , we fail . An additional complication is that IMPEG insists
desugar (S.PCon id) = return (PCon id [])
do ( bitCtors , _ ) < - ask
desugar e@(S.PTuple _) = failWith $ text "Internal error: tuple pattern at desugaring: " <+> ppr e
desugar e@(S.PTupleCon _) = failWith $ text "Internal error: tuple constructor pattern at desugaring: " <+> ppr e
desugar p@(S.PApp {}) =
case op of
At _ (S.PCon name) -> buildGuardedPattern name =<< mapM desugar ps
_ -> failWith $ text "Pattern must be the application of a constructor to a list of arguments: " <+> ppr p
where (op, ps) = S.flattenPattern (introduced p)
desugar (S.PLabeled ctor fieldPatterns) =
do rejectDuplicates [ At loc f | At loc (S.FieldPattern f p) <- fieldPatterns ]
n <- fresh "n"
foldM (addFieldGuards n) (PCon ctor [n]) fieldPatterns
where
For each field pattern field = p , add guards ( ... | let v = src.field , )
addFieldGuards n pat (At loc (S.FieldPattern field p))
p' <- desugar p
At _ body <- desugar (At loc (S.EVar "select") @@ At loc (S.EVar n) @@ sfield loc field)
return ((pat `PGuarded` GLet (Decls [Implicit [(v,[],MCommit (At loc body))]]))
`PGuarded` GFrom p' (introduced (EVar v)))
desugar e@(S.PInfix head tail) = failWith $ text "Internal error: infix expressions/types at desugaring: " <+> ppr e
there are no nested patterns remaining . One transformation that is not performed yet is to
buildGuardedPattern :: Id -> [Located (Pattern PredFN Id)] -> M (Pattern PredFN Id)
buildGuardedPattern name ps =
do (vs, guards) <- unzip `fmap` (mapM toGuard ps)
return (foldl PGuarded (PCon name vs) (catMaybes (zipWith (\v g -> fmap (flip GFrom (introduced (EVar v))) g) vs guards)))
where toGuard (At _ (PVar v)) = return (v, Nothing)
toGuard p = do v <- fresh "p"
return (v, Just p)
That 's fine and all , but when building functions ( either in ELam above or when handling equations
helper function that desugars a list of patterns and an expression into ( a ) a list of variables
and ( b ) a match . The final assembly of these parts is different in the two cases above .
desugarParameterList :: [Located S.Pattern] -> M (Match PredFN Id) -> M ([Id], Match PredFN Id)
desugarParameterList ps c =
do body <- c
foldM desugarPattern ([], body) (reverse ps)
where desugarPattern (args, body) p =
do p' <- desugar p
case p' of
At loc (PVar s) -> return (s : args, body)
_ -> do var <- fresh "x"
return (var : args, MGuarded (GFrom p' (introduced (EVar var))) body)
* The first confusion is figuring out what is actually being defined ; all we get from the parser
we 'd like to use the correct fixities when resolving the LHS 's , but as we do n't yet know which
* Once we 've disentangled the LHS 's , we can determine what the block defines , whether any of
new bindings and replacements in hand , we can desugar the RHS 's of the equations .
we 'll generate two identical pattern matches against the first parameter .
groups , we perform an SCC over a graph where declarations are vertices and edges are
instance Sugared S.Decls (Decls PredFN Id)
where desugar decls =
First , split the equations into their left- and right - hand sides .
let (lhss, rhss) = unzip [(lhs, rhs) | lhs S.:= rhs <- S.equations decls]
lhss' <- mapM splitPattern lhss
equations <- mapM desugarEquation (zip lhss' rhss)
(valDefs, fcnDefs) <- partitionEithers `fmap` mergeEquations equations
let valNames = concatMap (bound . fst) valDefs
fcnNames = [id | (id, _, _) <- fcnDefs]
names = valNames ++ fcnNames
signatures <- mapM desugar (S.signatures decls)
let explicitlyTyped = [name | Signature name _ <- signatures]
when (hasDuplicates names) $
failWithS "Duplicate symbol definition"
when (any (`notElem` names) explicitlyTyped) $
failWithS ("Signatures without definition: " ++ intercalate "," (map fromId (filter (`notElem` names) explicitlyTyped)))
Finally , we perform the SCC ...
let simpleGroups = [(Left (p, e), i, bound p, freeVariables e \\ explicitlyTyped) | (i, (p, e)) <- zip [0,2..] valDefs] ++
[(Right (name, args, body), i, [name], freeVariables body \\ (args ++ explicitlyTyped))
| (i, (name, args, body)) <- zip [1,3..] fcnDefs ]
nodes = [(body, i, links)
| (body, i, _, needed) <- simpleGroups
, let links = [j | (_, j, bound, _) <- simpleGroups, not (null (needed `intersect` bound))]]
sccs = stronglyConnComp nodes
decls' <- liftM Decls (mapM (makeTypingGroup signatures) sccs)
return decls'
splitPattern :: Located S.Pattern -> M (Either (Located S.Pattern) (Id, [Located S.Pattern]))
splitPattern p =
case S.flattenPattern p of
(At _ (S.PVar fcn), args) ->
return (Right (fcn, args))
(At _ (S.PCon name), _) ->
return (Left p)
(p, []) ->
return (Left p)
_ -> failWithS "Invalid LHS"
singleton = (:[])
desugarEquation :: (Either (Located S.Pattern) (Id, [Located S.Pattern]), S.Rhs)
-> M (Either (Located (Pattern PredFN Id), Match PredFN Id) (Id, [Located (Pattern PredFN Id)], Match PredFN Id))
desugarEquation (Left p, rhs) =
do p' <- desugar p
m <- desugar rhs
case p' of
At _ (PVar name) ->
case commuteLambdas m of
([], _) -> return (Left (p', m))
(ps, body) -> return (Right (name, map (introduced . PVar) ps, body))
_ -> return (Left (p', m))
desugarEquation (Right (name, params), rhs) =
do params' <- mapM desugar params
body <- desugar rhs
return (Right (name, params', body))
We commute lambdas in two cases ; either definitions of the form :
f = { ^ \x - > { p < - x = > m } }
f = { ^ \x - > m }
commuteLambdas :: Match PredFN Id -> ([Id], Match PredFN Id)
commuteLambdas (MCommit (At _ (ELam v (At _ (EMatch (MGuarded (GFrom p (At l (EVar v'))) body))))))
| v == v' = (v:ps, MGuarded (GFrom p (At l (EVar v))) body')
where (ps, body') = commuteLambdas body
commuteLambdas (MCommit (At _ (ELam v (At _ (EMatch body))))) = (v:ps, body')
where (ps, body') = commuteLambdas body
commuteLambdas m = ([], m)
hasDuplicates :: Eq t => [t] -> Bool
hasDuplicates [] = False
hasDuplicates (t:ts) = t `elem` ts || hasDuplicates ts
equations defining ( cases of ) the same function are combined using MElse
mergeEquations :: [Either (Located (Pattern PredFN Id), Match PredFN Id) (Id, [Located (Pattern PredFN Id)], Match PredFN Id)]
-> M [Either (Located (Pattern PredFN Id), Match PredFN Id) (Function PredFN Id)]
mergeEquations [] = return []
mergeEquations eqns = iter [] Nothing eqns
where iter done Nothing [] = return done
iter done (Just inProgress) [] = return (Right inProgress : done)
iter done Nothing (Left (p, e) : rest) = iter (Left (p, e) : done) Nothing rest
iter done (Just inProgress) (Left (p, e) : rest) = iter (Left (p, e) : Right inProgress : done) Nothing rest
iter done Nothing (Right (name, params, match) : rest) =
do args <- replicateM (length params) (fresh "x")
iter done (Just (name, args, matchFrom args params match)) rest
iter done (Just (nameIP, argsIP, matchIP)) (Right (name, params, match) : rest)
| nameIP == name =
if length argsIP /= length params
then failWithS ("Different arities in equations for " ++ fromId name)
else iter done (Just (nameIP, argsIP, MElse matchIP (matchFrom argsIP params match))) rest
| name `elem` [id | Right (id, _, _) <- done] =
failWithS ("Redefinition of function " ++ fromId name)
| otherwise =
do newArgs <- replicateM (length params) (fresh "x")
iter (Right (nameIP, argsIP, matchIP) : done) (Just (name, newArgs, matchFrom newArgs params match)) rest
matchFrom :: [Id] -> [Located (Pattern PredFN Id)] -> Match PredFN Id -> Match PredFN Id
matchFrom args params match = foldr (\(arg, p@(At l _)) m -> MGuarded (GFrom p (At l (EVar arg))) m) match (zip args params)
signatureFor :: Id -> [Signature PredFN Id] -> Maybe (Signature PredFN Id)
signatureFor name signatures = iter signatures
where iter [] = Nothing
iter (s@(Signature name' _) : rest)
| name == name' = Just s
| otherwise = iter rest
singleFunctionTypingGroup :: (Id, [Id], Match PredFN Id) -> [Signature PredFN Id] -> TypingGroup PredFN Id
singleFunctionTypingGroup (name, params, body) signatures =
case signatureFor name signatures of
Nothing -> Implicit [(name, params, body)]
Just (Signature _ tys) -> Explicit (name, params, body) tys
makeTypingGroup :: [Signature PredFN Id] -> SCC (Either (Located (Pattern PredFN Id), Match PredFN Id) (Function PredFN Id)) -> M (TypingGroup PredFN Id)
makeTypingGroup signatures (AcyclicSCC (Left (p, e))) =
return (Pattern p e (catMaybes [signatureFor name signatures | name <- bound p]))
makeTypingGroup signatures (AcyclicSCC (Right f)) =
return (singleFunctionTypingGroup f signatures)
makeTypingGroup signatures (CyclicSCC nodes) =
case partitionEithers nodes of
([], [f]) -> return (singleFunctionTypingGroup f signatures)
([], fcns) -> return (Implicit fcns)
((At loc _, _) : _, _) -> failAt loc $ failWithS "Recursive value definition"
instance Sugared S.Signature (Signature PredFN Id)
where desugar (S.Signature id ty) =
liftM (Signature id) (toKScheme [] [] `fmap` desugar ty)
as a pattern binding ( binding ' PVar " x " ' ) rather than a function binding . The following function
desugars pattern bindings of that form to " function " bindings , and indicates errors for any other
coercePatternBinding :: String -> TypingGroup PredFN Id -> M (Functions PredFN Id)
coercePatternBinding _ (Pattern (At _ (PVar s)) m _) = return ([(s, [], m)])
coercePatternBinding _ (Explicit f _ ) = return [f]
coercePatternBinding _ (Implicit fs) = return fs
coercePatternBinding s _ = failWithS s
datatypes , etc . , is that we parse the LHS of the definition as a type ( to allow for infixity ,
serves two roles in that conversion : first , it maps type arguments from ' Type 's to ' TyParam 's ,
and second , looks for duplicate parameters in the process .
validateTypeParameter :: Located (Type Id) -> [Located (Either KId Id)] -> M [Located (Either KId Id)]
validateTypeParameter arg args =
case arg of
At loc (TyVar v)
| v `elem` map paramName args' -> failAt loc $ failWithS ("Duplicate class parameter name '" ++ fromId v ++ "'")
| otherwise -> return (At loc (Right v) : args)
At loc (TyKinded (At _ (TyVar v)) (At _ k))
| v `elem` map paramName args' -> failAt loc $ failWithS ("Duplicate class parameter name '" ++ fromId v ++ "'")
| otherwise -> return (At loc (Left (Kinded v k)) : args)
At loc _ -> failAt loc $ failWith (text "Unexpected class parameter" <+> ppr arg)
where args' = map dislocate args
typeFromTypeParameter :: Located (Either KId Id) -> Located (Type Id)
typeFromTypeParameter (At l (Left (Kinded id k))) = At l (TyKinded (At l (TyVar id)) (At l k))
typeFromTypeParameter (At l (Right id)) = At l (TyVar id)
desugarClassConstraints :: Id -> [Located (Either KId Id)] -> [Located S.ClassConstraint] -> M ([Located ClassConstraint], [Top])
desugarClassConstraints className params constraints = partitionEithers `fmap` mapM desugar' constraints
where desugar' (At loc (S.Superclass p)) =
do n <- fresh "super"
p' <- desugar p
return (Right (Require [(n, At loc p')] [At loc (PredFN className (map typeFromTypeParameter params) Nothing Holds)]))
desugar' (At loc (S.Fundep fd)) =
do (At _ fd') <- desugarFunctionalDependency params (At loc fd)
return (Left (At loc (Fundep fd')))
desugar' (At loc (S.Opaque v)) =
case findIndex (v ==) names of
Nothing -> failWithS "Invalid parameter name in opacity constraint"
Just i -> return (Left (At loc (Opaque i)))
where names = map (paramName . dislocate) params
desugarFunctionalDependency :: [Located (Either KId Id)] -> Located (Fundep Id) -> M (Located (Fundep Int))
desugarFunctionalDependency params (At loc (xs :~> ys)) =
failAt loc $
case (xs', ys') of
(Just xs', Just ys') -> return (At loc (xs' :~> ys'))
_ -> failWithS "Invalid parameter name in functional dependency constraint"
where names = map (paramName . dislocate) params
toIdx s = findIndex (s ==) names
xs' = mapM toIdx xs
ys' = mapM toIdx ys
class Eq t where (= =) : : t - > t - > Bool
= = 's type should remain t - > t - > Bool , not forall _ 0 - > Bool .
desugarMethodSignature ps (S.Signature name qty) = Signature name `fmap` (toKScheme pkvars pvars `fmap` desugar qty)
where pkvars = K.vars ps
pvars = map (paramName . dislocate) ps
type Top = TopDecl PredFN Id (Either KId Id)
instance Sugared S.Class [Top]
where desugar (S.Class ty determined constraints mdecls) =
do ty' <- desugar ty
case flattenType ty' of
(At _ (TyCon name), []) ->
failWithS "Class without parameters is pointless"
(At _ (TyCon name), params) ->
do params' <- case determined of
Nothing -> return params
Just t -> do t' <- desugar t
return (params ++ [t'])
params'' <- foldrM validateTypeParameter [] params'
(constraints', requirements) <- desugarClassConstraints name params'' constraints
let n = length params''
constraints'' = case determined of
Nothing -> constraints'
Just (At loc _) -> At loc (Fundep ([0..n - 2] :~> [n - 1])) : constraints'
(methods, defaults) <-
case mdecls of
Nothing -> return ([], [])
Just decls ->
do let defaultNames = concatMap lhsBound [lhs | lhs S.:= _ <- S.equations decls]
defaultSignatures = [s | s@(S.Signature name _) <- S.signatures decls, name `elem` defaultNames]
methodNames = [name | S.Signature name _ <- S.signatures decls]
defaultDecls <- desugar decls { S.signatures = defaultSignatures }
defaults <- concatMapM (coercePatternBinding "Class method defaults must be functions")
(groups defaultDecls)
when (any (`notElem` methodNames) defaultNames) $
failWithS ("Default implementation for non-class method: " ++ intercalate ", " (map fromId (filter (`notElem` methodNames) defaultNames)))
signatures' <- mapM (desugarMethodSignature params'') (S.signatures decls)
return (signatures', defaults)
return (Class name params'' constraints'' methods defaults : requirements)
_ -> failWithS "Invalid class LHS (must be a class name applied to a list of parameters)"
where lhsBound :: Located S.Pattern -> [Id]
lhsBound p = case S.flattenPattern p of
(At loc (S.PVar name), []) -> [name]
(At loc (S.PVar fcn), args) -> [fcn]
(At loc (S.PCon name), args) -> concatMap bound args
(p, []) -> bound p
instance Sugared S.Instance (Top, [Primitive PredFN Id])
where desugar (S.Instance chain) =
do name <- fresh "i"
(chain', topDecls) <- unzip `fmap` mapM desugar' chain
let (cl:cls) = [name | (_ :=> At _ (PredFN name _ _ _), _) <- chain']
if all (cl ==) cls
then return (Instance name cl chain', catMaybes topDecls)
else failWithS "Instance refers to different classes"
where desugar' (qs S.:=> At l1 (S.Pred t (Just (At l2 S.TyWild)) Holds), mdecls) =
do name <- fresh "T"
((qp', decls), _) <- desugar' (qs S.:=> At l1 (S.Pred t (Just (At l2 (S.TyCon name))) Holds), mdecls)
return ((qp', decls), Just (PrimType name (KVar name)))
desugar' (qp, mdecls) =
do qp' <- desugar qp
decls <- maybe (return emptyDecls) desugar mdecls
>>= (concatMapM (coercePatternBinding "Instance methods must be functions") . groups)
return ((qp', decls), Nothing)
instance Sugared S.Requirement Top
where desugar (S.Require ps qs) =
do names <- replicateM (length ps) (fresh "require")
ps <- mapM desugar ps
Require (zip names ps) `fmap` mapM desugar qs
desugarInterface :: Id -> [Located (Either KId Id)] -> [Located (PredType PredFN Id)] -> Located (Type Id) -> S.Decls -> M [Top]
desugarInterface name params rhsPreds rhsType interface =
do instName <- fresh "opaque"
Decls ds <- desugar interface
signatures <- mapM (desugarMethodSignature params) (S.signatures interface)
case mapM fromTypingGroup ds of
Nothing ->
failWithS ("Unexpected declaration in opaque type interface")
Just impls ->
let cl = Class name
(params ++ [introduced (Right "t$")])
[introduced (Fundep ([0..n-1] :~> [n])), introduced (Fundep ([n] :~> [0..n-1])), introduced (Opaque n)]
signatures
[]
inst = Instance instName name
[(rhsPreds :=> introduced (PredFN name (map typeFromTypeParameter params ++ [rhsType]) Nothing Holds), impls)]
in return [cl, inst]
where n = length params
fromTypingGroup (Explicit impl@(id, _, _) _) =
Just impl
fromTypingGroup _ =
Nothing
instance Sugared S.Synonym [Top]
where desugar (S.Synonym lhs rhs interface) =
do lhs' <- desugar lhs
ps :=> t <- desugar rhs
case flattenType lhs' of
(At _ (TyCon name), params) ->
do params' <- foldrM validateTypeParameter [] params
case interface of
Nothing ->
do instName <- fresh "synonym"
let n = length params'
vs = tvs t
determined = catMaybes (map (findParam 0 params') vs)
fds | null determined = [introduced (Fundep ([0..n - 1] :~> [n]))]
| otherwise = [introduced (Fundep ([n] :~> determined)), introduced (Fundep ([0..n - 1] :~> [n]))]
cl = Class name (params' ++ [introduced (Right "$t")])
fds [] []
v = introduced (TyVar "$t")
inst = Instance instName name
[(ps :=> introduced (PredFN name (map typeFromTypeParameter params' ++ [t]) Nothing Holds), []),
([] :=> introduced (PredFN name (map typeFromTypeParameter params' ++ [v]) Nothing Fails), [])]
return [cl, inst]
Just ds ->
desugarInterface name params' ps t ds
_ -> failWithS "Invalid synonym LHS"
where findParam _ [] _ = Nothing
findParam n (At _ (Left (Kinded id _)) : rest) id'
| id == id' = Just n
| otherwise = findParam (n + 1) rest id'
findParam n (At _ (Right id) : rest) id'
| id == id' = Just n
| otherwise = findParam (n + 1) rest id'
TODO : generalizing over one ( 1 ) case here ...
desugarCtor :: (Sugared p p', Sugared t t', HasTypeVariables p' Id, HasTypeVariables t' Id) =>
[Id] -> Ctor Id p t -> M (Ctor Id p' t')
desugarCtor enclosing (Ctor name _ quals fields) =
do quals' <- mapM desugar quals
fields' <- mapM desugar fields
let vs = filter (`notElem` enclosing) (nub (concatMap tvs quals' ++ concatMap tvs fields'))
return (Ctor name vs (gen 0 vs quals') (gen 0 vs fields'))
instance Sugared S.Datatype [Top]
where desugar (S.Datatype lhs ctors drv interface) =
do (ps :=> lhs') <- desugar lhs
case flattenType lhs' of
(At loc (TyCon name), params) ->
do params' <- foldrM validateTypeParameter [] params
let pnames = map (paramName . dislocate) params'
ctors' <- mapM (desugarCtor pnames) ctors
case interface of
Nothing -> return [Datatype name params' ps ctors' drv]
Just ds -> do name' <- fresh name
let rhs = foldl (\t p -> at t (TyApp t (typeFromTypeParameter p))) (At loc (TyCon name')) params'
topDecls' <- desugarInterface name params' [] rhs ds
return (Datatype name' params' ps ctors' drv : topDecls')
_ -> failWithS "Invalid datatype LHS"
instance Sugared S.DataField (Type Id)
where desugar (S.DataField _ (At l t)) = desugar t
toMaybeScheme = maybe Nothing (Just . toScheme [])
toMaybeLocatedScheme = maybe Nothing (\(At loc qt) -> Just (At loc (toScheme [] qt)))
unzipLocated :: [Located (a, b)] -> ([Located a], [b])
unzipLocated lps = (as, map dislocate bs)
where (as, bs) = unzipLocated' lps
unzipLocated' :: [Located (a, b)] -> ([Located a], [Located b])
unzipLocated' lps = unzip [(At p t, At p u) | At p (t, u) <- lps]
type Init t = (Id, t, Located (Expr PredFN Id))
desugarCtorWithInit :: (Sugared t (t', Maybe (Init (Located (Type Id)))), HasTypeVariables t' Id)
=> [Id] -> Ctor Id S.Pred t -> M (Ctor Id (PredType PredFN Id) t', [Init (KScheme (Scheme PredFN Id))])
desugarCtorWithInit enclosing (Ctor name _ quals fields) =
do quals' <- mapM desugar quals
(fields', minits) <- unzipLocated `fmap` mapM desugar fields
let vs = filter (`notElem` enclosing) (nub (concatMap tvs quals' ++ concatMap tvs fields'))
inits = catMaybes minits
let initTyss = map (\(_, ty, _) -> toKScheme [] [] (quals' :=> ty)) inits
return (Ctor name vs (gen 0 vs quals') (gen 0 vs fields'), [(id, tys, e) | ((id, _, e), tys) <- zip inits initTyss])
instance Sugared S.Bitdatatype (Top, [TypingGroup PredFN Id])
where desugar (S.Bitdatatype name size ctors drv) =
do size' <- toMaybeScheme `fmap` desugar size
(ctors', inits) <- unzip `fmap` mapM (desugarCtorWithInit []) ctors
return (Bitdatatype name size' ctors' drv,
[Explicit (v, [], MCommit e) tys | (v, tys, e) <- concat inits])
instance Sugared S.BitdataField (BitdataField Id, Maybe (Id, Located (Type Id), Located (Expr PredFN Id)))
where desugar (S.LabeledField name ty Nothing) =
do ty' <- desugar ty
return (LabeledField name ty' Nothing, Nothing)
desugar (S.LabeledField name ty (Just (At loc init))) =
do v <- fresh "init"
ty' <- desugar ty
init' <- desugar init
return (LabeledField name ty' (Just v), Just (v, ty', At loc init'))
desugar (S.ConstantField lit) =
return (ConstantField lit, Nothing)
instance Sugared S.Struct (Top, [TypingGroup PredFN Id])
where desugar (S.Struct name size ctor align drv) =
do size' <- toMaybeScheme `fmap` desugar size
align' <- toMaybeLocatedScheme `fmap` desugar align
(ctor', inits) <- desugarCtorWithInit [] ctor
return (Struct name size' ctor' align' drv,
[Explicit (v, [], MCommit e) tys | (v, tys, e) <- inits])
instance Sugared S.StructRegion (StructRegion Id, Maybe (Id, Located (Type Id), Located (Expr PredFN Id)))
where desugar (S.StructRegion Nothing ty) =
do ty' <- desugar ty
return (StructRegion Nothing ty', Nothing)
desugar (S.StructRegion (Just field) ty) =
do (field', init') <- desugar field
ty'@(At loc _) <- desugar ty
let init'' = do (id, e) <- init'
return (id, At loc (TyApp (At loc (TyCon "Init")) ty'), e)
return (StructRegion (Just field') ty', init'')
instance Sugared S.StructField (StructField, Maybe (Id, Located (Expr PredFN Id)))
where desugar (S.StructField name Nothing) = return (StructField name Nothing, Nothing)
desugar (S.StructField name (Just (At loc init))) =
do v <- fresh "init"
init' <- desugar init
return (StructField name (Just v), Just (v, At loc init'))
instance Sugared S.Area (Top, [TypingGroup PredFN Id])
where desugar (S.Area v namesAndInits ty align mdecls) =
do qty@(ps :=> t) <- desugar ty
let tys = toScheme [] qty
initTy = toKScheme [] [] (ps :=> introduced (TyApp (introduced (TyCon "Init"))
(introduced (TyApp (introduced (TyCon "AreaOf")) t))))
align' <- toMaybeLocatedScheme `fmap` desugar align
Decls groups <-
case mdecls of
Nothing -> return (Decls [])
Just decls -> desugar decls
(ps, inits) <- unzip `fmap` mapM rewriteInit namesAndInits
return ( Area v ps tys align'
, groups ++ [Explicit (v, [], MCommit e) initTy | (v, e) <- inits] )
where rewriteInit (At loc name, Nothing) =
do v <- fresh "init"
return ((At loc name, v), (v, At loc (EVar "initialize")))
rewriteInit (name, Just init) =
do v <- fresh "init"
init' <- desugar init
return ((name, v), (v, init'))
validatePrimitiveTypeParameter :: Located (Either KId Id) -> M (Located KId)
validatePrimitiveTypeParameter (At l (Right _)) = failAt l $ failWithS "All arguments to primitive types and classes must have kind annotations"
validatePrimitiveTypeParameter (At l (Left id)) = return (At l id)
instance Sugared S.Primitive (Either (Signature PredFN Id, String) (Primitive PredFN Id))
where desugar (S.PrimValue s name _) =
do s' <- desugar s; return $ Left (s', name)
desugar (S.PrimCon s name _) =
do s' <- desugar s; return (Right (PrimCon s' name))
desugar (S.PrimType lhs) =
Right `fmap`
do lhs' <- desugar lhs
case flattenType lhs' of
(At _ (TyCon name), params) ->
do params' <- mapM validatePrimitiveTypeParameter =<< foldrM validateTypeParameter [] params
return (PrimType name (foldr KFun KStar (map (kind . dislocate) params')))
(At _(TyKinded (At _ (TyCon name)) (At _ k)), []) ->
return (PrimType name k)
_ -> failWithS "Invalid primitive type declaration"
desugar (S.PrimClass lhs determined constraints mdecls) =
Right `fmap`
do lhs' <- desugar lhs
case flattenType lhs' of
(At _ (TyCon _), []) ->
failWithS "Primitive class without parameters is primitively pointless"
(At _ (TyCon name), params) ->
do params' <- case determined of
Nothing -> return params
Just t -> do t' <- desugar t
return (params ++ [t'])
params'' <- mapM validatePrimitiveTypeParameter =<< foldrM validateTypeParameter [] params'
let eitheredParams = map (fmap Left) params''
constraints' <- mapM (desugarFunctionalDependency eitheredParams) constraints
let n = length params''
constraints'' = case determined of
Nothing -> constraints'
Just (At loc _) -> At loc ([0..n - 2] :~> [n - 1]) : constraints'
methods <-
case mdecls of
Nothing -> return []
Just decls ->
do when (not (null (S.equations decls))) $ failWithS "Unexpected default method in primitive class declaration"
mapM (desugarMethodSignature eitheredParams) (S.signatures decls)
return (PrimClass name params'' constraints'' methods)
Desugaring programs
The one complication here is that we need to know the order of bitdata fields when desugaring
patterns . Therefore , we start by collecting fields from each bitdata ctor ; afterwards , we can
map ' ' across the program structure as usual .
type DesugaringState = ([(Id, Id)], CtorEnv)
desugarProgram :: Has s DesugaringState => Pass s S.Program (Program PredFN Id (Either KId Id))
desugarProgram = up (\p -> PassM (StateT (f p)))
where f p globals = runReaderT (runM (convertProgram p globals)) ([], [])
pushLocationInwards :: Located [t] -> [Located t]
pushLocationInwards (At l ts) = map (At l) ts
typeDeclNames :: [Located Top] -> [Located Id]
typeDeclNames = catMaybes . map nameFrom
where nameFrom (At l (Datatype name _ _ _ _)) = Just (At l name)
nameFrom (At l (Bitdatatype name _ _ _)) = Just (At l name)
nameFrom (At l (Struct name _ _ _ _)) = Just (At l name)
nameFrom (At l (Area {})) = Nothing
nameFrom (At l (Class name _ _ _ _)) = Just (At l name)
nameFrom (At l (Instance {})) = Nothing
primitiveTypeNames = catMaybes . map nameFrom
where nameFrom (At l (PrimType name _)) = Just (At l name)
nameFrom (At l (PrimClass name _ _ _)) = Just (At l name)
tyconName :: Located S.Type -> M Id
tyconName ty = do ty' <- desugar ty
case flattenType ty' of
(At _ (TyCon name), _) -> return name
_ -> error ("tyconName (" ++ show (ppr ty) ++ ")")
convertProgram :: S.Program -> DesugaringState -> M (Program PredFN Id (Either KId Id), DesugaringState)
convertProgram p (globalMethodNames, (globalBitCtors, globalStructCtors)) =
bindCtors (bitCtorNames, structCtorNames) $
do Decls values <- desugar (S.decls p)
methodNames' <- (++ globalMethodNames) `fmap`
mapM (\(lhs, m) -> do name <- tyconName lhs; return (name, m))
methodNames
classesAndSupers <- (concat . map pushLocationInwards) `fmap` mapM desugar (S.classes p)
(instances, instPrimTypes) <- unzipLocated' `fmap` mapM desugar (S.instances p)
requirements <- mapM desugar (S.requirements p)
synonyms <- (concat . map pushLocationInwards) `fmap` mapM desugar (S.synonyms p)
datatypes <- (concat . map pushLocationInwards) `fmap` mapM desugar (S.datatypes p)
(bitdatatypes, bitdataInits) <- unzipLocated `fmap` mapM desugar (S.bitdatatypes p)
(structures, structureInits) <- unzipLocated `fmap` mapM desugar (S.structures p)
(areas, areaInits) <- unzipLocated `fmap` mapM desugar (S.areas p)
primitives <- mapM desugar (S.primitives p)
let primitiveTypesAndClasses = [At t p | At t (Right p) <- primitives]
primitiveValues = [PrimValue p s | At t (Left (p, s)) <- primitives]
topDecls = classesAndSupers ++ instances ++ requirements ++ synonyms ++ datatypes ++ bitdatatypes ++ structures ++ areas
rejectDuplicates locatedCtorNames
return (Program (Decls (values ++ concat bitdataInits ++ concat structureInits ++ concat areaInits ++ primitiveValues))
topDecls
(primitiveTypesAndClasses ++ concat (map pushLocationInwards instPrimTypes))
, (methodNames', (bitCtorNames, structCtorNames)))
where bitCtorNames = [(name, nullary fields) | At _ (S.Bitdatatype _ _ ctors _) <- S.bitdatatypes p,
Ctor (At _ name) _ _ fields <- ctors]
++ globalBitCtors
nullary fields = null [n | At _ (S.LabeledField n _ _) <- fields]
structCtorNames = [name | At _ (S.Struct _ _ (Ctor _ _ _ regions) _ _) <- S.structures p,
At _ (S.StructRegion (Just (S.StructField (At _ name) _)) _) <- regions]
++ globalStructCtors
methodNames =
[(classLHS, id) | At _ (S.Class classLHS _ _ (Just ds)) <- S.classes p, S.Signature id _ <- S.signatures ds] ++
[(classLHS, id) | At _ (S.PrimClass classLHS _ _ (Just ds)) <- S.primitives p, S.Signature id _ <- S.signatures ds]
allMethodNames = map snd methodNames ++ map snd globalMethodNames
locatedCtorNames =
concat ([map ctorName ctors | At _ (S.Datatype _ ctors _ _) <- S.datatypes p] ++
[map ctorName ctors | At _ (S.Bitdatatype _ _ ctors _) <- S.bitdatatypes p])
ctorNames = map dislocate locatedCtorNames
areaNames =
concat [map dislocate (fst (unzip inits)) | At _ (S.Area _ inits _ _ _) <- S.areas p]
primitiveNames =
[id | At _ (S.PrimValue (S.Signature id _) _ _) <- S.primitives p]
primitiveNamesAndVisibilities =
[(id, visible) | At _ (S.PrimValue (S.Signature id _) _ visible) <- S.primitives p]
rejectDuplicates :: [Located Id] -> M ()
rejectDuplicates ids =
case duplicates ids of
[] -> return ()
ds -> failWithS (unlines [fromId id ++ " appears at both " ++ show l ++ " and " ++ show l' | (id, l, l') <- ds])
where duplicates :: [Located Id] -> [(Id, Location, Location)]
duplicates [] = []
duplicates (At l id : rest) =
case locateDuplicate id rest of
Just l' -> (id, l, l') : rest'
_ -> rest'
where rest' = duplicates rest
locateDuplicate _ [] = Nothing
locateDuplicate id (At l id' : rest)
| id == id' = Just l
| otherwise = locateDuplicate id rest
|
3ca8c27b8d8dc631a3bc591c8d081869513e9d3ce687134c1b9d8f727f610274 | gildor478/ocaml-gettext | test4.ml | (**************************************************************************)
(* ocaml-gettext: a library to translate messages *)
(* *)
Copyright ( C ) 2003 - 2008 < >
(* *)
(* This library is free software; you can redistribute it and/or *)
(* modify it under the terms of the GNU Lesser General Public *)
License as published by the Free Software Foundation ; either
version 2.1 of the License , or ( at your option ) any later version ;
(* with the OCaml static compilation exception. *)
(* *)
(* This library is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *)
(* Lesser General Public License for more details. *)
(* *)
You should have received a copy of the GNU Lesser General Public
License along with this library ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307
USA
(**************************************************************************)
let t' = ()
let _ = s_ "s_"
let _ = f_ "f_"
let _ = sn_ "sn_ singular" "sn_ plural" 0
let _ = fn_ "fn_ singular" "fn_ plural" 0
let _ = gettext t' "gettext"
let _ = fgettext t' "fgettext"
let _ = dgettext t' "mydomain" "dgettext"
let _ = fdgettext t' "mydomain" "fdgettext"
let _ = dcgettext t' "mydomain" "dcgettext" LC_ALL
let _ = fdcgettext t' "mydomain" "fdcgettext" LC_ALL
let _ = ngettext t' "ngettext singular" "ngettext plural" 0
let _ = fngettext t' "fngettext singular" "fngettext plural" 0
let _ = dngettext t' "mydomain" "dngettext singular" "dngettext plural " 0
let _ = fdngettext t' "mydomain" "fdngettext singular" "fdngettext plural" 0
let _ =
dcngettext t' "mydomain" "dcngettext singular" "dcngettext plural" 0 LC_ALL
let _ =
fdcngettext t' "mydomain" "fdcngettext singular" "fdcngettext plural" 0
LC_ALL
let _ = TestGettext.s_ "TestGettext.s_"
let _ = TestGettext.f_ "TestGettext.f_"
let _ = TestGettext.sn_ "TestGettext.sn_ singular" "TestGettext.sn_ plural" 0
let _ = TestGettext.fn_ "TestGettext.fn_ singular" "TestGettext.fn_ plural" 0
let _ = GettextCompat.gettext t' "GettextCompat.gettext"
let _ = GettextCompat.fgettext t' "GettextCompat.fgettext"
let _ = GettextCompat.dgettext t' "mydomain" "GettextCompat.dgettext"
let _ = GettextCompat.fdgettext t' "mydomain" "GettextCompat.fdgettext"
let _ = GettextCompat.dcgettext t' "mydomain" "GettextCompat.dcgettext" LC_ALL
let _ =
GettextCompat.fdcgettext t' "mydomain" "GettextCompat.fdcgettext" LC_ALL
let _ =
GettextCompat.ngettext t' "GettextCompat.ngettext singular"
"GettextCompat.ngettext plural" 0
let _ =
GettextCompat.fngettext t' "GettextCompat.fngettext singular"
"GettextCompat.fngettext plural" 0
let _ =
GettextCompat.dngettext t' "mydomain" "GettextCompat.dngettext singular"
"GettextCompat.dngettext plural " 0
let _ =
GettextCompat.fdngettext t' "mydomain" "GettextCompat.fdngettext singular"
"GettextCompat.fdngettext plural" 0
let _ =
GettextCompat.dcngettext t' "mydomain" "GettextCompat.dcngettext singular"
"GettextCompat.dcngettext plural" 0 LC_ALL
let _ =
GettextCompat.fdcngettext t' "mydomain" "GettextCompat.fdcngettext singular"
"GettextCompat.fdcngettext plural" 0 LC_ALL
let _ = TestGettext.Library.s_ "TestGettext.Library.s_"
let _ = TestGettext.Library.f_ "TestGettext.Library.f_"
let _ =
TestGettext.Library.sn_ "TestGettext.Library.sn_ singular"
"TestGettext.Library.sn_ plural" 0
let _ =
TestGettext.Library.fn_ "TestGettext.Library.fn_ singular"
"TestGettext.Library.fn_ plural" 0
let _ = TestGettext.Program.s_ "TestGettext.Program.s_"
let _ = TestGettext.Program.f_ "TestGettext.Program.f_"
let _ =
TestGettext.Program.sn_ "TestGettext.Program.sn_ singular"
"TestGettext.Program.sn_ plural" 0
let _ =
TestGettext.Gettext.Program.fn_ "TestGettext.Program.fn_ singular"
"TestGettext.Program.fn_ plural" 0
| null | https://raw.githubusercontent.com/gildor478/ocaml-gettext/9b7afc702bccace9a544b8efa2a28bc2b13371ed/test/testdata/test4.ml | ocaml | ************************************************************************
ocaml-gettext: a library to translate messages
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
with the OCaml static compilation exception.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
************************************************************************ | Copyright ( C ) 2003 - 2008 < >
License as published by the Free Software Foundation ; either
version 2.1 of the License , or ( at your option ) any later version ;
You should have received a copy of the GNU Lesser General Public
License along with this library ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307
USA
let t' = ()
let _ = s_ "s_"
let _ = f_ "f_"
let _ = sn_ "sn_ singular" "sn_ plural" 0
let _ = fn_ "fn_ singular" "fn_ plural" 0
let _ = gettext t' "gettext"
let _ = fgettext t' "fgettext"
let _ = dgettext t' "mydomain" "dgettext"
let _ = fdgettext t' "mydomain" "fdgettext"
let _ = dcgettext t' "mydomain" "dcgettext" LC_ALL
let _ = fdcgettext t' "mydomain" "fdcgettext" LC_ALL
let _ = ngettext t' "ngettext singular" "ngettext plural" 0
let _ = fngettext t' "fngettext singular" "fngettext plural" 0
let _ = dngettext t' "mydomain" "dngettext singular" "dngettext plural " 0
let _ = fdngettext t' "mydomain" "fdngettext singular" "fdngettext plural" 0
let _ =
dcngettext t' "mydomain" "dcngettext singular" "dcngettext plural" 0 LC_ALL
let _ =
fdcngettext t' "mydomain" "fdcngettext singular" "fdcngettext plural" 0
LC_ALL
let _ = TestGettext.s_ "TestGettext.s_"
let _ = TestGettext.f_ "TestGettext.f_"
let _ = TestGettext.sn_ "TestGettext.sn_ singular" "TestGettext.sn_ plural" 0
let _ = TestGettext.fn_ "TestGettext.fn_ singular" "TestGettext.fn_ plural" 0
let _ = GettextCompat.gettext t' "GettextCompat.gettext"
let _ = GettextCompat.fgettext t' "GettextCompat.fgettext"
let _ = GettextCompat.dgettext t' "mydomain" "GettextCompat.dgettext"
let _ = GettextCompat.fdgettext t' "mydomain" "GettextCompat.fdgettext"
let _ = GettextCompat.dcgettext t' "mydomain" "GettextCompat.dcgettext" LC_ALL
let _ =
GettextCompat.fdcgettext t' "mydomain" "GettextCompat.fdcgettext" LC_ALL
let _ =
GettextCompat.ngettext t' "GettextCompat.ngettext singular"
"GettextCompat.ngettext plural" 0
let _ =
GettextCompat.fngettext t' "GettextCompat.fngettext singular"
"GettextCompat.fngettext plural" 0
let _ =
GettextCompat.dngettext t' "mydomain" "GettextCompat.dngettext singular"
"GettextCompat.dngettext plural " 0
let _ =
GettextCompat.fdngettext t' "mydomain" "GettextCompat.fdngettext singular"
"GettextCompat.fdngettext plural" 0
let _ =
GettextCompat.dcngettext t' "mydomain" "GettextCompat.dcngettext singular"
"GettextCompat.dcngettext plural" 0 LC_ALL
let _ =
GettextCompat.fdcngettext t' "mydomain" "GettextCompat.fdcngettext singular"
"GettextCompat.fdcngettext plural" 0 LC_ALL
let _ = TestGettext.Library.s_ "TestGettext.Library.s_"
let _ = TestGettext.Library.f_ "TestGettext.Library.f_"
let _ =
TestGettext.Library.sn_ "TestGettext.Library.sn_ singular"
"TestGettext.Library.sn_ plural" 0
let _ =
TestGettext.Library.fn_ "TestGettext.Library.fn_ singular"
"TestGettext.Library.fn_ plural" 0
let _ = TestGettext.Program.s_ "TestGettext.Program.s_"
let _ = TestGettext.Program.f_ "TestGettext.Program.f_"
let _ =
TestGettext.Program.sn_ "TestGettext.Program.sn_ singular"
"TestGettext.Program.sn_ plural" 0
let _ =
TestGettext.Gettext.Program.fn_ "TestGettext.Program.fn_ singular"
"TestGettext.Program.fn_ plural" 0
|
34c831d6e06a010510acefc93130b71f322affac2dbafa4112308e966d461fd2 | Hans-Halverson/myte | simplify_instructions.ml | open Mir
open Mir_builders
open Mir_type
type cx = { (* Instructions that could potentially be simplified *)
mutable worklist: VSet.t }
let enqueue_instr ~cx instr_value = cx.worklist <- VSet.add instr_value cx.worklist
let simplify_instruction ~cx instr_value =
let instr = cast_to_instruction instr_value in
let enqueue_operands_and_uses instr_value =
value_iter_uses ~value:instr_value (fun use -> enqueue_instr ~cx use.user);
instruction_iter_operands ~instr (fun operand ->
match operand.value.value with
| Instr _ -> enqueue_instr ~cx operand.value
| _ -> ())
in
let replace_instr_enqueue_uses new_instr_value =
enqueue_operands_and_uses instr_value;
insert_instruction_before ~before:instr_value new_instr_value;
replace_instruction ~from:instr_value ~to_:new_instr_value
in
let replace_instr_with_value_enqueue_uses new_value =
enqueue_operands_and_uses instr_value;
replace_instruction ~from:instr_value ~to_:new_value
in
match instr.instr with
(* Simplify phis where all arguments have the same value *)
| Phi phi ->
(match phi_get_single_arg_value phi with
| None -> ()
| Some arg_value -> replace_instr_with_value_enqueue_uses arg_value)
Comparison followed by not can be changed to inverted comparison
| Unary (Not, operand) ->
(match operand.value.value with
| Instr { instr = Cmp (comparison, op1, op2); _ } ->
let inverted_comparison = invert_comparison comparison in
let new_instr = mk_blockless_cmp ~cmp:inverted_comparison ~left:op1.value ~right:op2.value in
replace_instr_enqueue_uses new_instr
| _ -> ())
| Trunc trunc_arg ->
(match trunc_arg.value.value with
Trunc of a Trunc is combined to a single Trunc to final size
| Instr { instr = Trunc original_arg; _ } ->
let new_trunc_instr = mk_blockless_trunc ~arg:original_arg.value ~type_:instr.type_ in
replace_instr_enqueue_uses new_trunc_instr
Trunc of an extension may either cancel or shorten extension
| Instr { instr = (ZExt ext_arg | SExt ext_arg) as ext_instr; _ } ->
let original_type = type_of_use ext_arg in
let original_size = size_of_type original_type in
let intermediate_type = type_of_use trunc_arg in
let intermediate_size = size_of_type intermediate_type in
let final_type = instr.type_ in
let final_size = size_of_type final_type in
If truncated back to original size then replace trunc with original value
if original_size == final_size then
replace_instr_with_value_enqueue_uses ext_arg.value
If truncated below original size then ignore extension and trunc original value
else if original_size > final_size then
let new_trunc_instr = mk_blockless_trunc ~arg:ext_arg.value ~type_:final_type in
replace_instr_enqueue_uses new_trunc_instr
(* If truncated below extended size, shorten extension to the truncated size *)
else if intermediate_size > final_size then
let new_ext_instr =
match ext_instr with
| ZExt _ -> mk_blockless_zext ~arg:ext_arg.value ~type_:final_type
| SExt _ -> mk_blockless_sext ~arg:ext_arg.value ~type_:final_type
| _ -> failwith "Expected extension instruction"
in
replace_instr_enqueue_uses new_ext_instr
| _ -> ())
ZExt of a ZExt is condensed to a single ZExt to final size
| ZExt zext_arg ->
(match zext_arg.value.value with
| Instr { instr = ZExt original_arg; _ } ->
let new_trunc_instr = mk_blockless_zext ~arg:original_arg.value ~type_:instr.type_ in
replace_instr_enqueue_uses new_trunc_instr
| _ -> ())
SExt of a SExt is condensed to a single SExt to final size
| SExt sext_arg ->
(match sext_arg.value.value with
| Instr { instr = SExt original_arg; _ } ->
let new_trunc_instr = mk_blockless_sext ~arg:original_arg.value ~type_:instr.type_ in
replace_instr_enqueue_uses new_trunc_instr
| _ -> ())
Check for a comparison of a zero extended value against a literal that is out of range
| Cmp (((Eq | Neq) as cmp), cmp_left_arg, cmp_right_arg) ->
(match (cmp_left_arg.value.value, cmp_right_arg.value.value) with
| (Lit lit, Instr { instr = ZExt zext_arg; _ })
| (Instr { instr = ZExt zext_arg; _ }, Lit lit) ->
let lit_int = int64_of_literal lit in
(match type_of_use zext_arg with
| Byte ->
if Integers.is_out_of_signed_byte_range lit_int then
replace_instr_with_value_enqueue_uses (mk_bool_lit (cmp != Eq))
| Int ->
if Integers.is_out_of_signed_int_range lit_int then
replace_instr_with_value_enqueue_uses (mk_bool_lit (cmp != Eq))
| _ -> ())
(* Check for a comparison of a sign extended value against a literal, which is known if the
literal does not have the same bit value set for the sign extended range. *)
| (Instr { instr = SExt sext_arg; type_; _ }, Lit lit) ->
let lit_int = int64_of_literal lit in
let check_mask mask =
let masked_lit = Int64.logand lit_int mask in
if (not (Int64.equal masked_lit 0L)) && not (Int64.equal masked_lit mask) then
replace_instr_with_value_enqueue_uses (mk_bool_lit (cmp != Eq))
in
(match type_of_use sext_arg with
| Byte ->
(match type_ with
| Int -> check_mask 0xFFFFFF80L
| Long -> check_mask 0xFFFFFFFFFFFFFF80L
| _ -> ())
| Int ->
(match type_ with
| Long -> check_mask 0xFFFFFFFF80000000L
| _ -> ())
| _ -> ())
| _ -> ())
| _ -> ()
let run_on_instruction ~cx instr_value =
let instr = cast_to_instruction instr_value in
if Dead_instruction_elimination.is_dead_instruction instr_value then (
(* Remove instruction and enqueue instruction operands as they may now be unused *)
instruction_iter_operands ~instr (fun operand ->
match operand.value.value with
| Instr _ -> enqueue_instr ~cx operand.value
| _ -> ());
remove_instruction instr_value
) else
First try constant folding , otherwise try to simplify instruction
match Fold_constants.try_fold_instruction instr with
| Some constant ->
let constant_value = mk_value (Lit constant) in
value_iter_uses ~value:instr_value (fun use -> enqueue_instr ~cx use.user);
replace_instruction ~from:instr_value ~to_:constant_value
| None -> simplify_instruction ~cx instr_value
let run ~program =
let cx = { worklist = VSet.empty } in
(* Initial pass enqueues all instructions *)
program_iter_blocks program (fun block ->
iter_instructions block (fun instr_value _ -> enqueue_instr ~cx instr_value));
(* Keep checking for simplification and enqueuing dependent uses until no possible changes are left *)
while not (VSet.is_empty cx.worklist) do
let instr_value = VSet.choose cx.worklist in
run_on_instruction ~cx instr_value;
cx.worklist <- VSet.remove instr_value cx.worklist
done
| null | https://raw.githubusercontent.com/Hans-Halverson/myte/e3eaf0ba1397d7d241006b538ba0e3bbb0050f02/src/mir/transforms/simplify_instructions.ml | ocaml | Instructions that could potentially be simplified
Simplify phis where all arguments have the same value
If truncated below extended size, shorten extension to the truncated size
Check for a comparison of a sign extended value against a literal, which is known if the
literal does not have the same bit value set for the sign extended range.
Remove instruction and enqueue instruction operands as they may now be unused
Initial pass enqueues all instructions
Keep checking for simplification and enqueuing dependent uses until no possible changes are left | open Mir
open Mir_builders
open Mir_type
mutable worklist: VSet.t }
let enqueue_instr ~cx instr_value = cx.worklist <- VSet.add instr_value cx.worklist
let simplify_instruction ~cx instr_value =
let instr = cast_to_instruction instr_value in
let enqueue_operands_and_uses instr_value =
value_iter_uses ~value:instr_value (fun use -> enqueue_instr ~cx use.user);
instruction_iter_operands ~instr (fun operand ->
match operand.value.value with
| Instr _ -> enqueue_instr ~cx operand.value
| _ -> ())
in
let replace_instr_enqueue_uses new_instr_value =
enqueue_operands_and_uses instr_value;
insert_instruction_before ~before:instr_value new_instr_value;
replace_instruction ~from:instr_value ~to_:new_instr_value
in
let replace_instr_with_value_enqueue_uses new_value =
enqueue_operands_and_uses instr_value;
replace_instruction ~from:instr_value ~to_:new_value
in
match instr.instr with
| Phi phi ->
(match phi_get_single_arg_value phi with
| None -> ()
| Some arg_value -> replace_instr_with_value_enqueue_uses arg_value)
Comparison followed by not can be changed to inverted comparison
| Unary (Not, operand) ->
(match operand.value.value with
| Instr { instr = Cmp (comparison, op1, op2); _ } ->
let inverted_comparison = invert_comparison comparison in
let new_instr = mk_blockless_cmp ~cmp:inverted_comparison ~left:op1.value ~right:op2.value in
replace_instr_enqueue_uses new_instr
| _ -> ())
| Trunc trunc_arg ->
(match trunc_arg.value.value with
Trunc of a Trunc is combined to a single Trunc to final size
| Instr { instr = Trunc original_arg; _ } ->
let new_trunc_instr = mk_blockless_trunc ~arg:original_arg.value ~type_:instr.type_ in
replace_instr_enqueue_uses new_trunc_instr
Trunc of an extension may either cancel or shorten extension
| Instr { instr = (ZExt ext_arg | SExt ext_arg) as ext_instr; _ } ->
let original_type = type_of_use ext_arg in
let original_size = size_of_type original_type in
let intermediate_type = type_of_use trunc_arg in
let intermediate_size = size_of_type intermediate_type in
let final_type = instr.type_ in
let final_size = size_of_type final_type in
If truncated back to original size then replace trunc with original value
if original_size == final_size then
replace_instr_with_value_enqueue_uses ext_arg.value
If truncated below original size then ignore extension and trunc original value
else if original_size > final_size then
let new_trunc_instr = mk_blockless_trunc ~arg:ext_arg.value ~type_:final_type in
replace_instr_enqueue_uses new_trunc_instr
else if intermediate_size > final_size then
let new_ext_instr =
match ext_instr with
| ZExt _ -> mk_blockless_zext ~arg:ext_arg.value ~type_:final_type
| SExt _ -> mk_blockless_sext ~arg:ext_arg.value ~type_:final_type
| _ -> failwith "Expected extension instruction"
in
replace_instr_enqueue_uses new_ext_instr
| _ -> ())
ZExt of a ZExt is condensed to a single ZExt to final size
| ZExt zext_arg ->
(match zext_arg.value.value with
| Instr { instr = ZExt original_arg; _ } ->
let new_trunc_instr = mk_blockless_zext ~arg:original_arg.value ~type_:instr.type_ in
replace_instr_enqueue_uses new_trunc_instr
| _ -> ())
SExt of a SExt is condensed to a single SExt to final size
| SExt sext_arg ->
(match sext_arg.value.value with
| Instr { instr = SExt original_arg; _ } ->
let new_trunc_instr = mk_blockless_sext ~arg:original_arg.value ~type_:instr.type_ in
replace_instr_enqueue_uses new_trunc_instr
| _ -> ())
Check for a comparison of a zero extended value against a literal that is out of range
| Cmp (((Eq | Neq) as cmp), cmp_left_arg, cmp_right_arg) ->
(match (cmp_left_arg.value.value, cmp_right_arg.value.value) with
| (Lit lit, Instr { instr = ZExt zext_arg; _ })
| (Instr { instr = ZExt zext_arg; _ }, Lit lit) ->
let lit_int = int64_of_literal lit in
(match type_of_use zext_arg with
| Byte ->
if Integers.is_out_of_signed_byte_range lit_int then
replace_instr_with_value_enqueue_uses (mk_bool_lit (cmp != Eq))
| Int ->
if Integers.is_out_of_signed_int_range lit_int then
replace_instr_with_value_enqueue_uses (mk_bool_lit (cmp != Eq))
| _ -> ())
| (Instr { instr = SExt sext_arg; type_; _ }, Lit lit) ->
let lit_int = int64_of_literal lit in
let check_mask mask =
let masked_lit = Int64.logand lit_int mask in
if (not (Int64.equal masked_lit 0L)) && not (Int64.equal masked_lit mask) then
replace_instr_with_value_enqueue_uses (mk_bool_lit (cmp != Eq))
in
(match type_of_use sext_arg with
| Byte ->
(match type_ with
| Int -> check_mask 0xFFFFFF80L
| Long -> check_mask 0xFFFFFFFFFFFFFF80L
| _ -> ())
| Int ->
(match type_ with
| Long -> check_mask 0xFFFFFFFF80000000L
| _ -> ())
| _ -> ())
| _ -> ())
| _ -> ()
let run_on_instruction ~cx instr_value =
let instr = cast_to_instruction instr_value in
if Dead_instruction_elimination.is_dead_instruction instr_value then (
instruction_iter_operands ~instr (fun operand ->
match operand.value.value with
| Instr _ -> enqueue_instr ~cx operand.value
| _ -> ());
remove_instruction instr_value
) else
First try constant folding , otherwise try to simplify instruction
match Fold_constants.try_fold_instruction instr with
| Some constant ->
let constant_value = mk_value (Lit constant) in
value_iter_uses ~value:instr_value (fun use -> enqueue_instr ~cx use.user);
replace_instruction ~from:instr_value ~to_:constant_value
| None -> simplify_instruction ~cx instr_value
let run ~program =
let cx = { worklist = VSet.empty } in
program_iter_blocks program (fun block ->
iter_instructions block (fun instr_value _ -> enqueue_instr ~cx instr_value));
while not (VSet.is_empty cx.worklist) do
let instr_value = VSet.choose cx.worklist in
run_on_instruction ~cx instr_value;
cx.worklist <- VSet.remove instr_value cx.worklist
done
|
d51ee0325cb7b89c8de6485f1b89f608c0ef319bbab60bd6597a0f3c119db9db | CSCfi/rems | testing.cljs | (ns rems.testing
(:require [re-frame.core :as rf]))
(defn isolate-re-frame-state [f]
(let [restore-fn (rf/make-restore-fn)]
(try
(f)
(finally
(restore-fn)))))
(defn stub-re-frame-effect [id]
(rf/clear-fx id)
(rf/reg-fx id (fn [_])))
| null | https://raw.githubusercontent.com/CSCfi/rems/644ef6df4518b8e382cdfeadd7719e29508a26f0/test/cljs/rems/testing.cljs | clojure | (ns rems.testing
(:require [re-frame.core :as rf]))
(defn isolate-re-frame-state [f]
(let [restore-fn (rf/make-restore-fn)]
(try
(f)
(finally
(restore-fn)))))
(defn stub-re-frame-effect [id]
(rf/clear-fx id)
(rf/reg-fx id (fn [_])))
| |
e7642e46f0754bc51e2982e8730d91cd74eb2facdc6f14e6d7363720b53dd5e8 | christoff-buerger/racr | cookie-automaton.scm | ; This program and the accompanying materials are made available under the
terms of the MIT license ( X11 license ) which accompanies this distribution .
Author :
Specification of the cookie automaton given on page 21 , Figure 2.1 in
;
" Petrinetze : Modellierungstechnik , Analysemethoden , Fallstudien "
Vieweg+Teubner , 2010
978 - 3 - 8348 - 1290 - 2
#!r6rs
(import (rnrs) (racr core) (racr testing)
(atomic-petrinets user-interface) (atomic-petrinets analyses))
(define Box 'Box)
(define Box* 'Box*)
(define Euro 'Euro)
(define Token 'Token)
(define (make-cookie-automaton)
(petrinet:
; Places with start marking:
H with tokens of two different kind
(D Token) ; D with 'Token token
(G Token) ; G with 'Token token
E with integer token of value 7
(A) (B) (C) (F)) ; All other places have no tokens.
; Transitions:
(transition: c
Consume ' Token token from D.
((A 'Euro))) ; Produce 'Euro token in A.
(transition: e
((A (euro (eq? euro Euro)))) ; Consume 'Euro token from A.
Produce ' Token token in D.
(transition: a
((A (euro (eq? euro Euro))) ; Consume 'Euro token from A.
Consume an x > = 2 token from E.
(G (token (eq? token Token)))) ; Consume 'Token token from G.
Produce ' Token token in D.
Put x decremented by two in E.
Produce ' Euro token in F.
(B 'Token))) ; Produce 'Token token in B.
(transition: b
((B (token (eq? token Token))) ; Consume 'Euro token from B.
Consume two arbitrary tokens from H.
((G 'Token) ; Produce 'Token token in G.
(C y z))) ; Put tokens consumed from H in C.
(transition: d
((C (y #t))) ; Consume arbitrary token from C.
()))) ; d is cold-transition: produce nothing.
(define (run-tests)
; Test fixture: Transition b nondeterministicly selects boxes from H!
; To test markings without an explosion of possible combinations...
(set! Box* Box) ; ...rectify the box types.
(let ((net (make-cookie-automaton)))
(assert-marking
net
(list 'D Token)
(list 'E 7)
(list 'G Token)
(list 'H Box Box Box Box Box Box* Box*))
(assert-enabled net 'c)
(fire-transition! (=t-lookup net 'c))
(assert-marking
net
(list 'A Euro)
(list 'E 7)
(list 'G Token)
(list 'H Box Box Box Box Box Box* Box*))
(assert-enabled net 'a 'e)
(fire-transition! (=t-lookup net 'a))
(assert-marking
net
(list 'B Token)
(list 'D Token)
(list 'E 5)
(list 'F Euro)
(list 'H Box Box Box Box Box Box* Box*))
(assert-enabled net 'b 'c)
(fire-transition! (=t-lookup net 'c))
(assert-marking
net
(list 'A Euro)
(list 'B Token)
(list 'E 5)
(list 'F Euro)
(list 'H Box Box Box Box Box Box* Box*))
(assert-enabled net 'b 'e)
(fire-transition! (=t-lookup net 'e))
(assert-marking
net
(list 'B Token)
(list 'D Token)
(list 'E 5)
(list 'F Euro)
(list 'H Box Box Box Box Box Box* Box*))
(assert-enabled net 'b 'c)
(fire-transition! (=t-lookup net 'c))
(assert-marking
net
(list 'A Euro)
(list 'B Token)
(list 'E 5)
(list 'F Euro)
(list 'H Box Box Box Box Box Box* Box*))
(assert-enabled net 'b 'e)
(fire-transition! (=t-lookup net 'b))
(assert-marking
net
(list 'A Euro)
(list 'C Box Box)
(list 'E 5)
(list 'F Euro)
(list 'G Token)
(list 'H Box Box Box Box* Box*))
(assert-enabled net 'a 'd 'e)
(fire-transition! (=t-lookup net 'e))
(assert-marking
net
(list 'C Box Box)
(list 'D Token)
(list 'E 5)
(list 'F Euro)
(list 'G Token)
(list 'H Box Box Box Box* Box*))
(assert-enabled net 'c 'd)
(fire-transition! (=t-lookup net 'c))
(assert-marking
net
(list 'A Euro)
(list 'C Box Box)
(list 'E 5)
(list 'F Euro)
(list 'G Token)
(list 'H Box Box Box Box* Box*))
(assert-enabled net 'a 'd 'e)
(fire-transition! (=t-lookup net 'd))
(assert-marking
net
(list 'A Euro)
(list 'C Box)
(list 'E 5)
(list 'F Euro)
(list 'G Token)
(list 'H Box Box Box Box* Box*))
(assert-enabled net 'a 'e 'd)
(fire-transition! (=t-lookup net 'd))
(assert-marking
net
(list 'A Euro)
(list 'E 5)
(list 'F Euro)
(list 'G Token)
(list 'H Box Box Box Box* Box*))
(assert-enabled net 'a 'e)
(fire-transition! (=t-lookup net 'a))
(assert-marking
net
(list 'B Token)
(list 'D Token)
(list 'E 3)
(list 'F Euro Euro)
(list 'H Box Box Box Box* Box*))
(assert-enabled net 'b 'c)
(fire-transition! (=t-lookup net 'b))
(assert-marking
net
(list 'C Box Box)
(list 'D Token)
(list 'E 3)
(list 'F Euro Euro)
(list 'G Token)
(list 'H Box Box* Box*))
(assert-enabled net 'c 'd)
(fire-transition! (=t-lookup net 'c))
(assert-marking
net
(list 'A Euro)
(list 'C Box Box)
(list 'E 3)
(list 'F Euro Euro)
(list 'G Token)
(list 'H Box Box* Box*))
(assert-enabled net 'a 'd 'e)
(fire-transition! (=t-lookup net 'a))
(assert-marking
net
(list 'B Token)
(list 'C Box Box)
(list 'D Token)
(list 'E 1)
(list 'F Euro Euro Euro)
(list 'H Box Box* Box*))
(assert-enabled net 'b 'c 'd)
(fire-transition! (=t-lookup net 'b))
(assert-marking
net
(list 'C Box* Box Box Box)
(list 'D Token)
(list 'E 1)
(list 'F Euro Euro Euro)
(list 'G Token)
(list 'H Box*))
(assert-enabled net 'c 'd)
(fire-transition! (=t-lookup net 'c))
(assert-marking
net
(list 'A Euro)
(list 'C Box* Box Box Box)
(list 'E 1)
(list 'F Euro Euro Euro)
(list 'G Token)
(list 'H Box*))
(assert-enabled net 'd 'e)
(fire-transition! (=t-lookup net 'd))
(assert-marking
net
(list 'A Euro)
(list 'C Box* Box Box)
(list 'E 1)
(list 'F Euro Euro Euro)
(list 'G Token)
(list 'H Box*))
(assert-enabled net 'd 'e)
(fire-transition! (=t-lookup net 'd))
(assert-marking
net
(list 'A Euro)
(list 'C Box* Box)
(list 'E 1)
(list 'F Euro Euro Euro)
(list 'G Token)
(list 'H Box*))
(assert-enabled net 'd 'e)
(fire-transition! (=t-lookup net 'd))
(assert-marking
net
(list 'A Euro)
(list 'C Box*)
(list 'E 1)
(list 'F Euro Euro Euro)
(list 'G Token)
(list 'H Box*))
(assert-enabled net 'd 'e)
(fire-transition! (=t-lookup net 'd))
(assert-marking
net
(list 'A Euro)
(list 'E 1)
(list 'F Euro Euro Euro)
(list 'G Token)
(list 'H Box*))
(assert-enabled net 'e)
(fire-transition! (=t-lookup net 'e))
(assert-marking
net
(list 'D Token)
(list 'E 1)
(list 'F Euro Euro Euro)
(list 'G Token)
(list 'H Box*))
(assert-enabled net 'c)
(fire-transition! (=t-lookup net 'c))
(assert-enabled net 'e)
(assert-marking
net
(list 'A Euro)
(list 'E 1)
(list 'F Euro Euro Euro)
(list 'G Token)
(list 'H Box*))
(fire-transition! (=t-lookup net 'e))
(assert-marking
net
(list 'D Token)
(list 'E 1)
(list 'F Euro Euro Euro)
(list 'G Token)
(list 'H Box*))
(assert-enabled net 'c)
(fire-transition! (=t-lookup net 'c))
(assert-marking
net
(list 'A Euro)
(list 'E 1)
(list 'F Euro Euro Euro)
(list 'G Token)
(list 'H Box*))
(assert-enabled net 'e)
(fire-transition! (=t-lookup net 'e))
; ...
(assert-enabled net 'c)
(assert-marking
net
(list 'D Token)
(list 'E 1)
(list 'F Euro Euro Euro)
(list 'G Token)
(list 'H Box*)))
(let ((net (make-cookie-automaton)))
(rewrite-delete (=t-lookup net 'e))
(run-petrinet! net)
(assert-marking
net
(list 'A Euro)
(list 'E 1)
(list 'F Euro Euro Euro)
(list 'G Token)
(list 'H Box*)))
(let ((net (make-cookie-automaton)))
(rewrite-delete (=p-lookup net 'A))
(assert-exception petrinets-exception? (run-petrinet! net)))
(set! Box* 'Box*)) ; Undo test fixture.
(initialise-petrinet-language #t)
(run-tests) | null | https://raw.githubusercontent.com/christoff-buerger/racr/ecb2a9b8bf3f333550728cf45b97607a8298532f/examples/atomic-petrinets/examples/cookie-automaton.scm | scheme | This program and the accompanying materials are made available under the
Places with start marking:
D with 'Token token
G with 'Token token
All other places have no tokens.
Transitions:
Produce 'Euro token in A.
Consume 'Euro token from A.
Consume 'Euro token from A.
Consume 'Token token from G.
Produce 'Token token in B.
Consume 'Euro token from B.
Produce 'Token token in G.
Put tokens consumed from H in C.
Consume arbitrary token from C.
d is cold-transition: produce nothing.
Test fixture: Transition b nondeterministicly selects boxes from H!
To test markings without an explosion of possible combinations...
...rectify the box types.
...
Undo test fixture. | terms of the MIT license ( X11 license ) which accompanies this distribution .
Author :
Specification of the cookie automaton given on page 21 , Figure 2.1 in
" Petrinetze : Modellierungstechnik , Analysemethoden , Fallstudien "
Vieweg+Teubner , 2010
978 - 3 - 8348 - 1290 - 2
#!r6rs
(import (rnrs) (racr core) (racr testing)
(atomic-petrinets user-interface) (atomic-petrinets analyses))
(define Box 'Box)
(define Box* 'Box*)
(define Euro 'Euro)
(define Token 'Token)
(define (make-cookie-automaton)
(petrinet:
H with tokens of two different kind
E with integer token of value 7
(transition: c
Consume ' Token token from D.
(transition: e
Produce ' Token token in D.
(transition: a
Consume an x > = 2 token from E.
Produce ' Token token in D.
Put x decremented by two in E.
Produce ' Euro token in F.
(transition: b
Consume two arbitrary tokens from H.
(transition: d
(define (run-tests)
(let ((net (make-cookie-automaton)))
(assert-marking
net
(list 'D Token)
(list 'E 7)
(list 'G Token)
(list 'H Box Box Box Box Box Box* Box*))
(assert-enabled net 'c)
(fire-transition! (=t-lookup net 'c))
(assert-marking
net
(list 'A Euro)
(list 'E 7)
(list 'G Token)
(list 'H Box Box Box Box Box Box* Box*))
(assert-enabled net 'a 'e)
(fire-transition! (=t-lookup net 'a))
(assert-marking
net
(list 'B Token)
(list 'D Token)
(list 'E 5)
(list 'F Euro)
(list 'H Box Box Box Box Box Box* Box*))
(assert-enabled net 'b 'c)
(fire-transition! (=t-lookup net 'c))
(assert-marking
net
(list 'A Euro)
(list 'B Token)
(list 'E 5)
(list 'F Euro)
(list 'H Box Box Box Box Box Box* Box*))
(assert-enabled net 'b 'e)
(fire-transition! (=t-lookup net 'e))
(assert-marking
net
(list 'B Token)
(list 'D Token)
(list 'E 5)
(list 'F Euro)
(list 'H Box Box Box Box Box Box* Box*))
(assert-enabled net 'b 'c)
(fire-transition! (=t-lookup net 'c))
(assert-marking
net
(list 'A Euro)
(list 'B Token)
(list 'E 5)
(list 'F Euro)
(list 'H Box Box Box Box Box Box* Box*))
(assert-enabled net 'b 'e)
(fire-transition! (=t-lookup net 'b))
(assert-marking
net
(list 'A Euro)
(list 'C Box Box)
(list 'E 5)
(list 'F Euro)
(list 'G Token)
(list 'H Box Box Box Box* Box*))
(assert-enabled net 'a 'd 'e)
(fire-transition! (=t-lookup net 'e))
(assert-marking
net
(list 'C Box Box)
(list 'D Token)
(list 'E 5)
(list 'F Euro)
(list 'G Token)
(list 'H Box Box Box Box* Box*))
(assert-enabled net 'c 'd)
(fire-transition! (=t-lookup net 'c))
(assert-marking
net
(list 'A Euro)
(list 'C Box Box)
(list 'E 5)
(list 'F Euro)
(list 'G Token)
(list 'H Box Box Box Box* Box*))
(assert-enabled net 'a 'd 'e)
(fire-transition! (=t-lookup net 'd))
(assert-marking
net
(list 'A Euro)
(list 'C Box)
(list 'E 5)
(list 'F Euro)
(list 'G Token)
(list 'H Box Box Box Box* Box*))
(assert-enabled net 'a 'e 'd)
(fire-transition! (=t-lookup net 'd))
(assert-marking
net
(list 'A Euro)
(list 'E 5)
(list 'F Euro)
(list 'G Token)
(list 'H Box Box Box Box* Box*))
(assert-enabled net 'a 'e)
(fire-transition! (=t-lookup net 'a))
(assert-marking
net
(list 'B Token)
(list 'D Token)
(list 'E 3)
(list 'F Euro Euro)
(list 'H Box Box Box Box* Box*))
(assert-enabled net 'b 'c)
(fire-transition! (=t-lookup net 'b))
(assert-marking
net
(list 'C Box Box)
(list 'D Token)
(list 'E 3)
(list 'F Euro Euro)
(list 'G Token)
(list 'H Box Box* Box*))
(assert-enabled net 'c 'd)
(fire-transition! (=t-lookup net 'c))
(assert-marking
net
(list 'A Euro)
(list 'C Box Box)
(list 'E 3)
(list 'F Euro Euro)
(list 'G Token)
(list 'H Box Box* Box*))
(assert-enabled net 'a 'd 'e)
(fire-transition! (=t-lookup net 'a))
(assert-marking
net
(list 'B Token)
(list 'C Box Box)
(list 'D Token)
(list 'E 1)
(list 'F Euro Euro Euro)
(list 'H Box Box* Box*))
(assert-enabled net 'b 'c 'd)
(fire-transition! (=t-lookup net 'b))
(assert-marking
net
(list 'C Box* Box Box Box)
(list 'D Token)
(list 'E 1)
(list 'F Euro Euro Euro)
(list 'G Token)
(list 'H Box*))
(assert-enabled net 'c 'd)
(fire-transition! (=t-lookup net 'c))
(assert-marking
net
(list 'A Euro)
(list 'C Box* Box Box Box)
(list 'E 1)
(list 'F Euro Euro Euro)
(list 'G Token)
(list 'H Box*))
(assert-enabled net 'd 'e)
(fire-transition! (=t-lookup net 'd))
(assert-marking
net
(list 'A Euro)
(list 'C Box* Box Box)
(list 'E 1)
(list 'F Euro Euro Euro)
(list 'G Token)
(list 'H Box*))
(assert-enabled net 'd 'e)
(fire-transition! (=t-lookup net 'd))
(assert-marking
net
(list 'A Euro)
(list 'C Box* Box)
(list 'E 1)
(list 'F Euro Euro Euro)
(list 'G Token)
(list 'H Box*))
(assert-enabled net 'd 'e)
(fire-transition! (=t-lookup net 'd))
(assert-marking
net
(list 'A Euro)
(list 'C Box*)
(list 'E 1)
(list 'F Euro Euro Euro)
(list 'G Token)
(list 'H Box*))
(assert-enabled net 'd 'e)
(fire-transition! (=t-lookup net 'd))
(assert-marking
net
(list 'A Euro)
(list 'E 1)
(list 'F Euro Euro Euro)
(list 'G Token)
(list 'H Box*))
(assert-enabled net 'e)
(fire-transition! (=t-lookup net 'e))
(assert-marking
net
(list 'D Token)
(list 'E 1)
(list 'F Euro Euro Euro)
(list 'G Token)
(list 'H Box*))
(assert-enabled net 'c)
(fire-transition! (=t-lookup net 'c))
(assert-enabled net 'e)
(assert-marking
net
(list 'A Euro)
(list 'E 1)
(list 'F Euro Euro Euro)
(list 'G Token)
(list 'H Box*))
(fire-transition! (=t-lookup net 'e))
(assert-marking
net
(list 'D Token)
(list 'E 1)
(list 'F Euro Euro Euro)
(list 'G Token)
(list 'H Box*))
(assert-enabled net 'c)
(fire-transition! (=t-lookup net 'c))
(assert-marking
net
(list 'A Euro)
(list 'E 1)
(list 'F Euro Euro Euro)
(list 'G Token)
(list 'H Box*))
(assert-enabled net 'e)
(fire-transition! (=t-lookup net 'e))
(assert-enabled net 'c)
(assert-marking
net
(list 'D Token)
(list 'E 1)
(list 'F Euro Euro Euro)
(list 'G Token)
(list 'H Box*)))
(let ((net (make-cookie-automaton)))
(rewrite-delete (=t-lookup net 'e))
(run-petrinet! net)
(assert-marking
net
(list 'A Euro)
(list 'E 1)
(list 'F Euro Euro Euro)
(list 'G Token)
(list 'H Box*)))
(let ((net (make-cookie-automaton)))
(rewrite-delete (=p-lookup net 'A))
(assert-exception petrinets-exception? (run-petrinet! net)))
(initialise-petrinet-language #t)
(run-tests) |
beb717a2f778d9863bdf30734aa7307dbabd6dfa7c095020b923fd954dd6eb99 | acl2/acl2 | enum.cpp.ref.ast.lsp |
(funcdef foo () (block (return 0)))(funcdef bar () (block (return 5)))
| null | https://raw.githubusercontent.com/acl2/acl2/c2d69bad0ed3132cc19a00cb632de8b73558b1f9/books/projects/rac/tests/yaml_test/program_structure/enum.cpp.ref.ast.lsp | lisp |
(funcdef foo () (block (return 0)))(funcdef bar () (block (return 5)))
| |
07aea94ecc15a131ffb2bd48e6a9e70aab8b6faecaadae5fb6d5e386098da845 | takeoutweight/clojure-scheme | foo.cljs | (ns cljs.import-test.foo)
(defrecord Bar [x])
(deftype Quux [x])
| null | https://raw.githubusercontent.com/takeoutweight/clojure-scheme/6121de1690a6a52c7dbbe7fa722aaf3ddd4920dd/test/cljs/cljs/import_test/foo.cljs | clojure | (ns cljs.import-test.foo)
(defrecord Bar [x])
(deftype Quux [x])
| |
27c256e69c555aaeb8e38221d5b6a62a030c4427210ce2f14d20574752f8dbe3 | ToTal/total | beautify.ml | (** Renaming of bound variables for pretty printing. *)
open Syntax
(** default generated name *)
let default = "x"
* Split a variable name into base and numerical postfix , e.g. ,
[ " x42 " ] is split into [ ( " x " , 42 ) ] .
["x42"] is split into [("x", 42)]. *)
let split s =
let n = String.length s in
let i = ref (n - 1) in
while !i >= 0 && '0' <= s.[!i] && s.[!i] <= '9' do decr i done ;
if !i < 0 || !i = n - 1
then (s, None)
else
let k = int_of_string (String.sub s (!i+1) (n - !i - 1)) in
(String.sub s 0 (!i+1), Some k)
(** Given a variable [x] and a list of variable names [xs], find a variant of [x] which
does not appear in [xs]. *)
let refresh x xs =
match Common.get_name x with
| None when not (List.mem default xs) -> default
| None ->
let k = ref 0 in
while List.mem (default ^ string_of_int !k) xs do incr k done ;
default ^ string_of_int !k
| Some x when not (List.mem x xs)-> x
| Some x ->
let (y, k) = split x in
let k = ref (match k with Some k -> k | None -> 0) in
while List.mem (y ^ string_of_int !k) xs do incr k done ;
y ^ string_of_int !k
| null | https://raw.githubusercontent.com/ToTal/total/fa9c677c9110afd5fb423a4fe24eafff2fd08507/beautify.ml | ocaml | * Renaming of bound variables for pretty printing.
* default generated name
* Given a variable [x] and a list of variable names [xs], find a variant of [x] which
does not appear in [xs]. |
open Syntax
let default = "x"
* Split a variable name into base and numerical postfix , e.g. ,
[ " x42 " ] is split into [ ( " x " , 42 ) ] .
["x42"] is split into [("x", 42)]. *)
let split s =
let n = String.length s in
let i = ref (n - 1) in
while !i >= 0 && '0' <= s.[!i] && s.[!i] <= '9' do decr i done ;
if !i < 0 || !i = n - 1
then (s, None)
else
let k = int_of_string (String.sub s (!i+1) (n - !i - 1)) in
(String.sub s 0 (!i+1), Some k)
let refresh x xs =
match Common.get_name x with
| None when not (List.mem default xs) -> default
| None ->
let k = ref 0 in
while List.mem (default ^ string_of_int !k) xs do incr k done ;
default ^ string_of_int !k
| Some x when not (List.mem x xs)-> x
| Some x ->
let (y, k) = split x in
let k = ref (match k with Some k -> k | None -> 0) in
while List.mem (y ^ string_of_int !k) xs do incr k done ;
y ^ string_of_int !k
|
587282853b7de2ff59461b0b390e714cdae454eae8bf1476ca14984dcaf51fd2 | bmeurer/ocaml-arm | frames.mli | (***********************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
OCaml port by and
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
$ Id$
(****************************** Frames *********************************)
open Instruct
open Primitives
(* Current frame number *)
val current_frame : int ref
(* Event at selected position. *)
val selected_event : debug_event option ref
(* Selected position in source (module, line, column). *)
(* Raise `Not_found' if not on an event. *)
val selected_point : unit -> string * int * int
val selected_event_is_before : unit -> bool
(* Select a frame. *)
(* Raise `Not_found' if no such frame. *)
(* --- Assume the currents events have already been updated. *)
val select_frame : int -> unit
(* Select a frame. *)
(* Same as `select_frame' but raise no exception if the frame is not found. *)
(* --- Assume the currents events have already been updated. *)
val try_select_frame : int -> unit
(* Return to default frame (frame 0). *)
val reset_frame : unit -> unit
(* Perform a stack backtrace.
Call the given function with the events for each stack frame,
or None if we've encountered a stack frame with no debugging info
attached. Stop when the function returns false, or frame with no
debugging info reached, or top of stack reached. *)
val do_backtrace : (debug_event option -> bool) -> unit
(* Return the number of frames in the stack, or (-1) if it can't be
determined because some frames have no debugging info. *)
val stack_depth : unit -> int
| null | https://raw.githubusercontent.com/bmeurer/ocaml-arm/43f7689c76a349febe3d06ae7a4fc1d52984fd8b/debugger/frames.mli | ocaml | *********************************************************************
OCaml
*********************************************************************
***************************** Frames ********************************
Current frame number
Event at selected position.
Selected position in source (module, line, column).
Raise `Not_found' if not on an event.
Select a frame.
Raise `Not_found' if no such frame.
--- Assume the currents events have already been updated.
Select a frame.
Same as `select_frame' but raise no exception if the frame is not found.
--- Assume the currents events have already been updated.
Return to default frame (frame 0).
Perform a stack backtrace.
Call the given function with the events for each stack frame,
or None if we've encountered a stack frame with no debugging info
attached. Stop when the function returns false, or frame with no
debugging info reached, or top of stack reached.
Return the number of frames in the stack, or (-1) if it can't be
determined because some frames have no debugging info. | , projet Cristal , INRIA Rocquencourt
OCaml port by and
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
$ Id$
open Instruct
open Primitives
val current_frame : int ref
val selected_event : debug_event option ref
val selected_point : unit -> string * int * int
val selected_event_is_before : unit -> bool
val select_frame : int -> unit
val try_select_frame : int -> unit
val reset_frame : unit -> unit
val do_backtrace : (debug_event option -> bool) -> unit
val stack_depth : unit -> int
|
17df2ede8cf159e8486992f5cf793f6c8f647b0bbce068dece1c57b3369a690d | sonyxperiadev/dataflow | Renderer.hs | # LANGUAGE FlexibleInstances #
{-# LANGUAGE TypeSynonymInstances #-}
module DataFlow.PlantUML.Renderer (
renderPlantUML
) where
import Text.Printf
import DataFlow.PrettyRenderer
import DataFlow.PlantUML
class Renderable t where
render :: t -> Renderer ()
instance Renderable Stmt where
render (SkinParam name value) = do
write "skinparam "
write name
write " "
writeln value
render (Box name stmts) = do
writeln $ printf "box \"%s\"" name
withIndent $ render stmts
writeln "end box"
render (Participant id' name) =
writeln $ printf "participant \"%s\" as %s" name id'
render (Database id' name) =
writeln $ printf "database \"%s\" as %s" name id'
render (Entity id' name) =
writeln $ printf "entity \"%s\" as %s" name id'
render (Edge i1 i2 description) =
writeln $ printf "%s -> %s : %s" i1 i2 description
instance Renderable StmtList where
render = mapM_ render
instance Renderable Diagram where
render (SequenceDiagram stmts) = do
writeln "@startuml"
render stmts
writeln "@enduml"
renderPlantUML :: Diagram -> String
renderPlantUML = renderWithIndent . render
| null | https://raw.githubusercontent.com/sonyxperiadev/dataflow/8bef5bd6bf96a918197e66ad9d675ff8cd2a4e33/src/DataFlow/PlantUML/Renderer.hs | haskell | # LANGUAGE TypeSynonymInstances # | # LANGUAGE FlexibleInstances #
module DataFlow.PlantUML.Renderer (
renderPlantUML
) where
import Text.Printf
import DataFlow.PrettyRenderer
import DataFlow.PlantUML
class Renderable t where
render :: t -> Renderer ()
instance Renderable Stmt where
render (SkinParam name value) = do
write "skinparam "
write name
write " "
writeln value
render (Box name stmts) = do
writeln $ printf "box \"%s\"" name
withIndent $ render stmts
writeln "end box"
render (Participant id' name) =
writeln $ printf "participant \"%s\" as %s" name id'
render (Database id' name) =
writeln $ printf "database \"%s\" as %s" name id'
render (Entity id' name) =
writeln $ printf "entity \"%s\" as %s" name id'
render (Edge i1 i2 description) =
writeln $ printf "%s -> %s : %s" i1 i2 description
instance Renderable StmtList where
render = mapM_ render
instance Renderable Diagram where
render (SequenceDiagram stmts) = do
writeln "@startuml"
render stmts
writeln "@enduml"
renderPlantUML :: Diagram -> String
renderPlantUML = renderWithIndent . render
|
3caaeec49d9371e2bab61a8b9c49c3c13eda409a108c53ab1b3f1aa4e582ace3 | zotonic/zotonic | z_lib_include_tests.erl | @author < >
%% @hidden
-module(z_lib_include_tests).
-include_lib("zotonic.hrl").
-include_lib("eunit/include/eunit.hrl").
uncollapse_test() ->
?assertEqual([],
z_lib_include:uncollapse("")),
?assertEqual([ <<"/a/b1.js">>, <<"/a/b2.js">>, <<"/a/b/c.js">>, <<"/a/b3.js">> ],
z_lib_include:uncollapse(<<"/a/b1~b2~b/c~/a/b3~63415422477.js">>)),
?assertEqual([ <<"/a/b1.js">> ],
z_lib_include:uncollapse(<<"/a/b1~63415422477.js">>)),
?assertEqual([ <<"/a1.js">>, <<"/a2.js">>],
z_lib_include:uncollapse(<<"/a1~a2~63415422477.js">>)),
ok.
tag_test() ->
C = z_context:new(zotonic_site_testsandbox),
?assertEqual([_LinkElem = [], _ScriptElem = []],
z_lib_include:tag([], C)),
?assertEqual([_LinkElem = [], _ScriptElem = []],
z_lib_include:tag([ <<"/images/test.jpg">> ], C)).
These tests break on test systems with a timezone different than GMT+2 and are not generally very useful tests anyway .
%% ?assertEqual([[], <<"<script src=\"/lib/js/a~62167258800.js\" type=\"text/javascript\"></script>">>],
%% z_lib_include:tag(["/js/a.js"], C)),
%% ?assertEqual([[], <<"<script src=\"/lib/js/a~b~62167258800.js\" type=\"text/javascript\"></script>">>],
%% z_lib_include:tag(["/js/a.js", "/js/b.js"], C)),
? assertEqual([<<"<link href=\"/lib / css / a~62167258800.css\ " type=\"text / css\ " media=\"all\ " rel=\"stylesheet\"/ > " > > ,
< < " < script src=\"/lib / js / b~62167258800.js\ " type=\"text / javascript\"></script > " > > ] ,
%% z_lib_include:tag(["/css/a.css", "/js/b.js"], C)).
| null | https://raw.githubusercontent.com/zotonic/zotonic/852f627c28adf6e5212e8ad5383d4af3a2f25e3f/apps/zotonic_core/test/z_lib_include_tests.erl | erlang | @hidden
?assertEqual([[], <<"<script src=\"/lib/js/a~62167258800.js\" type=\"text/javascript\"></script>">>],
z_lib_include:tag(["/js/a.js"], C)),
?assertEqual([[], <<"<script src=\"/lib/js/a~b~62167258800.js\" type=\"text/javascript\"></script>">>],
z_lib_include:tag(["/js/a.js", "/js/b.js"], C)),
z_lib_include:tag(["/css/a.css", "/js/b.js"], C)). | @author < >
-module(z_lib_include_tests).
-include_lib("zotonic.hrl").
-include_lib("eunit/include/eunit.hrl").
uncollapse_test() ->
?assertEqual([],
z_lib_include:uncollapse("")),
?assertEqual([ <<"/a/b1.js">>, <<"/a/b2.js">>, <<"/a/b/c.js">>, <<"/a/b3.js">> ],
z_lib_include:uncollapse(<<"/a/b1~b2~b/c~/a/b3~63415422477.js">>)),
?assertEqual([ <<"/a/b1.js">> ],
z_lib_include:uncollapse(<<"/a/b1~63415422477.js">>)),
?assertEqual([ <<"/a1.js">>, <<"/a2.js">>],
z_lib_include:uncollapse(<<"/a1~a2~63415422477.js">>)),
ok.
tag_test() ->
C = z_context:new(zotonic_site_testsandbox),
?assertEqual([_LinkElem = [], _ScriptElem = []],
z_lib_include:tag([], C)),
?assertEqual([_LinkElem = [], _ScriptElem = []],
z_lib_include:tag([ <<"/images/test.jpg">> ], C)).
These tests break on test systems with a timezone different than GMT+2 and are not generally very useful tests anyway .
? assertEqual([<<"<link href=\"/lib / css / a~62167258800.css\ " type=\"text / css\ " media=\"all\ " rel=\"stylesheet\"/ > " > > ,
< < " < script src=\"/lib / js / b~62167258800.js\ " type=\"text / javascript\"></script > " > > ] ,
|
4473b3e66d34946f077052e9db6f4b8d588dc945e27f2949b99b11269b329bd7 | galdor/tungsten | random.lisp | (in-package :openssl)
(defun random-octets (n)
(rand-bytes n))
| null | https://raw.githubusercontent.com/galdor/tungsten/5d6e71fb89af32ab3994c5b2daf8b902a5447447/tungsten-openssl/src/random.lisp | lisp | (in-package :openssl)
(defun random-octets (n)
(rand-bytes n))
| |
711b752d5ac0d045e22c27546c56060d4b073d268f3d8fc0614ce6d3e6e02dda | haskell/ghc-builder | ExampleConfig.hs |
module Config (clients, fromAddress, emailAddresses, urlRoot) where
import Builder.Utils
fromAddress :: String
fromAddress = ""
emailAddresses :: [String]
emailAddresses = [""]
urlRoot :: String
urlRoot = "/"
buildSteps :: [BuildStep]
buildSteps = [BuildStep {
bs_name = "Test build step",
bs_subdir = ".",
bs_prog = "/bin/mkdir",
bs_args = ["build"]
},
BuildStep {
bs_name = "Second test build step",
bs_subdir = "build",
bs_prog = "/bin/echo",
bs_args = ["argx1", "argx2", "argx3"]
},
BuildStep {
bs_name = "Mem test build step",
bs_subdir = "build",
bs_prog = "/usr/bin/perl",
100 M
},
BuildStep {
bs_name = "Last test build step",
bs_subdir = "build",
bs_prog = "/bin/pwd",
bs_args = []
}]
clients :: [(String, UserInfo)]
clients = [("foo",
mkUserInfo "mypass"
"UTC"
(Timed (mkTime 2 0))
buildSteps),
("bar",
mkUserInfo "mypass"
"UTC"
Continuous
buildSteps),
("ghcBuilder",
mkUserInfo "mypass"
"UTC"
(Timed (mkTime 13 55))
ghcBuildSteps)
]
darcsRepo :: String
darcsRepo = "/home/ian/ghc/darcs/ghc"
ghcBuildSteps :: [BuildStep]
ghcBuildSteps =
[BuildStep {
bs_name = "darcs checkout",
bs_subdir = ".",
bs_prog = "darcs",
bs_args = ["get", "--partial", darcsRepo, "build"]
},
BuildStep {
bs_name = "create mk/build.mk",
bs_subdir = "build",
bs_prog = "/bin/sh",
bs_args = let ls = ["HADDOCK_DOCS=YES", "LATEX_DOCS=YES"]
str = concatMap (++ "\n") ls
in ["-c", "printf '" ++ str ++ "' | tee mk/build.mk"]
},
BuildStep {
bs_name = "make darcs-all executable",
bs_subdir = "build",
bs_prog = "chmod",
bs_args = ["+x", "darcs-all"]
},
BuildStep {
bs_name = "get subrepos",
bs_subdir = "build",
bs_prog = "./darcs-all",
bs_args = ["--testsuite", "get"]
},
BuildStep {
bs_name = "repo versions",
bs_subdir = "build",
bs_prog = "./darcs-all",
bs_args = ["changes", "--last=1"]
},
BuildStep {
bs_name = "setting version date",
bs_subdir = "build",
bs_prog = "sh",
bs_args = ["-c", "date +%Y%m%d | tee VERSION_DATE"]
},
BuildStep {
bs_name = "booting",
bs_subdir = "build",
bs_prog = "sh",
bs_args = ["boot"]
},
BuildStep {
bs_name = "configuring",
bs_subdir = "build",
bs_prog = "./configure",
bs_args = []
},
BuildStep {
bs_name = "compiling",
bs_subdir = "build",
bs_prog = "make",
bs_args = []
},
BuildStep {
bs_name = "making bindist",
bs_subdir = "build",
bs_prog = "make",
bs_args = ["binary-dist"]
},
BuildStep {
bs_name = "testing bindist",
bs_subdir = "build",
bs_prog = "make",
bs_args = ["-C", "bindisttest"]
},
BuildStep {
bs_name = "testing",
bs_subdir = "build",
bs_prog = "make",
bs_args = ["-C", "testsuite/tests/ghc-regress", "BINDIST=YES"]
}]
| null | https://raw.githubusercontent.com/haskell/ghc-builder/ef90aa7da7ec017d59d875e5bfe5d6b281d766f7/server/ExampleConfig.hs | haskell |
module Config (clients, fromAddress, emailAddresses, urlRoot) where
import Builder.Utils
fromAddress :: String
fromAddress = ""
emailAddresses :: [String]
emailAddresses = [""]
urlRoot :: String
urlRoot = "/"
buildSteps :: [BuildStep]
buildSteps = [BuildStep {
bs_name = "Test build step",
bs_subdir = ".",
bs_prog = "/bin/mkdir",
bs_args = ["build"]
},
BuildStep {
bs_name = "Second test build step",
bs_subdir = "build",
bs_prog = "/bin/echo",
bs_args = ["argx1", "argx2", "argx3"]
},
BuildStep {
bs_name = "Mem test build step",
bs_subdir = "build",
bs_prog = "/usr/bin/perl",
100 M
},
BuildStep {
bs_name = "Last test build step",
bs_subdir = "build",
bs_prog = "/bin/pwd",
bs_args = []
}]
clients :: [(String, UserInfo)]
clients = [("foo",
mkUserInfo "mypass"
"UTC"
(Timed (mkTime 2 0))
buildSteps),
("bar",
mkUserInfo "mypass"
"UTC"
Continuous
buildSteps),
("ghcBuilder",
mkUserInfo "mypass"
"UTC"
(Timed (mkTime 13 55))
ghcBuildSteps)
]
darcsRepo :: String
darcsRepo = "/home/ian/ghc/darcs/ghc"
ghcBuildSteps :: [BuildStep]
ghcBuildSteps =
[BuildStep {
bs_name = "darcs checkout",
bs_subdir = ".",
bs_prog = "darcs",
bs_args = ["get", "--partial", darcsRepo, "build"]
},
BuildStep {
bs_name = "create mk/build.mk",
bs_subdir = "build",
bs_prog = "/bin/sh",
bs_args = let ls = ["HADDOCK_DOCS=YES", "LATEX_DOCS=YES"]
str = concatMap (++ "\n") ls
in ["-c", "printf '" ++ str ++ "' | tee mk/build.mk"]
},
BuildStep {
bs_name = "make darcs-all executable",
bs_subdir = "build",
bs_prog = "chmod",
bs_args = ["+x", "darcs-all"]
},
BuildStep {
bs_name = "get subrepos",
bs_subdir = "build",
bs_prog = "./darcs-all",
bs_args = ["--testsuite", "get"]
},
BuildStep {
bs_name = "repo versions",
bs_subdir = "build",
bs_prog = "./darcs-all",
bs_args = ["changes", "--last=1"]
},
BuildStep {
bs_name = "setting version date",
bs_subdir = "build",
bs_prog = "sh",
bs_args = ["-c", "date +%Y%m%d | tee VERSION_DATE"]
},
BuildStep {
bs_name = "booting",
bs_subdir = "build",
bs_prog = "sh",
bs_args = ["boot"]
},
BuildStep {
bs_name = "configuring",
bs_subdir = "build",
bs_prog = "./configure",
bs_args = []
},
BuildStep {
bs_name = "compiling",
bs_subdir = "build",
bs_prog = "make",
bs_args = []
},
BuildStep {
bs_name = "making bindist",
bs_subdir = "build",
bs_prog = "make",
bs_args = ["binary-dist"]
},
BuildStep {
bs_name = "testing bindist",
bs_subdir = "build",
bs_prog = "make",
bs_args = ["-C", "bindisttest"]
},
BuildStep {
bs_name = "testing",
bs_subdir = "build",
bs_prog = "make",
bs_args = ["-C", "testsuite/tests/ghc-regress", "BINDIST=YES"]
}]
| |
fe56209fd8bbe8281462b2d938b1ca0ee019990670a6778ca2e0ab31f1e00052 | ocaml-multicore/ocaml-tsan | ambiguous_guarded_disjunction.ml | (* TEST
flags = " -w +A -strict-sequence "
* expect
*)
Ignore = b to be reproducible
Printexc.record_backtrace false;;
[%%expect {|
- : unit = ()
|}]
type expr = Val of int | Rest;;
[%%expect {|
type expr = Val of int | Rest
|}]
let ambiguous_typical_example = function
| ((Val x, _) | (_, Val x)) when x < 0 -> ()
| (_, Rest) -> ()
| (_, Val x) ->
(* the reader might expect *)
assert (x >= 0);
(* to hold here, but it is wrong! *)
()
;;
[%%expect {|
Line 2, characters 4-29:
2 | | ((Val x, _) | (_, Val x)) when x < 0 -> ()
^^^^^^^^^^^^^^^^^^^^^^^^^
Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
variable x appears in different places in different or-pattern alternatives.
Only the first match will be used to evaluate the guard expression.
(See manual section 13.5)
val ambiguous_typical_example : expr * expr -> unit = <fun>
|}]
let fails = ambiguous_typical_example (Val 2, Val (-1))
;;
[%%expect {|
Exception: Assert_failure ("", 6, 6).
|}]
let not_ambiguous__no_orpat = function
| Some x when x > 0 -> ()
| Some _ -> ()
| None -> ()
;;
[%%expect {|
val not_ambiguous__no_orpat : int option -> unit = <fun>
|}]
let not_ambiguous__no_guard = function
| `A -> ()
| (`B | `C) -> ()
;;
[%%expect {|
val not_ambiguous__no_guard : [< `A | `B | `C ] -> unit = <fun>
|}]
let not_ambiguous__no_patvar_in_guard b = function
| (`B x | `C x) when b -> ignore x
| _ -> ()
;;
[%%expect {|
val not_ambiguous__no_patvar_in_guard :
bool -> [> `B of 'a | `C of 'a ] -> unit = <fun>
|}]
let not_ambiguous__disjoint_cases = function
| (`B x | `C x) when x -> ()
| _ -> ()
;;
[%%expect {|
val not_ambiguous__disjoint_cases : [> `B of bool | `C of bool ] -> unit =
<fun>
|}]
the curious ( ... , _ , Some _ ) | ( ... , Some _ , _ ) device used in
those tests serves to avoid warning 12 ( this sub - pattern
is unused ) , by making sure that , even if the two sides of the
disjunction overlap , none is fully included in the other .
those tests serves to avoid warning 12 (this sub-pattern
is unused), by making sure that, even if the two sides of the
disjunction overlap, none is fully included in the other. *)
let not_ambiguous__prefix_variables = function
| (`B (x, _, Some y) | `B (x, Some y, _)) when x -> ignore y
| _ -> ()
;;
[%%expect {|
val not_ambiguous__prefix_variables :
[> `B of bool * 'a option * 'a option ] -> unit = <fun>
|}]
let ambiguous__y = function
| (`B (x, _, Some y) | `B (x, Some y, _)) when y -> ignore x
| _ -> ()
;;
[%%expect {|
Line 2, characters 4-43:
2 | | (`B (x, _, Some y) | `B (x, Some y, _)) when y -> ignore x
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
variable y appears in different places in different or-pattern alternatives.
Only the first match will be used to evaluate the guard expression.
(See manual section 13.5)
val ambiguous__y : [> `B of 'a * bool option * bool option ] -> unit = <fun>
|}]
(* it should be understood that the ambiguity warning only protects
(p | q) when guard -> ...
it will never warn on
(p | q) -> if guard ...
This is not a limitation. The point is that people have an
intuitive understanding of [(p | q) when guard -> ...] that differs
from the reality, while there is no such issue with
[(p | q) -> if guard ...].
*)
let not_ambiguous__rhs_not_protected = function
| (`B (x, _, Some y) | `B (x, Some y, _)) -> if y then ignore x else ()
| _ -> ()
;;
[%%expect {|
val not_ambiguous__rhs_not_protected :
[> `B of 'a * bool option * bool option ] -> unit = <fun>
|}]
let ambiguous__x_y = function
| (`B (x, _, Some y) | `B (x, Some y, _)) when x < y -> ()
| _ -> ()
;;
[%%expect {|
Line 2, characters 4-43:
2 | | (`B (x, _, Some y) | `B (x, Some y, _)) when x < y -> ()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
variable y appears in different places in different or-pattern alternatives.
Only the first match will be used to evaluate the guard expression.
(See manual section 13.5)
val ambiguous__x_y : [> `B of 'a * 'a option * 'a option ] -> unit = <fun>
|}]
let ambiguous__x_y_z = function
| (`B (x, z, Some y) | `B (x, Some y, z)) when x < y || Some x = z -> ()
| _ -> ()
;;
[%%expect {|
Line 2, characters 4-43:
2 | | (`B (x, z, Some y) | `B (x, Some y, z)) when x < y || Some x = z -> ()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
variables y, z appear in different places in different or-pattern alternatives.
Only the first match will be used to evaluate the guard expression.
(See manual section 13.5)
val ambiguous__x_y_z : [> `B of 'a * 'a option * 'a option ] -> unit = <fun>
|}]
let not_ambiguous__disjoint_in_depth = function
| `A (`B x | `C x) when x -> ()
| _ -> ()
;;
[%%expect {|
val not_ambiguous__disjoint_in_depth :
[> `A of [> `B of bool | `C of bool ] ] -> unit = <fun>
|}]
let not_ambiguous__prefix_variables_in_depth = function
| `A (`B (x, `C1) | `B (x, `C2)) when x -> ()
| _ -> ()
;;
[%%expect {|
val not_ambiguous__prefix_variables_in_depth :
[> `A of [> `B of bool * [> `C1 | `C2 ] ] ] -> unit = <fun>
|}]
let ambiguous__in_depth = function
| `A (`B (Some x, _) | `B (_, Some x)) when x -> ()
| _ -> ()
;;
[%%expect {|
Line 2, characters 4-40:
2 | | `A (`B (Some x, _) | `B (_, Some x)) when x -> ()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
variable x appears in different places in different or-pattern alternatives.
Only the first match will be used to evaluate the guard expression.
(See manual section 13.5)
val ambiguous__in_depth :
[> `A of [> `B of bool option * bool option ] ] -> unit = <fun>
|}]
let not_ambiguous__several_orpats = function
| `A ((`B (x, Some _, _) | `B (x, _, Some _)),
(`C (y, Some _, _) | `C (y, _, Some _)),
(`D1 (_, z, Some _, _) | `D2 (_, z, _, Some _))) when x < y && x < z ->
()
| _ -> ()
;;
[%%expect {|
val not_ambiguous__several_orpats :
[> `A of
[> `B of 'a * 'b option * 'c option ] *
[> `C of 'a * 'd option * 'e option ] *
[> `D1 of 'f * 'a * 'g option * 'h | `D2 of 'i * 'a * 'j * 'k option ]
] -> unit = <fun>
|}]
let ambiguous__first_orpat = function
| `A ((`B (Some x, _) | `B (_, Some x)),
(`C (Some y, Some _, _) | `C (Some y, _, Some _))) when x < y -> ()
| _ -> ()
;;
[%%expect {|
Lines 2-3, characters 4-58:
2 | ....`A ((`B (Some x, _) | `B (_, Some x)),
3 | (`C (Some y, Some _, _) | `C (Some y, _, Some _))).................
Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
variable x appears in different places in different or-pattern alternatives.
Only the first match will be used to evaluate the guard expression.
(See manual section 13.5)
val ambiguous__first_orpat :
[> `A of
[> `B of 'a option * 'a option ] *
[> `C of 'a option * 'b option * 'c option ] ] ->
unit = <fun>
|}]
let ambiguous__second_orpat = function
| `A ((`B (Some x, Some _, _) | `B (Some x, _, Some _)),
(`C (Some y, _) | `C (_, Some y))) when x < y -> ()
| _ -> ()
;;
[%%expect {|
Lines 2-3, characters 4-42:
2 | ....`A ((`B (Some x, Some _, _) | `B (Some x, _, Some _)),
3 | (`C (Some y, _) | `C (_, Some y))).................
Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
variable y appears in different places in different or-pattern alternatives.
Only the first match will be used to evaluate the guard expression.
(See manual section 13.5)
val ambiguous__second_orpat :
[> `A of
[> `B of 'a option * 'b option * 'c option ] *
[> `C of 'a option * 'a option ] ] ->
unit = <fun>
|}]
(* check that common prefixes work as expected *)
let not_ambiguous__pairs = function
| (x, Some _, _) | (x, _, Some _) when x -> ()
| _ -> ()
;;
[%%expect {|
val not_ambiguous__pairs : bool * 'a option * 'b option -> unit = <fun>
|}]
let not_ambiguous__vars =
begin[@warning "-12"] function
| (x | x) when x -> ()
| _ -> ()
end
;;
[%%expect {|
val not_ambiguous__vars : bool -> unit = <fun>
|}]
let not_ambiguous__as p = function
| (([], _) as x | ((_, []) as x)) when p x -> ()
| _ -> ()
;;
[%%expect {|
val not_ambiguous__as :
('a list * 'b list -> bool) -> 'a list * 'b list -> unit = <fun>
|}]
let not_ambiguous__as_var p = function
| (([], _) as x | x) when p x -> ()
| _ -> ()
;;
[%%expect {|
val not_ambiguous__as_var : ('a list * 'b -> bool) -> 'a list * 'b -> unit =
<fun>
|}]
let not_ambiguous__var_as p = function
| (x, Some _, _) | (([], _) as x, _, Some _) when p x -> ()
| _ -> ()
;;
[%%expect {|
val not_ambiguous__var_as :
('a list * 'b -> bool) -> ('a list * 'b) * 'c option * 'd option -> unit =
<fun>
|}]
let not_ambiguous__lazy = function
| (([], _), lazy x) | ((_, []), lazy x) when x -> ()
| _ -> ()
;;
[%%expect {|
val not_ambiguous__lazy : ('a list * 'b list) * bool lazy_t -> unit = <fun>
|}]
type t = A of int * int option * int option | B;;
[%%expect {|
type t = A of int * int option * int option | B
|}]
let not_ambiguous__constructor = function
| A (x, Some _, _) | A (x, _, Some _) when x > 0 -> ()
| A _ | B -> ()
;;
[%%expect {|
val not_ambiguous__constructor : t -> unit = <fun>
|}]
type amoi = Z of int | Y of int * int | X of amoi * amoi
;;
[%%expect {|
type amoi = Z of int | Y of int * int | X of amoi * amoi
|}]
let ambiguous__amoi a = match a with
| X (Z x,Y (y,0))
| X (Z y,Y (x,_))
when x+y > 0 -> 0
| X _|Y _|Z _ -> 1
;;
[%%expect {|
Lines 2-3, characters 2-17:
2 | ..X (Z x,Y (y,0))
3 | | X (Z y,Y (x,_))
Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
variables x, y appear in different places in different or-pattern alternatives.
Only the first match will be used to evaluate the guard expression.
(See manual section 13.5)
val ambiguous__amoi : amoi -> int = <fun>
|}]
module type S = sig val b : bool end
;;
[%%expect {|
module type S = sig val b : bool end
|}]
let ambiguous__module_variable x b = match x with
| (module M:S),_,(1,_)
| _,(module M:S),(_,1) when M.b && b -> 1
| _ -> 2
;;
[%%expect {|
Lines 2-3, characters 4-24:
2 | ....(module M:S),_,(1,_)
3 | | _,(module M:S),(_,1)...................
Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
variable M appears in different places in different or-pattern alternatives.
Only the first match will be used to evaluate the guard expression.
(See manual section 13.5)
val ambiguous__module_variable :
(module S) * (module S) * (int * int) -> bool -> int = <fun>
|}]
let not_ambiguous__module_variable x b = match x with
| (module M:S),_,(1,_)
| _,(module M:S),(_,1) when b -> 1
| _ -> 2
;;
[%%expect {|
Line 2, characters 12-13:
2 | | (module M:S),_,(1,_)
^
Warning 60 [unused-module]: unused module M.
val not_ambiguous__module_variable :
(module S) * (module S) * (int * int) -> bool -> int = <fun>
|}]
(* Mixed case *)
type t2 = A of int * int | B of int * int
;;
[%%expect {|
type t2 = A of int * int | B of int * int
|}]
let ambiguous_xy_but_not_ambiguous_z g = function
| A (x as z,(0 as y))|A (0 as y as z,x)|B (x,(y as z)) when g x (y+z) -> 1
| _ -> 2
;;
[%%expect {|
Line 2, characters 4-5:
2 | | A (x as z,(0 as y))|A (0 as y as z,x)|B (x,(y as z)) when g x (y+z) -> 1
^
Warning 41 [ambiguous-name]: A belongs to several types: t2 t
The first one was selected. Please disambiguate if this is wrong.
Lines 1-3, characters 41-10:
1 | .........................................function
2 | | A (x as z,(0 as y))|A (0 as y as z,x)|B (x,(y as z)) when g x (y+z) -> 1
3 | | _ -> 2
Warning 4 [fragile-match]: this pattern-matching is fragile.
It will remain exhaustive when constructors are added to type t2.
Line 2, characters 4-56:
2 | | A (x as z,(0 as y))|A (0 as y as z,x)|B (x,(y as z)) when g x (y+z) -> 1
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
variables x, y appear in different places in different or-pattern alternatives.
Only the first match will be used to evaluate the guard expression.
(See manual section 13.5)
val ambiguous_xy_but_not_ambiguous_z : (int -> int -> bool) -> t2 -> int =
<fun>
|}, Principal{|
Line 2, characters 4-5:
2 | | A (x as z,(0 as y))|A (0 as y as z,x)|B (x,(y as z)) when g x (y+z) -> 1
^
Warning 41 [ambiguous-name]: A belongs to several types: t2 t
The first one was selected. Please disambiguate if this is wrong.
Line 2, characters 24-25:
2 | | A (x as z,(0 as y))|A (0 as y as z,x)|B (x,(y as z)) when g x (y+z) -> 1
^
Warning 41 [ambiguous-name]: A belongs to several types: t2 t
The first one was selected. Please disambiguate if this is wrong.
Line 2, characters 42-43:
2 | | A (x as z,(0 as y))|A (0 as y as z,x)|B (x,(y as z)) when g x (y+z) -> 1
^
Warning 41 [ambiguous-name]: B belongs to several types: t2 t
The first one was selected. Please disambiguate if this is wrong.
Lines 1-3, characters 41-10:
1 | .........................................function
2 | | A (x as z,(0 as y))|A (0 as y as z,x)|B (x,(y as z)) when g x (y+z) -> 1
3 | | _ -> 2
Warning 4 [fragile-match]: this pattern-matching is fragile.
It will remain exhaustive when constructors are added to type t2.
Line 2, characters 4-56:
2 | | A (x as z,(0 as y))|A (0 as y as z,x)|B (x,(y as z)) when g x (y+z) -> 1
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
variables x, y appear in different places in different or-pattern alternatives.
Only the first match will be used to evaluate the guard expression.
(See manual section 13.5)
val ambiguous_xy_but_not_ambiguous_z : (int -> int -> bool) -> t2 -> int =
<fun>
|}]
Regression test against an erroneous simplification of the algorithm
One can not compute the stable variable of the first row of a matrix
after its simplification and before splitting the
submatrices . Indeed , further splits on the submatrices may reveal
that some rows of this first column belong to disjoint submatrices ,
and thus that the variables are more stable than is visible when
looking at the full column .
One cannot compute the stable variable of the first row of a matrix
after its simplification and before splitting the
submatrices. Indeed, further splits on the submatrices may reveal
that some rows of this first column belong to disjoint submatrices,
and thus that the variables are more stable than is visible when
looking at the full column.
*)
let not_ambiguous__as_disjoint_on_second_column_split = function
| ((Some a, (1 as b)) | (Some b, (2 as a))) when a = 0 -> ignore a; ignore b
| _ -> ()
;;
[%%expect {|
val not_ambiguous__as_disjoint_on_second_column_split :
int option * int -> unit = <fun>
|}]
we check for the ambiguous case first , so there
is no warning
is no warning *)
let solved_ambiguity_typical_example = function
| (Val x, Val y) ->
if x < 0 || y < 0
then ()
else ()
| ((Val x, _) | (_, Val x)) when x < 0 -> ()
| (_, Rest) -> ()
| (_, Val x) ->
(* the reader can expect *)
assert (x >= 0);
(* to hold here. *)
()
;;
[%%expect {|
val solved_ambiguity_typical_example : expr * expr -> unit = <fun>
|}]
(* if the check for the ambiguous case is guarded,
there is still a warning *)
let guarded_ambiguity = function
| (Val x, Val y) when x < 0 || y < 0 -> ()
| ((Val y, _) | (_, Val y)) when y < 0 -> ()
| (_, Rest) -> ()
| (_, Val x) ->
(* the reader can expect *)
assert (x >= 0);
(* to hold here. *)
()
;;
[%%expect {|
Line 3, characters 4-29:
3 | | ((Val y, _) | (_, Val y)) when y < 0 -> ()
^^^^^^^^^^^^^^^^^^^^^^^^^
Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
variable y appears in different places in different or-pattern alternatives.
Only the first match will be used to evaluate the guard expression.
(See manual section 13.5)
val guarded_ambiguity : expr * expr -> unit = <fun>
|}]
(* see GPR#1552 *)
type a = A1 | A2;;
[%%expect {|
type a = A1 | A2
|}]
type 'a alg =
| Val of 'a
| Binop of 'a alg * 'a alg;;
[%%expect {|
type 'a alg = Val of 'a | Binop of 'a alg * 'a alg
|}]
let cmp (pred : a -> bool) (x : a alg) (y : a alg) =
match x, y with
| Val A1, Val A1 -> ()
| ((Val x, _) | (_, Val x)) when pred x -> ()
(* below: silence exhaustiveness/fragility warnings *)
| (Val (A1 | A2) | Binop _), _ -> ()
;;
[%%expect {|
Line 4, characters 4-29:
4 | | ((Val x, _) | (_, Val x)) when pred x -> ()
^^^^^^^^^^^^^^^^^^^^^^^^^
Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
variable x appears in different places in different or-pattern alternatives.
Only the first match will be used to evaluate the guard expression.
(See manual section 13.5)
val cmp : (a -> bool) -> a alg -> a alg -> unit = <fun>
|}]
type a = A1;;
[%%expect {|
type a = A1
|}]
type 'a alg =
| Val of 'a
| Binop of 'a alg * 'a alg;;
[%%expect {|
type 'a alg = Val of 'a | Binop of 'a alg * 'a alg
|}]
let cmp (pred : a -> bool) (x : a alg) (y : a alg) =
match x, y with
| Val A1, Val A1 -> ()
| ((Val x, _) | (_, Val x)) when pred x -> ()
(* below: silence exhaustiveness/fragility warnings *)
| (Val A1 | Binop _), _ -> ()
;;
[%%expect {|
val cmp : (a -> bool) -> a alg -> a alg -> unit = <fun>
|}]
| null | https://raw.githubusercontent.com/ocaml-multicore/ocaml-tsan/ae9c1502103845550162a49fcd3f76276cdfa866/testsuite/tests/typing-warnings/ambiguous_guarded_disjunction.ml | ocaml | TEST
flags = " -w +A -strict-sequence "
* expect
the reader might expect
to hold here, but it is wrong!
it should be understood that the ambiguity warning only protects
(p | q) when guard -> ...
it will never warn on
(p | q) -> if guard ...
This is not a limitation. The point is that people have an
intuitive understanding of [(p | q) when guard -> ...] that differs
from the reality, while there is no such issue with
[(p | q) -> if guard ...].
check that common prefixes work as expected
Mixed case
the reader can expect
to hold here.
if the check for the ambiguous case is guarded,
there is still a warning
the reader can expect
to hold here.
see GPR#1552
below: silence exhaustiveness/fragility warnings
below: silence exhaustiveness/fragility warnings |
Ignore = b to be reproducible
Printexc.record_backtrace false;;
[%%expect {|
- : unit = ()
|}]
type expr = Val of int | Rest;;
[%%expect {|
type expr = Val of int | Rest
|}]
let ambiguous_typical_example = function
| ((Val x, _) | (_, Val x)) when x < 0 -> ()
| (_, Rest) -> ()
| (_, Val x) ->
assert (x >= 0);
()
;;
[%%expect {|
Line 2, characters 4-29:
2 | | ((Val x, _) | (_, Val x)) when x < 0 -> ()
^^^^^^^^^^^^^^^^^^^^^^^^^
Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
variable x appears in different places in different or-pattern alternatives.
Only the first match will be used to evaluate the guard expression.
(See manual section 13.5)
val ambiguous_typical_example : expr * expr -> unit = <fun>
|}]
let fails = ambiguous_typical_example (Val 2, Val (-1))
;;
[%%expect {|
Exception: Assert_failure ("", 6, 6).
|}]
let not_ambiguous__no_orpat = function
| Some x when x > 0 -> ()
| Some _ -> ()
| None -> ()
;;
[%%expect {|
val not_ambiguous__no_orpat : int option -> unit = <fun>
|}]
let not_ambiguous__no_guard = function
| `A -> ()
| (`B | `C) -> ()
;;
[%%expect {|
val not_ambiguous__no_guard : [< `A | `B | `C ] -> unit = <fun>
|}]
let not_ambiguous__no_patvar_in_guard b = function
| (`B x | `C x) when b -> ignore x
| _ -> ()
;;
[%%expect {|
val not_ambiguous__no_patvar_in_guard :
bool -> [> `B of 'a | `C of 'a ] -> unit = <fun>
|}]
let not_ambiguous__disjoint_cases = function
| (`B x | `C x) when x -> ()
| _ -> ()
;;
[%%expect {|
val not_ambiguous__disjoint_cases : [> `B of bool | `C of bool ] -> unit =
<fun>
|}]
the curious ( ... , _ , Some _ ) | ( ... , Some _ , _ ) device used in
those tests serves to avoid warning 12 ( this sub - pattern
is unused ) , by making sure that , even if the two sides of the
disjunction overlap , none is fully included in the other .
those tests serves to avoid warning 12 (this sub-pattern
is unused), by making sure that, even if the two sides of the
disjunction overlap, none is fully included in the other. *)
let not_ambiguous__prefix_variables = function
| (`B (x, _, Some y) | `B (x, Some y, _)) when x -> ignore y
| _ -> ()
;;
[%%expect {|
val not_ambiguous__prefix_variables :
[> `B of bool * 'a option * 'a option ] -> unit = <fun>
|}]
let ambiguous__y = function
| (`B (x, _, Some y) | `B (x, Some y, _)) when y -> ignore x
| _ -> ()
;;
[%%expect {|
Line 2, characters 4-43:
2 | | (`B (x, _, Some y) | `B (x, Some y, _)) when y -> ignore x
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
variable y appears in different places in different or-pattern alternatives.
Only the first match will be used to evaluate the guard expression.
(See manual section 13.5)
val ambiguous__y : [> `B of 'a * bool option * bool option ] -> unit = <fun>
|}]
let not_ambiguous__rhs_not_protected = function
| (`B (x, _, Some y) | `B (x, Some y, _)) -> if y then ignore x else ()
| _ -> ()
;;
[%%expect {|
val not_ambiguous__rhs_not_protected :
[> `B of 'a * bool option * bool option ] -> unit = <fun>
|}]
let ambiguous__x_y = function
| (`B (x, _, Some y) | `B (x, Some y, _)) when x < y -> ()
| _ -> ()
;;
[%%expect {|
Line 2, characters 4-43:
2 | | (`B (x, _, Some y) | `B (x, Some y, _)) when x < y -> ()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
variable y appears in different places in different or-pattern alternatives.
Only the first match will be used to evaluate the guard expression.
(See manual section 13.5)
val ambiguous__x_y : [> `B of 'a * 'a option * 'a option ] -> unit = <fun>
|}]
let ambiguous__x_y_z = function
| (`B (x, z, Some y) | `B (x, Some y, z)) when x < y || Some x = z -> ()
| _ -> ()
;;
[%%expect {|
Line 2, characters 4-43:
2 | | (`B (x, z, Some y) | `B (x, Some y, z)) when x < y || Some x = z -> ()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
variables y, z appear in different places in different or-pattern alternatives.
Only the first match will be used to evaluate the guard expression.
(See manual section 13.5)
val ambiguous__x_y_z : [> `B of 'a * 'a option * 'a option ] -> unit = <fun>
|}]
let not_ambiguous__disjoint_in_depth = function
| `A (`B x | `C x) when x -> ()
| _ -> ()
;;
[%%expect {|
val not_ambiguous__disjoint_in_depth :
[> `A of [> `B of bool | `C of bool ] ] -> unit = <fun>
|}]
let not_ambiguous__prefix_variables_in_depth = function
| `A (`B (x, `C1) | `B (x, `C2)) when x -> ()
| _ -> ()
;;
[%%expect {|
val not_ambiguous__prefix_variables_in_depth :
[> `A of [> `B of bool * [> `C1 | `C2 ] ] ] -> unit = <fun>
|}]
let ambiguous__in_depth = function
| `A (`B (Some x, _) | `B (_, Some x)) when x -> ()
| _ -> ()
;;
[%%expect {|
Line 2, characters 4-40:
2 | | `A (`B (Some x, _) | `B (_, Some x)) when x -> ()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
variable x appears in different places in different or-pattern alternatives.
Only the first match will be used to evaluate the guard expression.
(See manual section 13.5)
val ambiguous__in_depth :
[> `A of [> `B of bool option * bool option ] ] -> unit = <fun>
|}]
let not_ambiguous__several_orpats = function
| `A ((`B (x, Some _, _) | `B (x, _, Some _)),
(`C (y, Some _, _) | `C (y, _, Some _)),
(`D1 (_, z, Some _, _) | `D2 (_, z, _, Some _))) when x < y && x < z ->
()
| _ -> ()
;;
[%%expect {|
val not_ambiguous__several_orpats :
[> `A of
[> `B of 'a * 'b option * 'c option ] *
[> `C of 'a * 'd option * 'e option ] *
[> `D1 of 'f * 'a * 'g option * 'h | `D2 of 'i * 'a * 'j * 'k option ]
] -> unit = <fun>
|}]
let ambiguous__first_orpat = function
| `A ((`B (Some x, _) | `B (_, Some x)),
(`C (Some y, Some _, _) | `C (Some y, _, Some _))) when x < y -> ()
| _ -> ()
;;
[%%expect {|
Lines 2-3, characters 4-58:
2 | ....`A ((`B (Some x, _) | `B (_, Some x)),
3 | (`C (Some y, Some _, _) | `C (Some y, _, Some _))).................
Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
variable x appears in different places in different or-pattern alternatives.
Only the first match will be used to evaluate the guard expression.
(See manual section 13.5)
val ambiguous__first_orpat :
[> `A of
[> `B of 'a option * 'a option ] *
[> `C of 'a option * 'b option * 'c option ] ] ->
unit = <fun>
|}]
let ambiguous__second_orpat = function
| `A ((`B (Some x, Some _, _) | `B (Some x, _, Some _)),
(`C (Some y, _) | `C (_, Some y))) when x < y -> ()
| _ -> ()
;;
[%%expect {|
Lines 2-3, characters 4-42:
2 | ....`A ((`B (Some x, Some _, _) | `B (Some x, _, Some _)),
3 | (`C (Some y, _) | `C (_, Some y))).................
Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
variable y appears in different places in different or-pattern alternatives.
Only the first match will be used to evaluate the guard expression.
(See manual section 13.5)
val ambiguous__second_orpat :
[> `A of
[> `B of 'a option * 'b option * 'c option ] *
[> `C of 'a option * 'a option ] ] ->
unit = <fun>
|}]
let not_ambiguous__pairs = function
| (x, Some _, _) | (x, _, Some _) when x -> ()
| _ -> ()
;;
[%%expect {|
val not_ambiguous__pairs : bool * 'a option * 'b option -> unit = <fun>
|}]
let not_ambiguous__vars =
begin[@warning "-12"] function
| (x | x) when x -> ()
| _ -> ()
end
;;
[%%expect {|
val not_ambiguous__vars : bool -> unit = <fun>
|}]
let not_ambiguous__as p = function
| (([], _) as x | ((_, []) as x)) when p x -> ()
| _ -> ()
;;
[%%expect {|
val not_ambiguous__as :
('a list * 'b list -> bool) -> 'a list * 'b list -> unit = <fun>
|}]
let not_ambiguous__as_var p = function
| (([], _) as x | x) when p x -> ()
| _ -> ()
;;
[%%expect {|
val not_ambiguous__as_var : ('a list * 'b -> bool) -> 'a list * 'b -> unit =
<fun>
|}]
let not_ambiguous__var_as p = function
| (x, Some _, _) | (([], _) as x, _, Some _) when p x -> ()
| _ -> ()
;;
[%%expect {|
val not_ambiguous__var_as :
('a list * 'b -> bool) -> ('a list * 'b) * 'c option * 'd option -> unit =
<fun>
|}]
let not_ambiguous__lazy = function
| (([], _), lazy x) | ((_, []), lazy x) when x -> ()
| _ -> ()
;;
[%%expect {|
val not_ambiguous__lazy : ('a list * 'b list) * bool lazy_t -> unit = <fun>
|}]
type t = A of int * int option * int option | B;;
[%%expect {|
type t = A of int * int option * int option | B
|}]
let not_ambiguous__constructor = function
| A (x, Some _, _) | A (x, _, Some _) when x > 0 -> ()
| A _ | B -> ()
;;
[%%expect {|
val not_ambiguous__constructor : t -> unit = <fun>
|}]
type amoi = Z of int | Y of int * int | X of amoi * amoi
;;
[%%expect {|
type amoi = Z of int | Y of int * int | X of amoi * amoi
|}]
let ambiguous__amoi a = match a with
| X (Z x,Y (y,0))
| X (Z y,Y (x,_))
when x+y > 0 -> 0
| X _|Y _|Z _ -> 1
;;
[%%expect {|
Lines 2-3, characters 2-17:
2 | ..X (Z x,Y (y,0))
3 | | X (Z y,Y (x,_))
Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
variables x, y appear in different places in different or-pattern alternatives.
Only the first match will be used to evaluate the guard expression.
(See manual section 13.5)
val ambiguous__amoi : amoi -> int = <fun>
|}]
module type S = sig val b : bool end
;;
[%%expect {|
module type S = sig val b : bool end
|}]
let ambiguous__module_variable x b = match x with
| (module M:S),_,(1,_)
| _,(module M:S),(_,1) when M.b && b -> 1
| _ -> 2
;;
[%%expect {|
Lines 2-3, characters 4-24:
2 | ....(module M:S),_,(1,_)
3 | | _,(module M:S),(_,1)...................
Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
variable M appears in different places in different or-pattern alternatives.
Only the first match will be used to evaluate the guard expression.
(See manual section 13.5)
val ambiguous__module_variable :
(module S) * (module S) * (int * int) -> bool -> int = <fun>
|}]
let not_ambiguous__module_variable x b = match x with
| (module M:S),_,(1,_)
| _,(module M:S),(_,1) when b -> 1
| _ -> 2
;;
[%%expect {|
Line 2, characters 12-13:
2 | | (module M:S),_,(1,_)
^
Warning 60 [unused-module]: unused module M.
val not_ambiguous__module_variable :
(module S) * (module S) * (int * int) -> bool -> int = <fun>
|}]
type t2 = A of int * int | B of int * int
;;
[%%expect {|
type t2 = A of int * int | B of int * int
|}]
let ambiguous_xy_but_not_ambiguous_z g = function
| A (x as z,(0 as y))|A (0 as y as z,x)|B (x,(y as z)) when g x (y+z) -> 1
| _ -> 2
;;
[%%expect {|
Line 2, characters 4-5:
2 | | A (x as z,(0 as y))|A (0 as y as z,x)|B (x,(y as z)) when g x (y+z) -> 1
^
Warning 41 [ambiguous-name]: A belongs to several types: t2 t
The first one was selected. Please disambiguate if this is wrong.
Lines 1-3, characters 41-10:
1 | .........................................function
2 | | A (x as z,(0 as y))|A (0 as y as z,x)|B (x,(y as z)) when g x (y+z) -> 1
3 | | _ -> 2
Warning 4 [fragile-match]: this pattern-matching is fragile.
It will remain exhaustive when constructors are added to type t2.
Line 2, characters 4-56:
2 | | A (x as z,(0 as y))|A (0 as y as z,x)|B (x,(y as z)) when g x (y+z) -> 1
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
variables x, y appear in different places in different or-pattern alternatives.
Only the first match will be used to evaluate the guard expression.
(See manual section 13.5)
val ambiguous_xy_but_not_ambiguous_z : (int -> int -> bool) -> t2 -> int =
<fun>
|}, Principal{|
Line 2, characters 4-5:
2 | | A (x as z,(0 as y))|A (0 as y as z,x)|B (x,(y as z)) when g x (y+z) -> 1
^
Warning 41 [ambiguous-name]: A belongs to several types: t2 t
The first one was selected. Please disambiguate if this is wrong.
Line 2, characters 24-25:
2 | | A (x as z,(0 as y))|A (0 as y as z,x)|B (x,(y as z)) when g x (y+z) -> 1
^
Warning 41 [ambiguous-name]: A belongs to several types: t2 t
The first one was selected. Please disambiguate if this is wrong.
Line 2, characters 42-43:
2 | | A (x as z,(0 as y))|A (0 as y as z,x)|B (x,(y as z)) when g x (y+z) -> 1
^
Warning 41 [ambiguous-name]: B belongs to several types: t2 t
The first one was selected. Please disambiguate if this is wrong.
Lines 1-3, characters 41-10:
1 | .........................................function
2 | | A (x as z,(0 as y))|A (0 as y as z,x)|B (x,(y as z)) when g x (y+z) -> 1
3 | | _ -> 2
Warning 4 [fragile-match]: this pattern-matching is fragile.
It will remain exhaustive when constructors are added to type t2.
Line 2, characters 4-56:
2 | | A (x as z,(0 as y))|A (0 as y as z,x)|B (x,(y as z)) when g x (y+z) -> 1
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
variables x, y appear in different places in different or-pattern alternatives.
Only the first match will be used to evaluate the guard expression.
(See manual section 13.5)
val ambiguous_xy_but_not_ambiguous_z : (int -> int -> bool) -> t2 -> int =
<fun>
|}]
Regression test against an erroneous simplification of the algorithm
One can not compute the stable variable of the first row of a matrix
after its simplification and before splitting the
submatrices . Indeed , further splits on the submatrices may reveal
that some rows of this first column belong to disjoint submatrices ,
and thus that the variables are more stable than is visible when
looking at the full column .
One cannot compute the stable variable of the first row of a matrix
after its simplification and before splitting the
submatrices. Indeed, further splits on the submatrices may reveal
that some rows of this first column belong to disjoint submatrices,
and thus that the variables are more stable than is visible when
looking at the full column.
*)
let not_ambiguous__as_disjoint_on_second_column_split = function
| ((Some a, (1 as b)) | (Some b, (2 as a))) when a = 0 -> ignore a; ignore b
| _ -> ()
;;
[%%expect {|
val not_ambiguous__as_disjoint_on_second_column_split :
int option * int -> unit = <fun>
|}]
we check for the ambiguous case first , so there
is no warning
is no warning *)
let solved_ambiguity_typical_example = function
| (Val x, Val y) ->
if x < 0 || y < 0
then ()
else ()
| ((Val x, _) | (_, Val x)) when x < 0 -> ()
| (_, Rest) -> ()
| (_, Val x) ->
assert (x >= 0);
()
;;
[%%expect {|
val solved_ambiguity_typical_example : expr * expr -> unit = <fun>
|}]
let guarded_ambiguity = function
| (Val x, Val y) when x < 0 || y < 0 -> ()
| ((Val y, _) | (_, Val y)) when y < 0 -> ()
| (_, Rest) -> ()
| (_, Val x) ->
assert (x >= 0);
()
;;
[%%expect {|
Line 3, characters 4-29:
3 | | ((Val y, _) | (_, Val y)) when y < 0 -> ()
^^^^^^^^^^^^^^^^^^^^^^^^^
Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
variable y appears in different places in different or-pattern alternatives.
Only the first match will be used to evaluate the guard expression.
(See manual section 13.5)
val guarded_ambiguity : expr * expr -> unit = <fun>
|}]
type a = A1 | A2;;
[%%expect {|
type a = A1 | A2
|}]
type 'a alg =
| Val of 'a
| Binop of 'a alg * 'a alg;;
[%%expect {|
type 'a alg = Val of 'a | Binop of 'a alg * 'a alg
|}]
let cmp (pred : a -> bool) (x : a alg) (y : a alg) =
match x, y with
| Val A1, Val A1 -> ()
| ((Val x, _) | (_, Val x)) when pred x -> ()
| (Val (A1 | A2) | Binop _), _ -> ()
;;
[%%expect {|
Line 4, characters 4-29:
4 | | ((Val x, _) | (_, Val x)) when pred x -> ()
^^^^^^^^^^^^^^^^^^^^^^^^^
Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
variable x appears in different places in different or-pattern alternatives.
Only the first match will be used to evaluate the guard expression.
(See manual section 13.5)
val cmp : (a -> bool) -> a alg -> a alg -> unit = <fun>
|}]
type a = A1;;
[%%expect {|
type a = A1
|}]
type 'a alg =
| Val of 'a
| Binop of 'a alg * 'a alg;;
[%%expect {|
type 'a alg = Val of 'a | Binop of 'a alg * 'a alg
|}]
let cmp (pred : a -> bool) (x : a alg) (y : a alg) =
match x, y with
| Val A1, Val A1 -> ()
| ((Val x, _) | (_, Val x)) when pred x -> ()
| (Val A1 | Binop _), _ -> ()
;;
[%%expect {|
val cmp : (a -> bool) -> a alg -> a alg -> unit = <fun>
|}]
|
1157bf2ac7f2d7a7749beca46651671683fb96bdcf8dff7d099fb96edc252484 | trainline/optimus | core.clj | Copyright ( c ) Trainline Limited , 2017 . All rights reserved .
See LICENSE.txt in the project root for license information
(ns optimus.service.core
"This namespace is the business logic layer for the Optimus service.
Functions in this namespace perform the necessary orchestrations across the
meta data store, kv store and queue that feeds the async task processor."
(:require [optimus.service
[backend :as b]
[util :refer [rand-id throw-core-exception
throw-missing-entity throw-validation-error
metrics-name]]]
[clojure.core.memoize :refer [ttl]]
[samsara.trackit :refer :all]
[where.core :refer [where]]))
BackendStore - record to encapsulate the backend components of the Model Data
;; Store
(defrecord BackendStore
[queue meta-store kv-store pid config])
(defn ->BackendStore
([config]
(BackendStore. nil nil nil nil config))
([queue meta-store kv-store pid config]
(BackendStore. queue meta-store kv-store pid config)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;
;; ---==| D A T A S E T S |==---- ;;
;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn create-dataset
"Creates a new dataset for the given dataset name.
Returns the dataset created."
[{:keys [meta-store]} {:keys [name] :as dataset}]
(track-time
(metrics-name :core :create-dataset)
(-> (b/create-dataset meta-store dataset)
(b/get-dataset name))))
(defn get-dataset
"Returns dataset for the given dataset name"
[{:keys [meta-store]} dsname]
(track-time
(metrics-name :core :get-dataset)
(b/get-dataset meta-store dsname)))
(defn get-datasets
"Returns all datasets"
[{:keys [meta-store]}]
(track-time
(metrics-name :core :get-dataset)
(b/get-all-datasets meta-store)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;
;; ---==| V E R S I O N S |==---- ;;
;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn create-version
"Creates a new version and sends a :prepare event to the queue.
Returns the version created."
[{:keys [queue meta-store config] :as backend} version]
(track-time
(metrics-name :core :create-version)
(let [version-id (rand-id)]
(b/create-version meta-store (assoc version :id version-id))
(b/send-message! queue
(get-in config [:async-task :operations-topic])
{:action :prepare :version-id version-id})
(b/get-version meta-store version-id))))
(defn get-version
"Returns a version for the given version-id"
[{:keys [meta-store]} version-id]
(track-time
(metrics-name :core :get-version)
(b/get-version meta-store version-id)))
(defn get-versions
"Returns all versions for a given dataset name"
[{:keys [meta-store]} dsname]
(track-time
(metrics-name :core :get-versions)
(b/get-versions meta-store dsname)))
(defn save-version
"Changes the status of the specified version to :saving and publishes a `save`
event to the async task queue."
[{:keys [meta-store queue config]} version-id]
(track-time
(metrics-name :core :save-version)
(let [{:keys [status] :as version} (b/get-version meta-store version-id)]
(cond
;; Version not found
(nil? version) (throw-missing-entity "version not found"
{:error :version-not-found})
;; invalid status - version must be :awaiting-entries to load data
(not
(b/status-transition-valid?
status :saving)) (throw-validation-error "invalid version state"
{:error :invalid-version-state
:version version})
:else (do
(b/update-status meta-store version-id :saving {})
(b/send-message! queue
(get-in config [:async-task :operations-topic])
{:action :save :version-id version-id}))))))
(defn publish-version
"Changes the status of the specified version to :publishing and publishes a
`publish` event to the async task queue."
[{:keys [meta-store queue config]} version-id]
(track-time
(metrics-name :core :publish-version)
(let [{:keys [status] :as version} (b/get-version meta-store version-id)]
(cond
;; Version not found
(nil? version) (throw-missing-entity "version not found"
{:error :version-not-found})
;; invalid status - version must be :awaiting-entries to load data
(not
(b/status-transition-valid?
status :publishing)) (throw-validation-error "invalid version state"
{:error :invalid-version-state
:version version})
:else (do
(b/update-status meta-store version-id :publishing {})
(b/send-message! queue
(get-in config [:async-task :operations-topic])
{:action :publish :version-id version-id}))))))
(defn discard-version
"Discards the version corresponding to the specified version-id and
appends the specified reason to the operation log."
[{:keys [meta-store queue]} version-id reason]
(track-time
(metrics-name :core :discard-version)
(let [{:keys [status] :as version} (b/get-version meta-store version-id)]
(cond
;; Version not found
(nil? version) (throw-missing-entity "version not found"
{:error :version-not-found})
;; invalid status - version must be :awaiting-entries to load data
(not
(b/status-transition-valid?
status :discarded)) (throw-validation-error "invalid version state"
{:error :invalid-version-state})
:else (do
(b/update-status meta-store version-id :discarded {:reason reason}))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;
---==| L O A D D A T A |==---- ; ;
;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def memoized-get-dataset (memoize b/get-dataset))
(defn dataset-missing-in
"a `where` comparator that returns true if the dataset specified does not
exist in the meta data store."
[dataset meta-store]
(not (memoized-get-dataset meta-store dataset)))
(defn table-missing-in
"a `where` comparator that returns true if the table specified does not
exist for corresponding dataset in the meta data store."
[{:keys [dataset table]} meta-store]
(not (if-let [ds (memoized-get-dataset meta-store dataset)]
(get-in ds [:tables table] nil)
false)))
(defn missing-datasets
"Returns a collection of dataset names in the entries specified,
that do not exist in the meta data store."
[meta-store entries]
(->> entries
(filter (where :dataset dataset-missing-in meta-store))
(map #(get % :dataset))))
(defn missing-tables
"Returns the entries for which the specified table name does not exist
for the corresponding dataset in the meta data store"
[meta-store entries]
(->> entries
(filter (where table-missing-in meta-store))))
(defn validate-entries
"Validates the entries specified. This function does NOT validate the
schema of the entries supplied. It only checks if the tables
in the request exist in the meta data store.
Returns a vector that contains the result of validation and a map that
contains missing tables. eg.
[false {:missing-tables nil}
(or)
[false {:missing-tables ({:dataset \"ds1\" :table \"t2\"})}]
(or)
[true nil]"
[meta-store entries]
(let [ds-tbls (->> entries (map #(select-keys % [:dataset :table])) distinct)
missing-tb (seq (missing-tables meta-store ds-tbls))]
(if (nil? missing-tb)
[true nil]
[false {:missing-tables missing-tb}])))
(defn- entry->kv
"Transforms a flat entry that looks like: {:dataset :table :key :value}
to a kv pair [{:dataset :table :key} :value]"
[entry]
(-> entry
(select-keys [:dataset :table :version :key])
vector
(conj (:value entry))))
(defn- load-data
"Creates `entries` by adding dataset name and version to the specified
table-key-value pairs and loads them into the kv-store. Validates the
dataset and table names supplied and throws an exception when the validation
fails. See `create-entries` for information reg ex-data passed in the
exception. Returns :ok if the load was successful."
[{:keys [kv-store meta-store]} version-id dsname tbl-key-vals]
;; Structure of tbl-key-vals => [{:table "table" :key "key" :value "value"}]
;; Must be transformed to: {{:dataset "ds" :table "table" :key "key"} value}}
;; below structure in-order to be passed to the backend
;; Transformation Steps:
- conjoin { : dataset dsname : version version - id } to in - key - vals
;; -
(let [entries (->> tbl-key-vals
(map #(conj {:dataset dsname :version version-id} %))
(mapcat entry->kv)
(apply hash-map))
[valid? errors] (validate-entries meta-store (keys entries))]
(if-not valid?
(throw-missing-entity "Table(s) not found"
(conj {:error :tables-not-found} errors)))
;; Return true if put was successful.
(b/put-many kv-store entries)
:ok))
(defn create-entries
"Loads data for the specified version. Throws an exception in the following
cases with the given message and ex-data with 2 keys :error and additional
information containing context related to the error.
| Condition | :error | :addl-info |
|--------------------------+------------------------------+--------------------|
| Version: | | |
| - not found | :version-not-found | nil |
| - does not match dataset | :invalid-version-for-dataset | {:version} |
| - invalid state | :invalid-version-state | {:version} |
| | | |
| Data | :invalid-request | {:missing-tables} |
| | | |
Returns :ok on success."
([{:keys [meta-store kv-store] :as bknd-store} version-id dsname tbl-key-vals]
(track-time
(metrics-name :core :create-entries)
(let [{:keys [dataset status] :as version} (b/get-version meta-store version-id)]
(cond
;; Version not found
(nil? version) (throw-missing-entity "version not found"
{:error :version-not-found})
;; version does not match dataset
(not= dataset dsname) (throw-validation-error
"version does not match dataset"
{:error :invalid-version-for-dataset
:version version})
;; invalid status - version must be :awaiting-entries to load data
(not= status :awaiting-entries) (throw-validation-error
"invalid version state"
{:error :invalid-version-state
:version version})
:else (load-data bknd-store version-id dsname tbl-key-vals)))))
([bknd-store version-id dsname table-name key-vals]
(track-time
(metrics-name :core :create-entries table-name)
(->> key-vals
(map #(conj {:table table-name :version version-id} %))
(create-entries bknd-store version-id dsname))))
([{:keys [meta-store] :as bknd-store} version-id dsname table-name key value]
Validate if dataset is present .
(track-time
(metrics-name :core :create-entry)
(create-entries bknd-store version-id dsname
[{:table table-name :key key :value value}]))))
(defn get-active-version*
"Returns the active version of the dataset"
[bknd dataset-name]
(let [{:keys [active-version] :as dataset} (get-dataset bknd dataset-name)]
(cond
(nil? dataset) (throw-missing-entity "dataset does not exist" {})
(nil? active-version) (throw-validation-error "no active version for dataset" {})
:else active-version)))
(def get-active-version
"Returns the active version of the dataset. This function calls the
get-active-version* function and caches the output for 10
seconds."
(ttl
(fn [bknd dataset-name] (get-active-version* bknd dataset-name))
:ttl/threshold 10000))
(defn get-entry
"Return a single entry from the keyvalue store for the specified
version-id dataset table key combination. Returns a map that contains
the following keys::
:active-version-id - version currently active for the dataset requested.
:version-id - version of the data returned
:data - value for the requested key"
[{:keys [kv-store] :as bknd} version-id dataset table key]
(track-time
(metrics-name :core :get-entry)
(let [active-version (get-active-version bknd dataset)
version-id (if version-id version-id active-version)]
(->> {:dataset dataset :version version-id :table table :key key}
(b/get-one kv-store)
(assoc {:active-version-id active-version
:version-id version-id}
:data)))))
(defn get-entries
"Returns entries from the key value store for the specified
version-id dataset table and keys.Returns a map that contains
the following keys::
:active-version-id - version currently active for the dataset requested.
:version-id - version of the data returned
:data - values for the requested keys"
([{:keys [kv-store] :as bknd} version-id dataset table keys]
;; keys - [{:key String}]
(track-time
(metrics-name :core :get-entries)
(let [active-version (get-active-version bknd dataset)
version-id (if version-id version-id active-version)]
(->> keys
(map #(conj {:dataset dataset :table table :version version-id} %))
(b/get-many kv-store)
(assoc {:active-version-id active-version
:version-id version-id} :data))))))
| null | https://raw.githubusercontent.com/trainline/optimus/caf4d065f40d5edef87eeb60d767b8379465501e/service/src/optimus/service/core.clj | clojure | Store
;;
---==| D A T A S E T S |==---- ;;
;;
;;
---==| V E R S I O N S |==---- ;;
;;
Version not found
invalid status - version must be :awaiting-entries to load data
Version not found
invalid status - version must be :awaiting-entries to load data
Version not found
invalid status - version must be :awaiting-entries to load data
;;
;
;;
Structure of tbl-key-vals => [{:table "table" :key "key" :value "value"}]
Must be transformed to: {{:dataset "ds" :table "table" :key "key"} value}}
below structure in-order to be passed to the backend
Transformation Steps:
-
Return true if put was successful.
Version not found
version does not match dataset
invalid status - version must be :awaiting-entries to load data
keys - [{:key String}] | Copyright ( c ) Trainline Limited , 2017 . All rights reserved .
See LICENSE.txt in the project root for license information
(ns optimus.service.core
"This namespace is the business logic layer for the Optimus service.
Functions in this namespace perform the necessary orchestrations across the
meta data store, kv store and queue that feeds the async task processor."
(:require [optimus.service
[backend :as b]
[util :refer [rand-id throw-core-exception
throw-missing-entity throw-validation-error
metrics-name]]]
[clojure.core.memoize :refer [ttl]]
[samsara.trackit :refer :all]
[where.core :refer [where]]))
BackendStore - record to encapsulate the backend components of the Model Data
(defrecord BackendStore
[queue meta-store kv-store pid config])
(defn ->BackendStore
([config]
(BackendStore. nil nil nil nil config))
([queue meta-store kv-store pid config]
(BackendStore. queue meta-store kv-store pid config)))
(defn create-dataset
"Creates a new dataset for the given dataset name.
Returns the dataset created."
[{:keys [meta-store]} {:keys [name] :as dataset}]
(track-time
(metrics-name :core :create-dataset)
(-> (b/create-dataset meta-store dataset)
(b/get-dataset name))))
(defn get-dataset
"Returns dataset for the given dataset name"
[{:keys [meta-store]} dsname]
(track-time
(metrics-name :core :get-dataset)
(b/get-dataset meta-store dsname)))
(defn get-datasets
"Returns all datasets"
[{:keys [meta-store]}]
(track-time
(metrics-name :core :get-dataset)
(b/get-all-datasets meta-store)))
(defn create-version
"Creates a new version and sends a :prepare event to the queue.
Returns the version created."
[{:keys [queue meta-store config] :as backend} version]
(track-time
(metrics-name :core :create-version)
(let [version-id (rand-id)]
(b/create-version meta-store (assoc version :id version-id))
(b/send-message! queue
(get-in config [:async-task :operations-topic])
{:action :prepare :version-id version-id})
(b/get-version meta-store version-id))))
(defn get-version
"Returns a version for the given version-id"
[{:keys [meta-store]} version-id]
(track-time
(metrics-name :core :get-version)
(b/get-version meta-store version-id)))
(defn get-versions
"Returns all versions for a given dataset name"
[{:keys [meta-store]} dsname]
(track-time
(metrics-name :core :get-versions)
(b/get-versions meta-store dsname)))
(defn save-version
"Changes the status of the specified version to :saving and publishes a `save`
event to the async task queue."
[{:keys [meta-store queue config]} version-id]
(track-time
(metrics-name :core :save-version)
(let [{:keys [status] :as version} (b/get-version meta-store version-id)]
(cond
(nil? version) (throw-missing-entity "version not found"
{:error :version-not-found})
(not
(b/status-transition-valid?
status :saving)) (throw-validation-error "invalid version state"
{:error :invalid-version-state
:version version})
:else (do
(b/update-status meta-store version-id :saving {})
(b/send-message! queue
(get-in config [:async-task :operations-topic])
{:action :save :version-id version-id}))))))
(defn publish-version
"Changes the status of the specified version to :publishing and publishes a
`publish` event to the async task queue."
[{:keys [meta-store queue config]} version-id]
(track-time
(metrics-name :core :publish-version)
(let [{:keys [status] :as version} (b/get-version meta-store version-id)]
(cond
(nil? version) (throw-missing-entity "version not found"
{:error :version-not-found})
(not
(b/status-transition-valid?
status :publishing)) (throw-validation-error "invalid version state"
{:error :invalid-version-state
:version version})
:else (do
(b/update-status meta-store version-id :publishing {})
(b/send-message! queue
(get-in config [:async-task :operations-topic])
{:action :publish :version-id version-id}))))))
(defn discard-version
"Discards the version corresponding to the specified version-id and
appends the specified reason to the operation log."
[{:keys [meta-store queue]} version-id reason]
(track-time
(metrics-name :core :discard-version)
(let [{:keys [status] :as version} (b/get-version meta-store version-id)]
(cond
(nil? version) (throw-missing-entity "version not found"
{:error :version-not-found})
(not
(b/status-transition-valid?
status :discarded)) (throw-validation-error "invalid version state"
{:error :invalid-version-state})
:else (do
(b/update-status meta-store version-id :discarded {:reason reason}))))))
(def memoized-get-dataset (memoize b/get-dataset))
(defn dataset-missing-in
"a `where` comparator that returns true if the dataset specified does not
exist in the meta data store."
[dataset meta-store]
(not (memoized-get-dataset meta-store dataset)))
(defn table-missing-in
"a `where` comparator that returns true if the table specified does not
exist for corresponding dataset in the meta data store."
[{:keys [dataset table]} meta-store]
(not (if-let [ds (memoized-get-dataset meta-store dataset)]
(get-in ds [:tables table] nil)
false)))
(defn missing-datasets
"Returns a collection of dataset names in the entries specified,
that do not exist in the meta data store."
[meta-store entries]
(->> entries
(filter (where :dataset dataset-missing-in meta-store))
(map #(get % :dataset))))
(defn missing-tables
"Returns the entries for which the specified table name does not exist
for the corresponding dataset in the meta data store"
[meta-store entries]
(->> entries
(filter (where table-missing-in meta-store))))
(defn validate-entries
"Validates the entries specified. This function does NOT validate the
schema of the entries supplied. It only checks if the tables
in the request exist in the meta data store.
Returns a vector that contains the result of validation and a map that
contains missing tables. eg.
[false {:missing-tables nil}
(or)
[false {:missing-tables ({:dataset \"ds1\" :table \"t2\"})}]
(or)
[true nil]"
[meta-store entries]
(let [ds-tbls (->> entries (map #(select-keys % [:dataset :table])) distinct)
missing-tb (seq (missing-tables meta-store ds-tbls))]
(if (nil? missing-tb)
[true nil]
[false {:missing-tables missing-tb}])))
(defn- entry->kv
"Transforms a flat entry that looks like: {:dataset :table :key :value}
to a kv pair [{:dataset :table :key} :value]"
[entry]
(-> entry
(select-keys [:dataset :table :version :key])
vector
(conj (:value entry))))
(defn- load-data
"Creates `entries` by adding dataset name and version to the specified
table-key-value pairs and loads them into the kv-store. Validates the
dataset and table names supplied and throws an exception when the validation
fails. See `create-entries` for information reg ex-data passed in the
exception. Returns :ok if the load was successful."
[{:keys [kv-store meta-store]} version-id dsname tbl-key-vals]
- conjoin { : dataset dsname : version version - id } to in - key - vals
(let [entries (->> tbl-key-vals
(map #(conj {:dataset dsname :version version-id} %))
(mapcat entry->kv)
(apply hash-map))
[valid? errors] (validate-entries meta-store (keys entries))]
(if-not valid?
(throw-missing-entity "Table(s) not found"
(conj {:error :tables-not-found} errors)))
(b/put-many kv-store entries)
:ok))
(defn create-entries
"Loads data for the specified version. Throws an exception in the following
cases with the given message and ex-data with 2 keys :error and additional
information containing context related to the error.
| Condition | :error | :addl-info |
|--------------------------+------------------------------+--------------------|
| Version: | | |
| - not found | :version-not-found | nil |
| - does not match dataset | :invalid-version-for-dataset | {:version} |
| - invalid state | :invalid-version-state | {:version} |
| | | |
| Data | :invalid-request | {:missing-tables} |
| | | |
Returns :ok on success."
([{:keys [meta-store kv-store] :as bknd-store} version-id dsname tbl-key-vals]
(track-time
(metrics-name :core :create-entries)
(let [{:keys [dataset status] :as version} (b/get-version meta-store version-id)]
(cond
(nil? version) (throw-missing-entity "version not found"
{:error :version-not-found})
(not= dataset dsname) (throw-validation-error
"version does not match dataset"
{:error :invalid-version-for-dataset
:version version})
(not= status :awaiting-entries) (throw-validation-error
"invalid version state"
{:error :invalid-version-state
:version version})
:else (load-data bknd-store version-id dsname tbl-key-vals)))))
([bknd-store version-id dsname table-name key-vals]
(track-time
(metrics-name :core :create-entries table-name)
(->> key-vals
(map #(conj {:table table-name :version version-id} %))
(create-entries bknd-store version-id dsname))))
([{:keys [meta-store] :as bknd-store} version-id dsname table-name key value]
Validate if dataset is present .
(track-time
(metrics-name :core :create-entry)
(create-entries bknd-store version-id dsname
[{:table table-name :key key :value value}]))))
(defn get-active-version*
"Returns the active version of the dataset"
[bknd dataset-name]
(let [{:keys [active-version] :as dataset} (get-dataset bknd dataset-name)]
(cond
(nil? dataset) (throw-missing-entity "dataset does not exist" {})
(nil? active-version) (throw-validation-error "no active version for dataset" {})
:else active-version)))
(def get-active-version
"Returns the active version of the dataset. This function calls the
get-active-version* function and caches the output for 10
seconds."
(ttl
(fn [bknd dataset-name] (get-active-version* bknd dataset-name))
:ttl/threshold 10000))
(defn get-entry
"Return a single entry from the keyvalue store for the specified
version-id dataset table key combination. Returns a map that contains
the following keys::
:active-version-id - version currently active for the dataset requested.
:version-id - version of the data returned
:data - value for the requested key"
[{:keys [kv-store] :as bknd} version-id dataset table key]
(track-time
(metrics-name :core :get-entry)
(let [active-version (get-active-version bknd dataset)
version-id (if version-id version-id active-version)]
(->> {:dataset dataset :version version-id :table table :key key}
(b/get-one kv-store)
(assoc {:active-version-id active-version
:version-id version-id}
:data)))))
(defn get-entries
"Returns entries from the key value store for the specified
version-id dataset table and keys.Returns a map that contains
the following keys::
:active-version-id - version currently active for the dataset requested.
:version-id - version of the data returned
:data - values for the requested keys"
([{:keys [kv-store] :as bknd} version-id dataset table keys]
(track-time
(metrics-name :core :get-entries)
(let [active-version (get-active-version bknd dataset)
version-id (if version-id version-id active-version)]
(->> keys
(map #(conj {:dataset dataset :table table :version version-id} %))
(b/get-many kv-store)
(assoc {:active-version-id active-version
:version-id version-id} :data))))))
|
c7afa4ffed326458b29c37c20bbe84602f0e5d3c687d145deaa7556a6065a709 | ollef/sixty | OrderedHashSet.hs | # LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE TupleSections #
module Data.OrderedHashSet where
import Data.OrderedHashMap (OrderedHashMap)
import qualified Data.OrderedHashMap as OrderedHashMap
import Data.Persist
import Protolude hiding (toList)
import Prelude (Show (showsPrec), showParen, showString, shows)
newtype OrderedHashSet a = OrderedHashSet (OrderedHashMap a ())
deriving (Eq, Ord, Hashable, Persist)
instance Show a => Show (OrderedHashSet a) where
showsPrec p xs =
showParen (p > 10) $
showString "fromList " . shows (toList xs)
instance Foldable OrderedHashSet where
foldMap f =
foldMap f . toList
null :: OrderedHashSet a -> Bool
null (OrderedHashSet s) =
OrderedHashMap.null s
size :: OrderedHashSet a -> Int
size (OrderedHashSet s) =
OrderedHashMap.size s
member :: (Hashable a) => a -> OrderedHashSet a -> Bool
member a (OrderedHashSet s) =
isJust $ OrderedHashMap.lookup a s
toList :: OrderedHashSet a -> [a]
toList (OrderedHashSet s) =
fst <$> OrderedHashMap.toList s
fromList :: (Hashable a) => [a] -> OrderedHashSet a
fromList as =
OrderedHashSet $ OrderedHashMap.fromList $ (,()) <$> as
| null | https://raw.githubusercontent.com/ollef/sixty/2582551f3c12f84489afb961b800f0d7cfa74844/src/Data/OrderedHashSet.hs | haskell | # LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE TupleSections #
module Data.OrderedHashSet where
import Data.OrderedHashMap (OrderedHashMap)
import qualified Data.OrderedHashMap as OrderedHashMap
import Data.Persist
import Protolude hiding (toList)
import Prelude (Show (showsPrec), showParen, showString, shows)
newtype OrderedHashSet a = OrderedHashSet (OrderedHashMap a ())
deriving (Eq, Ord, Hashable, Persist)
instance Show a => Show (OrderedHashSet a) where
showsPrec p xs =
showParen (p > 10) $
showString "fromList " . shows (toList xs)
instance Foldable OrderedHashSet where
foldMap f =
foldMap f . toList
null :: OrderedHashSet a -> Bool
null (OrderedHashSet s) =
OrderedHashMap.null s
size :: OrderedHashSet a -> Int
size (OrderedHashSet s) =
OrderedHashMap.size s
member :: (Hashable a) => a -> OrderedHashSet a -> Bool
member a (OrderedHashSet s) =
isJust $ OrderedHashMap.lookup a s
toList :: OrderedHashSet a -> [a]
toList (OrderedHashSet s) =
fst <$> OrderedHashMap.toList s
fromList :: (Hashable a) => [a] -> OrderedHashSet a
fromList as =
OrderedHashSet $ OrderedHashMap.fromList $ (,()) <$> as
| |
145e97ddad863965c10ba8f9be40a44fdb460514aecc814503c20746fa2abb64 | ghc/packages-Cabal | Modular.hs | # LANGUAGE LambdaCase #
# LANGUAGE ScopedTypeVariables #
module Distribution.Solver.Modular
( modularResolver, SolverConfig(..), PruneAfterFirstSuccess(..) ) where
-- Here, we try to map between the external cabal-install solver
-- interface and the internal interface that the solver actually
-- expects. There are a number of type conversions to perform: we
-- have to convert the package indices to the uniform index used
-- by the solver; we also have to convert the initial constraints;
-- and finally, we have to convert back the resulting install
-- plan.
import Prelude ()
import Distribution.Solver.Compat.Prelude
import qualified Data.Map as M
import Data.Set (isSubsetOf)
import Distribution.Compat.Graph
( IsNode(..) )
import Distribution.Compiler
( CompilerInfo )
import Distribution.Solver.Modular.Assignment
( Assignment, toCPs )
import Distribution.Solver.Modular.ConfiguredConversion
( convCP )
import qualified Distribution.Solver.Modular.ConflictSet as CS
import Distribution.Solver.Modular.Dependency
import Distribution.Solver.Modular.Flag
import Distribution.Solver.Modular.Index
import Distribution.Solver.Modular.IndexConversion
( convPIs )
import Distribution.Solver.Modular.Log
( SolverFailure(..), displayLogMessages )
import Distribution.Solver.Modular.Package
( PN )
import Distribution.Solver.Modular.RetryLog
import Distribution.Solver.Modular.Solver
( SolverConfig(..), PruneAfterFirstSuccess(..), solve )
import Distribution.Solver.Types.DependencyResolver
import Distribution.Solver.Types.LabeledPackageConstraint
import Distribution.Solver.Types.PackageConstraint
import Distribution.Solver.Types.PackagePath
import Distribution.Solver.Types.PackagePreferences
import Distribution.Solver.Types.PkgConfigDb
( PkgConfigDb )
import Distribution.Solver.Types.Progress
import Distribution.Solver.Types.Variable
import Distribution.System
( Platform(..) )
import Distribution.Simple.Setup
( BooleanFlag(..) )
import Distribution.Simple.Utils
( ordNubBy )
import Distribution.Verbosity
| Ties the two worlds together : classic cabal - install vs. the modular
-- solver. Performs the necessary translations before and after.
modularResolver :: SolverConfig -> DependencyResolver loc
modularResolver sc (Platform arch os) cinfo iidx sidx pkgConfigDB pprefs pcs pns =
fmap (uncurry postprocess) $ -- convert install plan
solve' sc cinfo idx pkgConfigDB pprefs gcs pns
where
-- Indices have to be converted into solver-specific uniform index.
idx = convPIs os arch cinfo gcs (shadowPkgs sc) (strongFlags sc) (solveExecutables sc) iidx sidx
Constraints have to be converted into a finite map indexed by PN .
gcs = M.fromListWith (++) (map pair pcs)
where
pair lpc = (pcName $ unlabelPackageConstraint lpc, [lpc])
-- Results have to be converted into an install plan. 'convCP' removes
-- package qualifiers, which means that linked packages become duplicates
-- and can be removed.
postprocess a rdm = ordNubBy nodeKey $
map (convCP iidx sidx) (toCPs a rdm)
Helper function to extract the PN from a constraint .
pcName :: PackageConstraint -> PN
pcName (PackageConstraint scope _) = scopeToPackageName scope
-- | Run 'D.S.Modular.Solver.solve' and then produce a summarized log to display
-- in the error case.
--
-- When there is no solution, we produce the error message by rerunning the
-- solver but making it prefer the goals from the final conflict set from the
first run ( or a subset of the final conflict set with
-- --minimize-conflict-set). We also set the backjump limit to 0, so that the
log stops at the first backjump and is relatively short . Preferring goals
-- from the final conflict set increases the probability that the log to the
-- first backjump contains package, flag, and stanza choices that are relevant
-- to the final failure. The solver shouldn't need to choose any packages that
-- aren't in the final conflict set. (For every variable in the final conflict
-- set, the final conflict set should also contain the variable that introduced
-- that variable. The solver can then follow that chain of variables in reverse
-- order from the user target to the conflict.) However, it is possible that the
-- conflict set contains unnecessary variables.
--
-- Producing an error message when the solver reaches the backjump limit is more
-- complicated. There is no final conflict set, so we create one for the minimal
subtree containing the path that the solver took to the first backjump . This
-- conflict set helps explain why the solver reached the backjump limit, because
the first backjump contributes to reaching the backjump limit . Additionally ,
-- the solver is much more likely to be able to finish traversing this subtree
-- before the backjump limit, since its size is linear (not exponential) in the
number of goal choices . We create it by pruning all children after the first
-- successful child under each node in the original tree, so that there is at
-- most one valid choice at each level. Then we use the final conflict set from
-- that run to generate an error message, as in the case where the solver found
-- that there was no solution.
--
-- Using the full log from a rerun of the solver ensures that the log is
-- complete, i.e., it shows the whole chain of dependencies from the user
-- targets to the conflicting packages.
solve' :: SolverConfig
-> CompilerInfo
-> Index
-> PkgConfigDb
-> (PN -> PackagePreferences)
-> Map PN [LabeledPackageConstraint]
-> Set PN
-> Progress String String (Assignment, RevDepMap)
solve' sc cinfo idx pkgConfigDB pprefs gcs pns =
toProgress $ retry (runSolver printFullLog sc) createErrorMsg
where
runSolver :: Bool -> SolverConfig
-> RetryLog String SolverFailure (Assignment, RevDepMap)
runSolver keepLog sc' =
displayLogMessages keepLog $
solve sc' cinfo idx pkgConfigDB pprefs gcs pns
createErrorMsg :: SolverFailure
-> RetryLog String String (Assignment, RevDepMap)
createErrorMsg failure@(ExhaustiveSearch cs cm) =
if asBool $ minimizeConflictSet sc
then continueWith ("Found no solution after exhaustively searching the "
++ "dependency tree. Rerunning the dependency solver "
++ "to minimize the conflict set ({"
++ showConflictSet cs ++ "}).") $
retry (tryToMinimizeConflictSet (runSolver printFullLog) sc cs cm) $
\case
ExhaustiveSearch cs' cm' ->
fromProgress $ Fail $
rerunSolverForErrorMsg cs'
++ finalErrorMsg sc (ExhaustiveSearch cs' cm')
BackjumpLimitReached ->
fromProgress $ Fail $
"Reached backjump limit while trying to minimize the "
++ "conflict set to create a better error message. "
++ "Original error message:\n"
++ rerunSolverForErrorMsg cs
++ finalErrorMsg sc failure
else fromProgress $ Fail $
rerunSolverForErrorMsg cs ++ finalErrorMsg sc failure
createErrorMsg failure@BackjumpLimitReached =
continueWith
("Backjump limit reached. Rerunning dependency solver to generate "
++ "a final conflict set for the search tree containing the "
++ "first backjump.") $
retry (runSolver printFullLog sc { pruneAfterFirstSuccess = PruneAfterFirstSuccess True }) $
\case
ExhaustiveSearch cs _ ->
fromProgress $ Fail $
rerunSolverForErrorMsg cs ++ finalErrorMsg sc failure
BackjumpLimitReached ->
-- This case is possible when the number of goals involved in
-- conflicts is greater than the backjump limit.
fromProgress $ Fail $ finalErrorMsg sc failure
++ "Failed to generate a summarized dependency solver "
++ "log due to low backjump limit."
rerunSolverForErrorMsg :: ConflictSet -> String
rerunSolverForErrorMsg cs =
let sc' = sc {
goalOrder = Just goalOrder'
, maxBackjumps = Just 0
}
Preferring goals from the conflict set takes precedence over the
-- original goal order.
goalOrder' = preferGoalsFromConflictSet cs <> fromMaybe mempty (goalOrder sc)
in unlines ("Could not resolve dependencies:" : messages (toProgress (runSolver True sc')))
printFullLog = solverVerbosity sc >= verbose
messages :: Progress step fail done -> [step]
messages = foldProgress (:) (const []) (const [])
-- | Try to remove variables from the given conflict set to create a minimal
-- conflict set.
--
-- Minimal means that no proper subset of the conflict set is also a conflict
-- set, though there may be other possible conflict sets with fewer variables.
This function minimizes the input by trying to remove one variable at a time .
It only makes one pass over the variables , so it runs the solver at most N
times when given a conflict set of size N. Only one pass is necessary ,
-- because every superset of a conflict set is also a conflict set, meaning that
failing to remove variable X from a conflict set in one step means that X
-- cannot be removed from any subset of that conflict set in a subsequent step.
--
-- Example steps:
--
-- Start with {A, B, C}.
-- Try to remove A from {A, B, C} and fail.
-- Try to remove B from {A, B, C} and succeed.
-- Try to remove C from {A, C} and fail.
-- Return {A, C}
--
This function can fail for two reasons :
--
1 . The solver can reach the backjump limit on any run . In this case the
returned RetryLog ends with BackjumpLimitReached .
TODO : Consider applying the backjump limit to all solver runs combined ,
instead of each individual run . For example , 10 runs with 10 backjumps
each should count as 100 backjumps .
2 . Since this function works by rerunning the solver , it is possible for the
-- solver to add new unnecessary variables to the conflict set. This function
-- discards the result from any run that adds new variables to the conflict
-- set, but the end result may not be completely minimized.
tryToMinimizeConflictSet :: forall a . (SolverConfig -> RetryLog String SolverFailure a)
-> SolverConfig
-> ConflictSet
-> ConflictMap
-> RetryLog String SolverFailure a
tryToMinimizeConflictSet runSolver sc cs cm =
foldl (\r v -> retryNoSolution r $ tryToRemoveOneVar v)
(fromProgress $ Fail $ ExhaustiveSearch cs cm)
(CS.toList cs)
where
-- This function runs the solver and makes it prefer goals in the following
-- order:
--
1 . variables in ' smallestKnownCS ' , excluding ' v '
2 . ' v '
3 . all other variables
--
-- If 'v' is not necessary, then the solver will find that there is no
-- solution before starting to solve for 'v', and the new final conflict set
-- will be very likely to not contain 'v'. If 'v' is necessary, the solver
-- will most likely need to try solving for 'v' before finding that there is
-- no solution, and the new final conflict set will still contain 'v'.
-- However, this method isn't perfect, because it is possible for the solver
-- to add new unnecessary variables to the conflict set on any run. This
-- function prevents the conflict set from growing by checking that the new
-- conflict set is a subset of the old one and falling back to using the old
-- conflict set when that check fails.
tryToRemoveOneVar :: Var QPN
-> ConflictSet
-> ConflictMap
-> RetryLog String SolverFailure a
tryToRemoveOneVar v smallestKnownCS smallestKnownCM
-- Check whether v is still present, because it may have already been
-- removed in a previous solver rerun.
| not (v `CS.member` smallestKnownCS) =
fromProgress $ Fail $ ExhaustiveSearch smallestKnownCS smallestKnownCM
| otherwise =
continueWith ("Trying to remove variable " ++ varStr ++ " from the "
++ "conflict set.") $
retry (runSolver sc') $ \case
err@(ExhaustiveSearch cs' _)
| CS.toSet cs' `isSubsetOf` CS.toSet smallestKnownCS ->
let msg = if not $ CS.member v cs'
then "Successfully removed " ++ varStr ++ " from "
++ "the conflict set."
else "Failed to remove " ++ varStr ++ " from the "
++ "conflict set."
in -- Use the new conflict set, even if v wasn't removed,
-- because other variables may have been removed.
failWith (msg ++ " Continuing with " ++ showCS cs' ++ ".") err
| otherwise ->
failWith ("Failed to find a smaller conflict set. The new "
++ "conflict set is not a subset of the previous "
++ "conflict set: " ++ showCS cs') $
ExhaustiveSearch smallestKnownCS smallestKnownCM
BackjumpLimitReached ->
failWith ("Reached backjump limit while minimizing conflict set.")
BackjumpLimitReached
where
varStr = "\"" ++ showVar v ++ "\""
showCS cs' = "{" ++ showConflictSet cs' ++ "}"
sc' = sc { goalOrder = Just goalOrder' }
goalOrder' =
preferGoalsFromConflictSet (v `CS.delete` smallestKnownCS)
<> preferGoal v
<> fromMaybe mempty (goalOrder sc)
-- Like 'retry', except that it only applies the input function when the
-- backjump limit has not been reached.
retryNoSolution :: RetryLog step SolverFailure done
-> (ConflictSet -> ConflictMap -> RetryLog step SolverFailure done)
-> RetryLog step SolverFailure done
retryNoSolution lg f = retry lg $ \case
ExhaustiveSearch cs' cm' -> f cs' cm'
BackjumpLimitReached -> fromProgress (Fail BackjumpLimitReached)
-- | Goal ordering that chooses goals contained in the conflict set before
-- other goals.
preferGoalsFromConflictSet :: ConflictSet
-> Variable QPN -> Variable QPN -> Ordering
preferGoalsFromConflictSet cs = comparing $ \v -> not $ CS.member (toVar v) cs
| Goal ordering that chooses the given goal first .
preferGoal :: Var QPN -> Variable QPN -> Variable QPN -> Ordering
preferGoal preferred = comparing $ \v -> toVar v /= preferred
toVar :: Variable QPN -> Var QPN
toVar (PackageVar qpn) = P qpn
toVar (FlagVar qpn fn) = F (FN qpn fn)
toVar (StanzaVar qpn sn) = S (SN qpn sn)
finalErrorMsg :: SolverConfig -> SolverFailure -> String
finalErrorMsg sc failure =
case failure of
ExhaustiveSearch cs cm ->
"After searching the rest of the dependency tree exhaustively, "
++ "these were the goals I've had most trouble fulfilling: "
++ showCS cm cs
++ flagSuggestion
where
showCS = if solverVerbosity sc > normal
then CS.showCSWithFrequency
else CS.showCSSortedByFrequency
flagSuggestion =
-- Don't suggest --minimize-conflict-set if the conflict set is
-- already small, because it is unlikely to be reduced further.
if CS.size cs > 3 && not (asBool (minimizeConflictSet sc))
then "\nTry running with --minimize-conflict-set to improve the "
++ "error message."
else ""
BackjumpLimitReached ->
"Backjump limit reached (" ++ currlimit (maxBackjumps sc) ++
"change with --max-backjumps or try to run with --reorder-goals).\n"
where currlimit (Just n) = "currently " ++ show n ++ ", "
currlimit Nothing = ""
| null | https://raw.githubusercontent.com/ghc/packages-Cabal/6f22f2a789fa23edb210a2591d74ea6a5f767872/cabal-install/Distribution/Solver/Modular.hs | haskell | Here, we try to map between the external cabal-install solver
interface and the internal interface that the solver actually
expects. There are a number of type conversions to perform: we
have to convert the package indices to the uniform index used
by the solver; we also have to convert the initial constraints;
and finally, we have to convert back the resulting install
plan.
solver. Performs the necessary translations before and after.
convert install plan
Indices have to be converted into solver-specific uniform index.
Results have to be converted into an install plan. 'convCP' removes
package qualifiers, which means that linked packages become duplicates
and can be removed.
| Run 'D.S.Modular.Solver.solve' and then produce a summarized log to display
in the error case.
When there is no solution, we produce the error message by rerunning the
solver but making it prefer the goals from the final conflict set from the
--minimize-conflict-set). We also set the backjump limit to 0, so that the
from the final conflict set increases the probability that the log to the
first backjump contains package, flag, and stanza choices that are relevant
to the final failure. The solver shouldn't need to choose any packages that
aren't in the final conflict set. (For every variable in the final conflict
set, the final conflict set should also contain the variable that introduced
that variable. The solver can then follow that chain of variables in reverse
order from the user target to the conflict.) However, it is possible that the
conflict set contains unnecessary variables.
Producing an error message when the solver reaches the backjump limit is more
complicated. There is no final conflict set, so we create one for the minimal
conflict set helps explain why the solver reached the backjump limit, because
the solver is much more likely to be able to finish traversing this subtree
before the backjump limit, since its size is linear (not exponential) in the
successful child under each node in the original tree, so that there is at
most one valid choice at each level. Then we use the final conflict set from
that run to generate an error message, as in the case where the solver found
that there was no solution.
Using the full log from a rerun of the solver ensures that the log is
complete, i.e., it shows the whole chain of dependencies from the user
targets to the conflicting packages.
This case is possible when the number of goals involved in
conflicts is greater than the backjump limit.
original goal order.
| Try to remove variables from the given conflict set to create a minimal
conflict set.
Minimal means that no proper subset of the conflict set is also a conflict
set, though there may be other possible conflict sets with fewer variables.
because every superset of a conflict set is also a conflict set, meaning that
cannot be removed from any subset of that conflict set in a subsequent step.
Example steps:
Start with {A, B, C}.
Try to remove A from {A, B, C} and fail.
Try to remove B from {A, B, C} and succeed.
Try to remove C from {A, C} and fail.
Return {A, C}
solver to add new unnecessary variables to the conflict set. This function
discards the result from any run that adds new variables to the conflict
set, but the end result may not be completely minimized.
This function runs the solver and makes it prefer goals in the following
order:
If 'v' is not necessary, then the solver will find that there is no
solution before starting to solve for 'v', and the new final conflict set
will be very likely to not contain 'v'. If 'v' is necessary, the solver
will most likely need to try solving for 'v' before finding that there is
no solution, and the new final conflict set will still contain 'v'.
However, this method isn't perfect, because it is possible for the solver
to add new unnecessary variables to the conflict set on any run. This
function prevents the conflict set from growing by checking that the new
conflict set is a subset of the old one and falling back to using the old
conflict set when that check fails.
Check whether v is still present, because it may have already been
removed in a previous solver rerun.
Use the new conflict set, even if v wasn't removed,
because other variables may have been removed.
Like 'retry', except that it only applies the input function when the
backjump limit has not been reached.
| Goal ordering that chooses goals contained in the conflict set before
other goals.
Don't suggest --minimize-conflict-set if the conflict set is
already small, because it is unlikely to be reduced further. | # LANGUAGE LambdaCase #
# LANGUAGE ScopedTypeVariables #
module Distribution.Solver.Modular
( modularResolver, SolverConfig(..), PruneAfterFirstSuccess(..) ) where
import Prelude ()
import Distribution.Solver.Compat.Prelude
import qualified Data.Map as M
import Data.Set (isSubsetOf)
import Distribution.Compat.Graph
( IsNode(..) )
import Distribution.Compiler
( CompilerInfo )
import Distribution.Solver.Modular.Assignment
( Assignment, toCPs )
import Distribution.Solver.Modular.ConfiguredConversion
( convCP )
import qualified Distribution.Solver.Modular.ConflictSet as CS
import Distribution.Solver.Modular.Dependency
import Distribution.Solver.Modular.Flag
import Distribution.Solver.Modular.Index
import Distribution.Solver.Modular.IndexConversion
( convPIs )
import Distribution.Solver.Modular.Log
( SolverFailure(..), displayLogMessages )
import Distribution.Solver.Modular.Package
( PN )
import Distribution.Solver.Modular.RetryLog
import Distribution.Solver.Modular.Solver
( SolverConfig(..), PruneAfterFirstSuccess(..), solve )
import Distribution.Solver.Types.DependencyResolver
import Distribution.Solver.Types.LabeledPackageConstraint
import Distribution.Solver.Types.PackageConstraint
import Distribution.Solver.Types.PackagePath
import Distribution.Solver.Types.PackagePreferences
import Distribution.Solver.Types.PkgConfigDb
( PkgConfigDb )
import Distribution.Solver.Types.Progress
import Distribution.Solver.Types.Variable
import Distribution.System
( Platform(..) )
import Distribution.Simple.Setup
( BooleanFlag(..) )
import Distribution.Simple.Utils
( ordNubBy )
import Distribution.Verbosity
| Ties the two worlds together : classic cabal - install vs. the modular
modularResolver :: SolverConfig -> DependencyResolver loc
modularResolver sc (Platform arch os) cinfo iidx sidx pkgConfigDB pprefs pcs pns =
solve' sc cinfo idx pkgConfigDB pprefs gcs pns
where
idx = convPIs os arch cinfo gcs (shadowPkgs sc) (strongFlags sc) (solveExecutables sc) iidx sidx
Constraints have to be converted into a finite map indexed by PN .
gcs = M.fromListWith (++) (map pair pcs)
where
pair lpc = (pcName $ unlabelPackageConstraint lpc, [lpc])
postprocess a rdm = ordNubBy nodeKey $
map (convCP iidx sidx) (toCPs a rdm)
Helper function to extract the PN from a constraint .
pcName :: PackageConstraint -> PN
pcName (PackageConstraint scope _) = scopeToPackageName scope
first run ( or a subset of the final conflict set with
log stops at the first backjump and is relatively short . Preferring goals
subtree containing the path that the solver took to the first backjump . This
the first backjump contributes to reaching the backjump limit . Additionally ,
number of goal choices . We create it by pruning all children after the first
solve' :: SolverConfig
-> CompilerInfo
-> Index
-> PkgConfigDb
-> (PN -> PackagePreferences)
-> Map PN [LabeledPackageConstraint]
-> Set PN
-> Progress String String (Assignment, RevDepMap)
solve' sc cinfo idx pkgConfigDB pprefs gcs pns =
toProgress $ retry (runSolver printFullLog sc) createErrorMsg
where
runSolver :: Bool -> SolverConfig
-> RetryLog String SolverFailure (Assignment, RevDepMap)
runSolver keepLog sc' =
displayLogMessages keepLog $
solve sc' cinfo idx pkgConfigDB pprefs gcs pns
createErrorMsg :: SolverFailure
-> RetryLog String String (Assignment, RevDepMap)
createErrorMsg failure@(ExhaustiveSearch cs cm) =
if asBool $ minimizeConflictSet sc
then continueWith ("Found no solution after exhaustively searching the "
++ "dependency tree. Rerunning the dependency solver "
++ "to minimize the conflict set ({"
++ showConflictSet cs ++ "}).") $
retry (tryToMinimizeConflictSet (runSolver printFullLog) sc cs cm) $
\case
ExhaustiveSearch cs' cm' ->
fromProgress $ Fail $
rerunSolverForErrorMsg cs'
++ finalErrorMsg sc (ExhaustiveSearch cs' cm')
BackjumpLimitReached ->
fromProgress $ Fail $
"Reached backjump limit while trying to minimize the "
++ "conflict set to create a better error message. "
++ "Original error message:\n"
++ rerunSolverForErrorMsg cs
++ finalErrorMsg sc failure
else fromProgress $ Fail $
rerunSolverForErrorMsg cs ++ finalErrorMsg sc failure
createErrorMsg failure@BackjumpLimitReached =
continueWith
("Backjump limit reached. Rerunning dependency solver to generate "
++ "a final conflict set for the search tree containing the "
++ "first backjump.") $
retry (runSolver printFullLog sc { pruneAfterFirstSuccess = PruneAfterFirstSuccess True }) $
\case
ExhaustiveSearch cs _ ->
fromProgress $ Fail $
rerunSolverForErrorMsg cs ++ finalErrorMsg sc failure
BackjumpLimitReached ->
fromProgress $ Fail $ finalErrorMsg sc failure
++ "Failed to generate a summarized dependency solver "
++ "log due to low backjump limit."
rerunSolverForErrorMsg :: ConflictSet -> String
rerunSolverForErrorMsg cs =
let sc' = sc {
goalOrder = Just goalOrder'
, maxBackjumps = Just 0
}
Preferring goals from the conflict set takes precedence over the
goalOrder' = preferGoalsFromConflictSet cs <> fromMaybe mempty (goalOrder sc)
in unlines ("Could not resolve dependencies:" : messages (toProgress (runSolver True sc')))
printFullLog = solverVerbosity sc >= verbose
messages :: Progress step fail done -> [step]
messages = foldProgress (:) (const []) (const [])
This function minimizes the input by trying to remove one variable at a time .
It only makes one pass over the variables , so it runs the solver at most N
times when given a conflict set of size N. Only one pass is necessary ,
failing to remove variable X from a conflict set in one step means that X
This function can fail for two reasons :
1 . The solver can reach the backjump limit on any run . In this case the
returned RetryLog ends with BackjumpLimitReached .
TODO : Consider applying the backjump limit to all solver runs combined ,
instead of each individual run . For example , 10 runs with 10 backjumps
each should count as 100 backjumps .
2 . Since this function works by rerunning the solver , it is possible for the
tryToMinimizeConflictSet :: forall a . (SolverConfig -> RetryLog String SolverFailure a)
-> SolverConfig
-> ConflictSet
-> ConflictMap
-> RetryLog String SolverFailure a
tryToMinimizeConflictSet runSolver sc cs cm =
foldl (\r v -> retryNoSolution r $ tryToRemoveOneVar v)
(fromProgress $ Fail $ ExhaustiveSearch cs cm)
(CS.toList cs)
where
1 . variables in ' smallestKnownCS ' , excluding ' v '
2 . ' v '
3 . all other variables
tryToRemoveOneVar :: Var QPN
-> ConflictSet
-> ConflictMap
-> RetryLog String SolverFailure a
tryToRemoveOneVar v smallestKnownCS smallestKnownCM
| not (v `CS.member` smallestKnownCS) =
fromProgress $ Fail $ ExhaustiveSearch smallestKnownCS smallestKnownCM
| otherwise =
continueWith ("Trying to remove variable " ++ varStr ++ " from the "
++ "conflict set.") $
retry (runSolver sc') $ \case
err@(ExhaustiveSearch cs' _)
| CS.toSet cs' `isSubsetOf` CS.toSet smallestKnownCS ->
let msg = if not $ CS.member v cs'
then "Successfully removed " ++ varStr ++ " from "
++ "the conflict set."
else "Failed to remove " ++ varStr ++ " from the "
++ "conflict set."
failWith (msg ++ " Continuing with " ++ showCS cs' ++ ".") err
| otherwise ->
failWith ("Failed to find a smaller conflict set. The new "
++ "conflict set is not a subset of the previous "
++ "conflict set: " ++ showCS cs') $
ExhaustiveSearch smallestKnownCS smallestKnownCM
BackjumpLimitReached ->
failWith ("Reached backjump limit while minimizing conflict set.")
BackjumpLimitReached
where
varStr = "\"" ++ showVar v ++ "\""
showCS cs' = "{" ++ showConflictSet cs' ++ "}"
sc' = sc { goalOrder = Just goalOrder' }
goalOrder' =
preferGoalsFromConflictSet (v `CS.delete` smallestKnownCS)
<> preferGoal v
<> fromMaybe mempty (goalOrder sc)
retryNoSolution :: RetryLog step SolverFailure done
-> (ConflictSet -> ConflictMap -> RetryLog step SolverFailure done)
-> RetryLog step SolverFailure done
retryNoSolution lg f = retry lg $ \case
ExhaustiveSearch cs' cm' -> f cs' cm'
BackjumpLimitReached -> fromProgress (Fail BackjumpLimitReached)
preferGoalsFromConflictSet :: ConflictSet
-> Variable QPN -> Variable QPN -> Ordering
preferGoalsFromConflictSet cs = comparing $ \v -> not $ CS.member (toVar v) cs
| Goal ordering that chooses the given goal first .
preferGoal :: Var QPN -> Variable QPN -> Variable QPN -> Ordering
preferGoal preferred = comparing $ \v -> toVar v /= preferred
toVar :: Variable QPN -> Var QPN
toVar (PackageVar qpn) = P qpn
toVar (FlagVar qpn fn) = F (FN qpn fn)
toVar (StanzaVar qpn sn) = S (SN qpn sn)
finalErrorMsg :: SolverConfig -> SolverFailure -> String
finalErrorMsg sc failure =
case failure of
ExhaustiveSearch cs cm ->
"After searching the rest of the dependency tree exhaustively, "
++ "these were the goals I've had most trouble fulfilling: "
++ showCS cm cs
++ flagSuggestion
where
showCS = if solverVerbosity sc > normal
then CS.showCSWithFrequency
else CS.showCSSortedByFrequency
flagSuggestion =
if CS.size cs > 3 && not (asBool (minimizeConflictSet sc))
then "\nTry running with --minimize-conflict-set to improve the "
++ "error message."
else ""
BackjumpLimitReached ->
"Backjump limit reached (" ++ currlimit (maxBackjumps sc) ++
"change with --max-backjumps or try to run with --reorder-goals).\n"
where currlimit (Just n) = "currently " ++ show n ++ ", "
currlimit Nothing = ""
|
40108fa9e92f3960ed94f9d502ce1868f374edd456f974e2b7fd51c402611a81 | i-am-tom/dagless | HList.hs | # LANGUAGE AllowAmbiguousTypes #
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE GADTs #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE KindSignatures #
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
# LANGUAGE TypeApplications #
{-# LANGUAGE TypeOperators #-}
|
Module : Data . HList
Description : A nice , neat HList .
Copyright : ( c ) , 2018
License : MIT
Maintainer :
Stability : experimental
This module defines a heterogeneous list type . Any types can be stored in the
list , and the type itself is indexed by the types contained within . This module
also defines functions for extracting values /and/ folding an HList in which
all inhabitant types implement some constraint .
Module : Data.HList
Description : A nice, neat HList.
Copyright : (c) Tom Harding, 2018
License : MIT
Maintainer :
Stability : experimental
This module defines a heterogeneous list type. Any types can be stored in the
list, and the type itself is indexed by the types contained within. This module
also defines functions for extracting values /and/ folding an HList in which
all inhabitant types implement some constraint.
-}
module Data.HList where
import Data.Kind (Constraint, Type)
import Prelude hiding (foldMap)
-- | A heterogeneous list, indexed by the types that it contains. We define the
' :> ' notation for @Cons@ , which hopefully makes uses a bit neater .
data HList (xs :: [Type]) where
HNil :: HList '[ ]
(:>) :: x -> HList xs -> HList (x ': xs)
infixr 3 :>
| Pluck a type from an HList . The constraint ensures that the type exists
-- within the list, and thus it is a total function.
--
-- >>> :set -XTypeApplications
> > > let example = True :> 3 :> " hello " :> HNil
--
-- >>> pluck @Bool example
-- True
--
-- >>> pluck @String example
-- "hello"
--
-- >>> pluck @(()) example
-- ...
-- ... No instance for (PluckedFrom ...)
-- ...
class (x :: Type) `PluckedFrom` (xs :: [Type]) where
pluck :: HList xs -> x
instance x `PluckedFrom` (x ': xs) where
pluck (head :> _) = head
instance {-# OVERLAPPABLE #-} x `PluckedFrom` xs
=> x `PluckedFrom` (y ': xs) where
pluck (_ :> tail) = pluck tail
| Fold an HList . Assuming all the elements of the list satisfy some
-- constraint, we should be able to "fold" over the list according to some
-- monoid value produced using that constraint.
--
> > > let example = True :> 3 :> " hello " :> HNil
-- >>> foldMap @Show (pure @[] . show) example
[ " True","3","\"hello\ " " ]
--
We can also fold over a homogeneous HList using an equality constraint ,
-- allowing us to recover the traditional list folds:
--
> > > import Data . Monoid
> > > foldMap ) Int ) Sum ( 3 :> 2 :> 1 :> HNil )
Sum { getSum = 6 }
--
-- Finally, we can use 'Data.Coerce.coerce' for some truly interesting
-- operations:
--
> > > import Data . Coerce
> > > let example = Any False :> False :> All True :> HNil
> > > foldMap @(Coercible Any ) ( coerce @ _ ) example
Any { getAny = True }
class (c :: Type -> Constraint) `Folds` (xs :: [Type]) where
foldMap :: Monoid m => (forall x. c x => x -> m) -> HList xs -> m
instance anything `Folds` '[] where
foldMap _ HNil = mempty
instance (c x, c `Folds` xs) => c `Folds` (x ': xs) where
foldMap f (x :> xs) = f x <> foldMap @c f xs
| null | https://raw.githubusercontent.com/i-am-tom/dagless/783dc720eceb89416c7452c95c675b66124473e4/src/Data/HList.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE DataKinds #
# LANGUAGE RankNTypes #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeOperators #
| A heterogeneous list, indexed by the types that it contains. We define the
within the list, and thus it is a total function.
>>> :set -XTypeApplications
>>> pluck @Bool example
True
>>> pluck @String example
"hello"
>>> pluck @(()) example
...
... No instance for (PluckedFrom ...)
...
# OVERLAPPABLE #
constraint, we should be able to "fold" over the list according to some
monoid value produced using that constraint.
>>> foldMap @Show (pure @[] . show) example
allowing us to recover the traditional list folds:
Finally, we can use 'Data.Coerce.coerce' for some truly interesting
operations:
| # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE FlexibleInstances #
# LANGUAGE GADTs #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE KindSignatures #
# LANGUAGE TypeApplications #
|
Module : Data . HList
Description : A nice , neat HList .
Copyright : ( c ) , 2018
License : MIT
Maintainer :
Stability : experimental
This module defines a heterogeneous list type . Any types can be stored in the
list , and the type itself is indexed by the types contained within . This module
also defines functions for extracting values /and/ folding an HList in which
all inhabitant types implement some constraint .
Module : Data.HList
Description : A nice, neat HList.
Copyright : (c) Tom Harding, 2018
License : MIT
Maintainer :
Stability : experimental
This module defines a heterogeneous list type. Any types can be stored in the
list, and the type itself is indexed by the types contained within. This module
also defines functions for extracting values /and/ folding an HList in which
all inhabitant types implement some constraint.
-}
module Data.HList where
import Data.Kind (Constraint, Type)
import Prelude hiding (foldMap)
' :> ' notation for @Cons@ , which hopefully makes uses a bit neater .
data HList (xs :: [Type]) where
HNil :: HList '[ ]
(:>) :: x -> HList xs -> HList (x ': xs)
infixr 3 :>
| Pluck a type from an HList . The constraint ensures that the type exists
> > > let example = True :> 3 :> " hello " :> HNil
class (x :: Type) `PluckedFrom` (xs :: [Type]) where
pluck :: HList xs -> x
instance x `PluckedFrom` (x ': xs) where
pluck (head :> _) = head
=> x `PluckedFrom` (y ': xs) where
pluck (_ :> tail) = pluck tail
| Fold an HList . Assuming all the elements of the list satisfy some
> > > let example = True :> 3 :> " hello " :> HNil
[ " True","3","\"hello\ " " ]
We can also fold over a homogeneous HList using an equality constraint ,
> > > import Data . Monoid
> > > foldMap ) Int ) Sum ( 3 :> 2 :> 1 :> HNil )
Sum { getSum = 6 }
> > > import Data . Coerce
> > > let example = Any False :> False :> All True :> HNil
> > > foldMap @(Coercible Any ) ( coerce @ _ ) example
Any { getAny = True }
class (c :: Type -> Constraint) `Folds` (xs :: [Type]) where
foldMap :: Monoid m => (forall x. c x => x -> m) -> HList xs -> m
instance anything `Folds` '[] where
foldMap _ HNil = mempty
instance (c x, c `Folds` xs) => c `Folds` (x ': xs) where
foldMap f (x :> xs) = f x <> foldMap @c f xs
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.