_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 |
|---|---|---|---|---|---|---|---|---|
bcdd8515095c2e10b1a3f34ff01930c28a8fce724232fa2c6b8ed9802414fb4b | thi-ng/demos | meshworker.cljs | (.importScripts js/self "base.js")
(ns meshworker
(:require-macros
[cljs-log.core :refer [debug info warn]])
(:require
[thi.ng.math.core :as m]
[thi.ng.geom.core :as g]
[thi.ng.geom.matrix :as mat]
[thi.ng.geom.mesh.io :as mio]
[thi.ng.geom.gl.glmesh :as glm]
[thi.ng.strf.core :as f]))
(defn load-binary
[uri onload onerror]
(let [xhr (js/XMLHttpRequest.)]
(.open xhr "GET" uri true)
(set! (.-responseType xhr) "arraybuffer")
(set! (.-onload xhr)
(fn [e]
(if-let [buf (.-response xhr)]
(onload buf)
(when onerror (onerror xhr e)))))
(.send xhr)))
(defn build-mesh
[buf]
(let [t0 (f/timestamp)
mesh (mio/read-stl
(mio/wrapped-input-stream buf)
#(glm/gl-mesh % #{:fnorm}))
bounds (g/bounds mesh)
tx (-> mat/M44
(g/scale (/ 1.0 (-> bounds :size :y)))
(g/translate (m/- (g/centroid bounds))))
vertices (-> mesh .-vertices .-buffer)
fnormals (-> mesh .-fnormals .-buffer)
num (.-id mesh)]
(debug (- (f/timestamp) t0) "ms," num "triangles")
(.postMessage
js/self
#js [vertices fnormals num tx]
#js [vertices fnormals])))
(defn load-mesh
[msg]
(load-binary
(.-data msg)
build-mesh
#(warn "error loading mesh: " (.-data msg))))
(set! (.-onmessage js/self) load-mesh)
| null | https://raw.githubusercontent.com/thi-ng/demos/048cd131099a7db29be56b965c053908acad4166/ws-ldn-11/day2/ex05b/src/ex05b/meshworker.cljs | clojure | (.importScripts js/self "base.js")
(ns meshworker
(:require-macros
[cljs-log.core :refer [debug info warn]])
(:require
[thi.ng.math.core :as m]
[thi.ng.geom.core :as g]
[thi.ng.geom.matrix :as mat]
[thi.ng.geom.mesh.io :as mio]
[thi.ng.geom.gl.glmesh :as glm]
[thi.ng.strf.core :as f]))
(defn load-binary
[uri onload onerror]
(let [xhr (js/XMLHttpRequest.)]
(.open xhr "GET" uri true)
(set! (.-responseType xhr) "arraybuffer")
(set! (.-onload xhr)
(fn [e]
(if-let [buf (.-response xhr)]
(onload buf)
(when onerror (onerror xhr e)))))
(.send xhr)))
(defn build-mesh
[buf]
(let [t0 (f/timestamp)
mesh (mio/read-stl
(mio/wrapped-input-stream buf)
#(glm/gl-mesh % #{:fnorm}))
bounds (g/bounds mesh)
tx (-> mat/M44
(g/scale (/ 1.0 (-> bounds :size :y)))
(g/translate (m/- (g/centroid bounds))))
vertices (-> mesh .-vertices .-buffer)
fnormals (-> mesh .-fnormals .-buffer)
num (.-id mesh)]
(debug (- (f/timestamp) t0) "ms," num "triangles")
(.postMessage
js/self
#js [vertices fnormals num tx]
#js [vertices fnormals])))
(defn load-mesh
[msg]
(load-binary
(.-data msg)
build-mesh
#(warn "error loading mesh: " (.-data msg))))
(set! (.-onmessage js/self) load-mesh)
| |
471e530d5550734f94b76dd421d069365155e75ee7dce4af38bfc04169d5882a | conjure-cp/conjure | Or.hs | # LANGUAGE DeriveGeneric , DeriveDataTypeable , DeriveFunctor , , DeriveFoldable #
# LANGUAGE UndecidableInstances #
module Conjure.Language.Expression.Op.Or where
import Conjure.Prelude
import Conjure.Language.Expression.Op.Internal.Common
import qualified Data.Aeson as JSON -- aeson
import qualified Data.HashMap.Strict as M -- unordered-containers
import qualified Data.Vector as V -- vector
data OpOr x = OpOr x
deriving (Eq, Ord, Show, Data, Functor, Traversable, Foldable, Typeable, Generic)
instance Serialize x => Serialize (OpOr x)
instance Hashable x => Hashable (OpOr x)
instance ToJSON x => ToJSON (OpOr x) where toJSON = genericToJSON jsonOptions
instance FromJSON x => FromJSON (OpOr x) where parseJSON = genericParseJSON jsonOptions
instance BinaryOperator (OpOr x) where
opLexeme _ = L_Or
instance (TypeOf x, Pretty x, ExpressionLike x) => TypeOf (OpOr x) where
typeOf p@(OpOr x) = do
ty <- typeOf x
case ty of
TypeList TypeAny -> return TypeBool
TypeList TypeBool -> return TypeBool
TypeMatrix _ TypeAny -> return TypeBool
TypeMatrix _ TypeBool -> return TypeBool
TypeSet TypeBool -> return TypeBool
TypeMSet TypeBool -> return TypeBool
_ -> raiseTypeError $ vcat [ pretty p
, "The argument has type:" <+> pretty ty
]
instance (OpOr x :< x) => SimplifyOp OpOr x where
simplifyOp (OpOr x)
| Just xs <- listOut x
, let filtered = filter (/= fromBool True) xs
, length filtered /= length xs -- there were true's
= return $ fromBool True
simplifyOp (OpOr x)
| Just xs <- listOut x
, let filtered = filter (/= fromBool False) xs
, length filtered /= length xs -- there were false's
= return $ inject $ OpOr $ fromList filtered
simplifyOp _ = na "simplifyOp{OpOr}"
instance (Pretty x, ExpressionLike x) => Pretty (OpOr x) where
prettyPrec prec op@(OpOr x) | Just [a,b] <- listOut x = prettyPrecBinOp prec [op] a b
prettyPrec _ (OpOr x) = "or" <> prParens (pretty x)
instance (VarSymBreakingDescription x, ExpressionLike x) => VarSymBreakingDescription (OpOr x) where
varSymBreakingDescription (OpOr x) | Just xs <- listOut x = JSON.Object $ M.fromList
[ ("type", JSON.String "OpOr")
, ("children", JSON.Array $ V.fromList $ map varSymBreakingDescription xs)
, ("symmetricChildren", JSON.Bool True)
]
varSymBreakingDescription (OpOr x) = JSON.Object $ M.fromList
[ ("type", JSON.String "OpOr")
, ("children", varSymBreakingDescription x)
]
| null | https://raw.githubusercontent.com/conjure-cp/conjure/dd5a27df138af2ccbbb970274c2b8f22ac6b26a0/src/Conjure/Language/Expression/Op/Or.hs | haskell | aeson
unordered-containers
vector
there were true's
there were false's | # LANGUAGE DeriveGeneric , DeriveDataTypeable , DeriveFunctor , , DeriveFoldable #
# LANGUAGE UndecidableInstances #
module Conjure.Language.Expression.Op.Or where
import Conjure.Prelude
import Conjure.Language.Expression.Op.Internal.Common
data OpOr x = OpOr x
deriving (Eq, Ord, Show, Data, Functor, Traversable, Foldable, Typeable, Generic)
instance Serialize x => Serialize (OpOr x)
instance Hashable x => Hashable (OpOr x)
instance ToJSON x => ToJSON (OpOr x) where toJSON = genericToJSON jsonOptions
instance FromJSON x => FromJSON (OpOr x) where parseJSON = genericParseJSON jsonOptions
instance BinaryOperator (OpOr x) where
opLexeme _ = L_Or
instance (TypeOf x, Pretty x, ExpressionLike x) => TypeOf (OpOr x) where
typeOf p@(OpOr x) = do
ty <- typeOf x
case ty of
TypeList TypeAny -> return TypeBool
TypeList TypeBool -> return TypeBool
TypeMatrix _ TypeAny -> return TypeBool
TypeMatrix _ TypeBool -> return TypeBool
TypeSet TypeBool -> return TypeBool
TypeMSet TypeBool -> return TypeBool
_ -> raiseTypeError $ vcat [ pretty p
, "The argument has type:" <+> pretty ty
]
instance (OpOr x :< x) => SimplifyOp OpOr x where
simplifyOp (OpOr x)
| Just xs <- listOut x
, let filtered = filter (/= fromBool True) xs
= return $ fromBool True
simplifyOp (OpOr x)
| Just xs <- listOut x
, let filtered = filter (/= fromBool False) xs
= return $ inject $ OpOr $ fromList filtered
simplifyOp _ = na "simplifyOp{OpOr}"
instance (Pretty x, ExpressionLike x) => Pretty (OpOr x) where
prettyPrec prec op@(OpOr x) | Just [a,b] <- listOut x = prettyPrecBinOp prec [op] a b
prettyPrec _ (OpOr x) = "or" <> prParens (pretty x)
instance (VarSymBreakingDescription x, ExpressionLike x) => VarSymBreakingDescription (OpOr x) where
varSymBreakingDescription (OpOr x) | Just xs <- listOut x = JSON.Object $ M.fromList
[ ("type", JSON.String "OpOr")
, ("children", JSON.Array $ V.fromList $ map varSymBreakingDescription xs)
, ("symmetricChildren", JSON.Bool True)
]
varSymBreakingDescription (OpOr x) = JSON.Object $ M.fromList
[ ("type", JSON.String "OpOr")
, ("children", varSymBreakingDescription x)
]
|
5246f8c977043acd3bd1dbff1dac3e5afc59104ef87563f72ab90543c42871a2 | eighttrigrams/cljc-minimals | env.clj | (ns env)
(def wrap-env-defaults identity) | null | https://raw.githubusercontent.com/eighttrigrams/cljc-minimals/fa2c925ffa56386b23f502990270b80ea47b8cbc/mount/env/prod/env.clj | clojure | (ns env)
(def wrap-env-defaults identity) | |
3f22332517a086a7c312b8f13a8ec31c45a18c22cca63e38cf6c741a59d91ae2 | Feuerlabs/exometer_core | exometer_folsom_monitor.erl | %% -------------------------------------------------------------------
%%
Copyright ( c ) 2014 Basho Technologies , Inc. All Rights Reserved .
%%
This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
%%
%% -------------------------------------------------------------------
%%
%% @doc Hook API for following folsom-based legacy code with exometer
%%
%% This module installs hooks into folsom, allowing subscribers to trap
%% the creation of metrics using the folsom API, and instruct exometer
%% to create matching metrics entries.
%%
%% Subscriptions identify a module that should be on the call stack when
%% a module is created (when testing from the shell, use the module `shell'),
%% and a callback module which is used to retrieve the specs for exometer
%% metrics to create.
%% @end
-module(exometer_folsom_monitor).
-behaviour(gen_server).
-export([start_link/0,
init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3]).
-export([monitor/2]).
-export([hook/1]).
-record(st, {mon = orddict:new()}).
-include_lib("parse_trans/include/codegen.hrl").
-include_lib("hut/include/hut.hrl").
-include("exometer.hrl").
-type type() :: exometer:type().
-type name() :: exometer:name().
-type options() :: exometer:options().
-callback copy_folsom(name(), type(), options()) ->
{name(), type(), options()} |
[{name(), type(), options()}] |
false.
-spec monitor(atom(), atom()) -> ok.
%% @doc Monitor a legacy module.
%%
` FromMod ' is the name of a module that should appear on the call stack
%% when a call to `folsom_metrics:new_<Type>' is made (or <code>'_'</code>,
%% which will match any call stack). `Callback' is a callback module,
exporting the function ` copy_folsom(Name , Type , ) ' , which returns a
%% `{Name, Type, Options}' tuple, a list of such tuples, or the atom `false'.
%%
%% The callback module is called from the `exometer_folsom_monitor'
%% process, so the call stack will not contain the legacy modules.
%% However, if the corresponding exometer metrics end up calling other
%% folsom-based metrics (e.g. using the `exometer_folsom' module), there
%% will be a risk of generating a loop.
%% @end
monitor(FromMod, Callback) when is_atom(FromMod), is_atom(Callback) ->
gen_server:call(?MODULE, {monitor, FromMod, Callback}).
@private
hook(Args) ->
Stack = try error(x)
catch
?EXCEPTION(error, _, Stacktrace) ->
?GET_STACK(Stacktrace)
end,
gen_server:cast(?MODULE, {hook, Args, Stack}).
%% @doc Start the server (called automatically by exometer).
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
@private
init(_) ->
Mon = lists:foldl(
fun({Mf, Mc}, D) ->
orddict:append(Mf, Mc, D)
end, orddict:new(), find_env()),
init_monitor(Mon),
{ok, #st{mon = Mon}}.
find_env() ->
E1 = [E || {_, E} <- setup:find_env_vars(exometer_folsom_monitor)],
E2 = exometer_util:get_env(folsom_monitor, []),
lists:flatmap(
fun({_,_} = M) -> [M];
(L) when is_list(L) -> L
end, E1 ++ E2).
@private
handle_call({monitor, Mod, CB}, _, #st{mon = Mon} = S)
when is_atom(Mod), is_atom(CB) ->
if Mon == [] -> do_init_monitor();
true -> ok
end,
{reply, ok, S#st{mon = orddict:append(Mod, CB, Mon)}};
handle_call(_, _, S) ->
{reply, {error, unsupported}, S}.
@private
handle_cast({hook, Args, Stack}, S) ->
check_stack(S#st.mon, Stack, Args),
{noreply, S}.
@private
handle_info(_, S) -> {noreply, S}.
@private
terminate(_, _) -> ok.
@private
code_change(_, S, _) -> {ok, S}.
init_monitor([]) ->
ok;
init_monitor([_|_]) ->
do_init_monitor().
do_init_monitor() ->
case is_transformed() of
true ->
?log(debug, "already transformed...~n", []),
ok;
false ->
?log(debug, "transforming folsom_metrics...~n", []),
parse_trans_mod:transform_module(folsom_metrics, fun pt/2, [])
end.
pt(Forms, _) ->
Funcs = funcs(),
NewForms = parse_trans:plain_transform(
fun(F) ->
plain_pt(F, Funcs)
end, Forms),
mark_transformed(NewForms).
is_transformed() ->
Attrs = folsom_metrics:module_info(attributes),
[true || {?MODULE,[]} <- Attrs] =/= [].
mark_transformed([{attribute,L,module,_} = M|Fs]) ->
[M, {attribute,L,?MODULE,[]} | Fs];
mark_transformed([H|T]) ->
[H | mark_transformed(T)].
plain_pt({function,L,F,A,Cs}, Funcs) ->
case lists:keyfind({F,A}, 1, Funcs) of
{_, Type} ->
{function,L,F,A,insert_hook(Type, Cs)};
false ->
continue
end;
plain_pt(_, _) ->
continue.
funcs() ->
[{{new_counter , 1}, counter},
{{new_gauge , 1}, gauge},
{{new_meter , 1}, meter},
{{new_meter_reader, 1}, meter_reader},
{{new_history , 2}, history},
{{new_histogram , 4}, histogram},
{{new_spiral , 1}, spiral},
{{new_duration , 4}, duration}].
insert_hook(Type, Cs) ->
lists:map(
fun({clause,L0,Args,Gs,Body}) ->
L = element(2,hd(Body)),
{clause,L0,Args,Gs,
[{call,L,{remote,L,{atom,L,?MODULE},{atom,L,hook}},
[cons([{atom,L,Type}|Args], L)]}|Body]}
end, Cs).
cons([H|T], L) -> {cons,L,H,cons(T,L)};
cons([] , L) -> {nil,L}.
check_stack(Mon, Stack, Args) ->
orddict:fold(
fun('_', CBs, Acc) ->
_ = [maybe_create(CB, Args) || CB <- CBs],
Acc;
(Mod, CBs, Acc) ->
case lists:keymember(Mod, 1, Stack) of
true ->
_ = [maybe_create(CB, Args) || CB <- CBs];
false ->
ignore
end,
Acc
end, ok, Mon).
maybe_create(CB, [FolsomType, Name | Args]) ->
try CB:copy_folsom(Name, FolsomType, Args) of
{ExoName, ExoType, ExoArgs} ->
exometer:new(ExoName, ExoType, ExoArgs);
L when is_list(L) ->
lists:foreach(
fun({ExoName, ExoType, ExoArgs}) ->
exometer:new(ExoName, ExoType, ExoArgs)
end, L);
false ->
ignore
catch
Cat:Msg ->
?log(error, "~p:copy_folsom(~p,~p,~p): ~p:~p~n",
[CB, Name, FolsomType, Args, Cat, Msg]),
ignore
end.
| null | https://raw.githubusercontent.com/Feuerlabs/exometer_core/358d5c6724b823104f122ca4f16439ae0e767c82/src/exometer_folsom_monitor.erl | erlang | -------------------------------------------------------------------
-------------------------------------------------------------------
@doc Hook API for following folsom-based legacy code with exometer
This module installs hooks into folsom, allowing subscribers to trap
the creation of metrics using the folsom API, and instruct exometer
to create matching metrics entries.
Subscriptions identify a module that should be on the call stack when
a module is created (when testing from the shell, use the module `shell'),
and a callback module which is used to retrieve the specs for exometer
metrics to create.
@end
@doc Monitor a legacy module.
when a call to `folsom_metrics:new_<Type>' is made (or <code>'_'</code>,
which will match any call stack). `Callback' is a callback module,
`{Name, Type, Options}' tuple, a list of such tuples, or the atom `false'.
The callback module is called from the `exometer_folsom_monitor'
process, so the call stack will not contain the legacy modules.
However, if the corresponding exometer metrics end up calling other
folsom-based metrics (e.g. using the `exometer_folsom' module), there
will be a risk of generating a loop.
@end
@doc Start the server (called automatically by exometer). | Copyright ( c ) 2014 Basho Technologies , Inc. All Rights Reserved .
This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
-module(exometer_folsom_monitor).
-behaviour(gen_server).
-export([start_link/0,
init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3]).
-export([monitor/2]).
-export([hook/1]).
-record(st, {mon = orddict:new()}).
-include_lib("parse_trans/include/codegen.hrl").
-include_lib("hut/include/hut.hrl").
-include("exometer.hrl").
-type type() :: exometer:type().
-type name() :: exometer:name().
-type options() :: exometer:options().
-callback copy_folsom(name(), type(), options()) ->
{name(), type(), options()} |
[{name(), type(), options()}] |
false.
-spec monitor(atom(), atom()) -> ok.
` FromMod ' is the name of a module that should appear on the call stack
exporting the function ` copy_folsom(Name , Type , ) ' , which returns a
monitor(FromMod, Callback) when is_atom(FromMod), is_atom(Callback) ->
gen_server:call(?MODULE, {monitor, FromMod, Callback}).
@private
hook(Args) ->
Stack = try error(x)
catch
?EXCEPTION(error, _, Stacktrace) ->
?GET_STACK(Stacktrace)
end,
gen_server:cast(?MODULE, {hook, Args, Stack}).
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
@private
init(_) ->
Mon = lists:foldl(
fun({Mf, Mc}, D) ->
orddict:append(Mf, Mc, D)
end, orddict:new(), find_env()),
init_monitor(Mon),
{ok, #st{mon = Mon}}.
find_env() ->
E1 = [E || {_, E} <- setup:find_env_vars(exometer_folsom_monitor)],
E2 = exometer_util:get_env(folsom_monitor, []),
lists:flatmap(
fun({_,_} = M) -> [M];
(L) when is_list(L) -> L
end, E1 ++ E2).
@private
handle_call({monitor, Mod, CB}, _, #st{mon = Mon} = S)
when is_atom(Mod), is_atom(CB) ->
if Mon == [] -> do_init_monitor();
true -> ok
end,
{reply, ok, S#st{mon = orddict:append(Mod, CB, Mon)}};
handle_call(_, _, S) ->
{reply, {error, unsupported}, S}.
@private
handle_cast({hook, Args, Stack}, S) ->
check_stack(S#st.mon, Stack, Args),
{noreply, S}.
@private
handle_info(_, S) -> {noreply, S}.
@private
terminate(_, _) -> ok.
@private
code_change(_, S, _) -> {ok, S}.
init_monitor([]) ->
ok;
init_monitor([_|_]) ->
do_init_monitor().
do_init_monitor() ->
case is_transformed() of
true ->
?log(debug, "already transformed...~n", []),
ok;
false ->
?log(debug, "transforming folsom_metrics...~n", []),
parse_trans_mod:transform_module(folsom_metrics, fun pt/2, [])
end.
pt(Forms, _) ->
Funcs = funcs(),
NewForms = parse_trans:plain_transform(
fun(F) ->
plain_pt(F, Funcs)
end, Forms),
mark_transformed(NewForms).
is_transformed() ->
Attrs = folsom_metrics:module_info(attributes),
[true || {?MODULE,[]} <- Attrs] =/= [].
mark_transformed([{attribute,L,module,_} = M|Fs]) ->
[M, {attribute,L,?MODULE,[]} | Fs];
mark_transformed([H|T]) ->
[H | mark_transformed(T)].
plain_pt({function,L,F,A,Cs}, Funcs) ->
case lists:keyfind({F,A}, 1, Funcs) of
{_, Type} ->
{function,L,F,A,insert_hook(Type, Cs)};
false ->
continue
end;
plain_pt(_, _) ->
continue.
funcs() ->
[{{new_counter , 1}, counter},
{{new_gauge , 1}, gauge},
{{new_meter , 1}, meter},
{{new_meter_reader, 1}, meter_reader},
{{new_history , 2}, history},
{{new_histogram , 4}, histogram},
{{new_spiral , 1}, spiral},
{{new_duration , 4}, duration}].
insert_hook(Type, Cs) ->
lists:map(
fun({clause,L0,Args,Gs,Body}) ->
L = element(2,hd(Body)),
{clause,L0,Args,Gs,
[{call,L,{remote,L,{atom,L,?MODULE},{atom,L,hook}},
[cons([{atom,L,Type}|Args], L)]}|Body]}
end, Cs).
cons([H|T], L) -> {cons,L,H,cons(T,L)};
cons([] , L) -> {nil,L}.
check_stack(Mon, Stack, Args) ->
orddict:fold(
fun('_', CBs, Acc) ->
_ = [maybe_create(CB, Args) || CB <- CBs],
Acc;
(Mod, CBs, Acc) ->
case lists:keymember(Mod, 1, Stack) of
true ->
_ = [maybe_create(CB, Args) || CB <- CBs];
false ->
ignore
end,
Acc
end, ok, Mon).
maybe_create(CB, [FolsomType, Name | Args]) ->
try CB:copy_folsom(Name, FolsomType, Args) of
{ExoName, ExoType, ExoArgs} ->
exometer:new(ExoName, ExoType, ExoArgs);
L when is_list(L) ->
lists:foreach(
fun({ExoName, ExoType, ExoArgs}) ->
exometer:new(ExoName, ExoType, ExoArgs)
end, L);
false ->
ignore
catch
Cat:Msg ->
?log(error, "~p:copy_folsom(~p,~p,~p): ~p:~p~n",
[CB, Name, FolsomType, Args, Cat, Msg]),
ignore
end.
|
c73d991ea30d297cfbd094600ef32867f18669bebd72651bc8a1f563a4fd63d7 | TrustInSoft/tis-interpreter | integer.zarith.ml | (**************************************************************************)
(* *)
This file is part of Frama - C.
(* *)
Copyright ( C ) 2007 - 2015
CEA ( Commissariat à l'énergie atomique et aux énergies
(* alternatives) *)
(* *)
(* you can redistribute it and/or modify it under the terms of the GNU *)
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
(* *)
(* It 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. *)
(* *)
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(* *)
(**************************************************************************)
type t = Z.t
exception Too_big
let equal = Z.equal
let compare = Z.compare
let two_power_of_int k =
Z.shift_left Z.one k
let two_power y =
try
let k = Z.to_int y in
if k > 1024 then
(* avoid memory explosion *)
raise Too_big
else
two_power_of_int k
with Z.Overflow -> raise Too_big
let popcount = Z.popcount
(* To export *)
let small_nums = Array.init 33 (fun i -> Z.of_int i)
let zero = Z.zero
let one = Z.one
let minus_one = Z.minus_one
let two = Z.of_int 2
let four = Z.of_int 4
let eight = Z.of_int 8
let sixteen = Z.of_int 16
let thirtytwo = Z.of_int 32
let onethousand = Z.of_int 1000
let billion_one = Z.of_int 1_000_000_001
let two_power_32 = two_power_of_int 32
let two_power_60 = two_power_of_int 60
let two_power_64 = two_power_of_int 64
let is_zero v = Z.equal v Z.zero
let add = Z.add
let sub = Z.sub
let succ = Z.succ
let pred = Z.pred
let neg = Z.neg
let rem = Z.erem
let div = Z.ediv
let mul = Z.mul
let abs = Z.abs
let hash = Z.hash
let shift_left x y = Z.shift_left x (Z.to_int y)
let shift_right x y = Z.shift_right x (Z.to_int y)
let shift_right_logical x y = (* no meaning for negative value of x *)
if (Z.lt x Z.zero)
then failwith "log_shift_right_big_int"
else Z.shift_right x (Z.to_int y)
let logand = Z.logand
let lognot = Z.lognot
let logor = Z.logor
let logxor = Z.logxor
let le a b = Z.compare a b <= 0
let ge a b = Z.compare a b >= 0
let lt a b = Z.compare a b < 0
let gt a b = Z.compare a b > 0
let of_int = Z.of_int
let of_int64 = Z.of_int64
let of_int32 = Z.of_int32
Return the same exceptions as [ Big_int ]
let to_int = Big_int_Z.int_of_big_int
let to_int64 = Big_int_Z.int64_of_big_int
let of_string s =
try Z.of_string s
with Invalid_argument _ ->
We intentionally do NOT specify a string in the .mli , as Big_int
raises multiple [ Failure _ ] exceptions
raises multiple [Failure _] exceptions *)
failwith "Integer.of_string"
let max_int64 = of_int64 Int64.max_int
let min_int64 = of_int64 Int64.min_int
let to_string = Z.to_string
let to_float = Z.to_float
let of_float = Z.of_float
let add_2_64 x = add two_power_64 x
let add_2_32 x = add two_power_32 x
let pretty ?(hexa=false) fmt v =
let rec aux v =
if gt v two_power_60 then
let quo, rem = Z.ediv_rem v two_power_60 in
aux quo;
Format.fprintf fmt "%015LX" (to_int64 rem)
else
Format.fprintf fmt "%LX" (to_int64 v)
in
if hexa then
if equal v zero then Format.pp_print_string fmt "0"
else if gt v zero then (Format.pp_print_string fmt "0x"; aux v)
else (Format.pp_print_string fmt "-0x"; aux (Z.neg v))
else
Format.pp_print_string fmt (to_string v)
let is_one v = equal one v
let pos_div = div
let pos_rem = rem
let native_div = div
let divexact = Z.divexact
let div_rem = Z.div_rem
let c_div u v =
let bad_div = div u v in
if (lt u zero) && not (is_zero (rem u v))
then
if lt v zero
then pred bad_div
else succ bad_div
else bad_div
let c_rem u v =
sub u (mul v (c_div u v))
let cast ~size ~signed ~value =
if (not signed)
then
let factor = two_power size in logand value (pred factor)
else
let mask = two_power (sub size one) in
let p_mask = pred mask in
if equal (logand mask value) zero
then logand value p_mask
else
logor (lognot p_mask) value
let length u v = succ (sub v u)
let extract_bits ~start ~stop v =
assert (ge start zero && ge stop start);
" % a[%a .. %a]@\n " pretty v pretty start pretty stop ;
let r = Z.extract v (to_int start) (to_int (length start stop)) in
" % a[%a .. %a]=%a@\n " pretty v pretty start pretty stop pretty r ;
r
let is_even v = is_zero (logand one v)
(** [pgcd u 0] is allowed and returns [u] *)
let pgcd u v =
let r =
if is_zero v
then u
else Z.gcd u v in
r
let ppcm u v =
if u = zero || v = zero
then zero
else native_div (mul u v) (pgcd u v)
let min = Z.min
let max = Z.max
let round_down_to_zero v modu =
mul (pos_div v modu) modu
(** [round_up_to_r m r modu] is the smallest number [n] such that
[n]>=[m] and [n] = [r] modulo [modu] *)
let round_up_to_r ~min:m ~r ~modu =
add (add (round_down_to_zero (pred (sub m r)) modu) r) modu
(** [round_down_to_r m r modu] is the largest number [n] such that
[n]<=[m] and [n] = [r] modulo [modu] *)
let round_down_to_r ~max:m ~r ~modu =
add (round_down_to_zero (sub m r) modu) r
let to_num b =
Num.num_of_big_int
(Big_int.big_int_of_string (Big_int_Z.string_of_big_int b))
let power_int_positive_int = Big_int_Z.power_int_positive_int
| null | https://raw.githubusercontent.com/TrustInSoft/tis-interpreter/33132ce4a825494ea48bf2dd6fd03a56b62cc5c3/src/libraries/stdlib/integer.zarith.ml | ocaml | ************************************************************************
alternatives)
you can redistribute it and/or modify it under the terms of the GNU
It 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.
************************************************************************
avoid memory explosion
To export
no meaning for negative value of x
* [pgcd u 0] is allowed and returns [u]
* [round_up_to_r m r modu] is the smallest number [n] such that
[n]>=[m] and [n] = [r] modulo [modu]
* [round_down_to_r m r modu] is the largest number [n] such that
[n]<=[m] and [n] = [r] modulo [modu] | This file is part of Frama - C.
Copyright ( C ) 2007 - 2015
CEA ( Commissariat à l'énergie atomique et aux énergies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
type t = Z.t
exception Too_big
let equal = Z.equal
let compare = Z.compare
let two_power_of_int k =
Z.shift_left Z.one k
let two_power y =
try
let k = Z.to_int y in
if k > 1024 then
raise Too_big
else
two_power_of_int k
with Z.Overflow -> raise Too_big
let popcount = Z.popcount
let small_nums = Array.init 33 (fun i -> Z.of_int i)
let zero = Z.zero
let one = Z.one
let minus_one = Z.minus_one
let two = Z.of_int 2
let four = Z.of_int 4
let eight = Z.of_int 8
let sixteen = Z.of_int 16
let thirtytwo = Z.of_int 32
let onethousand = Z.of_int 1000
let billion_one = Z.of_int 1_000_000_001
let two_power_32 = two_power_of_int 32
let two_power_60 = two_power_of_int 60
let two_power_64 = two_power_of_int 64
let is_zero v = Z.equal v Z.zero
let add = Z.add
let sub = Z.sub
let succ = Z.succ
let pred = Z.pred
let neg = Z.neg
let rem = Z.erem
let div = Z.ediv
let mul = Z.mul
let abs = Z.abs
let hash = Z.hash
let shift_left x y = Z.shift_left x (Z.to_int y)
let shift_right x y = Z.shift_right x (Z.to_int y)
if (Z.lt x Z.zero)
then failwith "log_shift_right_big_int"
else Z.shift_right x (Z.to_int y)
let logand = Z.logand
let lognot = Z.lognot
let logor = Z.logor
let logxor = Z.logxor
let le a b = Z.compare a b <= 0
let ge a b = Z.compare a b >= 0
let lt a b = Z.compare a b < 0
let gt a b = Z.compare a b > 0
let of_int = Z.of_int
let of_int64 = Z.of_int64
let of_int32 = Z.of_int32
Return the same exceptions as [ Big_int ]
let to_int = Big_int_Z.int_of_big_int
let to_int64 = Big_int_Z.int64_of_big_int
let of_string s =
try Z.of_string s
with Invalid_argument _ ->
We intentionally do NOT specify a string in the .mli , as Big_int
raises multiple [ Failure _ ] exceptions
raises multiple [Failure _] exceptions *)
failwith "Integer.of_string"
let max_int64 = of_int64 Int64.max_int
let min_int64 = of_int64 Int64.min_int
let to_string = Z.to_string
let to_float = Z.to_float
let of_float = Z.of_float
let add_2_64 x = add two_power_64 x
let add_2_32 x = add two_power_32 x
let pretty ?(hexa=false) fmt v =
let rec aux v =
if gt v two_power_60 then
let quo, rem = Z.ediv_rem v two_power_60 in
aux quo;
Format.fprintf fmt "%015LX" (to_int64 rem)
else
Format.fprintf fmt "%LX" (to_int64 v)
in
if hexa then
if equal v zero then Format.pp_print_string fmt "0"
else if gt v zero then (Format.pp_print_string fmt "0x"; aux v)
else (Format.pp_print_string fmt "-0x"; aux (Z.neg v))
else
Format.pp_print_string fmt (to_string v)
let is_one v = equal one v
let pos_div = div
let pos_rem = rem
let native_div = div
let divexact = Z.divexact
let div_rem = Z.div_rem
let c_div u v =
let bad_div = div u v in
if (lt u zero) && not (is_zero (rem u v))
then
if lt v zero
then pred bad_div
else succ bad_div
else bad_div
let c_rem u v =
sub u (mul v (c_div u v))
let cast ~size ~signed ~value =
if (not signed)
then
let factor = two_power size in logand value (pred factor)
else
let mask = two_power (sub size one) in
let p_mask = pred mask in
if equal (logand mask value) zero
then logand value p_mask
else
logor (lognot p_mask) value
let length u v = succ (sub v u)
let extract_bits ~start ~stop v =
assert (ge start zero && ge stop start);
" % a[%a .. %a]@\n " pretty v pretty start pretty stop ;
let r = Z.extract v (to_int start) (to_int (length start stop)) in
" % a[%a .. %a]=%a@\n " pretty v pretty start pretty stop pretty r ;
r
let is_even v = is_zero (logand one v)
let pgcd u v =
let r =
if is_zero v
then u
else Z.gcd u v in
r
let ppcm u v =
if u = zero || v = zero
then zero
else native_div (mul u v) (pgcd u v)
let min = Z.min
let max = Z.max
let round_down_to_zero v modu =
mul (pos_div v modu) modu
let round_up_to_r ~min:m ~r ~modu =
add (add (round_down_to_zero (pred (sub m r)) modu) r) modu
let round_down_to_r ~max:m ~r ~modu =
add (round_down_to_zero (sub m r) modu) r
let to_num b =
Num.num_of_big_int
(Big_int.big_int_of_string (Big_int_Z.string_of_big_int b))
let power_int_positive_int = Big_int_Z.power_int_positive_int
|
4fdddf37be02ea03bd455f765795c98cdba4fdf2addb38d94f594911093fb776 | elginer/Delve | DelveVM.hs |
The Delve Programming Language
Copyright 2009
Distributed under the terms of the GNU General Public License v3 , or ( at your option ) any later version .
This file is part of Delve .
Delve 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 .
Delve 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 Delve . If not , see < / > .
The Delve Programming Language
Copyright 2009 John Morrice
Distributed under the terms of the GNU General Public License v3, or ( at your option ) any later version.
This file is part of Delve.
Delve 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.
Delve 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 Delve. If not, see </>.
-}
-- The virtual machine for the delve programming language
{-# OPTIONS -XBangPatterns #-}
module DelveVM
( module Control.Monad.State.Strict
, module Data.Maybe
, module Data.Word
, eval
, DState ( .. )
, ActivationFrame ( .. )
, Object ( .. )
, LocalEnv ( .. )
, Expr ( .. )
, get_object
, get_current_object_ref
, get_arg
, push_code
, get_prim
, get_symbol
, get_cont
, get_code_block
, run_delve
, lookup_current_object
, lookup_local_env
, get_activation_frame
, get_current_object
, get_result
, irrefutible_lookup
, put_result
, new
, new_prim
, call_cc
, jump_local
, jump_obj
, newIORef
, modifyIORef
, readIORef
)
where
import DMachineState
import Control.Monad.State.Strict
import Control.Applicative
import Control.Exception as E
import Control.Monad.Stream as C
import Data.List.Stream as L
import Data.Word
import Data.IORef
-- hiding ( newIORef , modifyIORef , readIORef , writeIORef )
--import qualified Data.IORef as I ( newIORef , modifyIORef , readIORef , writeIORef )
import qualified Data.Map as M
import Data.Maybe
import qualified Data.ByteString.Char8 as B
import Data.Array.IO
-- SHOULD THESE EVEN BE STRICT ! ! ? !
-- a strict version of ' newIORef '
newIORef : : a - > IO ( IORef a )
newIORef ! x = I.newIORef x
-- a strict version of ' modifyIORef '
modifyIORef : : IORef a - > ( a - > a ) - > IO ( )
modifyIORef ! ref ! f = do
a < - readIORef
let new_a = f $ ! a
case new_a of
! forced_a - > writeIORef ref forced_a
writeIORef : : IORef a - > a - > IO ( )
writeIORef ! ref ! a =
I.writeIORef ref a
-- a strict version of ' readIORef '
readIORef : : IORef a - > IO a
readIORef ref = do
a < - I.readIORef ref
case a of
! stuff - > return stuff
-- SHOULD THESE EVEN BE STRICT!!?!
-- a strict version of 'newIORef'
newIORef :: a -> IO ( IORef a )
newIORef !x = I.newIORef x
-- a strict version of 'modifyIORef'
modifyIORef :: IORef a -> ( a -> a ) -> IO ( )
modifyIORef !ref !f = do
a <- readIORef
let new_a = f $! a
case new_a of
!forced_a -> writeIORef ref forced_a
writeIORef :: IORef a -> a -> IO ( )
writeIORef !ref !a =
I.writeIORef ref a
-- a strict version of 'readIORef'
readIORef :: IORef a -> IO a
readIORef ref = do
a <- I.readIORef ref
case a of
!stuff -> return stuff
-}
Run a Delve program
run_delve :: Code -> IO ( )
run_delve code = do
new_delve_state code >>= runStateT eval
return ( )
-- | Add a new object to the heap and store the address in the result slot
new :: DelveM ( )
new = do
o <- new_object_addr
put_result o
-- | Add a new primative to the heap and store the address in the result slot
new_prim :: Prim -> DelveM ( )
new_prim prim = do
prim_addr <- new_prim_addr prim
put_result prim_addr
{-
This function ( eval_expr ) is plainly ridiculous. It needs to become a type class!
-}
-- | Evaluate an expression
eval_expr :: Expr -> DelveM ( )
-- create a new object
eval_expr New =
new
-- add a new block of code to the heap and store the address in the result slot
eval_expr ( NewBlock code ) = do
c_addr <- new_code_addr code
put_result c_addr
-- set the result address to this symbol in current object
eval_expr ( RefObj path ) = do
a <- lookup_current_object path
put_result a
-- set the result address to this symbol in the local environment
eval_expr ( RefLocal depth path ) = do
e <- get_environment_at depth
a <- search_environment e path
put_result a
-- create a new primative
eval_expr ( NewPrim prim ) =
new_prim prim
-- associate the current object stack with this symbol in the current object
eval_expr ( RememberObjObj path ) = do
a <- lookup_current_object path
remember_objects a
-- associate the current object stack with this symbol in the local scope
eval_expr ( RememberObjLocal depth path ) = do
le <- get_environment_at depth
ela <- find_addr_local le path
either ( const $ local_memory_error )
remember_objects
ela
-- associate the current local environment with this symbol in the current object
eval_expr ( RememberLocalObj path ) = do
a <- lookup_current_object path
remember_local a
-- associate the current local environment with this symbol in the local scope
eval_expr ( RememberLocalLocal depth path ) = do
le <- get_environment_at depth
ela <- find_addr_local le path
either ( const $ local_memory_error )
remember_local
ela
-- push the activation frame associated with the code block refered to by the symbol in the current object on the top of the activation stack
eval_expr ( PushFrameObj path ) = do
a <- lookup_current_object path
fr <- get_address_frame a
vat <- get_activation_frame
push_activation_frame vat fr
-- push the activation frame associated with the code block refered to by the symbol in the local environment to the top of the activation stack
eval_expr ( PushFrameLocal depth path ) = do
e <- get_environment_at depth
a <- search_environment e path
fr <- get_address_frame a
vat <- get_activation_frame
push_activation_frame vat fr
-- pop the current activation frame from the stack
eval_expr PopFrame = do
pop_activation_frame
return ( )
-- Push the address referred to by the symbol in the current object on to the argument stack
eval_expr ( PushObjArg path w ) = do
a <- lookup_current_object path
push_arg a w
-- Push the address referred to by the symbol in the local environment on to the argument stack
eval_expr ( PushLocalArg depth path w ) = do
e <- get_environment_at depth
a <- search_environment e path
push_arg a w
-- Set the argument at the index ( which should be counted from the other end, it's more efficient to work backwards ) in the current argument list equal to the symbol in the local environment
eval_expr ( WriteArg i sym ) = do
arg <- get_arg i
le <- get_current_env
assign_local le [ ] sym arg
-- Read the address in the result slot, and set a mapping between the symbol and this address in the local environment
eval_expr ( AssignLocal depth path sym ) = do
a <- get_result
ev <- get_environment_at depth
assign_local ev path sym a
-- Read the address in the result slot, and set a mapping between the symbol and this address in the object at the end of the chain of object references
eval_expr ( AssignObject path sym ) = do
a <- get_result
assign_object path sym a
-- Add the object refered to by the symbol in the current object to the top of the object stack ( it becomes the current object )
eval_expr (LoadObj path ) = do
o <- get_current_object_ref
a <- find_addr path $ ObjAddr o
let o = get_object a
push_object o
-- Add the object refered to by the symbol in the local environment to the top of the object stack ( it becomes the current object )
eval_expr ( LoadLocal depth path ) = do
e <- get_environment_at depth
a <- search_environment e path
let o = get_object a
push_object o
-- Pop an object from the top of the current object stack
eval_expr PopObject =
pop_object
-- Call the code refered to by the symbol in the current object by concatenating it with the rest of the executing code
eval_expr ( CallObj sym ) = do
-- liftIO $ putStrLn "gonna lookup"
o <- get_current_object
a <- lookup_current_object sym
-- liftIO $ do putStrLn "lookup up object"
-- case a of
_ - > putStrLn " got summink "
let cbio = get_code_block a
cb <- liftIO $ readIORef cbio
push_code_block cb
vat <- get_activation_frame
push_activation_frame vat $ memory_frame cb
-- Call the code refred to by the symbol in the current local environment by concatenating it with the rest of the executing code
eval_expr ( CallLocal depth path ) = do
a <- lookup_local_env depth path
let cbio = get_code_block a
cb <- liftIO $ readIORef cbio
push_code_block cb
vat <- get_activation_frame
push_activation_frame vat $ memory_frame cb
-- Add a new empty local scope to the local environment stack
eval_expr PushLocal = do
push_local
-- Pop the last local scope from the environment stack
eval_expr PopLocal = do
pop_local
-- Perform an arbitrary machine instruction
eval_expr ( MachineInstruction command ) =
command
A symbolic pattern match , comparing the symbol at the address referenced by symbol in the current object to one of the alternatives
eval_expr ( MatchObj path alts ) = do
o <- get_current_object_ref
a <- find_addr path $ ObjAddr o
sym <- liftIO $ readIORef $ get_symbol a
match sym alts
-- A symbolic pattern match, comparing the symbol at the address referenced by symbol in the local environment to one of the alternatives
eval_expr ( MatchLocal depth path alts ) = do
e <- get_environment_at depth
a <- search_environment e path
sym <- liftIO $ readIORef $ get_symbol a
match sym alts
-- move the current object into the return slot
eval_expr RefSelf = do
o <- get_current_object_ref
o2 <- get_current_object
put_result $ ObjAddr o
-- Tail call the code refered to by the symbol in the current object by concatenating it with the rest of the executing code and popping the local scope before it is executed
eval_expr ( LocalTailCallObj pop sym ) = do
a <- lookup_current_object sym
let cbio = get_code_block a
cb <- liftIO $ readIORef cbio
fr <- get_address_frame a
vat <- get_activation_frame
pop_local
C.when pop pop_object
push_activation_frame vat fr
push_code_block cb
-- Call the code refered to by the symbol in the current local environment by concatenating it with the rest of the executing code and popping the local scope before it is executed -- pop the current object if the flag is set
-- I think there's a bit of in consistancy here...
eval_expr ( LocalTailCallLocal pop depth sym ) = do
a <- lookup_local_env depth sym
let cbio = get_code_block a
cb <- liftIO $ readIORef cbio
fr <- get_address_frame a
vat <- get_activation_frame
pop_local
C.when pop pop_object
push_activation_frame vat fr
push_code_block cb
-- Call the code referred to by the symbol in the current local environment by concatenating it with the rest of the executing code and popping the activation frame before it is executed
eval_expr ( FrameTailCallLocal depth sym ) = do
a <- lookup_local_env depth sym
let cbio = get_code_block a
cb <- liftIO $ readIORef cbio
fr <- get_address_frame a
vat <- pop_activation_frame
push_activation_frame vat fr
push_code_block cb
-- Call the code referred to by the symbol in the current object by concatenating it with the rest of the executing code and popping the activation frame before it is executed
eval_expr ( FrameTailCallObj sym ) = do
a <- lookup_current_object sym
let cbio = get_code_block a
cb <- liftIO $ readIORef cbio
fr <- get_address_frame a
vat <- pop_activation_frame
push_activation_frame vat fr
push_code_block cb
-- assign space for a new symbol and set the result to this address
eval_expr ( NewSymbol sym ) = do
sym_addr <- fmap SymbolAddr $ liftIO $ newIORef sym
put_result sym_addr
-- call-with-current-continuation:
eval_expr ( CallCC code ) =
call_cc code
-- Jump to the continuation referenced by the symbol in the current object
eval_expr ( JumpObj path ) =
jump_obj path
-- Jump to the continuation referenced by the symbol in the local environment
eval_expr ( JumpLocal depth path ) =
jump_local depth path
-- Jump to the continuation referenced by the symbol in the local environment
jump_local :: Int -> [ Symbol ] -> DelveM ( )
jump_local depth path = do
e <- get_environment_at depth
cio <- fmap get_cont $ search_environment e path
c <- liftIO $ readIORef cio
r <- get_result
put c
put_result r
-- | call-with-current-continuation: create a new continuation and add it to a new arg list
call_cc :: Code -> DelveM ( )
call_cc code = do
st <- get
ca <- fmap ContAddr $ liftIO $ newIORef st
push_arg ca 0
push_code code
-- | Jump to the continuation referenced by the symbol in the current object
jump_obj :: [ Symbol ] -> DelveM ( )
jump_obj path = do
o <- get_current_object_ref
cio <- fmap get_cont $ find_addr path $ ObjAddr o
c <- liftIO $ readIORef cio
r <- get_result
put c
put_result r
-- | Initialize the state of the virtual machine
new_delve_state :: Code -> IO DState
new_delve_state c = do
act_stack <- new_activation_stack
arg_group <- new_arg_group 255
return $ DState {
activation_stack = act_stack
, result = Nothing
, code = c
, args = arg_group
}
-- | Create a new activation stack
new_activation_stack :: IO ActivationStack
new_activation_stack = do
os <- new_object_stack
le <- new_local_environment_stack
let act_ref = ActivationFrame os le
return [ act_ref ]
-- | Create a new object stack
new_object_stack :: IO ObjectStack
new_object_stack = do
o_ref <- new_object
return [ o_ref ]
-- | create a new object
new_object :: IO ( IORef Object )
new_object = do
let new_o = Object M.empty
newIORef new_o
-- | create a new local environment
new_local_environment :: IO ( IORef LocalEnv )
new_local_environment = do
let new_env = LocalEnv M.empty
newIORef new_env
-- | create a new local environment stack
new_local_environment_stack :: IO LocalEnvStack
new_local_environment_stack = do
env_ref <- new_local_environment
return [ env_ref ]
-- | Evaluate Delve
eval :: DelveM ( )
eval = do
me <- pop_expression
maybe ( return ( ) )
( \ e -> do
-- liftIO $ putStrLn $ "expr: " L.++ show e
eval_expr e
-- liftIO $ putStrLn "evaluated"
eval
)
me
-- | Pop an expression from the code
pop_expression :: DelveM ( Maybe Expr )
pop_expression = do
rst <- get
case code rst of
[ ] -> return Nothing
( c : rest ) -> do
put $ rst { code = rest }
return $ Just c
-- | The address of a new object
new_object_addr :: DelveM Addr
new_object_addr =
fmap ObjAddr $ liftIO new_object
-- | Get the address referenced by the symbol in the current object
| trigger a fatal error otherwise ( Delve is well - typed , so this should never happen unless you 're hacking the VM )
lookup_current_object :: [ Symbol ] -> DelveM Addr
lookup_current_object path@( _ : _ ) = do
o <- get_current_object_ref
-- liftIO $ putStrLn $ "Looking up: " L.++ show path
find_addr path $ ObjAddr o
lookup_current_object _ =
delve_error "Tried to look up current object with no path"
-- | Find the symbol in the object, looking up the superclass if it is not in the subclass
find_obj_sym :: Object -> Symbol -> DelveM Addr
find_obj_sym o s = do
-- liftIO $ putStrLn $ "find_obj_sym: " L.++ show s
-- liftIO $ putStrLn $ "members of object: " L.++ show ( M.keys $ members o )
-- let a = irrefutible_lookup s $ members o
-- case a of
ObjAddr _ - > liftIO $ putStrLn " Aaaargh ! "
liftIO $ putStrLn " yay "
maybe ( do let clsio = get_object $ irrefutible_lookup class_sym $ members o
cls <- liftIO $ readIORef clsio
search_classes cls s
)
return
$ M.lookup s ( members o )
-- The symbol for \"class\"
class_sym :: Symbol
class_sym = B.pack "class"
-- | An irrefutible symbol lookup in a map
irrefutible_lookup :: Symbol -> Members -> Addr
irrefutible_lookup s m =
fromMaybe ( symbol_error s )
$ M.lookup s m
| Search a class and its superclasses for a symbol
search_classes :: Object -> Symbol -> DelveM Addr
search_classes c s = do
-- liftIO $ putStrLn $ "members of class: " L.++ show ( M.keys $ members c )
let insio = get_object $ irrefutible_lookup methods_sym $ members c
ins <- liftIO $ readIORef insio
maybe find_in_parent
return
$ M.lookup s $ members ins
where
methods_sym = B.pack "instance_methods"
super_sym = B.pack "super"
find_in_parent = do
let superio = get_object $ irrefutible_lookup super_sym $ members c
super <- liftIO $ readIORef superio
search_classes super s
-- | Display an error message
delve_error msg =
error $ "The possible happened!\n" L.++ msg L.++ "\nUnless you were hacking on the Delve Virtual Machine, please submit the code that caused this as a bug report to <>"
-- | Symbol error
symbol_error :: Symbol -> a
symbol_error sym =
delve_error $ "Delve tried to look up '" L.++ B.unpack sym L.++ "', which wasn't there."
-- | Get the local environment stack
get_local_env :: DelveM LocalEnvStack
get_local_env = do
ActivationFrame _ local_env_stack <- get_activation_frame
return local_env_stack
-- | Get the current activation frame
get_activation_frame :: DelveM ActivationFrame
get_activation_frame = do
rst <- get
return $ L.head $ activation_stack rst
-- | Get the current object
get_current_object :: DelveM Object
get_current_object = do
cobject_ref <- get_current_object_ref
liftIO $ readIORef cobject_ref
-- | Get a reference to the current object
get_current_object_ref :: DelveM ( IORef Object )
get_current_object_ref = do
ActivationFrame object_stack _ <- get_activation_frame
return $ L.head object_stack
-- create a new code block wrapped in a reference
new_code_block :: Code -> DelveM ( IORef CodeBlock )
new_code_block =
liftIO . newIORef . CodeBlock ( MemoryFrame Nothing Nothing )
-- create an address for a block of code
new_code_addr :: Code -> DelveM Addr
new_code_addr =
fmap CodeAddr . new_code_block
-- create an address for a new primative value
new_prim_addr :: Prim -> DelveM Addr
new_prim_addr =
fmap PrimAddr . liftIO . newIORef
-- get the referece to a code block from an address
get_code_block :: Addr -> IORef CodeBlock
get_code_block a =
case a of
CodeAddr cb -> cb
_ -> delve_error "Could not find code at address"
-- get the current object stack
get_objects :: DelveM ObjectStack
get_objects = do
ActivationFrame os _ <- get_activation_frame
return os
-- add a local environment to a memory frame
add_local_frame :: LocalEnvStack -> CodeBlock -> CodeBlock
add_local_frame !les !( CodeBlock ( MemoryFrame os _ ) code ) =
CodeBlock ( MemoryFrame os $ Just les ) code
-- add an object stack to a memory frame
add_object_frame :: IORef Object -> CodeBlock -> CodeBlock
add_object_frame !os !( CodeBlock ( MemoryFrame _ les ) code ) =
CodeBlock ( MemoryFrame ( Just os ) les ) code
-- set the activation frame on an address to remember the current objects
remember_objects :: Addr -> DelveM ( )
remember_objects a = do
let f = get_code_block a
obj <- fmap L.head get_objects
liftIO $ modifyIORef f ( add_object_frame obj )
-- get the local environment stack
get_local_stack :: DelveM LocalEnvStack
get_local_stack = do
ActivationFrame _ les <- get_activation_frame
return les
-- set the activation frame on an address to remember the current local scope
remember_local :: Addr -> DelveM ( )
remember_local a = do
let f = get_code_block a
frame <- get_local_stack
liftIO $ modifyIORef f $ add_local_frame frame
-- get the memory frame associated with an address
get_address_frame :: Addr -> DelveM MemoryFrame
get_address_frame a = do
let iof = get_code_block a
CodeBlock fr _ <- liftIO $ readIORef iof
return fr
-- index a list safely
safe_index l i =
if L.length l <= i
then Nothing
else Just $ l L.!! i
-- push a new activation frame to the top of the activation frame stack
-- use the given activation frame there when trying to remember stuff the memory frame has not noted
push_activation_frame :: ActivationFrame -> MemoryFrame -> DelveM ( )
push_activation_frame (ActivationFrame last_os last_les ) ( MemoryFrame mos mles ) = do
let mfr = ( do os <- mos
les <- mles
Just $ ActivationFrame [ os ] les ) <|> ( do os <- mos
Just $ ActivationFrame [ os ] last_les ) <|> ( do les <- mles
Just $ ActivationFrame [ L.head $ last_os ] les )
f = fromMaybe id $ mfr >>= ( \ fr -> Just ( \ stack -> fr : stack ) )
modify $ \ dst -> dst { activation_stack = f $ activation_stack dst }
-- push an address onto the argument stack at the given index
push_arg :: Addr -> Word8 -> DelveM ( )
push_arg !a !w = do
arr <- fmap args get
liftIO $ writeArray arr w a
-- assign a symbol in the local environment to refer to an address
assign_local :: IORef LocalEnv -> [ Symbol ] -> Symbol -> Addr -> DelveM ( )
assign_local leio path sym addr = do
eenva <- find_addr_local leio path
liftIO $ either ( const $ return ( ) )
( \ a - > case a of
ObjAddr _ - > putStrLn " It 's an obj "
putStrLn " It 's code "
_ - > putStrLn " Some other shit "
) eenva
( \ a -> case a of
ObjAddr _ -> putStrLn "It's an obj"
CodeAddr _ -> putStrLn "It's code"
_ -> putStrLn "Some other shit"
) eenva -}
liftIO $ either ( \ ! envio -> modifyIORef envio $ \ ! le -> LocalEnv $ M.insert sym addr $ env le )
( ( \ ! obio -> modifyIORef obio $ \ ! o -> Object $ M.insert sym addr $ members o ) . get_object )
eenva
-- find an object from a path of object references, beginning in the local scope, or returning the local scope if there is no path
find_addr_local :: IORef LocalEnv -> [ Symbol ] -> DelveM ( Either ( IORef LocalEnv ) Addr )
find_addr_local leio [ ] = do
liftIO $ B.putStrLn $ B.pack " lookup up symbol : " ` B.append ` sym
return $ Left leio
find_addr_local leio ( s : ss ) = do
le <- liftIO $ readIORef leio
let ob = irrefutible_lookup s $ env le
if L.null ss
then return $ Right ob
else do
r <- find_addr ss ob
return $ Right r
-- assign a symbol to refer to an address in the object refered to by the path
assign_object :: [ Symbol ] -> Symbol -> Addr -> DelveM ( )
assign_object path sym addr = do
ActivationFrame ( oio : _ ) _ <- get_activation_frame
obio <- fmap get_object $ find_addr path $ ObjAddr oio
liftIO $ modifyIORef obio $ ( \ ! o -> Object $ M.insert sym addr $ members o )
-- find the object at the end of the path of object references
find_addr :: [ Symbol ] -> Addr -> DelveM Addr
find_addr ( s : ss ) addr = do
o <- liftIO $ readIORef $ get_object addr
-- liftIO $ putStrLn "Finding addr"
new_addr <- find_obj_sym o s
find_addr ss new_addr
find_addr _ addr = do
-- liftIO $ putStrLn "Not bothering"
return addr
-- get the last result, triggering an error if it has not been set
get_result :: DelveM Addr
get_result = do
rst <- get
case result rst of
!mr -> return $ fromMaybe ( delve_error "Result was not set" )
mr
-- get an object from an address
get_object :: Addr -> IORef Object
get_object a =
case a of
ObjAddr o -> o
_ -> delve_error "Address did not point to an object"
-- get a primative from an address
get_prim :: Addr -> IORef Prim
get_prim a =
case a of
PrimAddr p -> p
_ -> delve_error "Address did not point to a primative"
-- push an object onto the object stack so it becomes the current object
push_object :: IORef Object -> DelveM ( )
push_object o =
modify_frame $ \ fr -> fr { object_stack = o : object_stack fr }
-- change the current top activation frame
modify_frame :: ( ActivationFrame -> ActivationFrame ) -> DelveM ( )
modify_frame !f = do
dst <- get
let stack = activation_stack dst
put $ dst { activation_stack = ( f $ L.head stack ) : L.tail stack }
-- pop an object from the top of the object stack
pop_object :: DelveM ( )
pop_object = do
modify_frame $ \ fr -> fr { object_stack = L.tail $ object_stack fr }
-- add a piece of code from a code block into the machine
push_code_block :: CodeBlock -> DelveM ( )
push_code_block ( CodeBlock _ new_code ) =
push_code new_code
-- add a piece of code into the machine
push_code :: Code -> DelveM ( )
push_code new_code = do
dst <- get
put $ dst { code = new_code L.++ code dst }
-- push an empty local environment into the local environment stack
push_local :: DelveM ( )
push_local = do
new_env <- liftIO $ new_local_environment
modify_frame $ \ ! fr -> fr { local_env = new_env : local_env fr }
-- pop a local environment from the local environment stack
pop_local :: DelveM ( )
pop_local =
modify_frame $ \ ! fr -> fr { local_env = L.tail $ local_env fr }
Match the symbol given to one of the alternatives , and push the matched code onto the code stack
match :: Symbol -> Alternatives -> DelveM ( )
match !sym !alts = do
let !m_match = L.find ( ( == ) sym . fst ) alts
default_match = L.find ( (==) ( B.pack "default" ) . fst ) alts
new_code = fromMaybe ( delve_error "No case alternative matches." )
$ ( m_match >>= Just . snd ) <|> ( default_match >>= Just . snd )
push_code new_code
-- Get the symbol reference from an address
get_symbol :: Addr -> IORef Symbol
get_symbol a =
case a of
SymbolAddr s -> s
_ -> delve_error "Address did not point to a symbol"
-- set the result to an address
put_result :: Addr -> DelveM ( )
put_result a = do
dst <- get
put $ dst { result = Just a }
-- get the argument at the index
get_arg :: Word8 -> DelveM Addr
get_arg i = do
arg_group <- fmap args get
liftIO $ E.catch ( readArray arg_group i )
argument_exception
where
argument_exception :: ArrayException -> IO Addr
argument_exception = const $ delve_error "Function had less arguments than expected"
get_current_env :: DelveM ( IORef LocalEnv )
get_current_env =
fmap ( L.head . local_env . L.head . activation_stack ) get
-- Error when a path is not provided, when attempting to remember local data
local_memory_error =
delve_error "Local environment could not be saved as the target object was non-existant"
-- pop the current activation frame from the stack
pop_activation_frame :: DelveM ActivationFrame
pop_activation_frame = do
rst <- get
put $ rst { activation_stack = L.tail $ activation_stack rst }
return $ L.head $ activation_stack rst
-- a new empty argument group
new_arg_group :: Word8 -> IO ArgGroup
new_arg_group size =
newArray_ ( 0 , size - 1 )
-- get the continuation from an address
get_cont :: Addr -> IORef Continuation
get_cont a =
case a of
ContAddr c -> c
_ -> delve_error "Address did not point to a continuation"
-- find a variable in the environment at this depth
lookup_local_env :: Int -> [ Symbol ] -> DelveM Addr
lookup_local_env depth ( sym : path ) = do
envio <- get_environment_at depth
envi <- liftIO $ readIORef envio
let target = irrefutible_lookup sym $ env envi
find_addr path target
lookup_local_env _ _ =
delve_error "Tried to perform lookup in local environment with non-existant path"
-- get the environment at the given depth on the environment stack
get_environment_at :: Int -> DelveM ( IORef LocalEnv )
get_environment_at depth = do
les <- get_local_env
let mev = safe_index les depth
ev = fromMaybe ( delve_error "Tried to look up variable in non-existant local environment" ) mev
return ev
-- search the environment for the variable described by the path, fail if it is not found
search_environment :: IORef LocalEnv -> [ Symbol ] -> DelveM Addr
search_environment e path = do
ela <- find_addr_local e path
either ( const $ symbol_error $ render_path path )
return
$ ela
| null | https://raw.githubusercontent.com/elginer/Delve/997c25d2c43ac3ab06f7d70304a59f4a8d5f9670/src/DelveVM.hs | haskell | The virtual machine for the delve programming language
# OPTIONS -XBangPatterns #
hiding ( newIORef , modifyIORef , readIORef , writeIORef )
import qualified Data.IORef as I ( newIORef , modifyIORef , readIORef , writeIORef )
SHOULD THESE EVEN BE STRICT ! ! ? !
a strict version of ' newIORef '
a strict version of ' modifyIORef '
a strict version of ' readIORef '
SHOULD THESE EVEN BE STRICT!!?!
a strict version of 'newIORef'
a strict version of 'modifyIORef'
a strict version of 'readIORef'
| Add a new object to the heap and store the address in the result slot
| Add a new primative to the heap and store the address in the result slot
This function ( eval_expr ) is plainly ridiculous. It needs to become a type class!
| Evaluate an expression
create a new object
add a new block of code to the heap and store the address in the result slot
set the result address to this symbol in current object
set the result address to this symbol in the local environment
create a new primative
associate the current object stack with this symbol in the current object
associate the current object stack with this symbol in the local scope
associate the current local environment with this symbol in the current object
associate the current local environment with this symbol in the local scope
push the activation frame associated with the code block refered to by the symbol in the current object on the top of the activation stack
push the activation frame associated with the code block refered to by the symbol in the local environment to the top of the activation stack
pop the current activation frame from the stack
Push the address referred to by the symbol in the current object on to the argument stack
Push the address referred to by the symbol in the local environment on to the argument stack
Set the argument at the index ( which should be counted from the other end, it's more efficient to work backwards ) in the current argument list equal to the symbol in the local environment
Read the address in the result slot, and set a mapping between the symbol and this address in the local environment
Read the address in the result slot, and set a mapping between the symbol and this address in the object at the end of the chain of object references
Add the object refered to by the symbol in the current object to the top of the object stack ( it becomes the current object )
Add the object refered to by the symbol in the local environment to the top of the object stack ( it becomes the current object )
Pop an object from the top of the current object stack
Call the code refered to by the symbol in the current object by concatenating it with the rest of the executing code
liftIO $ putStrLn "gonna lookup"
liftIO $ do putStrLn "lookup up object"
case a of
Call the code refred to by the symbol in the current local environment by concatenating it with the rest of the executing code
Add a new empty local scope to the local environment stack
Pop the last local scope from the environment stack
Perform an arbitrary machine instruction
A symbolic pattern match, comparing the symbol at the address referenced by symbol in the local environment to one of the alternatives
move the current object into the return slot
Tail call the code refered to by the symbol in the current object by concatenating it with the rest of the executing code and popping the local scope before it is executed
Call the code refered to by the symbol in the current local environment by concatenating it with the rest of the executing code and popping the local scope before it is executed -- pop the current object if the flag is set
I think there's a bit of in consistancy here...
Call the code referred to by the symbol in the current local environment by concatenating it with the rest of the executing code and popping the activation frame before it is executed
Call the code referred to by the symbol in the current object by concatenating it with the rest of the executing code and popping the activation frame before it is executed
assign space for a new symbol and set the result to this address
call-with-current-continuation:
Jump to the continuation referenced by the symbol in the current object
Jump to the continuation referenced by the symbol in the local environment
Jump to the continuation referenced by the symbol in the local environment
| call-with-current-continuation: create a new continuation and add it to a new arg list
| Jump to the continuation referenced by the symbol in the current object
| Initialize the state of the virtual machine
| Create a new activation stack
| Create a new object stack
| create a new object
| create a new local environment
| create a new local environment stack
| Evaluate Delve
liftIO $ putStrLn $ "expr: " L.++ show e
liftIO $ putStrLn "evaluated"
| Pop an expression from the code
| The address of a new object
| Get the address referenced by the symbol in the current object
liftIO $ putStrLn $ "Looking up: " L.++ show path
| Find the symbol in the object, looking up the superclass if it is not in the subclass
liftIO $ putStrLn $ "find_obj_sym: " L.++ show s
liftIO $ putStrLn $ "members of object: " L.++ show ( M.keys $ members o )
let a = irrefutible_lookup s $ members o
case a of
The symbol for \"class\"
| An irrefutible symbol lookup in a map
liftIO $ putStrLn $ "members of class: " L.++ show ( M.keys $ members c )
| Display an error message
| Symbol error
| Get the local environment stack
| Get the current activation frame
| Get the current object
| Get a reference to the current object
create a new code block wrapped in a reference
create an address for a block of code
create an address for a new primative value
get the referece to a code block from an address
get the current object stack
add a local environment to a memory frame
add an object stack to a memory frame
set the activation frame on an address to remember the current objects
get the local environment stack
set the activation frame on an address to remember the current local scope
get the memory frame associated with an address
index a list safely
push a new activation frame to the top of the activation frame stack
use the given activation frame there when trying to remember stuff the memory frame has not noted
push an address onto the argument stack at the given index
assign a symbol in the local environment to refer to an address
find an object from a path of object references, beginning in the local scope, or returning the local scope if there is no path
assign a symbol to refer to an address in the object refered to by the path
find the object at the end of the path of object references
liftIO $ putStrLn "Finding addr"
liftIO $ putStrLn "Not bothering"
get the last result, triggering an error if it has not been set
get an object from an address
get a primative from an address
push an object onto the object stack so it becomes the current object
change the current top activation frame
pop an object from the top of the object stack
add a piece of code from a code block into the machine
add a piece of code into the machine
push an empty local environment into the local environment stack
pop a local environment from the local environment stack
Get the symbol reference from an address
set the result to an address
get the argument at the index
Error when a path is not provided, when attempting to remember local data
pop the current activation frame from the stack
a new empty argument group
get the continuation from an address
find a variable in the environment at this depth
get the environment at the given depth on the environment stack
search the environment for the variable described by the path, fail if it is not found |
The Delve Programming Language
Copyright 2009
Distributed under the terms of the GNU General Public License v3 , or ( at your option ) any later version .
This file is part of Delve .
Delve 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 .
Delve 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 Delve . If not , see < / > .
The Delve Programming Language
Copyright 2009 John Morrice
Distributed under the terms of the GNU General Public License v3, or ( at your option ) any later version.
This file is part of Delve.
Delve 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.
Delve 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 Delve. If not, see </>.
-}
module DelveVM
( module Control.Monad.State.Strict
, module Data.Maybe
, module Data.Word
, eval
, DState ( .. )
, ActivationFrame ( .. )
, Object ( .. )
, LocalEnv ( .. )
, Expr ( .. )
, get_object
, get_current_object_ref
, get_arg
, push_code
, get_prim
, get_symbol
, get_cont
, get_code_block
, run_delve
, lookup_current_object
, lookup_local_env
, get_activation_frame
, get_current_object
, get_result
, irrefutible_lookup
, put_result
, new
, new_prim
, call_cc
, jump_local
, jump_obj
, newIORef
, modifyIORef
, readIORef
)
where
import DMachineState
import Control.Monad.State.Strict
import Control.Applicative
import Control.Exception as E
import Control.Monad.Stream as C
import Data.List.Stream as L
import Data.Word
import Data.IORef
import qualified Data.Map as M
import Data.Maybe
import qualified Data.ByteString.Char8 as B
import Data.Array.IO
newIORef : : a - > IO ( IORef a )
newIORef ! x = I.newIORef x
modifyIORef : : IORef a - > ( a - > a ) - > IO ( )
modifyIORef ! ref ! f = do
a < - readIORef
let new_a = f $ ! a
case new_a of
! forced_a - > writeIORef ref forced_a
writeIORef : : IORef a - > a - > IO ( )
writeIORef ! ref ! a =
I.writeIORef ref a
readIORef : : IORef a - > IO a
readIORef ref = do
a < - I.readIORef ref
case a of
! stuff - > return stuff
newIORef :: a -> IO ( IORef a )
newIORef !x = I.newIORef x
modifyIORef :: IORef a -> ( a -> a ) -> IO ( )
modifyIORef !ref !f = do
a <- readIORef
let new_a = f $! a
case new_a of
!forced_a -> writeIORef ref forced_a
writeIORef :: IORef a -> a -> IO ( )
writeIORef !ref !a =
I.writeIORef ref a
readIORef :: IORef a -> IO a
readIORef ref = do
a <- I.readIORef ref
case a of
!stuff -> return stuff
-}
Run a Delve program
run_delve :: Code -> IO ( )
run_delve code = do
new_delve_state code >>= runStateT eval
return ( )
new :: DelveM ( )
new = do
o <- new_object_addr
put_result o
new_prim :: Prim -> DelveM ( )
new_prim prim = do
prim_addr <- new_prim_addr prim
put_result prim_addr
eval_expr :: Expr -> DelveM ( )
eval_expr New =
new
eval_expr ( NewBlock code ) = do
c_addr <- new_code_addr code
put_result c_addr
eval_expr ( RefObj path ) = do
a <- lookup_current_object path
put_result a
eval_expr ( RefLocal depth path ) = do
e <- get_environment_at depth
a <- search_environment e path
put_result a
eval_expr ( NewPrim prim ) =
new_prim prim
eval_expr ( RememberObjObj path ) = do
a <- lookup_current_object path
remember_objects a
eval_expr ( RememberObjLocal depth path ) = do
le <- get_environment_at depth
ela <- find_addr_local le path
either ( const $ local_memory_error )
remember_objects
ela
eval_expr ( RememberLocalObj path ) = do
a <- lookup_current_object path
remember_local a
eval_expr ( RememberLocalLocal depth path ) = do
le <- get_environment_at depth
ela <- find_addr_local le path
either ( const $ local_memory_error )
remember_local
ela
eval_expr ( PushFrameObj path ) = do
a <- lookup_current_object path
fr <- get_address_frame a
vat <- get_activation_frame
push_activation_frame vat fr
eval_expr ( PushFrameLocal depth path ) = do
e <- get_environment_at depth
a <- search_environment e path
fr <- get_address_frame a
vat <- get_activation_frame
push_activation_frame vat fr
eval_expr PopFrame = do
pop_activation_frame
return ( )
eval_expr ( PushObjArg path w ) = do
a <- lookup_current_object path
push_arg a w
eval_expr ( PushLocalArg depth path w ) = do
e <- get_environment_at depth
a <- search_environment e path
push_arg a w
eval_expr ( WriteArg i sym ) = do
arg <- get_arg i
le <- get_current_env
assign_local le [ ] sym arg
eval_expr ( AssignLocal depth path sym ) = do
a <- get_result
ev <- get_environment_at depth
assign_local ev path sym a
eval_expr ( AssignObject path sym ) = do
a <- get_result
assign_object path sym a
eval_expr (LoadObj path ) = do
o <- get_current_object_ref
a <- find_addr path $ ObjAddr o
let o = get_object a
push_object o
eval_expr ( LoadLocal depth path ) = do
e <- get_environment_at depth
a <- search_environment e path
let o = get_object a
push_object o
eval_expr PopObject =
pop_object
eval_expr ( CallObj sym ) = do
o <- get_current_object
a <- lookup_current_object sym
_ - > putStrLn " got summink "
let cbio = get_code_block a
cb <- liftIO $ readIORef cbio
push_code_block cb
vat <- get_activation_frame
push_activation_frame vat $ memory_frame cb
eval_expr ( CallLocal depth path ) = do
a <- lookup_local_env depth path
let cbio = get_code_block a
cb <- liftIO $ readIORef cbio
push_code_block cb
vat <- get_activation_frame
push_activation_frame vat $ memory_frame cb
eval_expr PushLocal = do
push_local
eval_expr PopLocal = do
pop_local
eval_expr ( MachineInstruction command ) =
command
A symbolic pattern match , comparing the symbol at the address referenced by symbol in the current object to one of the alternatives
eval_expr ( MatchObj path alts ) = do
o <- get_current_object_ref
a <- find_addr path $ ObjAddr o
sym <- liftIO $ readIORef $ get_symbol a
match sym alts
eval_expr ( MatchLocal depth path alts ) = do
e <- get_environment_at depth
a <- search_environment e path
sym <- liftIO $ readIORef $ get_symbol a
match sym alts
eval_expr RefSelf = do
o <- get_current_object_ref
o2 <- get_current_object
put_result $ ObjAddr o
eval_expr ( LocalTailCallObj pop sym ) = do
a <- lookup_current_object sym
let cbio = get_code_block a
cb <- liftIO $ readIORef cbio
fr <- get_address_frame a
vat <- get_activation_frame
pop_local
C.when pop pop_object
push_activation_frame vat fr
push_code_block cb
eval_expr ( LocalTailCallLocal pop depth sym ) = do
a <- lookup_local_env depth sym
let cbio = get_code_block a
cb <- liftIO $ readIORef cbio
fr <- get_address_frame a
vat <- get_activation_frame
pop_local
C.when pop pop_object
push_activation_frame vat fr
push_code_block cb
eval_expr ( FrameTailCallLocal depth sym ) = do
a <- lookup_local_env depth sym
let cbio = get_code_block a
cb <- liftIO $ readIORef cbio
fr <- get_address_frame a
vat <- pop_activation_frame
push_activation_frame vat fr
push_code_block cb
eval_expr ( FrameTailCallObj sym ) = do
a <- lookup_current_object sym
let cbio = get_code_block a
cb <- liftIO $ readIORef cbio
fr <- get_address_frame a
vat <- pop_activation_frame
push_activation_frame vat fr
push_code_block cb
eval_expr ( NewSymbol sym ) = do
sym_addr <- fmap SymbolAddr $ liftIO $ newIORef sym
put_result sym_addr
eval_expr ( CallCC code ) =
call_cc code
eval_expr ( JumpObj path ) =
jump_obj path
eval_expr ( JumpLocal depth path ) =
jump_local depth path
jump_local :: Int -> [ Symbol ] -> DelveM ( )
jump_local depth path = do
e <- get_environment_at depth
cio <- fmap get_cont $ search_environment e path
c <- liftIO $ readIORef cio
r <- get_result
put c
put_result r
call_cc :: Code -> DelveM ( )
call_cc code = do
st <- get
ca <- fmap ContAddr $ liftIO $ newIORef st
push_arg ca 0
push_code code
jump_obj :: [ Symbol ] -> DelveM ( )
jump_obj path = do
o <- get_current_object_ref
cio <- fmap get_cont $ find_addr path $ ObjAddr o
c <- liftIO $ readIORef cio
r <- get_result
put c
put_result r
new_delve_state :: Code -> IO DState
new_delve_state c = do
act_stack <- new_activation_stack
arg_group <- new_arg_group 255
return $ DState {
activation_stack = act_stack
, result = Nothing
, code = c
, args = arg_group
}
new_activation_stack :: IO ActivationStack
new_activation_stack = do
os <- new_object_stack
le <- new_local_environment_stack
let act_ref = ActivationFrame os le
return [ act_ref ]
new_object_stack :: IO ObjectStack
new_object_stack = do
o_ref <- new_object
return [ o_ref ]
new_object :: IO ( IORef Object )
new_object = do
let new_o = Object M.empty
newIORef new_o
new_local_environment :: IO ( IORef LocalEnv )
new_local_environment = do
let new_env = LocalEnv M.empty
newIORef new_env
new_local_environment_stack :: IO LocalEnvStack
new_local_environment_stack = do
env_ref <- new_local_environment
return [ env_ref ]
eval :: DelveM ( )
eval = do
me <- pop_expression
maybe ( return ( ) )
( \ e -> do
eval_expr e
eval
)
me
pop_expression :: DelveM ( Maybe Expr )
pop_expression = do
rst <- get
case code rst of
[ ] -> return Nothing
( c : rest ) -> do
put $ rst { code = rest }
return $ Just c
new_object_addr :: DelveM Addr
new_object_addr =
fmap ObjAddr $ liftIO new_object
| trigger a fatal error otherwise ( Delve is well - typed , so this should never happen unless you 're hacking the VM )
lookup_current_object :: [ Symbol ] -> DelveM Addr
lookup_current_object path@( _ : _ ) = do
o <- get_current_object_ref
find_addr path $ ObjAddr o
lookup_current_object _ =
delve_error "Tried to look up current object with no path"
find_obj_sym :: Object -> Symbol -> DelveM Addr
find_obj_sym o s = do
ObjAddr _ - > liftIO $ putStrLn " Aaaargh ! "
liftIO $ putStrLn " yay "
maybe ( do let clsio = get_object $ irrefutible_lookup class_sym $ members o
cls <- liftIO $ readIORef clsio
search_classes cls s
)
return
$ M.lookup s ( members o )
class_sym :: Symbol
class_sym = B.pack "class"
irrefutible_lookup :: Symbol -> Members -> Addr
irrefutible_lookup s m =
fromMaybe ( symbol_error s )
$ M.lookup s m
| Search a class and its superclasses for a symbol
search_classes :: Object -> Symbol -> DelveM Addr
search_classes c s = do
let insio = get_object $ irrefutible_lookup methods_sym $ members c
ins <- liftIO $ readIORef insio
maybe find_in_parent
return
$ M.lookup s $ members ins
where
methods_sym = B.pack "instance_methods"
super_sym = B.pack "super"
find_in_parent = do
let superio = get_object $ irrefutible_lookup super_sym $ members c
super <- liftIO $ readIORef superio
search_classes super s
delve_error msg =
error $ "The possible happened!\n" L.++ msg L.++ "\nUnless you were hacking on the Delve Virtual Machine, please submit the code that caused this as a bug report to <>"
symbol_error :: Symbol -> a
symbol_error sym =
delve_error $ "Delve tried to look up '" L.++ B.unpack sym L.++ "', which wasn't there."
get_local_env :: DelveM LocalEnvStack
get_local_env = do
ActivationFrame _ local_env_stack <- get_activation_frame
return local_env_stack
get_activation_frame :: DelveM ActivationFrame
get_activation_frame = do
rst <- get
return $ L.head $ activation_stack rst
get_current_object :: DelveM Object
get_current_object = do
cobject_ref <- get_current_object_ref
liftIO $ readIORef cobject_ref
get_current_object_ref :: DelveM ( IORef Object )
get_current_object_ref = do
ActivationFrame object_stack _ <- get_activation_frame
return $ L.head object_stack
new_code_block :: Code -> DelveM ( IORef CodeBlock )
new_code_block =
liftIO . newIORef . CodeBlock ( MemoryFrame Nothing Nothing )
new_code_addr :: Code -> DelveM Addr
new_code_addr =
fmap CodeAddr . new_code_block
new_prim_addr :: Prim -> DelveM Addr
new_prim_addr =
fmap PrimAddr . liftIO . newIORef
get_code_block :: Addr -> IORef CodeBlock
get_code_block a =
case a of
CodeAddr cb -> cb
_ -> delve_error "Could not find code at address"
get_objects :: DelveM ObjectStack
get_objects = do
ActivationFrame os _ <- get_activation_frame
return os
add_local_frame :: LocalEnvStack -> CodeBlock -> CodeBlock
add_local_frame !les !( CodeBlock ( MemoryFrame os _ ) code ) =
CodeBlock ( MemoryFrame os $ Just les ) code
add_object_frame :: IORef Object -> CodeBlock -> CodeBlock
add_object_frame !os !( CodeBlock ( MemoryFrame _ les ) code ) =
CodeBlock ( MemoryFrame ( Just os ) les ) code
remember_objects :: Addr -> DelveM ( )
remember_objects a = do
let f = get_code_block a
obj <- fmap L.head get_objects
liftIO $ modifyIORef f ( add_object_frame obj )
get_local_stack :: DelveM LocalEnvStack
get_local_stack = do
ActivationFrame _ les <- get_activation_frame
return les
remember_local :: Addr -> DelveM ( )
remember_local a = do
let f = get_code_block a
frame <- get_local_stack
liftIO $ modifyIORef f $ add_local_frame frame
get_address_frame :: Addr -> DelveM MemoryFrame
get_address_frame a = do
let iof = get_code_block a
CodeBlock fr _ <- liftIO $ readIORef iof
return fr
safe_index l i =
if L.length l <= i
then Nothing
else Just $ l L.!! i
push_activation_frame :: ActivationFrame -> MemoryFrame -> DelveM ( )
push_activation_frame (ActivationFrame last_os last_les ) ( MemoryFrame mos mles ) = do
let mfr = ( do os <- mos
les <- mles
Just $ ActivationFrame [ os ] les ) <|> ( do os <- mos
Just $ ActivationFrame [ os ] last_les ) <|> ( do les <- mles
Just $ ActivationFrame [ L.head $ last_os ] les )
f = fromMaybe id $ mfr >>= ( \ fr -> Just ( \ stack -> fr : stack ) )
modify $ \ dst -> dst { activation_stack = f $ activation_stack dst }
push_arg :: Addr -> Word8 -> DelveM ( )
push_arg !a !w = do
arr <- fmap args get
liftIO $ writeArray arr w a
assign_local :: IORef LocalEnv -> [ Symbol ] -> Symbol -> Addr -> DelveM ( )
assign_local leio path sym addr = do
eenva <- find_addr_local leio path
liftIO $ either ( const $ return ( ) )
( \ a - > case a of
ObjAddr _ - > putStrLn " It 's an obj "
putStrLn " It 's code "
_ - > putStrLn " Some other shit "
) eenva
( \ a -> case a of
ObjAddr _ -> putStrLn "It's an obj"
CodeAddr _ -> putStrLn "It's code"
_ -> putStrLn "Some other shit"
) eenva -}
liftIO $ either ( \ ! envio -> modifyIORef envio $ \ ! le -> LocalEnv $ M.insert sym addr $ env le )
( ( \ ! obio -> modifyIORef obio $ \ ! o -> Object $ M.insert sym addr $ members o ) . get_object )
eenva
find_addr_local :: IORef LocalEnv -> [ Symbol ] -> DelveM ( Either ( IORef LocalEnv ) Addr )
find_addr_local leio [ ] = do
liftIO $ B.putStrLn $ B.pack " lookup up symbol : " ` B.append ` sym
return $ Left leio
find_addr_local leio ( s : ss ) = do
le <- liftIO $ readIORef leio
let ob = irrefutible_lookup s $ env le
if L.null ss
then return $ Right ob
else do
r <- find_addr ss ob
return $ Right r
assign_object :: [ Symbol ] -> Symbol -> Addr -> DelveM ( )
assign_object path sym addr = do
ActivationFrame ( oio : _ ) _ <- get_activation_frame
obio <- fmap get_object $ find_addr path $ ObjAddr oio
liftIO $ modifyIORef obio $ ( \ ! o -> Object $ M.insert sym addr $ members o )
find_addr :: [ Symbol ] -> Addr -> DelveM Addr
find_addr ( s : ss ) addr = do
o <- liftIO $ readIORef $ get_object addr
new_addr <- find_obj_sym o s
find_addr ss new_addr
find_addr _ addr = do
return addr
get_result :: DelveM Addr
get_result = do
rst <- get
case result rst of
!mr -> return $ fromMaybe ( delve_error "Result was not set" )
mr
get_object :: Addr -> IORef Object
get_object a =
case a of
ObjAddr o -> o
_ -> delve_error "Address did not point to an object"
get_prim :: Addr -> IORef Prim
get_prim a =
case a of
PrimAddr p -> p
_ -> delve_error "Address did not point to a primative"
push_object :: IORef Object -> DelveM ( )
push_object o =
modify_frame $ \ fr -> fr { object_stack = o : object_stack fr }
modify_frame :: ( ActivationFrame -> ActivationFrame ) -> DelveM ( )
modify_frame !f = do
dst <- get
let stack = activation_stack dst
put $ dst { activation_stack = ( f $ L.head stack ) : L.tail stack }
pop_object :: DelveM ( )
pop_object = do
modify_frame $ \ fr -> fr { object_stack = L.tail $ object_stack fr }
push_code_block :: CodeBlock -> DelveM ( )
push_code_block ( CodeBlock _ new_code ) =
push_code new_code
push_code :: Code -> DelveM ( )
push_code new_code = do
dst <- get
put $ dst { code = new_code L.++ code dst }
push_local :: DelveM ( )
push_local = do
new_env <- liftIO $ new_local_environment
modify_frame $ \ ! fr -> fr { local_env = new_env : local_env fr }
pop_local :: DelveM ( )
pop_local =
modify_frame $ \ ! fr -> fr { local_env = L.tail $ local_env fr }
Match the symbol given to one of the alternatives , and push the matched code onto the code stack
match :: Symbol -> Alternatives -> DelveM ( )
match !sym !alts = do
let !m_match = L.find ( ( == ) sym . fst ) alts
default_match = L.find ( (==) ( B.pack "default" ) . fst ) alts
new_code = fromMaybe ( delve_error "No case alternative matches." )
$ ( m_match >>= Just . snd ) <|> ( default_match >>= Just . snd )
push_code new_code
get_symbol :: Addr -> IORef Symbol
get_symbol a =
case a of
SymbolAddr s -> s
_ -> delve_error "Address did not point to a symbol"
put_result :: Addr -> DelveM ( )
put_result a = do
dst <- get
put $ dst { result = Just a }
get_arg :: Word8 -> DelveM Addr
get_arg i = do
arg_group <- fmap args get
liftIO $ E.catch ( readArray arg_group i )
argument_exception
where
argument_exception :: ArrayException -> IO Addr
argument_exception = const $ delve_error "Function had less arguments than expected"
get_current_env :: DelveM ( IORef LocalEnv )
get_current_env =
fmap ( L.head . local_env . L.head . activation_stack ) get
local_memory_error =
delve_error "Local environment could not be saved as the target object was non-existant"
pop_activation_frame :: DelveM ActivationFrame
pop_activation_frame = do
rst <- get
put $ rst { activation_stack = L.tail $ activation_stack rst }
return $ L.head $ activation_stack rst
new_arg_group :: Word8 -> IO ArgGroup
new_arg_group size =
newArray_ ( 0 , size - 1 )
get_cont :: Addr -> IORef Continuation
get_cont a =
case a of
ContAddr c -> c
_ -> delve_error "Address did not point to a continuation"
lookup_local_env :: Int -> [ Symbol ] -> DelveM Addr
lookup_local_env depth ( sym : path ) = do
envio <- get_environment_at depth
envi <- liftIO $ readIORef envio
let target = irrefutible_lookup sym $ env envi
find_addr path target
lookup_local_env _ _ =
delve_error "Tried to perform lookup in local environment with non-existant path"
get_environment_at :: Int -> DelveM ( IORef LocalEnv )
get_environment_at depth = do
les <- get_local_env
let mev = safe_index les depth
ev = fromMaybe ( delve_error "Tried to look up variable in non-existant local environment" ) mev
return ev
search_environment :: IORef LocalEnv -> [ Symbol ] -> DelveM Addr
search_environment e path = do
ela <- find_addr_local e path
either ( const $ symbol_error $ render_path path )
return
$ ela
|
68f4061cf505c51e096207f6aea8844c030f4b1c626c75734ad0ae8d29c53d8b | ghc/packages-directory | RenamePath.hs | # LANGUAGE CPP #
module RenamePath where
#include "util.inl"
main :: TestEnv -> IO ()
main _t = do
createDirectory "a"
T(expectEq) () ["a"] =<< listDirectory "."
renamePath "a" "b"
T(expectEq) () ["b"] =<< listDirectory "."
writeFile tmp1 contents1
renamePath tmp1 tmp2
T(expectEq) () contents1 =<< readFile tmp2
writeFile tmp1 contents2
renamePath tmp2 tmp1
T(expectEq) () contents1 =<< readFile tmp1
where
tmp1 = "tmp1"
tmp2 = "tmp2"
contents1 = "test"
contents2 = "test2"
| null | https://raw.githubusercontent.com/ghc/packages-directory/75165a9d69bebba96e0e3a1e519ab481d1362dd2/tests/RenamePath.hs | haskell | # LANGUAGE CPP #
module RenamePath where
#include "util.inl"
main :: TestEnv -> IO ()
main _t = do
createDirectory "a"
T(expectEq) () ["a"] =<< listDirectory "."
renamePath "a" "b"
T(expectEq) () ["b"] =<< listDirectory "."
writeFile tmp1 contents1
renamePath tmp1 tmp2
T(expectEq) () contents1 =<< readFile tmp2
writeFile tmp1 contents2
renamePath tmp2 tmp1
T(expectEq) () contents1 =<< readFile tmp1
where
tmp1 = "tmp1"
tmp2 = "tmp2"
contents1 = "test"
contents2 = "test2"
| |
4cf7d8322fd7ed6ebf8c400ada92dd281d56004ee4515b8505bfadd766a27d3f | runeksvendsen/blockchain-restful-address-index | Util.hs | module Util
(
fromMaybe
, forM
, cs
, try
, fmapL
, (<>)
, Reader.ask, Reader.liftIO
, decodeHex
)
where
import Data.Maybe (fromMaybe)
import Control.Monad (forM)
import Data.Monoid ((<>))
import Data.String.Conversions (cs)
import Control.Exception (try)
import Data.EitherR (fmapL)
import qualified Control.Monad.Reader as Reader
import qualified Network.Haskoin.Util as HU
decodeHex bs = maybe (Left "invalid hex string") Right (HU.decodeHex bs) | null | https://raw.githubusercontent.com/runeksvendsen/blockchain-restful-address-index/7ec677ca91e0ea551b5cf93153aea65114924bba/src/Util.hs | haskell | module Util
(
fromMaybe
, forM
, cs
, try
, fmapL
, (<>)
, Reader.ask, Reader.liftIO
, decodeHex
)
where
import Data.Maybe (fromMaybe)
import Control.Monad (forM)
import Data.Monoid ((<>))
import Data.String.Conversions (cs)
import Control.Exception (try)
import Data.EitherR (fmapL)
import qualified Control.Monad.Reader as Reader
import qualified Network.Haskoin.Util as HU
decodeHex bs = maybe (Left "invalid hex string") Right (HU.decodeHex bs) | |
cca3170a8b369016c48a8ca6871079a8492f17fb740415714b5801f477429188 | slegrand45/mysql_protocol | mp_protocol.ml | type protocol_version =
Protocol_version_40
| Protocol_version_41
let protocol_version_to_string v =
let version =
match v with
| Protocol_version_40 -> "4.0"
| Protocol_version_41 -> "4.1"
in
version
| null | https://raw.githubusercontent.com/slegrand45/mysql_protocol/eb28d33dfbee7b12f88a7f798c2dbb40e1fb1bb0/src/mp_protocol.ml | ocaml | type protocol_version =
Protocol_version_40
| Protocol_version_41
let protocol_version_to_string v =
let version =
match v with
| Protocol_version_40 -> "4.0"
| Protocol_version_41 -> "4.1"
in
version
| |
bce57373baa62b12152df063721cde2074cb5b655071b8a34d80a22033a783e0 | kahaani/TINY-in-Haskell | Main.hs | module Main where
import Scan(scan)
import Parse(parse)
import TypeCheck(typeCheck)
import BuildSymtab(buildSymtab,testSymtab)
import CodeGen(codeGen)
main :: IO ()
main = do
contents <- getContents
mapM_ putStrLn . codeGen . buildSymtab . typeCheck . parse . scan $ contents
print . testSymtab . . parse . scan $ contents
print . . parse . scan $ contents
--print . parse . scan $ contents
--mapM_ print . scan $ contents
--print . scan $ contents
| null | https://raw.githubusercontent.com/kahaani/TINY-in-Haskell/9149c71faa09d33a18b00a08180cefeb6359de77/v1/Main.hs | haskell | print . parse . scan $ contents
mapM_ print . scan $ contents
print . scan $ contents | module Main where
import Scan(scan)
import Parse(parse)
import TypeCheck(typeCheck)
import BuildSymtab(buildSymtab,testSymtab)
import CodeGen(codeGen)
main :: IO ()
main = do
contents <- getContents
mapM_ putStrLn . codeGen . buildSymtab . typeCheck . parse . scan $ contents
print . testSymtab . . parse . scan $ contents
print . . parse . scan $ contents
|
28b932c5dc38f4b07c79d0a1a5f974570854f7d094fedf836f9ee5cc1d188bb5 | juspay/euler-hs | CachedSqlDBQuery.hs | {-# LANGUAGE OverloadedStrings #-}
module EulerHS.CachedSqlDBQuery
( create
, createSql
, updateOne
, updateOneWoReturning
, updateOneSql
, updateOneSqlWoReturning
, updateExtended
, findOne
, findOneSql
, findAll
, findAllSql
, findAllExtended
, SqlReturning(..)
)
where
import Data.Aeson (encode)
import qualified Data.ByteString.Lazy as BSL
import qualified Database.Beam as B
import qualified Database.Beam.MySQL as BM
import qualified Database.Beam.Postgres as BP
import qualified Database.Beam.Sqlite as BS
import qualified Data.Text as T
import qualified EulerHS.Core.SqlDB.Language as DB
import EulerHS.Core.Types.DB
import EulerHS.Core.Types.Serializable
import EulerHS.Extra.Language (getOrInitSqlConn, rGet, rSetB)
import qualified EulerHS.Framework.Language as L
import EulerHS.Prelude
import Named (defaults, (!))
import Sequelize
TODO : What should be used
cacheName :: String
cacheName = "eulerKVDB"
--------------- Core API ---------------
-- | Create a new database entry with the given value.
Cache the value if the DB insert succeeds .
class SqlReturning (beM :: Type -> Type) (be :: Type) where
createReturning ::
forall (table :: (Type -> Type) -> Type)
(m :: Type -> Type) .
( HasCallStack,
BeamRuntime be beM,
BeamRunner beM,
B.HasQBuilder be,
Model be table,
ToJSON (table Identity),
FromJSON (table Identity),
Show (table Identity),
L.MonadFlow m
) =>
DBConfig beM ->
table Identity ->
Maybe Text ->
m (Either DBError (table Identity))
instance SqlReturning BM.MySQLM BM.MySQL where
createReturning = createMySQL
instance SqlReturning BP.Pg BP.Postgres where
createReturning = create
instance SqlReturning BS.SqliteM BS.Sqlite where
createReturning = create
create ::
forall (be :: Type)
(beM :: Type -> Type)
(table :: (Type -> Type) -> Type)
(m :: Type -> Type) .
( HasCallStack,
BeamRuntime be beM,
BeamRunner beM,
B.HasQBuilder be,
Model be table,
ToJSON (table Identity),
FromJSON (table Identity),
Show (table Identity),
L.MonadFlow m
) =>
DBConfig beM ->
table Identity ->
Maybe Text ->
m (Either DBError (table Identity))
create dbConf value mCacheKey = do
res <- createSql dbConf value
case res of
Right val -> do
whenJust mCacheKey (`cacheWithKey` val)
return $ Right val
Left e -> return $ Left e
createMySQL ::
forall (table :: (Type -> Type) -> Type)
(m :: Type -> Type) .
( HasCallStack,
Model BM.MySQL table,
ToJSON (table Identity),
FromJSON (table Identity),
Show (table Identity),
L.MonadFlow m
) =>
DBConfig BM.MySQLM ->
table Identity ->
Maybe Text ->
m (Either DBError (table Identity))
createMySQL dbConf value mCacheKey = do
res <- createSqlMySQL dbConf value
case res of
Right val -> do
whenJust mCacheKey (`cacheWithKey` val)
return $ Right val
Left e -> return $ Left e
-- | Update an element matching the query to the new value.
-- Cache the value at the given key if the DB update succeeds.
updateOne ::
( HasCallStack,
BeamRuntime be beM,
BeamRunner beM,
Model be table,
B.HasQBuilder be,
ToJSON (table Identity),
FromJSON (table Identity),
Show (table Identity),
L.MonadFlow m
) =>
DBConfig beM ->
Maybe Text ->
[Set be table] ->
Where be table ->
m (Either DBError (table Identity))
updateOne dbConf (Just cacheKey) newVals whereClause = do
val <- updateOneSql dbConf newVals whereClause
whenRight val (\_ -> cacheWithKey cacheKey val)
return val
updateOne dbConf Nothing value whereClause = updateOneSql dbConf value whereClause
updateOneWoReturning ::
( HasCallStack,
BeamRuntime be beM,
BeamRunner beM,
Model be table,
B.HasQBuilder be,
ToJSON (table Identity),
FromJSON (table Identity),
Show (table Identity),
L.MonadFlow m
) =>
DBConfig beM ->
Maybe Text ->
[Set be table] ->
Where be table ->
m (Either DBError ())
updateOneWoReturning dbConf (Just _) newVals whereClause = do
val <- updateOneSqlWoReturning dbConf newVals whereClause
( \ _ - > cacheWithKey cacheKey val )
return val
updateOneWoReturning dbConf Nothing value whereClause = updateOneSqlWoReturning dbConf value whereClause
updateOneSqlWoReturning ::
forall m be beM table.
( HasCallStack,
BeamRuntime be beM,
BeamRunner beM,
Model be table,
B.HasQBuilder be,
FromJSON (table Identity),
ToJSON (table Identity),
Show (table Identity),
L.MonadFlow m
) =>
DBConfig beM ->
[Set be table] ->
Where be table ->
m (DBResult ())
updateOneSqlWoReturning dbConf newVals whereClause = do
let updateQuery = DB.updateRows $ sqlUpdate
! #set newVals
! #where_ whereClause
res <- runQuery dbConf updateQuery
case res of
Right x -> do
L.logDebug @Text "updateOneSqlWoReturning" "query executed"
return $ Right x
-- Right xs -> do
-- let message = "DB returned \"" <> show xs <> "\" after update"
-- L.logError @Text "create" message
return $ Left $ DBError UnexpectedResult message
Left e -> return $ Left e
updateOneSql ::
forall m be beM table.
( HasCallStack,
BeamRuntime be beM,
BeamRunner beM,
Model be table,
B.HasQBuilder be,
FromJSON (table Identity),
ToJSON (table Identity),
Show (table Identity),
L.MonadFlow m
) =>
DBConfig beM ->
[Set be table] ->
Where be table ->
m (DBResult (table Identity))
updateOneSql dbConf newVals whereClause = do
let updateQuery = DB.updateRowsReturningList $ sqlUpdate
! #set newVals
! #where_ whereClause
res <- runQuery dbConf updateQuery
case res of
Right [x] -> return $ Right x
Right xs -> do
let message = "DB returned \"" <> show xs <> "\" after update"
L.logError @Text "create" message
return $ Left $ DBError UnexpectedResult message
Left e -> return $ Left e
| Perform an arbitrary ' SqlUpdate ' . This will cache if successful .
updateExtended :: (HasCallStack, L.MonadFlow m, BeamRunner beM, BeamRuntime be beM) =>
DBConfig beM -> Maybe Text -> B.SqlUpdate be table -> m (Either DBError ())
updateExtended dbConf mKey upd = do
res <- runQuery dbConf . DB.updateRows $ upd
maybe (pure ()) (`cacheWithKey` res) mKey
pure res
-- | Find an element matching the query. Only uses the DB if the cache is empty.
-- Caches the result using the given key.
findOne ::
( HasCallStack,
BeamRuntime be beM,
BeamRunner beM,
Model be table,
B.HasQBuilder be,
ToJSON (table Identity),
FromJSON (table Identity),
L.MonadFlow m
) =>
DBConfig beM ->
Maybe Text ->
Where be table ->
m (Either DBError (Maybe (table Identity)))
findOne dbConf (Just cacheKey) whereClause = do
mRes <- rGet (T.pack cacheName) cacheKey
case join mRes of
(Just res) -> return $ Right $ Just res
Nothing -> do
mDBRes <- findOneSql dbConf whereClause
whenRight mDBRes (cacheWithKey cacheKey)
return mDBRes
findOne dbConf Nothing whereClause = findOneSql dbConf whereClause
-- | Find all elements matching the query. Only uses the DB if the cache is empty.
-- Caches the result using the given key.
NOTE : Ca n't use the same key as findOne , updateOne or create since it 's result is a list .
findAll ::
( HasCallStack,
BeamRuntime be beM,
BeamRunner beM,
Model be table,
B.HasQBuilder be,
ToJSON (table Identity),
FromJSON (table Identity),
L.MonadFlow m
) =>
DBConfig beM ->
Maybe Text ->
Where be table ->
m (Either DBError [table Identity])
findAll dbConf (Just cacheKey) whereClause = do
mRes <- rGet (T.pack cacheName) cacheKey
case mRes of
(Just res) -> return $ Right res
Nothing -> do
mDBRes <- findAllSql dbConf whereClause
whenRight mDBRes (cacheWithKey cacheKey)
return mDBRes
findAll dbConf Nothing whereClause = findAllSql dbConf whereClause
| Like ' findAll ' , but takes an explicit ' SqlSelect ' .
findAllExtended :: forall beM be table m .
(HasCallStack,
L.MonadFlow m,
B.FromBackendRow be (table Identity),
BeamRunner beM,
BeamRuntime be beM,
FromJSON (table Identity),
ToJSON (table Identity)) =>
DBConfig beM ->
Maybe Text ->
B.SqlSelect be (table Identity) ->
m (Either DBError [table Identity])
findAllExtended dbConf mKey sel = case mKey of
Nothing -> go
Just k -> do
mCached <- rGet (T.pack cacheName) k
case mCached of
Just res -> pure . Right $ res
Nothing -> do
dbRes <- go
either (\_ -> pure ()) (cacheWithKey k) dbRes
pure dbRes
where
go :: m (Either DBError [table Identity])
go = do
eConn <- getOrInitSqlConn dbConf
join <$> traverse (\conn -> L.runDB conn . DB.findRows $ sel) eConn
------------ Helper functions ------------
runQuery ::
( HasCallStack,
BeamRuntime be beM, BeamRunner beM,
JSONEx a,
L.MonadFlow m
) =>
DBConfig beM -> DB.SqlDB beM a -> m (Either DBError a)
runQuery dbConf query = do
conn <- getOrInitSqlConn dbConf
case conn of
Right c -> L.runDB c query
Left e -> return $ Left e
runQueryMySQL ::
( HasCallStack,
JSONEx a,
L.MonadFlow m
) =>
DBConfig BM.MySQLM -> DB.SqlDB BM.MySQLM a -> m (Either DBError a)
runQueryMySQL dbConf query = do
conn <- getOrInitSqlConn dbConf
case conn of
Right c -> L.runTransaction c query
Left e -> return $ Left e
sqlCreate ::
forall be table.
(HasCallStack, B.HasQBuilder be, Model be table) =>
table Identity ->
B.SqlInsert be table
sqlCreate value = B.insert modelTableEntity (mkExprWithDefault value)
createSql ::
forall m be beM table.
( HasCallStack,
BeamRuntime be beM,
BeamRunner beM,
B.HasQBuilder be,
Model be table,
ToJSON (table Identity),
FromJSON (table Identity),
Show (table Identity),
L.MonadFlow m
) =>
DBConfig beM ->
table Identity ->
m (Either DBError (table Identity))
createSql dbConf value = do
res <- runQuery dbConf $ DB.insertRowsReturningList $ sqlCreate value
case res of
Right [val] -> return $ Right val
Right xs -> do
let message = "DB returned \"" <> show xs <> "\" after inserting \"" <> show value <> "\""
L.logError @Text "create" message
return $ Left $ DBError UnexpectedResult message
Left e -> return $ Left e
createSqlMySQL ::
forall m table.
( HasCallStack,
Model BM.MySQL table,
ToJSON (table Identity),
FromJSON (table Identity),
Show (table Identity),
L.MonadFlow m
) =>
DBConfig BM.MySQLM ->
table Identity ->
m (Either DBError (table Identity))
createSqlMySQL dbConf value = do
res <- runQueryMySQL dbConf $ DB.insertRowReturningMySQL $ sqlCreate value
case res of
Right (Just val) -> return $ Right val
Right Nothing -> do
let message = "DB returned \"" <> "Nothing" <> "\" after inserting \"" <> show value <> "\""
L.logError @Text "createSqlMySQL" message
return $ Left $ DBError UnexpectedResult message
Left e -> return $ Left e
findOneSql ::
( HasCallStack,
BeamRuntime be beM,
BeamRunner beM,
Model be table,
B.HasQBuilder be,
ToJSON (table Identity),
FromJSON (table Identity),
L.MonadFlow m
) =>
DBConfig beM ->
Where be table ->
m (Either DBError (Maybe (table Identity)))
findOneSql dbConf whereClause = runQuery dbConf findQuery
where findQuery = DB.findRow (sqlSelect ! #where_ whereClause ! defaults)
findAllSql ::
( HasCallStack,
BeamRuntime be beM,
BeamRunner beM,
Model be table,
B.HasQBuilder be,
JSONEx (table Identity),
L.MonadFlow m
) =>
DBConfig beM ->
Where be table ->
m (Either DBError [table Identity])
findAllSql dbConf whereClause = do
let findQuery = DB.findRows (sqlSelect ! #where_ whereClause ! defaults)
sqlConn <- getOrInitSqlConn dbConf
join <$> mapM (`L.runDB` findQuery) sqlConn
cacheWithKey :: (HasCallStack, ToJSON table, L.MonadFlow m) => Text -> table -> m ()
cacheWithKey key row = do
-- TODO: Should we log errors here?
void $ rSetB (T.pack cacheName) (encodeUtf8 key) (BSL.toStrict $ encode row)
| null | https://raw.githubusercontent.com/juspay/euler-hs/0fdda6ef43c1a6c9c7221d7c194c278e375b9936/src/EulerHS/CachedSqlDBQuery.hs | haskell | # LANGUAGE OverloadedStrings #
------------- Core API ---------------
| Create a new database entry with the given value.
| Update an element matching the query to the new value.
Cache the value at the given key if the DB update succeeds.
Right xs -> do
let message = "DB returned \"" <> show xs <> "\" after update"
L.logError @Text "create" message
| Find an element matching the query. Only uses the DB if the cache is empty.
Caches the result using the given key.
| Find all elements matching the query. Only uses the DB if the cache is empty.
Caches the result using the given key.
---------- Helper functions ------------
TODO: Should we log errors here? |
module EulerHS.CachedSqlDBQuery
( create
, createSql
, updateOne
, updateOneWoReturning
, updateOneSql
, updateOneSqlWoReturning
, updateExtended
, findOne
, findOneSql
, findAll
, findAllSql
, findAllExtended
, SqlReturning(..)
)
where
import Data.Aeson (encode)
import qualified Data.ByteString.Lazy as BSL
import qualified Database.Beam as B
import qualified Database.Beam.MySQL as BM
import qualified Database.Beam.Postgres as BP
import qualified Database.Beam.Sqlite as BS
import qualified Data.Text as T
import qualified EulerHS.Core.SqlDB.Language as DB
import EulerHS.Core.Types.DB
import EulerHS.Core.Types.Serializable
import EulerHS.Extra.Language (getOrInitSqlConn, rGet, rSetB)
import qualified EulerHS.Framework.Language as L
import EulerHS.Prelude
import Named (defaults, (!))
import Sequelize
TODO : What should be used
cacheName :: String
cacheName = "eulerKVDB"
Cache the value if the DB insert succeeds .
class SqlReturning (beM :: Type -> Type) (be :: Type) where
createReturning ::
forall (table :: (Type -> Type) -> Type)
(m :: Type -> Type) .
( HasCallStack,
BeamRuntime be beM,
BeamRunner beM,
B.HasQBuilder be,
Model be table,
ToJSON (table Identity),
FromJSON (table Identity),
Show (table Identity),
L.MonadFlow m
) =>
DBConfig beM ->
table Identity ->
Maybe Text ->
m (Either DBError (table Identity))
instance SqlReturning BM.MySQLM BM.MySQL where
createReturning = createMySQL
instance SqlReturning BP.Pg BP.Postgres where
createReturning = create
instance SqlReturning BS.SqliteM BS.Sqlite where
createReturning = create
create ::
forall (be :: Type)
(beM :: Type -> Type)
(table :: (Type -> Type) -> Type)
(m :: Type -> Type) .
( HasCallStack,
BeamRuntime be beM,
BeamRunner beM,
B.HasQBuilder be,
Model be table,
ToJSON (table Identity),
FromJSON (table Identity),
Show (table Identity),
L.MonadFlow m
) =>
DBConfig beM ->
table Identity ->
Maybe Text ->
m (Either DBError (table Identity))
create dbConf value mCacheKey = do
res <- createSql dbConf value
case res of
Right val -> do
whenJust mCacheKey (`cacheWithKey` val)
return $ Right val
Left e -> return $ Left e
createMySQL ::
forall (table :: (Type -> Type) -> Type)
(m :: Type -> Type) .
( HasCallStack,
Model BM.MySQL table,
ToJSON (table Identity),
FromJSON (table Identity),
Show (table Identity),
L.MonadFlow m
) =>
DBConfig BM.MySQLM ->
table Identity ->
Maybe Text ->
m (Either DBError (table Identity))
createMySQL dbConf value mCacheKey = do
res <- createSqlMySQL dbConf value
case res of
Right val -> do
whenJust mCacheKey (`cacheWithKey` val)
return $ Right val
Left e -> return $ Left e
updateOne ::
( HasCallStack,
BeamRuntime be beM,
BeamRunner beM,
Model be table,
B.HasQBuilder be,
ToJSON (table Identity),
FromJSON (table Identity),
Show (table Identity),
L.MonadFlow m
) =>
DBConfig beM ->
Maybe Text ->
[Set be table] ->
Where be table ->
m (Either DBError (table Identity))
updateOne dbConf (Just cacheKey) newVals whereClause = do
val <- updateOneSql dbConf newVals whereClause
whenRight val (\_ -> cacheWithKey cacheKey val)
return val
updateOne dbConf Nothing value whereClause = updateOneSql dbConf value whereClause
updateOneWoReturning ::
( HasCallStack,
BeamRuntime be beM,
BeamRunner beM,
Model be table,
B.HasQBuilder be,
ToJSON (table Identity),
FromJSON (table Identity),
Show (table Identity),
L.MonadFlow m
) =>
DBConfig beM ->
Maybe Text ->
[Set be table] ->
Where be table ->
m (Either DBError ())
updateOneWoReturning dbConf (Just _) newVals whereClause = do
val <- updateOneSqlWoReturning dbConf newVals whereClause
( \ _ - > cacheWithKey cacheKey val )
return val
updateOneWoReturning dbConf Nothing value whereClause = updateOneSqlWoReturning dbConf value whereClause
updateOneSqlWoReturning ::
forall m be beM table.
( HasCallStack,
BeamRuntime be beM,
BeamRunner beM,
Model be table,
B.HasQBuilder be,
FromJSON (table Identity),
ToJSON (table Identity),
Show (table Identity),
L.MonadFlow m
) =>
DBConfig beM ->
[Set be table] ->
Where be table ->
m (DBResult ())
updateOneSqlWoReturning dbConf newVals whereClause = do
let updateQuery = DB.updateRows $ sqlUpdate
! #set newVals
! #where_ whereClause
res <- runQuery dbConf updateQuery
case res of
Right x -> do
L.logDebug @Text "updateOneSqlWoReturning" "query executed"
return $ Right x
return $ Left $ DBError UnexpectedResult message
Left e -> return $ Left e
updateOneSql ::
forall m be beM table.
( HasCallStack,
BeamRuntime be beM,
BeamRunner beM,
Model be table,
B.HasQBuilder be,
FromJSON (table Identity),
ToJSON (table Identity),
Show (table Identity),
L.MonadFlow m
) =>
DBConfig beM ->
[Set be table] ->
Where be table ->
m (DBResult (table Identity))
updateOneSql dbConf newVals whereClause = do
let updateQuery = DB.updateRowsReturningList $ sqlUpdate
! #set newVals
! #where_ whereClause
res <- runQuery dbConf updateQuery
case res of
Right [x] -> return $ Right x
Right xs -> do
let message = "DB returned \"" <> show xs <> "\" after update"
L.logError @Text "create" message
return $ Left $ DBError UnexpectedResult message
Left e -> return $ Left e
| Perform an arbitrary ' SqlUpdate ' . This will cache if successful .
updateExtended :: (HasCallStack, L.MonadFlow m, BeamRunner beM, BeamRuntime be beM) =>
DBConfig beM -> Maybe Text -> B.SqlUpdate be table -> m (Either DBError ())
updateExtended dbConf mKey upd = do
res <- runQuery dbConf . DB.updateRows $ upd
maybe (pure ()) (`cacheWithKey` res) mKey
pure res
findOne ::
( HasCallStack,
BeamRuntime be beM,
BeamRunner beM,
Model be table,
B.HasQBuilder be,
ToJSON (table Identity),
FromJSON (table Identity),
L.MonadFlow m
) =>
DBConfig beM ->
Maybe Text ->
Where be table ->
m (Either DBError (Maybe (table Identity)))
findOne dbConf (Just cacheKey) whereClause = do
mRes <- rGet (T.pack cacheName) cacheKey
case join mRes of
(Just res) -> return $ Right $ Just res
Nothing -> do
mDBRes <- findOneSql dbConf whereClause
whenRight mDBRes (cacheWithKey cacheKey)
return mDBRes
findOne dbConf Nothing whereClause = findOneSql dbConf whereClause
NOTE : Ca n't use the same key as findOne , updateOne or create since it 's result is a list .
findAll ::
( HasCallStack,
BeamRuntime be beM,
BeamRunner beM,
Model be table,
B.HasQBuilder be,
ToJSON (table Identity),
FromJSON (table Identity),
L.MonadFlow m
) =>
DBConfig beM ->
Maybe Text ->
Where be table ->
m (Either DBError [table Identity])
findAll dbConf (Just cacheKey) whereClause = do
mRes <- rGet (T.pack cacheName) cacheKey
case mRes of
(Just res) -> return $ Right res
Nothing -> do
mDBRes <- findAllSql dbConf whereClause
whenRight mDBRes (cacheWithKey cacheKey)
return mDBRes
findAll dbConf Nothing whereClause = findAllSql dbConf whereClause
| Like ' findAll ' , but takes an explicit ' SqlSelect ' .
findAllExtended :: forall beM be table m .
(HasCallStack,
L.MonadFlow m,
B.FromBackendRow be (table Identity),
BeamRunner beM,
BeamRuntime be beM,
FromJSON (table Identity),
ToJSON (table Identity)) =>
DBConfig beM ->
Maybe Text ->
B.SqlSelect be (table Identity) ->
m (Either DBError [table Identity])
findAllExtended dbConf mKey sel = case mKey of
Nothing -> go
Just k -> do
mCached <- rGet (T.pack cacheName) k
case mCached of
Just res -> pure . Right $ res
Nothing -> do
dbRes <- go
either (\_ -> pure ()) (cacheWithKey k) dbRes
pure dbRes
where
go :: m (Either DBError [table Identity])
go = do
eConn <- getOrInitSqlConn dbConf
join <$> traverse (\conn -> L.runDB conn . DB.findRows $ sel) eConn
runQuery ::
( HasCallStack,
BeamRuntime be beM, BeamRunner beM,
JSONEx a,
L.MonadFlow m
) =>
DBConfig beM -> DB.SqlDB beM a -> m (Either DBError a)
runQuery dbConf query = do
conn <- getOrInitSqlConn dbConf
case conn of
Right c -> L.runDB c query
Left e -> return $ Left e
runQueryMySQL ::
( HasCallStack,
JSONEx a,
L.MonadFlow m
) =>
DBConfig BM.MySQLM -> DB.SqlDB BM.MySQLM a -> m (Either DBError a)
runQueryMySQL dbConf query = do
conn <- getOrInitSqlConn dbConf
case conn of
Right c -> L.runTransaction c query
Left e -> return $ Left e
sqlCreate ::
forall be table.
(HasCallStack, B.HasQBuilder be, Model be table) =>
table Identity ->
B.SqlInsert be table
sqlCreate value = B.insert modelTableEntity (mkExprWithDefault value)
createSql ::
forall m be beM table.
( HasCallStack,
BeamRuntime be beM,
BeamRunner beM,
B.HasQBuilder be,
Model be table,
ToJSON (table Identity),
FromJSON (table Identity),
Show (table Identity),
L.MonadFlow m
) =>
DBConfig beM ->
table Identity ->
m (Either DBError (table Identity))
createSql dbConf value = do
res <- runQuery dbConf $ DB.insertRowsReturningList $ sqlCreate value
case res of
Right [val] -> return $ Right val
Right xs -> do
let message = "DB returned \"" <> show xs <> "\" after inserting \"" <> show value <> "\""
L.logError @Text "create" message
return $ Left $ DBError UnexpectedResult message
Left e -> return $ Left e
createSqlMySQL ::
forall m table.
( HasCallStack,
Model BM.MySQL table,
ToJSON (table Identity),
FromJSON (table Identity),
Show (table Identity),
L.MonadFlow m
) =>
DBConfig BM.MySQLM ->
table Identity ->
m (Either DBError (table Identity))
createSqlMySQL dbConf value = do
res <- runQueryMySQL dbConf $ DB.insertRowReturningMySQL $ sqlCreate value
case res of
Right (Just val) -> return $ Right val
Right Nothing -> do
let message = "DB returned \"" <> "Nothing" <> "\" after inserting \"" <> show value <> "\""
L.logError @Text "createSqlMySQL" message
return $ Left $ DBError UnexpectedResult message
Left e -> return $ Left e
findOneSql ::
( HasCallStack,
BeamRuntime be beM,
BeamRunner beM,
Model be table,
B.HasQBuilder be,
ToJSON (table Identity),
FromJSON (table Identity),
L.MonadFlow m
) =>
DBConfig beM ->
Where be table ->
m (Either DBError (Maybe (table Identity)))
findOneSql dbConf whereClause = runQuery dbConf findQuery
where findQuery = DB.findRow (sqlSelect ! #where_ whereClause ! defaults)
findAllSql ::
( HasCallStack,
BeamRuntime be beM,
BeamRunner beM,
Model be table,
B.HasQBuilder be,
JSONEx (table Identity),
L.MonadFlow m
) =>
DBConfig beM ->
Where be table ->
m (Either DBError [table Identity])
findAllSql dbConf whereClause = do
let findQuery = DB.findRows (sqlSelect ! #where_ whereClause ! defaults)
sqlConn <- getOrInitSqlConn dbConf
join <$> mapM (`L.runDB` findQuery) sqlConn
cacheWithKey :: (HasCallStack, ToJSON table, L.MonadFlow m) => Text -> table -> m ()
cacheWithKey key row = do
void $ rSetB (T.pack cacheName) (encodeUtf8 key) (BSL.toStrict $ encode row)
|
2696b10e2eba94f4b6962cd25c8f300d15820f2d3a1f91c44ceaed98c4190961 | hammerlab/secotrec | coclobas.mli | open Common
module Aws_batch_cluster: sig
type t = {
queue: string;
bucket: string;
} [@@deriving make]
end
type cluster = [
| `GKE of Gke_cluster.t
| `Local of int
| `Aws_batch of Aws_batch_cluster.t
]
type t
val make :
?name:string ->
?opam_pin: Opam.Pin.t list ->
?root:string ->
?port:int ->
?tmp_dir: string ->
db:Postgres.t ->
?image: string ->
cluster ->
t
val cluster : t -> cluster
val name: t -> string
val base_url: t -> string
val url_for_local_client: t -> string
val tmp_dir: t -> string
val root: t -> string
val logs_path: t -> string
val to_service : t -> Docker_compose.Configuration.service
| null | https://raw.githubusercontent.com/hammerlab/secotrec/c801a43fdb0feea98da6d3636145f948aed4e7be/src/lib/coclobas.mli | ocaml | open Common
module Aws_batch_cluster: sig
type t = {
queue: string;
bucket: string;
} [@@deriving make]
end
type cluster = [
| `GKE of Gke_cluster.t
| `Local of int
| `Aws_batch of Aws_batch_cluster.t
]
type t
val make :
?name:string ->
?opam_pin: Opam.Pin.t list ->
?root:string ->
?port:int ->
?tmp_dir: string ->
db:Postgres.t ->
?image: string ->
cluster ->
t
val cluster : t -> cluster
val name: t -> string
val base_url: t -> string
val url_for_local_client: t -> string
val tmp_dir: t -> string
val root: t -> string
val logs_path: t -> string
val to_service : t -> Docker_compose.Configuration.service
| |
e984f6312c80a2489d07134a2a899e1b3ed8581eba21f3fbde532e3f59612fb1 | sheyll/mediabus | Segment.hs | # LANGUAGE UndecidableInstances #
-- | Media segments with a fixed duration
module Data.MediaBus.Media.Segment
( Segment (..),
segmentContent,
CanSegment (..),
)
where
import Control.DeepSeq (NFData)
import Control.Lens (Iso, iso)
import Data.Default (Default)
import Data.MediaBus.Basics.Ticks
( CoerceRate (..),
HasDuration (getDuration),
HasRate (..),
KnownRate,
)
import Data.MediaBus.Media.Channels (EachChannel (..))
import Data.MediaBus.Media.Media (HasMedia (..))
import Data.MediaBus.Media.Samples (EachSample (..))
import Data.Time (NominalDiffTime)
import Test.QuickCheck (Arbitrary)
import Text.Printf (printf)
import Data.MediaBus.Media.Buffer
-- | A segment is some content with a fixed (maximum) duration.
-- The content is shorter at the end of a stream or when a 'Start'
' FrameCtx ' was sent .
newtype Segment c = MkSegment {_segmentContent :: c}
deriving (NFData, Default, Arbitrary, Functor, Eq)
| An ' ' for the ' Segment ' newtype .
segmentContent :: Iso (Segment c) (Segment c') c c'
segmentContent = iso _segmentContent MkSegment
instance (HasMedia c c') => HasMedia (Segment c) (Segment c') where
type MediaFrom (Segment c) = MediaFrom c
type MediaTo (Segment c') = MediaTo c'
media = segmentContent . media
instance
HasMediaBufferLens c c' =>
HasMediaBufferLens (Segment c) (Segment c')
where
type MediaBufferElemFrom (Segment c) = MediaBufferElemFrom c
type MediaBufferElemTo (Segment c') = MediaBufferElemTo c'
mediaBufferLens = segmentContent . mediaBufferLens
instance (EachSample c c') => EachSample (Segment c) (Segment c') where
type SamplesFrom (Segment c) = SamplesFrom c
type SamplesTo (Segment c') = SamplesTo c'
eachSample = segmentContent . eachSample
instance (EachChannel c c') => EachChannel (Segment c) (Segment c') where
type ChannelsFrom (Segment c) = ChannelsFrom c
type ChannelsTo (Segment c') = ChannelsTo c'
eachChannel = segmentContent . eachChannel
instance (HasRate c) => HasRate (Segment c) where
type GetRate (Segment c) = GetRate c
type SetRate (Segment c) r' = Segment (SetRate c r')
instance
(HasRate i, GetRate i ~ ri, SetRate i rj ~ j, KnownRate rj, CoerceRate i j ri rj) =>
CoerceRate (Segment i) (Segment j) ri rj
where
coerceRate px (MkSegment !c) = MkSegment (coerceRate px c)
instance
(HasDuration c, Show c) =>
Show (Segment c)
where
showsPrec _d (MkSegment c) =
showString "[| "
. shows c
. showString (printf " |%10s]" (show (getDuration c)))
instance
HasDuration x =>
HasDuration (Segment x)
where
getDuration (MkSegment x) = getDuration x
-- | Class of types that support splitting values into parts with a certain
-- duration.
class CanSegment a where
-- | Try to split the packet into the a part which has the given
-- duration and a rest. If it is not possible to split of the desired duration,
-- e.g. because the input data is too short, return `Nothing`.
splitAfterDuration :: NominalDiffTime -> a -> Maybe (a, a)
| null | https://raw.githubusercontent.com/sheyll/mediabus/2bc01544956b2c30dedbb0bb61dc115eef6aa689/src/Data/MediaBus/Media/Segment.hs | haskell | | Media segments with a fixed duration
| A segment is some content with a fixed (maximum) duration.
The content is shorter at the end of a stream or when a 'Start'
| Class of types that support splitting values into parts with a certain
duration.
| Try to split the packet into the a part which has the given
duration and a rest. If it is not possible to split of the desired duration,
e.g. because the input data is too short, return `Nothing`. | # LANGUAGE UndecidableInstances #
module Data.MediaBus.Media.Segment
( Segment (..),
segmentContent,
CanSegment (..),
)
where
import Control.DeepSeq (NFData)
import Control.Lens (Iso, iso)
import Data.Default (Default)
import Data.MediaBus.Basics.Ticks
( CoerceRate (..),
HasDuration (getDuration),
HasRate (..),
KnownRate,
)
import Data.MediaBus.Media.Channels (EachChannel (..))
import Data.MediaBus.Media.Media (HasMedia (..))
import Data.MediaBus.Media.Samples (EachSample (..))
import Data.Time (NominalDiffTime)
import Test.QuickCheck (Arbitrary)
import Text.Printf (printf)
import Data.MediaBus.Media.Buffer
' FrameCtx ' was sent .
newtype Segment c = MkSegment {_segmentContent :: c}
deriving (NFData, Default, Arbitrary, Functor, Eq)
| An ' ' for the ' Segment ' newtype .
segmentContent :: Iso (Segment c) (Segment c') c c'
segmentContent = iso _segmentContent MkSegment
instance (HasMedia c c') => HasMedia (Segment c) (Segment c') where
type MediaFrom (Segment c) = MediaFrom c
type MediaTo (Segment c') = MediaTo c'
media = segmentContent . media
instance
HasMediaBufferLens c c' =>
HasMediaBufferLens (Segment c) (Segment c')
where
type MediaBufferElemFrom (Segment c) = MediaBufferElemFrom c
type MediaBufferElemTo (Segment c') = MediaBufferElemTo c'
mediaBufferLens = segmentContent . mediaBufferLens
instance (EachSample c c') => EachSample (Segment c) (Segment c') where
type SamplesFrom (Segment c) = SamplesFrom c
type SamplesTo (Segment c') = SamplesTo c'
eachSample = segmentContent . eachSample
instance (EachChannel c c') => EachChannel (Segment c) (Segment c') where
type ChannelsFrom (Segment c) = ChannelsFrom c
type ChannelsTo (Segment c') = ChannelsTo c'
eachChannel = segmentContent . eachChannel
instance (HasRate c) => HasRate (Segment c) where
type GetRate (Segment c) = GetRate c
type SetRate (Segment c) r' = Segment (SetRate c r')
instance
(HasRate i, GetRate i ~ ri, SetRate i rj ~ j, KnownRate rj, CoerceRate i j ri rj) =>
CoerceRate (Segment i) (Segment j) ri rj
where
coerceRate px (MkSegment !c) = MkSegment (coerceRate px c)
instance
(HasDuration c, Show c) =>
Show (Segment c)
where
showsPrec _d (MkSegment c) =
showString "[| "
. shows c
. showString (printf " |%10s]" (show (getDuration c)))
instance
HasDuration x =>
HasDuration (Segment x)
where
getDuration (MkSegment x) = getDuration x
class CanSegment a where
splitAfterDuration :: NominalDiffTime -> a -> Maybe (a, a)
|
705a194b5793a633925071c309fe35aad2e164a30293e03eb16cb10513ccaf4d | riemann/riemann | keenio.clj | (ns riemann.keenio
"Forwards events to Keen IO"
(:require [clj-http.client :as client])
(:require [cheshire.core :as json]))
(def ^:private event-url
"/")
(defn post
"POST to Keen IO."
[collection project-id write-key request]
(let [final-event-url
(str event-url project-id "/events/" collection)]
(client/post final-event-url
{:body (json/generate-string request)
:query-params { "api_key" write-key }
:socket-timeout 5000
:conn-timeout 5000
:content-type :json
:accept :json
:throw-entire-message? true})))
(defn keenio
"Creates a keen adapter. Takes your Keen project id and write key, and
returns a function that accepts an event and sends it to Keen IO. The full
event will be sent.
```clojure
(streams
(let [kio (keenio \"COLLECTION_NAME\" \"PROJECT_ID\" \"WRITE_KEY\")]
(where (state \"error\") kio)))
```"
[collection project-id write-key]
(fn [event]
(post collection project-id write-key event)))
| null | https://raw.githubusercontent.com/riemann/riemann/1649687c0bd913c378701ee0b964a9863bde7c7c/src/riemann/keenio.clj | clojure | (ns riemann.keenio
"Forwards events to Keen IO"
(:require [clj-http.client :as client])
(:require [cheshire.core :as json]))
(def ^:private event-url
"/")
(defn post
"POST to Keen IO."
[collection project-id write-key request]
(let [final-event-url
(str event-url project-id "/events/" collection)]
(client/post final-event-url
{:body (json/generate-string request)
:query-params { "api_key" write-key }
:socket-timeout 5000
:conn-timeout 5000
:content-type :json
:accept :json
:throw-entire-message? true})))
(defn keenio
"Creates a keen adapter. Takes your Keen project id and write key, and
returns a function that accepts an event and sends it to Keen IO. The full
event will be sent.
```clojure
(streams
(let [kio (keenio \"COLLECTION_NAME\" \"PROJECT_ID\" \"WRITE_KEY\")]
(where (state \"error\") kio)))
```"
[collection project-id write-key]
(fn [event]
(post collection project-id write-key event)))
| |
0624698aa06a01da517f2dd35981373602eca6671da0768470ab77c07befc35f | andersfugmann/aws-s3 | body.ml | open StdLabels
module Make(Io : Types.Io) = struct
open Io
open Deferred
type t =
| String of string
| Empty
| Chunked of { pipe: string Pipe.reader; length: int; chunk_size: int }
let null () =
let rec read reader =
Pipe.read reader >>= function
| None -> return ()
| Some _ -> read reader
in
Pipe.create_writer ~f:read
let to_string body =
let rec loop acc =
Pipe.read body >>= function
| Some data ->
loop (data :: acc)
| None ->
String.concat ~sep:"" (List.rev acc) |> return
in
loop []
let read_string ?start ~length reader =
let rec loop acc data remain =
match data, remain with
| data, 0 -> Or_error.return (Buffer.contents acc, data)
| None, remain -> begin
Pipe.read reader >>= function
| None -> Or_error.fail (Failure "EOF")
| data -> loop acc data remain
end
| Some data, remain when String.length data < remain ->
Buffer.add_string acc data;
loop acc None (remain - String.length data)
| Some data, remain ->
Buffer.add_substring acc data 0 remain;
Or_error.return
(Buffer.contents acc, Some (String.sub data ~pos:remain ~len:(String.length data - remain)))
in
loop (Buffer.create length) start length
let transfer ?start ~length reader writer =
let rec loop writer data remain =
match remain, data with
| 0, data ->
Or_error.return data
| remain, Some data -> begin
match remain - String.length data with
| n when n >= 0 ->
Pipe.write writer data >>= fun () ->
loop writer None n
| _ -> (* Only write whats expected and discard the rest *)
Pipe.write writer (String.sub ~pos:0 ~len:remain data) >>= fun () ->
loop writer None 0
end
| remain, None ->
begin
Pipe.read reader >>= function
| None -> Or_error.fail (Failure "Premature end of input");
| data -> loop writer data remain
end
in
loop writer start length
let read_until ?start ~sep reader =
let buffer =
let b = Buffer.create 256 in
match start with
| Some data -> Buffer.add_string b data; b
| None -> b
in
let rec loop offset = function
| sep_index when sep_index = String.length sep ->
(* Found it. Return data *)
let v = Buffer.sub buffer 0 (offset - String.length sep) in
let remain =
match offset < Buffer.length buffer with
| true -> Some (Buffer.sub buffer offset (Buffer.length buffer - offset))
| false -> None
in
Or_error.return (v, remain)
| sep_index when offset >= (Buffer.length buffer) -> begin
Pipe.read reader >>= function
| Some data ->
Buffer.add_string buffer data;
loop offset sep_index;
| None ->
Or_error.fail (Failure (Printf.sprintf "EOF while looking for '%d'" (Char.code sep.[sep_index])))
end
| sep_index when Buffer.nth buffer offset = sep.[sep_index] ->
loop (offset + 1) (sep_index + 1)
| sep_index ->
(* Reset sep index. Look for the next element. *)
loop (offset - sep_index + 1) 0
in
loop 0 0
* Chunked encoding
format : < len_hex>\r\n < data>\r\n . Always ends with 0 length chunk
format: <len_hex>\r\n<data>\r\n. Always ends with 0 length chunk
*)
let chunked_transfer ?start reader writer =
let rec read_chunk data remain =
match data, remain with
| data, 0 -> return (Ok data)
| Some data, remain when String.length data < remain ->
Pipe.write writer data >>= fun () ->
read_chunk None (remain - String.length data)
| Some data, remain ->
Pipe.write writer (String.sub ~pos:0 ~len:remain data) >>= fun () ->
read_chunk (Some (String.sub ~pos:remain ~len:(String.length data - remain) data)) 0
| None, _ -> begin
Pipe.read reader >>= function
| None -> Or_error.fail (Failure "Premature EOF on input")
| v -> read_chunk v remain
end
in
let rec read remain =
read_until ?start:remain ~sep:"\r\n" reader >>=? fun (size_str, data) ->
begin
try Scanf.sscanf size_str "%x" (fun x -> x) |> Or_error.return
with _ -> Or_error.fail (Failure "Malformed chunk: Invalid length")
end >>=? fun chunk_size ->
match chunk_size with
| 0 -> read_until ?start:data ~sep:"\r\n" reader >>=? fun (_, remain) ->
Or_error.return remain
| n ->
read_chunk data n >>=? fun data ->
read_string ?start:data ~length:2 reader >>=? function
| ("\r\n", data) ->
read data
| (_, _data) ->
Or_error.fail (Failure "Malformed chunk: CRLF not present")
in
read start
end
| null | https://raw.githubusercontent.com/andersfugmann/aws-s3/84af629119e313ba46cf3eab9dd7b914e6bae5e9/aws-s3/body.ml | ocaml | Only write whats expected and discard the rest
Found it. Return data
Reset sep index. Look for the next element. | open StdLabels
module Make(Io : Types.Io) = struct
open Io
open Deferred
type t =
| String of string
| Empty
| Chunked of { pipe: string Pipe.reader; length: int; chunk_size: int }
let null () =
let rec read reader =
Pipe.read reader >>= function
| None -> return ()
| Some _ -> read reader
in
Pipe.create_writer ~f:read
let to_string body =
let rec loop acc =
Pipe.read body >>= function
| Some data ->
loop (data :: acc)
| None ->
String.concat ~sep:"" (List.rev acc) |> return
in
loop []
let read_string ?start ~length reader =
let rec loop acc data remain =
match data, remain with
| data, 0 -> Or_error.return (Buffer.contents acc, data)
| None, remain -> begin
Pipe.read reader >>= function
| None -> Or_error.fail (Failure "EOF")
| data -> loop acc data remain
end
| Some data, remain when String.length data < remain ->
Buffer.add_string acc data;
loop acc None (remain - String.length data)
| Some data, remain ->
Buffer.add_substring acc data 0 remain;
Or_error.return
(Buffer.contents acc, Some (String.sub data ~pos:remain ~len:(String.length data - remain)))
in
loop (Buffer.create length) start length
let transfer ?start ~length reader writer =
let rec loop writer data remain =
match remain, data with
| 0, data ->
Or_error.return data
| remain, Some data -> begin
match remain - String.length data with
| n when n >= 0 ->
Pipe.write writer data >>= fun () ->
loop writer None n
Pipe.write writer (String.sub ~pos:0 ~len:remain data) >>= fun () ->
loop writer None 0
end
| remain, None ->
begin
Pipe.read reader >>= function
| None -> Or_error.fail (Failure "Premature end of input");
| data -> loop writer data remain
end
in
loop writer start length
let read_until ?start ~sep reader =
let buffer =
let b = Buffer.create 256 in
match start with
| Some data -> Buffer.add_string b data; b
| None -> b
in
let rec loop offset = function
| sep_index when sep_index = String.length sep ->
let v = Buffer.sub buffer 0 (offset - String.length sep) in
let remain =
match offset < Buffer.length buffer with
| true -> Some (Buffer.sub buffer offset (Buffer.length buffer - offset))
| false -> None
in
Or_error.return (v, remain)
| sep_index when offset >= (Buffer.length buffer) -> begin
Pipe.read reader >>= function
| Some data ->
Buffer.add_string buffer data;
loop offset sep_index;
| None ->
Or_error.fail (Failure (Printf.sprintf "EOF while looking for '%d'" (Char.code sep.[sep_index])))
end
| sep_index when Buffer.nth buffer offset = sep.[sep_index] ->
loop (offset + 1) (sep_index + 1)
| sep_index ->
loop (offset - sep_index + 1) 0
in
loop 0 0
* Chunked encoding
format : < len_hex>\r\n < data>\r\n . Always ends with 0 length chunk
format: <len_hex>\r\n<data>\r\n. Always ends with 0 length chunk
*)
let chunked_transfer ?start reader writer =
let rec read_chunk data remain =
match data, remain with
| data, 0 -> return (Ok data)
| Some data, remain when String.length data < remain ->
Pipe.write writer data >>= fun () ->
read_chunk None (remain - String.length data)
| Some data, remain ->
Pipe.write writer (String.sub ~pos:0 ~len:remain data) >>= fun () ->
read_chunk (Some (String.sub ~pos:remain ~len:(String.length data - remain) data)) 0
| None, _ -> begin
Pipe.read reader >>= function
| None -> Or_error.fail (Failure "Premature EOF on input")
| v -> read_chunk v remain
end
in
let rec read remain =
read_until ?start:remain ~sep:"\r\n" reader >>=? fun (size_str, data) ->
begin
try Scanf.sscanf size_str "%x" (fun x -> x) |> Or_error.return
with _ -> Or_error.fail (Failure "Malformed chunk: Invalid length")
end >>=? fun chunk_size ->
match chunk_size with
| 0 -> read_until ?start:data ~sep:"\r\n" reader >>=? fun (_, remain) ->
Or_error.return remain
| n ->
read_chunk data n >>=? fun data ->
read_string ?start:data ~length:2 reader >>=? function
| ("\r\n", data) ->
read data
| (_, _data) ->
Or_error.fail (Failure "Malformed chunk: CRLF not present")
in
read start
end
|
a04cc01e95ee37f2609e35387e4c21060adf40ae132621d16412db026a9c0c13 | xapi-project/ocaml-opasswd | common.ml | let get_password name =
if Shadow.shadow_enabled ()
then Shadow.(with_lock (fun () ->
match getspnam name with
| None -> None
| Some sp -> Some sp.passwd))
else match Passwd.getpwnam name with
| None -> None
| Some pw -> Some pw.Passwd.passwd
let put_password name cipher =
if Shadow.shadow_enabled ()
then Shadow.(with_lock (fun () ->
match getspnam name with
| None -> ()
| Some sp ->
if cipher <> sp.passwd
then begin
get_db ()
|> fun db -> update_db db { sp with passwd = cipher }
|> write_db
end))
else Passwd.(
match getpwnam name with
| None -> ()
| Some pw ->
if cipher <> pw.passwd
then begin
get_db ()
|> fun db -> update_db db { pw with passwd = cipher }
|> write_db
end)
let rec unshadow acc = function
| [] -> List.rev acc
| pw::rest ->
match Shadow.getspnam pw.Passwd.name with
| None ->
unshadow (pw::acc) rest
| Some sp ->
unshadow ({ pw with Passwd.passwd = sp.Shadow.passwd }::acc) rest
let unshadow () =
if not (Shadow.shadow_enabled ())
then
Passwd.(get_db () |> db_to_string)
else
Shadow.with_lock (fun () -> Passwd.get_db () |> unshadow [])
|> Passwd.db_to_string
(* Local Variables: *)
(* indent-tabs-mode: nil *)
(* End: *)
| null | https://raw.githubusercontent.com/xapi-project/ocaml-opasswd/f7e608846d4f8a8b06343e97b662673897c73472/lib/common.ml | ocaml | Local Variables:
indent-tabs-mode: nil
End: | let get_password name =
if Shadow.shadow_enabled ()
then Shadow.(with_lock (fun () ->
match getspnam name with
| None -> None
| Some sp -> Some sp.passwd))
else match Passwd.getpwnam name with
| None -> None
| Some pw -> Some pw.Passwd.passwd
let put_password name cipher =
if Shadow.shadow_enabled ()
then Shadow.(with_lock (fun () ->
match getspnam name with
| None -> ()
| Some sp ->
if cipher <> sp.passwd
then begin
get_db ()
|> fun db -> update_db db { sp with passwd = cipher }
|> write_db
end))
else Passwd.(
match getpwnam name with
| None -> ()
| Some pw ->
if cipher <> pw.passwd
then begin
get_db ()
|> fun db -> update_db db { pw with passwd = cipher }
|> write_db
end)
let rec unshadow acc = function
| [] -> List.rev acc
| pw::rest ->
match Shadow.getspnam pw.Passwd.name with
| None ->
unshadow (pw::acc) rest
| Some sp ->
unshadow ({ pw with Passwd.passwd = sp.Shadow.passwd }::acc) rest
let unshadow () =
if not (Shadow.shadow_enabled ())
then
Passwd.(get_db () |> db_to_string)
else
Shadow.with_lock (fun () -> Passwd.get_db () |> unshadow [])
|> Passwd.db_to_string
|
47bdf3c5eca9ac9dea87ce7312e5ec0d6d6062a7f06dcfaf0c39f5b6a780331a | WhatsApp/eqwalizer | regular.erl | Copyright ( c ) Meta Platforms , Inc. and affiliates . All rights reserved .
%%%
This source code is licensed under the Apache 2.0 license found in
%%% the LICENSE file in the root directory of this source tree.
-module(regular).
| null | https://raw.githubusercontent.com/WhatsApp/eqwalizer/9935940d71ef65c7bf7a9dfad77d89c0006c288e/mini-elp/crates/parse_server/fixtures/regular.erl | erlang |
the LICENSE file in the root directory of this source tree. | Copyright ( c ) Meta Platforms , Inc. and affiliates . All rights reserved .
This source code is licensed under the Apache 2.0 license found in
-module(regular).
|
e79ff8aed537229d28c8c4e3a7fe51d7ee5f196de23d5d838447b1b55bc8626f | tamarin-prover/tamarin-prover | Rule.hs | {-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE StandaloneDeriving #
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeSynonymInstances #-}
# LANGUAGE MultiParamTypeClasses #
-- |
Copyright : ( c ) 2010 - 2012
-- License : GPL v3 (see LICENSE)
--
Maintainer : < >
-- Portability : portable
--
-- Rewriting rules representing protocol execution and intruder deduction. Once
modulo the full Diffie - Hellman equational theory and once modulo AC .
module Theory.Model.Rule (
-- * General Rules
Rule(..)
, PremIdx(..)
, ConcIdx(..)
-- ** Accessors
, rInfo
, rPrems
, rConcs
, rActs
, rPrem
, rConc
, rNewVars
, lookupPrem
, lookupConc
, enumPrems
, enumConcs
-- ** Extended positions
, ExtendedPosition
, printPosition
, printFactPosition
-- ** Genereal protocol and intruder rules
, RuleInfo(..)
, ruleInfo
-- * Protocol Rule Information
, RuleAttribute(..)
, ProtoRuleName(..)
, ProtoRuleEInfo(..)
, preName
, preAttributes
, preRestriction
, ProtoRuleACInfo(..)
, pracName
, pracAttributes
, pracVariants
, pracLoopBreakers
, ProtoRuleACInstInfo(..)
, praciName
, praciAttributes
, praciLoopBreakers
, RuleACConstrs
-- * Intruder Rule Information
, IntrRuleACInfo(..)
-- * Concrete Rules
, ProtoRuleE
, ProtoRuleAC
, IntrRuleAC
, RuleAC
, RuleACInst
-- ** Queries
, HasRuleName(..)
, HasRuleAttributes(..)
, isIntruderRule
, isDestrRule
, isIEqualityRule
, isConstrRule
, isPubConstrRule
, isFreshRule
, isIRecvRule
, isISendRule
, isCoerceRule
, isProtocolRule
, isConstantRule
, isSubtermRule
, containsNewVars
, getRuleName
, getRuleNameDiff
, getRemainingRuleApplications
, setRemainingRuleApplications
, nfRule
, normRule
, isTrivialProtoVariantAC
, getNewVariables
, getSubstitutionsFixingNewVars
, compareRulesUpToNewVars
, equalUpToAddedActions
, equalUpToTerms
-- ** Conversion
, ruleACToIntrRuleAC
, ruleACIntrToRuleAC
, ruleACIntrToRuleACInst
, getLeftRule
, getRightRule
, constrRuleToDestrRule
, destrRuleToConstrRule
, destrRuleToDestrRule
-- ** Construction
, someRuleACInst
, someRuleACInstAvoiding
, someRuleACInstAvoidingFixing
, someRuleACInstFixing
, addDiffLabel
, removeDiffLabel
, multRuleInstance
, unionRuleInstance
, xorRuleInstance
, addAction
-- ** Unification
, unifyRuleACInstEqs
, unifiableRuleACInsts
, equalRuleUpToRenaming
, equalRuleUpToAnnotations
, equalRuleUpToDiffAnnotation
, equalRuleUpToDiffAnnotationSym
-- * Pretty-Printing
, reservedRuleNames
, showRuleCaseName
, prettyRule
, prettyRuleRestrGen
, prettyRuleRestr
, prettyProtoRuleName
, prettyRuleName
, prettyRuleAttribute
, prettyProtoRuleE
, prettyProtoRuleAC
, prettyProtoRuleACasE
, prettyIntrRuleAC
, prettyIntrRuleACInfo
, prettyRuleAC
, prettyLoopBreakers
, prettyRuleACInst
, prettyProtoRuleACInstInfo
, prettyInstLoopBreakers
, prettyIntruderVariants) where
import Prelude hiding (id, (.))
import GHC.Generics (Generic)
import Data.Binary
import qualified Data.ByteString.Char8 as BC
import Data . Foldable ( foldMap )
import Data.Data
import Data.List
import qualified Data.Set as S
import qualified Data.Map as M
import Data.Monoid
-- import Data.Maybe (fromMaybe)
import Data.Color
import Safe
-- import Control.Basics
import Control.Category
import Control.DeepSeq
import Control.Monad.Bind
import Control.Monad.Reader
import Extension.Data.Label hiding (get)
import qualified Extension.Data.Label as L
import Logic.Connectives
import Term.LTerm
import Term.Positions
import Term.Rewriting.Norm (nf', norm')
import Term.Builtin.Convenience (var)
import Term.Unification
import Theory.Model.Fact
import qualified Theory.Model.Formula as F
import Theory.Text.Pretty
import Theory.Sapic
-- import Debug.Trace
------------------------------------------------------------------------------
-- General Rule
------------------------------------------------------------------------------
-- | Rewriting rules with arbitrary additional information and facts with names
-- and logical variables.
data Rule i = Rule {
_rInfo :: i
, _rPrems :: [LNFact]
, _rConcs :: [LNFact]
, _rActs :: [LNFact]
-- contains initially the new variables, then their instantiations
, _rNewVars :: [LNTerm]
}
deriving(Eq, Ord, Show, Data, Typeable, Generic)
instance NFData i => NFData (Rule i)
instance Binary i => Binary (Rule i)
$(mkLabels [''Rule])
| An index of a premise . The first premise has index ' 0 ' .
newtype PremIdx = PremIdx { getPremIdx :: Int }
deriving( Eq, Ord, Show, Enum, Data, Typeable, Binary, NFData )
| An index of a conclusion . The first conclusion has index ' 0 ' .
newtype ConcIdx = ConcIdx { getConcIdx :: Int }
deriving( Eq, Ord, Show, Enum, Data, Typeable, Binary, NFData )
-- | @lookupPrem i ru@ returns the @i@-th premise of rule @ru@, if possible.
lookupPrem :: PremIdx -> Rule i -> Maybe LNFact
lookupPrem i = (`atMay` getPremIdx i) . L.get rPrems
-- | @lookupConc i ru@ returns the @i@-th conclusion of rule @ru@, if possible.
lookupConc :: ConcIdx -> Rule i -> Maybe LNFact
lookupConc i = (`atMay` getConcIdx i) . L.get rConcs
-- | @rPrem i@ is a lens for the @i@-th premise of a rule.
rPrem :: PremIdx -> (Rule i :-> LNFact)
rPrem i = nthL (getPremIdx i) . rPrems
| is a lens for the @i@-th conclusion of a rule .
rConc :: ConcIdx -> (Rule i :-> LNFact)
rConc i = nthL (getConcIdx i) . rConcs
-- | Enumerate all premises of a rule.
enumPrems :: Rule i -> [(PremIdx, LNFact)]
enumPrems = zip [(PremIdx 0)..] . L.get rPrems
-- | Enumerate all conclusions of a rule.
enumConcs :: Rule i -> [(ConcIdx, LNFact)]
enumConcs = zip [(ConcIdx 0)..] . L.get rConcs
-- Instances
------------
we need special instances for and to ignore the new variable instantiations when comparing rules
instance ( Eq t ) = > Eq ( Rule t ) where
( Rule i0 as0 _ ) = = ( Rule i1 ps1 cs1 as1 _ ) =
( i0 = = i1 ) & & ( ps0 = = ps1 ) & & ( cs0 = = cs1 ) & & ( as0 = = )
compareRulesUpToNewVars :: (Ord i) => Rule i -> Rule i -> Ordering
compareRulesUpToNewVars (Rule i0 ps0 cs0 as0 _) (Rule i1 ps1 cs1 as1 _) =
if i0 == i1 then
if ps0 == ps1 then
if cs0 == cs1 then
compare as0 as1
else
compare cs0 cs1
else
compare ps0 ps1
else
compare i0 i1
deriving instance ( t ) = > Ord ( Rule t )
instance Functor Rule where
fmap f (Rule i ps cs as nvs) = Rule (f i) ps cs as nvs
instance (Show i, HasFrees i) => HasFrees (Rule i) where
foldFrees f (Rule i ps cs as nvs) =
(foldFrees f i `mappend`) $
(foldFrees f ps `mappend`) $
(foldFrees f cs `mappend`) $
(foldFrees f as `mappend`) $
(foldFrees f nvs)
-- We do not include the new variables in the occurrences
foldFreesOcc f c (Rule i ps cs as _) =
foldFreesOcc f ((show i):c) (ps, cs, as)
mapFrees f (Rule i ps cs as nvs) =
Rule <$> mapFrees f i
<*> mapFrees f ps <*> mapFrees f cs <*> mapFrees f as
<*> mapFrees f nvs
instance Apply LNSubst i => Apply LNSubst (Rule i) where
apply subst (Rule i ps cs as nvs) =
Rule (apply subst i) (apply subst ps) (apply subst cs) (apply subst as) (apply subst nvs)
instance Sized (Rule i) where
size (Rule _ ps cs as _) = size ps + size cs + size as
-----------------------------------------------
-- Extended Positions (of a term inside a rule)
-----------------------------------------------
type ExtendedPosition = (PremIdx, Int, Position)
printPosition :: ExtendedPosition -> String
printPosition (pidx, i, pos) = show (getPremIdx pidx) ++ "_" ++ show i ++ "_" ++ foldl (\x y -> x ++ show y ++ "_") "" pos
printFactPosition :: ExtendedPosition -> String
printFactPosition (pidx, _, _) = show (getPremIdx pidx)
------------------------------------------------------------------------------
-- Rule information split into intruder rule and protocol rules
------------------------------------------------------------------------------
-- | Rule information for protocol and intruder rules.
data RuleInfo p i =
ProtoInfo p
| IntrInfo i
deriving( Eq, Ord, Show, Generic)
instance (NFData i, NFData p) => NFData (RuleInfo p i)
instance (Binary i, Binary p) => Binary (RuleInfo p i)
-- | @ruleInfo proto intr@ maps the protocol information with @proto@ and the
-- intruder information with @intr@.
ruleInfo :: (p -> c) -> (i -> c) -> RuleInfo p i -> c
ruleInfo proto _ (ProtoInfo x) = proto x
ruleInfo _ intr (IntrInfo x) = intr x
-- Instances
------------
instance (HasFrees p, HasFrees i) => HasFrees (RuleInfo p i) where
foldFrees f = ruleInfo (foldFrees f) (foldFrees f)
foldFreesOcc _ _ = const mempty
mapFrees f = ruleInfo (fmap ProtoInfo . mapFrees f)
(fmap IntrInfo . mapFrees f)
instance (Apply s p, Apply s i) => Apply s (RuleInfo p i) where
apply subst = ruleInfo (ProtoInfo . apply subst) (IntrInfo . apply subst)
------------------------------------------------------------------------------
-- Protocol Rule Information
------------------------------------------------------------------------------
-- | An attribute for a Rule, which does not affect the semantics.
Color for display
| Process (PlainProcess)-- Process: for display, but also to recognise
lookup rule generated by SAPIC
-- which needs relaxed treatment in wellformedness check
TODO This type has no annotations , to avoid
dependency to . Annotations
-- need to see what we need here later.
deriving( Eq, Ord, Show, Data, Generic)
instance NFData RuleAttribute
instance Binary RuleAttribute
-- | A name of a protocol rule is either one of the special reserved rules or
-- some standard rule.
data ProtoRuleName =
FreshRule
| StandRule String -- ^ Some standard protocol rule
deriving( Eq, Ord, Show, Data, Typeable, Generic)
instance NFData ProtoRuleName
instance Binary ProtoRuleName
-- | Information for protocol rules modulo E.
data ProtoRuleEInfo = ProtoRuleEInfo
{ _preName :: ProtoRuleName
, _preAttributes :: [RuleAttribute]
, _preRestriction:: [F.SyntacticLNFormula]
}
deriving( Eq, Ord, Show, Data, Generic)
instance NFData ProtoRuleEInfo
instance Binary ProtoRuleEInfo
-- | Information for protocol rules modulo AC. The variants list the possible
-- instantiations of the free variables of the rule. The source is interpreted
-- modulo AC; i.e., its variants were also built.
data ProtoRuleACInfo = ProtoRuleACInfo
{ _pracName :: ProtoRuleName
, _pracAttributes :: [RuleAttribute]
, _pracVariants :: Disj (LNSubstVFresh)
, _pracLoopBreakers :: [PremIdx]
}
deriving(Eq, Ord, Show, Generic)
instance NFData ProtoRuleACInfo
instance Binary ProtoRuleACInfo
-- | Information for instances of protocol rules modulo AC.
data ProtoRuleACInstInfo = ProtoRuleACInstInfo
{ _praciName :: ProtoRuleName
, _praciAttributes :: [RuleAttribute]
, _praciLoopBreakers :: [PremIdx]
}
deriving(Eq, Ord, Show, Generic)
instance NFData ProtoRuleACInstInfo
instance Binary ProtoRuleACInstInfo
$(mkLabels [''ProtoRuleEInfo, ''ProtoRuleACInfo, ''ProtoRuleACInstInfo])
-- Instances
------------
instance Apply s RuleAttribute where
apply _ = id
instance HasFrees RuleAttribute where
foldFrees _ = const mempty
foldFreesOcc _ _ = const mempty
mapFrees _ = pure
instance Apply s ProtoRuleName where
apply _ = id
instance HasFrees ProtoRuleName where
foldFrees _ = const mempty
foldFreesOcc _ _ = const mempty
mapFrees _ = pure
instance Apply s PremIdx where
apply _ = id
instance HasFrees PremIdx where
foldFrees _ = const mempty
foldFreesOcc _ _ = const mempty
mapFrees _ = pure
instance Apply s ConcIdx where
apply _ = id
instance HasFrees ConcIdx where
foldFrees _ = const mempty
foldFreesOcc _ _ = const mempty
mapFrees _ = pure
instance HasFrees ProtoRuleEInfo where
foldFrees f (ProtoRuleEInfo na attr rstr) =
foldFrees f na `mappend` foldFrees f attr `mappend` foldFrees f rstr
foldFreesOcc _ _ = const mempty
mapFrees f (ProtoRuleEInfo na attr rstr) =
ProtoRuleEInfo na <$> mapFrees f attr <*> mapFrees f rstr
instance Apply s ProtoRuleEInfo where
apply _ = id
instance HasFrees ProtoRuleACInfo where
foldFrees f (ProtoRuleACInfo na attr vari breakers) =
foldFrees f na `mappend` foldFrees f attr
`mappend` foldFrees f vari
`mappend` foldFrees f breakers
foldFreesOcc _ _ = const mempty
mapFrees f (ProtoRuleACInfo na attr vari breakers) =
ProtoRuleACInfo na <$> mapFrees f attr
<*> mapFrees f vari
<*> mapFrees f breakers
instance Apply s ProtoRuleACInstInfo where
apply subst (ProtoRuleACInstInfo na attr breakers) =
ProtoRuleACInstInfo (apply subst na) attr breakers
instance HasFrees ProtoRuleACInstInfo where
foldFrees f (ProtoRuleACInstInfo na attr breakers) =
foldFrees f na `mappend` foldFrees f attr
`mappend` foldFrees f breakers
foldFreesOcc _ _ = const mempty
mapFrees f (ProtoRuleACInstInfo na attr breakers) =
ProtoRuleACInstInfo na <$> mapFrees f attr <*> mapFrees f breakers
------------------------------------------------------------------------------
-- Intruder Rule Information
------------------------------------------------------------------------------
-- | An intruder rule modulo AC is described by its name.
data IntrRuleACInfo =
ConstrRule BC.ByteString
| DestrRule BC.ByteString Int Bool Bool
-- the number of remaining consecutive applications of this destruction rule, 0 means unbounded, -1 means not yet determined
true if the RHS is a true subterm of the LHS
true if the RHS is a constant
| CoerceRule
| IRecvRule
| ISendRule
| PubConstrRule
| FreshConstrRule
| IEqualityRule -- Necessary for diff
deriving( Ord, Eq, Show, Data, Typeable, Generic)
instance NFData IntrRuleACInfo
instance Binary IntrRuleACInfo
-- | An intruder rule modulo AC.
type IntrRuleAC = Rule IntrRuleACInfo
| Converts between these two types of rules , if possible .
ruleACToIntrRuleAC :: RuleAC -> Maybe IntrRuleAC
ruleACToIntrRuleAC (Rule (IntrInfo i) ps cs as nvs) = Just (Rule i ps cs as nvs)
ruleACToIntrRuleAC _ = Nothing
| Converts between these two types of rules .
ruleACIntrToRuleAC :: IntrRuleAC -> RuleAC
ruleACIntrToRuleAC (Rule ri ps cs as nvs) = Rule (IntrInfo ri) ps cs as nvs
| Converts between these two types of rules .
ruleACIntrToRuleACInst :: IntrRuleAC -> RuleACInst
ruleACIntrToRuleACInst (Rule ri ps cs as nvs) = Rule (IntrInfo ri) ps cs as nvs
-- | Converts between constructor and destructor rules.
constrRuleToDestrRule :: RuleAC -> Int -> Bool -> Bool -> [RuleAC]
constrRuleToDestrRule (Rule (IntrInfo (ConstrRule name)) ps' cs _ _) i s c
-- we remove the actions and new variables as destructors do not have actions or new variables
= map toRule $ permutations ps'
where
toRule :: [LNFact] -> RuleAC
toRule [] = error "Bug in constrRuleToDestrRule. Please report."
toRule (p:ps) = Rule (IntrInfo (DestrRule name i s c)) ((convertKUtoKD p):ps) (map convertKUtoKD cs) [] []
constrRuleToDestrRule _ _ _ _ = error "Not a destructor rule."
-- | Converts between destructor and constructor rules.
destrRuleToConstrRule :: FunSym -> Int -> RuleAC -> [RuleAC]
destrRuleToConstrRule f l (Rule (IntrInfo (DestrRule name _ _ _)) ps cs _ _)
= map (\x -> toRule x (conclusions cs)) (permutations (map convertKDtoKU ps ++ kuFacts))
where
-- we add the conclusion as an action as constructors have this action
toRule :: [LNFact] -> [LNFact] -> RuleAC
toRule ps' cs' = Rule (IntrInfo (ConstrRule name)) ps' cs' cs' []
conclusions [] = []
KD and KU facts only have one term
conclusions ((Fact KDFact ann (m:ms)):cs') = (Fact KUFact ann ((addTerms m):ms)):(conclusions cs')
conclusions (c:cs') = c:(conclusions cs')
addTerms (FAPP f' t) | f'==f = fApp f (t ++ newvars)
addTerms t = fApp f (t:newvars)
kuFacts = map kuFact newvars
newvars = map (var "z") [1..(toInteger $ l-(length ps))]
destrRuleToConstrRule _ _ _ = error "Not a constructor rule."
| Creates variants of a destructor rule , where KD and KU facts are permuted .
destrRuleToDestrRule :: RuleAC -> [RuleAC]
destrRuleToDestrRule (Rule (IntrInfo (DestrRule name i s c)) ps' cs as nv)
= map toRule $ permutations (map convertKDtoKU ps')
where
toRule [] = error "Bug in destrRuleToDestrRule. Please report."
toRule (p:ps) = Rule (IntrInfo (DestrRule name i s c)) ((convertKUtoKD p):ps) cs as nv
destrRuleToDestrRule _ = error "Not a destructor rule."
-- Instances
------------
instance Apply s IntrRuleACInfo where
apply _ = id
instance HasFrees IntrRuleACInfo where
foldFrees _ = const mempty
foldFreesOcc _ _ = const mempty
mapFrees _ = pure
------------------------------------------------------------------------------
-- Concrete rules
------------------------------------------------------------------------------
-- | A rule modulo E is always a protocol rule. Intruder rules are specified
-- abstractly by their operations generating them and are only available once
-- their variants are built.
type ProtoRuleE = Rule ProtoRuleEInfo
-- | A protocol rule modulo AC.
type ProtoRuleAC = Rule ProtoRuleACInfo
-- | A rule modulo AC is either a protocol rule or an intruder rule
type RuleAC = Rule (RuleInfo ProtoRuleACInfo IntrRuleACInfo)
-- | A rule instance module AC is either a protocol rule or an intruder rule.
-- The info identifies the corresponding rule modulo AC that the instance was
-- derived from.
type RuleACInst = Rule (RuleInfo ProtoRuleACInstInfo IntrRuleACInfo)
-- Accessing the rule name
--------------------------
-- | Types that have an associated name.
class HasRuleName t where
ruleName :: t -> RuleInfo ProtoRuleName IntrRuleACInfo
instance HasRuleName ProtoRuleE where
ruleName = ProtoInfo . L.get (preName . rInfo)
instance HasRuleName RuleAC where
ruleName = ruleInfo (ProtoInfo . L.get pracName) IntrInfo . L.get rInfo
instance HasRuleName ProtoRuleAC where
ruleName = ProtoInfo . L.get (pracName . rInfo)
instance HasRuleName IntrRuleAC where
ruleName = IntrInfo . L.get rInfo
instance HasRuleName RuleACInst where
ruleName = ruleInfo (ProtoInfo . L.get praciName) IntrInfo . L.get rInfo
class HasRuleAttributes t where
ruleAttributes :: t -> [RuleAttribute]
instance HasRuleAttributes ProtoRuleE where
ruleAttributes = L.get (preAttributes . rInfo)
instance HasRuleAttributes RuleAC where
ruleAttributes (Rule (ProtoInfo ri) _ _ _ _) = L.get pracAttributes ri
ruleAttributes _ = []
instance HasRuleAttributes ProtoRuleAC where
ruleAttributes = L.get (pracAttributes . rInfo)
instance HasRuleAttributes IntrRuleAC where
ruleAttributes _ = []
instance HasRuleAttributes RuleACInst where
ruleAttributes (Rule (ProtoInfo ri) _ _ _ _) = L.get praciAttributes ri
ruleAttributes _ = []
Queries
----------
-- | True iff the rule is a destruction rule.
isDestrRule :: HasRuleName r => r -> Bool
isDestrRule ru = case ruleName ru of
IntrInfo (DestrRule _ _ _ _) -> True
IntrInfo IEqualityRule -> True
_ -> False
-- | True iff the rule is an iequality rule.
isIEqualityRule :: HasRuleName r => r -> Bool
isIEqualityRule ru = case ruleName ru of
IntrInfo IEqualityRule -> True
_ -> False
-- | True iff the rule is a construction rule.
isConstrRule :: HasRuleName r => r -> Bool
isConstrRule ru = case ruleName ru of
IntrInfo (ConstrRule _) -> True
IntrInfo FreshConstrRule -> True
IntrInfo PubConstrRule -> True
IntrInfo CoerceRule -> True
_ -> False
-- | True iff the rule is a construction rule.
isPubConstrRule :: HasRuleName r => r -> Bool
isPubConstrRule ru = case ruleName ru of
IntrInfo PubConstrRule -> True
_ -> False
-- | True iff the rule is the special fresh rule.
isFreshRule :: HasRuleName r => r -> Bool
isFreshRule = (ProtoInfo FreshRule ==) . ruleName
-- | True iff the rule is the special learn rule.
isIRecvRule :: HasRuleName r => r -> Bool
isIRecvRule = (IntrInfo IRecvRule ==) . ruleName
-- | True iff the rule is the special knows rule.
isISendRule :: HasRuleName r => r -> Bool
isISendRule = (IntrInfo ISendRule ==) . ruleName
-- | True iff the rule is the special coerce rule.
isCoerceRule :: HasRuleName r => r -> Bool
isCoerceRule = (IntrInfo CoerceRule ==) . ruleName
-- | True iff the rule is a destruction rule with constant RHS.
isConstantRule :: HasRuleName r => r -> Bool
isConstantRule ru = case ruleName ru of
IntrInfo (DestrRule _ _ _ constant) -> constant
_ -> False
| True iff the rule is a destruction rule where the RHS is a true subterm of the LHS .
isSubtermRule :: HasRuleName r => r -> Bool
isSubtermRule ru = case ruleName ru of
IntrInfo (DestrRule _ _ subterm _) -> subterm
IntrInfo IEqualityRule -> True
-- the equality rule is considered a subterm rule, as it has no RHS.
_ -> False
-- | True if the messages in premises and conclusions are in normal form
nfRule :: Rule i -> WithMaude Bool
nfRule (Rule _ ps cs as nvs) = reader $ \hnd ->
all (nfFactList hnd) [ps, cs, as, map termFact nvs]
where
nfFactList hnd xs =
getAll $ foldMap (foldMap (All . (\t -> nf' t `runReader` hnd))) xs
-- | Normalize all terms in premises, actions and conclusions
normRule :: Rule i -> WithMaude (Rule i)
normRule (Rule rn ps cs as nvs) = reader $ \hnd -> (Rule rn (normFacts ps hnd) (normFacts cs hnd) (normFacts as hnd) (normTerms nvs hnd))
where
normFacts fs hnd' = map (\f -> runReader (normFact f) hnd') fs
normTerms fs hnd' = map (\f -> runReader (norm' f) hnd') fs
-- | True iff the rule is an intruder rule
isIntruderRule :: HasRuleName r => r -> Bool
isIntruderRule ru =
case ruleName ru of IntrInfo _ -> True; ProtoInfo _ -> False
-- | True iff the rule is an intruder rule
isProtocolRule :: HasRuleName r => r -> Bool
isProtocolRule ru =
case ruleName ru of IntrInfo _ -> False; ProtoInfo _ -> True
-- | True if the protocol rule has only the trivial variant.
isTrivialProtoVariantAC :: ProtoRuleAC -> ProtoRuleE -> Bool
isTrivialProtoVariantAC (Rule info ps as cs nvs) (Rule _ ps' as' cs' nvs') =
L.get pracVariants info == Disj [emptySubstVFresh]
&& ps == ps' && as == as' && cs == cs' && nvs == nvs'
-- | Returns a rule's name
getRuleName :: HasRuleName (Rule i) => Rule i -> String
getRuleName ru = case ruleName ru of
IntrInfo i -> case i of
ConstrRule x -> "Constr" ++ (prefixIfReserved ('c' : BC.unpack x))
DestrRule x _ _ _ -> "Destr" ++ (prefixIfReserved ('d' : BC.unpack x))
CoerceRule -> "Coerce"
IRecvRule -> "Recv"
ISendRule -> "Send"
PubConstrRule -> "PubConstr"
FreshConstrRule -> "FreshConstr"
IEqualityRule -> "Equality"
ProtoInfo p -> case p of
FreshRule -> "FreshRule"
StandRule s -> s
-- | Returns a protocol rule's name
getRuleNameDiff :: HasRuleName (Rule i) => Rule i -> String
getRuleNameDiff ru = case ruleName ru of
IntrInfo i -> "Intr" ++ case i of
ConstrRule x -> "Constr" ++ (prefixIfReserved ('c' : BC.unpack x))
DestrRule x _ _ _ -> "Destr" ++ (prefixIfReserved ('d' : BC.unpack x))
CoerceRule -> "Coerce"
IRecvRule -> "Recv"
ISendRule -> "Send"
PubConstrRule -> "PubConstr"
FreshConstrRule -> "FreshConstr"
IEqualityRule -> "Equality"
ProtoInfo p -> "Proto" ++ case p of
FreshRule -> "FreshRule"
StandRule s -> s
-- | Returns the remaining rule applications within the deconstruction chain if possible, 0 otherwise
getRemainingRuleApplications :: RuleACInst -> Int
getRemainingRuleApplications ru = case ruleName ru of
IntrInfo (DestrRule _ i _ _) -> i
_ -> 0
-- | Sets the remaining rule applications within the deconstruction chain if possible
setRemainingRuleApplications :: RuleACInst -> Int -> RuleACInst
setRemainingRuleApplications (Rule (IntrInfo (DestrRule name _ subterm constant)) prems concs acts nvs) i
= Rule (IntrInfo (DestrRule name i subterm constant)) prems concs acts nvs
setRemainingRuleApplications rule _
= rule
-- | Converts a protocol rule to its "left" variant
getLeftRule :: Rule i -> Rule i
getLeftRule (Rule ri ps cs as nvs) =
Rule ri (map getLeftFact ps) (map getLeftFact cs) (map getLeftFact as) (map getLeftTerm nvs)
-- | Converts a protocol rule to its "right" variant
getRightRule :: Rule i -> Rule i
getRightRule (Rule ri ps cs as nvs) =
Rule ri (map getRightFact ps) (map getRightFact cs) (map getRightFact as) (map getRightTerm nvs)
-- | Returns a list of all new variables that need to be fixed for mirroring
getNewVariables :: Bool -> RuleACInst -> [LVar]
getNewVariables showPubVars (Rule _ _ _ _ nvs) = case showPubVars of
True -> newvars
False -> filter (\v -> not $ lvarSort v == LSortPub) newvars
where
newvars = toVariables nvs
toVariables [] = []
toVariables (x:xs) = case getVar x of
Just v -> v:(toVariables xs)
-- if the variable is already fixed, no need to fix it again!
Nothing -> toVariables xs
-- | Returns whether a given rule has new variables
containsNewVars :: RuleACInst -> Bool
containsNewVars (Rule _ _ _ _ nvs) = nvs == []
-- | Given a fresh rule instance and the rule instance to mirror, returns a substitution
-- determining how all new variables need to be instantiated if possible.
First parameter : original instance to mirror
Second parameter : fresh instance
getSubstitutionsFixingNewVars :: RuleACInst -> RuleACInst -> Maybe LNSubst
getSubstitutionsFixingNewVars (Rule (ProtoInfo (ProtoRuleACInstInfo _ _ _)) _ _ _ instancesO)
(Rule (ProtoInfo (ProtoRuleACInstInfo _ _ _)) _ _ _ instancesF)
| all (\(x, y) -> isPubVar x || x == y) $ zip instancesF instancesO
= Just $ Subst $ M.fromList $ substList instancesF instancesO
-- otherwise there is no substitution
| otherwise
= Nothing
where
substList [] [] = []
substList (f:fs) (o:os) = case getVar f of
Nothing -> (substList fs os)
Just v -> (v, o):(substList fs os)
substList _ _ = error "getSubstitutionsFixingNewVars: different number of new variables"
getSubstitutionsFixingNewVars _ _
= error "getSubstitutionsFixingNewVars: not called on a protocol rule" -- FIXME: Nothing?
| returns true if the first Rule has the same name , premise , conclusion and
-- action facts, ignoring added action facts and other rule information
-- TODO: Ignore renaming?
equalUpToAddedActions :: (HasRuleName (Rule i), HasRuleName (Rule i2)) => (Rule i) -> (Rule i2) -> Bool
equalUpToAddedActions ruAC@(Rule _ ps cs as _) ruE@(Rule _ ps' cs' as' _) =
ruleName ruE == ruleName ruAC && ps == ps' && cs == cs' && compareActions as as'
where
compareActions _ [] = True
compareActions [] _ = False
compareActions (a:ass) (a':ass') = if a == a'
then compareActions ass ass'
else compareActions ass (a':ass')
| returns true if the first Rule has the same name , premise , conclusion and
-- action facts, ignoring terms
equalUpToTerms :: (HasRuleName (Rule i), HasRuleName (Rule i2)) => (Rule i) -> (Rule i2) -> Bool
equalUpToTerms ruAC@(Rule _ ps cs as _) ruE@(Rule _ ps' cs' as' _) =
ruleName ruE == ruleName ruAC
&& length ps == length ps' && length cs == length cs' && length as == length as'
&& foldl sameFacts True (zip ps ps') && foldl sameFacts True (zip cs cs')
&& foldl sameFacts True (zip as as')
where
sameFacts b (f1, f2) = b && sameFact f1 f2
sameFact (Fact tag _ _) (Fact tag' _ _) = tag == tag'
-- Construction
---------------
-- | Returns a multiplication rule instance of the given size.
multRuleInstance :: Int -> RuleAC
multRuleInstance n = (Rule (IntrInfo (ConstrRule $ BC.pack "_mult")) (map xifact [1..n]) [prod] [prod] [])
where
prod = kuFact (FAPP (AC Mult) (map xi [1..n]))
xi :: Int -> LNTerm
xi k = (LIT $ Var $ LVar "x" LSortMsg (toInteger k))
xifact :: Int -> LNFact
xifact k = kuFact (xi k)
-- | Returns a union rule instance of the given size.
unionRuleInstance :: Int -> RuleAC
unionRuleInstance n = (Rule (IntrInfo (ConstrRule $ BC.pack "_union")) (map xifact [1..n]) [prod] [prod] [])
where
prod = kuFact (FAPP (AC Union) (map xi [1..n]))
xi :: Int -> LNTerm
xi k = (LIT $ Var $ LVar "x" LSortMsg (toInteger k))
xifact :: Int -> LNFact
xifact k = kuFact (xi k)
-- | Returns a xor rule instance of the given size.
xorRuleInstance :: Int -> RuleAC
xorRuleInstance n = (Rule (IntrInfo (ConstrRule $ BC.pack "_xor")) (map xifact [1..n]) [prod] [prod] [])
where
prod = Fact KUFact S.empty [(FAPP (AC Xor) (map xi [1..n]))]
xi :: Int -> LNTerm
xi k = (LIT $ Var $ LVar "x" LSortMsg (toInteger k))
xifact :: Int -> LNFact
xifact k = Fact KUFact S.empty [(xi k)]
type RuleACConstrs = Disj LNSubstVFresh
-- | Compute /some/ rule instance of a rule modulo AC. If the rule is a
-- protocol rule, then the given source and variants also need to be handled.
someRuleACInst :: MonadFresh m
=> RuleAC
-> m (RuleACInst, Maybe RuleACConstrs)
someRuleACInst =
fmap extractInsts . rename
where
extractInsts (Rule (ProtoInfo i) ps cs as nvs) =
( Rule (ProtoInfo i') ps cs as nvs
, Just (L.get pracVariants i)
)
where
i' = ProtoRuleACInstInfo (L.get pracName i)
(L.get pracAttributes i)
(L.get pracLoopBreakers i)
extractInsts (Rule (IntrInfo i) ps cs as nvs) =
( Rule (IntrInfo i) ps cs as nvs, Nothing )
-- | Compute /some/ rule instance of a rule modulo AC. If the rule is a
-- protocol rule, then the given source and variants also need to be handled.
someRuleACInstAvoiding :: HasFrees t
=> RuleAC
-> t
-> (RuleACInst, Maybe RuleACConstrs)
someRuleACInstAvoiding r s =
renameAvoiding (extractInsts r) s
where
extractInsts (Rule (ProtoInfo i) ps cs as nvs) =
( Rule (ProtoInfo i') ps cs as nvs
, Just (L.get pracVariants i)
)
where
i' = ProtoRuleACInstInfo (L.get pracName i)
(L.get pracAttributes i)
(L.get pracLoopBreakers i)
extractInsts (Rule (IntrInfo i) ps cs as nvs) =
( Rule (IntrInfo i) ps cs as nvs, Nothing )
-- | Compute /some/ rule instance of a rule modulo AC. If the rule is a
-- protocol rule, then the given source and variants also need to be handled.
someRuleACInstFixing :: MonadFresh m
=> RuleAC
-> LNSubst
-> m (RuleACInst, Maybe RuleACConstrs)
someRuleACInstFixing r subst =
renameIgnoring (varsRange subst) (extractInsts r)
where
extractInsts (Rule (ProtoInfo i) ps cs as nvs) =
( apply subst (Rule (ProtoInfo i') ps cs as nvs)
, Just (L.get pracVariants i)
)
where
i' = ProtoRuleACInstInfo (L.get pracName i)
(L.get pracAttributes i)
(L.get pracLoopBreakers i)
extractInsts (Rule (IntrInfo i) ps cs as nvs) =
( apply subst (Rule (IntrInfo i) ps cs as nvs), Nothing )
-- | Compute /some/ rule instance of a rule modulo AC. If the rule is a
-- protocol rule, then the given source and variants also need to be handled.
someRuleACInstAvoidingFixing :: HasFrees t
=> RuleAC
-> t
-> LNSubst
-> (RuleACInst, Maybe RuleACConstrs)
someRuleACInstAvoidingFixing r s subst =
renameAvoidingIgnoring (extractInsts r) s (varsRange subst)
where
extractInsts (Rule (ProtoInfo i) ps cs as nvs) =
( apply subst (Rule (ProtoInfo i') ps cs as nvs)
, Just (L.get pracVariants i)
)
where
i' = ProtoRuleACInstInfo (L.get pracName i)
(L.get pracAttributes i)
(L.get pracLoopBreakers i)
extractInsts (Rule (IntrInfo i) ps cs as nvs) =
( apply subst (Rule (IntrInfo i) ps cs as nvs), Nothing )
-- | Add the diff label to a rule
addDiffLabel :: Rule a -> String -> Rule a
addDiffLabel (Rule info prems concs acts nvs) name =
Rule info prems concs
(acts ++ [Fact {factTag = ProtoFact Linear name 0,
factAnnotations = S.empty, factTerms = []}]) nvs
-- | Remove the diff label from a rule
removeDiffLabel :: Rule a -> String -> Rule a
removeDiffLabel (Rule info prems concs acts nvs) name =
Rule info prems concs (filter isNotDiffAnnotation acts) nvs
where
isNotDiffAnnotation fa =
fa /= Fact {factTag = ProtoFact Linear name 0,
factAnnotations = S.empty, factTerms = []}
-- | Add an action label to a rule
addAction :: Rule a -> LNFact -> Rule a
addAction (Rule info prems concs acts nvs) act =
if act `elem` acts
then Rule info prems concs acts nvs
else Rule info prems concs (act:acts) nvs
Unification
--------------
| Unify a list of @RuleACInst@ equalities .
unifyRuleACInstEqs :: [Equal RuleACInst] -> WithMaude [LNSubstVFresh]
unifyRuleACInstEqs eqs
| all unifiable eqs = unifyLNFactEqs $ concatMap ruleEqs eqs
| otherwise = return []
where
unifiable (Equal ru1 ru2) =
L.get rInfo ru1 == L.get rInfo ru2
&& length (L.get rPrems ru1) == length (L.get rPrems ru2)
&& length (L.get rConcs ru1) == length (L.get rConcs ru2)
ruleEqs (Equal ru1 ru2) =
zipWith Equal (L.get rPrems ru1) (L.get rPrems ru2) ++
zipWith Equal (L.get rConcs ru1) (L.get rConcs ru2)
| Are these two rule instances unifiable ?
unifiableRuleACInsts :: RuleACInst -> RuleACInst -> WithMaude Bool
unifiableRuleACInsts ru1 ru2 =
(not . null) <$> unifyRuleACInstEqs [Equal ru1 ru2]
| Are these two rule instances equal up to renaming of variables ?
equalRuleUpToRenaming :: (Show a, Eq a, HasFrees a) => Rule a -> Rule a -> WithMaude Bool
equalRuleUpToRenaming r1@(Rule rn1 pr1 co1 ac1 nvs1) r2@(Rule rn2 pr2 co2 ac2 nvs2) = reader $ \hnd ->
case eqs of
Nothing -> False
Just eqs' -> (rn1 == rn2) && (any isRenamingPerRule $ unifs eqs' hnd)
where
isRenamingPerRule subst = isRenaming (restrictVFresh (vars r1) subst) && isRenaming (restrictVFresh (vars r2) subst)
vars ru = map fst $ varOccurences ru
unifs eq hnd = unifyLNTerm eq `runReader` hnd
eqs = foldl matchFacts (Just $ zipWith Equal nvs1 nvs2) $ zip (pr1++co1++ac1) (pr2++co2++ac2)
matchFacts Nothing _ = Nothing
matchFacts (Just l) (Fact f1 _ t1, Fact f2 _ t2) | f1 == f2 = Just ((zipWith Equal t1 t2)++l)
| otherwise = Nothing
| Are these two rule instances equal up to added annotations in ?
equalRuleUpToAnnotations :: (Eq a) => Rule a -> Rule a -> Bool
equalRuleUpToAnnotations (Rule rn1 pr1 co1 ac1 nvs1) (Rule rn2 pr2 co2 ac2 nvs2) =
rn1 == rn2 && pr1 == pr2 && co1 == co2 && nvs1 == nvs2 &&
S.isSubsetOf (S.fromList ac1) (S.fromList ac2)
| Are these two rule instances equal up to an added diff annotation in ?
equalRuleUpToDiffAnnotation :: (HasRuleName (Rule a), Eq a) => Rule a -> Rule a -> Bool
equalRuleUpToDiffAnnotation ru1@(Rule rn1 pr1 co1 ac1 nvs1) (Rule rn2 pr2 co2 ac2 nvs2) =
rn1 == rn2 && pr1 == pr2 && co1 == co2 && nvs1 == nvs2 &&
ac1 == filter isNotDiffAnnotation ac2
where
isNotDiffAnnotation fa = (fa /= Fact {factTag = ProtoFact Linear ("Diff" ++ getRuleNameDiff ru1) 0, factAnnotations = S.empty, factTerms = []})
| Are these two rule instances equal up to an added diff annotation in or @ac1@ ?
equalRuleUpToDiffAnnotationSym :: (HasRuleName (Rule a), Eq a) => Rule a -> Rule a -> Bool
equalRuleUpToDiffAnnotationSym ru1 ru2 = equalRuleUpToDiffAnnotation ru1 ru2
|| equalRuleUpToDiffAnnotation ru2 ru1
------------------------------------------------------------------------------
-- Fact analysis
------------------------------------------------------------------------------
-- | Globally unique facts.
--
A rule instance removes a fact fa if is in the rule 's premise but not
-- in the rule's conclusion.
--
-- A fact symbol fa is globally fresh with respect to a dependency graph if
there are no two rule instances that remove the same fact built from fa .
--
-- We are looking for sufficient criterion to prove that a fact symbol is
-- globally fresh.
--
-- The Fr symbol is globally fresh by construction.
--
-- We have to track every creation of a globally fresh fact to a Fr fact.
--
-- (And show that the equality of of the created fact implies the equality of
-- the corresponding fresh facts. Ignore this for now by assuming that no
-- duplication happens.)
--
-- (fa(x1), fr(y1)), (fa(x2), fr(y2)) : x2 = x1 ==> y1 == y2
--
-- And ensure that every duplication is non-unifiable.
--
-- A Fr fact is described
--
-- We track which symbols are not globally fresh.
--
-- All persistent facts are not globally fresh.
--
-- Adding a rule ru.
-- All fact symbols that occur twice in the conclusion
--
-- For simplicity: globally fresh fact symbols occur at most once in premise
-- and conclusion of a rule.
--
-- A fact is removed by a rule if it occurs in the rules premise
-- 1. but doesn't occur in the rule's conclusion
2 . or does occur but non - unifiable .
--
-- We want a sufficient criterion to prove that a fact is globally unique.
--
--
------------------------------------------------------------------------------
-- Pretty-Printing
------------------------------------------------------------------------------
-- | Prefix the name if it is equal to a reserved name.
--
-- NOTE: We maintain the invariant that a theory does not contain standard
-- rules with a reserved name. This is a last ressort. The pretty-printed
-- theory can then not be parsed anymore.
prefixIfReserved :: String -> String
prefixIfReserved n
| n `elem` reservedRuleNames = "_" ++ n
| "_" `isPrefixOf` n = "_" ++ n
| otherwise = n
-- | List of all reserved rule names.
reservedRuleNames :: [String]
reservedRuleNames = ["Fresh", "irecv", "isend", "coerce", "fresh", "pub", "iequality"]
prettyProtoRuleName :: Document d => ProtoRuleName -> d
prettyProtoRuleName rn = text $ case rn of
FreshRule -> "Fresh"
StandRule n -> prefixIfReserved n
prettyRuleName :: (HighlightDocument d, HasRuleName (Rule i)) => Rule i -> d
prettyRuleName = ruleInfo prettyProtoRuleName prettyIntrRuleACInfo . ruleName
prettyRuleAttribute :: (HighlightDocument d) => RuleAttribute -> d
prettyRuleAttribute attr = case attr of
RuleColor c -> text "color=" <> text (rgbToHex c)
Process p -> text "process=" <> text ("\"" ++ prettySapicTopLevel' f p ++ "\"")
where f l a r rest _ = render $ prettyRuleRestr (g l) (g a) (g r) (h rest)
g = map toLNFact
h = map toLFormula
-- | Pretty print the rule name such that it can be used as a case name
showRuleCaseName :: HasRuleName (Rule i) => Rule i -> String
showRuleCaseName =
render . ruleInfo prettyProtoRuleName prettyIntrRuleACInfo . ruleName
prettyIntrRuleACInfo :: Document d => IntrRuleACInfo -> d
prettyIntrRuleACInfo rn = text $ case rn of
IRecvRule -> "irecv"
ISendRule -> "isend"
CoerceRule -> "coerce"
FreshConstrRule -> "fresh"
PubConstrRule -> "pub"
IEqualityRule -> "iequality"
ConstrRule name -> prefixIfReserved ('c' : BC.unpack name)
DestrRule name _ _ _ -> prefixIfReserved ('d' : BC.unpack name)
DestrRule name i - > prefixIfReserved ( 'd ' : BC.unpack name + + " _ " + + show i )
TODO may be removed
prettyRestr : : d = > F.SyntacticLNFormula - > d
prettyRestr fact = operator _ " _ restrict ( " < > text ( filter ( /= ' # ' ) $ render $ F.prettySyntacticLNFormula fact ) < > operator _ " ) "
-- | pretty-print rules with restrictions
prettyRuleRestrGen :: (HighlightDocument d) => (f -> d) -> (r -> d) -> [f] -> [f] -> [f] -> [r] -> d
prettyRuleRestrGen ppFact ppRestr prems acts concls restr=
sep [ nest 1 $ ppFactsList prems
, if null acts && null restr
then operator_ "-->"
else fsep [operator_ "--["
, ppList (map ppFact acts
++ map ppRestr' restr)
, operator_ "]->"]
, nest 1 $ ppFactsList concls]
-- Debug:
-- (keyword_ "new variables: ") <> (ppList prettyLNTerm $ L.get rNewVars ru)
where
ppList = fsep . punctuate comma
ppFacts' = ppList . map ppFact
ppFactsList list = fsep [operator_ "[", ppFacts' list, operator_ "]"]
ppRestr' fact = operator_ "_restrict(" <> ppRestr fact <> operator_ ")"
-- | pretty-print rules with restrictions
prettyRuleRestr :: HighlightDocument d => [LNFact] -> [LNFact] -> [LNFact] -> [F.SyntacticLNFormula] -> d
prettyRuleRestr = prettyRuleRestrGen prettyLNFact F.prettySyntacticLNFormula
-- | pretty-print rules without restrictions
prettyRule :: HighlightDocument d => [LNFact] -> [LNFact] -> [LNFact] -> d
prettyRule prems acts concls = prettyRuleRestr prems acts concls []
prettyNamedRule :: (HighlightDocument d, HasRuleName (Rule i), HasRuleAttributes (Rule i))
=> d -- ^ Prefix.
-> (i -> d) -- ^ Rule info pretty printing.
-> Rule i -> d
prettyNamedRule prefix ppInfo ru =
prefix <-> prettyRuleName ru <> ppAttributes <> colon $-$
nest 2
(prettyRule (facts rPrems) acts (facts rConcs)) $-$
nest 2 (ppInfo $ L.get rInfo ru) --- $-$
where
acts = filter isNotDiffAnnotation (L.get rActs ru)
isNotDiffAnnotation fa = (fa /= Fact {factTag = ProtoFact Linear ("Diff" ++ getRuleNameDiff ru) 0, factAnnotations = S.empty, factTerms = []})
facts proj = L.get proj ru
ppAttributes = case ruleAttributes ru of
[] -> text ""
attrs -> hcat [text "[", ppList $ map prettyRuleAttribute attrs, text "]"]
ppList = fsep . punctuate comma
prettyProtoRuleACInfo :: HighlightDocument d => ProtoRuleACInfo -> d
prettyProtoRuleACInfo i =
(ppVariants $ L.get pracVariants i) $-$
prettyLoopBreakers i
where
ppVariants (Disj [subst]) | subst == emptySubstVFresh = emptyDoc
ppVariants substs = kwVariantsModulo "AC" $-$ prettyDisjLNSubstsVFresh substs
prettyProtoRuleACInstInfo :: HighlightDocument d => ProtoRuleACInstInfo -> d
prettyProtoRuleACInstInfo i = prettyInstLoopBreakers i
prettyLoopBreakers :: HighlightDocument d => ProtoRuleACInfo -> d
prettyLoopBreakers i = case breakers of
[] -> emptyDoc
[_] -> lineComment_ $ "loop breaker: " ++ show breakers
_ -> lineComment_ $ "loop breakers: " ++ show breakers
where
breakers = getPremIdx <$> L.get pracLoopBreakers i
prettyInstLoopBreakers :: HighlightDocument d => ProtoRuleACInstInfo -> d
prettyInstLoopBreakers i = case breakers of
[] -> emptyDoc
[_] -> lineComment_ $ "loop breaker: " ++ show breakers
_ -> lineComment_ $ "loop breakers: " ++ show breakers
where
breakers = getPremIdx <$> L.get praciLoopBreakers i
prettyProtoRuleE :: HighlightDocument d => ProtoRuleE -> d
prettyProtoRuleE = prettyNamedRule (kwRuleModulo "E") (const emptyDoc)
prettyRuleAC :: HighlightDocument d => RuleAC -> d
prettyRuleAC =
prettyNamedRule (kwRuleModulo "AC")
(ruleInfo prettyProtoRuleACInfo (const emptyDoc))
prettyProtoRuleACasE :: HighlightDocument d => ProtoRuleAC -> d
prettyProtoRuleACasE =
prettyNamedRule (kwRuleModulo "E") (const emptyDoc)
prettyIntrRuleAC :: HighlightDocument d => IntrRuleAC -> d
prettyIntrRuleAC = prettyNamedRule (kwRuleModulo "AC") (const emptyDoc)
prettyProtoRuleAC :: HighlightDocument d => ProtoRuleAC -> d
prettyProtoRuleAC = prettyNamedRule (kwRuleModulo "AC") prettyProtoRuleACInfo
prettyRuleACInst :: HighlightDocument d => RuleACInst -> d
prettyRuleACInst = prettyNamedRule (kwInstanceModulo "AC") (const emptyDoc)
-- | Pretty-print a non-empty bunch of intruder rules.
prettyIntruderVariants :: HighlightDocument d => [IntrRuleAC] -> d
prettyIntruderVariants vs = vcat . intersperse (text "") $ map prettyIntrRuleAC vs
-- | Pretty - print the intruder variants section .
prettyIntrVariantsSection : : d = > [ IntrRuleAC ] - > d
prettyIntrVariantsSection rules =
prettyFormalComment " section " " Finite Variants of the Intruder Rules " $ --$
nest 1 ( prettyIntruderVariants rules )
-- | Pretty-print the intruder variants section.
prettyIntrVariantsSection :: HighlightDocument d => [IntrRuleAC] -> d
prettyIntrVariantsSection rules =
prettyFormalComment "section" " Finite Variants of the Intruder Rules " $--$
nest 1 (prettyIntruderVariants rules)
-}
| null | https://raw.githubusercontent.com/tamarin-prover/tamarin-prover/e6854c9355274a7363c7481d27b753789604c2e2/lib/theory/src/Theory/Model/Rule.hs | haskell | # LANGUAGE DeriveDataTypeable #
# LANGUAGE DeriveGeneric #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeOperators #
# LANGUAGE TypeSynonymInstances #
|
License : GPL v3 (see LICENSE)
Portability : portable
Rewriting rules representing protocol execution and intruder deduction. Once
* General Rules
** Accessors
** Extended positions
** Genereal protocol and intruder rules
* Protocol Rule Information
* Intruder Rule Information
* Concrete Rules
** Queries
** Conversion
** Construction
** Unification
* Pretty-Printing
import Data.Maybe (fromMaybe)
import Control.Basics
import Debug.Trace
----------------------------------------------------------------------------
General Rule
----------------------------------------------------------------------------
| Rewriting rules with arbitrary additional information and facts with names
and logical variables.
contains initially the new variables, then their instantiations
| @lookupPrem i ru@ returns the @i@-th premise of rule @ru@, if possible.
| @lookupConc i ru@ returns the @i@-th conclusion of rule @ru@, if possible.
| @rPrem i@ is a lens for the @i@-th premise of a rule.
| Enumerate all premises of a rule.
| Enumerate all conclusions of a rule.
Instances
----------
We do not include the new variables in the occurrences
---------------------------------------------
Extended Positions (of a term inside a rule)
---------------------------------------------
----------------------------------------------------------------------------
Rule information split into intruder rule and protocol rules
----------------------------------------------------------------------------
| Rule information for protocol and intruder rules.
| @ruleInfo proto intr@ maps the protocol information with @proto@ and the
intruder information with @intr@.
Instances
----------
----------------------------------------------------------------------------
Protocol Rule Information
----------------------------------------------------------------------------
| An attribute for a Rule, which does not affect the semantics.
Process: for display, but also to recognise
which needs relaxed treatment in wellformedness check
need to see what we need here later.
| A name of a protocol rule is either one of the special reserved rules or
some standard rule.
^ Some standard protocol rule
| Information for protocol rules modulo E.
| Information for protocol rules modulo AC. The variants list the possible
instantiations of the free variables of the rule. The source is interpreted
modulo AC; i.e., its variants were also built.
| Information for instances of protocol rules modulo AC.
Instances
----------
----------------------------------------------------------------------------
Intruder Rule Information
----------------------------------------------------------------------------
| An intruder rule modulo AC is described by its name.
the number of remaining consecutive applications of this destruction rule, 0 means unbounded, -1 means not yet determined
Necessary for diff
| An intruder rule modulo AC.
| Converts between constructor and destructor rules.
we remove the actions and new variables as destructors do not have actions or new variables
| Converts between destructor and constructor rules.
we add the conclusion as an action as constructors have this action
Instances
----------
----------------------------------------------------------------------------
Concrete rules
----------------------------------------------------------------------------
| A rule modulo E is always a protocol rule. Intruder rules are specified
abstractly by their operations generating them and are only available once
their variants are built.
| A protocol rule modulo AC.
| A rule modulo AC is either a protocol rule or an intruder rule
| A rule instance module AC is either a protocol rule or an intruder rule.
The info identifies the corresponding rule modulo AC that the instance was
derived from.
Accessing the rule name
------------------------
| Types that have an associated name.
--------
| True iff the rule is a destruction rule.
| True iff the rule is an iequality rule.
| True iff the rule is a construction rule.
| True iff the rule is a construction rule.
| True iff the rule is the special fresh rule.
| True iff the rule is the special learn rule.
| True iff the rule is the special knows rule.
| True iff the rule is the special coerce rule.
| True iff the rule is a destruction rule with constant RHS.
the equality rule is considered a subterm rule, as it has no RHS.
| True if the messages in premises and conclusions are in normal form
| Normalize all terms in premises, actions and conclusions
| True iff the rule is an intruder rule
| True iff the rule is an intruder rule
| True if the protocol rule has only the trivial variant.
| Returns a rule's name
| Returns a protocol rule's name
| Returns the remaining rule applications within the deconstruction chain if possible, 0 otherwise
| Sets the remaining rule applications within the deconstruction chain if possible
| Converts a protocol rule to its "left" variant
| Converts a protocol rule to its "right" variant
| Returns a list of all new variables that need to be fixed for mirroring
if the variable is already fixed, no need to fix it again!
| Returns whether a given rule has new variables
| Given a fresh rule instance and the rule instance to mirror, returns a substitution
determining how all new variables need to be instantiated if possible.
otherwise there is no substitution
FIXME: Nothing?
action facts, ignoring added action facts and other rule information
TODO: Ignore renaming?
action facts, ignoring terms
Construction
-------------
| Returns a multiplication rule instance of the given size.
| Returns a union rule instance of the given size.
| Returns a xor rule instance of the given size.
| Compute /some/ rule instance of a rule modulo AC. If the rule is a
protocol rule, then the given source and variants also need to be handled.
| Compute /some/ rule instance of a rule modulo AC. If the rule is a
protocol rule, then the given source and variants also need to be handled.
| Compute /some/ rule instance of a rule modulo AC. If the rule is a
protocol rule, then the given source and variants also need to be handled.
| Compute /some/ rule instance of a rule modulo AC. If the rule is a
protocol rule, then the given source and variants also need to be handled.
| Add the diff label to a rule
| Remove the diff label from a rule
| Add an action label to a rule
------------
----------------------------------------------------------------------------
Fact analysis
----------------------------------------------------------------------------
| Globally unique facts.
in the rule's conclusion.
A fact symbol fa is globally fresh with respect to a dependency graph if
We are looking for sufficient criterion to prove that a fact symbol is
globally fresh.
The Fr symbol is globally fresh by construction.
We have to track every creation of a globally fresh fact to a Fr fact.
(And show that the equality of of the created fact implies the equality of
the corresponding fresh facts. Ignore this for now by assuming that no
duplication happens.)
(fa(x1), fr(y1)), (fa(x2), fr(y2)) : x2 = x1 ==> y1 == y2
And ensure that every duplication is non-unifiable.
A Fr fact is described
We track which symbols are not globally fresh.
All persistent facts are not globally fresh.
Adding a rule ru.
All fact symbols that occur twice in the conclusion
For simplicity: globally fresh fact symbols occur at most once in premise
and conclusion of a rule.
A fact is removed by a rule if it occurs in the rules premise
1. but doesn't occur in the rule's conclusion
We want a sufficient criterion to prove that a fact is globally unique.
----------------------------------------------------------------------------
Pretty-Printing
----------------------------------------------------------------------------
| Prefix the name if it is equal to a reserved name.
NOTE: We maintain the invariant that a theory does not contain standard
rules with a reserved name. This is a last ressort. The pretty-printed
theory can then not be parsed anymore.
| List of all reserved rule names.
| Pretty print the rule name such that it can be used as a case name
| pretty-print rules with restrictions
Debug:
(keyword_ "new variables: ") <> (ppList prettyLNTerm $ L.get rNewVars ru)
| pretty-print rules with restrictions
| pretty-print rules without restrictions
^ Prefix.
^ Rule info pretty printing.
- $-$
| Pretty-print a non-empty bunch of intruder rules.
| Pretty - print the intruder variants section .
$
| Pretty-print the intruder variants section.
$ | # LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE StandaloneDeriving #
# LANGUAGE MultiParamTypeClasses #
Copyright : ( c ) 2010 - 2012
Maintainer : < >
modulo the full Diffie - Hellman equational theory and once modulo AC .
module Theory.Model.Rule (
Rule(..)
, PremIdx(..)
, ConcIdx(..)
, rInfo
, rPrems
, rConcs
, rActs
, rPrem
, rConc
, rNewVars
, lookupPrem
, lookupConc
, enumPrems
, enumConcs
, ExtendedPosition
, printPosition
, printFactPosition
, RuleInfo(..)
, ruleInfo
, RuleAttribute(..)
, ProtoRuleName(..)
, ProtoRuleEInfo(..)
, preName
, preAttributes
, preRestriction
, ProtoRuleACInfo(..)
, pracName
, pracAttributes
, pracVariants
, pracLoopBreakers
, ProtoRuleACInstInfo(..)
, praciName
, praciAttributes
, praciLoopBreakers
, RuleACConstrs
, IntrRuleACInfo(..)
, ProtoRuleE
, ProtoRuleAC
, IntrRuleAC
, RuleAC
, RuleACInst
, HasRuleName(..)
, HasRuleAttributes(..)
, isIntruderRule
, isDestrRule
, isIEqualityRule
, isConstrRule
, isPubConstrRule
, isFreshRule
, isIRecvRule
, isISendRule
, isCoerceRule
, isProtocolRule
, isConstantRule
, isSubtermRule
, containsNewVars
, getRuleName
, getRuleNameDiff
, getRemainingRuleApplications
, setRemainingRuleApplications
, nfRule
, normRule
, isTrivialProtoVariantAC
, getNewVariables
, getSubstitutionsFixingNewVars
, compareRulesUpToNewVars
, equalUpToAddedActions
, equalUpToTerms
, ruleACToIntrRuleAC
, ruleACIntrToRuleAC
, ruleACIntrToRuleACInst
, getLeftRule
, getRightRule
, constrRuleToDestrRule
, destrRuleToConstrRule
, destrRuleToDestrRule
, someRuleACInst
, someRuleACInstAvoiding
, someRuleACInstAvoidingFixing
, someRuleACInstFixing
, addDiffLabel
, removeDiffLabel
, multRuleInstance
, unionRuleInstance
, xorRuleInstance
, addAction
, unifyRuleACInstEqs
, unifiableRuleACInsts
, equalRuleUpToRenaming
, equalRuleUpToAnnotations
, equalRuleUpToDiffAnnotation
, equalRuleUpToDiffAnnotationSym
, reservedRuleNames
, showRuleCaseName
, prettyRule
, prettyRuleRestrGen
, prettyRuleRestr
, prettyProtoRuleName
, prettyRuleName
, prettyRuleAttribute
, prettyProtoRuleE
, prettyProtoRuleAC
, prettyProtoRuleACasE
, prettyIntrRuleAC
, prettyIntrRuleACInfo
, prettyRuleAC
, prettyLoopBreakers
, prettyRuleACInst
, prettyProtoRuleACInstInfo
, prettyInstLoopBreakers
, prettyIntruderVariants) where
import Prelude hiding (id, (.))
import GHC.Generics (Generic)
import Data.Binary
import qualified Data.ByteString.Char8 as BC
import Data . Foldable ( foldMap )
import Data.Data
import Data.List
import qualified Data.Set as S
import qualified Data.Map as M
import Data.Monoid
import Data.Color
import Safe
import Control.Category
import Control.DeepSeq
import Control.Monad.Bind
import Control.Monad.Reader
import Extension.Data.Label hiding (get)
import qualified Extension.Data.Label as L
import Logic.Connectives
import Term.LTerm
import Term.Positions
import Term.Rewriting.Norm (nf', norm')
import Term.Builtin.Convenience (var)
import Term.Unification
import Theory.Model.Fact
import qualified Theory.Model.Formula as F
import Theory.Text.Pretty
import Theory.Sapic
data Rule i = Rule {
_rInfo :: i
, _rPrems :: [LNFact]
, _rConcs :: [LNFact]
, _rActs :: [LNFact]
, _rNewVars :: [LNTerm]
}
deriving(Eq, Ord, Show, Data, Typeable, Generic)
instance NFData i => NFData (Rule i)
instance Binary i => Binary (Rule i)
$(mkLabels [''Rule])
| An index of a premise . The first premise has index ' 0 ' .
newtype PremIdx = PremIdx { getPremIdx :: Int }
deriving( Eq, Ord, Show, Enum, Data, Typeable, Binary, NFData )
| An index of a conclusion . The first conclusion has index ' 0 ' .
newtype ConcIdx = ConcIdx { getConcIdx :: Int }
deriving( Eq, Ord, Show, Enum, Data, Typeable, Binary, NFData )
lookupPrem :: PremIdx -> Rule i -> Maybe LNFact
lookupPrem i = (`atMay` getPremIdx i) . L.get rPrems
lookupConc :: ConcIdx -> Rule i -> Maybe LNFact
lookupConc i = (`atMay` getConcIdx i) . L.get rConcs
rPrem :: PremIdx -> (Rule i :-> LNFact)
rPrem i = nthL (getPremIdx i) . rPrems
| is a lens for the @i@-th conclusion of a rule .
rConc :: ConcIdx -> (Rule i :-> LNFact)
rConc i = nthL (getConcIdx i) . rConcs
enumPrems :: Rule i -> [(PremIdx, LNFact)]
enumPrems = zip [(PremIdx 0)..] . L.get rPrems
enumConcs :: Rule i -> [(ConcIdx, LNFact)]
enumConcs = zip [(ConcIdx 0)..] . L.get rConcs
we need special instances for and to ignore the new variable instantiations when comparing rules
instance ( Eq t ) = > Eq ( Rule t ) where
( Rule i0 as0 _ ) = = ( Rule i1 ps1 cs1 as1 _ ) =
( i0 = = i1 ) & & ( ps0 = = ps1 ) & & ( cs0 = = cs1 ) & & ( as0 = = )
compareRulesUpToNewVars :: (Ord i) => Rule i -> Rule i -> Ordering
compareRulesUpToNewVars (Rule i0 ps0 cs0 as0 _) (Rule i1 ps1 cs1 as1 _) =
if i0 == i1 then
if ps0 == ps1 then
if cs0 == cs1 then
compare as0 as1
else
compare cs0 cs1
else
compare ps0 ps1
else
compare i0 i1
deriving instance ( t ) = > Ord ( Rule t )
instance Functor Rule where
fmap f (Rule i ps cs as nvs) = Rule (f i) ps cs as nvs
instance (Show i, HasFrees i) => HasFrees (Rule i) where
foldFrees f (Rule i ps cs as nvs) =
(foldFrees f i `mappend`) $
(foldFrees f ps `mappend`) $
(foldFrees f cs `mappend`) $
(foldFrees f as `mappend`) $
(foldFrees f nvs)
foldFreesOcc f c (Rule i ps cs as _) =
foldFreesOcc f ((show i):c) (ps, cs, as)
mapFrees f (Rule i ps cs as nvs) =
Rule <$> mapFrees f i
<*> mapFrees f ps <*> mapFrees f cs <*> mapFrees f as
<*> mapFrees f nvs
instance Apply LNSubst i => Apply LNSubst (Rule i) where
apply subst (Rule i ps cs as nvs) =
Rule (apply subst i) (apply subst ps) (apply subst cs) (apply subst as) (apply subst nvs)
instance Sized (Rule i) where
size (Rule _ ps cs as _) = size ps + size cs + size as
type ExtendedPosition = (PremIdx, Int, Position)
printPosition :: ExtendedPosition -> String
printPosition (pidx, i, pos) = show (getPremIdx pidx) ++ "_" ++ show i ++ "_" ++ foldl (\x y -> x ++ show y ++ "_") "" pos
printFactPosition :: ExtendedPosition -> String
printFactPosition (pidx, _, _) = show (getPremIdx pidx)
data RuleInfo p i =
ProtoInfo p
| IntrInfo i
deriving( Eq, Ord, Show, Generic)
instance (NFData i, NFData p) => NFData (RuleInfo p i)
instance (Binary i, Binary p) => Binary (RuleInfo p i)
ruleInfo :: (p -> c) -> (i -> c) -> RuleInfo p i -> c
ruleInfo proto _ (ProtoInfo x) = proto x
ruleInfo _ intr (IntrInfo x) = intr x
instance (HasFrees p, HasFrees i) => HasFrees (RuleInfo p i) where
foldFrees f = ruleInfo (foldFrees f) (foldFrees f)
foldFreesOcc _ _ = const mempty
mapFrees f = ruleInfo (fmap ProtoInfo . mapFrees f)
(fmap IntrInfo . mapFrees f)
instance (Apply s p, Apply s i) => Apply s (RuleInfo p i) where
apply subst = ruleInfo (ProtoInfo . apply subst) (IntrInfo . apply subst)
Color for display
lookup rule generated by SAPIC
TODO This type has no annotations , to avoid
dependency to . Annotations
deriving( Eq, Ord, Show, Data, Generic)
instance NFData RuleAttribute
instance Binary RuleAttribute
data ProtoRuleName =
FreshRule
deriving( Eq, Ord, Show, Data, Typeable, Generic)
instance NFData ProtoRuleName
instance Binary ProtoRuleName
data ProtoRuleEInfo = ProtoRuleEInfo
{ _preName :: ProtoRuleName
, _preAttributes :: [RuleAttribute]
, _preRestriction:: [F.SyntacticLNFormula]
}
deriving( Eq, Ord, Show, Data, Generic)
instance NFData ProtoRuleEInfo
instance Binary ProtoRuleEInfo
data ProtoRuleACInfo = ProtoRuleACInfo
{ _pracName :: ProtoRuleName
, _pracAttributes :: [RuleAttribute]
, _pracVariants :: Disj (LNSubstVFresh)
, _pracLoopBreakers :: [PremIdx]
}
deriving(Eq, Ord, Show, Generic)
instance NFData ProtoRuleACInfo
instance Binary ProtoRuleACInfo
data ProtoRuleACInstInfo = ProtoRuleACInstInfo
{ _praciName :: ProtoRuleName
, _praciAttributes :: [RuleAttribute]
, _praciLoopBreakers :: [PremIdx]
}
deriving(Eq, Ord, Show, Generic)
instance NFData ProtoRuleACInstInfo
instance Binary ProtoRuleACInstInfo
$(mkLabels [''ProtoRuleEInfo, ''ProtoRuleACInfo, ''ProtoRuleACInstInfo])
instance Apply s RuleAttribute where
apply _ = id
instance HasFrees RuleAttribute where
foldFrees _ = const mempty
foldFreesOcc _ _ = const mempty
mapFrees _ = pure
instance Apply s ProtoRuleName where
apply _ = id
instance HasFrees ProtoRuleName where
foldFrees _ = const mempty
foldFreesOcc _ _ = const mempty
mapFrees _ = pure
instance Apply s PremIdx where
apply _ = id
instance HasFrees PremIdx where
foldFrees _ = const mempty
foldFreesOcc _ _ = const mempty
mapFrees _ = pure
instance Apply s ConcIdx where
apply _ = id
instance HasFrees ConcIdx where
foldFrees _ = const mempty
foldFreesOcc _ _ = const mempty
mapFrees _ = pure
instance HasFrees ProtoRuleEInfo where
foldFrees f (ProtoRuleEInfo na attr rstr) =
foldFrees f na `mappend` foldFrees f attr `mappend` foldFrees f rstr
foldFreesOcc _ _ = const mempty
mapFrees f (ProtoRuleEInfo na attr rstr) =
ProtoRuleEInfo na <$> mapFrees f attr <*> mapFrees f rstr
instance Apply s ProtoRuleEInfo where
apply _ = id
instance HasFrees ProtoRuleACInfo where
foldFrees f (ProtoRuleACInfo na attr vari breakers) =
foldFrees f na `mappend` foldFrees f attr
`mappend` foldFrees f vari
`mappend` foldFrees f breakers
foldFreesOcc _ _ = const mempty
mapFrees f (ProtoRuleACInfo na attr vari breakers) =
ProtoRuleACInfo na <$> mapFrees f attr
<*> mapFrees f vari
<*> mapFrees f breakers
instance Apply s ProtoRuleACInstInfo where
apply subst (ProtoRuleACInstInfo na attr breakers) =
ProtoRuleACInstInfo (apply subst na) attr breakers
instance HasFrees ProtoRuleACInstInfo where
foldFrees f (ProtoRuleACInstInfo na attr breakers) =
foldFrees f na `mappend` foldFrees f attr
`mappend` foldFrees f breakers
foldFreesOcc _ _ = const mempty
mapFrees f (ProtoRuleACInstInfo na attr breakers) =
ProtoRuleACInstInfo na <$> mapFrees f attr <*> mapFrees f breakers
data IntrRuleACInfo =
ConstrRule BC.ByteString
| DestrRule BC.ByteString Int Bool Bool
true if the RHS is a true subterm of the LHS
true if the RHS is a constant
| CoerceRule
| IRecvRule
| ISendRule
| PubConstrRule
| FreshConstrRule
deriving( Ord, Eq, Show, Data, Typeable, Generic)
instance NFData IntrRuleACInfo
instance Binary IntrRuleACInfo
type IntrRuleAC = Rule IntrRuleACInfo
| Converts between these two types of rules , if possible .
ruleACToIntrRuleAC :: RuleAC -> Maybe IntrRuleAC
ruleACToIntrRuleAC (Rule (IntrInfo i) ps cs as nvs) = Just (Rule i ps cs as nvs)
ruleACToIntrRuleAC _ = Nothing
| Converts between these two types of rules .
ruleACIntrToRuleAC :: IntrRuleAC -> RuleAC
ruleACIntrToRuleAC (Rule ri ps cs as nvs) = Rule (IntrInfo ri) ps cs as nvs
| Converts between these two types of rules .
ruleACIntrToRuleACInst :: IntrRuleAC -> RuleACInst
ruleACIntrToRuleACInst (Rule ri ps cs as nvs) = Rule (IntrInfo ri) ps cs as nvs
constrRuleToDestrRule :: RuleAC -> Int -> Bool -> Bool -> [RuleAC]
constrRuleToDestrRule (Rule (IntrInfo (ConstrRule name)) ps' cs _ _) i s c
= map toRule $ permutations ps'
where
toRule :: [LNFact] -> RuleAC
toRule [] = error "Bug in constrRuleToDestrRule. Please report."
toRule (p:ps) = Rule (IntrInfo (DestrRule name i s c)) ((convertKUtoKD p):ps) (map convertKUtoKD cs) [] []
constrRuleToDestrRule _ _ _ _ = error "Not a destructor rule."
destrRuleToConstrRule :: FunSym -> Int -> RuleAC -> [RuleAC]
destrRuleToConstrRule f l (Rule (IntrInfo (DestrRule name _ _ _)) ps cs _ _)
= map (\x -> toRule x (conclusions cs)) (permutations (map convertKDtoKU ps ++ kuFacts))
where
toRule :: [LNFact] -> [LNFact] -> RuleAC
toRule ps' cs' = Rule (IntrInfo (ConstrRule name)) ps' cs' cs' []
conclusions [] = []
KD and KU facts only have one term
conclusions ((Fact KDFact ann (m:ms)):cs') = (Fact KUFact ann ((addTerms m):ms)):(conclusions cs')
conclusions (c:cs') = c:(conclusions cs')
addTerms (FAPP f' t) | f'==f = fApp f (t ++ newvars)
addTerms t = fApp f (t:newvars)
kuFacts = map kuFact newvars
newvars = map (var "z") [1..(toInteger $ l-(length ps))]
destrRuleToConstrRule _ _ _ = error "Not a constructor rule."
| Creates variants of a destructor rule , where KD and KU facts are permuted .
destrRuleToDestrRule :: RuleAC -> [RuleAC]
destrRuleToDestrRule (Rule (IntrInfo (DestrRule name i s c)) ps' cs as nv)
= map toRule $ permutations (map convertKDtoKU ps')
where
toRule [] = error "Bug in destrRuleToDestrRule. Please report."
toRule (p:ps) = Rule (IntrInfo (DestrRule name i s c)) ((convertKUtoKD p):ps) cs as nv
destrRuleToDestrRule _ = error "Not a destructor rule."
instance Apply s IntrRuleACInfo where
apply _ = id
instance HasFrees IntrRuleACInfo where
foldFrees _ = const mempty
foldFreesOcc _ _ = const mempty
mapFrees _ = pure
type ProtoRuleE = Rule ProtoRuleEInfo
type ProtoRuleAC = Rule ProtoRuleACInfo
type RuleAC = Rule (RuleInfo ProtoRuleACInfo IntrRuleACInfo)
type RuleACInst = Rule (RuleInfo ProtoRuleACInstInfo IntrRuleACInfo)
class HasRuleName t where
ruleName :: t -> RuleInfo ProtoRuleName IntrRuleACInfo
instance HasRuleName ProtoRuleE where
ruleName = ProtoInfo . L.get (preName . rInfo)
instance HasRuleName RuleAC where
ruleName = ruleInfo (ProtoInfo . L.get pracName) IntrInfo . L.get rInfo
instance HasRuleName ProtoRuleAC where
ruleName = ProtoInfo . L.get (pracName . rInfo)
instance HasRuleName IntrRuleAC where
ruleName = IntrInfo . L.get rInfo
instance HasRuleName RuleACInst where
ruleName = ruleInfo (ProtoInfo . L.get praciName) IntrInfo . L.get rInfo
class HasRuleAttributes t where
ruleAttributes :: t -> [RuleAttribute]
instance HasRuleAttributes ProtoRuleE where
ruleAttributes = L.get (preAttributes . rInfo)
instance HasRuleAttributes RuleAC where
ruleAttributes (Rule (ProtoInfo ri) _ _ _ _) = L.get pracAttributes ri
ruleAttributes _ = []
instance HasRuleAttributes ProtoRuleAC where
ruleAttributes = L.get (pracAttributes . rInfo)
instance HasRuleAttributes IntrRuleAC where
ruleAttributes _ = []
instance HasRuleAttributes RuleACInst where
ruleAttributes (Rule (ProtoInfo ri) _ _ _ _) = L.get praciAttributes ri
ruleAttributes _ = []
Queries
isDestrRule :: HasRuleName r => r -> Bool
isDestrRule ru = case ruleName ru of
IntrInfo (DestrRule _ _ _ _) -> True
IntrInfo IEqualityRule -> True
_ -> False
isIEqualityRule :: HasRuleName r => r -> Bool
isIEqualityRule ru = case ruleName ru of
IntrInfo IEqualityRule -> True
_ -> False
isConstrRule :: HasRuleName r => r -> Bool
isConstrRule ru = case ruleName ru of
IntrInfo (ConstrRule _) -> True
IntrInfo FreshConstrRule -> True
IntrInfo PubConstrRule -> True
IntrInfo CoerceRule -> True
_ -> False
isPubConstrRule :: HasRuleName r => r -> Bool
isPubConstrRule ru = case ruleName ru of
IntrInfo PubConstrRule -> True
_ -> False
isFreshRule :: HasRuleName r => r -> Bool
isFreshRule = (ProtoInfo FreshRule ==) . ruleName
isIRecvRule :: HasRuleName r => r -> Bool
isIRecvRule = (IntrInfo IRecvRule ==) . ruleName
isISendRule :: HasRuleName r => r -> Bool
isISendRule = (IntrInfo ISendRule ==) . ruleName
isCoerceRule :: HasRuleName r => r -> Bool
isCoerceRule = (IntrInfo CoerceRule ==) . ruleName
isConstantRule :: HasRuleName r => r -> Bool
isConstantRule ru = case ruleName ru of
IntrInfo (DestrRule _ _ _ constant) -> constant
_ -> False
| True iff the rule is a destruction rule where the RHS is a true subterm of the LHS .
isSubtermRule :: HasRuleName r => r -> Bool
isSubtermRule ru = case ruleName ru of
IntrInfo (DestrRule _ _ subterm _) -> subterm
IntrInfo IEqualityRule -> True
_ -> False
nfRule :: Rule i -> WithMaude Bool
nfRule (Rule _ ps cs as nvs) = reader $ \hnd ->
all (nfFactList hnd) [ps, cs, as, map termFact nvs]
where
nfFactList hnd xs =
getAll $ foldMap (foldMap (All . (\t -> nf' t `runReader` hnd))) xs
normRule :: Rule i -> WithMaude (Rule i)
normRule (Rule rn ps cs as nvs) = reader $ \hnd -> (Rule rn (normFacts ps hnd) (normFacts cs hnd) (normFacts as hnd) (normTerms nvs hnd))
where
normFacts fs hnd' = map (\f -> runReader (normFact f) hnd') fs
normTerms fs hnd' = map (\f -> runReader (norm' f) hnd') fs
isIntruderRule :: HasRuleName r => r -> Bool
isIntruderRule ru =
case ruleName ru of IntrInfo _ -> True; ProtoInfo _ -> False
isProtocolRule :: HasRuleName r => r -> Bool
isProtocolRule ru =
case ruleName ru of IntrInfo _ -> False; ProtoInfo _ -> True
isTrivialProtoVariantAC :: ProtoRuleAC -> ProtoRuleE -> Bool
isTrivialProtoVariantAC (Rule info ps as cs nvs) (Rule _ ps' as' cs' nvs') =
L.get pracVariants info == Disj [emptySubstVFresh]
&& ps == ps' && as == as' && cs == cs' && nvs == nvs'
getRuleName :: HasRuleName (Rule i) => Rule i -> String
getRuleName ru = case ruleName ru of
IntrInfo i -> case i of
ConstrRule x -> "Constr" ++ (prefixIfReserved ('c' : BC.unpack x))
DestrRule x _ _ _ -> "Destr" ++ (prefixIfReserved ('d' : BC.unpack x))
CoerceRule -> "Coerce"
IRecvRule -> "Recv"
ISendRule -> "Send"
PubConstrRule -> "PubConstr"
FreshConstrRule -> "FreshConstr"
IEqualityRule -> "Equality"
ProtoInfo p -> case p of
FreshRule -> "FreshRule"
StandRule s -> s
getRuleNameDiff :: HasRuleName (Rule i) => Rule i -> String
getRuleNameDiff ru = case ruleName ru of
IntrInfo i -> "Intr" ++ case i of
ConstrRule x -> "Constr" ++ (prefixIfReserved ('c' : BC.unpack x))
DestrRule x _ _ _ -> "Destr" ++ (prefixIfReserved ('d' : BC.unpack x))
CoerceRule -> "Coerce"
IRecvRule -> "Recv"
ISendRule -> "Send"
PubConstrRule -> "PubConstr"
FreshConstrRule -> "FreshConstr"
IEqualityRule -> "Equality"
ProtoInfo p -> "Proto" ++ case p of
FreshRule -> "FreshRule"
StandRule s -> s
getRemainingRuleApplications :: RuleACInst -> Int
getRemainingRuleApplications ru = case ruleName ru of
IntrInfo (DestrRule _ i _ _) -> i
_ -> 0
setRemainingRuleApplications :: RuleACInst -> Int -> RuleACInst
setRemainingRuleApplications (Rule (IntrInfo (DestrRule name _ subterm constant)) prems concs acts nvs) i
= Rule (IntrInfo (DestrRule name i subterm constant)) prems concs acts nvs
setRemainingRuleApplications rule _
= rule
getLeftRule :: Rule i -> Rule i
getLeftRule (Rule ri ps cs as nvs) =
Rule ri (map getLeftFact ps) (map getLeftFact cs) (map getLeftFact as) (map getLeftTerm nvs)
getRightRule :: Rule i -> Rule i
getRightRule (Rule ri ps cs as nvs) =
Rule ri (map getRightFact ps) (map getRightFact cs) (map getRightFact as) (map getRightTerm nvs)
getNewVariables :: Bool -> RuleACInst -> [LVar]
getNewVariables showPubVars (Rule _ _ _ _ nvs) = case showPubVars of
True -> newvars
False -> filter (\v -> not $ lvarSort v == LSortPub) newvars
where
newvars = toVariables nvs
toVariables [] = []
toVariables (x:xs) = case getVar x of
Just v -> v:(toVariables xs)
Nothing -> toVariables xs
containsNewVars :: RuleACInst -> Bool
containsNewVars (Rule _ _ _ _ nvs) = nvs == []
First parameter : original instance to mirror
Second parameter : fresh instance
getSubstitutionsFixingNewVars :: RuleACInst -> RuleACInst -> Maybe LNSubst
getSubstitutionsFixingNewVars (Rule (ProtoInfo (ProtoRuleACInstInfo _ _ _)) _ _ _ instancesO)
(Rule (ProtoInfo (ProtoRuleACInstInfo _ _ _)) _ _ _ instancesF)
| all (\(x, y) -> isPubVar x || x == y) $ zip instancesF instancesO
= Just $ Subst $ M.fromList $ substList instancesF instancesO
| otherwise
= Nothing
where
substList [] [] = []
substList (f:fs) (o:os) = case getVar f of
Nothing -> (substList fs os)
Just v -> (v, o):(substList fs os)
substList _ _ = error "getSubstitutionsFixingNewVars: different number of new variables"
getSubstitutionsFixingNewVars _ _
| returns true if the first Rule has the same name , premise , conclusion and
equalUpToAddedActions :: (HasRuleName (Rule i), HasRuleName (Rule i2)) => (Rule i) -> (Rule i2) -> Bool
equalUpToAddedActions ruAC@(Rule _ ps cs as _) ruE@(Rule _ ps' cs' as' _) =
ruleName ruE == ruleName ruAC && ps == ps' && cs == cs' && compareActions as as'
where
compareActions _ [] = True
compareActions [] _ = False
compareActions (a:ass) (a':ass') = if a == a'
then compareActions ass ass'
else compareActions ass (a':ass')
| returns true if the first Rule has the same name , premise , conclusion and
equalUpToTerms :: (HasRuleName (Rule i), HasRuleName (Rule i2)) => (Rule i) -> (Rule i2) -> Bool
equalUpToTerms ruAC@(Rule _ ps cs as _) ruE@(Rule _ ps' cs' as' _) =
ruleName ruE == ruleName ruAC
&& length ps == length ps' && length cs == length cs' && length as == length as'
&& foldl sameFacts True (zip ps ps') && foldl sameFacts True (zip cs cs')
&& foldl sameFacts True (zip as as')
where
sameFacts b (f1, f2) = b && sameFact f1 f2
sameFact (Fact tag _ _) (Fact tag' _ _) = tag == tag'
multRuleInstance :: Int -> RuleAC
multRuleInstance n = (Rule (IntrInfo (ConstrRule $ BC.pack "_mult")) (map xifact [1..n]) [prod] [prod] [])
where
prod = kuFact (FAPP (AC Mult) (map xi [1..n]))
xi :: Int -> LNTerm
xi k = (LIT $ Var $ LVar "x" LSortMsg (toInteger k))
xifact :: Int -> LNFact
xifact k = kuFact (xi k)
unionRuleInstance :: Int -> RuleAC
unionRuleInstance n = (Rule (IntrInfo (ConstrRule $ BC.pack "_union")) (map xifact [1..n]) [prod] [prod] [])
where
prod = kuFact (FAPP (AC Union) (map xi [1..n]))
xi :: Int -> LNTerm
xi k = (LIT $ Var $ LVar "x" LSortMsg (toInteger k))
xifact :: Int -> LNFact
xifact k = kuFact (xi k)
xorRuleInstance :: Int -> RuleAC
xorRuleInstance n = (Rule (IntrInfo (ConstrRule $ BC.pack "_xor")) (map xifact [1..n]) [prod] [prod] [])
where
prod = Fact KUFact S.empty [(FAPP (AC Xor) (map xi [1..n]))]
xi :: Int -> LNTerm
xi k = (LIT $ Var $ LVar "x" LSortMsg (toInteger k))
xifact :: Int -> LNFact
xifact k = Fact KUFact S.empty [(xi k)]
type RuleACConstrs = Disj LNSubstVFresh
someRuleACInst :: MonadFresh m
=> RuleAC
-> m (RuleACInst, Maybe RuleACConstrs)
someRuleACInst =
fmap extractInsts . rename
where
extractInsts (Rule (ProtoInfo i) ps cs as nvs) =
( Rule (ProtoInfo i') ps cs as nvs
, Just (L.get pracVariants i)
)
where
i' = ProtoRuleACInstInfo (L.get pracName i)
(L.get pracAttributes i)
(L.get pracLoopBreakers i)
extractInsts (Rule (IntrInfo i) ps cs as nvs) =
( Rule (IntrInfo i) ps cs as nvs, Nothing )
someRuleACInstAvoiding :: HasFrees t
=> RuleAC
-> t
-> (RuleACInst, Maybe RuleACConstrs)
someRuleACInstAvoiding r s =
renameAvoiding (extractInsts r) s
where
extractInsts (Rule (ProtoInfo i) ps cs as nvs) =
( Rule (ProtoInfo i') ps cs as nvs
, Just (L.get pracVariants i)
)
where
i' = ProtoRuleACInstInfo (L.get pracName i)
(L.get pracAttributes i)
(L.get pracLoopBreakers i)
extractInsts (Rule (IntrInfo i) ps cs as nvs) =
( Rule (IntrInfo i) ps cs as nvs, Nothing )
someRuleACInstFixing :: MonadFresh m
=> RuleAC
-> LNSubst
-> m (RuleACInst, Maybe RuleACConstrs)
someRuleACInstFixing r subst =
renameIgnoring (varsRange subst) (extractInsts r)
where
extractInsts (Rule (ProtoInfo i) ps cs as nvs) =
( apply subst (Rule (ProtoInfo i') ps cs as nvs)
, Just (L.get pracVariants i)
)
where
i' = ProtoRuleACInstInfo (L.get pracName i)
(L.get pracAttributes i)
(L.get pracLoopBreakers i)
extractInsts (Rule (IntrInfo i) ps cs as nvs) =
( apply subst (Rule (IntrInfo i) ps cs as nvs), Nothing )
someRuleACInstAvoidingFixing :: HasFrees t
=> RuleAC
-> t
-> LNSubst
-> (RuleACInst, Maybe RuleACConstrs)
someRuleACInstAvoidingFixing r s subst =
renameAvoidingIgnoring (extractInsts r) s (varsRange subst)
where
extractInsts (Rule (ProtoInfo i) ps cs as nvs) =
( apply subst (Rule (ProtoInfo i') ps cs as nvs)
, Just (L.get pracVariants i)
)
where
i' = ProtoRuleACInstInfo (L.get pracName i)
(L.get pracAttributes i)
(L.get pracLoopBreakers i)
extractInsts (Rule (IntrInfo i) ps cs as nvs) =
( apply subst (Rule (IntrInfo i) ps cs as nvs), Nothing )
addDiffLabel :: Rule a -> String -> Rule a
addDiffLabel (Rule info prems concs acts nvs) name =
Rule info prems concs
(acts ++ [Fact {factTag = ProtoFact Linear name 0,
factAnnotations = S.empty, factTerms = []}]) nvs
removeDiffLabel :: Rule a -> String -> Rule a
removeDiffLabel (Rule info prems concs acts nvs) name =
Rule info prems concs (filter isNotDiffAnnotation acts) nvs
where
isNotDiffAnnotation fa =
fa /= Fact {factTag = ProtoFact Linear name 0,
factAnnotations = S.empty, factTerms = []}
addAction :: Rule a -> LNFact -> Rule a
addAction (Rule info prems concs acts nvs) act =
if act `elem` acts
then Rule info prems concs acts nvs
else Rule info prems concs (act:acts) nvs
Unification
| Unify a list of @RuleACInst@ equalities .
unifyRuleACInstEqs :: [Equal RuleACInst] -> WithMaude [LNSubstVFresh]
unifyRuleACInstEqs eqs
| all unifiable eqs = unifyLNFactEqs $ concatMap ruleEqs eqs
| otherwise = return []
where
unifiable (Equal ru1 ru2) =
L.get rInfo ru1 == L.get rInfo ru2
&& length (L.get rPrems ru1) == length (L.get rPrems ru2)
&& length (L.get rConcs ru1) == length (L.get rConcs ru2)
ruleEqs (Equal ru1 ru2) =
zipWith Equal (L.get rPrems ru1) (L.get rPrems ru2) ++
zipWith Equal (L.get rConcs ru1) (L.get rConcs ru2)
| Are these two rule instances unifiable ?
unifiableRuleACInsts :: RuleACInst -> RuleACInst -> WithMaude Bool
unifiableRuleACInsts ru1 ru2 =
(not . null) <$> unifyRuleACInstEqs [Equal ru1 ru2]
| Are these two rule instances equal up to renaming of variables ?
equalRuleUpToRenaming :: (Show a, Eq a, HasFrees a) => Rule a -> Rule a -> WithMaude Bool
equalRuleUpToRenaming r1@(Rule rn1 pr1 co1 ac1 nvs1) r2@(Rule rn2 pr2 co2 ac2 nvs2) = reader $ \hnd ->
case eqs of
Nothing -> False
Just eqs' -> (rn1 == rn2) && (any isRenamingPerRule $ unifs eqs' hnd)
where
isRenamingPerRule subst = isRenaming (restrictVFresh (vars r1) subst) && isRenaming (restrictVFresh (vars r2) subst)
vars ru = map fst $ varOccurences ru
unifs eq hnd = unifyLNTerm eq `runReader` hnd
eqs = foldl matchFacts (Just $ zipWith Equal nvs1 nvs2) $ zip (pr1++co1++ac1) (pr2++co2++ac2)
matchFacts Nothing _ = Nothing
matchFacts (Just l) (Fact f1 _ t1, Fact f2 _ t2) | f1 == f2 = Just ((zipWith Equal t1 t2)++l)
| otherwise = Nothing
| Are these two rule instances equal up to added annotations in ?
equalRuleUpToAnnotations :: (Eq a) => Rule a -> Rule a -> Bool
equalRuleUpToAnnotations (Rule rn1 pr1 co1 ac1 nvs1) (Rule rn2 pr2 co2 ac2 nvs2) =
rn1 == rn2 && pr1 == pr2 && co1 == co2 && nvs1 == nvs2 &&
S.isSubsetOf (S.fromList ac1) (S.fromList ac2)
| Are these two rule instances equal up to an added diff annotation in ?
equalRuleUpToDiffAnnotation :: (HasRuleName (Rule a), Eq a) => Rule a -> Rule a -> Bool
equalRuleUpToDiffAnnotation ru1@(Rule rn1 pr1 co1 ac1 nvs1) (Rule rn2 pr2 co2 ac2 nvs2) =
rn1 == rn2 && pr1 == pr2 && co1 == co2 && nvs1 == nvs2 &&
ac1 == filter isNotDiffAnnotation ac2
where
isNotDiffAnnotation fa = (fa /= Fact {factTag = ProtoFact Linear ("Diff" ++ getRuleNameDiff ru1) 0, factAnnotations = S.empty, factTerms = []})
| Are these two rule instances equal up to an added diff annotation in or @ac1@ ?
equalRuleUpToDiffAnnotationSym :: (HasRuleName (Rule a), Eq a) => Rule a -> Rule a -> Bool
equalRuleUpToDiffAnnotationSym ru1 ru2 = equalRuleUpToDiffAnnotation ru1 ru2
|| equalRuleUpToDiffAnnotation ru2 ru1
A rule instance removes a fact fa if is in the rule 's premise but not
there are no two rule instances that remove the same fact built from fa .
2 . or does occur but non - unifiable .
prefixIfReserved :: String -> String
prefixIfReserved n
| n `elem` reservedRuleNames = "_" ++ n
| "_" `isPrefixOf` n = "_" ++ n
| otherwise = n
reservedRuleNames :: [String]
reservedRuleNames = ["Fresh", "irecv", "isend", "coerce", "fresh", "pub", "iequality"]
prettyProtoRuleName :: Document d => ProtoRuleName -> d
prettyProtoRuleName rn = text $ case rn of
FreshRule -> "Fresh"
StandRule n -> prefixIfReserved n
prettyRuleName :: (HighlightDocument d, HasRuleName (Rule i)) => Rule i -> d
prettyRuleName = ruleInfo prettyProtoRuleName prettyIntrRuleACInfo . ruleName
prettyRuleAttribute :: (HighlightDocument d) => RuleAttribute -> d
prettyRuleAttribute attr = case attr of
RuleColor c -> text "color=" <> text (rgbToHex c)
Process p -> text "process=" <> text ("\"" ++ prettySapicTopLevel' f p ++ "\"")
where f l a r rest _ = render $ prettyRuleRestr (g l) (g a) (g r) (h rest)
g = map toLNFact
h = map toLFormula
showRuleCaseName :: HasRuleName (Rule i) => Rule i -> String
showRuleCaseName =
render . ruleInfo prettyProtoRuleName prettyIntrRuleACInfo . ruleName
prettyIntrRuleACInfo :: Document d => IntrRuleACInfo -> d
prettyIntrRuleACInfo rn = text $ case rn of
IRecvRule -> "irecv"
ISendRule -> "isend"
CoerceRule -> "coerce"
FreshConstrRule -> "fresh"
PubConstrRule -> "pub"
IEqualityRule -> "iequality"
ConstrRule name -> prefixIfReserved ('c' : BC.unpack name)
DestrRule name _ _ _ -> prefixIfReserved ('d' : BC.unpack name)
DestrRule name i - > prefixIfReserved ( 'd ' : BC.unpack name + + " _ " + + show i )
TODO may be removed
prettyRestr : : d = > F.SyntacticLNFormula - > d
prettyRestr fact = operator _ " _ restrict ( " < > text ( filter ( /= ' # ' ) $ render $ F.prettySyntacticLNFormula fact ) < > operator _ " ) "
prettyRuleRestrGen :: (HighlightDocument d) => (f -> d) -> (r -> d) -> [f] -> [f] -> [f] -> [r] -> d
prettyRuleRestrGen ppFact ppRestr prems acts concls restr=
sep [ nest 1 $ ppFactsList prems
, if null acts && null restr
then operator_ "-->"
else fsep [operator_ "--["
, ppList (map ppFact acts
++ map ppRestr' restr)
, operator_ "]->"]
, nest 1 $ ppFactsList concls]
where
ppList = fsep . punctuate comma
ppFacts' = ppList . map ppFact
ppFactsList list = fsep [operator_ "[", ppFacts' list, operator_ "]"]
ppRestr' fact = operator_ "_restrict(" <> ppRestr fact <> operator_ ")"
prettyRuleRestr :: HighlightDocument d => [LNFact] -> [LNFact] -> [LNFact] -> [F.SyntacticLNFormula] -> d
prettyRuleRestr = prettyRuleRestrGen prettyLNFact F.prettySyntacticLNFormula
prettyRule :: HighlightDocument d => [LNFact] -> [LNFact] -> [LNFact] -> d
prettyRule prems acts concls = prettyRuleRestr prems acts concls []
prettyNamedRule :: (HighlightDocument d, HasRuleName (Rule i), HasRuleAttributes (Rule i))
-> Rule i -> d
prettyNamedRule prefix ppInfo ru =
prefix <-> prettyRuleName ru <> ppAttributes <> colon $-$
nest 2
(prettyRule (facts rPrems) acts (facts rConcs)) $-$
where
acts = filter isNotDiffAnnotation (L.get rActs ru)
isNotDiffAnnotation fa = (fa /= Fact {factTag = ProtoFact Linear ("Diff" ++ getRuleNameDiff ru) 0, factAnnotations = S.empty, factTerms = []})
facts proj = L.get proj ru
ppAttributes = case ruleAttributes ru of
[] -> text ""
attrs -> hcat [text "[", ppList $ map prettyRuleAttribute attrs, text "]"]
ppList = fsep . punctuate comma
prettyProtoRuleACInfo :: HighlightDocument d => ProtoRuleACInfo -> d
prettyProtoRuleACInfo i =
(ppVariants $ L.get pracVariants i) $-$
prettyLoopBreakers i
where
ppVariants (Disj [subst]) | subst == emptySubstVFresh = emptyDoc
ppVariants substs = kwVariantsModulo "AC" $-$ prettyDisjLNSubstsVFresh substs
prettyProtoRuleACInstInfo :: HighlightDocument d => ProtoRuleACInstInfo -> d
prettyProtoRuleACInstInfo i = prettyInstLoopBreakers i
prettyLoopBreakers :: HighlightDocument d => ProtoRuleACInfo -> d
prettyLoopBreakers i = case breakers of
[] -> emptyDoc
[_] -> lineComment_ $ "loop breaker: " ++ show breakers
_ -> lineComment_ $ "loop breakers: " ++ show breakers
where
breakers = getPremIdx <$> L.get pracLoopBreakers i
prettyInstLoopBreakers :: HighlightDocument d => ProtoRuleACInstInfo -> d
prettyInstLoopBreakers i = case breakers of
[] -> emptyDoc
[_] -> lineComment_ $ "loop breaker: " ++ show breakers
_ -> lineComment_ $ "loop breakers: " ++ show breakers
where
breakers = getPremIdx <$> L.get praciLoopBreakers i
prettyProtoRuleE :: HighlightDocument d => ProtoRuleE -> d
prettyProtoRuleE = prettyNamedRule (kwRuleModulo "E") (const emptyDoc)
prettyRuleAC :: HighlightDocument d => RuleAC -> d
prettyRuleAC =
prettyNamedRule (kwRuleModulo "AC")
(ruleInfo prettyProtoRuleACInfo (const emptyDoc))
prettyProtoRuleACasE :: HighlightDocument d => ProtoRuleAC -> d
prettyProtoRuleACasE =
prettyNamedRule (kwRuleModulo "E") (const emptyDoc)
prettyIntrRuleAC :: HighlightDocument d => IntrRuleAC -> d
prettyIntrRuleAC = prettyNamedRule (kwRuleModulo "AC") (const emptyDoc)
prettyProtoRuleAC :: HighlightDocument d => ProtoRuleAC -> d
prettyProtoRuleAC = prettyNamedRule (kwRuleModulo "AC") prettyProtoRuleACInfo
prettyRuleACInst :: HighlightDocument d => RuleACInst -> d
prettyRuleACInst = prettyNamedRule (kwInstanceModulo "AC") (const emptyDoc)
prettyIntruderVariants :: HighlightDocument d => [IntrRuleAC] -> d
prettyIntruderVariants vs = vcat . intersperse (text "") $ map prettyIntrRuleAC vs
prettyIntrVariantsSection : : d = > [ IntrRuleAC ] - > d
prettyIntrVariantsSection rules =
nest 1 ( prettyIntruderVariants rules )
prettyIntrVariantsSection :: HighlightDocument d => [IntrRuleAC] -> d
prettyIntrVariantsSection rules =
nest 1 (prettyIntruderVariants rules)
-}
|
e8071ddbfaf2b3b4fe2445b3d4ff621e808c4b6fc322290aebac6de40a645d4f | jeromesimeon/Galax | pervasive.mli | (***********************************************************************)
(* *)
(* GALAX *)
(* XQuery Engine *)
(* *)
Copyright 2001 - 2007 .
(* Distributed only by permission. *)
(* *)
(***********************************************************************)
$ I d : pervasive.mli , v 1.5 2007/02/01 22:08:45 simeon Exp $
(* Module: Pervasive
Description:
Contains built-functions signatures and types in XQuery
syntax. Generated automatically from the file
./stdlib/pervasive.xq file.
*)
val pervasive : string
| null | https://raw.githubusercontent.com/jeromesimeon/Galax/bc565acf782c140291911d08c1c784c9ac09b432/base/pervasive.mli | ocaml | *********************************************************************
GALAX
XQuery Engine
Distributed only by permission.
*********************************************************************
Module: Pervasive
Description:
Contains built-functions signatures and types in XQuery
syntax. Generated automatically from the file
./stdlib/pervasive.xq file.
| Copyright 2001 - 2007 .
$ I d : pervasive.mli , v 1.5 2007/02/01 22:08:45 simeon Exp $
val pervasive : string
|
14f057b2f8e330b2737f4d4378acaabbf2dedaad502b9e50f23fac2ddf8d2cce | ocamllabs/ocaml-modular-implicits | pr2719.ml | open Printf
let bug () =
let mat = [| [|false|] |]
and test = ref false in
printf "Value of test at the beginning : %b\n" !test; flush stdout;
(try let _ = mat.(0).(-1) in
(test := true;
printf "Am I going through this block of instructions ?\n";
flush stdout)
with Invalid_argument _ -> printf "Value of test now : %b\n" !test
);
(try if mat.(0).(-1) then ()
with Invalid_argument _ -> ()
)
let () = bug ()
| null | https://raw.githubusercontent.com/ocamllabs/ocaml-modular-implicits/92e45da5c8a4c2db8b2cd5be28a5bec2ac2181f1/testsuite/tests/basic-more/pr2719.ml | ocaml | open Printf
let bug () =
let mat = [| [|false|] |]
and test = ref false in
printf "Value of test at the beginning : %b\n" !test; flush stdout;
(try let _ = mat.(0).(-1) in
(test := true;
printf "Am I going through this block of instructions ?\n";
flush stdout)
with Invalid_argument _ -> printf "Value of test now : %b\n" !test
);
(try if mat.(0).(-1) then ()
with Invalid_argument _ -> ()
)
let () = bug ()
| |
2c2a6a745b97c637710698d382604ee7f995bb50ba5cf19b15e42ac6d30841fe | hidaris/thinking-dumps | a7-5.rkt | #lang racket
;; $ stand for $tream
(define-syntax cons$
(syntax-rules ()
((cons$ x y) (cons x (delay y)))))
(define car$ car)
(define cdr$
(lambda ($) (force (cdr $))))
(define take$
(lambda (n $)
(cond
[(zero? n) '()]
[else (cons (car$ $)
(let ((n- (sub1 n)))
(cond
[(zero? n-) '()]
[else (take$ n- (cdr$ $))])))])))
(define trib$
(letrec ([p (lambda (a)
(lambda (b)
(lambda (c)
(cons$ a (((p b) c) (+ a b c))))))])
(((p 0) 1) 1)))
| null | https://raw.githubusercontent.com/hidaris/thinking-dumps/ce13154e2d9e3140197b2230e7cea2f8be2ae84c/c311/a7-5.rkt | racket | $ stand for $tream | #lang racket
(define-syntax cons$
(syntax-rules ()
((cons$ x y) (cons x (delay y)))))
(define car$ car)
(define cdr$
(lambda ($) (force (cdr $))))
(define take$
(lambda (n $)
(cond
[(zero? n) '()]
[else (cons (car$ $)
(let ((n- (sub1 n)))
(cond
[(zero? n-) '()]
[else (take$ n- (cdr$ $))])))])))
(define trib$
(letrec ([p (lambda (a)
(lambda (b)
(lambda (c)
(cons$ a (((p b) c) (+ a b c))))))])
(((p 0) 1) 1)))
|
b28a56e1f9d6a45a687c7735b0d785dd30cd62e0ce62dbb3493b096386371701 | schemedoc/implementation-metadata | scheme2c.scm | (tagline "The original Scheme->C system, the first of its kind")
(rnrs 4)
(person "Joel Bartlett")
(repology "scheme2c")
| null | https://raw.githubusercontent.com/schemedoc/implementation-metadata/6280d9c4c73833dc5bd1c9bef9b45be6ea5beb68/schemes/scheme2c.scm | scheme | (tagline "The original Scheme->C system, the first of its kind")
(rnrs 4)
(person "Joel Bartlett")
(repology "scheme2c")
| |
7f80c00a9540df09b17bb1b640f531155b78fbfc36767c5aea18d62e9085620e | swarmpit/swarmpit | list.cljs | (ns swarmpit.component.service.list
(:require [material.icon :as icon]
[material.components :as comp]
[material.component.form :as form]
[material.component.list.basic :as list]
[material.component.list.util :as list-util]
[material.component.composite :as composite]
[material.component.label :as label]
[swarmpit.component.state :as state]
[swarmpit.component.mixin :as mixin]
[swarmpit.component.progress :as progress]
[swarmpit.component.common :as common]
[swarmpit.ajax :as ajax]
[swarmpit.routes :as routes]
[swarmpit.url :refer [dispatch!]]
[sablono.core :refer-macros [html]]
[rum.core :as rum]))
(enable-console-print!)
(defn- render-item-ports [item index]
(html
(map-indexed
(fn [i item]
[:div {:key (str "port-" i "-" index)}
[:span (:hostPort item)
[:span.Swarmpit-service-list-port (str " [" (:protocol item) "]")]]]) (:ports item))))
(defn- render-item-replicas [item]
(let [tasks (get-in item [:status :tasks])]
(str (:running tasks) " / " (:total tasks))))
(defn- render-item-update-state [value]
(case value
"rollback_started" (label/base "rollback" "pulsing")
(label/base value "pulsing")))
(defn- render-item-state [value]
(case value
"running" (label/base value "green")
"not running" (label/base value "info")
"partly running" (label/base value "yellow")))
(defn- render-status [item]
(let [update-status (get-in item [:status :update])]
(html
[:span.Swarmpit-table-status
(if (or (= "updating" update-status)
(= "rollback_started" update-status))
(render-item-update-state update-status)
(render-item-state (:state item)))])))
(def render-metadata
{:table {:summary [{:name "Service"
:render-fn (fn [item] (list/table-item-name (:serviceName item) (get-in item [:repository :image])))}
{:name "Replicas"
:render-fn (fn [item] (render-item-replicas item))}
{:name "Ports"
:render-fn (fn [item index] (render-item-ports item index))}
{:name ""
:status true
:render-fn (fn [item] (render-status item))}]}
:list {:primary (fn [item] (:serviceName item))
:secondary (fn [item] (get-in item [:repository :image]))
:status-fn (fn [item] (render-status item))}})
(defn onclick-handler
[item]
(routes/path-for-frontend :service-info {:id (:serviceName item)}))
(defn- services-handler
[]
(ajax/get
(routes/path-for-backend :services)
{:state [:loading?]
:on-success (fn [{:keys [response origin?]}]
(when origin?
(state/update-value [:items] response state/form-value-cursor)))}))
(defn form-search-fn
[event]
(state/update-value [:query] (-> event .-target .-value) state/search-cursor))
(defn- init-form-state
[]
(state/set-value {:loading? false
:filter {:state nil}
:filterOpen? false} state/form-state-cursor))
(def mixin-init-form
(mixin/init-form
(fn [_]
(init-form-state)
(services-handler))))
(defn linked
[services]
(comp/card
{:className "Swarmpit-card"}
(comp/card-header
{:className "Swarmpit-table-card-header"
:title (comp/typography {:variant "h6"} "Services")})
(if (empty? services)
(comp/card-content
{}
(form/item-info "No linked services found."))
(comp/card-content
{:className "Swarmpit-table-card-content"}
(list/responsive
render-metadata
services
onclick-handler)))))
(defn pinned
[services]
(comp/card
{:className "Swarmpit-card"}
(when services
(comp/card-content
{:className "Swarmpit-table-card-content"}
(list/responsive
render-metadata
services
onclick-handler)))))
(rum/defc form-filters < rum/static [filterOpen? {:keys [state] :as filter}]
(common/list-filters
filterOpen?
(comp/text-field
{:fullWidth true
:label "State"
:helperText "Filter by service state"
:select true
:value state
:variant "outlined"
:margin "normal"
:InputLabelProps {:shrink true}
:onChange #(state/update-value [:filter :state] (-> % .-target .-value) state/form-state-cursor)}
(comp/menu-item
{:key "running"
:value "running"} "running")
(comp/menu-item
{:key "shutdown"
:value "shutdown"} "shutdown"))))
(def toolbar-render-metadata
[{:name "New service"
:onClick #(dispatch! (routes/path-for-frontend :service-create-image))
:primary true
:icon (icon/add-circle-out)
:icon-alt (icon/add)}
{:name "Show filters"
:onClick #(state/update-value [:filterOpen?] true state/form-state-cursor)
:icon (icon/filter-list)
:icon-alt (icon/filter-list)
:variant "outlined"
:color "default"}])
(rum/defc form < rum/reactive
mixin-init-form
mixin/subscribe-form
mixin/focus-filter [_]
(let [{:keys [items]} (state/react state/form-value-cursor)
{:keys [query]} (state/react state/search-cursor)
{:keys [loading? filterOpen? filter]} (state/react state/form-state-cursor)
filtered-items (->> (list-util/filter items query)
(clojure.core/filter #(if (some? (:state filter))
(case (:state filter)
"running" (= "running" (:state %))
"shutdown" (= 0 (get-in % [:status :tasks :total])))
true))
(sort-by :createdAt)
(reverse))]
(progress/form
loading?
(comp/box
{}
(common/list "Services"
items
filtered-items
render-metadata
onclick-handler
toolbar-render-metadata)
(form-filters filterOpen? filter)))))
| null | https://raw.githubusercontent.com/swarmpit/swarmpit/38ffbe08e717d8620bf433c99f2e85a9e5984c32/src/cljs/swarmpit/component/service/list.cljs | clojure | (ns swarmpit.component.service.list
(:require [material.icon :as icon]
[material.components :as comp]
[material.component.form :as form]
[material.component.list.basic :as list]
[material.component.list.util :as list-util]
[material.component.composite :as composite]
[material.component.label :as label]
[swarmpit.component.state :as state]
[swarmpit.component.mixin :as mixin]
[swarmpit.component.progress :as progress]
[swarmpit.component.common :as common]
[swarmpit.ajax :as ajax]
[swarmpit.routes :as routes]
[swarmpit.url :refer [dispatch!]]
[sablono.core :refer-macros [html]]
[rum.core :as rum]))
(enable-console-print!)
(defn- render-item-ports [item index]
(html
(map-indexed
(fn [i item]
[:div {:key (str "port-" i "-" index)}
[:span (:hostPort item)
[:span.Swarmpit-service-list-port (str " [" (:protocol item) "]")]]]) (:ports item))))
(defn- render-item-replicas [item]
(let [tasks (get-in item [:status :tasks])]
(str (:running tasks) " / " (:total tasks))))
(defn- render-item-update-state [value]
(case value
"rollback_started" (label/base "rollback" "pulsing")
(label/base value "pulsing")))
(defn- render-item-state [value]
(case value
"running" (label/base value "green")
"not running" (label/base value "info")
"partly running" (label/base value "yellow")))
(defn- render-status [item]
(let [update-status (get-in item [:status :update])]
(html
[:span.Swarmpit-table-status
(if (or (= "updating" update-status)
(= "rollback_started" update-status))
(render-item-update-state update-status)
(render-item-state (:state item)))])))
(def render-metadata
{:table {:summary [{:name "Service"
:render-fn (fn [item] (list/table-item-name (:serviceName item) (get-in item [:repository :image])))}
{:name "Replicas"
:render-fn (fn [item] (render-item-replicas item))}
{:name "Ports"
:render-fn (fn [item index] (render-item-ports item index))}
{:name ""
:status true
:render-fn (fn [item] (render-status item))}]}
:list {:primary (fn [item] (:serviceName item))
:secondary (fn [item] (get-in item [:repository :image]))
:status-fn (fn [item] (render-status item))}})
(defn onclick-handler
[item]
(routes/path-for-frontend :service-info {:id (:serviceName item)}))
(defn- services-handler
[]
(ajax/get
(routes/path-for-backend :services)
{:state [:loading?]
:on-success (fn [{:keys [response origin?]}]
(when origin?
(state/update-value [:items] response state/form-value-cursor)))}))
(defn form-search-fn
[event]
(state/update-value [:query] (-> event .-target .-value) state/search-cursor))
(defn- init-form-state
[]
(state/set-value {:loading? false
:filter {:state nil}
:filterOpen? false} state/form-state-cursor))
(def mixin-init-form
(mixin/init-form
(fn [_]
(init-form-state)
(services-handler))))
(defn linked
[services]
(comp/card
{:className "Swarmpit-card"}
(comp/card-header
{:className "Swarmpit-table-card-header"
:title (comp/typography {:variant "h6"} "Services")})
(if (empty? services)
(comp/card-content
{}
(form/item-info "No linked services found."))
(comp/card-content
{:className "Swarmpit-table-card-content"}
(list/responsive
render-metadata
services
onclick-handler)))))
(defn pinned
[services]
(comp/card
{:className "Swarmpit-card"}
(when services
(comp/card-content
{:className "Swarmpit-table-card-content"}
(list/responsive
render-metadata
services
onclick-handler)))))
(rum/defc form-filters < rum/static [filterOpen? {:keys [state] :as filter}]
(common/list-filters
filterOpen?
(comp/text-field
{:fullWidth true
:label "State"
:helperText "Filter by service state"
:select true
:value state
:variant "outlined"
:margin "normal"
:InputLabelProps {:shrink true}
:onChange #(state/update-value [:filter :state] (-> % .-target .-value) state/form-state-cursor)}
(comp/menu-item
{:key "running"
:value "running"} "running")
(comp/menu-item
{:key "shutdown"
:value "shutdown"} "shutdown"))))
(def toolbar-render-metadata
[{:name "New service"
:onClick #(dispatch! (routes/path-for-frontend :service-create-image))
:primary true
:icon (icon/add-circle-out)
:icon-alt (icon/add)}
{:name "Show filters"
:onClick #(state/update-value [:filterOpen?] true state/form-state-cursor)
:icon (icon/filter-list)
:icon-alt (icon/filter-list)
:variant "outlined"
:color "default"}])
(rum/defc form < rum/reactive
mixin-init-form
mixin/subscribe-form
mixin/focus-filter [_]
(let [{:keys [items]} (state/react state/form-value-cursor)
{:keys [query]} (state/react state/search-cursor)
{:keys [loading? filterOpen? filter]} (state/react state/form-state-cursor)
filtered-items (->> (list-util/filter items query)
(clojure.core/filter #(if (some? (:state filter))
(case (:state filter)
"running" (= "running" (:state %))
"shutdown" (= 0 (get-in % [:status :tasks :total])))
true))
(sort-by :createdAt)
(reverse))]
(progress/form
loading?
(comp/box
{}
(common/list "Services"
items
filtered-items
render-metadata
onclick-handler
toolbar-render-metadata)
(form-filters filterOpen? filter)))))
| |
ac22a0b9548c8f4b18fb8a45ad354b9f697526486fcd4298a700f4d6dd26c4b6 | fakedata-haskell/fakedata | SwordArtOnline.hs | # LANGUAGE TemplateHaskell #
{-# LANGUAGE OverloadedStrings #-}
module Faker.JapaneseMedia.SwordArtOnline where
import Data.Text
import Faker
import Faker.Internal
import Faker.Provider.SwordArtOnline
import Faker.TH
$(generateFakeField "swordArtOnline" "real_name")
$(generateFakeField "swordArtOnline" "game_name")
$(generateFakeField "swordArtOnline" "location")
$(generateFakeField "swordArtOnline" "item")
| null | https://raw.githubusercontent.com/fakedata-haskell/fakedata/e6fbc16cfa27b2d17aa449ea8140788196ca135b/src/Faker/JapaneseMedia/SwordArtOnline.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE TemplateHaskell #
module Faker.JapaneseMedia.SwordArtOnline where
import Data.Text
import Faker
import Faker.Internal
import Faker.Provider.SwordArtOnline
import Faker.TH
$(generateFakeField "swordArtOnline" "real_name")
$(generateFakeField "swordArtOnline" "game_name")
$(generateFakeField "swordArtOnline" "location")
$(generateFakeField "swordArtOnline" "item")
|
edc26d63ccceee5bb3dde426ddb4985847967df7e7fcf46b5ba02a326100e9b5 | chrisdone/duet | placeholders.hs | data List a = Nil | Cons a (List a)
foldr = \f z l ->
case l of
Nil -> z
Cons x xs -> f x (foldr f z xs)
foldl = \f z l ->
case l of
Nil -> z
Cons x xs -> foldl f (f z x) xs
list = (Cons True (Cons False Nil))
main = foldr _f _nil list
| null | https://raw.githubusercontent.com/chrisdone/duet/959d40db68f4c2df04cabb7677724900d4f71db4/examples/placeholders.hs | haskell | data List a = Nil | Cons a (List a)
foldr = \f z l ->
case l of
Nil -> z
Cons x xs -> f x (foldr f z xs)
foldl = \f z l ->
case l of
Nil -> z
Cons x xs -> foldl f (f z x) xs
list = (Cons True (Cons False Nil))
main = foldr _f _nil list
| |
d5c1493a776212ce0585b5486e3a25fa993fdc51e33e6b7683a605a3824dad4a | BIMSBbioinfo/guix-bimsb-nonfree | kentutils.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2019 , 2021 , 2022 < >
;;;
;;; This file is NOT part of GNU Guix, but is supposed to be used with GNU
;;; Guix and thus has the same license.
;;;
GNU is free software ; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (non-free kentutils)
#:use-module ((guix licenses) #:prefix license:)
#:use-module ((guix licenses-nonfree) #:prefix nonfree:)
#:use-module (guix packages)
#:use-module (guix gexp)
#:use-module (guix git-download)
#:use-module (guix utils)
#:use-module (guix build-system gnu)
#:use-module (gnu packages)
#:use-module (gnu packages databases)
#:use-module (gnu packages image)
#:use-module (gnu packages linux)
#:use-module (gnu packages rsync)
#:use-module (gnu packages tls))
(define-public kentutils-nonfree
(package
(name "kentutils-nonfree")
(version "430")
(source (origin
(method git-fetch)
(uri (git-reference
(url "git-source.soe.ucsc.edu/kent.git")
(commit (string-append "v" version "_base"))))
(file-name (git-file-name name version))
(sha256
(base32
"1a9dz4xkb7gsdf644kfcpdj8wcqk2fl04hh7zkpw5z5ffgqwg50w"))))
(build-system gnu-build-system)
(arguments
`(#:make-flags
,#~(list "CC=gcc"
"CFLAGS=-fcommon -DUCSC_CRAM=1 -DKNETFILE_HOOKS -mpopcnt"
(string-append "DESTDIR=" #$output)
(string-append "DOCUMENTROOT=" #$output "/share/kentutils/htdocs")
(string-append "SCRIPTS=" #$output "/share/kentutils/scripts")
(string-append "CGI_BIN=" #$output "/share/kentutils/cgi-bin"))
#:tests? #f ; none included
#:phases
(modify-phases %standard-phases
;; The sources are expected to be found inside the "kent"
;; subdirectory.
(replace 'configure
(lambda _
(rename-file "src/userApps" "buildroot/")
(mkdir "buildroot/kent")
(rename-file "src" "buildroot/kent/src")
(for-each make-file-writable
(find-files "buildroot" ".*"))
(chdir "buildroot")))
(add-before 'build 'build-libs
(lambda* (#:key make-flags #:allow-other-keys)
(apply invoke "make" "-C" "kent/src" "libs" make-flags)))
;; By setting DESTDIR the binaries are built directly in the
;; target directory. There is no separate installation step.
(delete 'install))))
(inputs
(list openssl
libpng
(list util-linux "lib")
mysql))
(native-inputs
(list rsync))
(home-page "")
(synopsis "UCSC genome browser bioinformatic utilities")
(description "This package provides the command line
bioinformatics utilities from the kent source tree used in the UCSC
genome browser.")
;; no commercial usage permitted
(license (nonfree:non-free "file"))))
| null | https://raw.githubusercontent.com/BIMSBbioinfo/guix-bimsb-nonfree/c14c89321b7a4a69f0f1bfec7236621e9902c67e/non-free/kentutils.scm | scheme | GNU Guix --- Functional package management for GNU
This file is NOT part of GNU Guix, but is supposed to be used with GNU
Guix and thus has the same license.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
none included
The sources are expected to be found inside the "kent"
subdirectory.
By setting DESTDIR the binaries are built directly in the
target directory. There is no separate installation step.
no commercial usage permitted | Copyright © 2019 , 2021 , 2022 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (non-free kentutils)
#:use-module ((guix licenses) #:prefix license:)
#:use-module ((guix licenses-nonfree) #:prefix nonfree:)
#:use-module (guix packages)
#:use-module (guix gexp)
#:use-module (guix git-download)
#:use-module (guix utils)
#:use-module (guix build-system gnu)
#:use-module (gnu packages)
#:use-module (gnu packages databases)
#:use-module (gnu packages image)
#:use-module (gnu packages linux)
#:use-module (gnu packages rsync)
#:use-module (gnu packages tls))
(define-public kentutils-nonfree
(package
(name "kentutils-nonfree")
(version "430")
(source (origin
(method git-fetch)
(uri (git-reference
(url "git-source.soe.ucsc.edu/kent.git")
(commit (string-append "v" version "_base"))))
(file-name (git-file-name name version))
(sha256
(base32
"1a9dz4xkb7gsdf644kfcpdj8wcqk2fl04hh7zkpw5z5ffgqwg50w"))))
(build-system gnu-build-system)
(arguments
`(#:make-flags
,#~(list "CC=gcc"
"CFLAGS=-fcommon -DUCSC_CRAM=1 -DKNETFILE_HOOKS -mpopcnt"
(string-append "DESTDIR=" #$output)
(string-append "DOCUMENTROOT=" #$output "/share/kentutils/htdocs")
(string-append "SCRIPTS=" #$output "/share/kentutils/scripts")
(string-append "CGI_BIN=" #$output "/share/kentutils/cgi-bin"))
#:phases
(modify-phases %standard-phases
(replace 'configure
(lambda _
(rename-file "src/userApps" "buildroot/")
(mkdir "buildroot/kent")
(rename-file "src" "buildroot/kent/src")
(for-each make-file-writable
(find-files "buildroot" ".*"))
(chdir "buildroot")))
(add-before 'build 'build-libs
(lambda* (#:key make-flags #:allow-other-keys)
(apply invoke "make" "-C" "kent/src" "libs" make-flags)))
(delete 'install))))
(inputs
(list openssl
libpng
(list util-linux "lib")
mysql))
(native-inputs
(list rsync))
(home-page "")
(synopsis "UCSC genome browser bioinformatic utilities")
(description "This package provides the command line
bioinformatics utilities from the kent source tree used in the UCSC
genome browser.")
(license (nonfree:non-free "file"))))
|
20e2befee4f7ef0bb7fcaf28d125152e4d925cd65db46218a39e2b49e784c029 | dyzsr/ocaml-selectml | parsetree.mli | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(** Abstract syntax tree produced by parsing
{b Warning:} this module is unstable and part of
{{!Compiler_libs}compiler-libs}.
*)
open Asttypes
type constant =
| Pconst_integer of string * char option
* Integer constants such as [ 3 ] [ 3l ] [ 3L ] [ 3n ] .
Suffixes [ [ g - z][G - Z ] ] are accepted by the parser .
Suffixes except [ ' l ' ] , [ ' L ' ] and [ ' n ' ] are rejected by the typechecker
Suffixes [[g-z][G-Z]] are accepted by the parser.
Suffixes except ['l'], ['L'] and ['n'] are rejected by the typechecker
*)
| Pconst_char of char (** Character such as ['c']. *)
| Pconst_string of string * Location.t * string option
* Constant string such as [ " constant " ] or
[ { } ] .
The location span the content of the string , without the delimiters .
[{delim|other constant|delim}].
The location span the content of the string, without the delimiters.
*)
| Pconst_float of string * char option
* Float constant such as [ 3.4 ] , [ 2e5 ] or [ 1.4e-4 ] .
Suffixes [ g - z][G - Z ] are accepted by the parser .
Suffixes are rejected by the typechecker .
Suffixes [g-z][G-Z] are accepted by the parser.
Suffixes are rejected by the typechecker.
*)
type location_stack = Location.t list
* { 1 Extension points }
type attribute = {
attr_name : string loc;
attr_payload : payload;
attr_loc : Location.t;
}
(** Attributes such as [[\@id ARG]] and [[\@\@id ARG]].
Metadata containers passed around within the AST.
The compiler ignores unknown attributes.
*)
and extension = string loc * payload
(** Extension points such as [[%id ARG] and [%%id ARG]].
Sub-language placeholder -- rejected by the typechecker.
*)
and attributes = attribute list
and payload =
| PStr of structure
* [: SIG ] in an attribute or an extension point
| PTyp of core_type (** [: T] in an attribute or an extension point *)
| PPat of pattern * expression option
(** [? P] or [? P when E], in an attribute or an extension point *)
* { 1 Core language }
* { 2 Type expressions }
and core_type =
{
ptyp_desc: core_type_desc;
ptyp_loc: Location.t;
ptyp_loc_stack: location_stack;
ptyp_attributes: attributes; (** [... [\@id1] [\@id2]] *)
}
and core_type_desc =
| Ptyp_any (** [_] *)
| Ptyp_var of string (** A type variable such as ['a] *)
| Ptyp_arrow of arg_label * core_type * core_type
(** [Ptyp_arrow(lbl, T1, T2)] represents:
- [T1 -> T2] when [lbl] is
{{!Asttypes.arg_label.Nolabel}[Nolabel]},
- [~l:T1 -> T2] when [lbl] is
{{!Asttypes.arg_label.Labelled}[Labelled]},
- [?l:T1 -> T2] when [lbl] is
{{!Asttypes.arg_label.Optional}[Optional]}.
*)
| Ptyp_tuple of core_type list
* [ Ptyp_tuple([T1 ; ... ; Tn ] ) ]
represents a product type [ T1 * ... * Tn ] .
Invariant : [ n > = 2 ] .
represents a product type [T1 * ... * Tn].
Invariant: [n >= 2].
*)
| Ptyp_constr of Longident.t loc * core_type list
(** [Ptyp_constr(lident, l)] represents:
- [tconstr] when [l=[]],
- [T tconstr] when [l=[T]],
- [(T1, ..., Tn) tconstr] when [l=[T1 ; ... ; Tn]].
*)
| Ptyp_object of object_field list * closed_flag
(** [Ptyp_object([ l1:T1; ...; ln:Tn ], flag)] represents:
- [< l1:T1; ...; ln:Tn >] when [flag] is
{{!Asttypes.closed_flag.Closed}[Closed]},
- [< l1:T1; ...; ln:Tn; .. >] when [flag] is
{{!Asttypes.closed_flag.Open}[Open]}.
*)
| Ptyp_class of Longident.t loc * core_type list
(** [Ptyp_class(tconstr, l)] represents:
- [#tconstr] when [l=[]],
- [T #tconstr] when [l=[T]],
- [(T1, ..., Tn) #tconstr] when [l=[T1 ; ... ; Tn]].
*)
| Ptyp_alias of core_type * string (** [T as 'a]. *)
| Ptyp_variant of row_field list * closed_flag * label list option
(** [Ptyp_variant([`A;`B], flag, labels)] represents:
- [[ `A|`B ]]
when [flag] is {{!Asttypes.closed_flag.Closed}[Closed]},
and [labels] is [None],
- [[> `A|`B ]]
when [flag] is {{!Asttypes.closed_flag.Open}[Open]},
and [labels] is [None],
- [[< `A|`B ]]
when [flag] is {{!Asttypes.closed_flag.Closed}[Closed]},
and [labels] is [Some []],
- [[< `A|`B > `X `Y ]]
when [flag] is {{!Asttypes.closed_flag.Closed}[Closed]},
and [labels] is [Some ["X";"Y"]].
*)
| Ptyp_poly of string loc list * core_type
* [ ' a1 ... ' an . T ]
Can only appear in the following context :
- As the { ! core_type } of a
{ { ! pattern_desc . Ppat_constraint}[Ppat_constraint ] } node corresponding
to a constraint on a let - binding :
{ [ let x : ' a1 ... ' an . T = e ... ] }
- Under { { ! class_field_kind . Cfk_virtual}[Cfk_virtual ] } for methods
( not values ) .
- As the { ! core_type } of a
{ { ! class_type_field_desc . ] } node .
- As the { ! core_type } of a { { ! expression_desc . Pexp_poly}[Pexp_poly ] }
node .
- As the { { ! label_declaration.pld_type}[pld_type ] } field of a
{ ! label_declaration } .
- As a { ! core_type } of a { { ! core_type_desc . Ptyp_object}[Ptyp_object ] }
node .
- As the { { ! value_description.pval_type}[pval_type ] } field of a
{ ! value_description } .
Can only appear in the following context:
- As the {!core_type} of a
{{!pattern_desc.Ppat_constraint}[Ppat_constraint]} node corresponding
to a constraint on a let-binding:
{[let x : 'a1 ... 'an. T = e ...]}
- Under {{!class_field_kind.Cfk_virtual}[Cfk_virtual]} for methods
(not values).
- As the {!core_type} of a
{{!class_type_field_desc.Pctf_method}[Pctf_method]} node.
- As the {!core_type} of a {{!expression_desc.Pexp_poly}[Pexp_poly]}
node.
- As the {{!label_declaration.pld_type}[pld_type]} field of a
{!label_declaration}.
- As a {!core_type} of a {{!core_type_desc.Ptyp_object}[Ptyp_object]}
node.
- As the {{!value_description.pval_type}[pval_type]} field of a
{!value_description}.
*)
| Ptyp_package of package_type (** [(module S)]. *)
| Ptyp_extension of extension (** [[%id]]. *)
and package_type = Longident.t loc * (Longident.t loc * core_type) list
* As { ! package_type } typed values :
- [ ( S , [ ] ) ] represents [ ( module S ) ] ,
- [ ( S , [ ( t1 , T1 ) ; ... ; ( tn , Tn ) ] ) ]
represents [ ( module S with type t1 = T1 and ... and tn = Tn ) ] .
- [(S, [])] represents [(module S)],
- [(S, [(t1, T1) ; ... ; (tn, Tn)])]
represents [(module S with type t1 = T1 and ... and tn = Tn)].
*)
and row_field = {
prf_desc : row_field_desc;
prf_loc : Location.t;
prf_attributes : attributes;
}
and row_field_desc =
| Rtag of label loc * bool * core_type list
* [ , b , l ) ] represents :
- [ ` A ] when [ b ] is [ true ] and [ l ] is [ [ ] ] ,
- [ ` A of T ] when [ b ] is [ false ] and [ l ] is [ [ T ] ] ,
- [ ` A of T1 & .. & Tn ] when [ b ] is [ false ] and [ l ] is [ [ T1; ... Tn ] ] ,
- [ ` A of & T1 & .. & Tn ] when [ b ] is [ true ] and [ l ] is [ [ T1; ... Tn ] ] .
- The [ bool ] field is true if the tag contains a
constant ( empty ) constructor .
- [ & ] occurs when several types are used for the same constructor
( see 4.2 in the manual )
- [`A] when [b] is [true] and [l] is [[]],
- [`A of T] when [b] is [false] and [l] is [[T]],
- [`A of T1 & .. & Tn] when [b] is [false] and [l] is [[T1;...Tn]],
- [`A of & T1 & .. & Tn] when [b] is [true] and [l] is [[T1;...Tn]].
- The [bool] field is true if the tag contains a
constant (empty) constructor.
- [&] occurs when several types are used for the same constructor
(see 4.2 in the manual)
*)
| Rinherit of core_type (** [[ | t ]] *)
and object_field = {
pof_desc : object_field_desc;
pof_loc : Location.t;
pof_attributes : attributes;
}
and object_field_desc =
| Otag of label loc * core_type
| Oinherit of core_type
(** {2 Patterns} *)
and pattern =
{
ppat_desc: pattern_desc;
ppat_loc: Location.t;
ppat_loc_stack: location_stack;
ppat_attributes: attributes; (** [... [\@id1] [\@id2]] *)
}
and pattern_desc =
| Ppat_any (** The pattern [_]. *)
| Ppat_var of string loc (** A variable pattern such as [x] *)
| Ppat_alias of pattern * string loc
(** An alias pattern such as [P as 'a] *)
| Ppat_constant of constant
* Patterns such as [ 1 ] , [ ' a ' ] , [ " true " ] , [ 1.0 ] , [ 1l ] , [ 1L ] , [ 1n ]
| Ppat_interval of constant * constant
(** Patterns such as ['a'..'z'].
Other forms of interval are recognized by the parser
but rejected by the type-checker. *)
| Ppat_tuple of pattern list
* Patterns [ ( P1 , ... , Pn ) ] .
Invariant : [ n > = 2 ]
Invariant: [n >= 2]
*)
| Ppat_construct of Longident.t loc * (string loc list * pattern) option
(** [Ppat_construct(C, args)] represents:
- [C] when [args] is [None],
- [C P] when [args] is [Some ([], P)]
- [C (P1, ..., Pn)] when [args] is
[Some ([], Ppat_tuple [P1; ...; Pn])]
- [C (type a b) P] when [args] is [Some ([a; b], P)]
*)
| Ppat_variant of label * pattern option
(** [Ppat_variant(`A, pat)] represents:
- [`A] when [pat] is [None],
- [`A P] when [pat] is [Some P]
*)
| Ppat_record of (Longident.t loc * pattern) list * closed_flag
* [ Ppat_record([(l1 , P1 ) ; ... ; ( ln , Pn ) ] , flag ) ] represents :
- [ { l1 = P1 ; ... ; ln = Pn } ]
when [ flag ] is { { ! Asttypes.closed_flag . Closed}[Closed ] }
- [ { l1 = P1 ; ... ; ln = Pn ; _ } ]
when [ flag ] is { { ! Asttypes.closed_flag . Open}[Open ] }
Invariant : [ n > 0 ]
- [{ l1=P1; ...; ln=Pn }]
when [flag] is {{!Asttypes.closed_flag.Closed}[Closed]}
- [{ l1=P1; ...; ln=Pn; _}]
when [flag] is {{!Asttypes.closed_flag.Open}[Open]}
Invariant: [n > 0]
*)
| Ppat_array of pattern list (** Pattern [[| P1; ...; Pn |]] *)
| Ppat_or of pattern * pattern (** Pattern [P1 | P2] *)
| Ppat_constraint of pattern * core_type (** Pattern [(P : T)] *)
| Ppat_type of Longident.t loc (** Pattern [#tconst] *)
| Ppat_lazy of pattern (** Pattern [lazy P] *)
| Ppat_unpack of string option loc
(** [Ppat_unpack(s)] represents:
- [(module P)] when [s] is [Some "P"]
- [(module _)] when [s] is [None]
Note: [(module P : S)] is represented as
[Ppat_constraint(Ppat_unpack(Some "P"), Ptyp_package S)]
*)
| Ppat_exception of pattern (** Pattern [exception P] *)
| Ppat_extension of extension (** Pattern [[%id]] *)
| Ppat_open of Longident.t loc * pattern (** Pattern [M.(P)] *)
* { 2 Value expressions }
and expression =
{
pexp_desc: expression_desc;
pexp_loc: Location.t;
pexp_loc_stack: location_stack;
pexp_attributes: attributes; (** [... [\@id1] [\@id2]] *)
}
and expression_desc =
| Pexp_ident of Longident.t loc
* Identifiers such as [ x ] and [ ]
*)
| Pexp_constant of constant
* Expressions constant such as [ 1 ] , [ ' a ' ] , [ " true " ] , [ 1.0 ] , [ 1l ] ,
[ 1L ] , [ 1n ]
[1L], [1n] *)
| Pexp_let of rec_flag * value_binding list * expression
(** [Pexp_let(flag, [(P1,E1) ; ... ; (Pn,En)], E)] represents:
- [let P1 = E1 and ... and Pn = EN in E]
when [flag] is {{!Asttypes.rec_flag.Nonrecursive}[Nonrecursive]},
- [let rec P1 = E1 and ... and Pn = EN in E]
when [flag] is {{!Asttypes.rec_flag.Recursive}[Recursive]}.
*)
| Pexp_function of case list (** [function P1 -> E1 | ... | Pn -> En] *)
| Pexp_fun of arg_label * expression option * pattern * expression
* [ Pexp_fun(lbl , exp0 , P , E1 ) ] represents :
- [ fun P - > E1 ]
when [ lbl ] is { { ! Asttypes.arg_label . Nolabel}[Nolabel ] }
and [ exp0 ] is [ None ]
- [ fun ~l :P - > E1 ]
when [ lbl ] is { { ! Asttypes.arg_label . Labelled}[Labelled l ] }
and [ exp0 ] is [ None ]
- [ fun ? l :P - > E1 ]
when [ lbl ] is { { ! Asttypes.arg_label . Optional}[Optional l ] }
and [ exp0 ] is [ None ]
- [ fun ? l:(P = E0 ) - > E1 ]
when [ lbl ] is { { ! Asttypes.arg_label . Optional}[Optional l ] }
and [ exp0 ] is [ Some E0 ]
Notes :
- If [ E0 ] is provided , only
{ { ! Asttypes.arg_label . Optional}[Optional ] } is allowed .
- [ fun P1 P2 .. Pn - > E1 ] is represented as nested
{ { ! expression_desc . Pexp_fun}[Pexp_fun ] } .
- [ let f P = E ] is represented using
{ { ! expression_desc . Pexp_fun}[Pexp_fun ] } .
- [fun P -> E1]
when [lbl] is {{!Asttypes.arg_label.Nolabel}[Nolabel]}
and [exp0] is [None]
- [fun ~l:P -> E1]
when [lbl] is {{!Asttypes.arg_label.Labelled}[Labelled l]}
and [exp0] is [None]
- [fun ?l:P -> E1]
when [lbl] is {{!Asttypes.arg_label.Optional}[Optional l]}
and [exp0] is [None]
- [fun ?l:(P = E0) -> E1]
when [lbl] is {{!Asttypes.arg_label.Optional}[Optional l]}
and [exp0] is [Some E0]
Notes:
- If [E0] is provided, only
{{!Asttypes.arg_label.Optional}[Optional]} is allowed.
- [fun P1 P2 .. Pn -> E1] is represented as nested
{{!expression_desc.Pexp_fun}[Pexp_fun]}.
- [let f P = E] is represented using
{{!expression_desc.Pexp_fun}[Pexp_fun]}.
*)
| Pexp_apply of expression * (arg_label * expression) list
(** [Pexp_apply(E0, [(l1, E1) ; ... ; (ln, En)])]
represents [E0 ~l1:E1 ... ~ln:En]
[li] can be
{{!Asttypes.arg_label.Nolabel}[Nolabel]} (non labeled argument),
{{!Asttypes.arg_label.Labelled}[Labelled]} (labelled arguments) or
{{!Asttypes.arg_label.Optional}[Optional]} (optional argument).
Invariant: [n > 0]
*)
| Pexp_match of expression * case list
* [ match E0 with P1 - > E1 | ... | Pn - > En ]
| Pexp_try of expression * case list
* [ try E0 with P1 - > E1 | ... | Pn - > En ]
| Pexp_tuple of expression list
* Expressions [ ( E1 , ... , En ) ]
Invariant : [ n > = 2 ]
Invariant: [n >= 2]
*)
| Pexp_construct of Longident.t loc * expression option
(** [Pexp_construct(C, exp)] represents:
- [C] when [exp] is [None],
- [C E] when [exp] is [Some E],
- [C (E1, ..., En)] when [exp] is [Some (Pexp_tuple[E1;...;En])]
*)
| Pexp_variant of label * expression option
* [ Pexp_variant(`A , exp ) ] represents
- [ ` A ] when [ exp ] is [ None ]
- [ ` A E ] when [ exp ] is [ Some E ]
- [`A] when [exp] is [None]
- [`A E] when [exp] is [Some E]
*)
| Pexp_record of (Longident.t loc * expression) list * expression option
* [ Pexp_record([(l1,P1 ) ; ... ; ( ln , Pn ) ] , exp0 ) ] represents
- [ { l1 = P1 ; ... ; ln = Pn } ] when [ exp0 ] is [ None ]
- [ { E0 with l1 = P1 ; ... ; ln = Pn } ] when [ exp0 ] is [ Some E0 ]
Invariant : [ n > 0 ]
- [{ l1=P1; ...; ln=Pn }] when [exp0] is [None]
- [{ E0 with l1=P1; ...; ln=Pn }] when [exp0] is [Some E0]
Invariant: [n > 0]
*)
| Pexp_field of expression * Longident.t loc (** [E.l] *)
| Pexp_setfield of expression * Longident.t loc * expression
(** [E1.l <- E2] *)
| Pexp_array of expression list (** [[| E1; ...; En |]] *)
| Pexp_ifthenelse of expression * expression * expression option
(** [if E1 then E2 else E3] *)
| Pexp_sequence of expression * expression (** [E1; E2] *)
| Pexp_while of expression * expression (** [while E1 do E2 done] *)
| Pexp_for of pattern * expression * expression * direction_flag * expression
* [ Pexp_for(i , E1 , E2 , direction , E3 ) ] represents :
- [ for i = E1 to E2 do E3 done ]
when [ direction ] is { { ! Asttypes.direction_flag . Upto}[Upto ] }
- [ for i = E1 downto E2 do E3 done ]
when [ direction ] is { { ! Asttypes.direction_flag . Downto}[Downto ] }
- [for i = E1 to E2 do E3 done]
when [direction] is {{!Asttypes.direction_flag.Upto}[Upto]}
- [for i = E1 downto E2 do E3 done]
when [direction] is {{!Asttypes.direction_flag.Downto}[Downto]}
*)
| Pexp_constraint of expression * core_type (** [(E : T)] *)
| Pexp_coerce of expression * core_type option * core_type
* [ , from , T ) ] represents
- [ ( E :> T ) ] when [ from ] is [ None ] ,
- [ ( E : T0 :> T ) ] when [ from ] is [ Some T0 ] .
- [(E :> T)] when [from] is [None],
- [(E : T0 :> T)] when [from] is [Some T0].
*)
| Pexp_send of expression * label loc (** [E # m] *)
| Pexp_new of Longident.t loc (** [new M.c] *)
| Pexp_setinstvar of label loc * expression (** [x <- 2] *)
| Pexp_override of (label loc * expression) list
(** [{< x1 = E1; ...; xn = En >}] *)
| Pexp_letmodule of string option loc * module_expr * expression
(** [let module M = ME in E] *)
| Pexp_letexception of extension_constructor * expression
(** [let exception C in E] *)
| Pexp_assert of expression
(** [assert E].
Note: [assert false] is treated in a special way by the
type-checker. *)
| Pexp_lazy of expression (** [lazy E] *)
| Pexp_poly of expression * core_type option
(** Used for method bodies.
Can only be used as the expression under
{{!class_field_kind.Cfk_concrete}[Cfk_concrete]} for methods (not
values). *)
| Pexp_object of class_structure (** [object ... end] *)
| Pexp_newtype of string loc * expression (** [fun (type t) -> E] *)
| Pexp_pack of module_expr
(** [(module ME)].
[(module ME : S)] is represented as
[Pexp_constraint(Pexp_pack ME, Ptyp_package S)] *)
| Pexp_open of open_declaration * expression
(** - [M.(E)]
- [let open M in E]
- [let open! M in E] *)
| Pexp_letop of letop
(** - [let* P = E0 in E1]
- [let* P0 = E00 and* P1 = E01 in E1] *)
| Pexp_extension of extension (** [[%id]] *)
| Pexp_unreachable (** [.] *)
| Pexp_select of select_expr
(* SELECT ... FROM ... WHERE ...
GROUP BY ... HAVING ... ORDER BY ... *)
| Pexp_aggregate of expression * expression
(* SELECT {count (x, y)} ...
SELECT x, {sum y}, {avg z} ...
SELECT ... HAVING {count x} > 0 ...
SELECT ... ORDER BY {count x}
Invariant: usage outside SELECT context is not allowed *)
and select_expr =
{
se_select : expression;
se_distinct : bool loc;
se_from : source_expr option;
se_where : expression option;
se_groupby : expression option;
se_having : expression option;
se_orderby : (expression * order_direction) list;
se_orderby_loc : Location.t
}
and source_expr =
{
psrc_desc : source_expr_desc;
psrc_loc : Location.t
}
and source_expr_desc =
| Psrc_exp of expression * string loc list
| Psrc_product of source_expr * source_expr
| Psrc_join of source_expr * source_expr * expression
and order_direction =
| PAscending
| PDescending
| PUsing of expression
and case =
{
pc_lhs: pattern;
pc_guard: expression option;
pc_rhs: expression;
}
(** Values of type {!case} represents [(P -> E)] or [(P when E0 -> E)] *)
and letop =
{
let_ : binding_op;
ands : binding_op list;
body : expression;
}
and binding_op =
{
pbop_op : string loc;
pbop_pat : pattern;
pbop_exp : expression;
pbop_loc : Location.t;
}
* { 2 Value descriptions }
and value_description =
{
pval_name: string loc;
pval_type: core_type;
pval_prim: string list;
* [ ... [ \@\@id1 ] [ \@\@id2 ] ]
pval_loc: Location.t;
}
(** Values of type {!value_description} represents:
- [val x: T],
when {{!value_description.pval_prim}[pval_prim]} is [[]]
- [external x: T = "s1" ... "sn"]
when {{!value_description.pval_prim}[pval_prim]} is [["s1";..."sn"]]
*)
* { 2 Type declarations }
and type_declaration =
{
ptype_name: string loc;
ptype_params: (core_type * (variance * injectivity)) list;
(** [('a1,...'an) t] *)
ptype_cstrs: (core_type * core_type * Location.t) list;
* [ ... constraint T1 = T1 ' ... constraint ]
ptype_kind: type_kind;
ptype_private: private_flag; (** for [= private ...] *)
ptype_manifest: core_type option; (** represents [= T] *)
* [ ... [ \@\@id1 ] [ \@\@id2 ] ]
ptype_loc: Location.t;
}
*
Here are type declarations and their representation ,
for various { { ! type_declaration.ptype_kind}[ptype_kind ] }
and { { ! ] } values :
- [ type t ] when [ type_kind ] is { { ! type_kind . Ptype_abstract}[Ptype_abstract ] } ,
and [ manifest ] is [ None ] ,
- [ type t = T0 ]
when [ type_kind ] is { { ! type_kind . Ptype_abstract}[Ptype_abstract ] } ,
and [ manifest ] is [ Some T0 ] ,
- [ type t = C of T | ... ]
when [ type_kind ] is { { ! type_kind . Ptype_variant}[Ptype_variant ] } ,
and [ manifest ] is [ None ] ,
- [ type t = T0 = C of T | ... ]
when [ type_kind ] is { { ! type_kind . Ptype_variant}[Ptype_variant ] } ,
and [ manifest ] is [ Some T0 ] ,
- [ type t = { l : T ; ... } ]
when [ type_kind ] is { { ! type_kind . Ptype_record}[Ptype_record ] } ,
and [ manifest ] is [ None ] ,
- [ type t = T0 = { l : T ; ... } ]
when [ type_kind ] is { { ! type_kind . Ptype_record}[Ptype_record ] } ,
and [ manifest ] is [ Some T0 ] ,
- [ type t = .. ]
when [ type_kind ] is { { ! type_kind . Ptype_open}[Ptype_open ] } ,
and [ manifest ] is [ None ] .
Here are type declarations and their representation,
for various {{!type_declaration.ptype_kind}[ptype_kind]}
and {{!type_declaration.ptype_manifest}[ptype_manifest]} values:
- [type t] when [type_kind] is {{!type_kind.Ptype_abstract}[Ptype_abstract]},
and [manifest] is [None],
- [type t = T0]
when [type_kind] is {{!type_kind.Ptype_abstract}[Ptype_abstract]},
and [manifest] is [Some T0],
- [type t = C of T | ...]
when [type_kind] is {{!type_kind.Ptype_variant}[Ptype_variant]},
and [manifest] is [None],
- [type t = T0 = C of T | ...]
when [type_kind] is {{!type_kind.Ptype_variant}[Ptype_variant]},
and [manifest] is [Some T0],
- [type t = {l: T; ...}]
when [type_kind] is {{!type_kind.Ptype_record}[Ptype_record]},
and [manifest] is [None],
- [type t = T0 = {l : T; ...}]
when [type_kind] is {{!type_kind.Ptype_record}[Ptype_record]},
and [manifest] is [Some T0],
- [type t = ..]
when [type_kind] is {{!type_kind.Ptype_open}[Ptype_open]},
and [manifest] is [None].
*)
and type_kind =
| Ptype_abstract
| Ptype_variant of constructor_declaration list
| Ptype_record of label_declaration list (** Invariant: non-empty list *)
| Ptype_open
and label_declaration =
{
pld_name: string loc;
pld_mutable: mutable_flag;
pld_type: core_type;
pld_loc: Location.t;
pld_attributes: attributes; (** [l : T [\@id1] [\@id2]] *)
}
(**
- [{ ...; l: T; ... }]
when {{!label_declaration.pld_mutable}[pld_mutable]}
is {{!Asttypes.mutable_flag.Immutable}[Immutable]},
- [{ ...; mutable l: T; ... }]
when {{!label_declaration.pld_mutable}[pld_mutable]}
is {{!Asttypes.mutable_flag.Mutable}[Mutable]}.
Note: [T] can be a {{!core_type_desc.Ptyp_poly}[Ptyp_poly]}.
*)
and constructor_declaration =
{
pcd_name: string loc;
pcd_vars: string loc list;
pcd_args: constructor_arguments;
pcd_res: core_type option;
pcd_loc: Location.t;
pcd_attributes: attributes; (** [C of ... [\@id1] [\@id2]] *)
}
and constructor_arguments =
| Pcstr_tuple of core_type list
| Pcstr_record of label_declaration list
(** Values of type {!constructor_declaration}
represents the constructor arguments of:
- [C of T1 * ... * Tn] when [res = None],
and [args = Pcstr_tuple [T1; ... ; Tn]],
- [C: T0] when [res = Some T0],
and [args = Pcstr_tuple []],
- [C: T1 * ... * Tn -> T0] when [res = Some T0],
and [args = Pcstr_tuple [T1; ... ; Tn]],
- [C of {...}] when [res = None],
and [args = Pcstr_record [...]],
- [C: {...} -> T0] when [res = Some T0],
and [args = Pcstr_record [...]].
*)
and type_extension =
{
ptyext_path: Longident.t loc;
ptyext_params: (core_type * (variance * injectivity)) list;
ptyext_constructors: extension_constructor list;
ptyext_private: private_flag;
ptyext_loc: Location.t;
* ... [ \@\@id1 ] [ \@\@id2 ]
}
(**
Definition of new extensions constructors for the extensive sum type [t]
([type t += ...]).
*)
and extension_constructor =
{
pext_name: string loc;
pext_kind: extension_constructor_kind;
pext_loc: Location.t;
pext_attributes: attributes; (** [C of ... [\@id1] [\@id2]] *)
}
and type_exception =
{
ptyexn_constructor : extension_constructor;
ptyexn_loc : Location.t;
* [ ... [ \@\@id1 ] [ \@\@id2 ] ]
}
(** Definition of a new exception ([exception E]). *)
and extension_constructor_kind =
| Pext_decl of string loc list * constructor_arguments * core_type option
* [ Pext_decl(existentials , , t_opt ) ]
describes a new extension constructor . It can be :
- [ C of T1 * ... * Tn ] when :
{ ul { - [ existentials ] is [ [ ] ] , }
{ - [ c_args ] is [ [ T1 ; ... ; Tn ] ] , }
{ - [ t_opt ] is [ None ] } . }
- [ C : T0 ] when
{ ul { - [ existentials ] is [ [ ] ] , }
{ - [ c_args ] is [ [ ] ] , }
{ - [ t_opt ] is [ Some T0 ] . } }
- [ C : T1 * ... * Tn - > T0 ] when
{ ul { - [ existentials ] is [ [ ] ] , }
{ - [ c_args ] is [ [ T1 ; ... ; Tn ] ] , }
{ - [ t_opt ] is [ Some T0 ] . } }
- [ C : ' a ... . T1 * ... * Tn - > T0 ] when
{ ul { - [ existentials ] is [ [ ' a ; ... ] ] , }
{ - [ c_args ] is [ [ T1 ; ... ; Tn ] ] , }
{ - [ t_opt ] is [ Some T0 ] . } }
describes a new extension constructor. It can be:
- [C of T1 * ... * Tn] when:
{ul {- [existentials] is [[]],}
{- [c_args] is [[T1; ...; Tn]],}
{- [t_opt] is [None]}.}
- [C: T0] when
{ul {- [existentials] is [[]],}
{- [c_args] is [[]],}
{- [t_opt] is [Some T0].}}
- [C: T1 * ... * Tn -> T0] when
{ul {- [existentials] is [[]],}
{- [c_args] is [[T1; ...; Tn]],}
{- [t_opt] is [Some T0].}}
- [C: 'a... . T1 * ... * Tn -> T0] when
{ul {- [existentials] is [['a;...]],}
{- [c_args] is [[T1; ... ; Tn]],}
{- [t_opt] is [Some T0].}}
*)
| Pext_rebind of Longident.t loc
(** [Pext_rebind(D)] re-export the constructor [D] with the new name [C] *)
(** {1 Class language} *)
* { 2 Type expressions for the class language }
and class_type =
{
pcty_desc: class_type_desc;
pcty_loc: Location.t;
pcty_attributes: attributes; (** [... [\@id1] [\@id2]] *)
}
and class_type_desc =
| Pcty_constr of Longident.t loc * core_type list
(** - [c]
- [['a1, ..., 'an] c] *)
| Pcty_signature of class_signature (** [object ... end] *)
| Pcty_arrow of arg_label * core_type * class_type
(** [Pcty_arrow(lbl, T, CT)] represents:
- [T -> CT]
when [lbl] is {{!Asttypes.arg_label.Nolabel}[Nolabel]},
- [~l:T -> CT]
when [lbl] is {{!Asttypes.arg_label.Labelled}[Labelled l]},
- [?l:T -> CT]
when [lbl] is {{!Asttypes.arg_label.Optional}[Optional l]}.
*)
| Pcty_extension of extension (** [%id] *)
| Pcty_open of open_description * class_type (** [let open M in CT] *)
and class_signature =
{
pcsig_self: core_type;
pcsig_fields: class_type_field list;
}
(** Values of type [class_signature] represents:
- [object('selfpat) ... end]
- [object ... end] when {{!class_signature.pcsig_self}[pcsig_self]}
is {{!core_type_desc.Ptyp_any}[Ptyp_any]}
*)
and class_type_field =
{
pctf_desc: class_type_field_desc;
pctf_loc: Location.t;
* [ ... [ \@\@id1 ] [ \@\@id2 ] ]
}
and class_type_field_desc =
| Pctf_inherit of class_type (** [inherit CT] *)
| Pctf_val of (label loc * mutable_flag * virtual_flag * core_type)
* [ x : T ]
| Pctf_method of (label loc * private_flag * virtual_flag * core_type)
(** [method x: T]
Note: [T] can be a {{!core_type_desc.Ptyp_poly}[Ptyp_poly]}.
*)
| Pctf_constraint of (core_type * core_type) (** [constraint T1 = T2] *)
| Pctf_attribute of attribute (** [[\@\@\@id]] *)
| Pctf_extension of extension (** [[%%id]] *)
and 'a class_infos =
{
pci_virt: virtual_flag;
pci_params: (core_type * (variance * injectivity)) list;
pci_name: string loc;
pci_expr: 'a;
pci_loc: Location.t;
* [ ... [ \@\@id1 ] [ \@\@id2 ] ]
}
(** Values of type [class_expr class_infos] represents:
- [class c = ...]
- [class ['a1,...,'an] c = ...]
- [class virtual c = ...]
They are also used for "class type" declaration.
*)
and class_description = class_type class_infos
and class_type_declaration = class_type class_infos
* { 2 Value expressions for the class language }
and class_expr =
{
pcl_desc: class_expr_desc;
pcl_loc: Location.t;
pcl_attributes: attributes; (** [... [\@id1] [\@id2]] *)
}
and class_expr_desc =
| Pcl_constr of Longident.t loc * core_type list
(** [c] and [['a1, ..., 'an] c] *)
| Pcl_structure of class_structure (** [object ... end] *)
| Pcl_fun of arg_label * expression option * pattern * class_expr
* [ Pcl_fun(lbl , exp0 , P , CE ) ] represents :
- [ fun P - > CE ]
when [ lbl ] is { { ! Asttypes.arg_label . Nolabel}[Nolabel ] }
and [ exp0 ] is [ None ] ,
- [ fun ~l :P - > CE ]
when [ lbl ] is { { ! Asttypes.arg_label . Labelled}[Labelled l ] }
and [ exp0 ] is [ None ] ,
- [ fun ? l :P - > CE ]
when [ lbl ] is { { ! Asttypes.arg_label . Optional}[Optional l ] }
and [ exp0 ] is [ None ] ,
- [ fun ? l:(P = E0 ) - > CE ]
when [ lbl ] is { { ! Asttypes.arg_label . Optional}[Optional l ] }
and [ exp0 ] is [ Some E0 ] .
- [fun P -> CE]
when [lbl] is {{!Asttypes.arg_label.Nolabel}[Nolabel]}
and [exp0] is [None],
- [fun ~l:P -> CE]
when [lbl] is {{!Asttypes.arg_label.Labelled}[Labelled l]}
and [exp0] is [None],
- [fun ?l:P -> CE]
when [lbl] is {{!Asttypes.arg_label.Optional}[Optional l]}
and [exp0] is [None],
- [fun ?l:(P = E0) -> CE]
when [lbl] is {{!Asttypes.arg_label.Optional}[Optional l]}
and [exp0] is [Some E0].
*)
| Pcl_apply of class_expr * (arg_label * expression) list
* [ Pcl_apply(CE , [ ( ) ; ... ; ( ln , En ) ] ) ]
represents [ CE ~l1 : E1 ... ~ln : En ] .
[ li ] can be empty ( non labeled argument ) or start with [ ? ]
( optional argument ) .
Invariant : [ n > 0 ]
represents [CE ~l1:E1 ... ~ln:En].
[li] can be empty (non labeled argument) or start with [?]
(optional argument).
Invariant: [n > 0]
*)
| Pcl_let of rec_flag * value_binding list * class_expr
(** [Pcl_let(rec, [(P1, E1); ... ; (Pn, En)], CE)] represents:
- [let P1 = E1 and ... and Pn = EN in CE]
when [rec] is {{!Asttypes.rec_flag.Nonrecursive}[Nonrecursive]},
- [let rec P1 = E1 and ... and Pn = EN in CE]
when [rec] is {{!Asttypes.rec_flag.Recursive}[Recursive]}.
*)
| Pcl_constraint of class_expr * class_type (** [(CE : CT)] *)
| Pcl_extension of extension (** [[%id]] *)
| Pcl_open of open_description * class_expr (** [let open M in CE] *)
and class_structure =
{
pcstr_self: pattern;
pcstr_fields: class_field list;
}
(** Values of type {!class_structure} represents:
- [object(selfpat) ... end]
- [object ... end] when {{!class_structure.pcstr_self}[pcstr_self]}
is {{!pattern_desc.Ppat_any}[Ppat_any]}
*)
and class_field =
{
pcf_desc: class_field_desc;
pcf_loc: Location.t;
* [ ... [ \@\@id1 ] [ \@\@id2 ] ]
}
and class_field_desc =
| Pcf_inherit of override_flag * class_expr * string loc option
* [ Pcf_inherit(flag , CE , s ) ] represents :
- [ inherit CE ]
when [ flag ] is { { ! . Fresh}[Fresh ] }
and [ s ] is [ None ] ,
- [ inherit CE as x ]
when [ flag ] is { { ! . Fresh}[Fresh ] }
and [ s ] is [ Some x ] ,
- [ inherit ! CE ]
when [ flag ] is { { ! . Override}[Override ] }
and [ s ] is [ None ] ,
- [ inherit ! CE as x ]
when [ flag ] is { { ! . Override}[Override ] }
and [ s ] is [ Some x ]
- [inherit CE]
when [flag] is {{!Asttypes.override_flag.Fresh}[Fresh]}
and [s] is [None],
- [inherit CE as x]
when [flag] is {{!Asttypes.override_flag.Fresh}[Fresh]}
and [s] is [Some x],
- [inherit! CE]
when [flag] is {{!Asttypes.override_flag.Override}[Override]}
and [s] is [None],
- [inherit! CE as x]
when [flag] is {{!Asttypes.override_flag.Override}[Override]}
and [s] is [Some x]
*)
| Pcf_val of (label loc * mutable_flag * class_field_kind)
(** [Pcf_val(x,flag, kind)] represents:
- [val x = E]
when [flag] is {{!Asttypes.mutable_flag.Immutable}[Immutable]}
and [kind] is {{!class_field_kind.Cfk_concrete}[Cfk_concrete(Fresh, E)]}
- [val virtual x: T]
when [flag] is {{!Asttypes.mutable_flag.Immutable}[Immutable]}
and [kind] is {{!class_field_kind.Cfk_virtual}[Cfk_virtual(T)]}
- [val mutable x = E]
when [flag] is {{!Asttypes.mutable_flag.Mutable}[Mutable]}
and [kind] is {{!class_field_kind.Cfk_concrete}[Cfk_concrete(Fresh, E)]}
- [val mutable virtual x: T]
when [flag] is {{!Asttypes.mutable_flag.Mutable}[Mutable]}
and [kind] is {{!class_field_kind.Cfk_virtual}[Cfk_virtual(T)]}
*)
| Pcf_method of (label loc * private_flag * class_field_kind)
(** - [method x = E]
([E] can be a {{!expression_desc.Pexp_poly}[Pexp_poly]})
- [method virtual x: T]
([T] can be a {{!core_type_desc.Ptyp_poly}[Ptyp_poly]})
*)
| Pcf_constraint of (core_type * core_type) (** [constraint T1 = T2] *)
| Pcf_initializer of expression (** [initializer E] *)
| Pcf_attribute of attribute (** [[\@\@\@id]] *)
| Pcf_extension of extension (** [[%%id]] *)
and class_field_kind =
| Cfk_virtual of core_type
| Cfk_concrete of override_flag * expression
and class_declaration = class_expr class_infos
(** {1 Module language} *)
* { 2 Type expressions for the module language }
and module_type =
{
pmty_desc: module_type_desc;
pmty_loc: Location.t;
pmty_attributes: attributes; (** [... [\@id1] [\@id2]] *)
}
and module_type_desc =
| Pmty_ident of Longident.t loc (** [Pmty_ident(S)] represents [S] *)
| Pmty_signature of signature (** [sig ... end] *)
| Pmty_functor of functor_parameter * module_type
* [ functor(X : ) - > MT2 ]
| Pmty_with of module_type * with_constraint list (** [MT with ...] *)
| Pmty_typeof of module_expr (** [module type of ME] *)
| Pmty_extension of extension (** [[%id]] *)
| Pmty_alias of Longident.t loc (** [(module M)] *)
and functor_parameter =
| Unit (** [()] *)
| Named of string option loc * module_type
* [ Named(name , ) ] represents :
- [ ( X : MT ) ] when [ name ] is [ Some X ] ,
- [ ( _ : MT ) ] when [ name ] is [ None ]
- [(X : MT)] when [name] is [Some X],
- [(_ : MT)] when [name] is [None] *)
and signature = signature_item list
and signature_item =
{
psig_desc: signature_item_desc;
psig_loc: Location.t;
}
and signature_item_desc =
| Psig_value of value_description
(** - [val x: T]
- [external x: T = "s1" ... "sn"]
*)
| Psig_type of rec_flag * type_declaration list
* [ type t1 = ... and ... and = ... ]
| Psig_typesubst of type_declaration list
(** [type t1 := ... and ... and tn := ...] *)
| Psig_typext of type_extension (** [type t1 += ...] *)
| Psig_exception of type_exception (** [exception C of T] *)
| Psig_module of module_declaration (** [module X = M] and [module X : MT] *)
| Psig_modsubst of module_substitution (** [module X := M] *)
| Psig_recmodule of module_declaration list
* [ module rec X1 : and ... and Xn : MTn ]
| Psig_modtype of module_type_declaration
(** [module type S = MT] and [module type S] *)
| Psig_modtypesubst of module_type_declaration
(** [module type S := ...] *)
| Psig_open of open_description (** [open X] *)
| Psig_include of include_description (** [include MT] *)
| Psig_class of class_description list
(** [class c1 : ... and ... and cn : ...] *)
| Psig_class_type of class_type_declaration list
(** [class type ct1 = ... and ... and ctn = ...] *)
| Psig_attribute of attribute (** [[\@\@\@id]] *)
| Psig_extension of extension * attributes (** [[%%id]] *)
and module_declaration =
{
pmd_name: string option loc;
pmd_type: module_type;
* [ ... [ \@\@id1 ] [ \@\@id2 ] ]
pmd_loc: Location.t;
}
(** Values of type [module_declaration] represents [S : MT] *)
and module_substitution =
{
pms_name: string loc;
pms_manifest: Longident.t loc;
* [ ... [ \@\@id1 ] [ \@\@id2 ] ]
pms_loc: Location.t;
}
(** Values of type [module_substitution] represents [S := M] *)
and module_type_declaration =
{
pmtd_name: string loc;
pmtd_type: module_type option;
* [ ... [ \@\@id1 ] [ \@\@id2 ] ]
pmtd_loc: Location.t;
}
(** Values of type [module_type_declaration] represents:
- [S = MT],
- [S] for abstract module type declaration,
when {{!module_type_declaration.pmtd_type}[pmtd_type]} is [None].
*)
and 'a open_infos =
{
popen_expr: 'a;
popen_override: override_flag;
popen_loc: Location.t;
popen_attributes: attributes;
}
* Values of type [ ' a open_infos ] represents :
- [ open ! X ] when { { ! open_infos.popen_override}[popen_override ] }
is { { ! . Override}[Override ] }
( silences the " used identifier shadowing " warning )
- [ open X ] when { { ! open_infos.popen_override}[popen_override ] }
is { { ! . Fresh}[Fresh ] }
- [open! X] when {{!open_infos.popen_override}[popen_override]}
is {{!Asttypes.override_flag.Override}[Override]}
(silences the "used identifier shadowing" warning)
- [open X] when {{!open_infos.popen_override}[popen_override]}
is {{!Asttypes.override_flag.Fresh}[Fresh]}
*)
and open_description = Longident.t loc open_infos
(** Values of type [open_description] represents:
- [open M.N]
- [open M(N).O] *)
and open_declaration = module_expr open_infos
(** Values of type [open_declaration] represents:
- [open M.N]
- [open M(N).O]
- [open struct ... end] *)
and 'a include_infos =
{
pincl_mod: 'a;
pincl_loc: Location.t;
pincl_attributes: attributes;
}
and include_description = module_type include_infos
(** Values of type [include_description] represents [include MT] *)
and include_declaration = module_expr include_infos
(** Values of type [include_declaration] represents [include ME] *)
and with_constraint =
| Pwith_type of Longident.t loc * type_declaration
(** [with type X.t = ...]
Note: the last component of the longident must match
the name of the type_declaration. *)
| Pwith_module of Longident.t loc * Longident.t loc
(** [with module X.Y = Z] *)
| Pwith_modtype of Longident.t loc * module_type
(** [with module type X.Y = Z] *)
| Pwith_modtypesubst of Longident.t loc * module_type
(** [with module type X.Y := sig end] *)
| Pwith_typesubst of Longident.t loc * type_declaration
(** [with type X.t := ..., same format as [Pwith_type]] *)
| Pwith_modsubst of Longident.t loc * Longident.t loc
(** [with module X.Y := Z] *)
* { 2 Value expressions for the module language }
and module_expr =
{
pmod_desc: module_expr_desc;
pmod_loc: Location.t;
pmod_attributes: attributes; (** [... [\@id1] [\@id2]] *)
}
and module_expr_desc =
| Pmod_ident of Longident.t loc (** [X] *)
| Pmod_structure of structure (** [struct ... end] *)
| Pmod_functor of functor_parameter * module_expr
* [ functor(X : ) - > ME ]
* [ ) ]
| Pmod_constraint of module_expr * module_type (** [(ME : MT)] *)
| Pmod_unpack of expression (** [(val E)] *)
| Pmod_extension of extension (** [[%id]] *)
and structure = structure_item list
and structure_item =
{
pstr_desc: structure_item_desc;
pstr_loc: Location.t;
}
and structure_item_desc =
| Pstr_eval of expression * attributes (** [E] *)
| Pstr_value of rec_flag * value_binding list
* [ Pstr_value(rec , [ ( P1 , E1 ; ... ; ( Pn , En ) ) ] ) ] represents :
- [ let P1 = E1 and ... and Pn = EN ]
when [ rec ] is { { ! Asttypes.rec_flag . Nonrecursive}[Nonrecursive ] } ,
- [ let rec P1 = E1 and ... and Pn = EN ]
when [ rec ] is { { ! Asttypes.rec_flag . Recursive}[Recursive ] } .
- [let P1 = E1 and ... and Pn = EN]
when [rec] is {{!Asttypes.rec_flag.Nonrecursive}[Nonrecursive]},
- [let rec P1 = E1 and ... and Pn = EN ]
when [rec] is {{!Asttypes.rec_flag.Recursive}[Recursive]}.
*)
| Pstr_primitive of value_description
(** - [val x: T]
- [external x: T = "s1" ... "sn" ]*)
| Pstr_type of rec_flag * type_declaration list
(** [type t1 = ... and ... and tn = ...] *)
| Pstr_typext of type_extension (** [type t1 += ...] *)
| Pstr_exception of type_exception
(** - [exception C of T]
- [exception C = M.X] *)
| Pstr_module of module_binding (** [module X = ME] *)
| Pstr_recmodule of module_binding list
(** [module rec X1 = ME1 and ... and Xn = MEn] *)
| Pstr_modtype of module_type_declaration (** [module type S = MT] *)
| Pstr_open of open_declaration (** [open X] *)
| Pstr_class of class_declaration list
(** [class c1 = ... and ... and cn = ...] *)
| Pstr_class_type of class_type_declaration list
(** [class type ct1 = ... and ... and ctn = ...] *)
| Pstr_include of include_declaration (** [include ME] *)
| Pstr_attribute of attribute (** [[\@\@\@id]] *)
| Pstr_extension of extension * attributes (** [[%%id]] *)
and value_binding =
{
pvb_pat: pattern;
pvb_expr: expression;
pvb_attributes: attributes;
pvb_loc: Location.t;
}
and module_binding =
{
pmb_name: string option loc;
pmb_expr: module_expr;
pmb_attributes: attributes;
pmb_loc: Location.t;
}
(** Values of type [module_binding] represents [module X = ME] *)
* { 1 Toplevel }
* { 2 Toplevel phrases }
type toplevel_phrase =
| Ptop_def of structure
| Ptop_dir of toplevel_directive (** [#use], [#load] ... *)
and toplevel_directive =
{
pdir_name: string loc;
pdir_arg: directive_argument option;
pdir_loc: Location.t;
}
and directive_argument =
{
pdira_desc: directive_argument_desc;
pdira_loc: Location.t;
}
and directive_argument_desc =
| Pdir_string of string
| Pdir_int of string * char option
| Pdir_ident of Longident.t
| Pdir_bool of bool
| null | https://raw.githubusercontent.com/dyzsr/ocaml-selectml/42cccb99506f8f33dac87d3bdb65391269b31d05/parsing/parsetree.mli | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
* Abstract syntax tree produced by parsing
{b Warning:} this module is unstable and part of
{{!Compiler_libs}compiler-libs}.
* Character such as ['c'].
* Attributes such as [[\@id ARG]] and [[\@\@id ARG]].
Metadata containers passed around within the AST.
The compiler ignores unknown attributes.
* Extension points such as [[%id ARG] and [%%id ARG]].
Sub-language placeholder -- rejected by the typechecker.
* [: T] in an attribute or an extension point
* [? P] or [? P when E], in an attribute or an extension point
* [... [\@id1] [\@id2]]
* [_]
* A type variable such as ['a]
* [Ptyp_arrow(lbl, T1, T2)] represents:
- [T1 -> T2] when [lbl] is
{{!Asttypes.arg_label.Nolabel}[Nolabel]},
- [~l:T1 -> T2] when [lbl] is
{{!Asttypes.arg_label.Labelled}[Labelled]},
- [?l:T1 -> T2] when [lbl] is
{{!Asttypes.arg_label.Optional}[Optional]}.
* [Ptyp_constr(lident, l)] represents:
- [tconstr] when [l=[]],
- [T tconstr] when [l=[T]],
- [(T1, ..., Tn) tconstr] when [l=[T1 ; ... ; Tn]].
* [Ptyp_object([ l1:T1; ...; ln:Tn ], flag)] represents:
- [< l1:T1; ...; ln:Tn >] when [flag] is
{{!Asttypes.closed_flag.Closed}[Closed]},
- [< l1:T1; ...; ln:Tn; .. >] when [flag] is
{{!Asttypes.closed_flag.Open}[Open]}.
* [Ptyp_class(tconstr, l)] represents:
- [#tconstr] when [l=[]],
- [T #tconstr] when [l=[T]],
- [(T1, ..., Tn) #tconstr] when [l=[T1 ; ... ; Tn]].
* [T as 'a].
* [Ptyp_variant([`A;`B], flag, labels)] represents:
- [[ `A|`B ]]
when [flag] is {{!Asttypes.closed_flag.Closed}[Closed]},
and [labels] is [None],
- [[> `A|`B ]]
when [flag] is {{!Asttypes.closed_flag.Open}[Open]},
and [labels] is [None],
- [[< `A|`B ]]
when [flag] is {{!Asttypes.closed_flag.Closed}[Closed]},
and [labels] is [Some []],
- [[< `A|`B > `X `Y ]]
when [flag] is {{!Asttypes.closed_flag.Closed}[Closed]},
and [labels] is [Some ["X";"Y"]].
* [(module S)].
* [[%id]].
* [[ | t ]]
* {2 Patterns}
* [... [\@id1] [\@id2]]
* The pattern [_].
* A variable pattern such as [x]
* An alias pattern such as [P as 'a]
* Patterns such as ['a'..'z'].
Other forms of interval are recognized by the parser
but rejected by the type-checker.
* [Ppat_construct(C, args)] represents:
- [C] when [args] is [None],
- [C P] when [args] is [Some ([], P)]
- [C (P1, ..., Pn)] when [args] is
[Some ([], Ppat_tuple [P1; ...; Pn])]
- [C (type a b) P] when [args] is [Some ([a; b], P)]
* [Ppat_variant(`A, pat)] represents:
- [`A] when [pat] is [None],
- [`A P] when [pat] is [Some P]
* Pattern [[| P1; ...; Pn |]]
* Pattern [P1 | P2]
* Pattern [(P : T)]
* Pattern [#tconst]
* Pattern [lazy P]
* [Ppat_unpack(s)] represents:
- [(module P)] when [s] is [Some "P"]
- [(module _)] when [s] is [None]
Note: [(module P : S)] is represented as
[Ppat_constraint(Ppat_unpack(Some "P"), Ptyp_package S)]
* Pattern [exception P]
* Pattern [[%id]]
* Pattern [M.(P)]
* [... [\@id1] [\@id2]]
* [Pexp_let(flag, [(P1,E1) ; ... ; (Pn,En)], E)] represents:
- [let P1 = E1 and ... and Pn = EN in E]
when [flag] is {{!Asttypes.rec_flag.Nonrecursive}[Nonrecursive]},
- [let rec P1 = E1 and ... and Pn = EN in E]
when [flag] is {{!Asttypes.rec_flag.Recursive}[Recursive]}.
* [function P1 -> E1 | ... | Pn -> En]
* [Pexp_apply(E0, [(l1, E1) ; ... ; (ln, En)])]
represents [E0 ~l1:E1 ... ~ln:En]
[li] can be
{{!Asttypes.arg_label.Nolabel}[Nolabel]} (non labeled argument),
{{!Asttypes.arg_label.Labelled}[Labelled]} (labelled arguments) or
{{!Asttypes.arg_label.Optional}[Optional]} (optional argument).
Invariant: [n > 0]
* [Pexp_construct(C, exp)] represents:
- [C] when [exp] is [None],
- [C E] when [exp] is [Some E],
- [C (E1, ..., En)] when [exp] is [Some (Pexp_tuple[E1;...;En])]
* [E.l]
* [E1.l <- E2]
* [[| E1; ...; En |]]
* [if E1 then E2 else E3]
* [E1; E2]
* [while E1 do E2 done]
* [(E : T)]
* [E # m]
* [new M.c]
* [x <- 2]
* [{< x1 = E1; ...; xn = En >}]
* [let module M = ME in E]
* [let exception C in E]
* [assert E].
Note: [assert false] is treated in a special way by the
type-checker.
* [lazy E]
* Used for method bodies.
Can only be used as the expression under
{{!class_field_kind.Cfk_concrete}[Cfk_concrete]} for methods (not
values).
* [object ... end]
* [fun (type t) -> E]
* [(module ME)].
[(module ME : S)] is represented as
[Pexp_constraint(Pexp_pack ME, Ptyp_package S)]
* - [M.(E)]
- [let open M in E]
- [let open! M in E]
* - [let* P = E0 in E1]
- [let* P0 = E00 and* P1 = E01 in E1]
* [[%id]]
* [.]
SELECT ... FROM ... WHERE ...
GROUP BY ... HAVING ... ORDER BY ...
SELECT {count (x, y)} ...
SELECT x, {sum y}, {avg z} ...
SELECT ... HAVING {count x} > 0 ...
SELECT ... ORDER BY {count x}
Invariant: usage outside SELECT context is not allowed
* Values of type {!case} represents [(P -> E)] or [(P when E0 -> E)]
* Values of type {!value_description} represents:
- [val x: T],
when {{!value_description.pval_prim}[pval_prim]} is [[]]
- [external x: T = "s1" ... "sn"]
when {{!value_description.pval_prim}[pval_prim]} is [["s1";..."sn"]]
* [('a1,...'an) t]
* for [= private ...]
* represents [= T]
* Invariant: non-empty list
* [l : T [\@id1] [\@id2]]
*
- [{ ...; l: T; ... }]
when {{!label_declaration.pld_mutable}[pld_mutable]}
is {{!Asttypes.mutable_flag.Immutable}[Immutable]},
- [{ ...; mutable l: T; ... }]
when {{!label_declaration.pld_mutable}[pld_mutable]}
is {{!Asttypes.mutable_flag.Mutable}[Mutable]}.
Note: [T] can be a {{!core_type_desc.Ptyp_poly}[Ptyp_poly]}.
* [C of ... [\@id1] [\@id2]]
* Values of type {!constructor_declaration}
represents the constructor arguments of:
- [C of T1 * ... * Tn] when [res = None],
and [args = Pcstr_tuple [T1; ... ; Tn]],
- [C: T0] when [res = Some T0],
and [args = Pcstr_tuple []],
- [C: T1 * ... * Tn -> T0] when [res = Some T0],
and [args = Pcstr_tuple [T1; ... ; Tn]],
- [C of {...}] when [res = None],
and [args = Pcstr_record [...]],
- [C: {...} -> T0] when [res = Some T0],
and [args = Pcstr_record [...]].
*
Definition of new extensions constructors for the extensive sum type [t]
([type t += ...]).
* [C of ... [\@id1] [\@id2]]
* Definition of a new exception ([exception E]).
* [Pext_rebind(D)] re-export the constructor [D] with the new name [C]
* {1 Class language}
* [... [\@id1] [\@id2]]
* - [c]
- [['a1, ..., 'an] c]
* [object ... end]
* [Pcty_arrow(lbl, T, CT)] represents:
- [T -> CT]
when [lbl] is {{!Asttypes.arg_label.Nolabel}[Nolabel]},
- [~l:T -> CT]
when [lbl] is {{!Asttypes.arg_label.Labelled}[Labelled l]},
- [?l:T -> CT]
when [lbl] is {{!Asttypes.arg_label.Optional}[Optional l]}.
* [%id]
* [let open M in CT]
* Values of type [class_signature] represents:
- [object('selfpat) ... end]
- [object ... end] when {{!class_signature.pcsig_self}[pcsig_self]}
is {{!core_type_desc.Ptyp_any}[Ptyp_any]}
* [inherit CT]
* [method x: T]
Note: [T] can be a {{!core_type_desc.Ptyp_poly}[Ptyp_poly]}.
* [constraint T1 = T2]
* [[\@\@\@id]]
* [[%%id]]
* Values of type [class_expr class_infos] represents:
- [class c = ...]
- [class ['a1,...,'an] c = ...]
- [class virtual c = ...]
They are also used for "class type" declaration.
* [... [\@id1] [\@id2]]
* [c] and [['a1, ..., 'an] c]
* [object ... end]
* [Pcl_let(rec, [(P1, E1); ... ; (Pn, En)], CE)] represents:
- [let P1 = E1 and ... and Pn = EN in CE]
when [rec] is {{!Asttypes.rec_flag.Nonrecursive}[Nonrecursive]},
- [let rec P1 = E1 and ... and Pn = EN in CE]
when [rec] is {{!Asttypes.rec_flag.Recursive}[Recursive]}.
* [(CE : CT)]
* [[%id]]
* [let open M in CE]
* Values of type {!class_structure} represents:
- [object(selfpat) ... end]
- [object ... end] when {{!class_structure.pcstr_self}[pcstr_self]}
is {{!pattern_desc.Ppat_any}[Ppat_any]}
* [Pcf_val(x,flag, kind)] represents:
- [val x = E]
when [flag] is {{!Asttypes.mutable_flag.Immutable}[Immutable]}
and [kind] is {{!class_field_kind.Cfk_concrete}[Cfk_concrete(Fresh, E)]}
- [val virtual x: T]
when [flag] is {{!Asttypes.mutable_flag.Immutable}[Immutable]}
and [kind] is {{!class_field_kind.Cfk_virtual}[Cfk_virtual(T)]}
- [val mutable x = E]
when [flag] is {{!Asttypes.mutable_flag.Mutable}[Mutable]}
and [kind] is {{!class_field_kind.Cfk_concrete}[Cfk_concrete(Fresh, E)]}
- [val mutable virtual x: T]
when [flag] is {{!Asttypes.mutable_flag.Mutable}[Mutable]}
and [kind] is {{!class_field_kind.Cfk_virtual}[Cfk_virtual(T)]}
* - [method x = E]
([E] can be a {{!expression_desc.Pexp_poly}[Pexp_poly]})
- [method virtual x: T]
([T] can be a {{!core_type_desc.Ptyp_poly}[Ptyp_poly]})
* [constraint T1 = T2]
* [initializer E]
* [[\@\@\@id]]
* [[%%id]]
* {1 Module language}
* [... [\@id1] [\@id2]]
* [Pmty_ident(S)] represents [S]
* [sig ... end]
* [MT with ...]
* [module type of ME]
* [[%id]]
* [(module M)]
* [()]
* - [val x: T]
- [external x: T = "s1" ... "sn"]
* [type t1 := ... and ... and tn := ...]
* [type t1 += ...]
* [exception C of T]
* [module X = M] and [module X : MT]
* [module X := M]
* [module type S = MT] and [module type S]
* [module type S := ...]
* [open X]
* [include MT]
* [class c1 : ... and ... and cn : ...]
* [class type ct1 = ... and ... and ctn = ...]
* [[\@\@\@id]]
* [[%%id]]
* Values of type [module_declaration] represents [S : MT]
* Values of type [module_substitution] represents [S := M]
* Values of type [module_type_declaration] represents:
- [S = MT],
- [S] for abstract module type declaration,
when {{!module_type_declaration.pmtd_type}[pmtd_type]} is [None].
* Values of type [open_description] represents:
- [open M.N]
- [open M(N).O]
* Values of type [open_declaration] represents:
- [open M.N]
- [open M(N).O]
- [open struct ... end]
* Values of type [include_description] represents [include MT]
* Values of type [include_declaration] represents [include ME]
* [with type X.t = ...]
Note: the last component of the longident must match
the name of the type_declaration.
* [with module X.Y = Z]
* [with module type X.Y = Z]
* [with module type X.Y := sig end]
* [with type X.t := ..., same format as [Pwith_type]]
* [with module X.Y := Z]
* [... [\@id1] [\@id2]]
* [X]
* [struct ... end]
* [(ME : MT)]
* [(val E)]
* [[%id]]
* [E]
* - [val x: T]
- [external x: T = "s1" ... "sn" ]
* [type t1 = ... and ... and tn = ...]
* [type t1 += ...]
* - [exception C of T]
- [exception C = M.X]
* [module X = ME]
* [module rec X1 = ME1 and ... and Xn = MEn]
* [module type S = MT]
* [open X]
* [class c1 = ... and ... and cn = ...]
* [class type ct1 = ... and ... and ctn = ...]
* [include ME]
* [[\@\@\@id]]
* [[%%id]]
* Values of type [module_binding] represents [module X = ME]
* [#use], [#load] ... | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Asttypes
type constant =
| Pconst_integer of string * char option
* Integer constants such as [ 3 ] [ 3l ] [ 3L ] [ 3n ] .
Suffixes [ [ g - z][G - Z ] ] are accepted by the parser .
Suffixes except [ ' l ' ] , [ ' L ' ] and [ ' n ' ] are rejected by the typechecker
Suffixes [[g-z][G-Z]] are accepted by the parser.
Suffixes except ['l'], ['L'] and ['n'] are rejected by the typechecker
*)
| Pconst_string of string * Location.t * string option
* Constant string such as [ " constant " ] or
[ { } ] .
The location span the content of the string , without the delimiters .
[{delim|other constant|delim}].
The location span the content of the string, without the delimiters.
*)
| Pconst_float of string * char option
* Float constant such as [ 3.4 ] , [ 2e5 ] or [ 1.4e-4 ] .
Suffixes [ g - z][G - Z ] are accepted by the parser .
Suffixes are rejected by the typechecker .
Suffixes [g-z][G-Z] are accepted by the parser.
Suffixes are rejected by the typechecker.
*)
type location_stack = Location.t list
* { 1 Extension points }
type attribute = {
attr_name : string loc;
attr_payload : payload;
attr_loc : Location.t;
}
and extension = string loc * payload
and attributes = attribute list
and payload =
| PStr of structure
* [: SIG ] in an attribute or an extension point
| PPat of pattern * expression option
* { 1 Core language }
* { 2 Type expressions }
and core_type =
{
ptyp_desc: core_type_desc;
ptyp_loc: Location.t;
ptyp_loc_stack: location_stack;
}
and core_type_desc =
| Ptyp_arrow of arg_label * core_type * core_type
| Ptyp_tuple of core_type list
* [ Ptyp_tuple([T1 ; ... ; Tn ] ) ]
represents a product type [ T1 * ... * Tn ] .
Invariant : [ n > = 2 ] .
represents a product type [T1 * ... * Tn].
Invariant: [n >= 2].
*)
| Ptyp_constr of Longident.t loc * core_type list
| Ptyp_object of object_field list * closed_flag
| Ptyp_class of Longident.t loc * core_type list
| Ptyp_variant of row_field list * closed_flag * label list option
| Ptyp_poly of string loc list * core_type
* [ ' a1 ... ' an . T ]
Can only appear in the following context :
- As the { ! core_type } of a
{ { ! pattern_desc . Ppat_constraint}[Ppat_constraint ] } node corresponding
to a constraint on a let - binding :
{ [ let x : ' a1 ... ' an . T = e ... ] }
- Under { { ! class_field_kind . Cfk_virtual}[Cfk_virtual ] } for methods
( not values ) .
- As the { ! core_type } of a
{ { ! class_type_field_desc . ] } node .
- As the { ! core_type } of a { { ! expression_desc . Pexp_poly}[Pexp_poly ] }
node .
- As the { { ! label_declaration.pld_type}[pld_type ] } field of a
{ ! label_declaration } .
- As a { ! core_type } of a { { ! core_type_desc . Ptyp_object}[Ptyp_object ] }
node .
- As the { { ! value_description.pval_type}[pval_type ] } field of a
{ ! value_description } .
Can only appear in the following context:
- As the {!core_type} of a
{{!pattern_desc.Ppat_constraint}[Ppat_constraint]} node corresponding
to a constraint on a let-binding:
{[let x : 'a1 ... 'an. T = e ...]}
- Under {{!class_field_kind.Cfk_virtual}[Cfk_virtual]} for methods
(not values).
- As the {!core_type} of a
{{!class_type_field_desc.Pctf_method}[Pctf_method]} node.
- As the {!core_type} of a {{!expression_desc.Pexp_poly}[Pexp_poly]}
node.
- As the {{!label_declaration.pld_type}[pld_type]} field of a
{!label_declaration}.
- As a {!core_type} of a {{!core_type_desc.Ptyp_object}[Ptyp_object]}
node.
- As the {{!value_description.pval_type}[pval_type]} field of a
{!value_description}.
*)
and package_type = Longident.t loc * (Longident.t loc * core_type) list
* As { ! package_type } typed values :
- [ ( S , [ ] ) ] represents [ ( module S ) ] ,
- [ ( S , [ ( t1 , T1 ) ; ... ; ( tn , Tn ) ] ) ]
represents [ ( module S with type t1 = T1 and ... and tn = Tn ) ] .
- [(S, [])] represents [(module S)],
- [(S, [(t1, T1) ; ... ; (tn, Tn)])]
represents [(module S with type t1 = T1 and ... and tn = Tn)].
*)
and row_field = {
prf_desc : row_field_desc;
prf_loc : Location.t;
prf_attributes : attributes;
}
and row_field_desc =
| Rtag of label loc * bool * core_type list
* [ , b , l ) ] represents :
- [ ` A ] when [ b ] is [ true ] and [ l ] is [ [ ] ] ,
- [ ` A of T ] when [ b ] is [ false ] and [ l ] is [ [ T ] ] ,
- [ ` A of T1 & .. & Tn ] when [ b ] is [ false ] and [ l ] is [ [ T1; ... Tn ] ] ,
- [ ` A of & T1 & .. & Tn ] when [ b ] is [ true ] and [ l ] is [ [ T1; ... Tn ] ] .
- The [ bool ] field is true if the tag contains a
constant ( empty ) constructor .
- [ & ] occurs when several types are used for the same constructor
( see 4.2 in the manual )
- [`A] when [b] is [true] and [l] is [[]],
- [`A of T] when [b] is [false] and [l] is [[T]],
- [`A of T1 & .. & Tn] when [b] is [false] and [l] is [[T1;...Tn]],
- [`A of & T1 & .. & Tn] when [b] is [true] and [l] is [[T1;...Tn]].
- The [bool] field is true if the tag contains a
constant (empty) constructor.
- [&] occurs when several types are used for the same constructor
(see 4.2 in the manual)
*)
and object_field = {
pof_desc : object_field_desc;
pof_loc : Location.t;
pof_attributes : attributes;
}
and object_field_desc =
| Otag of label loc * core_type
| Oinherit of core_type
and pattern =
{
ppat_desc: pattern_desc;
ppat_loc: Location.t;
ppat_loc_stack: location_stack;
}
and pattern_desc =
| Ppat_alias of pattern * string loc
| Ppat_constant of constant
* Patterns such as [ 1 ] , [ ' a ' ] , [ " true " ] , [ 1.0 ] , [ 1l ] , [ 1L ] , [ 1n ]
| Ppat_interval of constant * constant
| Ppat_tuple of pattern list
* Patterns [ ( P1 , ... , Pn ) ] .
Invariant : [ n > = 2 ]
Invariant: [n >= 2]
*)
| Ppat_construct of Longident.t loc * (string loc list * pattern) option
| Ppat_variant of label * pattern option
| Ppat_record of (Longident.t loc * pattern) list * closed_flag
* [ Ppat_record([(l1 , P1 ) ; ... ; ( ln , Pn ) ] , flag ) ] represents :
- [ { l1 = P1 ; ... ; ln = Pn } ]
when [ flag ] is { { ! Asttypes.closed_flag . Closed}[Closed ] }
- [ { l1 = P1 ; ... ; ln = Pn ; _ } ]
when [ flag ] is { { ! Asttypes.closed_flag . Open}[Open ] }
Invariant : [ n > 0 ]
- [{ l1=P1; ...; ln=Pn }]
when [flag] is {{!Asttypes.closed_flag.Closed}[Closed]}
- [{ l1=P1; ...; ln=Pn; _}]
when [flag] is {{!Asttypes.closed_flag.Open}[Open]}
Invariant: [n > 0]
*)
| Ppat_unpack of string option loc
* { 2 Value expressions }
and expression =
{
pexp_desc: expression_desc;
pexp_loc: Location.t;
pexp_loc_stack: location_stack;
}
and expression_desc =
| Pexp_ident of Longident.t loc
* Identifiers such as [ x ] and [ ]
*)
| Pexp_constant of constant
* Expressions constant such as [ 1 ] , [ ' a ' ] , [ " true " ] , [ 1.0 ] , [ 1l ] ,
[ 1L ] , [ 1n ]
[1L], [1n] *)
| Pexp_let of rec_flag * value_binding list * expression
| Pexp_fun of arg_label * expression option * pattern * expression
* [ Pexp_fun(lbl , exp0 , P , E1 ) ] represents :
- [ fun P - > E1 ]
when [ lbl ] is { { ! Asttypes.arg_label . Nolabel}[Nolabel ] }
and [ exp0 ] is [ None ]
- [ fun ~l :P - > E1 ]
when [ lbl ] is { { ! Asttypes.arg_label . Labelled}[Labelled l ] }
and [ exp0 ] is [ None ]
- [ fun ? l :P - > E1 ]
when [ lbl ] is { { ! Asttypes.arg_label . Optional}[Optional l ] }
and [ exp0 ] is [ None ]
- [ fun ? l:(P = E0 ) - > E1 ]
when [ lbl ] is { { ! Asttypes.arg_label . Optional}[Optional l ] }
and [ exp0 ] is [ Some E0 ]
Notes :
- If [ E0 ] is provided , only
{ { ! Asttypes.arg_label . Optional}[Optional ] } is allowed .
- [ fun P1 P2 .. Pn - > E1 ] is represented as nested
{ { ! expression_desc . Pexp_fun}[Pexp_fun ] } .
- [ let f P = E ] is represented using
{ { ! expression_desc . Pexp_fun}[Pexp_fun ] } .
- [fun P -> E1]
when [lbl] is {{!Asttypes.arg_label.Nolabel}[Nolabel]}
and [exp0] is [None]
- [fun ~l:P -> E1]
when [lbl] is {{!Asttypes.arg_label.Labelled}[Labelled l]}
and [exp0] is [None]
- [fun ?l:P -> E1]
when [lbl] is {{!Asttypes.arg_label.Optional}[Optional l]}
and [exp0] is [None]
- [fun ?l:(P = E0) -> E1]
when [lbl] is {{!Asttypes.arg_label.Optional}[Optional l]}
and [exp0] is [Some E0]
Notes:
- If [E0] is provided, only
{{!Asttypes.arg_label.Optional}[Optional]} is allowed.
- [fun P1 P2 .. Pn -> E1] is represented as nested
{{!expression_desc.Pexp_fun}[Pexp_fun]}.
- [let f P = E] is represented using
{{!expression_desc.Pexp_fun}[Pexp_fun]}.
*)
| Pexp_apply of expression * (arg_label * expression) list
| Pexp_match of expression * case list
* [ match E0 with P1 - > E1 | ... | Pn - > En ]
| Pexp_try of expression * case list
* [ try E0 with P1 - > E1 | ... | Pn - > En ]
| Pexp_tuple of expression list
* Expressions [ ( E1 , ... , En ) ]
Invariant : [ n > = 2 ]
Invariant: [n >= 2]
*)
| Pexp_construct of Longident.t loc * expression option
| Pexp_variant of label * expression option
* [ Pexp_variant(`A , exp ) ] represents
- [ ` A ] when [ exp ] is [ None ]
- [ ` A E ] when [ exp ] is [ Some E ]
- [`A] when [exp] is [None]
- [`A E] when [exp] is [Some E]
*)
| Pexp_record of (Longident.t loc * expression) list * expression option
* [ Pexp_record([(l1,P1 ) ; ... ; ( ln , Pn ) ] , exp0 ) ] represents
- [ { l1 = P1 ; ... ; ln = Pn } ] when [ exp0 ] is [ None ]
- [ { E0 with l1 = P1 ; ... ; ln = Pn } ] when [ exp0 ] is [ Some E0 ]
Invariant : [ n > 0 ]
- [{ l1=P1; ...; ln=Pn }] when [exp0] is [None]
- [{ E0 with l1=P1; ...; ln=Pn }] when [exp0] is [Some E0]
Invariant: [n > 0]
*)
| Pexp_setfield of expression * Longident.t loc * expression
| Pexp_ifthenelse of expression * expression * expression option
| Pexp_for of pattern * expression * expression * direction_flag * expression
* [ Pexp_for(i , E1 , E2 , direction , E3 ) ] represents :
- [ for i = E1 to E2 do E3 done ]
when [ direction ] is { { ! Asttypes.direction_flag . Upto}[Upto ] }
- [ for i = E1 downto E2 do E3 done ]
when [ direction ] is { { ! Asttypes.direction_flag . Downto}[Downto ] }
- [for i = E1 to E2 do E3 done]
when [direction] is {{!Asttypes.direction_flag.Upto}[Upto]}
- [for i = E1 downto E2 do E3 done]
when [direction] is {{!Asttypes.direction_flag.Downto}[Downto]}
*)
| Pexp_coerce of expression * core_type option * core_type
* [ , from , T ) ] represents
- [ ( E :> T ) ] when [ from ] is [ None ] ,
- [ ( E : T0 :> T ) ] when [ from ] is [ Some T0 ] .
- [(E :> T)] when [from] is [None],
- [(E : T0 :> T)] when [from] is [Some T0].
*)
| Pexp_override of (label loc * expression) list
| Pexp_letmodule of string option loc * module_expr * expression
| Pexp_letexception of extension_constructor * expression
| Pexp_assert of expression
| Pexp_poly of expression * core_type option
| Pexp_pack of module_expr
| Pexp_open of open_declaration * expression
| Pexp_letop of letop
| Pexp_select of select_expr
| Pexp_aggregate of expression * expression
and select_expr =
{
se_select : expression;
se_distinct : bool loc;
se_from : source_expr option;
se_where : expression option;
se_groupby : expression option;
se_having : expression option;
se_orderby : (expression * order_direction) list;
se_orderby_loc : Location.t
}
and source_expr =
{
psrc_desc : source_expr_desc;
psrc_loc : Location.t
}
and source_expr_desc =
| Psrc_exp of expression * string loc list
| Psrc_product of source_expr * source_expr
| Psrc_join of source_expr * source_expr * expression
and order_direction =
| PAscending
| PDescending
| PUsing of expression
and case =
{
pc_lhs: pattern;
pc_guard: expression option;
pc_rhs: expression;
}
and letop =
{
let_ : binding_op;
ands : binding_op list;
body : expression;
}
and binding_op =
{
pbop_op : string loc;
pbop_pat : pattern;
pbop_exp : expression;
pbop_loc : Location.t;
}
* { 2 Value descriptions }
and value_description =
{
pval_name: string loc;
pval_type: core_type;
pval_prim: string list;
* [ ... [ \@\@id1 ] [ \@\@id2 ] ]
pval_loc: Location.t;
}
* { 2 Type declarations }
and type_declaration =
{
ptype_name: string loc;
ptype_params: (core_type * (variance * injectivity)) list;
ptype_cstrs: (core_type * core_type * Location.t) list;
* [ ... constraint T1 = T1 ' ... constraint ]
ptype_kind: type_kind;
* [ ... [ \@\@id1 ] [ \@\@id2 ] ]
ptype_loc: Location.t;
}
*
Here are type declarations and their representation ,
for various { { ! type_declaration.ptype_kind}[ptype_kind ] }
and { { ! ] } values :
- [ type t ] when [ type_kind ] is { { ! type_kind . Ptype_abstract}[Ptype_abstract ] } ,
and [ manifest ] is [ None ] ,
- [ type t = T0 ]
when [ type_kind ] is { { ! type_kind . Ptype_abstract}[Ptype_abstract ] } ,
and [ manifest ] is [ Some T0 ] ,
- [ type t = C of T | ... ]
when [ type_kind ] is { { ! type_kind . Ptype_variant}[Ptype_variant ] } ,
and [ manifest ] is [ None ] ,
- [ type t = T0 = C of T | ... ]
when [ type_kind ] is { { ! type_kind . Ptype_variant}[Ptype_variant ] } ,
and [ manifest ] is [ Some T0 ] ,
- [ type t = { l : T ; ... } ]
when [ type_kind ] is { { ! type_kind . Ptype_record}[Ptype_record ] } ,
and [ manifest ] is [ None ] ,
- [ type t = T0 = { l : T ; ... } ]
when [ type_kind ] is { { ! type_kind . Ptype_record}[Ptype_record ] } ,
and [ manifest ] is [ Some T0 ] ,
- [ type t = .. ]
when [ type_kind ] is { { ! type_kind . Ptype_open}[Ptype_open ] } ,
and [ manifest ] is [ None ] .
Here are type declarations and their representation,
for various {{!type_declaration.ptype_kind}[ptype_kind]}
and {{!type_declaration.ptype_manifest}[ptype_manifest]} values:
- [type t] when [type_kind] is {{!type_kind.Ptype_abstract}[Ptype_abstract]},
and [manifest] is [None],
- [type t = T0]
when [type_kind] is {{!type_kind.Ptype_abstract}[Ptype_abstract]},
and [manifest] is [Some T0],
- [type t = C of T | ...]
when [type_kind] is {{!type_kind.Ptype_variant}[Ptype_variant]},
and [manifest] is [None],
- [type t = T0 = C of T | ...]
when [type_kind] is {{!type_kind.Ptype_variant}[Ptype_variant]},
and [manifest] is [Some T0],
- [type t = {l: T; ...}]
when [type_kind] is {{!type_kind.Ptype_record}[Ptype_record]},
and [manifest] is [None],
- [type t = T0 = {l : T; ...}]
when [type_kind] is {{!type_kind.Ptype_record}[Ptype_record]},
and [manifest] is [Some T0],
- [type t = ..]
when [type_kind] is {{!type_kind.Ptype_open}[Ptype_open]},
and [manifest] is [None].
*)
and type_kind =
| Ptype_abstract
| Ptype_variant of constructor_declaration list
| Ptype_open
and label_declaration =
{
pld_name: string loc;
pld_mutable: mutable_flag;
pld_type: core_type;
pld_loc: Location.t;
}
and constructor_declaration =
{
pcd_name: string loc;
pcd_vars: string loc list;
pcd_args: constructor_arguments;
pcd_res: core_type option;
pcd_loc: Location.t;
}
and constructor_arguments =
| Pcstr_tuple of core_type list
| Pcstr_record of label_declaration list
and type_extension =
{
ptyext_path: Longident.t loc;
ptyext_params: (core_type * (variance * injectivity)) list;
ptyext_constructors: extension_constructor list;
ptyext_private: private_flag;
ptyext_loc: Location.t;
* ... [ \@\@id1 ] [ \@\@id2 ]
}
and extension_constructor =
{
pext_name: string loc;
pext_kind: extension_constructor_kind;
pext_loc: Location.t;
}
and type_exception =
{
ptyexn_constructor : extension_constructor;
ptyexn_loc : Location.t;
* [ ... [ \@\@id1 ] [ \@\@id2 ] ]
}
and extension_constructor_kind =
| Pext_decl of string loc list * constructor_arguments * core_type option
* [ Pext_decl(existentials , , t_opt ) ]
describes a new extension constructor . It can be :
- [ C of T1 * ... * Tn ] when :
{ ul { - [ existentials ] is [ [ ] ] , }
{ - [ c_args ] is [ [ T1 ; ... ; Tn ] ] , }
{ - [ t_opt ] is [ None ] } . }
- [ C : T0 ] when
{ ul { - [ existentials ] is [ [ ] ] , }
{ - [ c_args ] is [ [ ] ] , }
{ - [ t_opt ] is [ Some T0 ] . } }
- [ C : T1 * ... * Tn - > T0 ] when
{ ul { - [ existentials ] is [ [ ] ] , }
{ - [ c_args ] is [ [ T1 ; ... ; Tn ] ] , }
{ - [ t_opt ] is [ Some T0 ] . } }
- [ C : ' a ... . T1 * ... * Tn - > T0 ] when
{ ul { - [ existentials ] is [ [ ' a ; ... ] ] , }
{ - [ c_args ] is [ [ T1 ; ... ; Tn ] ] , }
{ - [ t_opt ] is [ Some T0 ] . } }
describes a new extension constructor. It can be:
- [C of T1 * ... * Tn] when:
{ul {- [existentials] is [[]],}
{- [c_args] is [[T1; ...; Tn]],}
{- [t_opt] is [None]}.}
- [C: T0] when
{ul {- [existentials] is [[]],}
{- [c_args] is [[]],}
{- [t_opt] is [Some T0].}}
- [C: T1 * ... * Tn -> T0] when
{ul {- [existentials] is [[]],}
{- [c_args] is [[T1; ...; Tn]],}
{- [t_opt] is [Some T0].}}
- [C: 'a... . T1 * ... * Tn -> T0] when
{ul {- [existentials] is [['a;...]],}
{- [c_args] is [[T1; ... ; Tn]],}
{- [t_opt] is [Some T0].}}
*)
| Pext_rebind of Longident.t loc
* { 2 Type expressions for the class language }
and class_type =
{
pcty_desc: class_type_desc;
pcty_loc: Location.t;
}
and class_type_desc =
| Pcty_constr of Longident.t loc * core_type list
| Pcty_arrow of arg_label * core_type * class_type
and class_signature =
{
pcsig_self: core_type;
pcsig_fields: class_type_field list;
}
and class_type_field =
{
pctf_desc: class_type_field_desc;
pctf_loc: Location.t;
* [ ... [ \@\@id1 ] [ \@\@id2 ] ]
}
and class_type_field_desc =
| Pctf_val of (label loc * mutable_flag * virtual_flag * core_type)
* [ x : T ]
| Pctf_method of (label loc * private_flag * virtual_flag * core_type)
and 'a class_infos =
{
pci_virt: virtual_flag;
pci_params: (core_type * (variance * injectivity)) list;
pci_name: string loc;
pci_expr: 'a;
pci_loc: Location.t;
* [ ... [ \@\@id1 ] [ \@\@id2 ] ]
}
and class_description = class_type class_infos
and class_type_declaration = class_type class_infos
* { 2 Value expressions for the class language }
and class_expr =
{
pcl_desc: class_expr_desc;
pcl_loc: Location.t;
}
and class_expr_desc =
| Pcl_constr of Longident.t loc * core_type list
| Pcl_fun of arg_label * expression option * pattern * class_expr
* [ Pcl_fun(lbl , exp0 , P , CE ) ] represents :
- [ fun P - > CE ]
when [ lbl ] is { { ! Asttypes.arg_label . Nolabel}[Nolabel ] }
and [ exp0 ] is [ None ] ,
- [ fun ~l :P - > CE ]
when [ lbl ] is { { ! Asttypes.arg_label . Labelled}[Labelled l ] }
and [ exp0 ] is [ None ] ,
- [ fun ? l :P - > CE ]
when [ lbl ] is { { ! Asttypes.arg_label . Optional}[Optional l ] }
and [ exp0 ] is [ None ] ,
- [ fun ? l:(P = E0 ) - > CE ]
when [ lbl ] is { { ! Asttypes.arg_label . Optional}[Optional l ] }
and [ exp0 ] is [ Some E0 ] .
- [fun P -> CE]
when [lbl] is {{!Asttypes.arg_label.Nolabel}[Nolabel]}
and [exp0] is [None],
- [fun ~l:P -> CE]
when [lbl] is {{!Asttypes.arg_label.Labelled}[Labelled l]}
and [exp0] is [None],
- [fun ?l:P -> CE]
when [lbl] is {{!Asttypes.arg_label.Optional}[Optional l]}
and [exp0] is [None],
- [fun ?l:(P = E0) -> CE]
when [lbl] is {{!Asttypes.arg_label.Optional}[Optional l]}
and [exp0] is [Some E0].
*)
| Pcl_apply of class_expr * (arg_label * expression) list
* [ Pcl_apply(CE , [ ( ) ; ... ; ( ln , En ) ] ) ]
represents [ CE ~l1 : E1 ... ~ln : En ] .
[ li ] can be empty ( non labeled argument ) or start with [ ? ]
( optional argument ) .
Invariant : [ n > 0 ]
represents [CE ~l1:E1 ... ~ln:En].
[li] can be empty (non labeled argument) or start with [?]
(optional argument).
Invariant: [n > 0]
*)
| Pcl_let of rec_flag * value_binding list * class_expr
and class_structure =
{
pcstr_self: pattern;
pcstr_fields: class_field list;
}
and class_field =
{
pcf_desc: class_field_desc;
pcf_loc: Location.t;
* [ ... [ \@\@id1 ] [ \@\@id2 ] ]
}
and class_field_desc =
| Pcf_inherit of override_flag * class_expr * string loc option
* [ Pcf_inherit(flag , CE , s ) ] represents :
- [ inherit CE ]
when [ flag ] is { { ! . Fresh}[Fresh ] }
and [ s ] is [ None ] ,
- [ inherit CE as x ]
when [ flag ] is { { ! . Fresh}[Fresh ] }
and [ s ] is [ Some x ] ,
- [ inherit ! CE ]
when [ flag ] is { { ! . Override}[Override ] }
and [ s ] is [ None ] ,
- [ inherit ! CE as x ]
when [ flag ] is { { ! . Override}[Override ] }
and [ s ] is [ Some x ]
- [inherit CE]
when [flag] is {{!Asttypes.override_flag.Fresh}[Fresh]}
and [s] is [None],
- [inherit CE as x]
when [flag] is {{!Asttypes.override_flag.Fresh}[Fresh]}
and [s] is [Some x],
- [inherit! CE]
when [flag] is {{!Asttypes.override_flag.Override}[Override]}
and [s] is [None],
- [inherit! CE as x]
when [flag] is {{!Asttypes.override_flag.Override}[Override]}
and [s] is [Some x]
*)
| Pcf_val of (label loc * mutable_flag * class_field_kind)
| Pcf_method of (label loc * private_flag * class_field_kind)
and class_field_kind =
| Cfk_virtual of core_type
| Cfk_concrete of override_flag * expression
and class_declaration = class_expr class_infos
* { 2 Type expressions for the module language }
and module_type =
{
pmty_desc: module_type_desc;
pmty_loc: Location.t;
}
and module_type_desc =
| Pmty_functor of functor_parameter * module_type
* [ functor(X : ) - > MT2 ]
and functor_parameter =
| Named of string option loc * module_type
* [ Named(name , ) ] represents :
- [ ( X : MT ) ] when [ name ] is [ Some X ] ,
- [ ( _ : MT ) ] when [ name ] is [ None ]
- [(X : MT)] when [name] is [Some X],
- [(_ : MT)] when [name] is [None] *)
and signature = signature_item list
and signature_item =
{
psig_desc: signature_item_desc;
psig_loc: Location.t;
}
and signature_item_desc =
| Psig_value of value_description
| Psig_type of rec_flag * type_declaration list
* [ type t1 = ... and ... and = ... ]
| Psig_typesubst of type_declaration list
| Psig_recmodule of module_declaration list
* [ module rec X1 : and ... and Xn : MTn ]
| Psig_modtype of module_type_declaration
| Psig_modtypesubst of module_type_declaration
| Psig_class of class_description list
| Psig_class_type of class_type_declaration list
and module_declaration =
{
pmd_name: string option loc;
pmd_type: module_type;
* [ ... [ \@\@id1 ] [ \@\@id2 ] ]
pmd_loc: Location.t;
}
and module_substitution =
{
pms_name: string loc;
pms_manifest: Longident.t loc;
* [ ... [ \@\@id1 ] [ \@\@id2 ] ]
pms_loc: Location.t;
}
and module_type_declaration =
{
pmtd_name: string loc;
pmtd_type: module_type option;
* [ ... [ \@\@id1 ] [ \@\@id2 ] ]
pmtd_loc: Location.t;
}
and 'a open_infos =
{
popen_expr: 'a;
popen_override: override_flag;
popen_loc: Location.t;
popen_attributes: attributes;
}
* Values of type [ ' a open_infos ] represents :
- [ open ! X ] when { { ! open_infos.popen_override}[popen_override ] }
is { { ! . Override}[Override ] }
( silences the " used identifier shadowing " warning )
- [ open X ] when { { ! open_infos.popen_override}[popen_override ] }
is { { ! . Fresh}[Fresh ] }
- [open! X] when {{!open_infos.popen_override}[popen_override]}
is {{!Asttypes.override_flag.Override}[Override]}
(silences the "used identifier shadowing" warning)
- [open X] when {{!open_infos.popen_override}[popen_override]}
is {{!Asttypes.override_flag.Fresh}[Fresh]}
*)
and open_description = Longident.t loc open_infos
and open_declaration = module_expr open_infos
and 'a include_infos =
{
pincl_mod: 'a;
pincl_loc: Location.t;
pincl_attributes: attributes;
}
and include_description = module_type include_infos
and include_declaration = module_expr include_infos
and with_constraint =
| Pwith_type of Longident.t loc * type_declaration
| Pwith_module of Longident.t loc * Longident.t loc
| Pwith_modtype of Longident.t loc * module_type
| Pwith_modtypesubst of Longident.t loc * module_type
| Pwith_typesubst of Longident.t loc * type_declaration
| Pwith_modsubst of Longident.t loc * Longident.t loc
* { 2 Value expressions for the module language }
and module_expr =
{
pmod_desc: module_expr_desc;
pmod_loc: Location.t;
}
and module_expr_desc =
| Pmod_functor of functor_parameter * module_expr
* [ functor(X : ) - > ME ]
* [ ) ]
and structure = structure_item list
and structure_item =
{
pstr_desc: structure_item_desc;
pstr_loc: Location.t;
}
and structure_item_desc =
| Pstr_value of rec_flag * value_binding list
* [ Pstr_value(rec , [ ( P1 , E1 ; ... ; ( Pn , En ) ) ] ) ] represents :
- [ let P1 = E1 and ... and Pn = EN ]
when [ rec ] is { { ! Asttypes.rec_flag . Nonrecursive}[Nonrecursive ] } ,
- [ let rec P1 = E1 and ... and Pn = EN ]
when [ rec ] is { { ! Asttypes.rec_flag . Recursive}[Recursive ] } .
- [let P1 = E1 and ... and Pn = EN]
when [rec] is {{!Asttypes.rec_flag.Nonrecursive}[Nonrecursive]},
- [let rec P1 = E1 and ... and Pn = EN ]
when [rec] is {{!Asttypes.rec_flag.Recursive}[Recursive]}.
*)
| Pstr_primitive of value_description
| Pstr_type of rec_flag * type_declaration list
| Pstr_exception of type_exception
| Pstr_recmodule of module_binding list
| Pstr_class of class_declaration list
| Pstr_class_type of class_type_declaration list
and value_binding =
{
pvb_pat: pattern;
pvb_expr: expression;
pvb_attributes: attributes;
pvb_loc: Location.t;
}
and module_binding =
{
pmb_name: string option loc;
pmb_expr: module_expr;
pmb_attributes: attributes;
pmb_loc: Location.t;
}
* { 1 Toplevel }
* { 2 Toplevel phrases }
type toplevel_phrase =
| Ptop_def of structure
and toplevel_directive =
{
pdir_name: string loc;
pdir_arg: directive_argument option;
pdir_loc: Location.t;
}
and directive_argument =
{
pdira_desc: directive_argument_desc;
pdira_loc: Location.t;
}
and directive_argument_desc =
| Pdir_string of string
| Pdir_int of string * char option
| Pdir_ident of Longident.t
| Pdir_bool of bool
|
8f0cdfe9af5b0ffb1bc9735065e938cc9145e81b9a5c499cb0bca6dd1c105e87 | data61/Mirza | Schema.hs | module Mirza.OrgRegistry.Database.Schema
( module Current
, migration
, orgRegistryDB
, checkedOrgRegistryDB
, primaryKey
) where
import Control . ( ( > > > ) )
import Database.Beam (DatabaseSettings)
import Database.Beam.Migrate.Types hiding (migrateScript)
import Database.Beam.Postgres (Postgres)
import Database.Beam.Schema.Tables (primaryKey)
import Mirza.OrgRegistry.Database.Schema.V0001 as Current hiding
(migration)
import qualified Mirza.OrgRegistry.Database.Schema.V0001 as V0001 (migration)
import qualified . OrgRegistry . Database . Schema . as ( migration )
migration :: MigrationSteps Postgres () (CheckedDatabaseSettings Postgres Current.OrgRegistryDB)
migration = migrationStep "Initial commit" V0001.migration
-- >>> migrationStep "Add LocationT table" V0002.migration
orgRegistryDB :: DatabaseSettings Postgres Current.OrgRegistryDB
orgRegistryDB = unCheckDatabase checkedOrgRegistryDB
checkedOrgRegistryDB :: CheckedDatabaseSettings Postgres Current.OrgRegistryDB
checkedOrgRegistryDB = evaluateDatabase migration
| null | https://raw.githubusercontent.com/data61/Mirza/24e5ccddfc307cceebcc5ce26d35e91020b8ee10/projects/or_scs/src/Mirza/OrgRegistry/Database/Schema.hs | haskell | >>> migrationStep "Add LocationT table" V0002.migration | module Mirza.OrgRegistry.Database.Schema
( module Current
, migration
, orgRegistryDB
, checkedOrgRegistryDB
, primaryKey
) where
import Control . ( ( > > > ) )
import Database.Beam (DatabaseSettings)
import Database.Beam.Migrate.Types hiding (migrateScript)
import Database.Beam.Postgres (Postgres)
import Database.Beam.Schema.Tables (primaryKey)
import Mirza.OrgRegistry.Database.Schema.V0001 as Current hiding
(migration)
import qualified Mirza.OrgRegistry.Database.Schema.V0001 as V0001 (migration)
import qualified . OrgRegistry . Database . Schema . as ( migration )
migration :: MigrationSteps Postgres () (CheckedDatabaseSettings Postgres Current.OrgRegistryDB)
migration = migrationStep "Initial commit" V0001.migration
orgRegistryDB :: DatabaseSettings Postgres Current.OrgRegistryDB
orgRegistryDB = unCheckDatabase checkedOrgRegistryDB
checkedOrgRegistryDB :: CheckedDatabaseSettings Postgres Current.OrgRegistryDB
checkedOrgRegistryDB = evaluateDatabase migration
|
dff84cbf2d5bd2ad6c35f948122fe8c8adc9d52c70d5ca9b282b00ce9301fccf | danhper/evm-analyzer | taggers.mli | open Core
val all: TracerTypes.Tagger.t List.t List.t
val for_vulnerability: String.t -> TracerTypes.Tagger.t List.t List.t
val per_block: TracerTypes.Tagger.t List.t List.t
val per_tx: TracerTypes.Tagger.t List.t List.t
| null | https://raw.githubusercontent.com/danhper/evm-analyzer/9fb1cf6dc743c2f779973b2f0892047ebbd4e5fd/src/taggers.mli | ocaml | open Core
val all: TracerTypes.Tagger.t List.t List.t
val for_vulnerability: String.t -> TracerTypes.Tagger.t List.t List.t
val per_block: TracerTypes.Tagger.t List.t List.t
val per_tx: TracerTypes.Tagger.t List.t List.t
| |
d113983ca806a8221422b04c6f4a0d57aa2a9576035f556c4117cd5ec6e03cb2 | DogLooksGood/holdem | event_handler.clj | (ns poker.game.event-handler
"Implementations of engine's event handler."
(:require
[poker.game.misc :as misc]
[poker.game.model :as model]
[poker.game.event-handler.impl :as impl]
[poker.utils :refer [filter-vals map-vals]]
[clojure.tools.logging :as log]))
;; errors
(defn throw-no-enough-stack!
[event]
(throw (ex-info "No enough stack" {:event event})))
(defn throw-invalid-player-id!
[event]
(throw (ex-info "Invalid player id" {:event event})))
(defn throw-player-already-buyin!
[event]
(throw (ex-info "Player already buyin" {:event event})))
(defn throw-great-than-max-buyin!
[event]
(throw (ex-info "Great than max buyin" {:event event})))
(defn throw-player-not-wait-for-bb!
[event]
(throw (ex-info "Player not wait for bb" {:event event})))
(defn throw-expired-event! [event] (throw (ex-info "Expired event" {:event event})))
(defn throw-game-already-started! [event] (throw (ex-info "Game already started" {:event event})))
(defn throw-less-than-min-buyin! [event] (throw (ex-info "Less than min buyin" {:event event})))
(defn throw-seat-is-occupied! [event] (throw (ex-info "Seat is occupied" {:event event})))
(defn throw-player-not-in-action! [event] (throw (ex-info "Player not in action" {:event event})))
(defn throw-no-enough-players! [event] (throw (ex-info "No enough players" {:event event})))
(defn throw-cant-bet! [event] (throw (ex-info "Can't bet" {:event event})))
(defn throw-bet-is-too-small! [event] (throw (ex-info "Bet is too small" {:event event})))
(defn throw-raise-is-too-small! [event] (throw (ex-info "Raise is too small" {:event event})))
(defn throw-cant-call! [event] (throw (ex-info "Can't call" {:event event})))
(defn throw-cant-check! [event] (throw (ex-info "Can't check" {:event event})))
(defn throw-cant-raise! [event] (throw (ex-info "Can't raise" {:event event})))
(defn throw-invalid-times! [event] (throw (ex-info "Invalid times" {:event event})))
(defn throw-invalid-event! [event] (throw (ex-info "Invalid event" {:event event})))
(defn throw-cant-musk! [event] (throw (ex-info "Can't musk" {:event event})))
(defn throw-last-player-cant-musk!
[event]
(throw (ex-info "Last player can't musk" {:event event})))
(defn throw-player-already-in-game!
[event]
(throw (ex-info "Player already in game" {:event event})))
(defn throw-duplicate-deal-times-request
[event]
(throw (ex-info "Duplicate deal times request" {:event event})))
;; assertions
(defn assert-enough-players!
[state event]
(when (->> state
(:players)
(vals)
(filter (comp #{:player-status/wait-for-start :player-status/wait-for-bb
:player-status/join-bet}
:status))
(count)
(> 2))
(throw-no-enough-players! event)))
(defn assert-player-not-in-game!
[state event id]
(when-let [p (get-in state [:players id])]
(when-not (= :player-status/leave (:status p))
(throw-player-already-in-game! event))))
(defn assert-player-id!
[state event id]
(when-not (get-in state [:players id]) (throw-invalid-player-id! event)))
(defn assert-player-off-seat!
[state event id]
(when-not (= :player-status/off-seat (get-in state [:players id :status]))
(throw-player-already-buyin! event)))
(defn assert-buyin-stack!
[state event stack]
(let [{:keys [min-buyin max-buyin]} (get state :opts)]
(cond (< max-buyin stack) (throw-great-than-max-buyin! event)
(> min-buyin stack) (throw-less-than-min-buyin! event))))
(defn assert-seat-is-available!
[state event seat]
(when (get-in state [:seats seat])
(throw-seat-is-occupied! event)))
(defn assert-player-can-call!
[state event player-id]
(let [{:keys [street-bet]} state
current-bet (or (peek (get-in state [:players player-id :bets])) 0)]
(when-not (pos? street-bet)
(throw-cant-call! event))
(when-not (> street-bet current-bet)
(throw-cant-call! event))))
(defn assert-game-can-start!
[state event]
(when-not (= :game-status/idle (:status state))
(throw-game-already-started! event)))
(defn assert-action-player-id!
[state event player-id]
(when-not (= :player-status/in-action (get-in state [:players player-id :status]))
(throw-player-not-in-action! event)))
(defn assert-valid-action-id!
[state event action-id]
(when-not (= action-id (:action-id state))
(throw-expired-event! event)))
(defn assert-valid-bet!
[state event player-id bet]
(cond (< bet (get-in state [:opts :bb])) (throw-bet-is-too-small! event)
(> bet (get-in state [:players player-id :stack])) (throw-no-enough-stack! event)))
(defn assert-valid-raise!
[state event player-id raise]
(let [player (get-in state [:players player-id])
{:keys [bets stack]} player
curr-bet (last bets)
{:keys [street-bet opts min-raise]}
state
{:keys [bb]}
opts]
(cond
(and (< (+ (or curr-bet 0) raise)
(+ (or street-bet 0) (or min-raise street-bet bb 0)))
(not= stack raise))
(throw-raise-is-too-small! event)
(> raise (get-in state [:players player-id :stack]))
(throw-no-enough-stack! event)
;; Only acted and wait-for-action can call the raise
(->> (:players state)
(keep (fn [[id p]]
(when-not (= player-id id)
(#{:player-status/acted :player-status/wait-for-action} (:status p)))))
(empty?))
(throw-cant-raise! event))))
(defn assert-valid-check!
[state event player-id]
(when-not (= (peek (get-in state [:players player-id :bets])) (get state :street-bet))
(throw-cant-check! event)))
(defn assert-valid-deal-times-request!
[state event player-id times]
(when-not (int? times) (throw-invalid-times! event))
(when-not (#{:player-status/acted :player-status/all-in}
(get-in state [:players player-id :status]))
(throw-player-not-in-action! event))
(let [curr-times (get-in state [:runner :deal-times] 2)]
(when-not (<= 1 times curr-times) (throw-invalid-times! event)))
(when (get-in state [:runner :player-deal-times player-id])
(throw-duplicate-deal-times-request event)))
(defn assert-can-bet!
[state event]
(when (:street-bet state) (throw-cant-bet! event)))
(defn assert-player-wait-for-bb!
[state event player-id]
(when-not (= :player-status/wait-for-bb (get-in state [:players player-id :status]))
(throw-player-not-wait-for-bb! event)))
(defn assert-player-can-musk!
[state event player-id]
(when-not (->> (:players state)
(vals)
(some (fn [{:keys [status id]}]
(and (not= id player-id)
(#{:player-status/all-in :player-status/acted} status)))))
(throw-last-player-cant-musk! event))
(when-not (= :player-status/acted (get-in state [:players player-id :status]))
(throw-cant-musk! event))
(when-not (= :game-status/showdown-prepare (:status state)) (throw-cant-musk! event)))
(defn assert-can-request-deal-times!
[state event]
(when-not (= (:status state) :game-status/runner-prepare) (throw-invalid-event! event)))
(defn dispatch-by-event-type [_game-state game-event] (first game-event))
(defmulti validate-game-event
"Validate game event."
dispatch-by-event-type)
(defmethod validate-game-event :default
[_ _])
(defmulti apply-game-event
"Apply game event to game state."
dispatch-by-event-type)
(defmethod apply-game-event :default
[_ event]
(throw-invalid-event! event))
(defn handle-game-event
"Game event handler dispatch by event-type."
[game-state game-event]
(validate-game-event game-state game-event)
(apply-game-event game-state game-event))
;; ----------------------------------------------------------------------------
;; validate game event
;; ----------------------------------------------------------------------------
;; Ensure the player is not in the game
(defmethod validate-game-event :game-event/player-join
[game-state
[_ {:keys [id]}
:as
event]]
(assert-player-not-in-game! game-state event id))
(defmethod validate-game-event :game-event/player-leave
[game-state [_ {:keys [player-id] :as event}]]
(assert-player-id! game-state event player-id))
;; Check player id
;; Ensure player status is off-seat
Ensure stack - add is between max - buyin & min - buyin
;; Ensure the seat is available
(defmethod validate-game-event :game-event/player-buyin
[game-state
[_ {:keys [player-id seat stack-add]}
:as
event]]
(assert-player-id! game-state event player-id)
(assert-player-off-seat! game-state event player-id)
(assert-buyin-stack! game-state event stack-add)
(assert-seat-is-available! game-state event seat))
;; Ensure the game is idle.
(defmethod validate-game-event :game-event/start-game
[game-state event]
Here we need two players to start a game
(assert-game-can-start! game-state event)
(assert-enough-players! game-state event))
(defmethod validate-game-event :game-event/player-join-bet
[game-state
[_ {:keys [player-id]}
:as
event]]
(assert-player-id! game-state event player-id)
(assert-player-wait-for-bb! game-state event player-id))
(defmethod validate-game-event :game-event/player-call
[game-state
[_ {:keys [player-id]}
:as
event]]
(assert-action-player-id! game-state event player-id)
(assert-player-can-call! game-state event player-id))
(defmethod validate-game-event :game-event/player-bet
[game-state
[_ {:keys [player-id bet]}
:as
event]]
(assert-action-player-id! game-state event player-id)
(assert-can-bet! game-state event)
(assert-valid-bet! game-state event player-id bet))
(defmethod validate-game-event :game-event/player-raise
[game-state
[_ {:keys [player-id raise]}
:as
event]]
(assert-action-player-id! game-state event player-id)
(assert-valid-raise! game-state event player-id raise))
(defmethod validate-game-event :game-event/player-fold
[game-state
[_ {:keys [player-id]}
:as
event]]
(assert-action-player-id! game-state event player-id))
(defmethod validate-game-event :game-event/fold-player
[game-state
[_ {:keys [player-id action-id], :as event}]]
(assert-action-player-id! game-state event player-id)
(assert-valid-action-id! game-state event action-id))
(defmethod validate-game-event :game-event/player-check
[game-state
[_ {:keys [player-id]}
:as
event]]
(assert-action-player-id! game-state event player-id)
(assert-valid-check! game-state event player-id))
(defmethod validate-game-event :game-event/player-musk
[game-state [_ {:keys [player-id], :as event}]]
(assert-player-id! game-state event player-id)
(assert-player-can-musk! game-state event player-id))
(defmethod validate-game-event :game-event/player-request-deal-times
[game-state
[_ {:keys [player-id deal-times]}
:as
event]]
(assert-player-id! game-state event player-id)
(assert-can-request-deal-times! game-state event)
(assert-valid-deal-times-request! game-state event player-id deal-times))
(defmethod validate-game-event :game-event/player-get-current-state
[game-state [_ {:keys [player-id], :as event}]]
(assert-player-id! game-state event player-id))
;; ----------------------------------------------------------------------------
;; apply game event
;; ----------------------------------------------------------------------------
;; Add player to game with initial state.
(defmethod apply-game-event :game-event/player-join
[game-state
[_ {:keys [id name props]}]]
(let [player (model/make-player-state {:id id, :name name, :props props})]
(impl/add-player game-state player)))
;; Kick player immediately if current game state is idle or settlement.
player as dropout , if still in game .
;; The dropout player can reconnect in this game, or be kicked out before start next game.
(defmethod apply-game-event :game-event/player-leave
[game-state [_ {:keys [player-id]}]]
(let [{:keys [players status]} game-state]
(if
(or (#{:game-status/showdown-settlement
:game-status/runner-settlement
:game-status/last-player-settlement
:game-status/idle}
status)
(#{:player-status/wait-for-bb
:player-status/join-bet
:player-status/off-seat}
(get-in players [player-id :status])))
;; kick player
(impl/remove-player game-state player-id)
;; mark player's network is dropout
(impl/mark-player-leave game-state player-id))))
;; Buyin will trigger a game-start immediately.
(defmethod apply-game-event :game-event/player-buyin
[game-state
[_ {:keys [player-id seat stack-add no-auto-start?]}]]
(let [next-events (:next-events game-state)
rep-next-events (if no-auto-start?
next-events
(conj next-events
[:game-event/start-game {}]))]
(-> game-state
(impl/player-set-stack player-id stack-add)
(impl/player-set-seat player-id seat)
(update :ladder-events
conj
[:ladder-event/player-buyin {:player-id player-id, :buyin stack-add}])
(assoc :next-events rep-next-events))))
;; Prepare state for next-game:
;; In this procedure we reset nearly all game states.
;; we kick dropout players
;; we update btn-seat to next player
;; Players without stack will be set as off-seat.
(defmethod apply-game-event :game-event/next-game
[game-state _]
(let [state (loop [state game-state
[{:keys [id status stack network-error], :as p} & ps] (vals (:players
game-state))]
(cond
(nil? p)
state
(some? network-error)
(recur (impl/remove-player state id) ps)
(= :player-status/leave status)
(recur (impl/remove-player state id) ps)
(and (int? stack) (zero? stack))
(recur (impl/set-player-off-seat state id) ps)
(#{:player-status/wait-for-bb
:player-status/join-bet
:player-status/off-seat}
status)
(recur state ps)
:else
(recur (impl/reset-player-state-for-new-game state id) ps)))]
(-> state
(assoc
:status :game-status/idle
:in-game-player-ids []
:cards nil
:community-cards []
:pots nil
:street-bet nil
:min-raise nil
:showdown nil
:awards nil
:return-bets nil
:runner nil
:player-action nil)
(update :schedule-events
conj
(model/make-schedule-event {:timeout 1000,
:event [:game-event/check-chip-leader {}]})
(model/make-schedule-event {:timeout 2000,
:event [:game-event/start-game {}]})))))
;; GAME START
;; The following setups will be done during start-game
1 . collect the players in this game
2 . create a deck of cards
3 . deliver cards for players .
4 . blind bet
5 . calculate round bet & pot
6 . next player to call
;; This event handler will check if it's possible to start
(defmethod apply-game-event :game-event/start-game
[game-state _event]
(-> game-state
;; some states should be reset
(assoc :status :game-status/preflop)
(assoc :next-events
[[:game-event/collect-players {}] [:game-event/deal-cards {}]])))
;; collect the player who is the next of the seat in game
;; when finished, goto next street.
(defmethod apply-game-event :game-event/collect-players
[game-state _]
(let [{:keys [opts players btn-seat]} game-state
{:keys [bb sb]} opts]
(letfn [(make-player-status-map
[id pos]
[id {:position pos, :status :player-status/wait-for-action, :bets [nil]}])]
(let [in-game-players (misc/find-players-for-start players btn-seat)
in-game-player-ids (mapv :id in-game-players)
pos-list (misc/players-num->position-list (count in-game-player-ids))
player-status-map (->> in-game-player-ids
(map-indexed #(make-player-status-map %2 (nth pos-list %1)))
(into {}))
two-player? (= 2 (count in-game-player-ids))
bb-events (if two-player?
[[:game-event/blind-bet
{:player-id (nth in-game-player-ids
1),
:bet sb}]
[:game-event/blind-bet
{:player-id (nth in-game-player-ids
0),
:bet bb}]]
(->> [sb bb]
(map-indexed (fn [idx bet]
(let [id (nth in-game-player-ids idx)]
(when (not= :player-status/join-bet
(get-in players [id :status]))
[:game-event/blind-bet
{:player-id id,
:bet bet}]))))
(filter some?)
(vec)))
join-bet-events (if two-player?
[]
(->> in-game-players
(filter (comp #{:player-status/join-bet} :status))
(map (fn [{:keys [id]}]
[:game-event/blind-bet
{:player-id id,
:bet bb}]))
(vec)))
rest-events (if two-player?
start from BTN
[[:game-event/count-pot {}]
[:game-event/next-player-or-stage
{:player-id (nth in-game-player-ids
0)}]]
start from UTG
[[:game-event/count-pot {}]
[:game-event/next-player-or-stage
{:player-id (nth in-game-player-ids
1)}]])
next-events (vec (concat join-bet-events bb-events rest-events))]
(log/infof "next-events: %s" next-events)
(-> game-state
(assoc :in-game-player-ids in-game-player-ids)
(assoc :btn-seat
(-> in-game-players
last
:seat))
(update :players (partial merge-with merge) player-status-map)
(update :next-events into next-events))))))
(defmethod apply-game-event :game-event/deal-cards
[game-state _]
(let [deck-of-cards (misc/create-deck-of-cards)
{:keys [in-game-player-ids]} game-state
player-cnt (count in-game-player-ids)
hole-cards-list (->> deck-of-cards
(partition 2)
(take player-cnt))
rest-cards (drop (* 2 player-cnt) deck-of-cards)
player-hole-cards-map (->> (map (fn [id hole-cards] [id {:hole-cards hole-cards}])
in-game-player-ids
hole-cards-list)
(into {}))]
(-> game-state
(assoc :cards rest-cards)
(update :players (partial merge-with merge) player-hole-cards-map))))
(defmethod apply-game-event :game-event/chip-leader-returns
[game-state [_ {:keys [player-id returns]}]]
(impl/player-returns game-state player-id returns))
(defmethod apply-game-event :game-event/check-chip-leader
[game-state _]
(let [{:keys [players opts]} game-state
{:keys [max-stack]} opts
events (->> players
(vals)
(keep (fn [{:keys [stack id]}]
(when (and (int? stack)
(> stack max-stack))
[:game-event/chip-leader-returns
{:player-id id,
:returns (- stack max-stack)}]))))]
(if (seq events)
(update game-state :next-events into events)
game-state)))
(defmethod apply-game-event :game-event/count-pot
[game-state [_ {:keys [collapse-all?]}]]
(let [{:keys [status players]} game-state
street (misc/game-status->street status)
rep-pots (misc/count-pot (when-not collapse-all? street) players)
street-bet (->> players
(vals)
(keep (comp peek :bets))
(reduce max 0))
street - bet ca n't be zero
street-bet (when-not (zero? street-bet) street-bet)]
(-> game-state
(assoc :street-bet street-bet :pots rep-pots))))
;; NEXT PLAYER OR STREET
(defmethod apply-game-event :game-event/next-player-or-stage
[game-state [_ {:keys [player-id]}]]
(let [{:keys [in-game-player-ids players street-bet opts status]} game-state
;; Here we try to found the `next-player-id` to act
;; he either has wait-for-action status or bet is less than `street-bet`.
;; we have to check according to the order in `in-game-player-ids`.
[before after] (split-with #(not= player-id %) in-game-player-ids)
check-ids (concat (next after) before)
rest-players (->> check-ids
(map players))
next-act-player-id (some->> rest-players
(filter #(or
;; no action yet
(= :player-status/wait-for-action (:status %))
;; acted, but other player raise
(and (not= street-bet (peek (:bets %)))
(= :player-status/acted (:status %)))))
(first)
(:id))
;; Here we filter for the rest players(players who not fold).
left-players (->> players
(vals)
(filter (comp #{:player-status/wait-for-action
:player-status/acted :player-status/all-in}
:status)))
allin-player-count (->> left-players
(filter (comp #{:player-status/all-in} :status))
(count))
;; first act player for next street
next-street-player-id (->> in-game-player-ids
(map players)
(filter #(= :player-status/acted (:status %)))
(first)
(:id))
state-next-street (fn [state evt]
(-> state
(update :next-events
conj
[evt {:action-player-id next-street-player-id}]
[:game-event/count-pot {}])
(misc/set-in-action-for-player next-street-player-id)))]
(cond
One player left
(= 1 (count left-players)) (-> game-state
(update :next-events
conj
[:game-event/last-player
{:player-id (:id (first left-players))}]))
;; Wait action from next player
next-act-player-id
(let [rep-players (->> (for [[id p] players]
[id
(cond-> p
(= id next-act-player-id)
(assoc :status :player-status/in-action))])
(into {}))]
(-> game-state
(assoc :players rep-players)
(misc/set-in-action-for-player next-act-player-id)))
Showdown
(and (nil? next-act-player-id) (= :game-status/river status)) (update
game-state
:next-events
conj
[:game-event/count-pot
{:collapse-all? true}]
[:game-event/showdown-prepare
{}])
Less equal than one player is not allin
;; -> runner
(>= allin-player-count (dec (count left-players)))
(-> game-state
(update :next-events
conj
[:game-event/count-pot {:collapse-all? true}]
[:game-event/runner-prepare {}]))
;; Preflop -> Flop
(= :game-status/preflop status) (state-next-street game-state :game-event/flop-street)
;; Flop -> Turn
(= :game-status/flop status) (state-next-street game-state :game-event/turn-street)
;; Turn -> River
(= :game-status/turn status) (state-next-street game-state :game-event/river-street)
:else
;; There's no player in game.
;; For all player has left.
;; Here we call next-game to clean states.
(update game-state :next-events conj [:game-event/next-game {}]))))
(defmethod apply-game-event :game-event/flop-street
[game-state [_ {:keys [action-player-id]}]]
(let [{:keys [cards players]} game-state
[community-cards rest-cards] (split-at 3 cards)
rep-players (misc/init-player-status-for-new-street players action-player-id)]
(-> game-state
(assoc :street-bet nil
:min-raise nil
:cards rest-cards
:community-cards (vec community-cards)
:status :game-status/flop
:players rep-players)
(assoc-in [:players action-player-id :status] :player-status/in-action))))
(defmethod apply-game-event :game-event/turn-street
[game-state [_ {:keys [action-player-id]}]]
(let [{:keys [cards players]} game-state
rep-players (misc/init-player-status-for-new-street players action-player-id)]
(-> game-state
(assoc :street-bet nil :min-raise nil :status :game-status/turn :players rep-players)
(update :community-cards conj (first cards))
(update :cards next)
(assoc-in [:players action-player-id :status] :player-status/in-action))))
(defmethod apply-game-event :game-event/river-street
[game-state [_ {:keys [action-player-id]}]]
(let [{:keys [cards players]} game-state
rep-players (misc/init-player-status-for-new-street players action-player-id)]
(-> game-state
(assoc :street-bet nil :min-raise nil :players rep-players :status :game-status/river)
(update :community-cards conj (first cards))
(update :cards next)
(assoc-in [:players action-player-id :status] :player-status/in-action))))
Newcomer 's bet
;; mark player will bet at next game.
(defmethod apply-game-event :game-event/player-join-bet
[game-state
[_ {:keys [player-id]}]]
(impl/mark-player-join-bet game-state player-id))
;; PLAYER ACTIONS
each player as 4 types of actions
1 . call
2 . fold
3 . raise
4 . check
;; CALL
(defmethod apply-game-event :game-event/player-call
[game-state
[_ {:keys [player-id]}]]
(let [{:keys [street-bet players]} game-state
bets (get-in players [player-id :bets])
current-bet (or (peek bets) 0)
stack (get-in players [player-id :stack])
stack-sub (- street-bet current-bet)
[status bet stack] (if (>= stack-sub stack)
[:player-status/all-in (+ current-bet stack) 0]
[:player-status/acted street-bet (- stack stack-sub)])
rep-bets (conj (pop bets) bet)]
(-> game-state
(update-in [:players player-id] assoc :status status :bets rep-bets :stack stack)
(update :next-events
conj
[:game-event/count-pot {}]
[:game-event/next-player-or-stage {:player-id player-id}])
;; (assoc :min-raise bet)
(assoc :player-action [:player-action/call {:player-id player-id}]))))
BET
the bet must great than BB
;; the bet must less equal than stack
;; if bet equals stack, means all-in
(defmethod apply-game-event :game-event/blind-bet
[game-state
[_ {:keys [player-id bet]}]]
(let [{:keys [players opts]} game-state
{:keys [stack bets]} (get players player-id)
status (if (= bet stack) :player-status/all-in :player-status/wait-for-action)
rep-bets (conj (pop bets) bet)]
(-> game-state
(update-in [:players player-id] assoc :bets rep-bets :status status :stack (- stack bet))
(assoc :street-bet (:bb opts))
(assoc :min-raise (:bb opts)))))
(defmethod apply-game-event :game-event/player-bet
[game-state
[_ {:keys [player-id bet]}]]
(let [{:keys [players]} game-state
{:keys [stack bets]} (get players player-id)
all-in? (= bet stack)
status (if all-in? :player-status/all-in :player-status/acted)
rep-bets (conj (pop bets) bet)]
(-> game-state
(update-in [:players player-id] assoc :bets rep-bets :status status :stack (- stack bet))
(assoc :min-raise bet)
(update :next-events
conj
[:game-event/count-pot {}]
[:game-event/next-player-or-stage {:player-id player-id}])
(assoc :player-action
[:player-action/bet {:player-id player-id, :bet bet, :all-in? all-in?}]))))
;; RAISE
the raise must great than ( max min - raise BB )
;; the raise must less equal than stack
;; if raise equals stack, means all-in
TODO ca n't raise when all player all - in
(defmethod apply-game-event :game-event/player-raise
[game-state
[_ {:keys [player-id raise]}]]
(let [{:keys [players street-bet min-raise]} game-state
{:keys [bets stack]} (get players player-id)
bet (peek bets)
all-in? (= stack raise)
status (if all-in? :player-status/all-in :player-status/acted)
new-bet (+ (or bet 0) raise)
rep-bets (conj (pop bets) new-bet)]
(-> game-state
(update-in [:players player-id] assoc :status status :bets rep-bets :stack (- stack raise))
(assoc :min-raise ((fnil max 0) min-raise (- new-bet (or street-bet 0))))
(update :next-events
conj
[:game-event/count-pot {}]
[:game-event/next-player-or-stage {:player-id player-id}])
(assoc :player-action
[:player-action/raise {:player-id player-id, :raise raise, :all-in? all-in?}]))))
FOLD
(defmethod apply-game-event :game-event/player-fold
[game-state
[_ {:keys [player-id]}]]
(-> game-state
(update-in [:players player-id] assoc :status :player-status/fold)
(update :next-events
conj
[:game-event/count-pot {}]
[:game-event/next-player-or-stage {:player-id player-id}])
(assoc :player-action [:player-action/fold {:player-id player-id}])))
;; System fold
(defmethod apply-game-event :game-event/fold-player
[game-state
[_ {:keys [player-id]}]]
(-> game-state
(update-in [:players player-id] assoc :status :player-status/fold)
(update :next-events
conj
[:game-event/count-pot {}]
[:game-event/next-player-or-stage {:player-id player-id}])
(assoc :player-action [:player-action/fold {:player-id player-id}])))
(defmethod apply-game-event :game-event/player-check
[game-state
[_ {:keys [player-id]}]]
(-> game-state
(update-in [:players player-id] assoc :status :player-status/acted)
(update :next-events
conj
[:game-event/next-player-or-stage {:player-id player-id}])
(assoc :player-action [:player-action/check {:player-id player-id}])))
;; Player can musk his cards before showdown.
(defmethod apply-game-event :game-event/player-musk
[game-state [_ {:keys [player-id]}]]
(-> game-state
(update-in [:players player-id] assoc :status :player-status/fold)
(assoc :player-action [:player-action/musk {:player-id player-id}])))
;; If a player is the last player, he will win all pots
(defmethod apply-game-event :game-event/last-player
[game-state [_ {:keys [player-id]}]]
(let [{:keys [pots players]} game-state
award (transduce (map :value) + pots)
awards {player-id award}
rep-pots (map #(assoc % :winner-ids [player-id]) pots)
rep-players (misc/reward-to-players awards players)]
(-> game-state
(assoc :status :game-status/last-player-settlement
:in-game-player-ids []
:cards nil
:pots rep-pots
:street-bet nil
:community-cards []
:min-raise nil
:showdown nil
:return-bets nil
:players rep-players
:awards awards)
(update :schedule-events
conj
(model/make-schedule-event {:timeout 4000,
:event [:game-event/next-game {}]})))))
(defmethod apply-game-event :game-event/showdown-prepare
[game-state _]
(-> game-state
(assoc :status :game-status/showdown-prepare)
(update :schedule-events
conj
(model/make-schedule-event {:timeout 2000,
:event [:game-event/showdown {}]}))))
(defmethod apply-game-event :game-event/showdown
[game-state _]
(let [{:keys [pots players community-cards in-game-player-ids]} game-state
{:keys [return-bets remain-pots]} (impl/pots-return-bets pots)
players (map-vals (fn [p]
(update p :stack + (get return-bets (:id p) 0)))
players)
;; showdown: id -> card value
{:keys [showdown awards pots]} (misc/calc-showdown {:players players,
:pots remain-pots,
:in-game-player-ids in-game-player-ids,
:community-cards community-cards})
rep-players (misc/reward-to-players awards players)]
(-> game-state
(assoc :showdown showdown
:status :game-status/showdown-settlement
:in-game-player-ids []
:cards nil
:pots pots
:street-bet nil
:min-raise nil
:return-bets return-bets
:players rep-players
:awards awards)
(update :schedule-events
conj
(model/make-schedule-event {:timeout 10000,
:event [:game-event/next-game {}]})))))
;; When all player all-in
;; reward those pots with single contributor.
;; ask players for times to run
(defmethod apply-game-event :game-event/runner-prepare
[game-state _]
(let [{:keys [players pots]} game-state
{:keys [return-bets remain-pots]} (impl/pots-return-bets pots)
rep-pots (misc/collapse-pots nil remain-pots)
rep-players (reduce (fn [ps [id v]] (update-in ps [id :stack] + v)) players return-bets)
showdown (map-vals (fn [p] (select-keys p [:hole-cards])) rep-players)
runner {:showdown showdown}]
(-> game-state
(assoc :players rep-players
:pots rep-pots
:runner runner
:return-bets return-bets
:status :game-status/runner-prepare)
(update :schedule-events
conj
(model/make-schedule-event {:timeout 4000,
:event [:game-event/runner-run {}]})))))
(defmethod apply-game-event :game-event/runner-run
[game-state _]
(let [{:keys [players community-cards runner cards pots]} game-state
{:keys [deal-times]} runner
when no player request deal times , default to 1
deal-times (or deal-times 1)
deal-n (- 5 (count community-cards))
deals-list (->> cards
(partition-all deal-n)
(take deal-times))
undivided-pot-values (mapv (fn [pot] (mod (:value pot) deal-times)) pots)
runner-pots (mapv (fn [pot] (update pot :value quot deal-times)) pots)
results (->> deals-list
(map-indexed
(fn [idx deals]
(let [cards (into community-cards deals)
runner-pots (if (zero? idx)
(mapv #(update %1 :value + %2)
runner-pots
undivided-pot-values)
runner-pots)
{:keys [awards pots showdown]} (misc/calc-showdown
{:players players,
:pots runner-pots,
:community-cards cards})]
{:awards awards,
:pots pots,
:showdown showdown,
:community-cards cards}))))
awards (apply merge-with
(fn [& xs]
(->> xs
(filter pos?)
(reduce +)))
(map :awards results))
rep-players (misc/reward-to-players awards players)]
(-> game-state
(update :runner assoc :results results)
(assoc :awards awards
:players rep-players
:status :game-status/runner-settlement
:in-game-player-ids []
:cards nil
:street-bet nil
:community-cards []
:min-raise nil
:showdown nil)
(update :schedule-events
conj
(model/make-schedule-event {:timeout (case deal-times
1 13000
2 23000),
:event [:game-event/next-game {}]})))))
(defmethod apply-game-event :game-event/player-request-deal-times
[game-state
[_ {:keys [player-id deal-times]}]]
(if (seq (get-in game-state [:runner :player-deal-times]))
(-> game-state
(update-in [:runner :deal-times] (fnil min 2) deal-times)
(assoc-in [:runner :player-deal-times player-id] deal-times)
(assoc :player-action
[:player-action/player-request-deal-times
{:player-id player-id, :deal-times deal-times}]))
(-> game-state
(assoc-in [:runner :deal-times] (min 2 deal-times))
(assoc-in [:runner :player-deal-times player-id] deal-times)
(assoc :player-action
[:player-action/player-request-deal-times
{:player-id player-id, :deal-times deal-times}]))))
(defmethod apply-game-event :game-event/player-get-current-state
[game-state [_ _]]
game-state)
| null | https://raw.githubusercontent.com/DogLooksGood/holdem/fddc99c25b004647b5d4e5cbe56bdcb4e18ac9a0/src/clj/poker/game/event_handler.clj | clojure | errors
assertions
Only acted and wait-for-action can call the raise
----------------------------------------------------------------------------
validate game event
----------------------------------------------------------------------------
Ensure the player is not in the game
Check player id
Ensure player status is off-seat
Ensure the seat is available
Ensure the game is idle.
----------------------------------------------------------------------------
apply game event
----------------------------------------------------------------------------
Add player to game with initial state.
Kick player immediately if current game state is idle or settlement.
The dropout player can reconnect in this game, or be kicked out before start next game.
kick player
mark player's network is dropout
Buyin will trigger a game-start immediately.
Prepare state for next-game:
In this procedure we reset nearly all game states.
we kick dropout players
we update btn-seat to next player
Players without stack will be set as off-seat.
GAME START
The following setups will be done during start-game
This event handler will check if it's possible to start
some states should be reset
collect the player who is the next of the seat in game
when finished, goto next street.
NEXT PLAYER OR STREET
Here we try to found the `next-player-id` to act
he either has wait-for-action status or bet is less than `street-bet`.
we have to check according to the order in `in-game-player-ids`.
no action yet
acted, but other player raise
Here we filter for the rest players(players who not fold).
first act player for next street
Wait action from next player
-> runner
Preflop -> Flop
Flop -> Turn
Turn -> River
There's no player in game.
For all player has left.
Here we call next-game to clean states.
mark player will bet at next game.
PLAYER ACTIONS
CALL
(assoc :min-raise bet)
the bet must less equal than stack
if bet equals stack, means all-in
RAISE
the raise must less equal than stack
if raise equals stack, means all-in
System fold
Player can musk his cards before showdown.
If a player is the last player, he will win all pots
showdown: id -> card value
When all player all-in
reward those pots with single contributor.
ask players for times to run | (ns poker.game.event-handler
"Implementations of engine's event handler."
(:require
[poker.game.misc :as misc]
[poker.game.model :as model]
[poker.game.event-handler.impl :as impl]
[poker.utils :refer [filter-vals map-vals]]
[clojure.tools.logging :as log]))
(defn throw-no-enough-stack!
[event]
(throw (ex-info "No enough stack" {:event event})))
(defn throw-invalid-player-id!
[event]
(throw (ex-info "Invalid player id" {:event event})))
(defn throw-player-already-buyin!
[event]
(throw (ex-info "Player already buyin" {:event event})))
(defn throw-great-than-max-buyin!
[event]
(throw (ex-info "Great than max buyin" {:event event})))
(defn throw-player-not-wait-for-bb!
[event]
(throw (ex-info "Player not wait for bb" {:event event})))
(defn throw-expired-event! [event] (throw (ex-info "Expired event" {:event event})))
(defn throw-game-already-started! [event] (throw (ex-info "Game already started" {:event event})))
(defn throw-less-than-min-buyin! [event] (throw (ex-info "Less than min buyin" {:event event})))
(defn throw-seat-is-occupied! [event] (throw (ex-info "Seat is occupied" {:event event})))
(defn throw-player-not-in-action! [event] (throw (ex-info "Player not in action" {:event event})))
(defn throw-no-enough-players! [event] (throw (ex-info "No enough players" {:event event})))
(defn throw-cant-bet! [event] (throw (ex-info "Can't bet" {:event event})))
(defn throw-bet-is-too-small! [event] (throw (ex-info "Bet is too small" {:event event})))
(defn throw-raise-is-too-small! [event] (throw (ex-info "Raise is too small" {:event event})))
(defn throw-cant-call! [event] (throw (ex-info "Can't call" {:event event})))
(defn throw-cant-check! [event] (throw (ex-info "Can't check" {:event event})))
(defn throw-cant-raise! [event] (throw (ex-info "Can't raise" {:event event})))
(defn throw-invalid-times! [event] (throw (ex-info "Invalid times" {:event event})))
(defn throw-invalid-event! [event] (throw (ex-info "Invalid event" {:event event})))
(defn throw-cant-musk! [event] (throw (ex-info "Can't musk" {:event event})))
(defn throw-last-player-cant-musk!
[event]
(throw (ex-info "Last player can't musk" {:event event})))
(defn throw-player-already-in-game!
[event]
(throw (ex-info "Player already in game" {:event event})))
(defn throw-duplicate-deal-times-request
[event]
(throw (ex-info "Duplicate deal times request" {:event event})))
(defn assert-enough-players!
[state event]
(when (->> state
(:players)
(vals)
(filter (comp #{:player-status/wait-for-start :player-status/wait-for-bb
:player-status/join-bet}
:status))
(count)
(> 2))
(throw-no-enough-players! event)))
(defn assert-player-not-in-game!
[state event id]
(when-let [p (get-in state [:players id])]
(when-not (= :player-status/leave (:status p))
(throw-player-already-in-game! event))))
(defn assert-player-id!
[state event id]
(when-not (get-in state [:players id]) (throw-invalid-player-id! event)))
(defn assert-player-off-seat!
[state event id]
(when-not (= :player-status/off-seat (get-in state [:players id :status]))
(throw-player-already-buyin! event)))
(defn assert-buyin-stack!
[state event stack]
(let [{:keys [min-buyin max-buyin]} (get state :opts)]
(cond (< max-buyin stack) (throw-great-than-max-buyin! event)
(> min-buyin stack) (throw-less-than-min-buyin! event))))
(defn assert-seat-is-available!
[state event seat]
(when (get-in state [:seats seat])
(throw-seat-is-occupied! event)))
(defn assert-player-can-call!
[state event player-id]
(let [{:keys [street-bet]} state
current-bet (or (peek (get-in state [:players player-id :bets])) 0)]
(when-not (pos? street-bet)
(throw-cant-call! event))
(when-not (> street-bet current-bet)
(throw-cant-call! event))))
(defn assert-game-can-start!
[state event]
(when-not (= :game-status/idle (:status state))
(throw-game-already-started! event)))
(defn assert-action-player-id!
[state event player-id]
(when-not (= :player-status/in-action (get-in state [:players player-id :status]))
(throw-player-not-in-action! event)))
(defn assert-valid-action-id!
[state event action-id]
(when-not (= action-id (:action-id state))
(throw-expired-event! event)))
(defn assert-valid-bet!
[state event player-id bet]
(cond (< bet (get-in state [:opts :bb])) (throw-bet-is-too-small! event)
(> bet (get-in state [:players player-id :stack])) (throw-no-enough-stack! event)))
(defn assert-valid-raise!
[state event player-id raise]
(let [player (get-in state [:players player-id])
{:keys [bets stack]} player
curr-bet (last bets)
{:keys [street-bet opts min-raise]}
state
{:keys [bb]}
opts]
(cond
(and (< (+ (or curr-bet 0) raise)
(+ (or street-bet 0) (or min-raise street-bet bb 0)))
(not= stack raise))
(throw-raise-is-too-small! event)
(> raise (get-in state [:players player-id :stack]))
(throw-no-enough-stack! event)
(->> (:players state)
(keep (fn [[id p]]
(when-not (= player-id id)
(#{:player-status/acted :player-status/wait-for-action} (:status p)))))
(empty?))
(throw-cant-raise! event))))
(defn assert-valid-check!
[state event player-id]
(when-not (= (peek (get-in state [:players player-id :bets])) (get state :street-bet))
(throw-cant-check! event)))
(defn assert-valid-deal-times-request!
[state event player-id times]
(when-not (int? times) (throw-invalid-times! event))
(when-not (#{:player-status/acted :player-status/all-in}
(get-in state [:players player-id :status]))
(throw-player-not-in-action! event))
(let [curr-times (get-in state [:runner :deal-times] 2)]
(when-not (<= 1 times curr-times) (throw-invalid-times! event)))
(when (get-in state [:runner :player-deal-times player-id])
(throw-duplicate-deal-times-request event)))
(defn assert-can-bet!
[state event]
(when (:street-bet state) (throw-cant-bet! event)))
(defn assert-player-wait-for-bb!
[state event player-id]
(when-not (= :player-status/wait-for-bb (get-in state [:players player-id :status]))
(throw-player-not-wait-for-bb! event)))
(defn assert-player-can-musk!
[state event player-id]
(when-not (->> (:players state)
(vals)
(some (fn [{:keys [status id]}]
(and (not= id player-id)
(#{:player-status/all-in :player-status/acted} status)))))
(throw-last-player-cant-musk! event))
(when-not (= :player-status/acted (get-in state [:players player-id :status]))
(throw-cant-musk! event))
(when-not (= :game-status/showdown-prepare (:status state)) (throw-cant-musk! event)))
(defn assert-can-request-deal-times!
[state event]
(when-not (= (:status state) :game-status/runner-prepare) (throw-invalid-event! event)))
(defn dispatch-by-event-type [_game-state game-event] (first game-event))
(defmulti validate-game-event
"Validate game event."
dispatch-by-event-type)
(defmethod validate-game-event :default
[_ _])
(defmulti apply-game-event
"Apply game event to game state."
dispatch-by-event-type)
(defmethod apply-game-event :default
[_ event]
(throw-invalid-event! event))
(defn handle-game-event
"Game event handler dispatch by event-type."
[game-state game-event]
(validate-game-event game-state game-event)
(apply-game-event game-state game-event))
(defmethod validate-game-event :game-event/player-join
[game-state
[_ {:keys [id]}
:as
event]]
(assert-player-not-in-game! game-state event id))
(defmethod validate-game-event :game-event/player-leave
[game-state [_ {:keys [player-id] :as event}]]
(assert-player-id! game-state event player-id))
Ensure stack - add is between max - buyin & min - buyin
(defmethod validate-game-event :game-event/player-buyin
[game-state
[_ {:keys [player-id seat stack-add]}
:as
event]]
(assert-player-id! game-state event player-id)
(assert-player-off-seat! game-state event player-id)
(assert-buyin-stack! game-state event stack-add)
(assert-seat-is-available! game-state event seat))
(defmethod validate-game-event :game-event/start-game
[game-state event]
Here we need two players to start a game
(assert-game-can-start! game-state event)
(assert-enough-players! game-state event))
(defmethod validate-game-event :game-event/player-join-bet
[game-state
[_ {:keys [player-id]}
:as
event]]
(assert-player-id! game-state event player-id)
(assert-player-wait-for-bb! game-state event player-id))
(defmethod validate-game-event :game-event/player-call
[game-state
[_ {:keys [player-id]}
:as
event]]
(assert-action-player-id! game-state event player-id)
(assert-player-can-call! game-state event player-id))
(defmethod validate-game-event :game-event/player-bet
[game-state
[_ {:keys [player-id bet]}
:as
event]]
(assert-action-player-id! game-state event player-id)
(assert-can-bet! game-state event)
(assert-valid-bet! game-state event player-id bet))
(defmethod validate-game-event :game-event/player-raise
[game-state
[_ {:keys [player-id raise]}
:as
event]]
(assert-action-player-id! game-state event player-id)
(assert-valid-raise! game-state event player-id raise))
(defmethod validate-game-event :game-event/player-fold
[game-state
[_ {:keys [player-id]}
:as
event]]
(assert-action-player-id! game-state event player-id))
(defmethod validate-game-event :game-event/fold-player
[game-state
[_ {:keys [player-id action-id], :as event}]]
(assert-action-player-id! game-state event player-id)
(assert-valid-action-id! game-state event action-id))
(defmethod validate-game-event :game-event/player-check
[game-state
[_ {:keys [player-id]}
:as
event]]
(assert-action-player-id! game-state event player-id)
(assert-valid-check! game-state event player-id))
(defmethod validate-game-event :game-event/player-musk
[game-state [_ {:keys [player-id], :as event}]]
(assert-player-id! game-state event player-id)
(assert-player-can-musk! game-state event player-id))
(defmethod validate-game-event :game-event/player-request-deal-times
[game-state
[_ {:keys [player-id deal-times]}
:as
event]]
(assert-player-id! game-state event player-id)
(assert-can-request-deal-times! game-state event)
(assert-valid-deal-times-request! game-state event player-id deal-times))
(defmethod validate-game-event :game-event/player-get-current-state
[game-state [_ {:keys [player-id], :as event}]]
(assert-player-id! game-state event player-id))
(defmethod apply-game-event :game-event/player-join
[game-state
[_ {:keys [id name props]}]]
(let [player (model/make-player-state {:id id, :name name, :props props})]
(impl/add-player game-state player)))
player as dropout , if still in game .
(defmethod apply-game-event :game-event/player-leave
[game-state [_ {:keys [player-id]}]]
(let [{:keys [players status]} game-state]
(if
(or (#{:game-status/showdown-settlement
:game-status/runner-settlement
:game-status/last-player-settlement
:game-status/idle}
status)
(#{:player-status/wait-for-bb
:player-status/join-bet
:player-status/off-seat}
(get-in players [player-id :status])))
(impl/remove-player game-state player-id)
(impl/mark-player-leave game-state player-id))))
(defmethod apply-game-event :game-event/player-buyin
[game-state
[_ {:keys [player-id seat stack-add no-auto-start?]}]]
(let [next-events (:next-events game-state)
rep-next-events (if no-auto-start?
next-events
(conj next-events
[:game-event/start-game {}]))]
(-> game-state
(impl/player-set-stack player-id stack-add)
(impl/player-set-seat player-id seat)
(update :ladder-events
conj
[:ladder-event/player-buyin {:player-id player-id, :buyin stack-add}])
(assoc :next-events rep-next-events))))
(defmethod apply-game-event :game-event/next-game
[game-state _]
(let [state (loop [state game-state
[{:keys [id status stack network-error], :as p} & ps] (vals (:players
game-state))]
(cond
(nil? p)
state
(some? network-error)
(recur (impl/remove-player state id) ps)
(= :player-status/leave status)
(recur (impl/remove-player state id) ps)
(and (int? stack) (zero? stack))
(recur (impl/set-player-off-seat state id) ps)
(#{:player-status/wait-for-bb
:player-status/join-bet
:player-status/off-seat}
status)
(recur state ps)
:else
(recur (impl/reset-player-state-for-new-game state id) ps)))]
(-> state
(assoc
:status :game-status/idle
:in-game-player-ids []
:cards nil
:community-cards []
:pots nil
:street-bet nil
:min-raise nil
:showdown nil
:awards nil
:return-bets nil
:runner nil
:player-action nil)
(update :schedule-events
conj
(model/make-schedule-event {:timeout 1000,
:event [:game-event/check-chip-leader {}]})
(model/make-schedule-event {:timeout 2000,
:event [:game-event/start-game {}]})))))
1 . collect the players in this game
2 . create a deck of cards
3 . deliver cards for players .
4 . blind bet
5 . calculate round bet & pot
6 . next player to call
(defmethod apply-game-event :game-event/start-game
[game-state _event]
(-> game-state
(assoc :status :game-status/preflop)
(assoc :next-events
[[:game-event/collect-players {}] [:game-event/deal-cards {}]])))
(defmethod apply-game-event :game-event/collect-players
[game-state _]
(let [{:keys [opts players btn-seat]} game-state
{:keys [bb sb]} opts]
(letfn [(make-player-status-map
[id pos]
[id {:position pos, :status :player-status/wait-for-action, :bets [nil]}])]
(let [in-game-players (misc/find-players-for-start players btn-seat)
in-game-player-ids (mapv :id in-game-players)
pos-list (misc/players-num->position-list (count in-game-player-ids))
player-status-map (->> in-game-player-ids
(map-indexed #(make-player-status-map %2 (nth pos-list %1)))
(into {}))
two-player? (= 2 (count in-game-player-ids))
bb-events (if two-player?
[[:game-event/blind-bet
{:player-id (nth in-game-player-ids
1),
:bet sb}]
[:game-event/blind-bet
{:player-id (nth in-game-player-ids
0),
:bet bb}]]
(->> [sb bb]
(map-indexed (fn [idx bet]
(let [id (nth in-game-player-ids idx)]
(when (not= :player-status/join-bet
(get-in players [id :status]))
[:game-event/blind-bet
{:player-id id,
:bet bet}]))))
(filter some?)
(vec)))
join-bet-events (if two-player?
[]
(->> in-game-players
(filter (comp #{:player-status/join-bet} :status))
(map (fn [{:keys [id]}]
[:game-event/blind-bet
{:player-id id,
:bet bb}]))
(vec)))
rest-events (if two-player?
start from BTN
[[:game-event/count-pot {}]
[:game-event/next-player-or-stage
{:player-id (nth in-game-player-ids
0)}]]
start from UTG
[[:game-event/count-pot {}]
[:game-event/next-player-or-stage
{:player-id (nth in-game-player-ids
1)}]])
next-events (vec (concat join-bet-events bb-events rest-events))]
(log/infof "next-events: %s" next-events)
(-> game-state
(assoc :in-game-player-ids in-game-player-ids)
(assoc :btn-seat
(-> in-game-players
last
:seat))
(update :players (partial merge-with merge) player-status-map)
(update :next-events into next-events))))))
(defmethod apply-game-event :game-event/deal-cards
[game-state _]
(let [deck-of-cards (misc/create-deck-of-cards)
{:keys [in-game-player-ids]} game-state
player-cnt (count in-game-player-ids)
hole-cards-list (->> deck-of-cards
(partition 2)
(take player-cnt))
rest-cards (drop (* 2 player-cnt) deck-of-cards)
player-hole-cards-map (->> (map (fn [id hole-cards] [id {:hole-cards hole-cards}])
in-game-player-ids
hole-cards-list)
(into {}))]
(-> game-state
(assoc :cards rest-cards)
(update :players (partial merge-with merge) player-hole-cards-map))))
(defmethod apply-game-event :game-event/chip-leader-returns
[game-state [_ {:keys [player-id returns]}]]
(impl/player-returns game-state player-id returns))
(defmethod apply-game-event :game-event/check-chip-leader
[game-state _]
(let [{:keys [players opts]} game-state
{:keys [max-stack]} opts
events (->> players
(vals)
(keep (fn [{:keys [stack id]}]
(when (and (int? stack)
(> stack max-stack))
[:game-event/chip-leader-returns
{:player-id id,
:returns (- stack max-stack)}]))))]
(if (seq events)
(update game-state :next-events into events)
game-state)))
(defmethod apply-game-event :game-event/count-pot
[game-state [_ {:keys [collapse-all?]}]]
(let [{:keys [status players]} game-state
street (misc/game-status->street status)
rep-pots (misc/count-pot (when-not collapse-all? street) players)
street-bet (->> players
(vals)
(keep (comp peek :bets))
(reduce max 0))
street - bet ca n't be zero
street-bet (when-not (zero? street-bet) street-bet)]
(-> game-state
(assoc :street-bet street-bet :pots rep-pots))))
(defmethod apply-game-event :game-event/next-player-or-stage
[game-state [_ {:keys [player-id]}]]
(let [{:keys [in-game-player-ids players street-bet opts status]} game-state
[before after] (split-with #(not= player-id %) in-game-player-ids)
check-ids (concat (next after) before)
rest-players (->> check-ids
(map players))
next-act-player-id (some->> rest-players
(filter #(or
(= :player-status/wait-for-action (:status %))
(and (not= street-bet (peek (:bets %)))
(= :player-status/acted (:status %)))))
(first)
(:id))
left-players (->> players
(vals)
(filter (comp #{:player-status/wait-for-action
:player-status/acted :player-status/all-in}
:status)))
allin-player-count (->> left-players
(filter (comp #{:player-status/all-in} :status))
(count))
next-street-player-id (->> in-game-player-ids
(map players)
(filter #(= :player-status/acted (:status %)))
(first)
(:id))
state-next-street (fn [state evt]
(-> state
(update :next-events
conj
[evt {:action-player-id next-street-player-id}]
[:game-event/count-pot {}])
(misc/set-in-action-for-player next-street-player-id)))]
(cond
One player left
(= 1 (count left-players)) (-> game-state
(update :next-events
conj
[:game-event/last-player
{:player-id (:id (first left-players))}]))
next-act-player-id
(let [rep-players (->> (for [[id p] players]
[id
(cond-> p
(= id next-act-player-id)
(assoc :status :player-status/in-action))])
(into {}))]
(-> game-state
(assoc :players rep-players)
(misc/set-in-action-for-player next-act-player-id)))
Showdown
(and (nil? next-act-player-id) (= :game-status/river status)) (update
game-state
:next-events
conj
[:game-event/count-pot
{:collapse-all? true}]
[:game-event/showdown-prepare
{}])
Less equal than one player is not allin
(>= allin-player-count (dec (count left-players)))
(-> game-state
(update :next-events
conj
[:game-event/count-pot {:collapse-all? true}]
[:game-event/runner-prepare {}]))
(= :game-status/preflop status) (state-next-street game-state :game-event/flop-street)
(= :game-status/flop status) (state-next-street game-state :game-event/turn-street)
(= :game-status/turn status) (state-next-street game-state :game-event/river-street)
:else
(update game-state :next-events conj [:game-event/next-game {}]))))
(defmethod apply-game-event :game-event/flop-street
[game-state [_ {:keys [action-player-id]}]]
(let [{:keys [cards players]} game-state
[community-cards rest-cards] (split-at 3 cards)
rep-players (misc/init-player-status-for-new-street players action-player-id)]
(-> game-state
(assoc :street-bet nil
:min-raise nil
:cards rest-cards
:community-cards (vec community-cards)
:status :game-status/flop
:players rep-players)
(assoc-in [:players action-player-id :status] :player-status/in-action))))
(defmethod apply-game-event :game-event/turn-street
[game-state [_ {:keys [action-player-id]}]]
(let [{:keys [cards players]} game-state
rep-players (misc/init-player-status-for-new-street players action-player-id)]
(-> game-state
(assoc :street-bet nil :min-raise nil :status :game-status/turn :players rep-players)
(update :community-cards conj (first cards))
(update :cards next)
(assoc-in [:players action-player-id :status] :player-status/in-action))))
(defmethod apply-game-event :game-event/river-street
[game-state [_ {:keys [action-player-id]}]]
(let [{:keys [cards players]} game-state
rep-players (misc/init-player-status-for-new-street players action-player-id)]
(-> game-state
(assoc :street-bet nil :min-raise nil :players rep-players :status :game-status/river)
(update :community-cards conj (first cards))
(update :cards next)
(assoc-in [:players action-player-id :status] :player-status/in-action))))
Newcomer 's bet
(defmethod apply-game-event :game-event/player-join-bet
[game-state
[_ {:keys [player-id]}]]
(impl/mark-player-join-bet game-state player-id))
each player as 4 types of actions
1 . call
2 . fold
3 . raise
4 . check
(defmethod apply-game-event :game-event/player-call
[game-state
[_ {:keys [player-id]}]]
(let [{:keys [street-bet players]} game-state
bets (get-in players [player-id :bets])
current-bet (or (peek bets) 0)
stack (get-in players [player-id :stack])
stack-sub (- street-bet current-bet)
[status bet stack] (if (>= stack-sub stack)
[:player-status/all-in (+ current-bet stack) 0]
[:player-status/acted street-bet (- stack stack-sub)])
rep-bets (conj (pop bets) bet)]
(-> game-state
(update-in [:players player-id] assoc :status status :bets rep-bets :stack stack)
(update :next-events
conj
[:game-event/count-pot {}]
[:game-event/next-player-or-stage {:player-id player-id}])
(assoc :player-action [:player-action/call {:player-id player-id}]))))
BET
the bet must great than BB
(defmethod apply-game-event :game-event/blind-bet
[game-state
[_ {:keys [player-id bet]}]]
(let [{:keys [players opts]} game-state
{:keys [stack bets]} (get players player-id)
status (if (= bet stack) :player-status/all-in :player-status/wait-for-action)
rep-bets (conj (pop bets) bet)]
(-> game-state
(update-in [:players player-id] assoc :bets rep-bets :status status :stack (- stack bet))
(assoc :street-bet (:bb opts))
(assoc :min-raise (:bb opts)))))
(defmethod apply-game-event :game-event/player-bet
[game-state
[_ {:keys [player-id bet]}]]
(let [{:keys [players]} game-state
{:keys [stack bets]} (get players player-id)
all-in? (= bet stack)
status (if all-in? :player-status/all-in :player-status/acted)
rep-bets (conj (pop bets) bet)]
(-> game-state
(update-in [:players player-id] assoc :bets rep-bets :status status :stack (- stack bet))
(assoc :min-raise bet)
(update :next-events
conj
[:game-event/count-pot {}]
[:game-event/next-player-or-stage {:player-id player-id}])
(assoc :player-action
[:player-action/bet {:player-id player-id, :bet bet, :all-in? all-in?}]))))
the raise must great than ( max min - raise BB )
TODO ca n't raise when all player all - in
(defmethod apply-game-event :game-event/player-raise
[game-state
[_ {:keys [player-id raise]}]]
(let [{:keys [players street-bet min-raise]} game-state
{:keys [bets stack]} (get players player-id)
bet (peek bets)
all-in? (= stack raise)
status (if all-in? :player-status/all-in :player-status/acted)
new-bet (+ (or bet 0) raise)
rep-bets (conj (pop bets) new-bet)]
(-> game-state
(update-in [:players player-id] assoc :status status :bets rep-bets :stack (- stack raise))
(assoc :min-raise ((fnil max 0) min-raise (- new-bet (or street-bet 0))))
(update :next-events
conj
[:game-event/count-pot {}]
[:game-event/next-player-or-stage {:player-id player-id}])
(assoc :player-action
[:player-action/raise {:player-id player-id, :raise raise, :all-in? all-in?}]))))
FOLD
(defmethod apply-game-event :game-event/player-fold
[game-state
[_ {:keys [player-id]}]]
(-> game-state
(update-in [:players player-id] assoc :status :player-status/fold)
(update :next-events
conj
[:game-event/count-pot {}]
[:game-event/next-player-or-stage {:player-id player-id}])
(assoc :player-action [:player-action/fold {:player-id player-id}])))
(defmethod apply-game-event :game-event/fold-player
[game-state
[_ {:keys [player-id]}]]
(-> game-state
(update-in [:players player-id] assoc :status :player-status/fold)
(update :next-events
conj
[:game-event/count-pot {}]
[:game-event/next-player-or-stage {:player-id player-id}])
(assoc :player-action [:player-action/fold {:player-id player-id}])))
(defmethod apply-game-event :game-event/player-check
[game-state
[_ {:keys [player-id]}]]
(-> game-state
(update-in [:players player-id] assoc :status :player-status/acted)
(update :next-events
conj
[:game-event/next-player-or-stage {:player-id player-id}])
(assoc :player-action [:player-action/check {:player-id player-id}])))
(defmethod apply-game-event :game-event/player-musk
[game-state [_ {:keys [player-id]}]]
(-> game-state
(update-in [:players player-id] assoc :status :player-status/fold)
(assoc :player-action [:player-action/musk {:player-id player-id}])))
(defmethod apply-game-event :game-event/last-player
[game-state [_ {:keys [player-id]}]]
(let [{:keys [pots players]} game-state
award (transduce (map :value) + pots)
awards {player-id award}
rep-pots (map #(assoc % :winner-ids [player-id]) pots)
rep-players (misc/reward-to-players awards players)]
(-> game-state
(assoc :status :game-status/last-player-settlement
:in-game-player-ids []
:cards nil
:pots rep-pots
:street-bet nil
:community-cards []
:min-raise nil
:showdown nil
:return-bets nil
:players rep-players
:awards awards)
(update :schedule-events
conj
(model/make-schedule-event {:timeout 4000,
:event [:game-event/next-game {}]})))))
(defmethod apply-game-event :game-event/showdown-prepare
[game-state _]
(-> game-state
(assoc :status :game-status/showdown-prepare)
(update :schedule-events
conj
(model/make-schedule-event {:timeout 2000,
:event [:game-event/showdown {}]}))))
(defmethod apply-game-event :game-event/showdown
[game-state _]
(let [{:keys [pots players community-cards in-game-player-ids]} game-state
{:keys [return-bets remain-pots]} (impl/pots-return-bets pots)
players (map-vals (fn [p]
(update p :stack + (get return-bets (:id p) 0)))
players)
{:keys [showdown awards pots]} (misc/calc-showdown {:players players,
:pots remain-pots,
:in-game-player-ids in-game-player-ids,
:community-cards community-cards})
rep-players (misc/reward-to-players awards players)]
(-> game-state
(assoc :showdown showdown
:status :game-status/showdown-settlement
:in-game-player-ids []
:cards nil
:pots pots
:street-bet nil
:min-raise nil
:return-bets return-bets
:players rep-players
:awards awards)
(update :schedule-events
conj
(model/make-schedule-event {:timeout 10000,
:event [:game-event/next-game {}]})))))
(defmethod apply-game-event :game-event/runner-prepare
[game-state _]
(let [{:keys [players pots]} game-state
{:keys [return-bets remain-pots]} (impl/pots-return-bets pots)
rep-pots (misc/collapse-pots nil remain-pots)
rep-players (reduce (fn [ps [id v]] (update-in ps [id :stack] + v)) players return-bets)
showdown (map-vals (fn [p] (select-keys p [:hole-cards])) rep-players)
runner {:showdown showdown}]
(-> game-state
(assoc :players rep-players
:pots rep-pots
:runner runner
:return-bets return-bets
:status :game-status/runner-prepare)
(update :schedule-events
conj
(model/make-schedule-event {:timeout 4000,
:event [:game-event/runner-run {}]})))))
(defmethod apply-game-event :game-event/runner-run
[game-state _]
(let [{:keys [players community-cards runner cards pots]} game-state
{:keys [deal-times]} runner
when no player request deal times , default to 1
deal-times (or deal-times 1)
deal-n (- 5 (count community-cards))
deals-list (->> cards
(partition-all deal-n)
(take deal-times))
undivided-pot-values (mapv (fn [pot] (mod (:value pot) deal-times)) pots)
runner-pots (mapv (fn [pot] (update pot :value quot deal-times)) pots)
results (->> deals-list
(map-indexed
(fn [idx deals]
(let [cards (into community-cards deals)
runner-pots (if (zero? idx)
(mapv #(update %1 :value + %2)
runner-pots
undivided-pot-values)
runner-pots)
{:keys [awards pots showdown]} (misc/calc-showdown
{:players players,
:pots runner-pots,
:community-cards cards})]
{:awards awards,
:pots pots,
:showdown showdown,
:community-cards cards}))))
awards (apply merge-with
(fn [& xs]
(->> xs
(filter pos?)
(reduce +)))
(map :awards results))
rep-players (misc/reward-to-players awards players)]
(-> game-state
(update :runner assoc :results results)
(assoc :awards awards
:players rep-players
:status :game-status/runner-settlement
:in-game-player-ids []
:cards nil
:street-bet nil
:community-cards []
:min-raise nil
:showdown nil)
(update :schedule-events
conj
(model/make-schedule-event {:timeout (case deal-times
1 13000
2 23000),
:event [:game-event/next-game {}]})))))
(defmethod apply-game-event :game-event/player-request-deal-times
[game-state
[_ {:keys [player-id deal-times]}]]
(if (seq (get-in game-state [:runner :player-deal-times]))
(-> game-state
(update-in [:runner :deal-times] (fnil min 2) deal-times)
(assoc-in [:runner :player-deal-times player-id] deal-times)
(assoc :player-action
[:player-action/player-request-deal-times
{:player-id player-id, :deal-times deal-times}]))
(-> game-state
(assoc-in [:runner :deal-times] (min 2 deal-times))
(assoc-in [:runner :player-deal-times player-id] deal-times)
(assoc :player-action
[:player-action/player-request-deal-times
{:player-id player-id, :deal-times deal-times}]))))
(defmethod apply-game-event :game-event/player-get-current-state
[game-state [_ _]]
game-state)
|
9aad7ddb04452595e7c4e5cadd053e737dea9661ce88f261d95eae3f056b9572 | metaocaml/ber-metaocaml | mtype.mli | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(* Operations on module types *)
open Types
val scrape: Env.t -> module_type -> module_type
(* Expand toplevel module type abbreviations
till hitting a "hard" module type (signature, functor,
or abstract module type ident. *)
val scrape_for_functor_arg: Env.t -> module_type -> module_type
(* Remove aliases in a functor argument type *)
val scrape_for_type_of:
remove_aliases:bool -> Env.t -> module_type -> module_type
(* Process type for module type of *)
val freshen: scope:int -> module_type -> module_type
(* Return an alpha-equivalent copy of the given module type
where bound identifiers are fresh. *)
val strengthen: aliasable:bool -> Env.t -> module_type -> Path.t -> module_type
(* Strengthen abstract type components relative to the
given path. *)
val strengthen_decl:
aliasable:bool -> Env.t -> module_declaration -> Path.t -> module_declaration
val nondep_supertype: Env.t -> Ident.t list -> module_type -> module_type
Return the smallest supertype of the given type
in which none of the given idents appears .
@raise [ Ctype . Nondep_cannot_erase ] if no such type exists .
in which none of the given idents appears.
@raise [Ctype.Nondep_cannot_erase] if no such type exists. *)
val nondep_sig_item: Env.t -> Ident.t list -> signature_item -> signature_item
Returns the signature item with its type updated
to be the smallest supertype of its initial type
in which none of the given idents appears .
@raise [ Ctype . Nondep_cannot_erase ] if no such type exists .
to be the smallest supertype of its initial type
in which none of the given idents appears.
@raise [Ctype.Nondep_cannot_erase] if no such type exists. *)
val no_code_needed: Env.t -> module_type -> bool
val no_code_needed_sig: Env.t -> signature -> bool
(* Determine whether a module needs no implementation code,
i.e. consists only of type definitions. *)
val enrich_modtype: Env.t -> Path.t -> module_type -> module_type
val enrich_typedecl: Env.t -> Path.t -> Ident.t -> type_declaration ->
type_declaration
val type_paths: Env.t -> Path.t -> module_type -> Path.t list
val contains_type: Env.t -> module_type -> bool
val lower_nongen: int -> module_type -> unit
| null | https://raw.githubusercontent.com/metaocaml/ber-metaocaml/4992d1f87fc08ccb958817926cf9d1d739caf3a2/typing/mtype.mli | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
Operations on module types
Expand toplevel module type abbreviations
till hitting a "hard" module type (signature, functor,
or abstract module type ident.
Remove aliases in a functor argument type
Process type for module type of
Return an alpha-equivalent copy of the given module type
where bound identifiers are fresh.
Strengthen abstract type components relative to the
given path.
Determine whether a module needs no implementation code,
i.e. consists only of type definitions. | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Types
val scrape: Env.t -> module_type -> module_type
val scrape_for_functor_arg: Env.t -> module_type -> module_type
val scrape_for_type_of:
remove_aliases:bool -> Env.t -> module_type -> module_type
val freshen: scope:int -> module_type -> module_type
val strengthen: aliasable:bool -> Env.t -> module_type -> Path.t -> module_type
val strengthen_decl:
aliasable:bool -> Env.t -> module_declaration -> Path.t -> module_declaration
val nondep_supertype: Env.t -> Ident.t list -> module_type -> module_type
Return the smallest supertype of the given type
in which none of the given idents appears .
@raise [ Ctype . Nondep_cannot_erase ] if no such type exists .
in which none of the given idents appears.
@raise [Ctype.Nondep_cannot_erase] if no such type exists. *)
val nondep_sig_item: Env.t -> Ident.t list -> signature_item -> signature_item
Returns the signature item with its type updated
to be the smallest supertype of its initial type
in which none of the given idents appears .
@raise [ Ctype . Nondep_cannot_erase ] if no such type exists .
to be the smallest supertype of its initial type
in which none of the given idents appears.
@raise [Ctype.Nondep_cannot_erase] if no such type exists. *)
val no_code_needed: Env.t -> module_type -> bool
val no_code_needed_sig: Env.t -> signature -> bool
val enrich_modtype: Env.t -> Path.t -> module_type -> module_type
val enrich_typedecl: Env.t -> Path.t -> Ident.t -> type_declaration ->
type_declaration
val type_paths: Env.t -> Path.t -> module_type -> Path.t list
val contains_type: Env.t -> module_type -> bool
val lower_nongen: int -> module_type -> unit
|
47e6028ad244e208668fb9637ca9e73cab53cf3b55d4ee9283c3b3445e099a6a | nuprl/gradual-typing-performance | streams-stream-unfold.rkt | #lang racket/base
(provide stream-unfold)
(require "streams-struct.rkt")
Destruct a stream into its first value and the new stream produced by de - thunking the tail
;(: stream-unfold (-> stream (values Natural stream)))
(define (stream-unfold st)
(values (stream-first st) ((stream-rest st))))
| null | https://raw.githubusercontent.com/nuprl/gradual-typing-performance/35442b3221299a9cadba6810573007736b0d65d4/experimental/micro/sieve/untyped/streams-stream-unfold.rkt | racket | (: stream-unfold (-> stream (values Natural stream))) | #lang racket/base
(provide stream-unfold)
(require "streams-struct.rkt")
Destruct a stream into its first value and the new stream produced by de - thunking the tail
(define (stream-unfold st)
(values (stream-first st) ((stream-rest st))))
|
f8a87b48ab797bd8aa63cfd1dc1b217026e0b546c504cdd1b16beddca1134837 | mfoemmel/erlang-otp | wxTextDataObject.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2008 - 2009 . 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="">wxTextDataObject</a>.
%% <p>This class is derived (and can use functions) from:
%% <br />{@link wxDataObject}
%% </p>
%% @type wxTextDataObject(). 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(wxTextDataObject).
-include("wxe.hrl").
-export([destroy/1,getText/1,getTextLength/1,new/0,new/1,setText/2]).
%% inherited exports
-export([parent_class/1]).
%% @hidden
parent_class(wxDataObject) -> true;
parent_class(_Class) -> erlang:error({badtype, ?MODULE}).
( ) - > wxTextDataObject ( )
%% @equiv new([])
new() ->
new([]).
( [ Option ] ) - > wxTextDataObject ( )
%% Option = {text, string()}
%% @doc See <a href="#wxtextdataobjectwxtextdataobject">external documentation</a>.
new(Options)
when is_list(Options) ->
MOpts = fun({text, Text}, Acc) -> Text_UC = unicode:characters_to_binary([Text,0]),[<<1:32/?UI,(byte_size(Text_UC)):32/?UI,(Text_UC)/binary, 0:(((8- ((0+byte_size(Text_UC)) band 16#7)) band 16#7))/unit:8>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:construct(?wxTextDataObject_new,
<<BinOpt/binary>>).
%% @spec (This::wxTextDataObject()) -> integer()
%% @doc See <a href="#wxtextdataobjectgettextlength">external documentation</a>.
getTextLength(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxTextDataObject),
wxe_util:call(?wxTextDataObject_GetTextLength,
<<ThisRef:32/?UI>>).
%% @spec (This::wxTextDataObject()) -> string()
%% @doc See <a href="#wxtextdataobjectgettext">external documentation</a>.
getText(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxTextDataObject),
wxe_util:call(?wxTextDataObject_GetText,
<<ThisRef:32/?UI>>).
@spec ( This::wxTextDataObject ( ) , ( ) ) - > ok
%% @doc See <a href="#wxtextdataobjectsettext">external documentation</a>.
setText(#wx_ref{type=ThisT,ref=ThisRef},Text)
when is_list(Text) ->
?CLASS(ThisT,wxTextDataObject),
Text_UC = unicode:characters_to_binary([Text,0]),
wxe_util:cast(?wxTextDataObject_SetText,
<<ThisRef:32/?UI,(byte_size(Text_UC)):32/?UI,(Text_UC)/binary, 0:(((8- ((0+byte_size(Text_UC)) band 16#7)) band 16#7))/unit:8>>).
%% @spec (This::wxTextDataObject()) -> ok
%% @doc Destroys this object, do not use object again
destroy(Obj=#wx_ref{type=Type}) ->
?CLASS(Type,wxTextDataObject),
wxe_util:destroy(?wxTextDataObject_destroy,Obj),
ok.
%% From wxDataObject
| null | https://raw.githubusercontent.com/mfoemmel/erlang-otp/9c6fdd21e4e6573ca6f567053ff3ac454d742bc2/lib/wx/src/gen/wxTextDataObject.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="">wxTextDataObject</a>.
<p>This class is derived (and can use functions) from:
<br />{@link wxDataObject}
</p>
@type wxTextDataObject(). 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
@equiv new([])
Option = {text, string()}
@doc See <a href="#wxtextdataobjectwxtextdataobject">external documentation</a>.
@spec (This::wxTextDataObject()) -> integer()
@doc See <a href="#wxtextdataobjectgettextlength">external documentation</a>.
@spec (This::wxTextDataObject()) -> string()
@doc See <a href="#wxtextdataobjectgettext">external documentation</a>.
@doc See <a href="#wxtextdataobjectsettext">external documentation</a>.
@spec (This::wxTextDataObject()) -> ok
@doc Destroys this object, do not use object again
From wxDataObject | Copyright Ericsson AB 2008 - 2009 . 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(wxTextDataObject).
-include("wxe.hrl").
-export([destroy/1,getText/1,getTextLength/1,new/0,new/1,setText/2]).
-export([parent_class/1]).
parent_class(wxDataObject) -> true;
parent_class(_Class) -> erlang:error({badtype, ?MODULE}).
( ) - > wxTextDataObject ( )
new() ->
new([]).
( [ Option ] ) - > wxTextDataObject ( )
new(Options)
when is_list(Options) ->
MOpts = fun({text, Text}, Acc) -> Text_UC = unicode:characters_to_binary([Text,0]),[<<1:32/?UI,(byte_size(Text_UC)):32/?UI,(Text_UC)/binary, 0:(((8- ((0+byte_size(Text_UC)) band 16#7)) band 16#7))/unit:8>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:construct(?wxTextDataObject_new,
<<BinOpt/binary>>).
getTextLength(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxTextDataObject),
wxe_util:call(?wxTextDataObject_GetTextLength,
<<ThisRef:32/?UI>>).
getText(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxTextDataObject),
wxe_util:call(?wxTextDataObject_GetText,
<<ThisRef:32/?UI>>).
@spec ( This::wxTextDataObject ( ) , ( ) ) - > ok
setText(#wx_ref{type=ThisT,ref=ThisRef},Text)
when is_list(Text) ->
?CLASS(ThisT,wxTextDataObject),
Text_UC = unicode:characters_to_binary([Text,0]),
wxe_util:cast(?wxTextDataObject_SetText,
<<ThisRef:32/?UI,(byte_size(Text_UC)):32/?UI,(Text_UC)/binary, 0:(((8- ((0+byte_size(Text_UC)) band 16#7)) band 16#7))/unit:8>>).
destroy(Obj=#wx_ref{type=Type}) ->
?CLASS(Type,wxTextDataObject),
wxe_util:destroy(?wxTextDataObject_destroy,Obj),
ok.
|
3dc149c16419b68414d8d5acbd16e6964674e8209ee512984ae314e094f5c3d9 | chr15m/sitefox | sync-deps.cljs | (ns update-deps
(:require
["fs" :as fs]
[clojure.edn :as edn]
[clojure.pprint :refer [pprint]]))
(let [package (js/require "../package.json")
js-deps (js->clj (aget package "dependencies"))
deps (edn/read-string (fs/readFileSync "src/deps.cljs" "utf8"))
deps-updated (assoc deps :npm-deps js-deps)]
(binding [*print-fn* (fn [s]
(fs/writeFileSync "src/deps.cljs" s))]
(pprint deps-updated)))
| null | https://raw.githubusercontent.com/chr15m/sitefox/3e85c8eb4a56459fb225ca16c21f7a16de62e6cd/bin/sync-deps.cljs | clojure | (ns update-deps
(:require
["fs" :as fs]
[clojure.edn :as edn]
[clojure.pprint :refer [pprint]]))
(let [package (js/require "../package.json")
js-deps (js->clj (aget package "dependencies"))
deps (edn/read-string (fs/readFileSync "src/deps.cljs" "utf8"))
deps-updated (assoc deps :npm-deps js-deps)]
(binding [*print-fn* (fn [s]
(fs/writeFileSync "src/deps.cljs" s))]
(pprint deps-updated)))
| |
fcbe604b4443076c74f89447e9eeceb752f9ceaff7f20f4a6e926bb6db02e206 | racket/plot | plot-bitmap.rkt | #lang typed/racket/base
(require typed/racket/draw
"../common/type-doc.rkt"
"../common/types.rkt"
"../common/parameters.rkt"
"../common/nonrenderer.rkt"
"../plot2d/renderer.rkt"
"../plot3d/renderer.rkt"
"plot2d.rkt"
"plot3d.rkt"
typed/racket/unsafe)
(unsafe-provide plot plot3d)
(:: plot
(->* [(Treeof (U renderer2d nonrenderer))]
[#:x-min (U Real #f) #:x-max (U Real #f)
#:y-min (U Real #f) #:y-max (U Real #f)
#:width Positive-Integer
#:height Positive-Integer
#:title (U String #f)
#:x-label (U String #f)
#:y-label (U String #f)
#:aspect-ratio (U Nonnegative-Real #f)
#:legend-anchor Anchor
#:out-file (U Path-String Output-Port #f)
#:out-kind (U 'auto Image-File-Format)]
(Instance (Class #:implements Bitmap% #:implements Plot-Metrics<%>))))
(define (plot renderer-tree
#:x-min [x-min #f] #:x-max [x-max #f]
#:y-min [y-min #f] #:y-max [y-max #f]
#:width [width (plot-width)]
#:height [height (plot-height)]
#:title [title (plot-title)]
#:x-label [x-label (plot-x-label)]
#:y-label [y-label (plot-y-label)]
#:aspect-ratio [aspect-ratio (plot-aspect-ratio)]
#:legend-anchor [legend-anchor (plot-legend-anchor)]
#:out-file [out-file #f]
#:out-kind [out-kind 'auto])
(when out-file
(plot-file renderer-tree out-file out-kind
#:x-min x-min #:x-max x-max #:y-min y-min #:y-max y-max #:width width #:height height
#:title title #:x-label x-label #:y-label y-label #:legend-anchor legend-anchor
#:aspect-ratio aspect-ratio))
(plot-bitmap renderer-tree
#:x-min x-min #:x-max x-max #:y-min y-min #:y-max y-max #:width width #:height height
#:title title #:x-label x-label #:y-label y-label #:legend-anchor legend-anchor
#:aspect-ratio aspect-ratio))
(:: plot3d
(->* [(Treeof (U renderer3d nonrenderer))]
[#:x-min (U Real #f) #:x-max (U Real #f)
#:y-min (U Real #f) #:y-max (U Real #f)
#:z-min (U Real #f) #:z-max (U Real #f)
#:width Positive-Integer
#:height Positive-Integer
#:angle Real #:altitude Real
#:title (U String #f)
#:x-label (U String #f)
#:y-label (U String #f)
#:z-label (U String #f)
#:aspect-ratio (U Nonnegative-Real #f)
#:legend-anchor Anchor
#:out-file (U Path-String Output-Port #f)
#:out-kind (U 'auto Image-File-Format)]
(Instance (Class #:implements Bitmap% #:implements Plot-Metrics<%>))))
(define (plot3d renderer-tree
#:x-min [x-min #f] #:x-max [x-max #f]
#:y-min [y-min #f] #:y-max [y-max #f]
#:z-min [z-min #f] #:z-max [z-max #f]
#:width [width (plot-width)]
#:height [height (plot-height)]
#:angle [angle (plot3d-angle)]
#:altitude [altitude (plot3d-altitude)]
#:title [title (plot-title)]
#:x-label [x-label (plot-x-label)]
#:y-label [y-label (plot-y-label)]
#:z-label [z-label (plot-z-label)]
#:aspect-ratio [aspect-ratio (plot-aspect-ratio)]
#:legend-anchor [legend-anchor (plot-legend-anchor)]
#:out-file [out-file #f]
#:out-kind [out-kind 'auto])
(when out-file
(plot3d-file renderer-tree out-file out-kind
#:x-min x-min #:x-max x-max #:y-min y-min #:y-max y-max #:z-min z-min #:z-max z-max
#:width width #:height height #:title title
#:angle (or angle (plot3d-angle)) #:altitude (or altitude (plot3d-altitude))
#:x-label x-label #:y-label y-label #:z-label z-label #:legend-anchor legend-anchor
#:aspect-ratio aspect-ratio))
(plot3d-bitmap renderer-tree
#:x-min x-min #:x-max x-max #:y-min y-min #:y-max y-max #:z-min z-min #:z-max z-max
#:width width #:height height #:title title
#:angle (or angle (plot3d-angle)) #:altitude (or altitude (plot3d-altitude))
#:x-label x-label #:y-label y-label #:z-label z-label #:legend-anchor legend-anchor
#:aspect-ratio aspect-ratio))
| null | https://raw.githubusercontent.com/racket/plot/c4126001f2c609e36c3aa12f300e9c673ab1a806/plot-lib/plot/private/no-gui/plot-bitmap.rkt | racket | #lang typed/racket/base
(require typed/racket/draw
"../common/type-doc.rkt"
"../common/types.rkt"
"../common/parameters.rkt"
"../common/nonrenderer.rkt"
"../plot2d/renderer.rkt"
"../plot3d/renderer.rkt"
"plot2d.rkt"
"plot3d.rkt"
typed/racket/unsafe)
(unsafe-provide plot plot3d)
(:: plot
(->* [(Treeof (U renderer2d nonrenderer))]
[#:x-min (U Real #f) #:x-max (U Real #f)
#:y-min (U Real #f) #:y-max (U Real #f)
#:width Positive-Integer
#:height Positive-Integer
#:title (U String #f)
#:x-label (U String #f)
#:y-label (U String #f)
#:aspect-ratio (U Nonnegative-Real #f)
#:legend-anchor Anchor
#:out-file (U Path-String Output-Port #f)
#:out-kind (U 'auto Image-File-Format)]
(Instance (Class #:implements Bitmap% #:implements Plot-Metrics<%>))))
(define (plot renderer-tree
#:x-min [x-min #f] #:x-max [x-max #f]
#:y-min [y-min #f] #:y-max [y-max #f]
#:width [width (plot-width)]
#:height [height (plot-height)]
#:title [title (plot-title)]
#:x-label [x-label (plot-x-label)]
#:y-label [y-label (plot-y-label)]
#:aspect-ratio [aspect-ratio (plot-aspect-ratio)]
#:legend-anchor [legend-anchor (plot-legend-anchor)]
#:out-file [out-file #f]
#:out-kind [out-kind 'auto])
(when out-file
(plot-file renderer-tree out-file out-kind
#:x-min x-min #:x-max x-max #:y-min y-min #:y-max y-max #:width width #:height height
#:title title #:x-label x-label #:y-label y-label #:legend-anchor legend-anchor
#:aspect-ratio aspect-ratio))
(plot-bitmap renderer-tree
#:x-min x-min #:x-max x-max #:y-min y-min #:y-max y-max #:width width #:height height
#:title title #:x-label x-label #:y-label y-label #:legend-anchor legend-anchor
#:aspect-ratio aspect-ratio))
(:: plot3d
(->* [(Treeof (U renderer3d nonrenderer))]
[#:x-min (U Real #f) #:x-max (U Real #f)
#:y-min (U Real #f) #:y-max (U Real #f)
#:z-min (U Real #f) #:z-max (U Real #f)
#:width Positive-Integer
#:height Positive-Integer
#:angle Real #:altitude Real
#:title (U String #f)
#:x-label (U String #f)
#:y-label (U String #f)
#:z-label (U String #f)
#:aspect-ratio (U Nonnegative-Real #f)
#:legend-anchor Anchor
#:out-file (U Path-String Output-Port #f)
#:out-kind (U 'auto Image-File-Format)]
(Instance (Class #:implements Bitmap% #:implements Plot-Metrics<%>))))
(define (plot3d renderer-tree
#:x-min [x-min #f] #:x-max [x-max #f]
#:y-min [y-min #f] #:y-max [y-max #f]
#:z-min [z-min #f] #:z-max [z-max #f]
#:width [width (plot-width)]
#:height [height (plot-height)]
#:angle [angle (plot3d-angle)]
#:altitude [altitude (plot3d-altitude)]
#:title [title (plot-title)]
#:x-label [x-label (plot-x-label)]
#:y-label [y-label (plot-y-label)]
#:z-label [z-label (plot-z-label)]
#:aspect-ratio [aspect-ratio (plot-aspect-ratio)]
#:legend-anchor [legend-anchor (plot-legend-anchor)]
#:out-file [out-file #f]
#:out-kind [out-kind 'auto])
(when out-file
(plot3d-file renderer-tree out-file out-kind
#:x-min x-min #:x-max x-max #:y-min y-min #:y-max y-max #:z-min z-min #:z-max z-max
#:width width #:height height #:title title
#:angle (or angle (plot3d-angle)) #:altitude (or altitude (plot3d-altitude))
#:x-label x-label #:y-label y-label #:z-label z-label #:legend-anchor legend-anchor
#:aspect-ratio aspect-ratio))
(plot3d-bitmap renderer-tree
#:x-min x-min #:x-max x-max #:y-min y-min #:y-max y-max #:z-min z-min #:z-max z-max
#:width width #:height height #:title title
#:angle (or angle (plot3d-angle)) #:altitude (or altitude (plot3d-altitude))
#:x-label x-label #:y-label y-label #:z-label z-label #:legend-anchor legend-anchor
#:aspect-ratio aspect-ratio))
| |
57c14038a0c7904cfa852311d97a33d5eea9a21f6d62aa7bfec6f7cc1c7445e8 | nvim-treesitter/nvim-treesitter | locals.scm | ;; Definitions
(variable_declarator
. (identifier) @definition.var)
(variable_declarator
(tuple_pattern
(identifier) @definition.var))
(declaration_expression
name: (identifier) @definition.var)
(for_each_statement
left: (identifier) @definition.var)
(for_each_statement
left: (tuple_pattern
(identifier) @definition.var))
(parameter
(identifier) @definition.parameter)
(method_declaration
name: (identifier) @definition.method)
(local_function_statement
name: (identifier) @definition.method)
(property_declaration
name: (identifier) @definition)
(type_parameter
(identifier) @definition.type)
(class_declaration
name: (identifier) @definition)
;; References
(identifier) @reference
;; Scope
(block) @scope
| null | https://raw.githubusercontent.com/nvim-treesitter/nvim-treesitter/d8d5e4eb8100f402b27ae98b9de4db9363f2248f/queries/c_sharp/locals.scm | scheme | Definitions
References
Scope | (variable_declarator
. (identifier) @definition.var)
(variable_declarator
(tuple_pattern
(identifier) @definition.var))
(declaration_expression
name: (identifier) @definition.var)
(for_each_statement
left: (identifier) @definition.var)
(for_each_statement
left: (tuple_pattern
(identifier) @definition.var))
(parameter
(identifier) @definition.parameter)
(method_declaration
name: (identifier) @definition.method)
(local_function_statement
name: (identifier) @definition.method)
(property_declaration
name: (identifier) @definition)
(type_parameter
(identifier) @definition.type)
(class_declaration
name: (identifier) @definition)
(identifier) @reference
(block) @scope
|
376bfd205f30466485424146ecbf16d58b53df262da0ce5b94dd28ddcc14a4b4 | fakedata-haskell/fakedata | Futurama.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TemplateHaskell #
module Faker.Provider.Futurama where
import Config
import Control.Monad.Catch
import Data.Text (Text)
import Data.Vector (Vector)
import Data.Monoid ((<>))
import Data.Yaml
import Faker
import Faker.Internal
import Faker.Provider.TH
import Language.Haskell.TH
parseFuturama :: FromJSON a => FakerSettings -> Value -> Parser a
parseFuturama settings (Object obj) = do
en <- obj .: (getLocaleKey settings)
faker <- en .: "faker"
futurama <- faker .: "futurama"
pure futurama
parseFuturama settings val = fail $ "expected Object, but got " <> (show val)
parseFuturamaField ::
(FromJSON a, Monoid a) => FakerSettings -> AesonKey -> Value -> Parser a
parseFuturamaField settings txt val = do
futurama <- parseFuturama settings val
field <- futurama .:? txt .!= mempty
pure field
parseFuturamaFields ::
(FromJSON a, Monoid a) => FakerSettings -> [AesonKey] -> Value -> Parser a
parseFuturamaFields settings txts val = do
futurama <- parseFuturama settings val
helper futurama txts
where
helper :: (FromJSON a) => Value -> [AesonKey] -> Parser a
helper a [] = parseJSON a
helper (Object a) (x:xs) = do
field <- a .: x
helper field xs
helper a (x:xs) = fail $ "expect Object, but got " <> (show a)
parseUnresolvedFuturamaFields ::
(FromJSON a, Monoid a)
=> FakerSettings
-> [AesonKey]
-> Value
-> Parser (Unresolved a)
parseUnresolvedFuturamaFields settings txts val = do
futurama <- parseFuturama settings val
helper futurama txts
where
helper :: (FromJSON a) => Value -> [AesonKey] -> Parser (Unresolved a)
helper a [] = do
v <- parseJSON a
pure $ pure v
helper (Object a) (x:xs) = do
field <- a .: x
helper field xs
helper a _ = fail $ "expect Object, but got " <> (show a)
$(genParser "futurama" "characters")
$(genProvider "futurama" "characters")
$(genParser "futurama" "locations")
$(genProvider "futurama" "locations")
$(genParser "futurama" "quotes")
$(genProvider "futurama" "quotes")
$(genParser "futurama" "hermes_catchphrases")
$(genProvider "futurama" "hermes_catchphrases")
| null | https://raw.githubusercontent.com/fakedata-haskell/fakedata/7b0875067386e9bb844c8b985c901c91a58842ff/src/Faker/Provider/Futurama.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE TemplateHaskell #
module Faker.Provider.Futurama where
import Config
import Control.Monad.Catch
import Data.Text (Text)
import Data.Vector (Vector)
import Data.Monoid ((<>))
import Data.Yaml
import Faker
import Faker.Internal
import Faker.Provider.TH
import Language.Haskell.TH
parseFuturama :: FromJSON a => FakerSettings -> Value -> Parser a
parseFuturama settings (Object obj) = do
en <- obj .: (getLocaleKey settings)
faker <- en .: "faker"
futurama <- faker .: "futurama"
pure futurama
parseFuturama settings val = fail $ "expected Object, but got " <> (show val)
parseFuturamaField ::
(FromJSON a, Monoid a) => FakerSettings -> AesonKey -> Value -> Parser a
parseFuturamaField settings txt val = do
futurama <- parseFuturama settings val
field <- futurama .:? txt .!= mempty
pure field
parseFuturamaFields ::
(FromJSON a, Monoid a) => FakerSettings -> [AesonKey] -> Value -> Parser a
parseFuturamaFields settings txts val = do
futurama <- parseFuturama settings val
helper futurama txts
where
helper :: (FromJSON a) => Value -> [AesonKey] -> Parser a
helper a [] = parseJSON a
helper (Object a) (x:xs) = do
field <- a .: x
helper field xs
helper a (x:xs) = fail $ "expect Object, but got " <> (show a)
parseUnresolvedFuturamaFields ::
(FromJSON a, Monoid a)
=> FakerSettings
-> [AesonKey]
-> Value
-> Parser (Unresolved a)
parseUnresolvedFuturamaFields settings txts val = do
futurama <- parseFuturama settings val
helper futurama txts
where
helper :: (FromJSON a) => Value -> [AesonKey] -> Parser (Unresolved a)
helper a [] = do
v <- parseJSON a
pure $ pure v
helper (Object a) (x:xs) = do
field <- a .: x
helper field xs
helper a _ = fail $ "expect Object, but got " <> (show a)
$(genParser "futurama" "characters")
$(genProvider "futurama" "characters")
$(genParser "futurama" "locations")
$(genProvider "futurama" "locations")
$(genParser "futurama" "quotes")
$(genProvider "futurama" "quotes")
$(genParser "futurama" "hermes_catchphrases")
$(genProvider "futurama" "hermes_catchphrases")
|
84a31f13edd94c56cf0587aa75f61d0e536b0626bfe74e4d74d0b54e9a71676d | NoRedInk/haskell-libraries | QueryParser.hs | -- |
Parse some high - level information out of a query , for use in tracing .
-- We try to find the query method (SELECT / INSERT / ...) and queried table
in the root SQL query . We assume the root query to be the first query not
-- in a sub query. We assume everything between parens `( ... )` to be a
-- sub query.
module Postgres.QueryParser
( parse,
QueryMeta (..),
)
where
import Control.Applicative
import Control.Monad (void)
import Data.Attoparsec.Text (Parser, anyChar, asciiCI, char, inClass, manyTill, skipSpace, space, takeWhile)
import qualified Data.Attoparsec.Text as Attoparsec
import Data.Foldable (asum)
import qualified List
import qualified Maybe
import qualified Text
import Prelude (Either (Left, Right))
parse :: Text -> QueryMeta
parse query =
case Attoparsec.parseOnly parser query of
Left _ ->
QueryMeta
{ queriedRelation =
Text.lines query
|> List.head
|> Maybe.withDefault "",
sqlOperation = "UNKNOWN"
}
Right result -> result
data QueryMeta = QueryMeta
{ queriedRelation :: Text,
sqlOperation :: Text
}
deriving (Eq, Show)
parser :: Parser QueryMeta
parser =
keepLooking
<| asum
[ delete,
insert,
select,
truncate',
update
]
keepLooking :: Parser a -> Parser a
keepLooking p = do
skipSpace
asum
1 . If we encounter sub queries ( bounded in parens ) , skip them first .
do
void <| some skipSubExpression
keepLooking p,
2 . Try to run the target parser .
p,
3 . Failing all else , move forward a word and try again .
do
void <| manyTill anyChar (space <|> char '(')
keepLooking p
]
skipSubExpression :: Parser ()
skipSubExpression = do
void <| char '('
void <| keepLooking (char ')')
delete :: Parser QueryMeta
delete = do
void <| asciiCI "DELETE"
skipSpace
void <| asciiCI "FROM"
skipSpace
queriedRelation <- tableName
pure QueryMeta {queriedRelation, sqlOperation = "DELETE"}
insert :: Parser QueryMeta
insert = do
void <| asciiCI "INSERT"
skipSpace
void <| asciiCI "INTO"
skipSpace
queriedRelation <- tableName
pure QueryMeta {queriedRelation, sqlOperation = "INSERT"}
select :: Parser QueryMeta
select = do
void <| asciiCI "SELECT"
keepLooking <| do
void <| asciiCI "FROM"
keepLooking <| do
queriedRelation <- tableName
pure QueryMeta {queriedRelation, sqlOperation = "SELECT"}
tableName :: Parser Text
tableName =
takeWhile (inClass "a-zA-Z0-9._")
truncate' :: Parser QueryMeta
truncate' = do
void <| asciiCI "UPDATE"
skipSpace
(asciiCI "ONLY" |> void) <|> pure ()
skipSpace
queriedRelation <- tableName
pure QueryMeta {queriedRelation, sqlOperation = "UPDATE"}
update :: Parser QueryMeta
update = do
void <| asciiCI "TRUNCATE"
skipSpace
(asciiCI "TABLE" |> void) <|> pure ()
(asciiCI "ONLY" |> void) <|> pure ()
skipSpace
queriedRelation <- tableName
pure QueryMeta {queriedRelation, sqlOperation = "TRUNCATE"}
| null | https://raw.githubusercontent.com/NoRedInk/haskell-libraries/7af1e05549e09d519b08ab49dff956b5a97d4f7e/nri-postgresql/src/Postgres/QueryParser.hs | haskell | |
We try to find the query method (SELECT / INSERT / ...) and queried table
in a sub query. We assume everything between parens `( ... )` to be a
sub query. | Parse some high - level information out of a query , for use in tracing .
in the root SQL query . We assume the root query to be the first query not
module Postgres.QueryParser
( parse,
QueryMeta (..),
)
where
import Control.Applicative
import Control.Monad (void)
import Data.Attoparsec.Text (Parser, anyChar, asciiCI, char, inClass, manyTill, skipSpace, space, takeWhile)
import qualified Data.Attoparsec.Text as Attoparsec
import Data.Foldable (asum)
import qualified List
import qualified Maybe
import qualified Text
import Prelude (Either (Left, Right))
parse :: Text -> QueryMeta
parse query =
case Attoparsec.parseOnly parser query of
Left _ ->
QueryMeta
{ queriedRelation =
Text.lines query
|> List.head
|> Maybe.withDefault "",
sqlOperation = "UNKNOWN"
}
Right result -> result
data QueryMeta = QueryMeta
{ queriedRelation :: Text,
sqlOperation :: Text
}
deriving (Eq, Show)
parser :: Parser QueryMeta
parser =
keepLooking
<| asum
[ delete,
insert,
select,
truncate',
update
]
keepLooking :: Parser a -> Parser a
keepLooking p = do
skipSpace
asum
1 . If we encounter sub queries ( bounded in parens ) , skip them first .
do
void <| some skipSubExpression
keepLooking p,
2 . Try to run the target parser .
p,
3 . Failing all else , move forward a word and try again .
do
void <| manyTill anyChar (space <|> char '(')
keepLooking p
]
skipSubExpression :: Parser ()
skipSubExpression = do
void <| char '('
void <| keepLooking (char ')')
delete :: Parser QueryMeta
delete = do
void <| asciiCI "DELETE"
skipSpace
void <| asciiCI "FROM"
skipSpace
queriedRelation <- tableName
pure QueryMeta {queriedRelation, sqlOperation = "DELETE"}
insert :: Parser QueryMeta
insert = do
void <| asciiCI "INSERT"
skipSpace
void <| asciiCI "INTO"
skipSpace
queriedRelation <- tableName
pure QueryMeta {queriedRelation, sqlOperation = "INSERT"}
select :: Parser QueryMeta
select = do
void <| asciiCI "SELECT"
keepLooking <| do
void <| asciiCI "FROM"
keepLooking <| do
queriedRelation <- tableName
pure QueryMeta {queriedRelation, sqlOperation = "SELECT"}
tableName :: Parser Text
tableName =
takeWhile (inClass "a-zA-Z0-9._")
truncate' :: Parser QueryMeta
truncate' = do
void <| asciiCI "UPDATE"
skipSpace
(asciiCI "ONLY" |> void) <|> pure ()
skipSpace
queriedRelation <- tableName
pure QueryMeta {queriedRelation, sqlOperation = "UPDATE"}
update :: Parser QueryMeta
update = do
void <| asciiCI "TRUNCATE"
skipSpace
(asciiCI "TABLE" |> void) <|> pure ()
(asciiCI "ONLY" |> void) <|> pure ()
skipSpace
queriedRelation <- tableName
pure QueryMeta {queriedRelation, sqlOperation = "TRUNCATE"}
|
56e188f835c5cba571a432da5a21cbb4d3deebcddd27f939cd3ce6902f0ce3e5 | herbelin/coq-hh | termdn.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
open Util
open Names
open Nameops
open Term
open Pattern
open Rawterm
open Libnames
open Nametab
Discrimination nets of terms .
See the module dn.ml for further explanations .
( 5/8/97 )
See the module dn.ml for further explanations.
Eduardo (5/8/97) *)
module Make =
functor (Z : Map.OrderedType) ->
struct
module X = struct
type t = constr_pattern
let compare = Pervasives.compare
end
type term_label =
| GRLabel of global_reference
| ProdLabel
| LambdaLabel
| SortLabel
module Y = struct
type t = term_label
let compare x y =
let make_name n =
match n with
| GRLabel(ConstRef con) ->
GRLabel(ConstRef(constant_of_kn(canonical_con con)))
| GRLabel(IndRef (kn,i)) ->
GRLabel(IndRef(mind_of_kn(canonical_mind kn),i))
| GRLabel(ConstructRef ((kn,i),j ))->
GRLabel(ConstructRef((mind_of_kn(canonical_mind kn),i),j))
| k -> k
in
Pervasives.compare (make_name x) (make_name y)
end
module Dn = Dn.Make(X)(Y)(Z)
type t = Dn.t
type 'a lookup_res = 'a Dn.lookup_res
(*If we have: f a b c ..., decomp gives: (f,[a;b;c;...])*)
let decomp =
let rec decrec acc c = match kind_of_term c with
| App (f,l) -> decrec (Array.fold_right (fun a l -> a::l) l acc) f
| Cast (c1,_,_) -> decrec acc c1
| _ -> (c,acc)
in
decrec []
let decomp_pat =
let rec decrec acc = function
| PApp (f,args) -> decrec (Array.to_list args @ acc) f
| c -> (c,acc)
in
decrec []
let constr_pat_discr t =
if not (occur_meta_pattern t) then
None
else
match decomp_pat t with
| PRef ((IndRef _) as ref), args
| PRef ((ConstructRef _ ) as ref), args -> Some (GRLabel ref,args)
| PRef ((VarRef v) as ref), args -> Some(GRLabel ref,args)
| _ -> None
let constr_pat_discr_st (idpred,cpred) t =
match decomp_pat t with
| PRef ((IndRef _) as ref), args
| PRef ((ConstructRef _ ) as ref), args -> Some (GRLabel ref,args)
| PRef ((VarRef v) as ref), args when not (Idpred.mem v idpred) ->
Some(GRLabel ref,args)
| PVar v, args when not (Idpred.mem v idpred) ->
Some(GRLabel (VarRef v),args)
| PRef ((ConstRef c) as ref), args when not (Cpred.mem c cpred) ->
Some (GRLabel ref, args)
| PProd (_, d, c), [] -> Some (ProdLabel, [d ; c])
| PLambda (_, d, c), l -> Some (LambdaLabel, [d ; c] @ l)
| PSort s, [] -> Some (SortLabel, [])
| _ -> None
open Dn
let constr_val_discr t =
let c, l = decomp t in
match kind_of_term c with
| Ind ind_sp -> Label(GRLabel (IndRef ind_sp),l)
| Construct cstr_sp -> Label(GRLabel (ConstructRef cstr_sp),l)
| Var id -> Label(GRLabel (VarRef id),l)
| Const _ -> Everything
| _ -> Nothing
let constr_val_discr_st (idpred,cpred) t =
let c, l = decomp t in
match kind_of_term c with
| Const c -> if Cpred.mem c cpred then Everything else Label(GRLabel (ConstRef c),l)
| Ind ind_sp -> Label(GRLabel (IndRef ind_sp),l)
| Construct cstr_sp -> Label(GRLabel (ConstructRef cstr_sp),l)
| Var id when not (Idpred.mem id idpred) -> Label(GRLabel (VarRef id),l)
| Prod (n, d, c) -> Label(ProdLabel, [d; c])
| Lambda (n, d, c) -> Label(LambdaLabel, [d; c] @ l)
| Sort _ -> Label (SortLabel, [])
| Evar _ -> Everything
| _ -> Nothing
let create = Dn.create
let add dn st = Dn.add dn (constr_pat_discr_st st)
let rmv dn st = Dn.rmv dn (constr_pat_discr_st st)
let lookup dn st t = Dn.lookup dn (constr_val_discr_st st) t
let app f dn = Dn.app f dn
end
| null | https://raw.githubusercontent.com/herbelin/coq-hh/296d03d5049fea661e8bdbaf305ed4bf6d2001d2/tactics/termdn.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
If we have: f a b c ..., decomp gives: (f,[a;b;c;...]) | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Util
open Names
open Nameops
open Term
open Pattern
open Rawterm
open Libnames
open Nametab
Discrimination nets of terms .
See the module dn.ml for further explanations .
( 5/8/97 )
See the module dn.ml for further explanations.
Eduardo (5/8/97) *)
module Make =
functor (Z : Map.OrderedType) ->
struct
module X = struct
type t = constr_pattern
let compare = Pervasives.compare
end
type term_label =
| GRLabel of global_reference
| ProdLabel
| LambdaLabel
| SortLabel
module Y = struct
type t = term_label
let compare x y =
let make_name n =
match n with
| GRLabel(ConstRef con) ->
GRLabel(ConstRef(constant_of_kn(canonical_con con)))
| GRLabel(IndRef (kn,i)) ->
GRLabel(IndRef(mind_of_kn(canonical_mind kn),i))
| GRLabel(ConstructRef ((kn,i),j ))->
GRLabel(ConstructRef((mind_of_kn(canonical_mind kn),i),j))
| k -> k
in
Pervasives.compare (make_name x) (make_name y)
end
module Dn = Dn.Make(X)(Y)(Z)
type t = Dn.t
type 'a lookup_res = 'a Dn.lookup_res
let decomp =
let rec decrec acc c = match kind_of_term c with
| App (f,l) -> decrec (Array.fold_right (fun a l -> a::l) l acc) f
| Cast (c1,_,_) -> decrec acc c1
| _ -> (c,acc)
in
decrec []
let decomp_pat =
let rec decrec acc = function
| PApp (f,args) -> decrec (Array.to_list args @ acc) f
| c -> (c,acc)
in
decrec []
let constr_pat_discr t =
if not (occur_meta_pattern t) then
None
else
match decomp_pat t with
| PRef ((IndRef _) as ref), args
| PRef ((ConstructRef _ ) as ref), args -> Some (GRLabel ref,args)
| PRef ((VarRef v) as ref), args -> Some(GRLabel ref,args)
| _ -> None
let constr_pat_discr_st (idpred,cpred) t =
match decomp_pat t with
| PRef ((IndRef _) as ref), args
| PRef ((ConstructRef _ ) as ref), args -> Some (GRLabel ref,args)
| PRef ((VarRef v) as ref), args when not (Idpred.mem v idpred) ->
Some(GRLabel ref,args)
| PVar v, args when not (Idpred.mem v idpred) ->
Some(GRLabel (VarRef v),args)
| PRef ((ConstRef c) as ref), args when not (Cpred.mem c cpred) ->
Some (GRLabel ref, args)
| PProd (_, d, c), [] -> Some (ProdLabel, [d ; c])
| PLambda (_, d, c), l -> Some (LambdaLabel, [d ; c] @ l)
| PSort s, [] -> Some (SortLabel, [])
| _ -> None
open Dn
let constr_val_discr t =
let c, l = decomp t in
match kind_of_term c with
| Ind ind_sp -> Label(GRLabel (IndRef ind_sp),l)
| Construct cstr_sp -> Label(GRLabel (ConstructRef cstr_sp),l)
| Var id -> Label(GRLabel (VarRef id),l)
| Const _ -> Everything
| _ -> Nothing
let constr_val_discr_st (idpred,cpred) t =
let c, l = decomp t in
match kind_of_term c with
| Const c -> if Cpred.mem c cpred then Everything else Label(GRLabel (ConstRef c),l)
| Ind ind_sp -> Label(GRLabel (IndRef ind_sp),l)
| Construct cstr_sp -> Label(GRLabel (ConstructRef cstr_sp),l)
| Var id when not (Idpred.mem id idpred) -> Label(GRLabel (VarRef id),l)
| Prod (n, d, c) -> Label(ProdLabel, [d; c])
| Lambda (n, d, c) -> Label(LambdaLabel, [d; c] @ l)
| Sort _ -> Label (SortLabel, [])
| Evar _ -> Everything
| _ -> Nothing
let create = Dn.create
let add dn st = Dn.add dn (constr_pat_discr_st st)
let rmv dn st = Dn.rmv dn (constr_pat_discr_st st)
let lookup dn st t = Dn.lookup dn (constr_val_discr_st st) t
let app f dn = Dn.app f dn
end
|
7d8b237d2be24b84980b42aaae78700120ee955a6cbe1110f6299f3daf7ee298 | Dasudian/DSDIN | dsdso_abi_tests.erl | -module(dsdso_abi_tests).
-include_lib("eunit/include/eunit.hrl").
encode_call_with_integer_test() ->
[64, 128, 42, 4, "main"] =
dsdso_test_utils:dump_words(
dsdso_abi:create_calldata("", "main", "42")).
| null | https://raw.githubusercontent.com/Dasudian/DSDIN/b27a437d8deecae68613604fffcbb9804a6f1729/apps/dsdsophia/test/dsdso_abi_tests.erl | erlang | -module(dsdso_abi_tests).
-include_lib("eunit/include/eunit.hrl").
encode_call_with_integer_test() ->
[64, 128, 42, 4, "main"] =
dsdso_test_utils:dump_words(
dsdso_abi:create_calldata("", "main", "42")).
| |
6ab608124b041c5f317923d5fb6c50b7bcde4ecf831495f788a1395854d60672 | c4-project/c4f | mem.ml | This file is part of c4f .
Copyright ( c ) 2018 - 2022 C4 Project
c4 t itself is licensed under the MIT License . See the LICENSE file in the
project root for more information .
Parts of c4 t are based on code from the Herdtools7 project
( ) : see the LICENSE.herd file in the
project root for more information .
Copyright (c) 2018-2022 C4 Project
c4t itself is licensed under the MIT License. See the LICENSE file in the
project root for more information.
Parts of c4t are based on code from the Herdtools7 project
() : see the LICENSE.herd file in the
project root for more information. *)
open Base
open Import
let%test_module "running payloads on test subject" =
( module struct
let test_action (payload : Src.Mem.Strengthen_payload.t) :
Fuzz.Subject.Test.t Fuzz.State.Monad.t =
Src.Mem.Strengthen.run
(Lazy.force Fuzz_test.Subject.Test_data.test)
~payload
let test (lpath : Fuzz.Path.t Lazy.t) (mo : C4f_fir.Mem_order.t)
(can_weaken : bool) : unit =
let path = Fuzz.Path_meta.With_meta.make (Lazy.force lpath) in
let pld = Src.Mem.Strengthen_payload.make ~path ~mo ~can_weaken in
let action = test_action pld in
Fuzz_test.Action.Test_utils.run_and_dump_test action
~initial_state:(Lazy.force Fuzz_test.State.Test_data.state)
let sc_action : Fuzz.Path.t Lazy.t =
Fuzz.Path.(
Fuzz_test.Subject.Test_data.Path.thread_0_stms @@ Stms.stm 0)
let rlx_action : Fuzz.Path.t Lazy.t =
Fuzz.Path.(
Fuzz_test.Subject.Test_data.Path.thread_0_stms @@ Stms.stm 2)
let nest_action : Fuzz.Path.t Lazy.t =
Fuzz.Path.(
Fuzz_test.Subject.Test_data.Path.thread_0_stms @@ Stms.in_stm 4
@@ Stm.in_if @@ If.in_branch true @@ Stms.stm 0)
let%expect_test "failed SC->RLX" =
test sc_action C4f_fir.Mem_order.Relaxed false ;
[%expect
{|
void
P0(bool a, atomic_bool b, atomic_int bar, bool barbaz, atomic_int *baz,
bool c, int d, int e, int foo, atomic_bool foobar, atomic_int *x,
atomic_int *y)
{
atomic_int r0 = 4004;
int r1 = 8008;
atomic_store_explicit(x, 42, memory_order_seq_cst);
;
atomic_store_explicit(y, foo, memory_order_relaxed);
if (foo == y)
{ atomic_store_explicit(x, 56, memory_order_seq_cst); kappa_kappa: ; }
if (false)
{
atomic_store_explicit(y,
atomic_load_explicit(x, memory_order_seq_cst),
memory_order_seq_cst);
}
do { atomic_store_explicit(x, 44, memory_order_seq_cst); } while (4 ==
5);
for (r1 = 0; r1 <= 2; r1++)
{ atomic_store_explicit(x, 99, memory_order_seq_cst); }
while (4 == 5) { atomic_store_explicit(x, 44, memory_order_seq_cst); }
}
void
P1(bool a, atomic_bool b, atomic_int bar, bool barbaz, atomic_int *baz,
bool c, int d, int e, int foo, atomic_bool foobar, atomic_int *x,
atomic_int *y)
{ loop: ; if (true) { } else { goto loop; } }
Vars:
a: bool, =false, @global, generated, []
b: atomic_bool, =true, @global, generated, []
bar: atomic_int, =?, @global, existing, []
barbaz: bool, =?, @global, existing, []
baz: atomic_int*, =?, @global, existing, []
c: bool, =?, @global, generated, []
d: int, =?, @global, existing, []
e: int, =?, @global, generated, []
foo: int, =?, @global, existing, []
foobar: atomic_bool, =?, @global, existing, []
x: atomic_int*, =27, @global, generated, []
y: atomic_int*, =53, @global, generated, []
0:r0: atomic_int, =4004, @P0, generated, []
0:r1: int, =8008, @P0, generated, []
1:r0: bool, =?, @P1, existing, []
1:r1: int, =?, @P1, existing, []
2:r0: int, =?, @P2, existing, []
2:r1: bool, =?, @P2, existing, []
3:r0: int*, =?, @P3, existing, [] |}]
let%expect_test "forced SC->RLX" =
test sc_action C4f_fir.Mem_order.Relaxed true ;
[%expect
{|
void
P0(bool a, atomic_bool b, atomic_int bar, bool barbaz, atomic_int *baz,
bool c, int d, int e, int foo, atomic_bool foobar, atomic_int *x,
atomic_int *y)
{
atomic_int r0 = 4004;
int r1 = 8008;
atomic_store_explicit(x, 42, memory_order_relaxed);
;
atomic_store_explicit(y, foo, memory_order_relaxed);
if (foo == y)
{ atomic_store_explicit(x, 56, memory_order_seq_cst); kappa_kappa: ; }
if (false)
{
atomic_store_explicit(y,
atomic_load_explicit(x, memory_order_seq_cst),
memory_order_seq_cst);
}
do { atomic_store_explicit(x, 44, memory_order_seq_cst); } while (4 ==
5);
for (r1 = 0; r1 <= 2; r1++)
{ atomic_store_explicit(x, 99, memory_order_seq_cst); }
while (4 == 5) { atomic_store_explicit(x, 44, memory_order_seq_cst); }
}
void
P1(bool a, atomic_bool b, atomic_int bar, bool barbaz, atomic_int *baz,
bool c, int d, int e, int foo, atomic_bool foobar, atomic_int *x,
atomic_int *y)
{ loop: ; if (true) { } else { goto loop; } }
Vars:
a: bool, =false, @global, generated, []
b: atomic_bool, =true, @global, generated, []
bar: atomic_int, =?, @global, existing, []
barbaz: bool, =?, @global, existing, []
baz: atomic_int*, =?, @global, existing, []
c: bool, =?, @global, generated, []
d: int, =?, @global, existing, []
e: int, =?, @global, generated, []
foo: int, =?, @global, existing, []
foobar: atomic_bool, =?, @global, existing, []
x: atomic_int*, =27, @global, generated, []
y: atomic_int*, =53, @global, generated, []
0:r0: atomic_int, =4004, @P0, generated, []
0:r1: int, =8008, @P0, generated, []
1:r0: bool, =?, @P1, existing, []
1:r1: int, =?, @P1, existing, []
2:r0: int, =?, @P2, existing, []
2:r1: bool, =?, @P2, existing, []
3:r0: int*, =?, @P3, existing, [] |}]
let%expect_test "successful RLX->SC" =
test rlx_action C4f_fir.Mem_order.Seq_cst false ;
[%expect
{|
void
P0(bool a, atomic_bool b, atomic_int bar, bool barbaz, atomic_int *baz,
bool c, int d, int e, int foo, atomic_bool foobar, atomic_int *x,
atomic_int *y)
{
atomic_int r0 = 4004;
int r1 = 8008;
atomic_store_explicit(x, 42, memory_order_seq_cst);
;
atomic_store_explicit(y, foo, memory_order_seq_cst);
if (foo == y)
{ atomic_store_explicit(x, 56, memory_order_seq_cst); kappa_kappa: ; }
if (false)
{
atomic_store_explicit(y,
atomic_load_explicit(x, memory_order_seq_cst),
memory_order_seq_cst);
}
do { atomic_store_explicit(x, 44, memory_order_seq_cst); } while (4 ==
5);
for (r1 = 0; r1 <= 2; r1++)
{ atomic_store_explicit(x, 99, memory_order_seq_cst); }
while (4 == 5) { atomic_store_explicit(x, 44, memory_order_seq_cst); }
}
void
P1(bool a, atomic_bool b, atomic_int bar, bool barbaz, atomic_int *baz,
bool c, int d, int e, int foo, atomic_bool foobar, atomic_int *x,
atomic_int *y)
{ loop: ; if (true) { } else { goto loop; } }
Vars:
a: bool, =false, @global, generated, []
b: atomic_bool, =true, @global, generated, []
bar: atomic_int, =?, @global, existing, []
barbaz: bool, =?, @global, existing, []
baz: atomic_int*, =?, @global, existing, []
c: bool, =?, @global, generated, []
d: int, =?, @global, existing, []
e: int, =?, @global, generated, []
foo: int, =?, @global, existing, []
foobar: atomic_bool, =?, @global, existing, []
x: atomic_int*, =27, @global, generated, []
y: atomic_int*, =53, @global, generated, []
0:r0: atomic_int, =4004, @P0, generated, []
0:r1: int, =8008, @P0, generated, []
1:r0: bool, =?, @P1, existing, []
1:r1: int, =?, @P1, existing, []
2:r0: int, =?, @P2, existing, []
2:r1: bool, =?, @P2, existing, []
3:r0: int*, =?, @P3, existing, [] |}]
let%expect_test "ignored RLX->ACQ" =
test rlx_action C4f_fir.Mem_order.Acquire true ;
[%expect
{|
void
P0(bool a, atomic_bool b, atomic_int bar, bool barbaz, atomic_int *baz,
bool c, int d, int e, int foo, atomic_bool foobar, atomic_int *x,
atomic_int *y)
{
atomic_int r0 = 4004;
int r1 = 8008;
atomic_store_explicit(x, 42, memory_order_seq_cst);
;
atomic_store_explicit(y, foo, memory_order_relaxed);
if (foo == y)
{ atomic_store_explicit(x, 56, memory_order_seq_cst); kappa_kappa: ; }
if (false)
{
atomic_store_explicit(y,
atomic_load_explicit(x, memory_order_seq_cst),
memory_order_seq_cst);
}
do { atomic_store_explicit(x, 44, memory_order_seq_cst); } while (4 ==
5);
for (r1 = 0; r1 <= 2; r1++)
{ atomic_store_explicit(x, 99, memory_order_seq_cst); }
while (4 == 5) { atomic_store_explicit(x, 44, memory_order_seq_cst); }
}
void
P1(bool a, atomic_bool b, atomic_int bar, bool barbaz, atomic_int *baz,
bool c, int d, int e, int foo, atomic_bool foobar, atomic_int *x,
atomic_int *y)
{ loop: ; if (true) { } else { goto loop; } }
Vars:
a: bool, =false, @global, generated, []
b: atomic_bool, =true, @global, generated, []
bar: atomic_int, =?, @global, existing, []
barbaz: bool, =?, @global, existing, []
baz: atomic_int*, =?, @global, existing, []
c: bool, =?, @global, generated, []
d: int, =?, @global, existing, []
e: int, =?, @global, generated, []
foo: int, =?, @global, existing, []
foobar: atomic_bool, =?, @global, existing, []
x: atomic_int*, =27, @global, generated, []
y: atomic_int*, =53, @global, generated, []
0:r0: atomic_int, =4004, @P0, generated, []
0:r1: int, =8008, @P0, generated, []
1:r0: bool, =?, @P1, existing, []
1:r1: int, =?, @P1, existing, []
2:r0: int, =?, @P2, existing, []
2:r1: bool, =?, @P2, existing, []
3:r0: int*, =?, @P3, existing, [] |}]
let%expect_test "part-ignored nested change (outer)" =
test nest_action C4f_fir.Mem_order.Acquire true ;
[%expect
{|
void
P0(bool a, atomic_bool b, atomic_int bar, bool barbaz, atomic_int *baz,
bool c, int d, int e, int foo, atomic_bool foobar, atomic_int *x,
atomic_int *y)
{
atomic_int r0 = 4004;
int r1 = 8008;
atomic_store_explicit(x, 42, memory_order_seq_cst);
;
atomic_store_explicit(y, foo, memory_order_relaxed);
if (foo == y)
{ atomic_store_explicit(x, 56, memory_order_seq_cst); kappa_kappa: ; }
if (false)
{
atomic_store_explicit(y,
atomic_load_explicit(x, memory_order_acquire),
memory_order_seq_cst);
}
do { atomic_store_explicit(x, 44, memory_order_seq_cst); } while (4 ==
5);
for (r1 = 0; r1 <= 2; r1++)
{ atomic_store_explicit(x, 99, memory_order_seq_cst); }
while (4 == 5) { atomic_store_explicit(x, 44, memory_order_seq_cst); }
}
void
P1(bool a, atomic_bool b, atomic_int bar, bool barbaz, atomic_int *baz,
bool c, int d, int e, int foo, atomic_bool foobar, atomic_int *x,
atomic_int *y)
{ loop: ; if (true) { } else { goto loop; } }
Vars:
a: bool, =false, @global, generated, []
b: atomic_bool, =true, @global, generated, []
bar: atomic_int, =?, @global, existing, []
barbaz: bool, =?, @global, existing, []
baz: atomic_int*, =?, @global, existing, []
c: bool, =?, @global, generated, []
d: int, =?, @global, existing, []
e: int, =?, @global, generated, []
foo: int, =?, @global, existing, []
foobar: atomic_bool, =?, @global, existing, []
x: atomic_int*, =27, @global, generated, []
y: atomic_int*, =53, @global, generated, []
0:r0: atomic_int, =4004, @P0, generated, []
0:r1: int, =8008, @P0, generated, []
1:r0: bool, =?, @P1, existing, []
1:r1: int, =?, @P1, existing, []
2:r0: int, =?, @P2, existing, []
2:r1: bool, =?, @P2, existing, []
3:r0: int*, =?, @P3, existing, [] |}]
let%expect_test "part-ignored nested change (inner)" =
test nest_action C4f_fir.Mem_order.Release true ;
[%expect
{|
void
P0(bool a, atomic_bool b, atomic_int bar, bool barbaz, atomic_int *baz,
bool c, int d, int e, int foo, atomic_bool foobar, atomic_int *x,
atomic_int *y)
{
atomic_int r0 = 4004;
int r1 = 8008;
atomic_store_explicit(x, 42, memory_order_seq_cst);
;
atomic_store_explicit(y, foo, memory_order_relaxed);
if (foo == y)
{ atomic_store_explicit(x, 56, memory_order_seq_cst); kappa_kappa: ; }
if (false)
{
atomic_store_explicit(y,
atomic_load_explicit(x, memory_order_seq_cst),
memory_order_release);
}
do { atomic_store_explicit(x, 44, memory_order_seq_cst); } while (4 ==
5);
for (r1 = 0; r1 <= 2; r1++)
{ atomic_store_explicit(x, 99, memory_order_seq_cst); }
while (4 == 5) { atomic_store_explicit(x, 44, memory_order_seq_cst); }
}
void
P1(bool a, atomic_bool b, atomic_int bar, bool barbaz, atomic_int *baz,
bool c, int d, int e, int foo, atomic_bool foobar, atomic_int *x,
atomic_int *y)
{ loop: ; if (true) { } else { goto loop; } }
Vars:
a: bool, =false, @global, generated, []
b: atomic_bool, =true, @global, generated, []
bar: atomic_int, =?, @global, existing, []
barbaz: bool, =?, @global, existing, []
baz: atomic_int*, =?, @global, existing, []
c: bool, =?, @global, generated, []
d: int, =?, @global, existing, []
e: int, =?, @global, generated, []
foo: int, =?, @global, existing, []
foobar: atomic_bool, =?, @global, existing, []
x: atomic_int*, =27, @global, generated, []
y: atomic_int*, =53, @global, generated, []
0:r0: atomic_int, =4004, @P0, generated, []
0:r1: int, =8008, @P0, generated, []
1:r0: bool, =?, @P1, existing, []
1:r1: int, =?, @P1, existing, []
2:r0: int, =?, @P2, existing, []
2:r1: bool, =?, @P2, existing, []
3:r0: int*, =?, @P3, existing, [] |}]
end )
| null | https://raw.githubusercontent.com/c4-project/c4f/8939477732861789abc807c8c1532a302b2848a5/lib/fuzz_actions/test/mem.ml | ocaml | This file is part of c4f .
Copyright ( c ) 2018 - 2022 C4 Project
c4 t itself is licensed under the MIT License . See the LICENSE file in the
project root for more information .
Parts of c4 t are based on code from the Herdtools7 project
( ) : see the LICENSE.herd file in the
project root for more information .
Copyright (c) 2018-2022 C4 Project
c4t itself is licensed under the MIT License. See the LICENSE file in the
project root for more information.
Parts of c4t are based on code from the Herdtools7 project
() : see the LICENSE.herd file in the
project root for more information. *)
open Base
open Import
let%test_module "running payloads on test subject" =
( module struct
let test_action (payload : Src.Mem.Strengthen_payload.t) :
Fuzz.Subject.Test.t Fuzz.State.Monad.t =
Src.Mem.Strengthen.run
(Lazy.force Fuzz_test.Subject.Test_data.test)
~payload
let test (lpath : Fuzz.Path.t Lazy.t) (mo : C4f_fir.Mem_order.t)
(can_weaken : bool) : unit =
let path = Fuzz.Path_meta.With_meta.make (Lazy.force lpath) in
let pld = Src.Mem.Strengthen_payload.make ~path ~mo ~can_weaken in
let action = test_action pld in
Fuzz_test.Action.Test_utils.run_and_dump_test action
~initial_state:(Lazy.force Fuzz_test.State.Test_data.state)
let sc_action : Fuzz.Path.t Lazy.t =
Fuzz.Path.(
Fuzz_test.Subject.Test_data.Path.thread_0_stms @@ Stms.stm 0)
let rlx_action : Fuzz.Path.t Lazy.t =
Fuzz.Path.(
Fuzz_test.Subject.Test_data.Path.thread_0_stms @@ Stms.stm 2)
let nest_action : Fuzz.Path.t Lazy.t =
Fuzz.Path.(
Fuzz_test.Subject.Test_data.Path.thread_0_stms @@ Stms.in_stm 4
@@ Stm.in_if @@ If.in_branch true @@ Stms.stm 0)
let%expect_test "failed SC->RLX" =
test sc_action C4f_fir.Mem_order.Relaxed false ;
[%expect
{|
void
P0(bool a, atomic_bool b, atomic_int bar, bool barbaz, atomic_int *baz,
bool c, int d, int e, int foo, atomic_bool foobar, atomic_int *x,
atomic_int *y)
{
atomic_int r0 = 4004;
int r1 = 8008;
atomic_store_explicit(x, 42, memory_order_seq_cst);
;
atomic_store_explicit(y, foo, memory_order_relaxed);
if (foo == y)
{ atomic_store_explicit(x, 56, memory_order_seq_cst); kappa_kappa: ; }
if (false)
{
atomic_store_explicit(y,
atomic_load_explicit(x, memory_order_seq_cst),
memory_order_seq_cst);
}
do { atomic_store_explicit(x, 44, memory_order_seq_cst); } while (4 ==
5);
for (r1 = 0; r1 <= 2; r1++)
{ atomic_store_explicit(x, 99, memory_order_seq_cst); }
while (4 == 5) { atomic_store_explicit(x, 44, memory_order_seq_cst); }
}
void
P1(bool a, atomic_bool b, atomic_int bar, bool barbaz, atomic_int *baz,
bool c, int d, int e, int foo, atomic_bool foobar, atomic_int *x,
atomic_int *y)
{ loop: ; if (true) { } else { goto loop; } }
Vars:
a: bool, =false, @global, generated, []
b: atomic_bool, =true, @global, generated, []
bar: atomic_int, =?, @global, existing, []
barbaz: bool, =?, @global, existing, []
baz: atomic_int*, =?, @global, existing, []
c: bool, =?, @global, generated, []
d: int, =?, @global, existing, []
e: int, =?, @global, generated, []
foo: int, =?, @global, existing, []
foobar: atomic_bool, =?, @global, existing, []
x: atomic_int*, =27, @global, generated, []
y: atomic_int*, =53, @global, generated, []
0:r0: atomic_int, =4004, @P0, generated, []
0:r1: int, =8008, @P0, generated, []
1:r0: bool, =?, @P1, existing, []
1:r1: int, =?, @P1, existing, []
2:r0: int, =?, @P2, existing, []
2:r1: bool, =?, @P2, existing, []
3:r0: int*, =?, @P3, existing, [] |}]
let%expect_test "forced SC->RLX" =
test sc_action C4f_fir.Mem_order.Relaxed true ;
[%expect
{|
void
P0(bool a, atomic_bool b, atomic_int bar, bool barbaz, atomic_int *baz,
bool c, int d, int e, int foo, atomic_bool foobar, atomic_int *x,
atomic_int *y)
{
atomic_int r0 = 4004;
int r1 = 8008;
atomic_store_explicit(x, 42, memory_order_relaxed);
;
atomic_store_explicit(y, foo, memory_order_relaxed);
if (foo == y)
{ atomic_store_explicit(x, 56, memory_order_seq_cst); kappa_kappa: ; }
if (false)
{
atomic_store_explicit(y,
atomic_load_explicit(x, memory_order_seq_cst),
memory_order_seq_cst);
}
do { atomic_store_explicit(x, 44, memory_order_seq_cst); } while (4 ==
5);
for (r1 = 0; r1 <= 2; r1++)
{ atomic_store_explicit(x, 99, memory_order_seq_cst); }
while (4 == 5) { atomic_store_explicit(x, 44, memory_order_seq_cst); }
}
void
P1(bool a, atomic_bool b, atomic_int bar, bool barbaz, atomic_int *baz,
bool c, int d, int e, int foo, atomic_bool foobar, atomic_int *x,
atomic_int *y)
{ loop: ; if (true) { } else { goto loop; } }
Vars:
a: bool, =false, @global, generated, []
b: atomic_bool, =true, @global, generated, []
bar: atomic_int, =?, @global, existing, []
barbaz: bool, =?, @global, existing, []
baz: atomic_int*, =?, @global, existing, []
c: bool, =?, @global, generated, []
d: int, =?, @global, existing, []
e: int, =?, @global, generated, []
foo: int, =?, @global, existing, []
foobar: atomic_bool, =?, @global, existing, []
x: atomic_int*, =27, @global, generated, []
y: atomic_int*, =53, @global, generated, []
0:r0: atomic_int, =4004, @P0, generated, []
0:r1: int, =8008, @P0, generated, []
1:r0: bool, =?, @P1, existing, []
1:r1: int, =?, @P1, existing, []
2:r0: int, =?, @P2, existing, []
2:r1: bool, =?, @P2, existing, []
3:r0: int*, =?, @P3, existing, [] |}]
let%expect_test "successful RLX->SC" =
test rlx_action C4f_fir.Mem_order.Seq_cst false ;
[%expect
{|
void
P0(bool a, atomic_bool b, atomic_int bar, bool barbaz, atomic_int *baz,
bool c, int d, int e, int foo, atomic_bool foobar, atomic_int *x,
atomic_int *y)
{
atomic_int r0 = 4004;
int r1 = 8008;
atomic_store_explicit(x, 42, memory_order_seq_cst);
;
atomic_store_explicit(y, foo, memory_order_seq_cst);
if (foo == y)
{ atomic_store_explicit(x, 56, memory_order_seq_cst); kappa_kappa: ; }
if (false)
{
atomic_store_explicit(y,
atomic_load_explicit(x, memory_order_seq_cst),
memory_order_seq_cst);
}
do { atomic_store_explicit(x, 44, memory_order_seq_cst); } while (4 ==
5);
for (r1 = 0; r1 <= 2; r1++)
{ atomic_store_explicit(x, 99, memory_order_seq_cst); }
while (4 == 5) { atomic_store_explicit(x, 44, memory_order_seq_cst); }
}
void
P1(bool a, atomic_bool b, atomic_int bar, bool barbaz, atomic_int *baz,
bool c, int d, int e, int foo, atomic_bool foobar, atomic_int *x,
atomic_int *y)
{ loop: ; if (true) { } else { goto loop; } }
Vars:
a: bool, =false, @global, generated, []
b: atomic_bool, =true, @global, generated, []
bar: atomic_int, =?, @global, existing, []
barbaz: bool, =?, @global, existing, []
baz: atomic_int*, =?, @global, existing, []
c: bool, =?, @global, generated, []
d: int, =?, @global, existing, []
e: int, =?, @global, generated, []
foo: int, =?, @global, existing, []
foobar: atomic_bool, =?, @global, existing, []
x: atomic_int*, =27, @global, generated, []
y: atomic_int*, =53, @global, generated, []
0:r0: atomic_int, =4004, @P0, generated, []
0:r1: int, =8008, @P0, generated, []
1:r0: bool, =?, @P1, existing, []
1:r1: int, =?, @P1, existing, []
2:r0: int, =?, @P2, existing, []
2:r1: bool, =?, @P2, existing, []
3:r0: int*, =?, @P3, existing, [] |}]
let%expect_test "ignored RLX->ACQ" =
test rlx_action C4f_fir.Mem_order.Acquire true ;
[%expect
{|
void
P0(bool a, atomic_bool b, atomic_int bar, bool barbaz, atomic_int *baz,
bool c, int d, int e, int foo, atomic_bool foobar, atomic_int *x,
atomic_int *y)
{
atomic_int r0 = 4004;
int r1 = 8008;
atomic_store_explicit(x, 42, memory_order_seq_cst);
;
atomic_store_explicit(y, foo, memory_order_relaxed);
if (foo == y)
{ atomic_store_explicit(x, 56, memory_order_seq_cst); kappa_kappa: ; }
if (false)
{
atomic_store_explicit(y,
atomic_load_explicit(x, memory_order_seq_cst),
memory_order_seq_cst);
}
do { atomic_store_explicit(x, 44, memory_order_seq_cst); } while (4 ==
5);
for (r1 = 0; r1 <= 2; r1++)
{ atomic_store_explicit(x, 99, memory_order_seq_cst); }
while (4 == 5) { atomic_store_explicit(x, 44, memory_order_seq_cst); }
}
void
P1(bool a, atomic_bool b, atomic_int bar, bool barbaz, atomic_int *baz,
bool c, int d, int e, int foo, atomic_bool foobar, atomic_int *x,
atomic_int *y)
{ loop: ; if (true) { } else { goto loop; } }
Vars:
a: bool, =false, @global, generated, []
b: atomic_bool, =true, @global, generated, []
bar: atomic_int, =?, @global, existing, []
barbaz: bool, =?, @global, existing, []
baz: atomic_int*, =?, @global, existing, []
c: bool, =?, @global, generated, []
d: int, =?, @global, existing, []
e: int, =?, @global, generated, []
foo: int, =?, @global, existing, []
foobar: atomic_bool, =?, @global, existing, []
x: atomic_int*, =27, @global, generated, []
y: atomic_int*, =53, @global, generated, []
0:r0: atomic_int, =4004, @P0, generated, []
0:r1: int, =8008, @P0, generated, []
1:r0: bool, =?, @P1, existing, []
1:r1: int, =?, @P1, existing, []
2:r0: int, =?, @P2, existing, []
2:r1: bool, =?, @P2, existing, []
3:r0: int*, =?, @P3, existing, [] |}]
let%expect_test "part-ignored nested change (outer)" =
test nest_action C4f_fir.Mem_order.Acquire true ;
[%expect
{|
void
P0(bool a, atomic_bool b, atomic_int bar, bool barbaz, atomic_int *baz,
bool c, int d, int e, int foo, atomic_bool foobar, atomic_int *x,
atomic_int *y)
{
atomic_int r0 = 4004;
int r1 = 8008;
atomic_store_explicit(x, 42, memory_order_seq_cst);
;
atomic_store_explicit(y, foo, memory_order_relaxed);
if (foo == y)
{ atomic_store_explicit(x, 56, memory_order_seq_cst); kappa_kappa: ; }
if (false)
{
atomic_store_explicit(y,
atomic_load_explicit(x, memory_order_acquire),
memory_order_seq_cst);
}
do { atomic_store_explicit(x, 44, memory_order_seq_cst); } while (4 ==
5);
for (r1 = 0; r1 <= 2; r1++)
{ atomic_store_explicit(x, 99, memory_order_seq_cst); }
while (4 == 5) { atomic_store_explicit(x, 44, memory_order_seq_cst); }
}
void
P1(bool a, atomic_bool b, atomic_int bar, bool barbaz, atomic_int *baz,
bool c, int d, int e, int foo, atomic_bool foobar, atomic_int *x,
atomic_int *y)
{ loop: ; if (true) { } else { goto loop; } }
Vars:
a: bool, =false, @global, generated, []
b: atomic_bool, =true, @global, generated, []
bar: atomic_int, =?, @global, existing, []
barbaz: bool, =?, @global, existing, []
baz: atomic_int*, =?, @global, existing, []
c: bool, =?, @global, generated, []
d: int, =?, @global, existing, []
e: int, =?, @global, generated, []
foo: int, =?, @global, existing, []
foobar: atomic_bool, =?, @global, existing, []
x: atomic_int*, =27, @global, generated, []
y: atomic_int*, =53, @global, generated, []
0:r0: atomic_int, =4004, @P0, generated, []
0:r1: int, =8008, @P0, generated, []
1:r0: bool, =?, @P1, existing, []
1:r1: int, =?, @P1, existing, []
2:r0: int, =?, @P2, existing, []
2:r1: bool, =?, @P2, existing, []
3:r0: int*, =?, @P3, existing, [] |}]
let%expect_test "part-ignored nested change (inner)" =
test nest_action C4f_fir.Mem_order.Release true ;
[%expect
{|
void
P0(bool a, atomic_bool b, atomic_int bar, bool barbaz, atomic_int *baz,
bool c, int d, int e, int foo, atomic_bool foobar, atomic_int *x,
atomic_int *y)
{
atomic_int r0 = 4004;
int r1 = 8008;
atomic_store_explicit(x, 42, memory_order_seq_cst);
;
atomic_store_explicit(y, foo, memory_order_relaxed);
if (foo == y)
{ atomic_store_explicit(x, 56, memory_order_seq_cst); kappa_kappa: ; }
if (false)
{
atomic_store_explicit(y,
atomic_load_explicit(x, memory_order_seq_cst),
memory_order_release);
}
do { atomic_store_explicit(x, 44, memory_order_seq_cst); } while (4 ==
5);
for (r1 = 0; r1 <= 2; r1++)
{ atomic_store_explicit(x, 99, memory_order_seq_cst); }
while (4 == 5) { atomic_store_explicit(x, 44, memory_order_seq_cst); }
}
void
P1(bool a, atomic_bool b, atomic_int bar, bool barbaz, atomic_int *baz,
bool c, int d, int e, int foo, atomic_bool foobar, atomic_int *x,
atomic_int *y)
{ loop: ; if (true) { } else { goto loop; } }
Vars:
a: bool, =false, @global, generated, []
b: atomic_bool, =true, @global, generated, []
bar: atomic_int, =?, @global, existing, []
barbaz: bool, =?, @global, existing, []
baz: atomic_int*, =?, @global, existing, []
c: bool, =?, @global, generated, []
d: int, =?, @global, existing, []
e: int, =?, @global, generated, []
foo: int, =?, @global, existing, []
foobar: atomic_bool, =?, @global, existing, []
x: atomic_int*, =27, @global, generated, []
y: atomic_int*, =53, @global, generated, []
0:r0: atomic_int, =4004, @P0, generated, []
0:r1: int, =8008, @P0, generated, []
1:r0: bool, =?, @P1, existing, []
1:r1: int, =?, @P1, existing, []
2:r0: int, =?, @P2, existing, []
2:r1: bool, =?, @P2, existing, []
3:r0: int*, =?, @P3, existing, [] |}]
end )
| |
2146753ced1e7e7158154451fc16e80b6822fd89c0462794c03bfd60daa85a83 | yav/hobbit | MonadIO.hs | module Type.MonadIO where
import AST
import Data.IORef
import Utils
import Error
getVar :: TyVar -> IO (Maybe Type)
getVar (TyVar _ r _) = readIORef r
getVar (TyUser {}) = return Nothing
setVar :: TyVar -> Type -> IO ()
setVar (TyVar _ r _) t = writeIORef r (Just t)
setVar (TyUser {}) _ = "setVar" `unexpected` "TyUser"
class TypeIO t where
sameIO :: t -> t -> IO Bool
: Should we expand ty.syns ?
instance TypeIO t => TypeIO [t] where
sameIO (t:ts) (t':ts') = do same <- sameIO t t'
if same then sameIO ts ts'
else return False
sameIO [] [] = return True
sameIO _ _ = return False
pruneIO b ts = forEach ts (pruneIO b)
instance TypeIO Type where
sameIO t1 t2 = sameP # pruneIO True t1 <## pruneIO True t2
where
sameP (TApp t1 t2) (TApp t1' t2') = do x <- sameIO t1 t1'
if x then sameIO t2 t2'
else return False
sameP (TCon x) (TCon y) = return (x == y)
sameP (TFree x) (TFree y) = return (x == y)
-- XXX: Cannot happen
sameP (TSyn _ _ t) (TSyn _ _ t') = sameIO t t'
sameP _ _ = return False
pruneIO b a@(TFree x) = do t <- getVar x
case t of
Just t -> do t' <- pruneIO b t
setVar x t'
return t'
Nothing -> return a
pruneIO True (TSyn _ _ t) = pruneIO True t
pruneIO _ t = return t
instance TypeIO Pred where
sameIO (CIn c ts) (CIn c' ts')
| c == c' = sameIO ts ts'
| otherwise = return False
pruneIO b (CIn c ts) = CIn c # pruneIO b ts
instance TypeIO Goal where
sameIO (Ev x p) (Ev y q)
| x == y = sameIO p q
| otherwise = return False
pruneIO b (Ev x p) = Ev x # pruneIO b p
| null | https://raw.githubusercontent.com/yav/hobbit/31414ba1188f4b39620c2553b45b9e4d4aa40169/src/Type/MonadIO.hs | haskell | XXX: Cannot happen | module Type.MonadIO where
import AST
import Data.IORef
import Utils
import Error
getVar :: TyVar -> IO (Maybe Type)
getVar (TyVar _ r _) = readIORef r
getVar (TyUser {}) = return Nothing
setVar :: TyVar -> Type -> IO ()
setVar (TyVar _ r _) t = writeIORef r (Just t)
setVar (TyUser {}) _ = "setVar" `unexpected` "TyUser"
class TypeIO t where
sameIO :: t -> t -> IO Bool
: Should we expand ty.syns ?
instance TypeIO t => TypeIO [t] where
sameIO (t:ts) (t':ts') = do same <- sameIO t t'
if same then sameIO ts ts'
else return False
sameIO [] [] = return True
sameIO _ _ = return False
pruneIO b ts = forEach ts (pruneIO b)
instance TypeIO Type where
sameIO t1 t2 = sameP # pruneIO True t1 <## pruneIO True t2
where
sameP (TApp t1 t2) (TApp t1' t2') = do x <- sameIO t1 t1'
if x then sameIO t2 t2'
else return False
sameP (TCon x) (TCon y) = return (x == y)
sameP (TFree x) (TFree y) = return (x == y)
sameP (TSyn _ _ t) (TSyn _ _ t') = sameIO t t'
sameP _ _ = return False
pruneIO b a@(TFree x) = do t <- getVar x
case t of
Just t -> do t' <- pruneIO b t
setVar x t'
return t'
Nothing -> return a
pruneIO True (TSyn _ _ t) = pruneIO True t
pruneIO _ t = return t
instance TypeIO Pred where
sameIO (CIn c ts) (CIn c' ts')
| c == c' = sameIO ts ts'
| otherwise = return False
pruneIO b (CIn c ts) = CIn c # pruneIO b ts
instance TypeIO Goal where
sameIO (Ev x p) (Ev y q)
| x == y = sameIO p q
| otherwise = return False
pruneIO b (Ev x p) = Ev x # pruneIO b p
|
5689f5c2a401810ba07e5fa927c0d794c2119d219faad4b574d891dd2c33251f | marigold-dev/easier-proofs | main.ml | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2021 Marigold < >
(* *)
(* 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 Easier_proof.DslProp
open Easier_proof.GenerateProofs
open Format
open Stdio
let bool_properties =
to_proofs
[ block "Conjuction property of Bool"
[ prop "andb_true"
~context:(forall [("b", "boolean")])
( atom "andb b True" =.= atom "b" >> case "b"
&^ (atom "andb True b" =.= atom "b" >> straight) ) ] ]
let () =
if Array.length Sys.argv = 2 then
let filename = Sys.argv.(1) in
Out_channel.with_file ~append:true ~fail_if_exists:false filename
~f:(fun out ->
let fmt = formatter_of_out_channel out in
generate_proof fmt bool_properties ;
close_out out )
else fprintf err_formatter "target file name missing"
| null | https://raw.githubusercontent.com/marigold-dev/easier-proofs/49aa431be997df8c7363c8a81f7b64c0c70af0a8/examples/bool/bin/main.ml | 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 ) 2021 Marigold < >
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 Easier_proof.DslProp
open Easier_proof.GenerateProofs
open Format
open Stdio
let bool_properties =
to_proofs
[ block "Conjuction property of Bool"
[ prop "andb_true"
~context:(forall [("b", "boolean")])
( atom "andb b True" =.= atom "b" >> case "b"
&^ (atom "andb True b" =.= atom "b" >> straight) ) ] ]
let () =
if Array.length Sys.argv = 2 then
let filename = Sys.argv.(1) in
Out_channel.with_file ~append:true ~fail_if_exists:false filename
~f:(fun out ->
let fmt = formatter_of_out_channel out in
generate_proof fmt bool_properties ;
close_out out )
else fprintf err_formatter "target file name missing"
|
804b4c663dd884abe715447ae7902748af0dfac360058a13e5ed73ce5276c97a | yoriyuki/Camomile | tbl31.ml | (** Tbl31 : fast table keyed by integers *)
Copyright ( C ) 2002 , 2003
(* 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 of
the License , or ( at your option ) any later version .
As a special exception to the GNU Library General Public License , you
(* may link, statically or dynamically, a "work that uses this library" *)
(* with a publicly distributed version of this library to produce an *)
(* executable file containing portions of this library, and distribute *)
(* that executable file under terms of your choice, without any of the *)
additional requirements listed in clause 6 of the GNU Library General
(* Public License. By "a publicly distributed version of this library", *)
we mean either the unmodified Library as distributed by the authors ,
(* or a modified version of this library that is distributed under the *)
conditions defined in clause 3 of the GNU Library General Public
(* License. This exception does not however invalidate any other reasons *)
why the executable file might be covered by the GNU Library General
(* Public License . *)
(* 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
(* You can contact the authour by sending email to *)
(* *)
CRC - hash , algorithm comes from addnode.c / pathalias
31 - bits CRC - polynomial , by
let poly = 0x48000000
let crc_tbl = Array.init 128 (fun i ->
let rec loop j sum =
if j < 0 then sum else
if i land (1 lsl j) <> 0 then
loop (j - 1) (sum lxor (poly lsr j))
else
loop (j - 1) sum in
loop (7 - 1) 0)
let byte3 n = n lsr 24 land 127
let byte2 n = n lsr 16 land 255
let byte1 n = n lsr 8 land 255
let byte0 n = n land 255
let (lsl) x n =
if n >= Sys.word_size then 0 else
if n <= ~- Sys.word_size then 0 else
if n < 0 then x lsr (~-n) else
x lsl n
type 'a tbl = 'a array array array array
type 'a t = 'a tbl
type 'a tagged = Tag of 'a * int
let untag (Tag (a, _)) = a
let id (Tag (_, n)) = n
let get tbl n =
let lev = Array.unsafe_get tbl (byte3 n) in
let lev = Array.unsafe_get lev (byte2 n) in
let lev = Array.unsafe_get lev (byte1 n) in
Array.unsafe_get lev (byte0 n)
let get tbl n =
Printf.printf " level 3 % d " ( Array.length tbl ) ; print_newline ( ) ;
let lev = tbl.(byte3 n ) in
Printf.printf " level 2 % d " ( Array.length tbl ) ; print_newline ( ) ;
let lev = lev.(byte2 n ) in
Printf.printf " level 1 % d " ( Array.length tbl ) ; print_newline ( ) ;
let lev = lev.(byte1 n ) in
Printf.printf " level 0 % d " ( Array.length tbl ) ; print_newline ( ) ;
lev.(byte0 n )
Printf.printf "level 3 %d" (Array.length tbl); print_newline ();
let lev = tbl.(byte3 n) in
Printf.printf "level 2 %d" (Array.length tbl); print_newline ();
let lev = lev.(byte2 n) in
Printf.printf "level 1 %d" (Array.length tbl); print_newline ();
let lev = lev.(byte1 n) in
Printf.printf "level 0 %d" (Array.length tbl); print_newline ();
lev.(byte0 n) *)
module type NodeType = sig
type elt
type t
val level : int
val make : elt -> t tagged
val of_map : int -> elt -> elt IMap.t -> t tagged
val of_set : int -> elt -> ISet.t -> elt -> t tagged
end
module MakeNode (Sub : NodeType) = struct
type elt = Sub.elt
type node = Sub.t array
type t = node
let level = Sub.level + 1
module NodeHash = struct
type t = node tagged
let equal x y =
let a = untag x in
let b = untag y in
let rec loop i =
if i < 0 then true else
if a.(i) == b.(i) then loop (i - 1) else
false in
loop (if level = 3 then 127 else 255)
let hash = id
end
module NodePool = Weak.Make (NodeHash)
let pool = NodePool.create 256
let crc_hash v =
let rec loop i sum =
if i < 0 then sum else
let a = id v.(i) in
let sum = sum lsr 7 lxor crc_tbl.(sum lxor (byte3 a) land 0x7f) in
let sum = sum lsr 7 lxor crc_tbl.(sum lxor (byte2 a) land 0x7f) in
let sum = sum lsr 7 lxor crc_tbl.(sum lxor (byte1 a) land 0x7f) in
let sum = sum lsr 7 lxor crc_tbl.(sum lxor (byte0 a) land 0x7f) in
loop (i - 1) sum in
loop (if level = 3 then 127 else 255) 0
let hashcons a =
let n = crc_hash a in
let b = Array.map untag a in
prerr_int ( Array.length b ) ; ( ) ;
let x = Tag (b, n) in
try NodePool.find pool x with Not_found ->
NodePool.add pool x;
x
let make_raw def =
Array.make (if level = 3 then 128 else 256) (Sub.make def)
let make def = hashcons (make_raw def)
let of_map n0 def m =
let a = make_raw def in begin
if IMap.is_empty m then () else
let l = AvlTree.left_branch m in
let r = AvlTree.right_branch m in
if IMap.is_empty l && IMap.is_empty r then
let k1, k2, v = AvlTree.root m in
let i1 = (k1 - n0) lsr (8 * level) in
let n1 = n0 lor (i1 lsl (8 * level)) in
let n2 = n1 lor (1 lsl (8 * level) - 1) in
a.(i1) <- Sub.of_map n1 def (IMap.until n2 (IMap.from n1 m));
let i2 = (k2 - n0) lsr (8 * level) in
if i1 <> i2 then
let n1 = n0 lor (i2 lsl (8 * level)) in
let n2 = n1 lor (1 lsl (8 * level) - 1) in
a.(i2) <- Sub.of_map n1 def (IMap.until n2 (IMap.from n1 m));
let b = Sub.make v in
for i = i1 + 1 to i2 - 1 do a.(i) <- b done;
else ()
else
for i = 0 to if level = 3 then 127 else 255 do
let n1 = n0 lor (i lsl (8 * level)) in
let n2 = n1 lor (1 lsl (8 * level) - 1) in
let m' = IMap.until n2 (IMap.from n1 m) in
if IMap.is_empty m' then () else
a.(i) <- Sub.of_map n1 def m'
done
end;
hashcons a
let of_set n0 def s v =
let a = make_raw def in
for i = 0 to if level = 3 then 127 else 255 do
let n1 = n0 lor (i lsl (8 * level)) in
let n2 = n1 lor (1 lsl (8 * level) - 1) in
let s' = ISet.until n2 (ISet.from n1 s) in
if ISet.is_empty s' then () else
a.(i) <- Sub.of_set n1 def s' v
done;
hashcons a
end
module MakeTbl (Lev0 : NodeType) = struct
module Lev1 = MakeNode (Lev0)
module Lev2 = MakeNode (Lev1)
module Lev3 = MakeNode (Lev2)
include Lev3
let get = get
let of_map def m = untag (Lev3.of_map 0 def m)
end
module ArrayLeaf (H : Hashtbl.HashedType) = struct
type elt = H.t
type t = elt array
type node = t
let level = 0
module NodeHash = struct
type t = node tagged
let equal x y =
let a = untag x in
let b = untag y in
let rec loop i =
if i >= 255 then true else
if H.equal a.(i) b.(i) then loop (i + 1) else
false in
loop 0
let hash = id
end
module Pool = Weak.Make (NodeHash)
let pool = Pool.create 256
let crc_hash v =
let rec loop i sum =
if i < 0 then sum else
let a = H.hash v.(i) in
let sum = sum lsr 7 lxor crc_tbl.(sum lxor (byte3 a) land 0x7f) in
let sum = sum lsr 7 lxor crc_tbl.(sum lxor (byte2 a) land 0x7f) in
let sum = sum lsr 7 lxor crc_tbl.(sum lxor (byte1 a) land 0x7f) in
let sum = sum lsr 7 lxor crc_tbl.(sum lxor (byte0 a) land 0x7f) in
loop (i - 1) sum in
loop 255 0
let hashcons a =
let n = crc_hash a in
let x = Tag (a, n) in
try Pool.find pool x with Not_found ->
Pool.add pool x;
x
let make_raw def = Array.make 256 def
let make def = hashcons (make_raw def)
let of_map n0 def m =
let a = make_raw def in
IMap.iter_range (fun n1 n2 v ->
Printf.eprintf " Tl31.ArrayLeaf.of_map : % x % x - % x : % s\n " n0 n1 n2
( String.escaped ( Obj.magic v ) ) ;
for i = n1 - n0 to n2 - n0 do a.(i) <- v done)
m;
hashcons a
let of_set n0 def s v =
let a = make_raw def in
ISet.iter_range (fun n1 n2 ->
for i = n1 - n0 to n2 - n0 do a.(i) <- v done)
s;
hashcons a
end
module type Type = sig
type elt
type t = elt tbl
val get : elt tbl -> int -> elt
val of_map : elt -> elt IMap.t -> elt tbl
end
module Make (H : Hashtbl.HashedType) = MakeTbl(ArrayLeaf(H))
module StringContentsHash = struct
type t = Bytes.t tagged
let equal x1 x2 =
let s1 = untag x1 in
let s2 = untag x2 in
if Bytes.length s1 <> Bytes.length s2 then false else
let rec loop i =
if i < 0 then true else
if Bytes.get s1 i <> Bytes.get s2 i then false else
loop (i - 1) in
loop (Bytes.length s1 - 1)
let hash = id
end
let bytes_hash v =
let rec loop i sum =
if i < 0 then sum else
let a = Char.code (Bytes.get v i) in
let sum = sum lsr 7 lxor crc_tbl.(sum lxor a land 0x7f) in
loop (i - 1) sum in
loop (Bytes.length v - 5) 0
module BoolLeaf = struct
type elt = bool
type t = Bytes.t
let level = 0
module Pool = Weak.Make (StringContentsHash)
let pool = Pool.create 256
let hashcons s =
let n = bytes_hash s in
let x = Tag (s, n) in
try Pool.find pool x with Not_found ->
Pool.add pool x;
x
let make_raw def = Bytes.make 32 (if def then '\255' else '\000')
let make def = hashcons (make_raw def)
let boolset s k b =
let j = Char.code (Bytes.get s (k / 8)) in
let j' = if b then j lor (1 lsl (k mod 8)) else j in
Bytes.set s (k / 8) (Char.chr j')
let of_map n0 def m =
let a = make_raw def in
IMap.iter_range (fun n1 n2 v ->
for i = n1 - n0 to n2 - n0 do boolset a i v done)
m;
hashcons a
let of_set n0 def s v =
let a = make_raw def in
ISet.iter_range (fun n1 n2 ->
for i = n1 - n0 to n2 - n0 do boolset a i v done)
s;
hashcons a
end
module Bool = struct
module BoolTbl = MakeTbl (BoolLeaf)
include BoolTbl
let of_set s = untag (BoolTbl.of_set 0 false s true)
let get tbl n =
let lev = Array.unsafe_get tbl (byte3 n) in
let lev = Array.unsafe_get lev (byte2 n) in
let lev = Array.unsafe_get lev (byte1 n) in
let k = byte0 n in
let i = Char.code (Bytes.unsafe_get lev (k / 8)) in
i lsr (k mod 8) land 1 <> 0
end
module CharLeaf = struct
type elt = char
type t = Bytes.t
let level = 0
module Pool = Weak.Make (StringContentsHash)
let pool = Pool.create 256
let hashcons s =
let n = bytes_hash s in
let x = Tag (s, n) in
try Pool.find pool x with Not_found ->
Pool.add pool x;
x
let make_raw c = Bytes.make 256 c
let make c = hashcons (make_raw c)
let of_map n0 def m =
let a = make_raw def in
IMap.iter_range (fun n1 n2 v ->
for i = n1 - n0 to n2 - n0 do Bytes.set a i v done)
m;
hashcons a
let of_set n0 def s v =
let a = make_raw def in
ISet.iter_range (fun n1 n2 ->
for i = n1 - n0 to n2 - n0 do Bytes.set a i v done)
s;
hashcons a
end
module Char = struct
module CharTbl = MakeTbl (CharLeaf)
include CharTbl
let get tbl n =
let lev = Array.unsafe_get tbl (byte3 n) in
let lev = Array.unsafe_get lev (byte2 n) in
let lev = Array.unsafe_get lev (byte1 n) in
Bytes.unsafe_get lev (byte0 n)
end
module BitsContentsHash = struct
type t = Bitsvect.t tagged
let equal x1 x2 =
let a1 = untag x1 in
let a2 = untag x2 in
let rec loop i =
if i < 0 then true else
if Bitsvect.get a1 i = Bitsvect.get a2 i then loop (i - 1) else false in
loop 255
let hash = id
end
module BitsLeaf = struct
type elt = int
type t = Bitsvect.t
let level = 0
module Pool = Weak.Make (BitsContentsHash)
let pool = Pool.create 256
let hash v =
let rec loop i sum =
if i < 0 then sum else
let a = Bitsvect.get v i in
let sum = sum lsr 7 lxor crc_tbl.(sum lxor a land 0x7f) in
loop (i - 1) sum in
loop (Bitsvect.length v - 5) 0
let hashcons a =
let n = hash a in
let x = Tag (a, n) in
try Pool.find pool x with Not_found ->
Pool.add pool x;
x
let make_raw = Bitsvect.make 256
let make def = hashcons (make_raw def)
let of_map n0 def m =
let a = make_raw def in
IMap.iter_range (fun n1 n2 v ->
for i = n1 - n0 to n2 - n0 do Bitsvect.set a i v done)
m;
hashcons a
let of_set n0 def s v =
let a = make_raw def in
ISet.iter_range (fun n1 n2 ->
for i = n1 - n0 to n2 - n0 do Bitsvect.set a i v done)
s;
hashcons a
end
module Bits = struct
include MakeTbl (BitsLeaf)
let get tbl n =
let lev = Array.unsafe_get tbl (byte3 n) in
let lev = Array.unsafe_get lev (byte2 n) in
let lev = Array.unsafe_get lev (byte1 n) in
Bitsvect.unsafe_get lev (byte0 n)
end
module BytesContentsHash = struct
type t = Bytesvect.t tagged
let equal x1 x2 =
let a1 = untag x1 in
let a2 = untag x2 in
let rec loop i =
if i < 0 then true else
if Bytesvect.get a1 i = Bytesvect.get a2 i then
loop (i - 1)
else false in
loop 255
let hash = id
end
module BytesLeaf = struct
type elt = int
type t = Bytesvect.t
let level = 0
module Pool = Weak.Make (BytesContentsHash)
let pool = Pool.create 256
let hash v =
let rec loop i sum =
if i < 0 then sum else
let a = Bytesvect.get v i in
let sum = sum lsr 7 lxor crc_tbl.(sum lxor (byte3 a) land 0x7f) in
let sum = sum lsr 7 lxor crc_tbl.(sum lxor (byte2 a) land 0x7f) in
let sum = sum lsr 7 lxor crc_tbl.(sum lxor (byte1 a) land 0x7f) in
let sum = sum lsr 7 lxor crc_tbl.(sum lxor (byte0 a) land 0x7f) in
loop (i - 1) sum in
loop 255 0
let hashcons a =
let n = hash a in
let x = Tag (a, n) in
try Pool.find pool x with Not_found ->
Pool.add pool x;
x
let make_raw = Bytesvect.make 256
let make def = hashcons (make_raw def)
let of_map n0 def m =
let a = make_raw def in
IMap.iter_range (fun n1 n2 v ->
for i = n1 - n0 to n2 - n0 do Bytesvect.set a i v done)
m;
hashcons a
let of_set n0 def s v =
let a = make_raw def in
ISet.iter_range (fun n1 n2 ->
for i = n1 - n0 to n2 - n0 do Bytesvect.set a i v done)
s;
hashcons a
end
module Bytes = struct
include MakeTbl (BytesLeaf)
let get tbl n =
let lev = Array.unsafe_get tbl (byte3 n) in
let lev = Array.unsafe_get lev (byte2 n) in
let lev = Array.unsafe_get lev (byte1 n) in
Bytesvect.unsafe_get lev (byte0 n)
end
| null | https://raw.githubusercontent.com/yoriyuki/Camomile/d7d8843c88fae774f513610f8e09a613778e64b3/Camomile/internal/tbl31.ml | ocaml | * Tbl31 : fast table keyed by integers
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
may link, statically or dynamically, a "work that uses this library"
with a publicly distributed version of this library to produce an
executable file containing portions of this library, and distribute
that executable file under terms of your choice, without any of the
Public License. By "a publicly distributed version of this library",
or a modified version of this library that is distributed under the
License. This exception does not however invalidate any other reasons
Public License .
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.
License along with this library; if not, write to the Free Software
You can contact the authour by sending email to
| Copyright ( C ) 2002 , 2003
as published by the Free Software Foundation ; either version 2 of
the License , or ( at your option ) any later version .
As a special exception to the GNU Library General Public License , you
additional requirements listed in clause 6 of the GNU Library General
we mean either the unmodified Library as distributed by the authors ,
conditions defined in clause 3 of the GNU Library General Public
why the executable file might be covered by the GNU Library General
You should have received a copy of the GNU Lesser General Public
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307
USA
CRC - hash , algorithm comes from addnode.c / pathalias
31 - bits CRC - polynomial , by
let poly = 0x48000000
let crc_tbl = Array.init 128 (fun i ->
let rec loop j sum =
if j < 0 then sum else
if i land (1 lsl j) <> 0 then
loop (j - 1) (sum lxor (poly lsr j))
else
loop (j - 1) sum in
loop (7 - 1) 0)
let byte3 n = n lsr 24 land 127
let byte2 n = n lsr 16 land 255
let byte1 n = n lsr 8 land 255
let byte0 n = n land 255
let (lsl) x n =
if n >= Sys.word_size then 0 else
if n <= ~- Sys.word_size then 0 else
if n < 0 then x lsr (~-n) else
x lsl n
type 'a tbl = 'a array array array array
type 'a t = 'a tbl
type 'a tagged = Tag of 'a * int
let untag (Tag (a, _)) = a
let id (Tag (_, n)) = n
let get tbl n =
let lev = Array.unsafe_get tbl (byte3 n) in
let lev = Array.unsafe_get lev (byte2 n) in
let lev = Array.unsafe_get lev (byte1 n) in
Array.unsafe_get lev (byte0 n)
let get tbl n =
Printf.printf " level 3 % d " ( Array.length tbl ) ; print_newline ( ) ;
let lev = tbl.(byte3 n ) in
Printf.printf " level 2 % d " ( Array.length tbl ) ; print_newline ( ) ;
let lev = lev.(byte2 n ) in
Printf.printf " level 1 % d " ( Array.length tbl ) ; print_newline ( ) ;
let lev = lev.(byte1 n ) in
Printf.printf " level 0 % d " ( Array.length tbl ) ; print_newline ( ) ;
lev.(byte0 n )
Printf.printf "level 3 %d" (Array.length tbl); print_newline ();
let lev = tbl.(byte3 n) in
Printf.printf "level 2 %d" (Array.length tbl); print_newline ();
let lev = lev.(byte2 n) in
Printf.printf "level 1 %d" (Array.length tbl); print_newline ();
let lev = lev.(byte1 n) in
Printf.printf "level 0 %d" (Array.length tbl); print_newline ();
lev.(byte0 n) *)
module type NodeType = sig
type elt
type t
val level : int
val make : elt -> t tagged
val of_map : int -> elt -> elt IMap.t -> t tagged
val of_set : int -> elt -> ISet.t -> elt -> t tagged
end
module MakeNode (Sub : NodeType) = struct
type elt = Sub.elt
type node = Sub.t array
type t = node
let level = Sub.level + 1
module NodeHash = struct
type t = node tagged
let equal x y =
let a = untag x in
let b = untag y in
let rec loop i =
if i < 0 then true else
if a.(i) == b.(i) then loop (i - 1) else
false in
loop (if level = 3 then 127 else 255)
let hash = id
end
module NodePool = Weak.Make (NodeHash)
let pool = NodePool.create 256
let crc_hash v =
let rec loop i sum =
if i < 0 then sum else
let a = id v.(i) in
let sum = sum lsr 7 lxor crc_tbl.(sum lxor (byte3 a) land 0x7f) in
let sum = sum lsr 7 lxor crc_tbl.(sum lxor (byte2 a) land 0x7f) in
let sum = sum lsr 7 lxor crc_tbl.(sum lxor (byte1 a) land 0x7f) in
let sum = sum lsr 7 lxor crc_tbl.(sum lxor (byte0 a) land 0x7f) in
loop (i - 1) sum in
loop (if level = 3 then 127 else 255) 0
let hashcons a =
let n = crc_hash a in
let b = Array.map untag a in
prerr_int ( Array.length b ) ; ( ) ;
let x = Tag (b, n) in
try NodePool.find pool x with Not_found ->
NodePool.add pool x;
x
let make_raw def =
Array.make (if level = 3 then 128 else 256) (Sub.make def)
let make def = hashcons (make_raw def)
let of_map n0 def m =
let a = make_raw def in begin
if IMap.is_empty m then () else
let l = AvlTree.left_branch m in
let r = AvlTree.right_branch m in
if IMap.is_empty l && IMap.is_empty r then
let k1, k2, v = AvlTree.root m in
let i1 = (k1 - n0) lsr (8 * level) in
let n1 = n0 lor (i1 lsl (8 * level)) in
let n2 = n1 lor (1 lsl (8 * level) - 1) in
a.(i1) <- Sub.of_map n1 def (IMap.until n2 (IMap.from n1 m));
let i2 = (k2 - n0) lsr (8 * level) in
if i1 <> i2 then
let n1 = n0 lor (i2 lsl (8 * level)) in
let n2 = n1 lor (1 lsl (8 * level) - 1) in
a.(i2) <- Sub.of_map n1 def (IMap.until n2 (IMap.from n1 m));
let b = Sub.make v in
for i = i1 + 1 to i2 - 1 do a.(i) <- b done;
else ()
else
for i = 0 to if level = 3 then 127 else 255 do
let n1 = n0 lor (i lsl (8 * level)) in
let n2 = n1 lor (1 lsl (8 * level) - 1) in
let m' = IMap.until n2 (IMap.from n1 m) in
if IMap.is_empty m' then () else
a.(i) <- Sub.of_map n1 def m'
done
end;
hashcons a
let of_set n0 def s v =
let a = make_raw def in
for i = 0 to if level = 3 then 127 else 255 do
let n1 = n0 lor (i lsl (8 * level)) in
let n2 = n1 lor (1 lsl (8 * level) - 1) in
let s' = ISet.until n2 (ISet.from n1 s) in
if ISet.is_empty s' then () else
a.(i) <- Sub.of_set n1 def s' v
done;
hashcons a
end
module MakeTbl (Lev0 : NodeType) = struct
module Lev1 = MakeNode (Lev0)
module Lev2 = MakeNode (Lev1)
module Lev3 = MakeNode (Lev2)
include Lev3
let get = get
let of_map def m = untag (Lev3.of_map 0 def m)
end
module ArrayLeaf (H : Hashtbl.HashedType) = struct
type elt = H.t
type t = elt array
type node = t
let level = 0
module NodeHash = struct
type t = node tagged
let equal x y =
let a = untag x in
let b = untag y in
let rec loop i =
if i >= 255 then true else
if H.equal a.(i) b.(i) then loop (i + 1) else
false in
loop 0
let hash = id
end
module Pool = Weak.Make (NodeHash)
let pool = Pool.create 256
let crc_hash v =
let rec loop i sum =
if i < 0 then sum else
let a = H.hash v.(i) in
let sum = sum lsr 7 lxor crc_tbl.(sum lxor (byte3 a) land 0x7f) in
let sum = sum lsr 7 lxor crc_tbl.(sum lxor (byte2 a) land 0x7f) in
let sum = sum lsr 7 lxor crc_tbl.(sum lxor (byte1 a) land 0x7f) in
let sum = sum lsr 7 lxor crc_tbl.(sum lxor (byte0 a) land 0x7f) in
loop (i - 1) sum in
loop 255 0
let hashcons a =
let n = crc_hash a in
let x = Tag (a, n) in
try Pool.find pool x with Not_found ->
Pool.add pool x;
x
let make_raw def = Array.make 256 def
let make def = hashcons (make_raw def)
let of_map n0 def m =
let a = make_raw def in
IMap.iter_range (fun n1 n2 v ->
Printf.eprintf " Tl31.ArrayLeaf.of_map : % x % x - % x : % s\n " n0 n1 n2
( String.escaped ( Obj.magic v ) ) ;
for i = n1 - n0 to n2 - n0 do a.(i) <- v done)
m;
hashcons a
let of_set n0 def s v =
let a = make_raw def in
ISet.iter_range (fun n1 n2 ->
for i = n1 - n0 to n2 - n0 do a.(i) <- v done)
s;
hashcons a
end
module type Type = sig
type elt
type t = elt tbl
val get : elt tbl -> int -> elt
val of_map : elt -> elt IMap.t -> elt tbl
end
module Make (H : Hashtbl.HashedType) = MakeTbl(ArrayLeaf(H))
module StringContentsHash = struct
type t = Bytes.t tagged
let equal x1 x2 =
let s1 = untag x1 in
let s2 = untag x2 in
if Bytes.length s1 <> Bytes.length s2 then false else
let rec loop i =
if i < 0 then true else
if Bytes.get s1 i <> Bytes.get s2 i then false else
loop (i - 1) in
loop (Bytes.length s1 - 1)
let hash = id
end
let bytes_hash v =
let rec loop i sum =
if i < 0 then sum else
let a = Char.code (Bytes.get v i) in
let sum = sum lsr 7 lxor crc_tbl.(sum lxor a land 0x7f) in
loop (i - 1) sum in
loop (Bytes.length v - 5) 0
module BoolLeaf = struct
type elt = bool
type t = Bytes.t
let level = 0
module Pool = Weak.Make (StringContentsHash)
let pool = Pool.create 256
let hashcons s =
let n = bytes_hash s in
let x = Tag (s, n) in
try Pool.find pool x with Not_found ->
Pool.add pool x;
x
let make_raw def = Bytes.make 32 (if def then '\255' else '\000')
let make def = hashcons (make_raw def)
let boolset s k b =
let j = Char.code (Bytes.get s (k / 8)) in
let j' = if b then j lor (1 lsl (k mod 8)) else j in
Bytes.set s (k / 8) (Char.chr j')
let of_map n0 def m =
let a = make_raw def in
IMap.iter_range (fun n1 n2 v ->
for i = n1 - n0 to n2 - n0 do boolset a i v done)
m;
hashcons a
let of_set n0 def s v =
let a = make_raw def in
ISet.iter_range (fun n1 n2 ->
for i = n1 - n0 to n2 - n0 do boolset a i v done)
s;
hashcons a
end
module Bool = struct
module BoolTbl = MakeTbl (BoolLeaf)
include BoolTbl
let of_set s = untag (BoolTbl.of_set 0 false s true)
let get tbl n =
let lev = Array.unsafe_get tbl (byte3 n) in
let lev = Array.unsafe_get lev (byte2 n) in
let lev = Array.unsafe_get lev (byte1 n) in
let k = byte0 n in
let i = Char.code (Bytes.unsafe_get lev (k / 8)) in
i lsr (k mod 8) land 1 <> 0
end
module CharLeaf = struct
type elt = char
type t = Bytes.t
let level = 0
module Pool = Weak.Make (StringContentsHash)
let pool = Pool.create 256
let hashcons s =
let n = bytes_hash s in
let x = Tag (s, n) in
try Pool.find pool x with Not_found ->
Pool.add pool x;
x
let make_raw c = Bytes.make 256 c
let make c = hashcons (make_raw c)
let of_map n0 def m =
let a = make_raw def in
IMap.iter_range (fun n1 n2 v ->
for i = n1 - n0 to n2 - n0 do Bytes.set a i v done)
m;
hashcons a
let of_set n0 def s v =
let a = make_raw def in
ISet.iter_range (fun n1 n2 ->
for i = n1 - n0 to n2 - n0 do Bytes.set a i v done)
s;
hashcons a
end
module Char = struct
module CharTbl = MakeTbl (CharLeaf)
include CharTbl
let get tbl n =
let lev = Array.unsafe_get tbl (byte3 n) in
let lev = Array.unsafe_get lev (byte2 n) in
let lev = Array.unsafe_get lev (byte1 n) in
Bytes.unsafe_get lev (byte0 n)
end
module BitsContentsHash = struct
type t = Bitsvect.t tagged
let equal x1 x2 =
let a1 = untag x1 in
let a2 = untag x2 in
let rec loop i =
if i < 0 then true else
if Bitsvect.get a1 i = Bitsvect.get a2 i then loop (i - 1) else false in
loop 255
let hash = id
end
module BitsLeaf = struct
type elt = int
type t = Bitsvect.t
let level = 0
module Pool = Weak.Make (BitsContentsHash)
let pool = Pool.create 256
let hash v =
let rec loop i sum =
if i < 0 then sum else
let a = Bitsvect.get v i in
let sum = sum lsr 7 lxor crc_tbl.(sum lxor a land 0x7f) in
loop (i - 1) sum in
loop (Bitsvect.length v - 5) 0
let hashcons a =
let n = hash a in
let x = Tag (a, n) in
try Pool.find pool x with Not_found ->
Pool.add pool x;
x
let make_raw = Bitsvect.make 256
let make def = hashcons (make_raw def)
let of_map n0 def m =
let a = make_raw def in
IMap.iter_range (fun n1 n2 v ->
for i = n1 - n0 to n2 - n0 do Bitsvect.set a i v done)
m;
hashcons a
let of_set n0 def s v =
let a = make_raw def in
ISet.iter_range (fun n1 n2 ->
for i = n1 - n0 to n2 - n0 do Bitsvect.set a i v done)
s;
hashcons a
end
module Bits = struct
include MakeTbl (BitsLeaf)
let get tbl n =
let lev = Array.unsafe_get tbl (byte3 n) in
let lev = Array.unsafe_get lev (byte2 n) in
let lev = Array.unsafe_get lev (byte1 n) in
Bitsvect.unsafe_get lev (byte0 n)
end
module BytesContentsHash = struct
type t = Bytesvect.t tagged
let equal x1 x2 =
let a1 = untag x1 in
let a2 = untag x2 in
let rec loop i =
if i < 0 then true else
if Bytesvect.get a1 i = Bytesvect.get a2 i then
loop (i - 1)
else false in
loop 255
let hash = id
end
module BytesLeaf = struct
type elt = int
type t = Bytesvect.t
let level = 0
module Pool = Weak.Make (BytesContentsHash)
let pool = Pool.create 256
let hash v =
let rec loop i sum =
if i < 0 then sum else
let a = Bytesvect.get v i in
let sum = sum lsr 7 lxor crc_tbl.(sum lxor (byte3 a) land 0x7f) in
let sum = sum lsr 7 lxor crc_tbl.(sum lxor (byte2 a) land 0x7f) in
let sum = sum lsr 7 lxor crc_tbl.(sum lxor (byte1 a) land 0x7f) in
let sum = sum lsr 7 lxor crc_tbl.(sum lxor (byte0 a) land 0x7f) in
loop (i - 1) sum in
loop 255 0
let hashcons a =
let n = hash a in
let x = Tag (a, n) in
try Pool.find pool x with Not_found ->
Pool.add pool x;
x
let make_raw = Bytesvect.make 256
let make def = hashcons (make_raw def)
let of_map n0 def m =
let a = make_raw def in
IMap.iter_range (fun n1 n2 v ->
for i = n1 - n0 to n2 - n0 do Bytesvect.set a i v done)
m;
hashcons a
let of_set n0 def s v =
let a = make_raw def in
ISet.iter_range (fun n1 n2 ->
for i = n1 - n0 to n2 - n0 do Bytesvect.set a i v done)
s;
hashcons a
end
module Bytes = struct
include MakeTbl (BytesLeaf)
let get tbl n =
let lev = Array.unsafe_get tbl (byte3 n) in
let lev = Array.unsafe_get lev (byte2 n) in
let lev = Array.unsafe_get lev (byte1 n) in
Bytesvect.unsafe_get lev (byte0 n)
end
|
ace8b9777bd1f4d49d5479e43b1fb61e02cb61887cce9386d1846f91e74415a1 | dimitri/pgloader | mysql-connection.lisp | ;;;
;;; Tools to handle MySQL connection and querying
;;;
(in-package :pgloader.source.mysql)
(defvar *connection* nil "Current MySQL connection")
;;;
;;; General utility to manage MySQL connection
;;;
(defclass mysql-connection (db-connection)
((use-ssl :initarg :use-ssl :accessor myconn-use-ssl)))
(defmethod initialize-instance :after ((myconn mysql-connection) &key)
"Assign the type slot to mysql."
(setf (slot-value myconn 'type) "mysql"))
(defmethod clone-connection ((c mysql-connection))
(let ((clone
(change-class (call-next-method c) 'mysql-connection)))
(setf (myconn-use-ssl clone) (myconn-use-ssl c))
clone))
(defmethod ssl-mode ((myconn mysql-connection))
"Return non-nil when the connection uses SSL"
(ecase (myconn-use-ssl myconn)
(:try :unspecified)
(:yes t)
(:no nil)))
(defmethod open-connection ((myconn mysql-connection) &key)
(setf (conn-handle myconn)
(if (and (consp (db-host myconn)) (eq :unix (car (db-host myconn))))
(qmynd:mysql-local-connect :path (cdr (db-host myconn))
:username (db-user myconn)
:password (db-pass myconn)
:database (db-name myconn))
(qmynd:mysql-connect :host (db-host myconn)
:port (db-port myconn)
:username (db-user myconn)
:password (db-pass myconn)
:database (db-name myconn)
:ssl (ssl-mode myconn))))
(log-message :debug "CONNECTED TO ~a" myconn)
;; apply mysql-settings, if any
(loop :for (name . value) :in *mysql-settings*
:for sql := (format nil "set ~a = ~a;" name value)
:do (query myconn sql))
;; return the connection object
myconn)
(defmethod close-connection ((myconn mysql-connection))
(qmynd:mysql-disconnect (conn-handle myconn))
(setf (conn-handle myconn) nil)
myconn)
(defmethod query ((myconn mysql-connection)
sql
&key
row-fn
(as-text t)
(result-type 'list))
"Run SQL query against MySQL connection MYCONN."
(log-message :sql "MySQL: sending query: ~a" sql)
(qmynd:mysql-query (conn-handle myconn)
sql
:row-fn row-fn
:as-text as-text
:result-type result-type))
;;;
;;; The generic API query is recent, used to look like this:
;;;
(declaim (inline mysql-query))
(defun mysql-query (query &key row-fn (as-text t) (result-type 'list))
"Execute given QUERY within the current *connection*, and set proper
defaults for pgloader."
(query *connection* query
:row-fn row-fn
:as-text as-text
:result-type result-type))
| null | https://raw.githubusercontent.com/dimitri/pgloader/3047c9afe141763e9e7ec05b7f2a6aa97cf06801/src/sources/mysql/mysql-connection.lisp | lisp |
Tools to handle MySQL connection and querying
General utility to manage MySQL connection
apply mysql-settings, if any
return the connection object
The generic API query is recent, used to look like this:
|
(in-package :pgloader.source.mysql)
(defvar *connection* nil "Current MySQL connection")
(defclass mysql-connection (db-connection)
((use-ssl :initarg :use-ssl :accessor myconn-use-ssl)))
(defmethod initialize-instance :after ((myconn mysql-connection) &key)
"Assign the type slot to mysql."
(setf (slot-value myconn 'type) "mysql"))
(defmethod clone-connection ((c mysql-connection))
(let ((clone
(change-class (call-next-method c) 'mysql-connection)))
(setf (myconn-use-ssl clone) (myconn-use-ssl c))
clone))
(defmethod ssl-mode ((myconn mysql-connection))
"Return non-nil when the connection uses SSL"
(ecase (myconn-use-ssl myconn)
(:try :unspecified)
(:yes t)
(:no nil)))
(defmethod open-connection ((myconn mysql-connection) &key)
(setf (conn-handle myconn)
(if (and (consp (db-host myconn)) (eq :unix (car (db-host myconn))))
(qmynd:mysql-local-connect :path (cdr (db-host myconn))
:username (db-user myconn)
:password (db-pass myconn)
:database (db-name myconn))
(qmynd:mysql-connect :host (db-host myconn)
:port (db-port myconn)
:username (db-user myconn)
:password (db-pass myconn)
:database (db-name myconn)
:ssl (ssl-mode myconn))))
(log-message :debug "CONNECTED TO ~a" myconn)
(loop :for (name . value) :in *mysql-settings*
:for sql := (format nil "set ~a = ~a;" name value)
:do (query myconn sql))
myconn)
(defmethod close-connection ((myconn mysql-connection))
(qmynd:mysql-disconnect (conn-handle myconn))
(setf (conn-handle myconn) nil)
myconn)
(defmethod query ((myconn mysql-connection)
sql
&key
row-fn
(as-text t)
(result-type 'list))
"Run SQL query against MySQL connection MYCONN."
(log-message :sql "MySQL: sending query: ~a" sql)
(qmynd:mysql-query (conn-handle myconn)
sql
:row-fn row-fn
:as-text as-text
:result-type result-type))
(declaim (inline mysql-query))
(defun mysql-query (query &key row-fn (as-text t) (result-type 'list))
"Execute given QUERY within the current *connection*, and set proper
defaults for pgloader."
(query *connection* query
:row-fn row-fn
:as-text as-text
:result-type result-type))
|
dc330b3ed4db6b75f174ada73de4f17f8619118fba866a3715553e1517224c3d | turquoise-hexagon/euler | solution.scm | (import
(euler))
(define (solve l n)
(let ((m (expt 10 n)))
(do ((i 1 (+ i 1))
(acc 0 (modulo (+ acc (modular-expt i i m)) m)))
((> i l) acc))))
(let ((_ (solve 1000 10)))
(print _) (assert (= _ 9110846700)))
| null | https://raw.githubusercontent.com/turquoise-hexagon/euler/5034b7024cbe20f61ea162e9be4e73c40a367a67/src/048/solution.scm | scheme | (import
(euler))
(define (solve l n)
(let ((m (expt 10 n)))
(do ((i 1 (+ i 1))
(acc 0 (modulo (+ acc (modular-expt i i m)) m)))
((> i l) acc))))
(let ((_ (solve 1000 10)))
(print _) (assert (= _ 9110846700)))
| |
4aacfa10c7a5962164f19426ec378690500c38b240cebac52d6458ffc8fcd622 | reborg/clojure-essential-reference | 2.clj | (ns com.package.myns)
< 1 >
com.package.myns | null | https://raw.githubusercontent.com/reborg/clojure-essential-reference/c37fa19d45dd52b2995a191e3e96f0ebdc3f6d69/VarsandNamespaces/the-ns%2Cns-nameandnamespace/2.clj | clojure | (ns com.package.myns)
< 1 >
com.package.myns | |
6be75f1d523c694914ce78dffbb75840f42fd36891f9db27a9af1f3cfb2932d3 | vusec/poking-holes | preallocations.ml | open Core.Std
open Sexplib_num.Std.Big_int
type t = {
sizes : big_int list;
low : big_int;
high : big_int;
} with sexp
| null | https://raw.githubusercontent.com/vusec/poking-holes/4184960e4d8d7a5832f74d4d33fd06022786b6d2/preallocations.ml | ocaml | open Core.Std
open Sexplib_num.Std.Big_int
type t = {
sizes : big_int list;
low : big_int;
high : big_int;
} with sexp
| |
98e07db2008cfb9f56260667b381ccfe05fe8a5e65bfa08f758573d61a12195f | penpot/penpot | render.cljs | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
;;
;; Copyright (c) KALEIDOS INC
(ns app.main.render
"Rendering utilities and components for penpot SVG.
NOTE: This namespace is used from worker and from many parts of the
workspace; we need to be careful when adding new requires because
this can cause to import too many deps on worker bundle."
(:require
["react-dom/server" :as rds]
[app.common.colors :as clr]
[app.common.data.macros :as dm]
[app.common.geom.point :as gpt]
[app.common.geom.shapes :as gsh]
[app.common.geom.shapes.bounds :as gsb]
[app.common.math :as mth]
[app.common.pages.helpers :as cph]
[app.common.types.modifiers :as ctm]
[app.common.types.shape-tree :as ctst]
[app.config :as cfg]
[app.main.fonts :as fonts]
[app.main.ui.context :as muc]
[app.main.ui.shapes.bool :as bool]
[app.main.ui.shapes.circle :as circle]
[app.main.ui.shapes.embed :as embed]
[app.main.ui.shapes.export :as export]
[app.main.ui.shapes.frame :as frame]
[app.main.ui.shapes.group :as group]
[app.main.ui.shapes.image :as image]
[app.main.ui.shapes.path :as path]
[app.main.ui.shapes.rect :as rect]
[app.main.ui.shapes.shape :refer [shape-container]]
[app.main.ui.shapes.svg-raw :as svg-raw]
[app.main.ui.shapes.text :as text]
[app.main.ui.shapes.text.fontfaces :as ff]
[app.util.http :as http]
[app.util.object :as obj]
[app.util.strings :as ust]
[app.util.timers :as ts]
[beicon.core :as rx]
[clojure.set :as set]
[cuerdas.core :as str]
[rumext.v2 :as mf]))
(def ^:const viewbox-decimal-precision 3)
(def ^:private default-color clr/canvas)
(mf/defc background
[{:keys [vbox color]}]
[:rect
{:x (:x vbox)
:y (:y vbox)
:width (:width vbox)
:height (:height vbox)
:fill color}])
(defn- calculate-dimensions
[objects]
(let [bounds
(->> (ctst/get-root-objects objects)
(map (partial gsb/get-object-bounds objects))
(gsh/join-rects))]
(-> bounds
(update :x mth/finite 0)
(update :y mth/finite 0)
(update :width mth/finite 100000)
(update :height mth/finite 100000))))
(declare shape-wrapper-factory)
(defn frame-wrapper-factory
[objects]
(let [shape-wrapper (shape-wrapper-factory objects)
frame-shape (frame/frame-shape shape-wrapper)]
(mf/fnc frame-wrapper
[{:keys [shape] :as props}]
(let [render-thumbnails? (mf/use-ctx muc/render-thumbnails)
childs (mapv #(get objects %) (:shapes shape))]
(if (and render-thumbnails? (some? (:thumbnail shape)))
[:& frame/frame-thumbnail {:shape shape :bounds (:children-bounds shape)}]
[:& frame-shape {:shape shape :childs childs}])))))
(defn group-wrapper-factory
[objects]
(let [shape-wrapper (shape-wrapper-factory objects)
group-shape (group/group-shape shape-wrapper)]
(mf/fnc group-wrapper
[{:keys [shape] :as props}]
(let [childs (mapv #(get objects %) (:shapes shape))]
[:& group-shape {:shape shape
:is-child-selected? true
:childs childs}]))))
(defn bool-wrapper-factory
[objects]
(let [shape-wrapper (shape-wrapper-factory objects)
bool-shape (bool/bool-shape shape-wrapper)]
(mf/fnc bool-wrapper
[{:keys [shape] :as props}]
(let [childs (mf/with-memo [(:id shape) objects]
(->> (cph/get-children-ids objects (:id shape))
(select-keys objects)))]
[:& bool-shape {:shape shape :childs childs}]))))
(defn svg-raw-wrapper-factory
[objects]
(let [shape-wrapper (shape-wrapper-factory objects)
svg-raw-shape (svg-raw/svg-raw-shape shape-wrapper)]
(mf/fnc svg-raw-wrapper
[{:keys [shape] :as props}]
(let [childs (mapv #(get objects %) (:shapes shape))]
(if (and (map? (:content shape))
(or (= :svg (get-in shape [:content :tag]))
(contains? shape :svg-attrs)))
[:> shape-container {:shape shape}
[:& svg-raw-shape {:shape shape
:childs childs}]]
[:& svg-raw-shape {:shape shape
:childs childs}])))))
(defn shape-wrapper-factory
[objects]
(mf/fnc shape-wrapper
[{:keys [frame shape] :as props}]
(let [group-wrapper (mf/use-memo (mf/deps objects) #(group-wrapper-factory objects))
svg-raw-wrapper (mf/use-memo (mf/deps objects) #(svg-raw-wrapper-factory objects))
bool-wrapper (mf/use-memo (mf/deps objects) #(bool-wrapper-factory objects))
frame-wrapper (mf/use-memo (mf/deps objects) #(frame-wrapper-factory objects))]
(when (and shape (not (:hidden shape)))
(let [opts #js {:shape shape}
svg-raw? (= :svg-raw (:type shape))]
(if-not svg-raw?
[:> shape-container {:shape shape}
(case (:type shape)
:text [:> text/text-shape opts]
:rect [:> rect/rect-shape opts]
:path [:> path/path-shape opts]
:image [:> image/image-shape opts]
:circle [:> circle/circle-shape opts]
:frame [:> frame-wrapper {:shape shape}]
:group [:> group-wrapper {:shape shape :frame frame}]
:bool [:> bool-wrapper {:shape shape :frame frame}]
nil)]
;; Don't wrap svg elements inside a <g> otherwise some can break
[:> svg-raw-wrapper {:shape shape :frame frame}]))))))
(defn format-viewbox
"Format a viewbox given a rectangle"
[{:keys [x y width height] :or {x 0 y 0 width 100 height 100}}]
(str/join
" "
(->> [x y width height]
(map #(ust/format-precision % viewbox-decimal-precision)))))
(defn adapt-root-frame
[objects object]
(let [shapes (cph/get-immediate-children objects)
srect (gsh/selection-rect shapes)
object (merge object (select-keys srect [:x :y :width :height]))]
(assoc object :fill-color "#f0f0f0")))
(defn adapt-objects-for-shape
[objects object-id]
(let [object (get objects object-id)
object (cond->> object
(cph/root? object)
(adapt-root-frame objects))
Replace the previous object with the new one
objects (assoc objects object-id object)
vector (-> (gpt/point (:x object) (:y object))
(gpt/negate))
mod-ids (cons object-id (cph/get-children-ids objects object-id))
updt-fn #(update %1 %2 gsh/transform-shape (ctm/move-modifiers vector))]
(reduce updt-fn objects mod-ids)))
(mf/defc page-svg
{::mf/wrap [mf/memo]}
[{:keys [data thumbnails? render-embed? include-metadata?] :as props
:or {render-embed? false include-metadata? false}}]
(let [objects (:objects data)
shapes (cph/get-immediate-children objects)
dim (calculate-dimensions objects)
vbox (format-viewbox dim)
bgcolor (dm/get-in data [:options :background] default-color)
shape-wrapper
(mf/use-memo
(mf/deps objects)
#(shape-wrapper-factory objects))]
[:& (mf/provider muc/render-thumbnails) {:value thumbnails?}
[:& (mf/provider embed/context) {:value render-embed?}
[:& (mf/provider export/include-metadata-ctx) {:value include-metadata?}
[:svg {:view-box vbox
:version "1.1"
:xmlns ""
:xmlnsXlink ""
:xmlns:penpot (when include-metadata? "")
:style {:width "100%"
:height "100%"
:background bgcolor}
:fill "none"}
(when include-metadata?
[:& export/export-page {:id (:id data) :options (:options data)}])
(let [shapes (->> shapes
(remove cph/frame-shape?)
(mapcat #(cph/get-children-with-self objects (:id %))))
fonts (ff/shapes->fonts shapes)]
[:& ff/fontfaces-style {:fonts fonts}])
(for [item shapes]
[:& shape-wrapper {:shape item
:key (:id item)}])]]]]))
;; Component that serves for render frame thumbnails, mainly used in
;; the viewer and inspector
(mf/defc frame-svg
{::mf/wrap [mf/memo]}
[{:keys [objects frame zoom show-thumbnails?] :or {zoom 1} :as props}]
(let [frame-id (:id frame)
include-metadata? (mf/use-ctx export/include-metadata-ctx)
bounds (gsb/get-object-bounds objects frame)
;; Bounds without shadows/blur will be the bounds of the thumbnail
bounds2 (gsb/get-object-bounds objects (dissoc frame :shadow :blur))
delta-bounds (gpt/point (:x bounds) (:y bounds))
vector (gpt/negate delta-bounds)
children-ids
(cph/get-children-ids objects frame-id)
objects
(mf/with-memo [frame-id objects vector]
(let [update-fn #(update %1 %2 gsh/transform-shape (ctm/move-modifiers vector))]
(->> children-ids
(into [frame-id])
(reduce update-fn objects))))
frame
(mf/with-memo [vector]
(gsh/transform-shape frame (ctm/move-modifiers vector)))
frame
(cond-> frame
(and (some? bounds) (nil? (:children-bounds bounds)))
(assoc :children-bounds bounds2))
frame (-> frame
(update-in [:children-bounds :x] - (:x delta-bounds))
(update-in [:children-bounds :y] - (:y delta-bounds)))
shape-wrapper
(mf/use-memo
(mf/deps objects)
#(shape-wrapper-factory objects))
width (* (:width bounds) zoom)
height (* (:height bounds) zoom)
vbox (format-viewbox {:width (:width bounds 0) :height (:height bounds 0)})]
[:& (mf/provider muc/render-thumbnails) {:value show-thumbnails?}
[:svg {:view-box vbox
:width (ust/format-precision width viewbox-decimal-precision)
:height (ust/format-precision height viewbox-decimal-precision)
:version "1.1"
:xmlns ""
:xmlnsXlink ""
:xmlns:penpot (when include-metadata? "")
:fill "none"}
[:& shape-wrapper {:shape frame}]]]))
;; Component for rendering a thumbnail of a single componenent. Mainly
;; used to render thumbnails on assets panel.
(mf/defc component-svg
{::mf/wrap [mf/memo #(mf/deferred % ts/idle-then-raf)]}
[{:keys [objects root-shape zoom] :or {zoom 1} :as props}]
(let [root-shape-id (:id root-shape)
include-metadata? (mf/use-ctx export/include-metadata-ctx)
vector
(mf/use-memo
(mf/deps (:x root-shape) (:y root-shape))
(fn []
(-> (gpt/point (:x root-shape) (:y root-shape))
(gpt/negate))))
objects
(mf/use-memo
(mf/deps vector objects root-shape-id)
(fn []
(let [children-ids (cons root-shape-id (cph/get-children-ids objects root-shape-id))
update-fn #(update %1 %2 gsh/transform-shape (ctm/move-modifiers vector))]
(reduce update-fn objects children-ids))))
root-shape (get objects root-shape-id)
width (* (:width root-shape) zoom)
height (* (:height root-shape) zoom)
vbox (format-viewbox {:width (:width root-shape 0)
:height (:height root-shape 0)})
root-shape-wrapper
(mf/use-memo
(mf/deps objects root-shape)
(fn []
(case (:type root-shape)
:group (group-wrapper-factory objects)
:frame (frame-wrapper-factory objects))))]
[:svg {:view-box vbox
:width (ust/format-precision width viewbox-decimal-precision)
:height (ust/format-precision height viewbox-decimal-precision)
:version "1.1"
:xmlns ""
:xmlnsXlink ""
:xmlns:penpot (when include-metadata? "")
:fill "none"}
[:> shape-container {:shape root-shape}
[:& (mf/provider muc/is-component?) {:value true}
[:& root-shape-wrapper {:shape root-shape :view-box vbox}]]]]))
(mf/defc object-svg
{::mf/wrap [mf/memo]}
[{:keys [objects object-id render-embed?]
:or {render-embed? false}
:as props}]
(let [object (get objects object-id)
object (cond-> object
(:hide-fill-on-export object)
(assoc :fills []))
{:keys [width height] :as bounds} (gsb/get-object-bounds objects object)
vbox (format-viewbox bounds)
fonts (ff/shape->fonts object objects)
shape-wrapper
(mf/with-memo [objects]
(shape-wrapper-factory objects))]
[:& (mf/provider export/include-metadata-ctx) {:value false}
[:& (mf/provider embed/context) {:value render-embed?}
[:svg {:id (dm/str "screenshot-" object-id)
:view-box vbox
:width (ust/format-precision width viewbox-decimal-precision)
:height (ust/format-precision height viewbox-decimal-precision)
:version "1.1"
:xmlns ""
:xmlnsXlink ""
Fix Chromium bug about color of html texts
;; #c5
:style {:-webkit-print-color-adjust :exact}
:fill "none"}
[:& ff/fontfaces-style {:fonts fonts}]
[:& shape-wrapper {:shape object}]]]]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; SPRITES (DEBUG)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(mf/defc component-symbol
[{:keys [id data] :as props}]
(let [name (:name data)
path (:path data)
objects (-> (:objects data)
(adapt-objects-for-shape id))
root-shape (get objects id)
selrect (:selrect root-shape)
main-instance-id (:main-instance-id data)
main-instance-page (:main-instance-page data)
main-instance-x (:main-instance-x data)
main-instance-y (:main-instance-y data)
vbox
(format-viewbox
{:width (:width selrect)
:height (:height selrect)})
group-wrapper
(mf/use-memo
(mf/deps objects)
(fn [] (group-wrapper-factory objects)))
frame-wrapper
(mf/use-memo
(mf/deps objects)
(fn [] (frame-wrapper-factory objects)))]
[:> "symbol" #js {:id (str id)
:viewBox vbox
"penpot:path" path
"penpot:main-instance-id" main-instance-id
"penpot:main-instance-page" main-instance-page
"penpot:main-instance-x" main-instance-x
"penpot:main-instance-y" main-instance-y}
[:title name]
[:> shape-container {:shape root-shape}
(case (:type root-shape)
:group [:& group-wrapper {:shape root-shape :view-box vbox}]
:frame [:& frame-wrapper {:shape root-shape :view-box vbox}])]]))
(mf/defc components-sprite-svg
{::mf/wrap-props false}
[props]
(let [data (obj/get props "data")
children (obj/get props "children")
render-embed? (obj/get props "render-embed?")
include-metadata? (obj/get props "include-metadata?")
source (keyword (obj/get props "source" "components"))]
[:& (mf/provider embed/context) {:value render-embed?}
[:& (mf/provider export/include-metadata-ctx) {:value include-metadata?}
[:svg {:version "1.1"
:xmlns ""
:xmlnsXlink ""
:xmlns:penpot (when include-metadata? "")
:style {:display (when-not (some? children) "none")}
:fill "none"}
[:defs
(for [[id data] (source data)]
[:& component-symbol {:id id :key (dm/str id) :data data}])]
children]]]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; RENDER FOR DOWNLOAD (wrongly called exportation)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- get-image-data [shape]
(cond
(= :image (:type shape))
[(:metadata shape)]
(some? (:fill-image shape))
[(:fill-image shape)]
:else
[]))
(defn- populate-images-cache
[objects]
(let [images (->> objects
(vals)
(mapcat get-image-data))]
(->> (rx/from images)
(rx/map #(cfg/resolve-file-media %))
(rx/flat-map http/fetch-data-uri))))
(defn populate-fonts-cache [objects]
(let [texts (->> objects
(vals)
(filterv #(= (:type %) :text))
(mapv :content))]
(->> (rx/from texts)
(rx/map fonts/get-content-fonts)
(rx/reduce set/union #{})
(rx/flat-map identity)
(rx/flat-map fonts/fetch-font-css)
(rx/flat-map fonts/extract-fontface-urls)
(rx/flat-map http/fetch-data-uri))))
(defn render-page
[data]
(rx/concat
(->> (rx/merge
(populate-images-cache (:objects data))
(populate-fonts-cache (:objects data)))
(rx/ignore))
(->> (rx/of data)
(rx/map
(fn [data]
(let [elem (mf/element page-svg #js {:data data :render-embed? true :include-metadata? true})]
(rds/renderToStaticMarkup elem)))))))
(defn render-components
[data source]
(let [;; Join all components objects into a single map
objects (->> (source data)
(vals)
(map :objects)
(reduce conj))]
(rx/concat
(->> (rx/merge
(populate-images-cache objects)
(populate-fonts-cache objects))
(rx/ignore))
(->> (rx/of data)
(rx/map
(fn [data]
(let [elem (mf/element components-sprite-svg
#js {:data data :render-embed? true :include-metadata? true
:source (name source)})]
(rds/renderToStaticMarkup elem))))))))
| null | https://raw.githubusercontent.com/penpot/penpot/c3ce0eb7945b5412f72a50e55312a7341387ba51/frontend/src/app/main/render.cljs | clojure |
Copyright (c) KALEIDOS INC
we need to be careful when adding new requires because
Don't wrap svg elements inside a <g> otherwise some can break
Component that serves for render frame thumbnails, mainly used in
the viewer and inspector
Bounds without shadows/blur will be the bounds of the thumbnail
Component for rendering a thumbnail of a single componenent. Mainly
used to render thumbnails on assets panel.
#c5
SPRITES (DEBUG)
RENDER FOR DOWNLOAD (wrongly called exportation)
Join all components objects into a single map | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
(ns app.main.render
"Rendering utilities and components for penpot SVG.
NOTE: This namespace is used from worker and from many parts of the
this can cause to import too many deps on worker bundle."
(:require
["react-dom/server" :as rds]
[app.common.colors :as clr]
[app.common.data.macros :as dm]
[app.common.geom.point :as gpt]
[app.common.geom.shapes :as gsh]
[app.common.geom.shapes.bounds :as gsb]
[app.common.math :as mth]
[app.common.pages.helpers :as cph]
[app.common.types.modifiers :as ctm]
[app.common.types.shape-tree :as ctst]
[app.config :as cfg]
[app.main.fonts :as fonts]
[app.main.ui.context :as muc]
[app.main.ui.shapes.bool :as bool]
[app.main.ui.shapes.circle :as circle]
[app.main.ui.shapes.embed :as embed]
[app.main.ui.shapes.export :as export]
[app.main.ui.shapes.frame :as frame]
[app.main.ui.shapes.group :as group]
[app.main.ui.shapes.image :as image]
[app.main.ui.shapes.path :as path]
[app.main.ui.shapes.rect :as rect]
[app.main.ui.shapes.shape :refer [shape-container]]
[app.main.ui.shapes.svg-raw :as svg-raw]
[app.main.ui.shapes.text :as text]
[app.main.ui.shapes.text.fontfaces :as ff]
[app.util.http :as http]
[app.util.object :as obj]
[app.util.strings :as ust]
[app.util.timers :as ts]
[beicon.core :as rx]
[clojure.set :as set]
[cuerdas.core :as str]
[rumext.v2 :as mf]))
(def ^:const viewbox-decimal-precision 3)
(def ^:private default-color clr/canvas)
(mf/defc background
[{:keys [vbox color]}]
[:rect
{:x (:x vbox)
:y (:y vbox)
:width (:width vbox)
:height (:height vbox)
:fill color}])
(defn- calculate-dimensions
[objects]
(let [bounds
(->> (ctst/get-root-objects objects)
(map (partial gsb/get-object-bounds objects))
(gsh/join-rects))]
(-> bounds
(update :x mth/finite 0)
(update :y mth/finite 0)
(update :width mth/finite 100000)
(update :height mth/finite 100000))))
(declare shape-wrapper-factory)
(defn frame-wrapper-factory
[objects]
(let [shape-wrapper (shape-wrapper-factory objects)
frame-shape (frame/frame-shape shape-wrapper)]
(mf/fnc frame-wrapper
[{:keys [shape] :as props}]
(let [render-thumbnails? (mf/use-ctx muc/render-thumbnails)
childs (mapv #(get objects %) (:shapes shape))]
(if (and render-thumbnails? (some? (:thumbnail shape)))
[:& frame/frame-thumbnail {:shape shape :bounds (:children-bounds shape)}]
[:& frame-shape {:shape shape :childs childs}])))))
(defn group-wrapper-factory
[objects]
(let [shape-wrapper (shape-wrapper-factory objects)
group-shape (group/group-shape shape-wrapper)]
(mf/fnc group-wrapper
[{:keys [shape] :as props}]
(let [childs (mapv #(get objects %) (:shapes shape))]
[:& group-shape {:shape shape
:is-child-selected? true
:childs childs}]))))
(defn bool-wrapper-factory
[objects]
(let [shape-wrapper (shape-wrapper-factory objects)
bool-shape (bool/bool-shape shape-wrapper)]
(mf/fnc bool-wrapper
[{:keys [shape] :as props}]
(let [childs (mf/with-memo [(:id shape) objects]
(->> (cph/get-children-ids objects (:id shape))
(select-keys objects)))]
[:& bool-shape {:shape shape :childs childs}]))))
(defn svg-raw-wrapper-factory
[objects]
(let [shape-wrapper (shape-wrapper-factory objects)
svg-raw-shape (svg-raw/svg-raw-shape shape-wrapper)]
(mf/fnc svg-raw-wrapper
[{:keys [shape] :as props}]
(let [childs (mapv #(get objects %) (:shapes shape))]
(if (and (map? (:content shape))
(or (= :svg (get-in shape [:content :tag]))
(contains? shape :svg-attrs)))
[:> shape-container {:shape shape}
[:& svg-raw-shape {:shape shape
:childs childs}]]
[:& svg-raw-shape {:shape shape
:childs childs}])))))
(defn shape-wrapper-factory
[objects]
(mf/fnc shape-wrapper
[{:keys [frame shape] :as props}]
(let [group-wrapper (mf/use-memo (mf/deps objects) #(group-wrapper-factory objects))
svg-raw-wrapper (mf/use-memo (mf/deps objects) #(svg-raw-wrapper-factory objects))
bool-wrapper (mf/use-memo (mf/deps objects) #(bool-wrapper-factory objects))
frame-wrapper (mf/use-memo (mf/deps objects) #(frame-wrapper-factory objects))]
(when (and shape (not (:hidden shape)))
(let [opts #js {:shape shape}
svg-raw? (= :svg-raw (:type shape))]
(if-not svg-raw?
[:> shape-container {:shape shape}
(case (:type shape)
:text [:> text/text-shape opts]
:rect [:> rect/rect-shape opts]
:path [:> path/path-shape opts]
:image [:> image/image-shape opts]
:circle [:> circle/circle-shape opts]
:frame [:> frame-wrapper {:shape shape}]
:group [:> group-wrapper {:shape shape :frame frame}]
:bool [:> bool-wrapper {:shape shape :frame frame}]
nil)]
[:> svg-raw-wrapper {:shape shape :frame frame}]))))))
(defn format-viewbox
"Format a viewbox given a rectangle"
[{:keys [x y width height] :or {x 0 y 0 width 100 height 100}}]
(str/join
" "
(->> [x y width height]
(map #(ust/format-precision % viewbox-decimal-precision)))))
(defn adapt-root-frame
[objects object]
(let [shapes (cph/get-immediate-children objects)
srect (gsh/selection-rect shapes)
object (merge object (select-keys srect [:x :y :width :height]))]
(assoc object :fill-color "#f0f0f0")))
(defn adapt-objects-for-shape
[objects object-id]
(let [object (get objects object-id)
object (cond->> object
(cph/root? object)
(adapt-root-frame objects))
Replace the previous object with the new one
objects (assoc objects object-id object)
vector (-> (gpt/point (:x object) (:y object))
(gpt/negate))
mod-ids (cons object-id (cph/get-children-ids objects object-id))
updt-fn #(update %1 %2 gsh/transform-shape (ctm/move-modifiers vector))]
(reduce updt-fn objects mod-ids)))
(mf/defc page-svg
{::mf/wrap [mf/memo]}
[{:keys [data thumbnails? render-embed? include-metadata?] :as props
:or {render-embed? false include-metadata? false}}]
(let [objects (:objects data)
shapes (cph/get-immediate-children objects)
dim (calculate-dimensions objects)
vbox (format-viewbox dim)
bgcolor (dm/get-in data [:options :background] default-color)
shape-wrapper
(mf/use-memo
(mf/deps objects)
#(shape-wrapper-factory objects))]
[:& (mf/provider muc/render-thumbnails) {:value thumbnails?}
[:& (mf/provider embed/context) {:value render-embed?}
[:& (mf/provider export/include-metadata-ctx) {:value include-metadata?}
[:svg {:view-box vbox
:version "1.1"
:xmlns ""
:xmlnsXlink ""
:xmlns:penpot (when include-metadata? "")
:style {:width "100%"
:height "100%"
:background bgcolor}
:fill "none"}
(when include-metadata?
[:& export/export-page {:id (:id data) :options (:options data)}])
(let [shapes (->> shapes
(remove cph/frame-shape?)
(mapcat #(cph/get-children-with-self objects (:id %))))
fonts (ff/shapes->fonts shapes)]
[:& ff/fontfaces-style {:fonts fonts}])
(for [item shapes]
[:& shape-wrapper {:shape item
:key (:id item)}])]]]]))
(mf/defc frame-svg
{::mf/wrap [mf/memo]}
[{:keys [objects frame zoom show-thumbnails?] :or {zoom 1} :as props}]
(let [frame-id (:id frame)
include-metadata? (mf/use-ctx export/include-metadata-ctx)
bounds (gsb/get-object-bounds objects frame)
bounds2 (gsb/get-object-bounds objects (dissoc frame :shadow :blur))
delta-bounds (gpt/point (:x bounds) (:y bounds))
vector (gpt/negate delta-bounds)
children-ids
(cph/get-children-ids objects frame-id)
objects
(mf/with-memo [frame-id objects vector]
(let [update-fn #(update %1 %2 gsh/transform-shape (ctm/move-modifiers vector))]
(->> children-ids
(into [frame-id])
(reduce update-fn objects))))
frame
(mf/with-memo [vector]
(gsh/transform-shape frame (ctm/move-modifiers vector)))
frame
(cond-> frame
(and (some? bounds) (nil? (:children-bounds bounds)))
(assoc :children-bounds bounds2))
frame (-> frame
(update-in [:children-bounds :x] - (:x delta-bounds))
(update-in [:children-bounds :y] - (:y delta-bounds)))
shape-wrapper
(mf/use-memo
(mf/deps objects)
#(shape-wrapper-factory objects))
width (* (:width bounds) zoom)
height (* (:height bounds) zoom)
vbox (format-viewbox {:width (:width bounds 0) :height (:height bounds 0)})]
[:& (mf/provider muc/render-thumbnails) {:value show-thumbnails?}
[:svg {:view-box vbox
:width (ust/format-precision width viewbox-decimal-precision)
:height (ust/format-precision height viewbox-decimal-precision)
:version "1.1"
:xmlns ""
:xmlnsXlink ""
:xmlns:penpot (when include-metadata? "")
:fill "none"}
[:& shape-wrapper {:shape frame}]]]))
(mf/defc component-svg
{::mf/wrap [mf/memo #(mf/deferred % ts/idle-then-raf)]}
[{:keys [objects root-shape zoom] :or {zoom 1} :as props}]
(let [root-shape-id (:id root-shape)
include-metadata? (mf/use-ctx export/include-metadata-ctx)
vector
(mf/use-memo
(mf/deps (:x root-shape) (:y root-shape))
(fn []
(-> (gpt/point (:x root-shape) (:y root-shape))
(gpt/negate))))
objects
(mf/use-memo
(mf/deps vector objects root-shape-id)
(fn []
(let [children-ids (cons root-shape-id (cph/get-children-ids objects root-shape-id))
update-fn #(update %1 %2 gsh/transform-shape (ctm/move-modifiers vector))]
(reduce update-fn objects children-ids))))
root-shape (get objects root-shape-id)
width (* (:width root-shape) zoom)
height (* (:height root-shape) zoom)
vbox (format-viewbox {:width (:width root-shape 0)
:height (:height root-shape 0)})
root-shape-wrapper
(mf/use-memo
(mf/deps objects root-shape)
(fn []
(case (:type root-shape)
:group (group-wrapper-factory objects)
:frame (frame-wrapper-factory objects))))]
[:svg {:view-box vbox
:width (ust/format-precision width viewbox-decimal-precision)
:height (ust/format-precision height viewbox-decimal-precision)
:version "1.1"
:xmlns ""
:xmlnsXlink ""
:xmlns:penpot (when include-metadata? "")
:fill "none"}
[:> shape-container {:shape root-shape}
[:& (mf/provider muc/is-component?) {:value true}
[:& root-shape-wrapper {:shape root-shape :view-box vbox}]]]]))
(mf/defc object-svg
{::mf/wrap [mf/memo]}
[{:keys [objects object-id render-embed?]
:or {render-embed? false}
:as props}]
(let [object (get objects object-id)
object (cond-> object
(:hide-fill-on-export object)
(assoc :fills []))
{:keys [width height] :as bounds} (gsb/get-object-bounds objects object)
vbox (format-viewbox bounds)
fonts (ff/shape->fonts object objects)
shape-wrapper
(mf/with-memo [objects]
(shape-wrapper-factory objects))]
[:& (mf/provider export/include-metadata-ctx) {:value false}
[:& (mf/provider embed/context) {:value render-embed?}
[:svg {:id (dm/str "screenshot-" object-id)
:view-box vbox
:width (ust/format-precision width viewbox-decimal-precision)
:height (ust/format-precision height viewbox-decimal-precision)
:version "1.1"
:xmlns ""
:xmlnsXlink ""
Fix Chromium bug about color of html texts
:style {:-webkit-print-color-adjust :exact}
:fill "none"}
[:& ff/fontfaces-style {:fonts fonts}]
[:& shape-wrapper {:shape object}]]]]))
(mf/defc component-symbol
[{:keys [id data] :as props}]
(let [name (:name data)
path (:path data)
objects (-> (:objects data)
(adapt-objects-for-shape id))
root-shape (get objects id)
selrect (:selrect root-shape)
main-instance-id (:main-instance-id data)
main-instance-page (:main-instance-page data)
main-instance-x (:main-instance-x data)
main-instance-y (:main-instance-y data)
vbox
(format-viewbox
{:width (:width selrect)
:height (:height selrect)})
group-wrapper
(mf/use-memo
(mf/deps objects)
(fn [] (group-wrapper-factory objects)))
frame-wrapper
(mf/use-memo
(mf/deps objects)
(fn [] (frame-wrapper-factory objects)))]
[:> "symbol" #js {:id (str id)
:viewBox vbox
"penpot:path" path
"penpot:main-instance-id" main-instance-id
"penpot:main-instance-page" main-instance-page
"penpot:main-instance-x" main-instance-x
"penpot:main-instance-y" main-instance-y}
[:title name]
[:> shape-container {:shape root-shape}
(case (:type root-shape)
:group [:& group-wrapper {:shape root-shape :view-box vbox}]
:frame [:& frame-wrapper {:shape root-shape :view-box vbox}])]]))
(mf/defc components-sprite-svg
{::mf/wrap-props false}
[props]
(let [data (obj/get props "data")
children (obj/get props "children")
render-embed? (obj/get props "render-embed?")
include-metadata? (obj/get props "include-metadata?")
source (keyword (obj/get props "source" "components"))]
[:& (mf/provider embed/context) {:value render-embed?}
[:& (mf/provider export/include-metadata-ctx) {:value include-metadata?}
[:svg {:version "1.1"
:xmlns ""
:xmlnsXlink ""
:xmlns:penpot (when include-metadata? "")
:style {:display (when-not (some? children) "none")}
:fill "none"}
[:defs
(for [[id data] (source data)]
[:& component-symbol {:id id :key (dm/str id) :data data}])]
children]]]))
(defn- get-image-data [shape]
(cond
(= :image (:type shape))
[(:metadata shape)]
(some? (:fill-image shape))
[(:fill-image shape)]
:else
[]))
(defn- populate-images-cache
[objects]
(let [images (->> objects
(vals)
(mapcat get-image-data))]
(->> (rx/from images)
(rx/map #(cfg/resolve-file-media %))
(rx/flat-map http/fetch-data-uri))))
(defn populate-fonts-cache [objects]
(let [texts (->> objects
(vals)
(filterv #(= (:type %) :text))
(mapv :content))]
(->> (rx/from texts)
(rx/map fonts/get-content-fonts)
(rx/reduce set/union #{})
(rx/flat-map identity)
(rx/flat-map fonts/fetch-font-css)
(rx/flat-map fonts/extract-fontface-urls)
(rx/flat-map http/fetch-data-uri))))
(defn render-page
[data]
(rx/concat
(->> (rx/merge
(populate-images-cache (:objects data))
(populate-fonts-cache (:objects data)))
(rx/ignore))
(->> (rx/of data)
(rx/map
(fn [data]
(let [elem (mf/element page-svg #js {:data data :render-embed? true :include-metadata? true})]
(rds/renderToStaticMarkup elem)))))))
(defn render-components
[data source]
objects (->> (source data)
(vals)
(map :objects)
(reduce conj))]
(rx/concat
(->> (rx/merge
(populate-images-cache objects)
(populate-fonts-cache objects))
(rx/ignore))
(->> (rx/of data)
(rx/map
(fn [data]
(let [elem (mf/element components-sprite-svg
#js {:data data :render-embed? true :include-metadata? true
:source (name source)})]
(rds/renderToStaticMarkup elem))))))))
|
1f407e8637cb450edd34404838bcfb372bd8245113feb8999296e221ac77a063 | anwyn/cl-horde3d | examples.lisp | ;;; examples.lisp --- Examples of the standard horde3d distribution ported to Lisp
;;; _
;;; _____ ____ _ _ __ ___ _ __ | | ___ ___
/ _ \ \/ / _ ` | ' _ ` _ \| ' _ \| |/ _ \/ _ _ |
;;; | __/> < (_| | | | | | | |_) | | __/\__ \
;;; \___/_/\_\__,_|_| |_| |_| .__/|_|\___||___/
;;; |_|
;;;
Copyright ( C ) 2009 < >
;;;
(in-package :horde3d-examples)
(defparameter *horde3d-home-directory*
(asdf:system-relative-pathname (asdf:find-system :horde3d-examples)
(make-pathname :directory '(:relative "Horde3D"))))
(defclass example-application ()
((viewer-position :accessor viewer-position :initarg :viewer-position :initform (make-array 3 :initial-element 0.0 :element-type '(or null single-float)))
(viewer-orientation :accessor viewer-orientation :initarg :viewer-orientation :initform (make-array 2 :initial-element 0.0 :element-type '(or null single-float)))
(velocity :accessor velocity :initform 10.0)
(keys :accessor keys :initform (make-hash-table))
(modifiers :accessor modifiers :initform nil)
(fullscreen :accessor fullscreen? :initarg :fullscreen :initform nil)
(width :accessor width :initarg :width)
(height :accessor height :initarg :height)
(hdr-pipeline :accessor hdr-pipeline :initarg :hdr-pipeline)
(fwd-pipeline :accessor fwd-pipeline :initarg :fwd-pipeline)
(camera-node :accessor camera-node :initarg :camera-node)
(anim-time :accessor anim-time :initarg :anim-time :initform 0.0)
(anim-weight :accessor anim-weight :initarg :anim-weight :initform 1.0)
(curr-fps :accessor curr-fps :initarg :curr-fps :initform 30.0)
(logo-resource :accessor logo-resource :initarg :logo-resource)
(font-resource :accessor font-resource :initarg :font-resource)
(panel-resource :accessor panel-resource :initarg :panel-resource)
(content-path :accessor content-path :initarg :content-path)
(debug-view :accessor show-debug-view? :initarg :show-debug-view :initform nil)
(wire-frame :accessor show-wire-frame? :initarg :show-wire-frame :initform nil)
(freeze :accessor freeze? :initarg :freeze :initform nil)
(stat-mode :accessor stat-mode :initarg :stat-mode :initform 0))
(:documentation "Base class for Horde3D Examples. Inits/releases Horde and handles basic
keys and mouse movement."))
(defgeneric app-init (app)
(:method :before ((app example-application))
(h3d:init)
(h3d:set-option :load-textures 1)
(h3d:set-option :texture-compression 0)
(h3d:set-option :fast-animation 0)
(h3d:set-option :max-anisotropy 4)
(h3d:set-option :shadow-map-size 2048)
(setf (fwd-pipeline app) (h3d:add-resource :pipeline "pipelines/forward.pipeline.xml" 0)
(font-resource app) (h3d:add-resource :material "overlays/font.material.xml" 0)
(panel-resource app) (h3d:add-resource :material "overlays/panel.material.xml" 0)
(logo-resource app) (h3d:add-resource :material "overlays/logo.material.xml" 0))))
(defgeneric app-release (app)
(:method ((app example-application))
(declare (ignore app)))
(:method :after ((app example-application))
(declare (ignore app))
(h3d:release)))
(defgeneric app-resize (app width height)
(:documentation "Set window of app to new width and height.")
(:method :after ((app example-application) width height)
(setf (width app) width
(height app) height))
(:method ((app example-application) width height)
(let ((cam (camera-node app)))
(setf (h3d:node-parameter cam :camera-viewport-x) 0
(h3d:node-parameter cam :camera-viewport-y) 0
(h3d:node-parameter cam :camera-viewport-width) width
(h3d:node-parameter cam :camera-viewport-height) height)
(h3d:setup-camera-view cam 45.0 (/ width height) 0.1 1000.0)
(h3d:resize-pipeline-buffers (hdr-pipeline app) width height)
(h3d:resize-pipeline-buffers (fwd-pipeline app) width height))))
(defgeneric app-key-press-event (app key)
(:documentation "Key handler")
(:method ((app example-application) key)
(declare (ignore app key)))
(:method ((app example-application) (key (eql :sdl-key-escape)))
(sdl:push-quit-event))
(:method ((app example-application) (key (eql :sdl-key-space)))
(setf (freeze? app) (not (freeze? app))))
(:method ((app example-application) (key (eql :sdl-key-f1)))
(toggle-fullscreen app))
(:method ((app example-application) (key (eql :sdl-key-f3)))
(with-accessors ((cam camera-node)) app
(if (eql (h3d:node-parameter cam :camera-pipeline-resource) (fwd-pipeline app))
(setf (h3d:node-parameter cam :camera-pipeline-resource) (hdr-pipeline app))
(setf (h3d:node-parameter cam :camera-pipeline-resource) (fwd-pipeline app)))))
(:method ((app example-application) (key (eql :sdl-key-f7)))
(setf (show-debug-view? app) (not (show-debug-view? app))))
(:method ((app example-application) (key (eql :sdl-key-f8)))
(setf (show-wire-frame? app) (not (show-wire-frame? app))))
(:method ((app example-application) (key (eql :sdl-key-f9)))
(when (> (incf (stat-mode app)) 2)
(setf (stat-mode app) 0))))
(defgeneric app-key-release-event (app key)
(:method ((app example-application) key)
(declare (ignore app key))))
(defgeneric app-mouse-move-event (app x y)
(:method ((app example-application) x y)
(declare (ignore app x y)))
(:method :before ((app example-application) x y)
(decf (aref (viewer-orientation app) 1)
(coerce (* 30 (/ x 100)) 'single-float))
(incf (aref (viewer-orientation app) 0)
(coerce (max -90 (min 90 (* 30 (/ y 100)))) 'single-float))))
(declaim (inline degtorad))
(defun degtorad (angle)
(coerce (* angle (/ pi 180.0)) 'single-float))
(declaim (inline radtodeg))
(defun radtodeg (angle)
(coerce (* angle (/ 180.0 pi)) 'single-float))
(defun handle-movement (app)
(let ((curr-vel (/ (velocity app) (curr-fps app))))
(declare (type single-float curr-vel))
(with-accessors ((mods modifiers)
(keys keys)
(pos viewer-position)
(rot viewer-orientation)) app
(when (member :sdl-key-mod-lshift mods)
(setf curr-vel (* 5 curr-vel)))
(let ((w (gethash :sdl-key-w keys))
(s (gethash :sdl-key-s keys)))
(when (or w s)
(let ((rx (degtorad (aref rot 0)))
(ry (degtorad (aref rot 1))))
(declare (type single-float rx ry))
(when w
(decf (aref pos 0) (coerce (* curr-vel (sin ry) (cos (- rx))) 'single-float))
(decf (aref pos 1) (coerce (* curr-vel (sin (- rx))) 'single-float))
(decf (aref pos 2) (coerce (* curr-vel (cos ry) (cos (- rx))) 'single-float)))
(when s
(incf (aref pos 0) (coerce (* curr-vel (sin ry) (cos (- rx))) 'single-float))
(incf (aref pos 1) (coerce (* curr-vel (sin (- rx))) 'single-float))
(incf (aref pos 2) (coerce (* curr-vel (cos ry) (cos (- rx))) 'single-float))))))
(let ((a (gethash :sdl-key-a keys))
(d (gethash :sdl-key-d keys)))
(when (or a d)
(let ((ry-90 (degtorad (- (aref rot 1) 90.0f0)))
(ry+90 (degtorad (+ (aref rot 1) 90.0f0))))
(declare (type single-float ry-90 ry+90))
(when a
(incf (aref pos 0) (coerce (* curr-vel (sin ry-90)) 'single-float))
(incf (aref pos 2) (coerce (* curr-vel (cos ry-90)) 'single-float)))
(when (gethash :sdl-key-d keys)
(incf (aref pos 0) (coerce (* curr-vel (sin ry+90)) 'single-float))
(incf (aref pos 2) (coerce (* curr-vel (cos ry+90)) 'single-float)))))))))
(defgeneric app-main-loop (app)
(:method :before ((app example-application))
(h3d:set-option :debug-view-mode (if (show-debug-view? app) 1 0))
(h3d:set-option :wireframe-mode (if (show-wire-frame? app) 1 0))
(handle-movement app))
(:method :after ((app example-application))
(h3d:finalize-frame)
(h3d:clear-overlays)
(h3d:dump-messages)))
(defgeneric toggle-fullscreen (app)
(:documentation "Switch from windowed mode to fullscreen an vice versa.")
(:method ((app example-application))
(let ((width (width app))
(height (height app)))
(app-release app)
(if (fullscreen? app)
(sdl:resize-window width height :flags '(sdl:sdl-opengl sdl:sdl-resizable))
(sdl:resize-window width height :flags '(sdl:sdl-opengl sdl:sdl-fullscreen)))
(setf (fullscreen? app) (if (fullscreen? app) nil t))
(app-init app)
(app-resize app width height))))
(defun example-main-sdl (app &key (width 800) (height 600) (caption "Horde3D example"))
"Main example function. This function contains the game loop. Call it with an
instance of a class derived from example-application."
(sdl:with-init ()
(sdl:window width height
:bpp 32
:flags sdl:sdl-opengl
:title-caption caption
:icon-caption caption)
(app-init app)
(app-resize app width height)
(setf (sdl:frame-rate) 0)
(sdl:enable-unicode)
(let ((frames 0)
(fps 100.0)
(mx 0)
(my 0)
(m-init nil))
(sdl:with-events ()
;; Redraw display
(:video-expose-event ()
(sdl:update-display))
;; leave example
(:quit-event () (app-release app) t)
(:active-event (:gain gain)
(when (= gain 1)
(setf m-init nil)))
(:mouse-motion-event (:x x :y y)
(when (null m-init)
(setf m-init t)
(setf mx x my y))
(when (not (freeze? app))
(app-mouse-move-event app (- x mx) (- y my)))
(setf mx x my y))
;; Key pressed
(:key-down-event (:key key :mod-key mod)
(setf (modifiers app) mod)
(setf (gethash key (keys app)) t)
(app-key-press-event app key))
;; Key released
(:key-up-event (:key key :mod-key mod)
(setf (modifiers app) mod)
(setf (gethash key (keys app)) nil)
(app-key-release-event app key))
;; Do work
(:idle ()
(when (>= (incf frames) 3)
(setf fps (max 100.0 (sdl:average-fps)))
(setf frames 0))
(setf (curr-fps app) (coerce fps 'single-float))
(with-simple-restart
(skip-game-loop "Skip game loop for this frame")
(app-main-loop app))
# + horde3d - debug
;; (with-simple-restart
;; (skip-swank-request "Skip swank evaluation")
;; (let ((connection
;; (or swank::*emacs-connection* (swank::default-connection))))
;; (swank::handle-requests connection t)))
(sdl:update-display))))))
;;; examples.lisp ends here
| null | https://raw.githubusercontent.com/anwyn/cl-horde3d/0576aba1879ab6c0f7688566c604d022cc538b4c/examples/examples.lisp | lisp | examples.lisp --- Examples of the standard horde3d distribution ported to Lisp
_
_____ ____ _ _ __ ___ _ __ | | ___ ___
| __/> < (_| | | | | | | |_) | | __/\__ \
\___/_/\_\__,_|_| |_| |_| .__/|_|\___||___/
|_|
Redraw display
leave example
Key pressed
Key released
Do work
(with-simple-restart
(skip-swank-request "Skip swank evaluation")
(let ((connection
(or swank::*emacs-connection* (swank::default-connection))))
(swank::handle-requests connection t)))
examples.lisp ends here | / _ \ \/ / _ ` | ' _ ` _ \| ' _ \| |/ _ \/ _ _ |
Copyright ( C ) 2009 < >
(in-package :horde3d-examples)
(defparameter *horde3d-home-directory*
(asdf:system-relative-pathname (asdf:find-system :horde3d-examples)
(make-pathname :directory '(:relative "Horde3D"))))
(defclass example-application ()
((viewer-position :accessor viewer-position :initarg :viewer-position :initform (make-array 3 :initial-element 0.0 :element-type '(or null single-float)))
(viewer-orientation :accessor viewer-orientation :initarg :viewer-orientation :initform (make-array 2 :initial-element 0.0 :element-type '(or null single-float)))
(velocity :accessor velocity :initform 10.0)
(keys :accessor keys :initform (make-hash-table))
(modifiers :accessor modifiers :initform nil)
(fullscreen :accessor fullscreen? :initarg :fullscreen :initform nil)
(width :accessor width :initarg :width)
(height :accessor height :initarg :height)
(hdr-pipeline :accessor hdr-pipeline :initarg :hdr-pipeline)
(fwd-pipeline :accessor fwd-pipeline :initarg :fwd-pipeline)
(camera-node :accessor camera-node :initarg :camera-node)
(anim-time :accessor anim-time :initarg :anim-time :initform 0.0)
(anim-weight :accessor anim-weight :initarg :anim-weight :initform 1.0)
(curr-fps :accessor curr-fps :initarg :curr-fps :initform 30.0)
(logo-resource :accessor logo-resource :initarg :logo-resource)
(font-resource :accessor font-resource :initarg :font-resource)
(panel-resource :accessor panel-resource :initarg :panel-resource)
(content-path :accessor content-path :initarg :content-path)
(debug-view :accessor show-debug-view? :initarg :show-debug-view :initform nil)
(wire-frame :accessor show-wire-frame? :initarg :show-wire-frame :initform nil)
(freeze :accessor freeze? :initarg :freeze :initform nil)
(stat-mode :accessor stat-mode :initarg :stat-mode :initform 0))
(:documentation "Base class for Horde3D Examples. Inits/releases Horde and handles basic
keys and mouse movement."))
(defgeneric app-init (app)
(:method :before ((app example-application))
(h3d:init)
(h3d:set-option :load-textures 1)
(h3d:set-option :texture-compression 0)
(h3d:set-option :fast-animation 0)
(h3d:set-option :max-anisotropy 4)
(h3d:set-option :shadow-map-size 2048)
(setf (fwd-pipeline app) (h3d:add-resource :pipeline "pipelines/forward.pipeline.xml" 0)
(font-resource app) (h3d:add-resource :material "overlays/font.material.xml" 0)
(panel-resource app) (h3d:add-resource :material "overlays/panel.material.xml" 0)
(logo-resource app) (h3d:add-resource :material "overlays/logo.material.xml" 0))))
(defgeneric app-release (app)
(:method ((app example-application))
(declare (ignore app)))
(:method :after ((app example-application))
(declare (ignore app))
(h3d:release)))
(defgeneric app-resize (app width height)
(:documentation "Set window of app to new width and height.")
(:method :after ((app example-application) width height)
(setf (width app) width
(height app) height))
(:method ((app example-application) width height)
(let ((cam (camera-node app)))
(setf (h3d:node-parameter cam :camera-viewport-x) 0
(h3d:node-parameter cam :camera-viewport-y) 0
(h3d:node-parameter cam :camera-viewport-width) width
(h3d:node-parameter cam :camera-viewport-height) height)
(h3d:setup-camera-view cam 45.0 (/ width height) 0.1 1000.0)
(h3d:resize-pipeline-buffers (hdr-pipeline app) width height)
(h3d:resize-pipeline-buffers (fwd-pipeline app) width height))))
(defgeneric app-key-press-event (app key)
(:documentation "Key handler")
(:method ((app example-application) key)
(declare (ignore app key)))
(:method ((app example-application) (key (eql :sdl-key-escape)))
(sdl:push-quit-event))
(:method ((app example-application) (key (eql :sdl-key-space)))
(setf (freeze? app) (not (freeze? app))))
(:method ((app example-application) (key (eql :sdl-key-f1)))
(toggle-fullscreen app))
(:method ((app example-application) (key (eql :sdl-key-f3)))
(with-accessors ((cam camera-node)) app
(if (eql (h3d:node-parameter cam :camera-pipeline-resource) (fwd-pipeline app))
(setf (h3d:node-parameter cam :camera-pipeline-resource) (hdr-pipeline app))
(setf (h3d:node-parameter cam :camera-pipeline-resource) (fwd-pipeline app)))))
(:method ((app example-application) (key (eql :sdl-key-f7)))
(setf (show-debug-view? app) (not (show-debug-view? app))))
(:method ((app example-application) (key (eql :sdl-key-f8)))
(setf (show-wire-frame? app) (not (show-wire-frame? app))))
(:method ((app example-application) (key (eql :sdl-key-f9)))
(when (> (incf (stat-mode app)) 2)
(setf (stat-mode app) 0))))
(defgeneric app-key-release-event (app key)
(:method ((app example-application) key)
(declare (ignore app key))))
(defgeneric app-mouse-move-event (app x y)
(:method ((app example-application) x y)
(declare (ignore app x y)))
(:method :before ((app example-application) x y)
(decf (aref (viewer-orientation app) 1)
(coerce (* 30 (/ x 100)) 'single-float))
(incf (aref (viewer-orientation app) 0)
(coerce (max -90 (min 90 (* 30 (/ y 100)))) 'single-float))))
(declaim (inline degtorad))
(defun degtorad (angle)
(coerce (* angle (/ pi 180.0)) 'single-float))
(declaim (inline radtodeg))
(defun radtodeg (angle)
(coerce (* angle (/ 180.0 pi)) 'single-float))
(defun handle-movement (app)
(let ((curr-vel (/ (velocity app) (curr-fps app))))
(declare (type single-float curr-vel))
(with-accessors ((mods modifiers)
(keys keys)
(pos viewer-position)
(rot viewer-orientation)) app
(when (member :sdl-key-mod-lshift mods)
(setf curr-vel (* 5 curr-vel)))
(let ((w (gethash :sdl-key-w keys))
(s (gethash :sdl-key-s keys)))
(when (or w s)
(let ((rx (degtorad (aref rot 0)))
(ry (degtorad (aref rot 1))))
(declare (type single-float rx ry))
(when w
(decf (aref pos 0) (coerce (* curr-vel (sin ry) (cos (- rx))) 'single-float))
(decf (aref pos 1) (coerce (* curr-vel (sin (- rx))) 'single-float))
(decf (aref pos 2) (coerce (* curr-vel (cos ry) (cos (- rx))) 'single-float)))
(when s
(incf (aref pos 0) (coerce (* curr-vel (sin ry) (cos (- rx))) 'single-float))
(incf (aref pos 1) (coerce (* curr-vel (sin (- rx))) 'single-float))
(incf (aref pos 2) (coerce (* curr-vel (cos ry) (cos (- rx))) 'single-float))))))
(let ((a (gethash :sdl-key-a keys))
(d (gethash :sdl-key-d keys)))
(when (or a d)
(let ((ry-90 (degtorad (- (aref rot 1) 90.0f0)))
(ry+90 (degtorad (+ (aref rot 1) 90.0f0))))
(declare (type single-float ry-90 ry+90))
(when a
(incf (aref pos 0) (coerce (* curr-vel (sin ry-90)) 'single-float))
(incf (aref pos 2) (coerce (* curr-vel (cos ry-90)) 'single-float)))
(when (gethash :sdl-key-d keys)
(incf (aref pos 0) (coerce (* curr-vel (sin ry+90)) 'single-float))
(incf (aref pos 2) (coerce (* curr-vel (cos ry+90)) 'single-float)))))))))
(defgeneric app-main-loop (app)
(:method :before ((app example-application))
(h3d:set-option :debug-view-mode (if (show-debug-view? app) 1 0))
(h3d:set-option :wireframe-mode (if (show-wire-frame? app) 1 0))
(handle-movement app))
(:method :after ((app example-application))
(h3d:finalize-frame)
(h3d:clear-overlays)
(h3d:dump-messages)))
(defgeneric toggle-fullscreen (app)
(:documentation "Switch from windowed mode to fullscreen an vice versa.")
(:method ((app example-application))
(let ((width (width app))
(height (height app)))
(app-release app)
(if (fullscreen? app)
(sdl:resize-window width height :flags '(sdl:sdl-opengl sdl:sdl-resizable))
(sdl:resize-window width height :flags '(sdl:sdl-opengl sdl:sdl-fullscreen)))
(setf (fullscreen? app) (if (fullscreen? app) nil t))
(app-init app)
(app-resize app width height))))
(defun example-main-sdl (app &key (width 800) (height 600) (caption "Horde3D example"))
"Main example function. This function contains the game loop. Call it with an
instance of a class derived from example-application."
(sdl:with-init ()
(sdl:window width height
:bpp 32
:flags sdl:sdl-opengl
:title-caption caption
:icon-caption caption)
(app-init app)
(app-resize app width height)
(setf (sdl:frame-rate) 0)
(sdl:enable-unicode)
(let ((frames 0)
(fps 100.0)
(mx 0)
(my 0)
(m-init nil))
(sdl:with-events ()
(:video-expose-event ()
(sdl:update-display))
(:quit-event () (app-release app) t)
(:active-event (:gain gain)
(when (= gain 1)
(setf m-init nil)))
(:mouse-motion-event (:x x :y y)
(when (null m-init)
(setf m-init t)
(setf mx x my y))
(when (not (freeze? app))
(app-mouse-move-event app (- x mx) (- y my)))
(setf mx x my y))
(:key-down-event (:key key :mod-key mod)
(setf (modifiers app) mod)
(setf (gethash key (keys app)) t)
(app-key-press-event app key))
(:key-up-event (:key key :mod-key mod)
(setf (modifiers app) mod)
(setf (gethash key (keys app)) nil)
(app-key-release-event app key))
(:idle ()
(when (>= (incf frames) 3)
(setf fps (max 100.0 (sdl:average-fps)))
(setf frames 0))
(setf (curr-fps app) (coerce fps 'single-float))
(with-simple-restart
(skip-game-loop "Skip game loop for this frame")
(app-main-loop app))
# + horde3d - debug
(sdl:update-display))))))
|
a234426cc4c2a83fdf7ef44f71bada0d1067be0bc6960c1bcd4ca83e8f42a271 | realworldocaml/examples | multiple_inheritance.ml | open Core.Std
open Async.Std
open Async_graphics
class virtual shape x y = object(self)
method virtual private contains: int -> int -> bool
val mutable x: int = x
method x = x
val mutable y: int = y
method y = y
method on_click ?start ?stop f =
on_click ?start ?stop
(fun {mouse_x;mouse_y} ->
if self#contains mouse_x mouse_y then
f mouse_x mouse_y)
method on_mousedown ?start ?stop f =
on_mousedown ?start ?stop
(fun {mouse_x;mouse_y} ->
if self#contains mouse_x mouse_y then
f mouse_x mouse_y)
end
class square w x y = object
inherit shape x y
val mutable width = w
method width = width
method draw = fill_rect x y width width
method private contains x' y' =
x <= x' && x' <= x + width &&
y <= y' && y' <= y + width
end
part 1
class square_outline w x y = object
inherit square w x y
method draw = draw_rect x y width width
end
| null | https://raw.githubusercontent.com/realworldocaml/examples/32ea926861a0b728813a29b0e4cf20dd15eb486e/code/classes-async/multiple_inheritance.ml | ocaml | open Core.Std
open Async.Std
open Async_graphics
class virtual shape x y = object(self)
method virtual private contains: int -> int -> bool
val mutable x: int = x
method x = x
val mutable y: int = y
method y = y
method on_click ?start ?stop f =
on_click ?start ?stop
(fun {mouse_x;mouse_y} ->
if self#contains mouse_x mouse_y then
f mouse_x mouse_y)
method on_mousedown ?start ?stop f =
on_mousedown ?start ?stop
(fun {mouse_x;mouse_y} ->
if self#contains mouse_x mouse_y then
f mouse_x mouse_y)
end
class square w x y = object
inherit shape x y
val mutable width = w
method width = width
method draw = fill_rect x y width width
method private contains x' y' =
x <= x' && x' <= x + width &&
y <= y' && y' <= y + width
end
part 1
class square_outline w x y = object
inherit square w x y
method draw = draw_rect x y width width
end
| |
7a2a9fb68c10bf9e529796c8a12af2c616a3156f4c5dfb363c1867a8e7a918b6 | clojure-interop/aws-api | S3ControlClientOptions.clj | (ns com.amazonaws.services.s3control.S3ControlClientOptions
(:refer-clojure :only [require comment defn ->])
(:import [com.amazonaws.services.s3control S3ControlClientOptions]))
(defn ->s-3-control-client-options
"Constructor."
(^S3ControlClientOptions []
(new S3ControlClientOptions )))
(def *-dualstack-enabled
"Static Constant.
Advanced option to enable dualstack endpoints.
type: com.amazonaws.client.builder.AdvancedConfig$Key<java.lang.Boolean>"
S3ControlClientOptions/DUALSTACK_ENABLED)
(def *-fips-enabled
"Static Constant.
Advanced option to use fips endpoints.
type: com.amazonaws.client.builder.AdvancedConfig$Key<java.lang.Boolean>"
S3ControlClientOptions/FIPS_ENABLED)
| null | https://raw.githubusercontent.com/clojure-interop/aws-api/59249b43d3bfaff0a79f5f4f8b7bc22518a3bf14/com.amazonaws.services.s3control/src/com/amazonaws/services/s3control/S3ControlClientOptions.clj | clojure | (ns com.amazonaws.services.s3control.S3ControlClientOptions
(:refer-clojure :only [require comment defn ->])
(:import [com.amazonaws.services.s3control S3ControlClientOptions]))
(defn ->s-3-control-client-options
"Constructor."
(^S3ControlClientOptions []
(new S3ControlClientOptions )))
(def *-dualstack-enabled
"Static Constant.
Advanced option to enable dualstack endpoints.
type: com.amazonaws.client.builder.AdvancedConfig$Key<java.lang.Boolean>"
S3ControlClientOptions/DUALSTACK_ENABLED)
(def *-fips-enabled
"Static Constant.
Advanced option to use fips endpoints.
type: com.amazonaws.client.builder.AdvancedConfig$Key<java.lang.Boolean>"
S3ControlClientOptions/FIPS_ENABLED)
| |
552480a585ddcce450088c1f6f444997ba6d67f08473877b02b2b8d5ad3fe19b | erlangonrails/devdb | riak_kv_wm_raw.erl | %% -------------------------------------------------------------------
%%
raw_http_resource : Webmachine resource for serving data
%%
Copyright ( c ) 2007 - 2010 Basho Technologies , Inc. All Rights Reserved .
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% -------------------------------------------------------------------
@doc Resource for serving objects over HTTP .
%%
%% Available operations:
%%
%% GET /Prefix/Bucket
%% Get information about the named Bucket, in JSON form:
{ " props":{Prop1 : Val1,Prop2 : Val2 , ... } ,
%% "keys":[Key1,Key2,...]}.
%% Each bucket property will be included in the "props" object.
%% "linkfun" and "chash_keyfun" properties will be encoded as
%% JSON objects of the form:
%% {"mod":ModuleName,
%% "fun":FunctionName}
Where ModuleName and FunctionName are each strings representing
%% a module and function.
%% Including the query param "props=false" will cause the "props"
%% field to be omitted from the response.
%% Including the query param "keys=false" will cause the "keys"
%% field to be omitted from the response.
%%
%% PUT /Prefix/Bucket
%% Modify bucket properties.
%% Content-type must be application/json, and the body must have
%% the form:
%% {"props":{Prop:Val}}
%% Where the "props" object takes the same form as returned from
%% a GET of the same resource.
%%
%% POST /Prefix/Bucket
Equivalent to " PUT /Prefix / Bucket / Key " where Key is chosen
%% by the server.
%%
%% GET /Prefix/Bucket/Key
Get the data stored in the named Bucket under the named Key .
%% Content-type of the response will be whatever incoming
%% Content-type was used in the request that stored the data.
%% Additional headers will include:
%% X-Riak-Vclock: The vclock of the object.
%% Link: The links the object has
Etag : The " vtag " metadata of the object
%% Last-Modified: The last-modified time of the object
%% Encoding: The value of the incoming Encoding header from
%% the request that stored the data.
X - Riak - Meta- : Any headers prefixed by X - Riak - Meta- supplied
on PUT are returned verbatim
Specifying the query param " r = R " , where R is an integer will
cause to use R as the r - value for the read request . A
default r - value of 2 will be used if none is specified .
%% If the object is found to have siblings (only possible if the
%% bucket property "allow_mult" has been set to true), then
%% Content-type will be text/plain; Link, Etag, and Last-Modified
%% headers will be omitted; and the body of the response will
%% be a list of the vtags of each sibling. To request a specific
%% sibling, include the query param "vtag=V", where V is the vtag
%% of the sibling you want.
%%
%% PUT /Prefix/Bucket/Key
Store new data in the named Bucket under the named Key .
%% A Content-type header *must* be included in the request. The
%% value of this header will be used in the response to subsequent
%% GET requests.
%% The body of the request will be stored literally as the value
%% of the riak_object, and will be served literally as the body of
%% the response to subsequent GET requests.
%% Include an X-Riak-Vclock header to modify data without creating
%% siblings.
%% Include a Link header to set the links of the object.
%% Include an Encoding header if you would like an Encoding header
%% to be included in the response to subsequent GET requests.
Include custom metadata using headers prefixed with X - Riak - Meta- .
%% They will be returned verbatim on subsequent GET requests.
Specifying the query param " w = W " , where W is an integer will
cause to use W as the w - value for the write request . A
default w - value of 2 will be used if none is specified .
Specifying the query param " dw = DW " , where DW is an integer will
cause to use DW as the dw - value for the write request . A
%% default dw-value of 0 will be used if none is specified.
Specifying the query param " r = R " , where R is an integer will
cause to use R as the r - value for the read request ( used
%% to determine whether or not the resource exists). A default
r - value of 2 will be used if none is specified .
%%
%% POST /Prefix/Bucket/Key
Equivalent to " PUT /Prefix / Bucket / Key " ( useful for clients that
do not support the PUT method ) .
%%
%% DELETE /Prefix/Bucket/Key
Delete the data stored in the named Bucket under the named Key .
Specifying the query param " rw = RW " , where RW is an integer will
cause to use RW as the rw - value for the delete request . A
default rw - value of 2 will be used if none is specified .
%%
Webmachine dispatch lines for this resource should look like :
%%
%% {["riak", bucket],
%% riak_kv_wm_raw,
%% [{prefix, "riak"},
%% {riak, local} %% or {riak, {'riak@127.0.0.1', riak_cookie}}
%% ]}.
%% {["riak", bucket, key],
%% riak_kv_wm_raw,
%% [{prefix, "riak"},
%% {riak, local} %% or {riak, {'riak@127.0.0.1', riak_cookie}}
%% ]}.
%%
%% These example dispatch lines will expose this resource at
/riak / Bucket and /riak / Bucket / Key . The resource will attempt to
connect to on the same Erlang node one which the resource
%% is executing. Using the alternate {riak, {Node, Cookie}} form
%% will cause the resource to connect to riak on the specified
%% Node with the specified Cookie.
-module(riak_kv_wm_raw).
-author('Bryan Fink <>').
%% webmachine resource exports
-export([
init/1,
service_available/2,
allowed_methods/2,
allow_missing_post/2,
malformed_request/2,
resource_exists/2,
last_modified/2,
generate_etag/2,
content_types_provided/2,
charsets_provided/2,
encodings_provided/2,
content_types_accepted/2,
produce_bucket_body/2,
accept_bucket_body/2,
post_is_create/2,
create_path/2,
process_post/2,
produce_doc_body/2,
accept_doc_body/2,
produce_sibling_message_body/2,
produce_multipart_body/2,
multiple_choices/2,
delete_resource/2
]).
utility exports ( used in )
-export([
vclock_header/1,
format_link/2, format_link/4,
multipart_encode_body/3
]).
%% @type context() = term()
-record(ctx, {bucket, %% binary() - Bucket name (from uri)
key, %% binary() - Key (from uri)
client, %% riak_client() - the store client
r, %% integer() - r-value for reads
w, %% integer() - w-value for writes
dw, %% integer() - dw-value for writes
rw, %% integer() - rw-value for deletes
prefix, %% string() - prefix for resource uris
riak, %% local | {node(), atom()} - params for riak client
doc, %% {ok, riak_object()}|{error, term()} - the object found
vtag, %% string() - vtag the user asked for
bucketprops, %% proplist() - properties of the bucket
links, %% [link()] - links of the object
method %% atom() - HTTP method for the request
}).
@type link ( ) = { ( ) , Key::binary ( ) } , Tag::binary ( ) }
-include_lib("webmachine/include/webmachine.hrl").
-include("riak_kv_wm_raw.hrl").
%% @spec init(proplist()) -> {ok, context()}
%% @doc Initialize this resource. This function extracts the
%% 'prefix' and 'riak' properties from the dispatch args.
init(Props) ->
{ok, #ctx{prefix=proplists:get_value(prefix, Props),
riak=proplists:get_value(riak, Props)}}.
( ) , context ( ) ) - >
%% {boolean(), reqdata(), context()}
@doc Determine whether or not a connection to Riak
%% can be established. This function also takes this
%% opportunity to extract the 'bucket' and 'key' path
%% bindings from the dispatch, as well as any vtag
%% query parameter.
service_available(RD, Ctx=#ctx{riak=RiakProps}) ->
case get_riak_client(RiakProps, get_client_id(RD)) of
{ok, C} ->
{true,
RD,
Ctx#ctx{
method=wrq:method(RD),
client=C,
bucket=list_to_binary(wrq:path_info(bucket, RD)),
key=case wrq:path_info(key, RD) of
undefined -> undefined;
K -> list_to_binary(K)
end,
vtag=wrq:get_qs_value(?Q_VTAG, RD)
}};
Error ->
{false,
wrq:set_resp_body(
io_lib:format("Unable to connect to Riak: ~p~n", [Error]),
wrq:set_resp_header(?HEAD_CTYPE, "text/plain", RD)),
Ctx}
end.
( ) } , term ( ) ) - >
%% {ok, riak_client()} | error()
%% @doc Get a riak_client.
get_riak_client(local, ClientId) ->
riak:local_client(ClientId);
get_riak_client({Node, Cookie}, ClientId) ->
erlang:set_cookie(node(), Cookie),
riak:client_connect(Node, ClientId).
( ) ) - > term ( )
%% @doc Extract the request's preferred client id from the
%% X-Riak-ClientId header. Return value will be:
%% 'undefined' if no header was found
32 - bit binary ( ) if the header could be base64 - decoded
into a 32 - bit binary
%% string() if the header could not be base64-decoded
into a 32 - bit binary
get_client_id(RD) ->
case wrq:get_req_header(?HEAD_CLIENT, RD) of
undefined -> undefined;
RawId ->
case catch base64:decode(RawId) of
ClientId= <<_:32>> -> ClientId;
_ -> RawId
end
end.
%% @spec allowed_methods(reqdata(), context()) ->
%% {[method()], reqdata(), context()}
%% @doc Get the list of methods this resource supports.
HEAD , GET , POST , and PUT are supported at both
%% the bucket and key levels. DELETE is supported
%% at the key level only.
allowed_methods(RD, Ctx=#ctx{key=undefined}) ->
%% bucket-level: no delete
{['HEAD', 'GET', 'POST', 'PUT'], RD, Ctx};
allowed_methods(RD, Ctx) ->
%% key-level: just about anything
{['HEAD', 'GET', 'POST', 'PUT', 'DELETE'], RD, Ctx}.
allow_missing_post(reqdata ( ) , context ( ) ) - >
%% {true, reqdata(), context()}
@doc Makes POST and PUT equivalent for creating new
%% bucket entries.
allow_missing_post(RD, Ctx) ->
{true, RD, Ctx}.
( ) , context ( ) ) - > boolean ( )
%% @doc Determine whether this request is of the form
%% PUT /Prefix/Bucket
%% This method expects the 'key' path binding to have
%% been set in the 'key' field of the context().
is_bucket_put(RD, Ctx) ->
{undefined, 'PUT'} =:= {Ctx#ctx.key, wrq:method(RD)}.
%% @spec malformed_request(reqdata(), context()) ->
%% {boolean(), reqdata(), context()}
%% @doc Determine whether query parameters, request headers,
%% and request body are badly-formed.
%% Body format is checked to be valid JSON, including
%% a "props" object for a bucket-PUT. Body format
%% is not tested for a key-level request (since the
%% body may be any content the client desires).
%% Query parameters r, w, dw, and rw are checked to
%% be valid integers. Their values are stored in
%% the context() at this time.
%% Link headers are checked for the form:
& lt;/Prefix / Bucket / Key> ; ; " , ...
%% The parsed links are stored in the context()
%% at this time.
malformed_request(RD, Ctx) when Ctx#ctx.method =:= 'POST'
orelse Ctx#ctx.method =:= 'PUT' ->
case is_bucket_put(RD, Ctx) of
true ->
malformed_bucket_put(RD, Ctx);
false ->
case wrq:get_req_header("Content-Type", RD) of
undefined ->
{true, missing_content_type(RD), Ctx};
_ ->
case malformed_rw_params(RD, Ctx) of
Result={true, _, _} -> Result;
{false, RWRD, RWCtx} ->
malformed_link_headers(RWRD, RWCtx)
end
end
end;
malformed_request(RD, Ctx) ->
case malformed_rw_params(RD, Ctx) of
Result={true, _, _} -> Result;
{false, RWRD, RWCtx} ->
malformed_link_headers(RWRD, RWCtx)
end.
%% @spec malformed_bucket_put(reqdata(), context()) ->
%% {boolean(), reqdata(), context()}
@doc Check the JSON format of a bucket - level PUT .
%% Must be a valid JSON object, containing a "props" object.
malformed_bucket_put(RD, Ctx) ->
case catch mochijson2:decode(wrq:req_body(RD)) of
{struct, Fields} ->
case proplists:get_value(?JSON_PROPS, Fields) of
{struct, Props} ->
{false, RD, Ctx#ctx{bucketprops=Props}};
_ ->
{true, bucket_format_message(RD), Ctx}
end;
_ ->
{true, bucket_format_message(RD), Ctx}
end.
( ) ) - > reqdata ( )
%% @doc Put an error about the format of the bucket-PUT body
%% in the response body of the reqdata().
bucket_format_message(RD) ->
wrq:append_to_resp_body(
["bucket PUT must be a JSON object of the form:\n",
"{\"",?JSON_PROPS,"\":{...bucket properties...}}"],
wrq:set_resp_header(?HEAD_CTYPE, "text/plain", RD)).
( ) , context ( ) ) - >
%% {boolean(), reqdata(), context()}
%% @doc Check that r, w, dw, and rw query parameters are
%% string-encoded integers. Store the integer values
%% in context() if so.
malformed_rw_params(RD, Ctx) ->
lists:foldl(fun malformed_rw_param/2,
{false, RD, Ctx},
[{#ctx.r, "r", "2"},
{#ctx.w, "w", "2"},
{#ctx.dw, "dw", "0"},
{#ctx.rw, "rw", "2"}]).
( ) , Name::string ( ) , Default::string ( ) } ,
%% {boolean(), reqdata(), context()}) ->
%% {boolean(), reqdata(), context()}
%% @doc Check that a specific r, w, dw, or rw query param is a
%% string-encoded integer. Store its result in context() if it
is , or print an error message in ( ) if it is not .
malformed_rw_param({Idx, Name, Default}, {Result, RD, Ctx}) ->
case catch list_to_integer(wrq:get_qs_value(Name, Default, RD)) of
N when is_integer(N) ->
{Result, RD, setelement(Idx, Ctx, N)};
_ ->
{true,
wrq:append_to_resp_body(
io_lib:format("~s query parameter must be an integer~n",
[Name]),
wrq:set_resp_header(?HEAD_CTYPE, "text/plain", RD)),
Ctx}
end.
( ) , context ( ) ) - >
%% {boolean(), reqdata(), context()}
%% @doc Check that the Link header in the request() is valid.
%% Store the parsed links in context() if the header is valid,
%% or print an error in reqdata() if it is not.
%% A link header should be of the form:
& lt;/Prefix / Bucket / Key> ; ; " , ...
malformed_link_headers(RD, Ctx) ->
case catch get_link_heads(RD, Ctx) of
Links when is_list(Links) ->
{false, RD, Ctx#ctx{links=Links}};
_Error ->
{true,
wrq:append_to_resp_body(
io_lib:format("Invalid Link header. Links must be of the form~n"
"</~s/BUCKET/KEY>; riaktag=\"TAG\"~n",
[Ctx#ctx.prefix]),
wrq:set_resp_header(?HEAD_CTYPE, "text/plain", RD)),
Ctx}
end.
( ) , context ( ) ) - >
{ [ { ContentType::string ( ) , Producer::atom ( ) } ] , reqdata ( ) , context ( ) }
%% @doc List the content types available for representing this resource.
%% "application/json" is the content-type for bucket-level GET requests
%% The content-type for a key-level request is the content-type that
was used in the PUT request that stored the document in Riak .
content_types_provided(RD, Ctx=#ctx{key=undefined}) ->
%% bucket-level: JSON description only
{[{"application/json", produce_bucket_body}], RD, Ctx};
content_types_provided(RD, Ctx=#ctx{method=Method}=Ctx) when Method =:= 'PUT';
Method =:= 'POST' ->
{ContentType, _} = extract_content_type(RD),
{[{ContentType, produce_doc_body}], RD, Ctx};
content_types_provided(RD, Ctx0) ->
DocCtx = ensure_doc(Ctx0),
case DocCtx#ctx.doc of
{ok, _} ->
case select_doc(DocCtx) of
{MD, V} ->
{[{get_ctype(MD,V), produce_doc_body}], RD, DocCtx};
multiple_choices ->
{[{"text/plain", produce_sibling_message_body},
{"multipart/mixed", produce_multipart_body}], RD, DocCtx}
end;
{error, notfound} ->
{[{"text/plain", produce_error_message}], RD, DocCtx}
end.
%% @spec charsets_provided(reqdata(), context()) ->
%% {no_charset|[{Charset::string(), Producer::function()}],
%% reqdata(), context()}
%% @doc List the charsets available for representing this resource.
%% No charset will be specified for a bucket-level request.
%% The charset for a key-level request is the charset that was used
in the PUT request that stored the document in ( none if
no charset was specified at PUT - time ) .
charsets_provided(RD, Ctx=#ctx{key=undefined}) ->
%% default charset for bucket-level request
{no_charset, RD, Ctx};
charsets_provided(RD, #ctx{method=Method}=Ctx) when Method =:= 'PUT';
Method =:= 'POST' ->
case extract_content_type(RD) of
{_, undefined} ->
{no_charset, RD, Ctx};
{_, Charset} ->
{[{Charset, fun(X) -> X end}], RD, Ctx}
end;
charsets_provided(RD, Ctx0) ->
DocCtx = ensure_doc(Ctx0),
case DocCtx#ctx.doc of
{ok, _} ->
case select_doc(DocCtx) of
{MD, _} ->
case dict:find(?MD_CHARSET, MD) of
{ok, CS} ->
{[{CS, fun(X) -> X end}], RD, DocCtx};
error ->
{no_charset, RD, DocCtx}
end;
multiple_choices ->
{no_charset, RD, DocCtx}
end;
{error, notfound} ->
{no_charset, RD, DocCtx}
end.
( ) , context ( ) ) - >
%% {[{Encoding::string(), Producer::function()}], reqdata(), context()}
%% @doc List the encodings available for representing this resource.
%% "identity" and "gzip" are available for bucket-level requests.
%% The encoding for a key-level request is the encoding that was
used in the PUT request that stored the document in Riak , or
" identity " and " gzip " if no encoding was specified at PUT - time .
encodings_provided(RD, Ctx=#ctx{key=undefined}) ->
%% identity and gzip for bucket-level request
{default_encodings(), RD, Ctx};
encodings_provided(RD, Ctx0) ->
DocCtx = ensure_doc(Ctx0),
case DocCtx#ctx.doc of
{ok, _} ->
case select_doc(DocCtx) of
{MD, _} ->
case dict:find(?MD_ENCODING, MD) of
{ok, Enc} ->
{[{Enc, fun(X) -> X end}], RD, DocCtx};
error ->
{default_encodings(), RD, DocCtx}
end;
multiple_choices ->
{default_encodings(), RD, DocCtx}
end;
{error, notfound} ->
{default_encodings(), RD, DocCtx}
end.
default_encodings ( ) - > [ { Encoding::string ( ) , Producer::function ( ) } ]
%% @doc The default encodings available: identity and gzip.
default_encodings() ->
[{"identity", fun(X) -> X end},
{"gzip", fun(X) -> zlib:gzip(X) end}].
content_types_accepted(reqdata ( ) , context ( ) ) - >
%% {[{ContentType::string(), Acceptor::atom()}],
%% reqdata(), context()}
%% @doc Get the list of content types this resource will accept.
%% "application/json" is the only type accepted for bucket-PUT.
%% Whatever content type is specified by the Content-Type header
of a key - level PUT request will be accepted by this resource .
%% (A key-level put *must* include a Content-Type header.)
content_types_accepted(RD, Ctx) ->
case is_bucket_put(RD, Ctx) of
true ->
%% bucket-PUT: JSON only
{[{"application/json", accept_bucket_body}], RD, Ctx};
false ->
case wrq:get_req_header(?HEAD_CTYPE, RD) of
undefined ->
%% user must specify content type of the data
{[], RD, Ctx};
CType ->
Media = hd(string:tokens(CType, ";")),
case string:tokens(Media, "/") of
[_Type, _Subtype] ->
%% accept whatever the user says
{[{Media, accept_doc_body}], RD, Ctx};
_ ->
{[],
wrq:set_resp_header(
?HEAD_CTYPE,
"text/plain",
wrq:set_resp_body(
["\"", Media, "\""
" is not a valid media type"
" for the Content-type header.\n"],
RD)),
Ctx}
end
end
end.
@spec resource_exists(reqdata ( ) , context ( ) ) - > { boolean ( ) , reqdata ( ) , context ( ) }
%% @doc Determine whether or not the requested item exists.
%% All buckets exists, whether they have data in them or not.
Documents exists if a read request to returns { ok , riak_object ( ) } ,
%% and either no vtag query parameter was specified, or the value of the
vtag param matches the vtag of some value of the object .
resource_exists(RD, Ctx=#ctx{key=undefined}) ->
%% all buckets exist
{true, RD, Ctx};
resource_exists(RD, Ctx0) ->
DocCtx = ensure_doc(Ctx0),
case DocCtx#ctx.doc of
{ok, Doc} ->
case DocCtx#ctx.vtag of
undefined ->
{true, RD, DocCtx};
Vtag ->
MDs = riak_object:get_metadatas(Doc),
{lists:any(fun(M) ->
dict:fetch(?MD_VTAG, M) =:= Vtag
end,
MDs),
RD, DocCtx#ctx{vtag=Vtag}}
end;
{error, notfound} ->
{false, RD, DocCtx}
end.
( ) , context ( ) ) - > { binary ( ) , reqdata ( ) , context ( ) }
%% @doc Produce the JSON response to a bucket-level GET.
%% Includes the bucket props unless the "props=false" query param
%% is specified.
%% Includes the keys of the documents in the bucket unless the
%% "keys=false" query param is specified. If "keys=stream" query param
%% is specified, keys will be streamed back to the client in JSON chunks
like so : { " keys":[Key1 , Key2 , ... ] } .
%% A Link header will also be added to the response by this function
%% if the keys are included in the JSON object. The Link header
%% will include links to all keys in the bucket, with the property
%% "rel=contained".
produce_bucket_body(RD, Ctx=#ctx{bucket=B, client=C}) ->
SchemaPart =
case wrq:get_qs_value(?Q_PROPS, RD) of
?Q_FALSE -> [];
_ ->
Props = C:get_bucket(B),
JsonProps = lists:map(fun jsonify_bucket_prop/1, Props),
[{?JSON_PROPS, {struct, JsonProps}}]
end,
{KeyPart, KeyRD} =
case wrq:get_qs_value(?Q_KEYS, RD) of
?Q_FALSE -> {[], RD};
?Q_STREAM -> {stream, RD};
_ ->
{ok, KeyList} = C:list_keys(B),
{[{?Q_KEYS, KeyList}],
lists:foldl(
fun(K, Acc) ->
add_link_head(B, K, "contained", Acc, Ctx)
end,
RD, KeyList)}
end,
case KeyPart of
stream -> {{stream, {mochijson2:encode({struct, SchemaPart}),
fun() ->
{ok, ReqId} = C:stream_list_keys(B),
stream_keys(ReqId)
end}},
KeyRD,
Ctx};
_ ->
{mochijson2:encode({struct, SchemaPart++KeyPart}), KeyRD, Ctx}
end.
stream_keys(ReqId) ->
receive
{ReqId, {keys, Keys}} ->
{mochijson2:encode({struct, [{<<"keys">>, Keys}]}), fun() -> stream_keys(ReqId) end};
{ReqId, done} -> {mochijson2:encode({struct, [{<<"keys">>, []}]}), done}
end.
accept_bucket_body(reqdata ( ) , context ( ) ) - > { true , reqdata ( ) , context ( ) }
%% @doc Modify the bucket properties according to the body of the
bucket - level PUT request .
accept_bucket_body(RD, Ctx=#ctx{bucket=B, client=C, bucketprops=Props}) ->
ErlProps = lists:map(fun erlify_bucket_prop/1, Props),
C:set_bucket(B, ErlProps),
{true, RD, Ctx}.
( ) , erlpropvalue ( ) } ) - >
%% {Property::binary(), jsonpropvalue()}
@type erlpropvalue ( ) = integer()|string()|boolean()|
{ modfun , atom ( ) , atom()}|{atom ( ) , atom ( ) }
%% @type jsonpropvalue() = integer()|string()|boolean()|{struct,[jsonmodfun()]}
@type jsonmodfun ( ) = { mod_binary ( ) , binary()}|{fun_binary ( ) , binary ( ) }
@doc Convert erlang bucket properties to JSON bucket properties .
%% Property names are converted from atoms to binaries.
%% Integer, string, and boolean property values are left as integer,
%% string, or boolean JSON values.
%% {modfun, Module, Function} or {Module, Function} values of the
%% linkfun and chash_keyfun properties are converted to JSON objects
%% of the form:
%% {"mod":ModuleNameAsString,
%% "fun":FunctionNameAsString}
jsonify_bucket_prop({linkfun, {modfun, Module, Function}}) ->
{?JSON_LINKFUN, {struct, [{?JSON_MOD,
list_to_binary(atom_to_list(Module))},
{?JSON_FUN,
list_to_binary(atom_to_list(Function))}]}};
jsonify_bucket_prop({linkfun, {qfun, _}}) ->
{?JSON_LINKFUN, <<"qfun">>};
jsonify_bucket_prop({linkfun, {jsfun, Name}}) ->
{?JSON_LINKFUN, {struct, [{?JSON_JSFUN, Name}]}};
jsonify_bucket_prop({linkfun, {jsanon, {Bucket, Key}}}) ->
{?JSON_LINKFUN, {struct, [{?JSON_JSANON,
{struct, [{?JSON_JSBUCKET, Bucket},
{?JSON_JSKEY, Key}]}}]}};
jsonify_bucket_prop({linkfun, {jsanon, Source}}) ->
{?JSON_LINKFUN, {struct, [{?JSON_JSANON, Source}]}};
jsonify_bucket_prop({chash_keyfun, {Module, Function}}) ->
{?JSON_CHASH, {struct, [{?JSON_MOD,
list_to_binary(atom_to_list(Module))},
{?JSON_FUN,
list_to_binary(atom_to_list(Function))}]}};
jsonify_bucket_prop({Prop, Value}) ->
{list_to_binary(atom_to_list(Prop)), Value}.
%% @spec erlify_bucket_prop({Property::binary(), jsonpropvalue()}) ->
%% {Property::atom(), erlpropvalue()}
@doc The reverse of jsonify_bucket_prop/1 . Converts JSON representation
of bucket properties to their Erlang form .
erlify_bucket_prop({?JSON_LINKFUN, {struct, Props}}) ->
case {proplists:get_value(?JSON_MOD, Props),
proplists:get_value(?JSON_FUN, Props)} of
{Mod, Fun} when is_binary(Mod), is_binary(Fun) ->
{linkfun, {modfun,
list_to_existing_atom(binary_to_list(Mod)),
list_to_existing_atom(binary_to_list(Fun))}};
{undefined, undefined} ->
case proplists:get_value(?JSON_JSFUN, Props) of
Name when is_binary(Name) ->
{linkfun, {jsfun, Name}};
undefined ->
case proplists:get_value(?JSON_JSANON, Props) of
{struct, Bkey} ->
Bucket = proplists:get_value(?JSON_JSBUCKET, Bkey),
Key = proplists:get_value(?JSON_JSKEY, Bkey),
%% bomb if malformed
true = is_binary(Bucket) andalso is_binary(Key),
{linkfun, {jsanon, {Bucket, Key}}};
Source when is_binary(Source) ->
{linkfun, {jsanon, Source}}
end
end
end;
erlify_bucket_prop({?JSON_CHASH, {struct, Props}}) ->
{chash_keyfun, {list_to_existing_atom(
binary_to_list(
proplists:get_value(?JSON_MOD, Props))),
list_to_existing_atom(
binary_to_list(
proplists:get_value(?JSON_FUN, Props)))}};
erlify_bucket_prop({?JSON_ALLOW_MULT, Value}) ->
{allow_mult, any_to_bool(Value)};
erlify_bucket_prop({Prop, Value}) ->
{list_to_existing_atom(binary_to_list(Prop)), Value}.
( ) , context ( ) ) - > { boolean ( ) , reqdata ( ) , context ( ) }
%% @doc POST is considered a document-creation operation for bucket-level
requests ( this makes webmachine call create_path/2 , where the key
%% for the created document will be chosen).
post_is_create(RD, Ctx=#ctx{key=undefined}) ->
%% bucket-POST is create
{true, RD, Ctx};
post_is_create(RD, Ctx) ->
%% key-POST is not create
{false, RD, Ctx}.
create_path(reqdata ( ) , context ( ) ) - > { string ( ) , reqdata ( ) , context ( ) }
%% @doc Choose the Key for the document created during a bucket-level POST.
%% This function also sets the Location header to generate a
201 Created response .
create_path(RD, Ctx=#ctx{prefix=P, bucket=B}) ->
K = riak_core_util:unique_id_62(),
{K,
wrq:set_resp_header("Location",
lists:append(["/",P,"/",binary_to_list(B),"/",K]),
RD),
Ctx#ctx{key=list_to_binary(K)}}.
process_post(reqdata ( ) , context ( ) ) - > { true , reqdata ( ) , context ( ) }
%% @doc Pass-through for key-level requests to allow POST to function
as PUT for clients that do not support PUT .
process_post(RD, Ctx) -> accept_doc_body(RD, Ctx).
( ) , context ( ) ) - > { true , ( ) , context ( ) }
@doc Store the data the client is PUTing in the document .
%% This function translates the headers and body of the HTTP request
into their final riak_object ( ) form , and executes the put .
accept_doc_body(RD, Ctx=#ctx{bucket=B, key=K, client=C, links=L}) ->
Doc0 = case Ctx#ctx.doc of
{ok, D} -> D;
_ -> riak_object:new(B, K, <<>>)
end,
VclockDoc = riak_object:set_vclock(Doc0, decode_vclock_header(RD)),
{CType, Charset} = extract_content_type(RD),
UserMeta = extract_user_meta(RD),
CTypeMD = dict:store(?MD_CTYPE, CType, dict:new()),
CharsetMD = if Charset /= undefined ->
dict:store(?MD_CHARSET, Charset, CTypeMD);
true -> CTypeMD
end,
EncMD = case wrq:get_req_header(?HEAD_ENCODING, RD) of
undefined -> CharsetMD;
E -> dict:store(?MD_ENCODING, E, CharsetMD)
end,
LinkMD = dict:store(?MD_LINKS, L, EncMD),
UserMetaMD = dict:store(?MD_USERMETA, UserMeta, LinkMD),
MDDoc = riak_object:update_metadata(VclockDoc, UserMetaMD),
Doc = riak_object:update_value(MDDoc, accept_value(CType, wrq:req_body(RD))),
Options = case wrq:get_qs_value(?Q_RETURNBODY, RD) of ?Q_TRUE -> [returnbody]; _ -> [] end,
case C:put(Doc, Ctx#ctx.w, Ctx#ctx.dw, 60000, Options) of
{error, precommit_fail} ->
{{halt, 403}, send_precommit_error(RD, undefined), Ctx};
{error, {precommit_fail, Reason}} ->
{{halt, 403}, send_precommit_error(RD, Reason), Ctx};
ok ->
{true, RD, Ctx#ctx{doc={ok, Doc}}};
{ok, RObj} ->
DocCtx = Ctx#ctx{doc={ok, RObj}},
HasSiblings = (select_doc(DocCtx) == multiple_choices),
send_returnbody(RD, DocCtx, HasSiblings)
end.
%% Handle the no-sibling case. Just send the object.
send_returnbody(RD, DocCtx, _HasSiblings = false) ->
{Body, DocRD, DocCtx2} = produce_doc_body(RD, DocCtx),
{true, wrq:append_to_response_body(Body, DocRD), DocCtx2};
%% Handle the sibling case. Send either the sibling message body, or a
%% multipart body, depending on what the client accepts.
send_returnbody(RD, DocCtx, _HasSiblings = true) ->
AcceptHdr = wrq:get_req_header("Accept", RD),
case webmachine_util:choose_media_type(["multipart/mixed", "text/plain"], AcceptHdr) of
"multipart/mixed" ->
{Body, DocRD, DocCtx2} = produce_multipart_body(RD, DocCtx),
{true, wrq:append_to_response_body(Body, DocRD), DocCtx2};
_ ->
{Body, DocRD, DocCtx2} = produce_sibling_message_body(RD, DocCtx),
{true, wrq:append_to_response_body(Body, DocRD), DocCtx2}
end.
@spec extract_content_type(reqdata ( ) ) - >
%% {ContentType::string(), Charset::string()|undefined}
@doc Interpret the Content - Type header in the client 's PUT request .
%% This function extracts the content type and charset for use
%% in subsequent GET requests.
extract_content_type(RD) ->
case wrq:get_req_header(?HEAD_CTYPE, RD) of
undefined ->
undefined;
RawCType ->
[CType|RawParams] = string:tokens(RawCType, "; "),
Params = [ list_to_tuple(string:tokens(P, "=")) || P <- RawParams],
{CType, proplists:get_value("charset", Params)}
end.
( ) ) - > proplist ( )
@doc Extract headers prefixed by X - Riak - Meta- in the client 's PUT request
%% to be returned by subsequent GET requests.
extract_user_meta(RD) ->
lists:filter(fun({K,_V}) ->
lists:prefix(
?HEAD_USERMETA_PREFIX,
string:to_lower(any_to_list(K)))
end,
mochiweb_headers:to_list(wrq:req_headers(RD))).
%% @spec multiple_choices(reqdata(), context()) ->
%% {boolean(), reqdata(), context()}
%% @doc Determine whether a document has siblings. If the user has
%% specified a specific vtag, the document is considered not to
%% have sibling versions. This is a safe assumption, because
%% resource_exists will have filtered out requests earlier for
vtags that are invalid for this version of the document .
multiple_choices(RD, Ctx=#ctx{key=undefined}) ->
%% bucket operations never have multiple choices
{false, RD, Ctx};
multiple_choices(RD, Ctx=#ctx{vtag=undefined, doc={ok, Doc}}) ->
%% user didn't specify a vtag, so there better not be siblings
case riak_object:get_update_value(Doc) of
undefined ->
case riak_object:value_count(Doc) of
1 -> {false, RD, Ctx};
_ -> {true, RD, Ctx}
end;
_ ->
%% just updated can't have multiple
{false, RD, Ctx}
end;
multiple_choices(RD, Ctx) ->
specific vtag was specified
{false, RD, Ctx}.
produce_doc_body(reqdata ( ) , context ( ) ) - > { binary ( ) , reqdata ( ) , context ( ) }
%% @doc Extract the value of the document, and place it in the response
body of the request . This function also adds the Link and X - Riak - Meta-
headers to the response . One link will point to the bucket , with the
%% property "rel=container". The rest of the links will be constructed
%% from the links of the document.
produce_doc_body(RD, Ctx) ->
case select_doc(Ctx) of
{MD, Doc} ->
Links = case dict:find(?MD_LINKS, MD) of
{ok, L} -> L;
error -> []
end,
LinkRD = add_container_link(
lists:foldl(fun({{B,K},T},Acc) ->
add_link_head(B,K,T,Acc,Ctx)
end,
RD, Links),
Ctx),
UserMetaRD = case dict:find(?MD_USERMETA, MD) of
{ok, UserMeta} ->
lists:foldl(fun({K,V},Acc) ->
wrq:merge_resp_headers([{K,V}],Acc)
end,
LinkRD, UserMeta);
error -> LinkRD
end,
{encode_value(Doc), encode_vclock_header(UserMetaRD, Ctx), Ctx};
multiple_choices ->
throw({unexpected_code_path, ?MODULE, produce_doc_body, multiple_choices})
end.
( ) , context ( ) ) - >
%% {iolist(), reqdata(), context()}
%% @doc Produce the text message informing the user that there are multiple
%% values for this document, and giving that user the vtags of those
values so they can get to them with the vtag query param .
produce_sibling_message_body(RD, Ctx=#ctx{doc={ok, Doc}}) ->
Vtags = [ dict:fetch(?MD_VTAG, M)
|| M <- riak_object:get_metadatas(Doc) ],
{[<<"Siblings:\n">>, [ [V,<<"\n">>] || V <- Vtags]],
wrq:set_resp_header(?HEAD_CTYPE, "text/plain",
encode_vclock_header(RD, Ctx)),
Ctx}.
produce_multipart_body(reqdata ( ) , context ( ) ) - >
%% {iolist(), reqdata(), context()}
%% @doc Produce a multipart body representation of an object with multiple
values ( siblings ) , each sibling being one part of the larger
%% document.
produce_multipart_body(RD, Ctx=#ctx{doc={ok, Doc}, bucket=B, prefix=P}) ->
Boundary = riak_core_util:unique_id_62(),
{[[["\r\n--",Boundary,"\r\n",
multipart_encode_body(P, B, Content)]
|| Content <- riak_object:get_contents(Doc)],
"\r\n--",Boundary,"--\r\n"],
wrq:set_resp_header(?HEAD_CTYPE,
"multipart/mixed; boundary="++Boundary,
encode_vclock_header(RD, Ctx)),
Ctx}.
( ) , binary ( ) , { dict ( ) , binary ( ) } ) - > iolist ( )
@doc Produce one part of a multipart body , representing one sibling
%% of a multi-valued document.
multipart_encode_body(Prefix, Bucket, {MD, V}) ->
[{LHead, Links}] =
mochiweb_headers:to_list(
mochiweb_headers:make(
[{?HEAD_LINK, format_link(Prefix,Bucket)}|
[{?HEAD_LINK, format_link(Prefix,B,K,T)}
|| {{B,K},T} <- case dict:find(?MD_LINKS, MD) of
{ok, Ls} -> Ls;
error -> []
end]])),
[?HEAD_CTYPE, ": ",get_ctype(MD,V),
case dict:find(?MD_CHARSET, MD) of
{ok, CS} -> ["; charset=",CS];
error -> []
end,
"\r\n",
case dict:find(?MD_ENCODING, MD) of
{ok, Enc} -> [?HEAD_ENCODING,": ",Enc,"\r\n"];
error -> []
end,
LHead,": ",Links,"\r\n",
"Etag: ",dict:fetch(?MD_VTAG, MD),"\r\n",
"Last-Modified: ",
case dict:fetch(?MD_LASTMOD, MD) of
Now={_,_,_} ->
httpd_util:rfc1123_date(
calendar:now_to_local_time(Now));
Rfc1123 when is_list(Rfc1123) ->
Rfc1123
end,
"\r\n",
case dict:find(?MD_USERMETA, MD) of
{ok, M} ->
lists:foldl(fun({Hdr,Val},Acc) ->
[Acc|[Hdr,": ",Val,"\r\n"]]
end,
[], M);
error -> []
end,
"\r\n",encode_value(V)].
@spec select_doc(context ( ) ) - > { metadata ( ) , value()}|multiple_choices
%% @doc Selects the "proper" document:
%% - chooses update-value/metadata if update-value is set
- chooses only / if only one exists
- chooses val / given Vtag if multiple contents exist
%% (assumes a vtag has been specified)
select_doc(#ctx{doc={ok, Doc}, vtag=Vtag}) ->
case riak_object:get_update_value(Doc) of
undefined ->
case riak_object:get_contents(Doc) of
[Single] -> Single;
Mult ->
case lists:dropwhile(
fun({M,_}) ->
dict:fetch(?MD_VTAG, M) /= Vtag
end,
Mult) of
[Match|_] -> Match;
[] -> multiple_choices
end
end;
UpdateValue ->
{riak_object:get_update_metadata(Doc), UpdateValue}
end.
%% @spec encode_vclock_header(reqdata(), context()) -> reqdata()
@doc Add the X - Riak - Vclock header to the response .
encode_vclock_header(RD, #ctx{doc={ok, Doc}}) ->
{Head, Val} = vclock_header(Doc),
wrq:set_resp_header(Head, Val, RD).
@spec vclock_header(riak_object ( ) ) - > { Name::string ( ) , Value::string ( ) }
@doc Transform the Erlang representation of the document 's vclock
%% into something suitable for an HTTP header
vclock_header(Doc) ->
{?HEAD_VCLOCK,
binary_to_list(
base64:encode(zlib:zip(term_to_binary(riak_object:vclock(Doc)))))}.
@spec decode_vclock_header(reqdata ( ) ) - > vclock ( )
@doc Translate the X - Riak - Vclock header value from the request into
its Erlang representation . If no vclock header exists , a fresh
%% vclock is returned.
decode_vclock_header(RD) ->
case wrq:get_req_header(?HEAD_VCLOCK, RD) of
undefined -> vclock:fresh();
Head -> binary_to_term(zlib:unzip(base64:decode(Head)))
end.
@spec ensure_doc(context ( ) ) - > context ( )
%% @doc Ensure that the 'doc' field of the context() has been filled
%% with the result of a riak_client:get request. This is a
%% convenience for memoizing the result of a get so it can be
%% used in multiple places in this resource, without having to
%% worry about the order of executing of those places.
ensure_doc(Ctx=#ctx{doc=undefined, bucket=B, key=K, client=C, r=R}) ->
Ctx#ctx{doc=C:get(B, K, R)};
ensure_doc(Ctx) -> Ctx.
( ) , context ( ) ) - > { true , reqdata ( ) , context ( ) }
%% @doc Delete the document specified.
delete_resource(RD, Ctx=#ctx{bucket=B, key=K, client=C, rw=RW}) ->
case C:delete(B, K, RW) of
{error, precommit_fail} ->
{{halt, 403}, send_precommit_error(RD, undefined), Ctx};
{error, {precommit_fail, Reason}} ->
{{halt, 403}, send_precommit_error(RD, Reason), Ctx};
ok ->
{true, RD, Ctx}
end.
( ) , context ( ) ) - >
( ) , reqdata ( ) , context ( ) }
%% @doc Get the etag for this resource.
%% Bucket requests will have no etag.
%% Documents will have an etag equal to their vtag. No etag will be
%% given for documents with siblings, if no sibling was chosen with the
%% vtag query param.
generate_etag(RD, Ctx=#ctx{key=undefined}) ->
{undefined, RD, Ctx};
generate_etag(RD, Ctx) ->
case select_doc(Ctx) of
{MD, _} ->
{dict:fetch(?MD_VTAG, MD), RD, Ctx};
multiple_choices ->
{undefined, RD, Ctx}
end.
( ) , context ( ) ) - >
%% {undefined|datetime(), reqdata(), context()}
%% @doc Get the last-modified time for this resource.
%% Bucket requests will have no last-modified time.
%% Documents will have the last-modified time specified by the riak_object.
%% No last-modified time will be given for documents with siblings, if no
sibling was chosen with the vtag query param .
last_modified(RD, Ctx=#ctx{key=undefined}) ->
{undefined, RD, Ctx};
last_modified(RD, Ctx) ->
case select_doc(Ctx) of
{MD, _} ->
{case dict:fetch(?MD_LASTMOD, MD) of
Now={_,_,_} ->
calendar:now_to_universal_time(Now);
Rfc1123 when is_list(Rfc1123) ->
httpd_util:convert_request_date(Rfc1123)
end,
RD, Ctx};
multiple_choices ->
{undefined, RD, Ctx}
end.
( ) , context ( ) ) - > reqdata ( )
%% @doc Add the Link header specifying the containing bucket of
%% the document to the response.
add_container_link(RD, #ctx{prefix=Prefix, bucket=Bucket}) ->
Val = format_link(Prefix, Bucket),
wrq:merge_resp_headers([{?HEAD_LINK,Val}], RD).
@spec add_link_head(binary ( ) , binary ( ) , binary ( ) , reqdata ( ) , context ( ) ) - >
%% reqdata()
%% @doc Add a Link header specifying the given Bucket and Key
%% with the given Tag to the response.
add_link_head(Bucket, Key, Tag, RD, #ctx{prefix=Prefix}) ->
Val = format_link(Prefix, Bucket, Key, Tag),
wrq:merge_resp_headers([{?HEAD_LINK,Val}], RD).
%% @spec format_link(string(), binary()) -> string()
%% @doc Format a Link header to a bucket.
format_link(Prefix, Bucket) ->
io_lib:format("</~s/~s>; rel=\"up\"",
[Prefix,
mochiweb_util:quote_plus(Bucket)]).
%% @spec format_link(string(), binary(), binary(), binary()) -> string()
%% @doc Format a Link header to another document.
format_link(Prefix, Bucket, Key, Tag) ->
io_lib:format("</~s/~s/~s>; riaktag=\"~s\"",
[Prefix|
[mochiweb_util:quote_plus(E) ||
E <- [Bucket, Key, Tag] ]]).
( ) , context ( ) ) - > [ link ( ) ]
%% @doc Extract the list of links from the Link request header.
%% This function will die if an invalid link header format
%% is found.
get_link_heads(RD, #ctx{prefix=Prefix, bucket=B}) ->
case wrq:get_req_header(?HEAD_LINK, RD) of
undefined -> [];
Heads ->
BucketLink = lists:flatten(format_link(Prefix, B)),
{ok, Re} = re:compile("</([^/]+)/([^/]+)/([^/]+)>; ?riaktag=\"([^\"]+)\""),
lists:map(
fun(L) ->
{match,[InPrefix,Bucket,Key,Tag]} =
re:run(L, Re, [{capture,[1,2,3,4],binary}]),
Prefix = binary_to_list(InPrefix),
{{list_to_binary(mochiweb_util:unquote(Bucket)),
list_to_binary(mochiweb_util:unquote(Key))},
list_to_binary(mochiweb_util:unquote(Tag))}
end,
lists:delete(BucketLink, [string:strip(T) || T<- string:tokens(Heads, ",")]))
end.
get_ctype(dict ( ) , term ( ) ) - > string ( )
%% @doc Work out the content type for this object - use the metadata if provided
get_ctype(MD,V) ->
case dict:find(?MD_CTYPE, MD) of
{ok, Ctype} ->
Ctype;
error when is_binary(V) ->
"application/octet-stream";
error ->
"application/x-erlang-binary"
end.
@spec encode_value(term ( ) ) - > binary ( )
%% @doc Encode the object value as a binary - content type can be used
%% to decode
encode_value(V) when is_binary(V) ->
V;
encode_value(V) ->
term_to_binary(V).
accept_value(string ( ) , binary ( ) ) - > term ( )
%% @doc Accept the object value as a binary - content type can be used
%% to decode
accept_value("application/x-erlang-binary",V) ->
binary_to_term(V);
accept_value(_Ctype, V) ->
V.
any_to_list(V) when is_list(V) ->
V;
any_to_list(V) when is_atom(V) ->
atom_to_list(V);
any_to_list(V) when is_binary(V) ->
binary_to_list(V).
any_to_bool(V) when is_list(V) ->
(V == "1") orelse (V == "true") orelse (V == "TRUE");
any_to_bool(V) when is_binary(V) ->
any_to_bool(binary_to_list(V));
any_to_bool(V) when is_integer(V) ->
V /= 0;
any_to_bool(V) when is_boolean(V) ->
V.
missing_content_type(RD) ->
RD1 = wrq:set_resp_header("Content-Type", "text/plain", RD),
wrq:append_to_response_body(<<"Missing Content-Type request header">>, RD1).
send_precommit_error(RD, Reason) ->
RD1 = wrq:set_resp_header("Content-Type", "text/plain", RD),
Error = if
Reason =:= undefined ->
list_to_binary([atom_to_binary(wrq:method(RD1), utf8),
<<" aborted by pre-commit hook.">>]);
true ->
Reason
end,
wrq:append_to_response_body(Error, RD1).
| null | https://raw.githubusercontent.com/erlangonrails/devdb/0e7eaa6bd810ec3892bfc3d933439560620d0941/dev/riak-0.11.0/apps/riak_kv/src/riak_kv_wm_raw.erl | erlang | -------------------------------------------------------------------
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-------------------------------------------------------------------
Available operations:
GET /Prefix/Bucket
Get information about the named Bucket, in JSON form:
"keys":[Key1,Key2,...]}.
Each bucket property will be included in the "props" object.
"linkfun" and "chash_keyfun" properties will be encoded as
JSON objects of the form:
{"mod":ModuleName,
"fun":FunctionName}
a module and function.
Including the query param "props=false" will cause the "props"
field to be omitted from the response.
Including the query param "keys=false" will cause the "keys"
field to be omitted from the response.
PUT /Prefix/Bucket
Modify bucket properties.
Content-type must be application/json, and the body must have
the form:
{"props":{Prop:Val}}
Where the "props" object takes the same form as returned from
a GET of the same resource.
POST /Prefix/Bucket
by the server.
GET /Prefix/Bucket/Key
Content-type of the response will be whatever incoming
Content-type was used in the request that stored the data.
Additional headers will include:
X-Riak-Vclock: The vclock of the object.
Link: The links the object has
Last-Modified: The last-modified time of the object
Encoding: The value of the incoming Encoding header from
the request that stored the data.
If the object is found to have siblings (only possible if the
bucket property "allow_mult" has been set to true), then
Content-type will be text/plain; Link, Etag, and Last-Modified
headers will be omitted; and the body of the response will
be a list of the vtags of each sibling. To request a specific
sibling, include the query param "vtag=V", where V is the vtag
of the sibling you want.
PUT /Prefix/Bucket/Key
A Content-type header *must* be included in the request. The
value of this header will be used in the response to subsequent
GET requests.
The body of the request will be stored literally as the value
of the riak_object, and will be served literally as the body of
the response to subsequent GET requests.
Include an X-Riak-Vclock header to modify data without creating
siblings.
Include a Link header to set the links of the object.
Include an Encoding header if you would like an Encoding header
to be included in the response to subsequent GET requests.
They will be returned verbatim on subsequent GET requests.
default dw-value of 0 will be used if none is specified.
to determine whether or not the resource exists). A default
POST /Prefix/Bucket/Key
DELETE /Prefix/Bucket/Key
{["riak", bucket],
riak_kv_wm_raw,
[{prefix, "riak"},
{riak, local} %% or {riak, {'riak@127.0.0.1', riak_cookie}}
]}.
{["riak", bucket, key],
riak_kv_wm_raw,
[{prefix, "riak"},
{riak, local} %% or {riak, {'riak@127.0.0.1', riak_cookie}}
]}.
These example dispatch lines will expose this resource at
is executing. Using the alternate {riak, {Node, Cookie}} form
will cause the resource to connect to riak on the specified
Node with the specified Cookie.
webmachine resource exports
@type context() = term()
binary() - Bucket name (from uri)
binary() - Key (from uri)
riak_client() - the store client
integer() - r-value for reads
integer() - w-value for writes
integer() - dw-value for writes
integer() - rw-value for deletes
string() - prefix for resource uris
local | {node(), atom()} - params for riak client
{ok, riak_object()}|{error, term()} - the object found
string() - vtag the user asked for
proplist() - properties of the bucket
[link()] - links of the object
atom() - HTTP method for the request
@spec init(proplist()) -> {ok, context()}
@doc Initialize this resource. This function extracts the
'prefix' and 'riak' properties from the dispatch args.
{boolean(), reqdata(), context()}
can be established. This function also takes this
opportunity to extract the 'bucket' and 'key' path
bindings from the dispatch, as well as any vtag
query parameter.
{ok, riak_client()} | error()
@doc Get a riak_client.
@doc Extract the request's preferred client id from the
X-Riak-ClientId header. Return value will be:
'undefined' if no header was found
string() if the header could not be base64-decoded
@spec allowed_methods(reqdata(), context()) ->
{[method()], reqdata(), context()}
@doc Get the list of methods this resource supports.
the bucket and key levels. DELETE is supported
at the key level only.
bucket-level: no delete
key-level: just about anything
{true, reqdata(), context()}
bucket entries.
@doc Determine whether this request is of the form
PUT /Prefix/Bucket
This method expects the 'key' path binding to have
been set in the 'key' field of the context().
@spec malformed_request(reqdata(), context()) ->
{boolean(), reqdata(), context()}
@doc Determine whether query parameters, request headers,
and request body are badly-formed.
Body format is checked to be valid JSON, including
a "props" object for a bucket-PUT. Body format
is not tested for a key-level request (since the
body may be any content the client desires).
Query parameters r, w, dw, and rw are checked to
be valid integers. Their values are stored in
the context() at this time.
Link headers are checked for the form:
The parsed links are stored in the context()
at this time.
@spec malformed_bucket_put(reqdata(), context()) ->
{boolean(), reqdata(), context()}
Must be a valid JSON object, containing a "props" object.
@doc Put an error about the format of the bucket-PUT body
in the response body of the reqdata().
{boolean(), reqdata(), context()}
@doc Check that r, w, dw, and rw query parameters are
string-encoded integers. Store the integer values
in context() if so.
{boolean(), reqdata(), context()}) ->
{boolean(), reqdata(), context()}
@doc Check that a specific r, w, dw, or rw query param is a
string-encoded integer. Store its result in context() if it
{boolean(), reqdata(), context()}
@doc Check that the Link header in the request() is valid.
Store the parsed links in context() if the header is valid,
or print an error in reqdata() if it is not.
A link header should be of the form:
@doc List the content types available for representing this resource.
"application/json" is the content-type for bucket-level GET requests
The content-type for a key-level request is the content-type that
bucket-level: JSON description only
@spec charsets_provided(reqdata(), context()) ->
{no_charset|[{Charset::string(), Producer::function()}],
reqdata(), context()}
@doc List the charsets available for representing this resource.
No charset will be specified for a bucket-level request.
The charset for a key-level request is the charset that was used
default charset for bucket-level request
{[{Encoding::string(), Producer::function()}], reqdata(), context()}
@doc List the encodings available for representing this resource.
"identity" and "gzip" are available for bucket-level requests.
The encoding for a key-level request is the encoding that was
identity and gzip for bucket-level request
@doc The default encodings available: identity and gzip.
{[{ContentType::string(), Acceptor::atom()}],
reqdata(), context()}
@doc Get the list of content types this resource will accept.
"application/json" is the only type accepted for bucket-PUT.
Whatever content type is specified by the Content-Type header
(A key-level put *must* include a Content-Type header.)
bucket-PUT: JSON only
user must specify content type of the data
accept whatever the user says
@doc Determine whether or not the requested item exists.
All buckets exists, whether they have data in them or not.
and either no vtag query parameter was specified, or the value of the
all buckets exist
@doc Produce the JSON response to a bucket-level GET.
Includes the bucket props unless the "props=false" query param
is specified.
Includes the keys of the documents in the bucket unless the
"keys=false" query param is specified. If "keys=stream" query param
is specified, keys will be streamed back to the client in JSON chunks
A Link header will also be added to the response by this function
if the keys are included in the JSON object. The Link header
will include links to all keys in the bucket, with the property
"rel=contained".
@doc Modify the bucket properties according to the body of the
{Property::binary(), jsonpropvalue()}
@type jsonpropvalue() = integer()|string()|boolean()|{struct,[jsonmodfun()]}
Property names are converted from atoms to binaries.
Integer, string, and boolean property values are left as integer,
string, or boolean JSON values.
{modfun, Module, Function} or {Module, Function} values of the
linkfun and chash_keyfun properties are converted to JSON objects
of the form:
{"mod":ModuleNameAsString,
"fun":FunctionNameAsString}
@spec erlify_bucket_prop({Property::binary(), jsonpropvalue()}) ->
{Property::atom(), erlpropvalue()}
bomb if malformed
@doc POST is considered a document-creation operation for bucket-level
for the created document will be chosen).
bucket-POST is create
key-POST is not create
@doc Choose the Key for the document created during a bucket-level POST.
This function also sets the Location header to generate a
@doc Pass-through for key-level requests to allow POST to function
This function translates the headers and body of the HTTP request
Handle the no-sibling case. Just send the object.
Handle the sibling case. Send either the sibling message body, or a
multipart body, depending on what the client accepts.
{ContentType::string(), Charset::string()|undefined}
This function extracts the content type and charset for use
in subsequent GET requests.
to be returned by subsequent GET requests.
@spec multiple_choices(reqdata(), context()) ->
{boolean(), reqdata(), context()}
@doc Determine whether a document has siblings. If the user has
specified a specific vtag, the document is considered not to
have sibling versions. This is a safe assumption, because
resource_exists will have filtered out requests earlier for
bucket operations never have multiple choices
user didn't specify a vtag, so there better not be siblings
just updated can't have multiple
@doc Extract the value of the document, and place it in the response
property "rel=container". The rest of the links will be constructed
from the links of the document.
{iolist(), reqdata(), context()}
@doc Produce the text message informing the user that there are multiple
values for this document, and giving that user the vtags of those
{iolist(), reqdata(), context()}
@doc Produce a multipart body representation of an object with multiple
document.
of a multi-valued document.
@doc Selects the "proper" document:
- chooses update-value/metadata if update-value is set
(assumes a vtag has been specified)
@spec encode_vclock_header(reqdata(), context()) -> reqdata()
into something suitable for an HTTP header
vclock is returned.
@doc Ensure that the 'doc' field of the context() has been filled
with the result of a riak_client:get request. This is a
convenience for memoizing the result of a get so it can be
used in multiple places in this resource, without having to
worry about the order of executing of those places.
@doc Delete the document specified.
@doc Get the etag for this resource.
Bucket requests will have no etag.
Documents will have an etag equal to their vtag. No etag will be
given for documents with siblings, if no sibling was chosen with the
vtag query param.
{undefined|datetime(), reqdata(), context()}
@doc Get the last-modified time for this resource.
Bucket requests will have no last-modified time.
Documents will have the last-modified time specified by the riak_object.
No last-modified time will be given for documents with siblings, if no
@doc Add the Link header specifying the containing bucket of
the document to the response.
reqdata()
@doc Add a Link header specifying the given Bucket and Key
with the given Tag to the response.
@spec format_link(string(), binary()) -> string()
@doc Format a Link header to a bucket.
@spec format_link(string(), binary(), binary(), binary()) -> string()
@doc Format a Link header to another document.
@doc Extract the list of links from the Link request header.
This function will die if an invalid link header format
is found.
@doc Work out the content type for this object - use the metadata if provided
@doc Encode the object value as a binary - content type can be used
to decode
@doc Accept the object value as a binary - content type can be used
to decode | raw_http_resource : Webmachine resource for serving data
Copyright ( c ) 2007 - 2010 Basho Technologies , Inc. All Rights Reserved .
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
@doc Resource for serving objects over HTTP .
{ " props":{Prop1 : Val1,Prop2 : Val2 , ... } ,
Where ModuleName and FunctionName are each strings representing
Equivalent to " PUT /Prefix / Bucket / Key " where Key is chosen
Get the data stored in the named Bucket under the named Key .
Etag : The " vtag " metadata of the object
X - Riak - Meta- : Any headers prefixed by X - Riak - Meta- supplied
on PUT are returned verbatim
Specifying the query param " r = R " , where R is an integer will
cause to use R as the r - value for the read request . A
default r - value of 2 will be used if none is specified .
Store new data in the named Bucket under the named Key .
Include custom metadata using headers prefixed with X - Riak - Meta- .
Specifying the query param " w = W " , where W is an integer will
cause to use W as the w - value for the write request . A
default w - value of 2 will be used if none is specified .
Specifying the query param " dw = DW " , where DW is an integer will
cause to use DW as the dw - value for the write request . A
Specifying the query param " r = R " , where R is an integer will
cause to use R as the r - value for the read request ( used
r - value of 2 will be used if none is specified .
Equivalent to " PUT /Prefix / Bucket / Key " ( useful for clients that
do not support the PUT method ) .
Delete the data stored in the named Bucket under the named Key .
Specifying the query param " rw = RW " , where RW is an integer will
cause to use RW as the rw - value for the delete request . A
default rw - value of 2 will be used if none is specified .
Webmachine dispatch lines for this resource should look like :
/riak / Bucket and /riak / Bucket / Key . The resource will attempt to
connect to on the same Erlang node one which the resource
-module(riak_kv_wm_raw).
-author('Bryan Fink <>').
-export([
init/1,
service_available/2,
allowed_methods/2,
allow_missing_post/2,
malformed_request/2,
resource_exists/2,
last_modified/2,
generate_etag/2,
content_types_provided/2,
charsets_provided/2,
encodings_provided/2,
content_types_accepted/2,
produce_bucket_body/2,
accept_bucket_body/2,
post_is_create/2,
create_path/2,
process_post/2,
produce_doc_body/2,
accept_doc_body/2,
produce_sibling_message_body/2,
produce_multipart_body/2,
multiple_choices/2,
delete_resource/2
]).
utility exports ( used in )
-export([
vclock_header/1,
format_link/2, format_link/4,
multipart_encode_body/3
]).
}).
@type link ( ) = { ( ) , Key::binary ( ) } , Tag::binary ( ) }
-include_lib("webmachine/include/webmachine.hrl").
-include("riak_kv_wm_raw.hrl").
init(Props) ->
{ok, #ctx{prefix=proplists:get_value(prefix, Props),
riak=proplists:get_value(riak, Props)}}.
( ) , context ( ) ) - >
@doc Determine whether or not a connection to Riak
service_available(RD, Ctx=#ctx{riak=RiakProps}) ->
case get_riak_client(RiakProps, get_client_id(RD)) of
{ok, C} ->
{true,
RD,
Ctx#ctx{
method=wrq:method(RD),
client=C,
bucket=list_to_binary(wrq:path_info(bucket, RD)),
key=case wrq:path_info(key, RD) of
undefined -> undefined;
K -> list_to_binary(K)
end,
vtag=wrq:get_qs_value(?Q_VTAG, RD)
}};
Error ->
{false,
wrq:set_resp_body(
io_lib:format("Unable to connect to Riak: ~p~n", [Error]),
wrq:set_resp_header(?HEAD_CTYPE, "text/plain", RD)),
Ctx}
end.
( ) } , term ( ) ) - >
get_riak_client(local, ClientId) ->
riak:local_client(ClientId);
get_riak_client({Node, Cookie}, ClientId) ->
erlang:set_cookie(node(), Cookie),
riak:client_connect(Node, ClientId).
( ) ) - > term ( )
32 - bit binary ( ) if the header could be base64 - decoded
into a 32 - bit binary
into a 32 - bit binary
get_client_id(RD) ->
case wrq:get_req_header(?HEAD_CLIENT, RD) of
undefined -> undefined;
RawId ->
case catch base64:decode(RawId) of
ClientId= <<_:32>> -> ClientId;
_ -> RawId
end
end.
HEAD , GET , POST , and PUT are supported at both
allowed_methods(RD, Ctx=#ctx{key=undefined}) ->
{['HEAD', 'GET', 'POST', 'PUT'], RD, Ctx};
allowed_methods(RD, Ctx) ->
{['HEAD', 'GET', 'POST', 'PUT', 'DELETE'], RD, Ctx}.
allow_missing_post(reqdata ( ) , context ( ) ) - >
@doc Makes POST and PUT equivalent for creating new
allow_missing_post(RD, Ctx) ->
{true, RD, Ctx}.
( ) , context ( ) ) - > boolean ( )
is_bucket_put(RD, Ctx) ->
{undefined, 'PUT'} =:= {Ctx#ctx.key, wrq:method(RD)}.
& lt;/Prefix / Bucket / Key> ; ; " , ...
malformed_request(RD, Ctx) when Ctx#ctx.method =:= 'POST'
orelse Ctx#ctx.method =:= 'PUT' ->
case is_bucket_put(RD, Ctx) of
true ->
malformed_bucket_put(RD, Ctx);
false ->
case wrq:get_req_header("Content-Type", RD) of
undefined ->
{true, missing_content_type(RD), Ctx};
_ ->
case malformed_rw_params(RD, Ctx) of
Result={true, _, _} -> Result;
{false, RWRD, RWCtx} ->
malformed_link_headers(RWRD, RWCtx)
end
end
end;
malformed_request(RD, Ctx) ->
case malformed_rw_params(RD, Ctx) of
Result={true, _, _} -> Result;
{false, RWRD, RWCtx} ->
malformed_link_headers(RWRD, RWCtx)
end.
@doc Check the JSON format of a bucket - level PUT .
malformed_bucket_put(RD, Ctx) ->
case catch mochijson2:decode(wrq:req_body(RD)) of
{struct, Fields} ->
case proplists:get_value(?JSON_PROPS, Fields) of
{struct, Props} ->
{false, RD, Ctx#ctx{bucketprops=Props}};
_ ->
{true, bucket_format_message(RD), Ctx}
end;
_ ->
{true, bucket_format_message(RD), Ctx}
end.
( ) ) - > reqdata ( )
bucket_format_message(RD) ->
wrq:append_to_resp_body(
["bucket PUT must be a JSON object of the form:\n",
"{\"",?JSON_PROPS,"\":{...bucket properties...}}"],
wrq:set_resp_header(?HEAD_CTYPE, "text/plain", RD)).
( ) , context ( ) ) - >
malformed_rw_params(RD, Ctx) ->
lists:foldl(fun malformed_rw_param/2,
{false, RD, Ctx},
[{#ctx.r, "r", "2"},
{#ctx.w, "w", "2"},
{#ctx.dw, "dw", "0"},
{#ctx.rw, "rw", "2"}]).
( ) , Name::string ( ) , Default::string ( ) } ,
is , or print an error message in ( ) if it is not .
malformed_rw_param({Idx, Name, Default}, {Result, RD, Ctx}) ->
case catch list_to_integer(wrq:get_qs_value(Name, Default, RD)) of
N when is_integer(N) ->
{Result, RD, setelement(Idx, Ctx, N)};
_ ->
{true,
wrq:append_to_resp_body(
io_lib:format("~s query parameter must be an integer~n",
[Name]),
wrq:set_resp_header(?HEAD_CTYPE, "text/plain", RD)),
Ctx}
end.
( ) , context ( ) ) - >
& lt;/Prefix / Bucket / Key> ; ; " , ...
malformed_link_headers(RD, Ctx) ->
case catch get_link_heads(RD, Ctx) of
Links when is_list(Links) ->
{false, RD, Ctx#ctx{links=Links}};
_Error ->
{true,
wrq:append_to_resp_body(
io_lib:format("Invalid Link header. Links must be of the form~n"
"</~s/BUCKET/KEY>; riaktag=\"TAG\"~n",
[Ctx#ctx.prefix]),
wrq:set_resp_header(?HEAD_CTYPE, "text/plain", RD)),
Ctx}
end.
( ) , context ( ) ) - >
{ [ { ContentType::string ( ) , Producer::atom ( ) } ] , reqdata ( ) , context ( ) }
was used in the PUT request that stored the document in Riak .
content_types_provided(RD, Ctx=#ctx{key=undefined}) ->
{[{"application/json", produce_bucket_body}], RD, Ctx};
content_types_provided(RD, Ctx=#ctx{method=Method}=Ctx) when Method =:= 'PUT';
Method =:= 'POST' ->
{ContentType, _} = extract_content_type(RD),
{[{ContentType, produce_doc_body}], RD, Ctx};
content_types_provided(RD, Ctx0) ->
DocCtx = ensure_doc(Ctx0),
case DocCtx#ctx.doc of
{ok, _} ->
case select_doc(DocCtx) of
{MD, V} ->
{[{get_ctype(MD,V), produce_doc_body}], RD, DocCtx};
multiple_choices ->
{[{"text/plain", produce_sibling_message_body},
{"multipart/mixed", produce_multipart_body}], RD, DocCtx}
end;
{error, notfound} ->
{[{"text/plain", produce_error_message}], RD, DocCtx}
end.
in the PUT request that stored the document in ( none if
no charset was specified at PUT - time ) .
charsets_provided(RD, Ctx=#ctx{key=undefined}) ->
{no_charset, RD, Ctx};
charsets_provided(RD, #ctx{method=Method}=Ctx) when Method =:= 'PUT';
Method =:= 'POST' ->
case extract_content_type(RD) of
{_, undefined} ->
{no_charset, RD, Ctx};
{_, Charset} ->
{[{Charset, fun(X) -> X end}], RD, Ctx}
end;
charsets_provided(RD, Ctx0) ->
DocCtx = ensure_doc(Ctx0),
case DocCtx#ctx.doc of
{ok, _} ->
case select_doc(DocCtx) of
{MD, _} ->
case dict:find(?MD_CHARSET, MD) of
{ok, CS} ->
{[{CS, fun(X) -> X end}], RD, DocCtx};
error ->
{no_charset, RD, DocCtx}
end;
multiple_choices ->
{no_charset, RD, DocCtx}
end;
{error, notfound} ->
{no_charset, RD, DocCtx}
end.
( ) , context ( ) ) - >
used in the PUT request that stored the document in Riak , or
" identity " and " gzip " if no encoding was specified at PUT - time .
encodings_provided(RD, Ctx=#ctx{key=undefined}) ->
{default_encodings(), RD, Ctx};
encodings_provided(RD, Ctx0) ->
DocCtx = ensure_doc(Ctx0),
case DocCtx#ctx.doc of
{ok, _} ->
case select_doc(DocCtx) of
{MD, _} ->
case dict:find(?MD_ENCODING, MD) of
{ok, Enc} ->
{[{Enc, fun(X) -> X end}], RD, DocCtx};
error ->
{default_encodings(), RD, DocCtx}
end;
multiple_choices ->
{default_encodings(), RD, DocCtx}
end;
{error, notfound} ->
{default_encodings(), RD, DocCtx}
end.
default_encodings ( ) - > [ { Encoding::string ( ) , Producer::function ( ) } ]
default_encodings() ->
[{"identity", fun(X) -> X end},
{"gzip", fun(X) -> zlib:gzip(X) end}].
content_types_accepted(reqdata ( ) , context ( ) ) - >
of a key - level PUT request will be accepted by this resource .
content_types_accepted(RD, Ctx) ->
case is_bucket_put(RD, Ctx) of
true ->
{[{"application/json", accept_bucket_body}], RD, Ctx};
false ->
case wrq:get_req_header(?HEAD_CTYPE, RD) of
undefined ->
{[], RD, Ctx};
CType ->
Media = hd(string:tokens(CType, ";")),
case string:tokens(Media, "/") of
[_Type, _Subtype] ->
{[{Media, accept_doc_body}], RD, Ctx};
_ ->
{[],
wrq:set_resp_header(
?HEAD_CTYPE,
"text/plain",
wrq:set_resp_body(
["\"", Media, "\""
" is not a valid media type"
" for the Content-type header.\n"],
RD)),
Ctx}
end
end
end.
@spec resource_exists(reqdata ( ) , context ( ) ) - > { boolean ( ) , reqdata ( ) , context ( ) }
Documents exists if a read request to returns { ok , riak_object ( ) } ,
vtag param matches the vtag of some value of the object .
resource_exists(RD, Ctx=#ctx{key=undefined}) ->
{true, RD, Ctx};
resource_exists(RD, Ctx0) ->
DocCtx = ensure_doc(Ctx0),
case DocCtx#ctx.doc of
{ok, Doc} ->
case DocCtx#ctx.vtag of
undefined ->
{true, RD, DocCtx};
Vtag ->
MDs = riak_object:get_metadatas(Doc),
{lists:any(fun(M) ->
dict:fetch(?MD_VTAG, M) =:= Vtag
end,
MDs),
RD, DocCtx#ctx{vtag=Vtag}}
end;
{error, notfound} ->
{false, RD, DocCtx}
end.
( ) , context ( ) ) - > { binary ( ) , reqdata ( ) , context ( ) }
like so : { " keys":[Key1 , Key2 , ... ] } .
produce_bucket_body(RD, Ctx=#ctx{bucket=B, client=C}) ->
SchemaPart =
case wrq:get_qs_value(?Q_PROPS, RD) of
?Q_FALSE -> [];
_ ->
Props = C:get_bucket(B),
JsonProps = lists:map(fun jsonify_bucket_prop/1, Props),
[{?JSON_PROPS, {struct, JsonProps}}]
end,
{KeyPart, KeyRD} =
case wrq:get_qs_value(?Q_KEYS, RD) of
?Q_FALSE -> {[], RD};
?Q_STREAM -> {stream, RD};
_ ->
{ok, KeyList} = C:list_keys(B),
{[{?Q_KEYS, KeyList}],
lists:foldl(
fun(K, Acc) ->
add_link_head(B, K, "contained", Acc, Ctx)
end,
RD, KeyList)}
end,
case KeyPart of
stream -> {{stream, {mochijson2:encode({struct, SchemaPart}),
fun() ->
{ok, ReqId} = C:stream_list_keys(B),
stream_keys(ReqId)
end}},
KeyRD,
Ctx};
_ ->
{mochijson2:encode({struct, SchemaPart++KeyPart}), KeyRD, Ctx}
end.
stream_keys(ReqId) ->
receive
{ReqId, {keys, Keys}} ->
{mochijson2:encode({struct, [{<<"keys">>, Keys}]}), fun() -> stream_keys(ReqId) end};
{ReqId, done} -> {mochijson2:encode({struct, [{<<"keys">>, []}]}), done}
end.
accept_bucket_body(reqdata ( ) , context ( ) ) - > { true , reqdata ( ) , context ( ) }
bucket - level PUT request .
accept_bucket_body(RD, Ctx=#ctx{bucket=B, client=C, bucketprops=Props}) ->
ErlProps = lists:map(fun erlify_bucket_prop/1, Props),
C:set_bucket(B, ErlProps),
{true, RD, Ctx}.
( ) , erlpropvalue ( ) } ) - >
@type erlpropvalue ( ) = integer()|string()|boolean()|
{ modfun , atom ( ) , atom()}|{atom ( ) , atom ( ) }
@type jsonmodfun ( ) = { mod_binary ( ) , binary()}|{fun_binary ( ) , binary ( ) }
@doc Convert erlang bucket properties to JSON bucket properties .
jsonify_bucket_prop({linkfun, {modfun, Module, Function}}) ->
{?JSON_LINKFUN, {struct, [{?JSON_MOD,
list_to_binary(atom_to_list(Module))},
{?JSON_FUN,
list_to_binary(atom_to_list(Function))}]}};
jsonify_bucket_prop({linkfun, {qfun, _}}) ->
{?JSON_LINKFUN, <<"qfun">>};
jsonify_bucket_prop({linkfun, {jsfun, Name}}) ->
{?JSON_LINKFUN, {struct, [{?JSON_JSFUN, Name}]}};
jsonify_bucket_prop({linkfun, {jsanon, {Bucket, Key}}}) ->
{?JSON_LINKFUN, {struct, [{?JSON_JSANON,
{struct, [{?JSON_JSBUCKET, Bucket},
{?JSON_JSKEY, Key}]}}]}};
jsonify_bucket_prop({linkfun, {jsanon, Source}}) ->
{?JSON_LINKFUN, {struct, [{?JSON_JSANON, Source}]}};
jsonify_bucket_prop({chash_keyfun, {Module, Function}}) ->
{?JSON_CHASH, {struct, [{?JSON_MOD,
list_to_binary(atom_to_list(Module))},
{?JSON_FUN,
list_to_binary(atom_to_list(Function))}]}};
jsonify_bucket_prop({Prop, Value}) ->
{list_to_binary(atom_to_list(Prop)), Value}.
@doc The reverse of jsonify_bucket_prop/1 . Converts JSON representation
of bucket properties to their Erlang form .
erlify_bucket_prop({?JSON_LINKFUN, {struct, Props}}) ->
case {proplists:get_value(?JSON_MOD, Props),
proplists:get_value(?JSON_FUN, Props)} of
{Mod, Fun} when is_binary(Mod), is_binary(Fun) ->
{linkfun, {modfun,
list_to_existing_atom(binary_to_list(Mod)),
list_to_existing_atom(binary_to_list(Fun))}};
{undefined, undefined} ->
case proplists:get_value(?JSON_JSFUN, Props) of
Name when is_binary(Name) ->
{linkfun, {jsfun, Name}};
undefined ->
case proplists:get_value(?JSON_JSANON, Props) of
{struct, Bkey} ->
Bucket = proplists:get_value(?JSON_JSBUCKET, Bkey),
Key = proplists:get_value(?JSON_JSKEY, Bkey),
true = is_binary(Bucket) andalso is_binary(Key),
{linkfun, {jsanon, {Bucket, Key}}};
Source when is_binary(Source) ->
{linkfun, {jsanon, Source}}
end
end
end;
erlify_bucket_prop({?JSON_CHASH, {struct, Props}}) ->
{chash_keyfun, {list_to_existing_atom(
binary_to_list(
proplists:get_value(?JSON_MOD, Props))),
list_to_existing_atom(
binary_to_list(
proplists:get_value(?JSON_FUN, Props)))}};
erlify_bucket_prop({?JSON_ALLOW_MULT, Value}) ->
{allow_mult, any_to_bool(Value)};
erlify_bucket_prop({Prop, Value}) ->
{list_to_existing_atom(binary_to_list(Prop)), Value}.
( ) , context ( ) ) - > { boolean ( ) , reqdata ( ) , context ( ) }
requests ( this makes webmachine call create_path/2 , where the key
post_is_create(RD, Ctx=#ctx{key=undefined}) ->
{true, RD, Ctx};
post_is_create(RD, Ctx) ->
{false, RD, Ctx}.
create_path(reqdata ( ) , context ( ) ) - > { string ( ) , reqdata ( ) , context ( ) }
201 Created response .
create_path(RD, Ctx=#ctx{prefix=P, bucket=B}) ->
K = riak_core_util:unique_id_62(),
{K,
wrq:set_resp_header("Location",
lists:append(["/",P,"/",binary_to_list(B),"/",K]),
RD),
Ctx#ctx{key=list_to_binary(K)}}.
process_post(reqdata ( ) , context ( ) ) - > { true , reqdata ( ) , context ( ) }
as PUT for clients that do not support PUT .
process_post(RD, Ctx) -> accept_doc_body(RD, Ctx).
( ) , context ( ) ) - > { true , ( ) , context ( ) }
@doc Store the data the client is PUTing in the document .
into their final riak_object ( ) form , and executes the put .
accept_doc_body(RD, Ctx=#ctx{bucket=B, key=K, client=C, links=L}) ->
Doc0 = case Ctx#ctx.doc of
{ok, D} -> D;
_ -> riak_object:new(B, K, <<>>)
end,
VclockDoc = riak_object:set_vclock(Doc0, decode_vclock_header(RD)),
{CType, Charset} = extract_content_type(RD),
UserMeta = extract_user_meta(RD),
CTypeMD = dict:store(?MD_CTYPE, CType, dict:new()),
CharsetMD = if Charset /= undefined ->
dict:store(?MD_CHARSET, Charset, CTypeMD);
true -> CTypeMD
end,
EncMD = case wrq:get_req_header(?HEAD_ENCODING, RD) of
undefined -> CharsetMD;
E -> dict:store(?MD_ENCODING, E, CharsetMD)
end,
LinkMD = dict:store(?MD_LINKS, L, EncMD),
UserMetaMD = dict:store(?MD_USERMETA, UserMeta, LinkMD),
MDDoc = riak_object:update_metadata(VclockDoc, UserMetaMD),
Doc = riak_object:update_value(MDDoc, accept_value(CType, wrq:req_body(RD))),
Options = case wrq:get_qs_value(?Q_RETURNBODY, RD) of ?Q_TRUE -> [returnbody]; _ -> [] end,
case C:put(Doc, Ctx#ctx.w, Ctx#ctx.dw, 60000, Options) of
{error, precommit_fail} ->
{{halt, 403}, send_precommit_error(RD, undefined), Ctx};
{error, {precommit_fail, Reason}} ->
{{halt, 403}, send_precommit_error(RD, Reason), Ctx};
ok ->
{true, RD, Ctx#ctx{doc={ok, Doc}}};
{ok, RObj} ->
DocCtx = Ctx#ctx{doc={ok, RObj}},
HasSiblings = (select_doc(DocCtx) == multiple_choices),
send_returnbody(RD, DocCtx, HasSiblings)
end.
send_returnbody(RD, DocCtx, _HasSiblings = false) ->
{Body, DocRD, DocCtx2} = produce_doc_body(RD, DocCtx),
{true, wrq:append_to_response_body(Body, DocRD), DocCtx2};
send_returnbody(RD, DocCtx, _HasSiblings = true) ->
AcceptHdr = wrq:get_req_header("Accept", RD),
case webmachine_util:choose_media_type(["multipart/mixed", "text/plain"], AcceptHdr) of
"multipart/mixed" ->
{Body, DocRD, DocCtx2} = produce_multipart_body(RD, DocCtx),
{true, wrq:append_to_response_body(Body, DocRD), DocCtx2};
_ ->
{Body, DocRD, DocCtx2} = produce_sibling_message_body(RD, DocCtx),
{true, wrq:append_to_response_body(Body, DocRD), DocCtx2}
end.
@spec extract_content_type(reqdata ( ) ) - >
@doc Interpret the Content - Type header in the client 's PUT request .
extract_content_type(RD) ->
case wrq:get_req_header(?HEAD_CTYPE, RD) of
undefined ->
undefined;
RawCType ->
[CType|RawParams] = string:tokens(RawCType, "; "),
Params = [ list_to_tuple(string:tokens(P, "=")) || P <- RawParams],
{CType, proplists:get_value("charset", Params)}
end.
( ) ) - > proplist ( )
@doc Extract headers prefixed by X - Riak - Meta- in the client 's PUT request
extract_user_meta(RD) ->
lists:filter(fun({K,_V}) ->
lists:prefix(
?HEAD_USERMETA_PREFIX,
string:to_lower(any_to_list(K)))
end,
mochiweb_headers:to_list(wrq:req_headers(RD))).
vtags that are invalid for this version of the document .
multiple_choices(RD, Ctx=#ctx{key=undefined}) ->
{false, RD, Ctx};
multiple_choices(RD, Ctx=#ctx{vtag=undefined, doc={ok, Doc}}) ->
case riak_object:get_update_value(Doc) of
undefined ->
case riak_object:value_count(Doc) of
1 -> {false, RD, Ctx};
_ -> {true, RD, Ctx}
end;
_ ->
{false, RD, Ctx}
end;
multiple_choices(RD, Ctx) ->
specific vtag was specified
{false, RD, Ctx}.
produce_doc_body(reqdata ( ) , context ( ) ) - > { binary ( ) , reqdata ( ) , context ( ) }
body of the request . This function also adds the Link and X - Riak - Meta-
headers to the response . One link will point to the bucket , with the
produce_doc_body(RD, Ctx) ->
case select_doc(Ctx) of
{MD, Doc} ->
Links = case dict:find(?MD_LINKS, MD) of
{ok, L} -> L;
error -> []
end,
LinkRD = add_container_link(
lists:foldl(fun({{B,K},T},Acc) ->
add_link_head(B,K,T,Acc,Ctx)
end,
RD, Links),
Ctx),
UserMetaRD = case dict:find(?MD_USERMETA, MD) of
{ok, UserMeta} ->
lists:foldl(fun({K,V},Acc) ->
wrq:merge_resp_headers([{K,V}],Acc)
end,
LinkRD, UserMeta);
error -> LinkRD
end,
{encode_value(Doc), encode_vclock_header(UserMetaRD, Ctx), Ctx};
multiple_choices ->
throw({unexpected_code_path, ?MODULE, produce_doc_body, multiple_choices})
end.
( ) , context ( ) ) - >
values so they can get to them with the vtag query param .
produce_sibling_message_body(RD, Ctx=#ctx{doc={ok, Doc}}) ->
Vtags = [ dict:fetch(?MD_VTAG, M)
|| M <- riak_object:get_metadatas(Doc) ],
{[<<"Siblings:\n">>, [ [V,<<"\n">>] || V <- Vtags]],
wrq:set_resp_header(?HEAD_CTYPE, "text/plain",
encode_vclock_header(RD, Ctx)),
Ctx}.
produce_multipart_body(reqdata ( ) , context ( ) ) - >
values ( siblings ) , each sibling being one part of the larger
produce_multipart_body(RD, Ctx=#ctx{doc={ok, Doc}, bucket=B, prefix=P}) ->
Boundary = riak_core_util:unique_id_62(),
{[[["\r\n--",Boundary,"\r\n",
multipart_encode_body(P, B, Content)]
|| Content <- riak_object:get_contents(Doc)],
"\r\n--",Boundary,"--\r\n"],
wrq:set_resp_header(?HEAD_CTYPE,
"multipart/mixed; boundary="++Boundary,
encode_vclock_header(RD, Ctx)),
Ctx}.
( ) , binary ( ) , { dict ( ) , binary ( ) } ) - > iolist ( )
@doc Produce one part of a multipart body , representing one sibling
multipart_encode_body(Prefix, Bucket, {MD, V}) ->
[{LHead, Links}] =
mochiweb_headers:to_list(
mochiweb_headers:make(
[{?HEAD_LINK, format_link(Prefix,Bucket)}|
[{?HEAD_LINK, format_link(Prefix,B,K,T)}
|| {{B,K},T} <- case dict:find(?MD_LINKS, MD) of
{ok, Ls} -> Ls;
error -> []
end]])),
[?HEAD_CTYPE, ": ",get_ctype(MD,V),
case dict:find(?MD_CHARSET, MD) of
{ok, CS} -> ["; charset=",CS];
error -> []
end,
"\r\n",
case dict:find(?MD_ENCODING, MD) of
{ok, Enc} -> [?HEAD_ENCODING,": ",Enc,"\r\n"];
error -> []
end,
LHead,": ",Links,"\r\n",
"Etag: ",dict:fetch(?MD_VTAG, MD),"\r\n",
"Last-Modified: ",
case dict:fetch(?MD_LASTMOD, MD) of
Now={_,_,_} ->
httpd_util:rfc1123_date(
calendar:now_to_local_time(Now));
Rfc1123 when is_list(Rfc1123) ->
Rfc1123
end,
"\r\n",
case dict:find(?MD_USERMETA, MD) of
{ok, M} ->
lists:foldl(fun({Hdr,Val},Acc) ->
[Acc|[Hdr,": ",Val,"\r\n"]]
end,
[], M);
error -> []
end,
"\r\n",encode_value(V)].
@spec select_doc(context ( ) ) - > { metadata ( ) , value()}|multiple_choices
- chooses only / if only one exists
- chooses val / given Vtag if multiple contents exist
select_doc(#ctx{doc={ok, Doc}, vtag=Vtag}) ->
case riak_object:get_update_value(Doc) of
undefined ->
case riak_object:get_contents(Doc) of
[Single] -> Single;
Mult ->
case lists:dropwhile(
fun({M,_}) ->
dict:fetch(?MD_VTAG, M) /= Vtag
end,
Mult) of
[Match|_] -> Match;
[] -> multiple_choices
end
end;
UpdateValue ->
{riak_object:get_update_metadata(Doc), UpdateValue}
end.
@doc Add the X - Riak - Vclock header to the response .
encode_vclock_header(RD, #ctx{doc={ok, Doc}}) ->
{Head, Val} = vclock_header(Doc),
wrq:set_resp_header(Head, Val, RD).
@spec vclock_header(riak_object ( ) ) - > { Name::string ( ) , Value::string ( ) }
@doc Transform the Erlang representation of the document 's vclock
vclock_header(Doc) ->
{?HEAD_VCLOCK,
binary_to_list(
base64:encode(zlib:zip(term_to_binary(riak_object:vclock(Doc)))))}.
@spec decode_vclock_header(reqdata ( ) ) - > vclock ( )
@doc Translate the X - Riak - Vclock header value from the request into
its Erlang representation . If no vclock header exists , a fresh
decode_vclock_header(RD) ->
case wrq:get_req_header(?HEAD_VCLOCK, RD) of
undefined -> vclock:fresh();
Head -> binary_to_term(zlib:unzip(base64:decode(Head)))
end.
@spec ensure_doc(context ( ) ) - > context ( )
ensure_doc(Ctx=#ctx{doc=undefined, bucket=B, key=K, client=C, r=R}) ->
Ctx#ctx{doc=C:get(B, K, R)};
ensure_doc(Ctx) -> Ctx.
( ) , context ( ) ) - > { true , reqdata ( ) , context ( ) }
delete_resource(RD, Ctx=#ctx{bucket=B, key=K, client=C, rw=RW}) ->
case C:delete(B, K, RW) of
{error, precommit_fail} ->
{{halt, 403}, send_precommit_error(RD, undefined), Ctx};
{error, {precommit_fail, Reason}} ->
{{halt, 403}, send_precommit_error(RD, Reason), Ctx};
ok ->
{true, RD, Ctx}
end.
( ) , context ( ) ) - >
( ) , reqdata ( ) , context ( ) }
generate_etag(RD, Ctx=#ctx{key=undefined}) ->
{undefined, RD, Ctx};
generate_etag(RD, Ctx) ->
case select_doc(Ctx) of
{MD, _} ->
{dict:fetch(?MD_VTAG, MD), RD, Ctx};
multiple_choices ->
{undefined, RD, Ctx}
end.
( ) , context ( ) ) - >
sibling was chosen with the vtag query param .
last_modified(RD, Ctx=#ctx{key=undefined}) ->
{undefined, RD, Ctx};
last_modified(RD, Ctx) ->
case select_doc(Ctx) of
{MD, _} ->
{case dict:fetch(?MD_LASTMOD, MD) of
Now={_,_,_} ->
calendar:now_to_universal_time(Now);
Rfc1123 when is_list(Rfc1123) ->
httpd_util:convert_request_date(Rfc1123)
end,
RD, Ctx};
multiple_choices ->
{undefined, RD, Ctx}
end.
( ) , context ( ) ) - > reqdata ( )
add_container_link(RD, #ctx{prefix=Prefix, bucket=Bucket}) ->
Val = format_link(Prefix, Bucket),
wrq:merge_resp_headers([{?HEAD_LINK,Val}], RD).
@spec add_link_head(binary ( ) , binary ( ) , binary ( ) , reqdata ( ) , context ( ) ) - >
add_link_head(Bucket, Key, Tag, RD, #ctx{prefix=Prefix}) ->
Val = format_link(Prefix, Bucket, Key, Tag),
wrq:merge_resp_headers([{?HEAD_LINK,Val}], RD).
format_link(Prefix, Bucket) ->
io_lib:format("</~s/~s>; rel=\"up\"",
[Prefix,
mochiweb_util:quote_plus(Bucket)]).
format_link(Prefix, Bucket, Key, Tag) ->
io_lib:format("</~s/~s/~s>; riaktag=\"~s\"",
[Prefix|
[mochiweb_util:quote_plus(E) ||
E <- [Bucket, Key, Tag] ]]).
( ) , context ( ) ) - > [ link ( ) ]
get_link_heads(RD, #ctx{prefix=Prefix, bucket=B}) ->
case wrq:get_req_header(?HEAD_LINK, RD) of
undefined -> [];
Heads ->
BucketLink = lists:flatten(format_link(Prefix, B)),
{ok, Re} = re:compile("</([^/]+)/([^/]+)/([^/]+)>; ?riaktag=\"([^\"]+)\""),
lists:map(
fun(L) ->
{match,[InPrefix,Bucket,Key,Tag]} =
re:run(L, Re, [{capture,[1,2,3,4],binary}]),
Prefix = binary_to_list(InPrefix),
{{list_to_binary(mochiweb_util:unquote(Bucket)),
list_to_binary(mochiweb_util:unquote(Key))},
list_to_binary(mochiweb_util:unquote(Tag))}
end,
lists:delete(BucketLink, [string:strip(T) || T<- string:tokens(Heads, ",")]))
end.
get_ctype(dict ( ) , term ( ) ) - > string ( )
get_ctype(MD,V) ->
case dict:find(?MD_CTYPE, MD) of
{ok, Ctype} ->
Ctype;
error when is_binary(V) ->
"application/octet-stream";
error ->
"application/x-erlang-binary"
end.
@spec encode_value(term ( ) ) - > binary ( )
encode_value(V) when is_binary(V) ->
V;
encode_value(V) ->
term_to_binary(V).
accept_value(string ( ) , binary ( ) ) - > term ( )
accept_value("application/x-erlang-binary",V) ->
binary_to_term(V);
accept_value(_Ctype, V) ->
V.
any_to_list(V) when is_list(V) ->
V;
any_to_list(V) when is_atom(V) ->
atom_to_list(V);
any_to_list(V) when is_binary(V) ->
binary_to_list(V).
any_to_bool(V) when is_list(V) ->
(V == "1") orelse (V == "true") orelse (V == "TRUE");
any_to_bool(V) when is_binary(V) ->
any_to_bool(binary_to_list(V));
any_to_bool(V) when is_integer(V) ->
V /= 0;
any_to_bool(V) when is_boolean(V) ->
V.
missing_content_type(RD) ->
RD1 = wrq:set_resp_header("Content-Type", "text/plain", RD),
wrq:append_to_response_body(<<"Missing Content-Type request header">>, RD1).
send_precommit_error(RD, Reason) ->
RD1 = wrq:set_resp_header("Content-Type", "text/plain", RD),
Error = if
Reason =:= undefined ->
list_to_binary([atom_to_binary(wrq:method(RD1), utf8),
<<" aborted by pre-commit hook.">>]);
true ->
Reason
end,
wrq:append_to_response_body(Error, RD1).
|
4349640a68fec0ebb2c06f4d91c8427a59def2e773e01c330697140896bd88a5 | turtlesoupy/haskakafka | ConsumerExample.hs | module Haskakafka.ConsumerExample
where
import Control.Arrow ((&&&))
import Haskakafka
import Haskakafka.Consumer
import Haskakafka.InternalRdKafkaEnum ()
iterator :: [Integer]
iterator = [0 .. 20]
runConsumerExample :: IO ()
runConsumerExample = do
res <- runConsumer
(ConsumerGroupId "test_group")
[]
(BrokersString "localhost:9092")
[TopicName "^hl-test*"]
processMessages
print $ show res
consumerExample :: IO ()
consumerExample = do
print "creating kafka conf"
conf <- newKafkaConsumerConf (ConsumerGroupId "test_group") []
-- unnecessary, demo only
setRebalanceCallback conf printingRebalanceCallback
res <- runConsumerConf
conf
(BrokersString "localhost:9092")
[TopicName "^hl-test*"]
processMessages
print $ show res
-------------------------------------------------------------------
processMessages :: Kafka -> IO (Either KafkaError ())
processMessages kafka = do
mapM_ (\_ -> do
msg1 <- pollMessage kafka 1000
print $ show msg1) iterator
return $ Right ()
printingRebalanceCallback :: Kafka -> KafkaError -> [KafkaTopicPartition] -> IO ()
printingRebalanceCallback k e ps = do
print $ show e
print "partitions: "
mapM_ (print . show . (ktpTopicName &&& ktpPartition &&& ktpOffset)) ps
case e of
KafkaResponseError RdKafkaRespErrAssignPartitions -> do
err <- assign k ps
print $ "Assign result: " ++ show err
KafkaResponseError RdKafkaRespErrRevokePartitions -> do
err <- assign k []
print $ "Revoke result: " ++ show err
x ->
print "UNKNOWN (and unlikely!)" >> print (show x)
| null | https://raw.githubusercontent.com/turtlesoupy/haskakafka/cae3348be1a3934629cf58d433c224d87ff59608/src/Haskakafka/ConsumerExample.hs | haskell | unnecessary, demo only
----------------------------------------------------------------- | module Haskakafka.ConsumerExample
where
import Control.Arrow ((&&&))
import Haskakafka
import Haskakafka.Consumer
import Haskakafka.InternalRdKafkaEnum ()
iterator :: [Integer]
iterator = [0 .. 20]
runConsumerExample :: IO ()
runConsumerExample = do
res <- runConsumer
(ConsumerGroupId "test_group")
[]
(BrokersString "localhost:9092")
[TopicName "^hl-test*"]
processMessages
print $ show res
consumerExample :: IO ()
consumerExample = do
print "creating kafka conf"
conf <- newKafkaConsumerConf (ConsumerGroupId "test_group") []
setRebalanceCallback conf printingRebalanceCallback
res <- runConsumerConf
conf
(BrokersString "localhost:9092")
[TopicName "^hl-test*"]
processMessages
print $ show res
processMessages :: Kafka -> IO (Either KafkaError ())
processMessages kafka = do
mapM_ (\_ -> do
msg1 <- pollMessage kafka 1000
print $ show msg1) iterator
return $ Right ()
printingRebalanceCallback :: Kafka -> KafkaError -> [KafkaTopicPartition] -> IO ()
printingRebalanceCallback k e ps = do
print $ show e
print "partitions: "
mapM_ (print . show . (ktpTopicName &&& ktpPartition &&& ktpOffset)) ps
case e of
KafkaResponseError RdKafkaRespErrAssignPartitions -> do
err <- assign k ps
print $ "Assign result: " ++ show err
KafkaResponseError RdKafkaRespErrRevokePartitions -> do
err <- assign k []
print $ "Revoke result: " ++ show err
x ->
print "UNKNOWN (and unlikely!)" >> print (show x)
|
7478ba141da76dc36877f40cd17a4531cb41b45da7398e3da7378f4bfa3d8846 | clojure-interop/aws-api | AWSXRayAsyncClientBuilder.clj | (ns com.amazonaws.services.xray.AWSXRayAsyncClientBuilder
"Fluent builder for AWSXRayAsync. Use of the builder is preferred over using
constructors of the client class."
(:refer-clojure :only [require comment defn ->])
(:import [com.amazonaws.services.xray AWSXRayAsyncClientBuilder]))
(defn *standard
"returns: Create new instance of builder with all defaults set. - `com.amazonaws.services.xray.AWSXRayAsyncClientBuilder`"
(^com.amazonaws.services.xray.AWSXRayAsyncClientBuilder []
(AWSXRayAsyncClientBuilder/standard )))
(defn *default-client
"returns: Default async client using the DefaultAWSCredentialsProviderChain and
DefaultAwsRegionProviderChain chain - `com.amazonaws.services.xray.AWSXRayAsync`"
(^com.amazonaws.services.xray.AWSXRayAsync []
(AWSXRayAsyncClientBuilder/defaultClient )))
| null | https://raw.githubusercontent.com/clojure-interop/aws-api/59249b43d3bfaff0a79f5f4f8b7bc22518a3bf14/com.amazonaws.services.xray/src/com/amazonaws/services/xray/AWSXRayAsyncClientBuilder.clj | clojure | (ns com.amazonaws.services.xray.AWSXRayAsyncClientBuilder
"Fluent builder for AWSXRayAsync. Use of the builder is preferred over using
constructors of the client class."
(:refer-clojure :only [require comment defn ->])
(:import [com.amazonaws.services.xray AWSXRayAsyncClientBuilder]))
(defn *standard
"returns: Create new instance of builder with all defaults set. - `com.amazonaws.services.xray.AWSXRayAsyncClientBuilder`"
(^com.amazonaws.services.xray.AWSXRayAsyncClientBuilder []
(AWSXRayAsyncClientBuilder/standard )))
(defn *default-client
"returns: Default async client using the DefaultAWSCredentialsProviderChain and
DefaultAwsRegionProviderChain chain - `com.amazonaws.services.xray.AWSXRayAsync`"
(^com.amazonaws.services.xray.AWSXRayAsync []
(AWSXRayAsyncClientBuilder/defaultClient )))
| |
1a9c79fa70683f9b88cb3a24b22a10cf5972be1c972100c2d08703e0dee14b28 | cpeikert/ALCHEMY | Arithmetic.hs | # LANGUAGE MultiParamTypeClasses #
# LANGUAGE TypeFamilies #
module Crypto.Alchemy.Language.Arithmetic where
import Crypto.Alchemy.Language.Lambda
-- | Addition.
class Add_ expr a where
-- | Addition.
add_ :: expr e (a -> a -> a)
-- | Negation.
neg_ :: expr e (a -> a)
infixl 6 +:, -:
(+:), (-:) :: (Add_ expr a, Lambda_ expr) => expr e a -> expr e a -> expr e a
-- | Convenient metalanguage version of 'add_'.
a +: b = add_ $: a $: b
-- | Convenient metalanguage version of subtraction.
a -: b = a +: (neg_ $: b)
-- | Addition of (metalanguage) literals to (object language)
-- expressions.
class AddLit_ expr a where
addLit_ :: a -> expr e (a -> a)
infixl 6 >+:
(>+:) :: (AddLit_ expr a, Lambda_ expr) => a -> expr e a -> expr e a
a >+: b = addLit_ a $: b
| Multiplication . ( Note that the input type @b@ may differ from the
output type )
class Mul_ expr a where
type PreMul_ expr a
-- | Multiplication.
mul_ :: expr e (PreMul_ expr a -> PreMul_ expr a -> a)
-- | Convenient metalanguage version of 'mul'.
match 's precedence
(*:) :: (Mul_ expr a, Lambda_ expr) =>
expr e (PreMul_ expr a) -> expr e (PreMul_ expr a) -> expr e a
a *: b = mul_ $: a $: b
-- | Multiplication of (metalanguage) literals to (object language)
-- expressions.
class MulLit_ expr a where
mulLit_ :: a -> expr e (a -> a)
infixl 7 >*:
(>*:) :: (MulLit_ expr a, Lambda_ expr) => a -> expr e a -> expr e a
a >*: b = mulLit_ a $: b
-- | Symantics for division-by-2 of a known-to-be-even value along
-- with its integer modulus.
class Div2_ expr a where
type PreDiv2_ expr a
-- | Divide a value that is known to be even, along with its integer
modulus , by two .
div2_ :: expr e (PreDiv2_ expr a -> a)
| null | https://raw.githubusercontent.com/cpeikert/ALCHEMY/adbef64576c6f6885600da66f59c5a4ad91810b7/src/Crypto/Alchemy/Language/Arithmetic.hs | haskell | | Addition.
| Addition.
| Negation.
| Convenient metalanguage version of 'add_'.
| Convenient metalanguage version of subtraction.
| Addition of (metalanguage) literals to (object language)
expressions.
| Multiplication.
| Convenient metalanguage version of 'mul'.
| Multiplication of (metalanguage) literals to (object language)
expressions.
| Symantics for division-by-2 of a known-to-be-even value along
with its integer modulus.
| Divide a value that is known to be even, along with its integer | # LANGUAGE MultiParamTypeClasses #
# LANGUAGE TypeFamilies #
module Crypto.Alchemy.Language.Arithmetic where
import Crypto.Alchemy.Language.Lambda
class Add_ expr a where
add_ :: expr e (a -> a -> a)
neg_ :: expr e (a -> a)
infixl 6 +:, -:
(+:), (-:) :: (Add_ expr a, Lambda_ expr) => expr e a -> expr e a -> expr e a
a +: b = add_ $: a $: b
a -: b = a +: (neg_ $: b)
class AddLit_ expr a where
addLit_ :: a -> expr e (a -> a)
infixl 6 >+:
(>+:) :: (AddLit_ expr a, Lambda_ expr) => a -> expr e a -> expr e a
a >+: b = addLit_ a $: b
| Multiplication . ( Note that the input type @b@ may differ from the
output type )
class Mul_ expr a where
type PreMul_ expr a
mul_ :: expr e (PreMul_ expr a -> PreMul_ expr a -> a)
match 's precedence
(*:) :: (Mul_ expr a, Lambda_ expr) =>
expr e (PreMul_ expr a) -> expr e (PreMul_ expr a) -> expr e a
a *: b = mul_ $: a $: b
class MulLit_ expr a where
mulLit_ :: a -> expr e (a -> a)
infixl 7 >*:
(>*:) :: (MulLit_ expr a, Lambda_ expr) => a -> expr e a -> expr e a
a >*: b = mulLit_ a $: b
class Div2_ expr a where
type PreDiv2_ expr a
modulus , by two .
div2_ :: expr e (PreDiv2_ expr a -> a)
|
cf6c7c413ca767ed3995619f7ad1536e85277d665e31829945471262014824ad | kappelmann/eidi2_repetitorium_tum | List_Stack.ml | open Stack
module ListStack : Stack = struct
type 'a stack = 'a list
let empty = []
let is_empty s = s=[]
let push s e = e::s
let pop = function [] -> (None,[]) | x::xs -> (Some x, xs)
end
let s = ListStack.empty
let s = ListStack.push s 1
let s = ListStack.push s 2
let s = ListStack.push s 3
let (Some x, s) = ListStack.pop s
3 printen
let (Some x, s) = ListStack.pop s
2 printen
| null | https://raw.githubusercontent.com/kappelmann/eidi2_repetitorium_tum/1d16bbc498487a85960e0d83152249eb13944611/2017/ocaml/data_structures/case_example_stack/List_Stack.ml | ocaml | open Stack
module ListStack : Stack = struct
type 'a stack = 'a list
let empty = []
let is_empty s = s=[]
let push s e = e::s
let pop = function [] -> (None,[]) | x::xs -> (Some x, xs)
end
let s = ListStack.empty
let s = ListStack.push s 1
let s = ListStack.push s 2
let s = ListStack.push s 3
let (Some x, s) = ListStack.pop s
3 printen
let (Some x, s) = ListStack.pop s
2 printen
| |
2921dfa7e834cbff6743b2cc3a84a55cea044ef93efafdddcde989cdafc4e6ea | psholtz/MIT-SICP | exercise1-23.scm | ;;
Exercise 1.23
;;
;; The "smallest-divisor" procedure shown at the start of this section does lots of
needless testing : After it checks to see if the number is divisible by 2 , there
;; is no point in checking to see if it is divisible by any larger even numbers. This
suggests that the values used for " test - divisor " should not be 2,3,4,5,6 , ... but
;; rather 2,3,5,7,9... To implement this change, define a procedure "next" that returns
3 if its input is equal to 2 , and otherwise returns its input plus 2 . Modify the
" smallest - divisor " procedure to use " ( next test - divisor ) " instead of " ( + test - divisor 1 ) " .
;; With "timed-prime-test" incorporaitng this modified version of "smallest-divisor", run
the test for each of the 12 primes found in exercise 1.22 . Since this modification
;; halves the number of test steps, you should expect it to run about twice as fast.
;; Is this expectation confirmed? If not, what is the observed ratio of the speeds of
the two algorithms , and how do you explain the fact that it is different from 2 ?
;;
;;
As before , let 's first define the code that allows us to check for primes .
;;
The major difference between this code and that in Exercise 1.22 is
;; that here we have defined a new procedure "next", which should cut
down the time needed to test a number for primality roughly by half .
;;
;; The statistics gathered at the end of this document, and discussed
;; in greater depth in the corresponding .md file, give a more detailed
;; analysis of the performance improvement resulting from this code modification.
;;
(define (smallest-divisor n)
(find-divisor n 2))
(define (next n)
(cond ((= n 2) 3)
(else (+ n 2))))
(define (find-divisor n test-divisor)
(cond ((> (square test-divisor) n) n)
((divides? test-divisor n) test-divisor)
(else (find-divisor n (next test-divisor)))))
(define (divides? a b)
(= (remainder b a) 0))
(define (square x) (* x x))
(define (even? n) (= (remainder n 2) 0))
(define (prime? n)
(= n (smallest-divisor n)))
;;
;; Let's run some unit tests, to make sure it works:
;;
(prime? 3)
;; --> #t
(prime? 4)
;; --> #f
(prime? 5)
;; --> #t
(prime? 6)
;; --> #f
(prime? 7)
;; --> #t
;;
Next , define the procedures for running timed tests .
;;
;; We'll change this somewhat from the procedures presented in the text,
;; in that our procedure will only print a number (and corresponding time)
;; if it's prime.
;;
On MIT Scheme , the ( runtime ) primitive is given by ( real - time - clock ) , and
;; this is the procedure we will use in our code.
;;
(define (timed-prime-test n)
(start-prime-test n (real-time-clock)))
;;
;; Use this definition of start-prime-test, which returns "true" or "false"
;; depending on whether the test candidate is prime, so that we can more easily
;; support the "search-for-n-primes" procedure defined below.
;;
(define (start-prime-test n start-time)
(cond ((prime? n)
(report-prime n (- (real-time-clock) start-time))
#t)
(else #f)))
;;
;; Modify procedure slightly, from what is defined in the text, so that
;; we only print the prime numbers (i.e., non-primes are suppressed).
;;
(define (report-prime n elapsed-time)
(newline)
(display n)
(display " (")
(display elapsed-time)
(display ")"))
;;
;; Finally, let's define the "search-for-primes" procedure.
;;
The procedure will take two integers , a and b , and for each prime
inbetween the two integers ( inclusive ) it will print the prime out
;; and display the time required to calculate that it was a prime.
;;
(define (search-for-primes a b)
(define (search n)
(cond ((<= n b) (timed-prime-test n)))
(cond ((< n b) (search (+ n 2)))))
(if (even? a)
(search (+ a 1))
(search a)))
;;
;; Run use cases..
;;
(search-for-primes 1000 1050)
-- > 1009 ( 0 )
-- > 1013 ( 0 )
-- > 1019 ( 0 )
-- > 1021 ( 0 )
;; --> 1031 (0)
-- > 1033 ( 0 )
-- > 1039 ( 0 )
-- > 1049 ( 0 )
(search-for-primes 10000 10050)
-- > 10007 ( 0 )
;; --> 10009 (0)
-- > 10037 ( 0 )
-- > 10039 ( 0 )
(search-for-primes 100000 100050)
-- > 100003 ( 1 )
-- > 100019 ( 1 )
-- > 100043 ( 1 )
-- > 100049 ( 0 )
(search-for-primes 1000000 1000050)
-- > 1000003 ( 2 )
-- > 1000033 ( 1 )
-- > 1000037 ( 2 )
-- > 1000039 ( 2 )
;;
Now define one additional procedure , which starts at a number a
;; and finds the next n prime numbers (this is, technically, what
;; Exercise 1.22 asks us to do).
;;
(define (search-for-n-primes a n)
(define (search j c)
(let ((next-j (+ j 2)))
(cond ((< c n)
(if (timed-prime-test j)
(search next-j (+ c 1))
(search next-j c))))))
(if (even? a)
(search (+ a 1) 0)
(search a 0)))
;;
;; Run the same use cases.
;;
(search-for-n-primes 1000 3)
-- > 1009 ( 0 )
-- > 1013 ( 0 )
-- > 1019 ( 0 )
(search-for-n-primes 10000 3)
-- > 10007 ( 0 )
;; --> 10009 (0)
-- > 10037 ( 0 )
(search-for-n-primes 100000 3)
;; --> 100003 (0)
-- > 100019 ( 0 )
;; --> 100043 (0)
(search-for-n-primes 1000000 3)
-- > 1000003 ( 2 )
-- > 1000033 ( 1 )
-- > 1000037 ( 2 )
;;
;; These results do seem "faster" than those obtained in the previous version of prime?
;;
;; More comprehensive analysis can be found in the corresponding .md file.
;;
;;
The nine primes analyzed in Exercise 1.22 :
;;
(define point 1000000000)
(timed-prime-test (+ point 7))
-- > 58 milliseconds
(timed-prime-test (+ point 9))
-- > 58 milliseconds
(timed-prime-test (+ point 21))
-- > 58 milliseconds
(define point 10000000000)
(timed-prime-test (+ point 19))
-- > 211 milliseconds
(timed-prime-test (+ point 33))
-- > 210 milliseconds
(timed-prime-test (+ point 61))
-- > 187 milliseconds
(define point 100000000000)
(timed-prime-test (+ point 3))
-- > 620 milliseconds
(timed-prime-test (+ point 19))
-- > 622 milliseconds
(timed-prime-test (+ point 57))
-- > 625 milliseconds | null | https://raw.githubusercontent.com/psholtz/MIT-SICP/01e9b722ac5008e26f386624849117ca8fa80906/Section-1.2/mit-scheme/exercise1-23.scm | scheme |
The "smallest-divisor" procedure shown at the start of this section does lots of
is no point in checking to see if it is divisible by any larger even numbers. This
rather 2,3,5,7,9... To implement this change, define a procedure "next" that returns
With "timed-prime-test" incorporaitng this modified version of "smallest-divisor", run
halves the number of test steps, you should expect it to run about twice as fast.
Is this expectation confirmed? If not, what is the observed ratio of the speeds of
that here we have defined a new procedure "next", which should cut
The statistics gathered at the end of this document, and discussed
in greater depth in the corresponding .md file, give a more detailed
analysis of the performance improvement resulting from this code modification.
Let's run some unit tests, to make sure it works:
--> #t
--> #f
--> #t
--> #f
--> #t
We'll change this somewhat from the procedures presented in the text,
in that our procedure will only print a number (and corresponding time)
if it's prime.
this is the procedure we will use in our code.
Use this definition of start-prime-test, which returns "true" or "false"
depending on whether the test candidate is prime, so that we can more easily
support the "search-for-n-primes" procedure defined below.
Modify procedure slightly, from what is defined in the text, so that
we only print the prime numbers (i.e., non-primes are suppressed).
Finally, let's define the "search-for-primes" procedure.
and display the time required to calculate that it was a prime.
Run use cases..
--> 1031 (0)
--> 10009 (0)
and finds the next n prime numbers (this is, technically, what
Exercise 1.22 asks us to do).
Run the same use cases.
--> 10009 (0)
--> 100003 (0)
--> 100043 (0)
These results do seem "faster" than those obtained in the previous version of prime?
More comprehensive analysis can be found in the corresponding .md file.
| Exercise 1.23
needless testing : After it checks to see if the number is divisible by 2 , there
suggests that the values used for " test - divisor " should not be 2,3,4,5,6 , ... but
3 if its input is equal to 2 , and otherwise returns its input plus 2 . Modify the
" smallest - divisor " procedure to use " ( next test - divisor ) " instead of " ( + test - divisor 1 ) " .
the test for each of the 12 primes found in exercise 1.22 . Since this modification
the two algorithms , and how do you explain the fact that it is different from 2 ?
As before , let 's first define the code that allows us to check for primes .
The major difference between this code and that in Exercise 1.22 is
down the time needed to test a number for primality roughly by half .
(define (smallest-divisor n)
(find-divisor n 2))
(define (next n)
(cond ((= n 2) 3)
(else (+ n 2))))
(define (find-divisor n test-divisor)
(cond ((> (square test-divisor) n) n)
((divides? test-divisor n) test-divisor)
(else (find-divisor n (next test-divisor)))))
(define (divides? a b)
(= (remainder b a) 0))
(define (square x) (* x x))
(define (even? n) (= (remainder n 2) 0))
(define (prime? n)
(= n (smallest-divisor n)))
(prime? 3)
(prime? 4)
(prime? 5)
(prime? 6)
(prime? 7)
Next , define the procedures for running timed tests .
On MIT Scheme , the ( runtime ) primitive is given by ( real - time - clock ) , and
(define (timed-prime-test n)
(start-prime-test n (real-time-clock)))
(define (start-prime-test n start-time)
(cond ((prime? n)
(report-prime n (- (real-time-clock) start-time))
#t)
(else #f)))
(define (report-prime n elapsed-time)
(newline)
(display n)
(display " (")
(display elapsed-time)
(display ")"))
The procedure will take two integers , a and b , and for each prime
inbetween the two integers ( inclusive ) it will print the prime out
(define (search-for-primes a b)
(define (search n)
(cond ((<= n b) (timed-prime-test n)))
(cond ((< n b) (search (+ n 2)))))
(if (even? a)
(search (+ a 1))
(search a)))
(search-for-primes 1000 1050)
-- > 1009 ( 0 )
-- > 1013 ( 0 )
-- > 1019 ( 0 )
-- > 1021 ( 0 )
-- > 1033 ( 0 )
-- > 1039 ( 0 )
-- > 1049 ( 0 )
(search-for-primes 10000 10050)
-- > 10007 ( 0 )
-- > 10037 ( 0 )
-- > 10039 ( 0 )
(search-for-primes 100000 100050)
-- > 100003 ( 1 )
-- > 100019 ( 1 )
-- > 100043 ( 1 )
-- > 100049 ( 0 )
(search-for-primes 1000000 1000050)
-- > 1000003 ( 2 )
-- > 1000033 ( 1 )
-- > 1000037 ( 2 )
-- > 1000039 ( 2 )
Now define one additional procedure , which starts at a number a
(define (search-for-n-primes a n)
(define (search j c)
(let ((next-j (+ j 2)))
(cond ((< c n)
(if (timed-prime-test j)
(search next-j (+ c 1))
(search next-j c))))))
(if (even? a)
(search (+ a 1) 0)
(search a 0)))
(search-for-n-primes 1000 3)
-- > 1009 ( 0 )
-- > 1013 ( 0 )
-- > 1019 ( 0 )
(search-for-n-primes 10000 3)
-- > 10007 ( 0 )
-- > 10037 ( 0 )
(search-for-n-primes 100000 3)
-- > 100019 ( 0 )
(search-for-n-primes 1000000 3)
-- > 1000003 ( 2 )
-- > 1000033 ( 1 )
-- > 1000037 ( 2 )
The nine primes analyzed in Exercise 1.22 :
(define point 1000000000)
(timed-prime-test (+ point 7))
-- > 58 milliseconds
(timed-prime-test (+ point 9))
-- > 58 milliseconds
(timed-prime-test (+ point 21))
-- > 58 milliseconds
(define point 10000000000)
(timed-prime-test (+ point 19))
-- > 211 milliseconds
(timed-prime-test (+ point 33))
-- > 210 milliseconds
(timed-prime-test (+ point 61))
-- > 187 milliseconds
(define point 100000000000)
(timed-prime-test (+ point 3))
-- > 620 milliseconds
(timed-prime-test (+ point 19))
-- > 622 milliseconds
(timed-prime-test (+ point 57))
-- > 625 milliseconds |
dc59dca4a4f0926fef6f8deb94a76b408261528d5054d539230cd4199a5b6b84 | hugoduncan/makejack | uber.clj | (ns makejack.tasks.uber
(:require
[babashka.fs :as fs]
[clojure.tools.build.api :as b]
[makejack.defaults.api :as defaults]
[makejack.deps.api :as mj-deps]
[makejack.project-data.api :as project-data]
[makejack.verbose.api :as v]))
(defn uber
"Build an uberjar file"
[params]
(v/println params "Build uberjar...")
(binding [b/*project-root* (:dir params ".")]
(let [params (defaults/project-data params)
params (project-data/expand-version params)
jar-path (fs/path
(defaults/target-path params)
(defaults/jar-filename params))
basis (mj-deps/lift-local-deps
(or (:basis params) (defaults/basis params)))
src-dirs (defaults/paths basis)
class-dir (str (defaults/classes-path params))
relative? (complement fs/absolute?)]
(b/write-pom {:basis (update basis :paths
#(filterv relative? %))
:class-dir class-dir
:lib (:name params)
:version (:version params)})
(b/copy-dir {:src-dirs src-dirs
:target-dir class-dir
:ignores (defaults/jar-ignores)})
(b/uber (merge
(select-keys
params
[:conflict-handlers :exclude :manifest :main])
{:class-dir class-dir
:uber-file (str jar-path)}))
(assoc params :jar-file (str jar-path)))))
| null | https://raw.githubusercontent.com/hugoduncan/makejack/6968c6c8f2433d5a618acf8820eaa27f41464b95/bases/tasks/src/makejack/tasks/uber.clj | clojure | (ns makejack.tasks.uber
(:require
[babashka.fs :as fs]
[clojure.tools.build.api :as b]
[makejack.defaults.api :as defaults]
[makejack.deps.api :as mj-deps]
[makejack.project-data.api :as project-data]
[makejack.verbose.api :as v]))
(defn uber
"Build an uberjar file"
[params]
(v/println params "Build uberjar...")
(binding [b/*project-root* (:dir params ".")]
(let [params (defaults/project-data params)
params (project-data/expand-version params)
jar-path (fs/path
(defaults/target-path params)
(defaults/jar-filename params))
basis (mj-deps/lift-local-deps
(or (:basis params) (defaults/basis params)))
src-dirs (defaults/paths basis)
class-dir (str (defaults/classes-path params))
relative? (complement fs/absolute?)]
(b/write-pom {:basis (update basis :paths
#(filterv relative? %))
:class-dir class-dir
:lib (:name params)
:version (:version params)})
(b/copy-dir {:src-dirs src-dirs
:target-dir class-dir
:ignores (defaults/jar-ignores)})
(b/uber (merge
(select-keys
params
[:conflict-handlers :exclude :manifest :main])
{:class-dir class-dir
:uber-file (str jar-path)}))
(assoc params :jar-file (str jar-path)))))
| |
fe5762dfec289c96a2abeeed03240115813ebd0996d3e59f0773401801eb3e48 | garrigue/lablgl | test17.ml | #!/usr/bin/env lablglut
Ported to lablglut by Issac Trotts on Sun Aug 11 14:55:37 MDT 2002 .
open Printf
Copyright ( c ) .
(* This program is freely distributable without licensing fees
and is provided without guarantee or warrantee expressed or
implied. This program is -not- in the public domain. *)
(* Test for GLUT 3.0's overlay functionality. *)
let transP = ref 0
let main_win = ref 0
let x = ref 0.0 and y = ref 0.0
let render_normal () =
Glut.useLayer(Glut.NORMAL);
GlClear.clear [`color];
GlDraw.color (0.0,0.0,1.0);
GlDraw.begins `polygon;
GlDraw.vertex ~x:0.2 ~y:0.28 ();
GlDraw.vertex ~x:0.5 ~y:0.58 ();
GlDraw.vertex ~x:0.2 ~y:0.58 ();
GlDraw.ends();
Gl.flush();
;;
let render_overlay () =
GlClear.clear [`color];
GlDraw.begins `polygon;
GlDraw.vertex ~x:(0.2 +. !x) ~y:(0.2 +. !y) ();
GlDraw.vertex ~x:(0.5 +. !x) ~y:(0.5 +. !y) ();
GlDraw.vertex ~x:(0.2 +. !x) ~y:(0.5 +. !y) ();
GlDraw.ends();
Gl.flush();
;;
let render () =
Glut.useLayer(Glut.NORMAL);
render_normal();
if (Glut.layerGet(Glut.HAS_OVERLAY)) then begin
Glut.useLayer(Glut.OVERLAY);
render_overlay();
end
;;
let render_sub () =
printf("render_sub\n");
Glut.useLayer(Glut.NORMAL);
render_normal();
if (Glut.layerGet(Glut.HAS_OVERLAY)) then begin
Glut.useLayer(Glut.OVERLAY);
render_overlay();
end
;;
let display_count = ref 0
let damage_expectation = ref false
let timer ~value =
if (value <> 777) then failwith("unexpected timer value");
damage_expectation := true;
Glut.showWindow();
;;
let rec time2 ~value =
if (value = 666) then begin
printf("PASS: test17\n");
exit(0);
end;
if (value <> 888) then failwith("bad value");
Glut.destroyWindow(!main_win);
Glut.timerFunc 500 time2 666;
;;
let move_on () =
incr display_count;
if (!display_count = 2) then begin
damage_expectation := true;
Glut.iconifyWindow();
Glut.timerFunc 500 timer 777;
end;
if !display_count = 4 then begin
printf "display_count = 4\n";
Glut.initDisplayMode ();
ignore(Glut.createSubWindow !main_win 10 10 150 150);
GlClear.color (0.5, 0.5, 0.5);
Glut.displayFunc(render_sub);
Glut.initDisplayMode ~index:true ();
Glut.establishOverlay();
Glut.copyColormap !main_win;
Glut.setColor ~cell:((!transP + 1) mod 2) ~red:0.0 ~green:1.0 ~blue:1.0;
Glut.removeOverlay();
Glut.establishOverlay();
Glut.copyColormap(!main_win);
Glut.copyColormap(!main_win);
Glut.setColor ~cell:((!transP + 1) mod 2) ~red:1.0 ~green:1.0 ~blue:1.0;
GlClear.index ((float_of_int !transP));
GlDraw.index (float_of_int ((!transP + 1) mod 2));
Glut.setWindow(!main_win);
Glut.removeOverlay();
Glut.timerFunc 500 time2 888;
end
;;
let display_normal() =
if (Glut.layerGet(Glut.NORMAL_DAMAGED) <> !damage_expectation) then
failwith(" normal damage not expected\n");
render_normal();
move_on();
;;
let display_overlay() =
if (Glut.layerGet(Glut.OVERLAY_DAMAGED) <> !damage_expectation) then
failwith(" overlay damage not expected\n");
render_overlay();
move_on();
;;
let been_here = ref false (* strange: this never gets set to true... -ijt *)
let display2() =
if Glut.layerGet(Glut.NORMAL_DAMAGED) then
failwith(" normal damage not expected\n");
if Glut.layerGet(Glut.OVERLAY_DAMAGED) then
failwith(" overlay damage not expected\n");
if (!been_here) then Glut.postOverlayRedisplay()
else begin
Glut.overlayDisplayFunc(display_overlay);
Glut.displayFunc(display_normal);
damage_expectation := true;
Glut.postOverlayRedisplay();
Glut.postRedisplay();
end
;;
let display() =
if not (Glut.layerGet(Glut.NORMAL_DAMAGED)) then
failwith(" normal damage expected\n");
if not (Glut.layerGet(Glut.OVERLAY_DAMAGED)) then
failwith(" overlay damage expected\n");
render();
Glut.displayFunc(display2);
Glut.postRedisplay();
;;
let main () =
ignore(Glut.init Sys.argv);
Glut.initWindowSize 300 300;
Glut.initDisplayMode ~index:true ();
if not (Glut.layerGet(Glut.OVERLAY_POSSIBLE)) then begin
printf "UNRESOLVED: need overlays for this test (your window system ";
printf "lacks overlays)\n";
exit(0);
end;
Glut.initDisplayMode ();
main_win := Glut.createWindow("test17");
if Glut.layerGetInUse() = Glut.OVERLAY then
failwith(" overlay should not be in use\n");
if Glut.layerGet(Glut.HAS_OVERLAY) then
failwith(" overlay should not exist\n");
if Glut.layerGetTransparentIndex() <> -1 then
failwith(" transparent pixel of normal plane should be -1\n");
if Glut.layerGet(Glut.NORMAL_DAMAGED) then
failwith(" no normal damage yet\n");
(* raises exception if overlay is not in use: *)
ignore(Glut.layerGet(Glut.OVERLAY_DAMAGED));
GlClear.color (0.0, 1.0, 0.0);
Glut.initDisplayMode ~index:true ();
(* Small torture test. *)
Glut.establishOverlay();
Glut.removeOverlay();
Glut.establishOverlay();
Glut.establishOverlay();
Glut.showOverlay();
Glut.hideOverlay();
Glut.showOverlay();
Glut.removeOverlay();
Glut.removeOverlay();
Glut.establishOverlay();
if (Glut.get(Glut.WINDOW_RGBA) <> 0) then
failwith(" overlay should not be RGBA\n");
Glut.useLayer(Glut.NORMAL);
if not (Glut.get(Glut.WINDOW_RGBA) <> 0) then
failwith(" normal should be RGBA\n");
Glut.useLayer(Glut.OVERLAY);
if (Glut.get(Glut.WINDOW_RGBA) <> 0) then
failwith(" overlay should not be RGBA\n");
if (Glut.layerGetInUse() = Glut.NORMAL) then
failwith(" overlay should be in use\n");
if not (Glut.layerGet(Glut.HAS_OVERLAY)) then
failwith(" overlay should exist\n");
if (Glut.layerGetTransparentIndex() = -1) then
failwith(" transparent pixel should exist\n");
if Glut.layerGet(Glut.NORMAL_DAMAGED) then
failwith(" no normal damage yet\n");
if Glut.layerGet(Glut.OVERLAY_DAMAGED) then
failwith(" no overlay damage yet\n");
transP := Glut.layerGetTransparentIndex();
GlClear.index (float_of_int (Glut.layerGetTransparentIndex()));
Glut.setColor ((!transP + 1) mod 2) 1.0 0.0 1.0;
GlDraw.index (float_of_int ((!transP + 1) mod 2));
Glut.useLayer(Glut.NORMAL);
if (Glut.layerGetInUse() = Glut.OVERLAY) then
failwith(" overlay should not be in use\n");
Glut.displayFunc(display);
Glut.mainLoop();
;;
let _ = main();;
| null | https://raw.githubusercontent.com/garrigue/lablgl/d76e4ac834b6d803e7a6c07c3b71bff0e534614f/LablGlut/examples/glut3.7/test/test17.ml | ocaml | This program is freely distributable without licensing fees
and is provided without guarantee or warrantee expressed or
implied. This program is -not- in the public domain.
Test for GLUT 3.0's overlay functionality.
strange: this never gets set to true... -ijt
raises exception if overlay is not in use:
Small torture test. | #!/usr/bin/env lablglut
Ported to lablglut by Issac Trotts on Sun Aug 11 14:55:37 MDT 2002 .
open Printf
Copyright ( c ) .
let transP = ref 0
let main_win = ref 0
let x = ref 0.0 and y = ref 0.0
let render_normal () =
Glut.useLayer(Glut.NORMAL);
GlClear.clear [`color];
GlDraw.color (0.0,0.0,1.0);
GlDraw.begins `polygon;
GlDraw.vertex ~x:0.2 ~y:0.28 ();
GlDraw.vertex ~x:0.5 ~y:0.58 ();
GlDraw.vertex ~x:0.2 ~y:0.58 ();
GlDraw.ends();
Gl.flush();
;;
let render_overlay () =
GlClear.clear [`color];
GlDraw.begins `polygon;
GlDraw.vertex ~x:(0.2 +. !x) ~y:(0.2 +. !y) ();
GlDraw.vertex ~x:(0.5 +. !x) ~y:(0.5 +. !y) ();
GlDraw.vertex ~x:(0.2 +. !x) ~y:(0.5 +. !y) ();
GlDraw.ends();
Gl.flush();
;;
let render () =
Glut.useLayer(Glut.NORMAL);
render_normal();
if (Glut.layerGet(Glut.HAS_OVERLAY)) then begin
Glut.useLayer(Glut.OVERLAY);
render_overlay();
end
;;
let render_sub () =
printf("render_sub\n");
Glut.useLayer(Glut.NORMAL);
render_normal();
if (Glut.layerGet(Glut.HAS_OVERLAY)) then begin
Glut.useLayer(Glut.OVERLAY);
render_overlay();
end
;;
let display_count = ref 0
let damage_expectation = ref false
let timer ~value =
if (value <> 777) then failwith("unexpected timer value");
damage_expectation := true;
Glut.showWindow();
;;
let rec time2 ~value =
if (value = 666) then begin
printf("PASS: test17\n");
exit(0);
end;
if (value <> 888) then failwith("bad value");
Glut.destroyWindow(!main_win);
Glut.timerFunc 500 time2 666;
;;
let move_on () =
incr display_count;
if (!display_count = 2) then begin
damage_expectation := true;
Glut.iconifyWindow();
Glut.timerFunc 500 timer 777;
end;
if !display_count = 4 then begin
printf "display_count = 4\n";
Glut.initDisplayMode ();
ignore(Glut.createSubWindow !main_win 10 10 150 150);
GlClear.color (0.5, 0.5, 0.5);
Glut.displayFunc(render_sub);
Glut.initDisplayMode ~index:true ();
Glut.establishOverlay();
Glut.copyColormap !main_win;
Glut.setColor ~cell:((!transP + 1) mod 2) ~red:0.0 ~green:1.0 ~blue:1.0;
Glut.removeOverlay();
Glut.establishOverlay();
Glut.copyColormap(!main_win);
Glut.copyColormap(!main_win);
Glut.setColor ~cell:((!transP + 1) mod 2) ~red:1.0 ~green:1.0 ~blue:1.0;
GlClear.index ((float_of_int !transP));
GlDraw.index (float_of_int ((!transP + 1) mod 2));
Glut.setWindow(!main_win);
Glut.removeOverlay();
Glut.timerFunc 500 time2 888;
end
;;
let display_normal() =
if (Glut.layerGet(Glut.NORMAL_DAMAGED) <> !damage_expectation) then
failwith(" normal damage not expected\n");
render_normal();
move_on();
;;
let display_overlay() =
if (Glut.layerGet(Glut.OVERLAY_DAMAGED) <> !damage_expectation) then
failwith(" overlay damage not expected\n");
render_overlay();
move_on();
;;
let display2() =
if Glut.layerGet(Glut.NORMAL_DAMAGED) then
failwith(" normal damage not expected\n");
if Glut.layerGet(Glut.OVERLAY_DAMAGED) then
failwith(" overlay damage not expected\n");
if (!been_here) then Glut.postOverlayRedisplay()
else begin
Glut.overlayDisplayFunc(display_overlay);
Glut.displayFunc(display_normal);
damage_expectation := true;
Glut.postOverlayRedisplay();
Glut.postRedisplay();
end
;;
let display() =
if not (Glut.layerGet(Glut.NORMAL_DAMAGED)) then
failwith(" normal damage expected\n");
if not (Glut.layerGet(Glut.OVERLAY_DAMAGED)) then
failwith(" overlay damage expected\n");
render();
Glut.displayFunc(display2);
Glut.postRedisplay();
;;
let main () =
ignore(Glut.init Sys.argv);
Glut.initWindowSize 300 300;
Glut.initDisplayMode ~index:true ();
if not (Glut.layerGet(Glut.OVERLAY_POSSIBLE)) then begin
printf "UNRESOLVED: need overlays for this test (your window system ";
printf "lacks overlays)\n";
exit(0);
end;
Glut.initDisplayMode ();
main_win := Glut.createWindow("test17");
if Glut.layerGetInUse() = Glut.OVERLAY then
failwith(" overlay should not be in use\n");
if Glut.layerGet(Glut.HAS_OVERLAY) then
failwith(" overlay should not exist\n");
if Glut.layerGetTransparentIndex() <> -1 then
failwith(" transparent pixel of normal plane should be -1\n");
if Glut.layerGet(Glut.NORMAL_DAMAGED) then
failwith(" no normal damage yet\n");
ignore(Glut.layerGet(Glut.OVERLAY_DAMAGED));
GlClear.color (0.0, 1.0, 0.0);
Glut.initDisplayMode ~index:true ();
Glut.establishOverlay();
Glut.removeOverlay();
Glut.establishOverlay();
Glut.establishOverlay();
Glut.showOverlay();
Glut.hideOverlay();
Glut.showOverlay();
Glut.removeOverlay();
Glut.removeOverlay();
Glut.establishOverlay();
if (Glut.get(Glut.WINDOW_RGBA) <> 0) then
failwith(" overlay should not be RGBA\n");
Glut.useLayer(Glut.NORMAL);
if not (Glut.get(Glut.WINDOW_RGBA) <> 0) then
failwith(" normal should be RGBA\n");
Glut.useLayer(Glut.OVERLAY);
if (Glut.get(Glut.WINDOW_RGBA) <> 0) then
failwith(" overlay should not be RGBA\n");
if (Glut.layerGetInUse() = Glut.NORMAL) then
failwith(" overlay should be in use\n");
if not (Glut.layerGet(Glut.HAS_OVERLAY)) then
failwith(" overlay should exist\n");
if (Glut.layerGetTransparentIndex() = -1) then
failwith(" transparent pixel should exist\n");
if Glut.layerGet(Glut.NORMAL_DAMAGED) then
failwith(" no normal damage yet\n");
if Glut.layerGet(Glut.OVERLAY_DAMAGED) then
failwith(" no overlay damage yet\n");
transP := Glut.layerGetTransparentIndex();
GlClear.index (float_of_int (Glut.layerGetTransparentIndex()));
Glut.setColor ((!transP + 1) mod 2) 1.0 0.0 1.0;
GlDraw.index (float_of_int ((!transP + 1) mod 2));
Glut.useLayer(Glut.NORMAL);
if (Glut.layerGetInUse() = Glut.OVERLAY) then
failwith(" overlay should not be in use\n");
Glut.displayFunc(display);
Glut.mainLoop();
;;
let _ = main();;
|
5a1597680ec2d276873d15d5f45edc84a25df991cd378041f142a43a23ec7b7c | falsetru/htdp | 23.3.3.scm | (define (g-fives-closed i)
(* 3 (expt 5 i)))
(define (seq-g-fives n)
(build-list n g-fives-closed))
(require rackunit)
(require rackunit/text-ui)
(define seq-g-fives-tests
(test-suite "Test for seq-g-fives"
(check-equal? (seq-g-fives 3) '(3 15 75))
))
(exit (run-tests seq-g-fives-tests))
| null | https://raw.githubusercontent.com/falsetru/htdp/4cdad3b999f19b89ff4fa7561839cbcbaad274df/23/23.3.3.scm | scheme | (define (g-fives-closed i)
(* 3 (expt 5 i)))
(define (seq-g-fives n)
(build-list n g-fives-closed))
(require rackunit)
(require rackunit/text-ui)
(define seq-g-fives-tests
(test-suite "Test for seq-g-fives"
(check-equal? (seq-g-fives 3) '(3 15 75))
))
(exit (run-tests seq-g-fives-tests))
| |
76e8dc9e38cfe9fa162a3f6718fcfcd0c9cf7cc948e1fb664727b3192e707d94 | ocamllabs/opamfu | opamfuFormula.mli |
* Copyright ( c ) 2013 < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
*
* Copyright (c) 2013 David Sheets <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*)
(** Simplified boolean expression type *)
type 'a expr = Atom of 'a | And of 'a expr list | Or of 'a expr list
type version = OpamPackage.Version.t
type version_set = OpamPackage.Version.Set.t
type version_dnf = OpamFormula.version_constraint OpamFormula.dnf
type version_expr = OpamFormula.version_constraint expr option
type t = (OpamPackage.Name.t * version_expr) expr option
val eval : ('a -> bool) -> 'a expr option -> bool
* [ interpret and_op or_op atom_op zero t ] will interpret [ t ] with
the provided operators .
the provided operators.
*)
val interpret :
('z -> 'z -> 'z) -> ('z -> 'z -> 'z) -> ('x -> 'z) ->
'z -> ('x expr option) -> 'z
val map : ('a -> 'b) -> 'a expr -> 'b expr
val to_opam_formula : 'a expr option -> 'a OpamFormula.formula
val of_opam_formula : OpamFormula.t -> t
val dnf_of_expr : 'a expr option -> 'a expr option
val expr_of_version_dnf : version_dnf -> version_expr
val simplify_expr : 'a expr option -> 'a expr option
val simplify : t -> t
val compare : acompare:('a -> 'a -> int) -> 'a expr -> 'a expr -> int
val sort : ('a expr -> 'a expr -> int) -> 'a expr option -> 'a expr option
val sort_formula :
?ncompare:(OpamPackage.Name.t -> OpamPackage.Name.t -> int) ->
?vcompare:(OpamPackage.Version.t -> OpamPackage.Version.t -> int) ->
t -> t
val max_depth : t -> int
val count_width : ('a -> int) -> int -> 'a expr -> int
val expr_width : 'a expr -> int
val width : t -> int
val filter_versions : version_expr -> version_set -> version_set
val extremum_of_version_constraint :
version_set -> OpamFormula.version_constraint -> version option
val dnf_of_version_subset : version_set -> version_set -> version_dnf
val could_satisfy : version_set OpamTypes.name_map -> t -> bool
| null | https://raw.githubusercontent.com/ocamllabs/opamfu/bfb9f24cd624f0889a26afb979a856e547344391/lib/opamfuFormula.mli | ocaml | * Simplified boolean expression type |
* Copyright ( c ) 2013 < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
*
* Copyright (c) 2013 David Sheets <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*)
type 'a expr = Atom of 'a | And of 'a expr list | Or of 'a expr list
type version = OpamPackage.Version.t
type version_set = OpamPackage.Version.Set.t
type version_dnf = OpamFormula.version_constraint OpamFormula.dnf
type version_expr = OpamFormula.version_constraint expr option
type t = (OpamPackage.Name.t * version_expr) expr option
val eval : ('a -> bool) -> 'a expr option -> bool
* [ interpret and_op or_op atom_op zero t ] will interpret [ t ] with
the provided operators .
the provided operators.
*)
val interpret :
('z -> 'z -> 'z) -> ('z -> 'z -> 'z) -> ('x -> 'z) ->
'z -> ('x expr option) -> 'z
val map : ('a -> 'b) -> 'a expr -> 'b expr
val to_opam_formula : 'a expr option -> 'a OpamFormula.formula
val of_opam_formula : OpamFormula.t -> t
val dnf_of_expr : 'a expr option -> 'a expr option
val expr_of_version_dnf : version_dnf -> version_expr
val simplify_expr : 'a expr option -> 'a expr option
val simplify : t -> t
val compare : acompare:('a -> 'a -> int) -> 'a expr -> 'a expr -> int
val sort : ('a expr -> 'a expr -> int) -> 'a expr option -> 'a expr option
val sort_formula :
?ncompare:(OpamPackage.Name.t -> OpamPackage.Name.t -> int) ->
?vcompare:(OpamPackage.Version.t -> OpamPackage.Version.t -> int) ->
t -> t
val max_depth : t -> int
val count_width : ('a -> int) -> int -> 'a expr -> int
val expr_width : 'a expr -> int
val width : t -> int
val filter_versions : version_expr -> version_set -> version_set
val extremum_of_version_constraint :
version_set -> OpamFormula.version_constraint -> version option
val dnf_of_version_subset : version_set -> version_set -> version_dnf
val could_satisfy : version_set OpamTypes.name_map -> t -> bool
|
65cfd1c7cd8ba462ac2b908bf490e6dcf5f075513e35fff2b91c16f1d685da37 | kosmikus/records-sop | Record.hs | {-# LANGUAGE ConstraintKinds #-}
# LANGUAGE CPP #
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE StandaloneDeriving #
{-# LANGUAGE TypeInType #-}
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE UndecidableInstances #
# OPTIONS_GHC -fno - warn - unticked - promoted - constructors #
# OPTIONS_GHC -fno - warn - redundant - constraints #
module Generics.SOP.Record
( -- * A suitable representation for single-constructor records
FieldLabel
, RecordCode
, Record
, RecordRep
-- * Computing the record code
, RecordCodeOf
, IsRecord
, ValidRecordCode
, ExtractTypesFromRecordCode
, ExtractLabelsFromRecordCode
, RecombineRecordCode
-- * Conversion between a type and its record representation.
, toRecord
, fromRecord
-- * Utilities
, P(..)
, Snd
)
where
import Control.DeepSeq
import Generics.SOP.BasicFunctors
import Generics.SOP.NP
import Generics.SOP.NS
import Generics.SOP.Universe
import Generics.SOP.Sing
import Generics.SOP.Type.Metadata
import qualified GHC.Generics as GHC
import GHC.TypeLits
import GHC.Types
import Unsafe.Coerce
--------------------------------------------------------------------------
-- A suitable representation for single-constructor records.
--------------------------------------------------------------------------
-- | On the type-level, we represent fiel labels using symbols.
type FieldLabel = Symbol
| The record code deviates from the normal SOP code in two
-- ways:
--
- There is only one list , because we require that there is
-- only a single constructor.
--
-- - In addition to the types of the fields, we store the labels
-- of the fields.
--
type RecordCode = [(FieldLabel, Type)]
-- | The record representation of a type is a record indexed
-- by the record code.
--
type RecordRep (a :: Type) = Record (RecordCodeOf a)
-- | The representation of a record is just a product indexed by
-- a record code, containing elements of the types indicated
-- by the code.
--
-- Note that the representation is deliberately chosen such that
-- it has the same run-time representation as the product part
of the normal SOP representation .
--
type Record (r :: RecordCode) = NP P r
--------------------------------------------------------------------------
-- Computing the record code
--------------------------------------------------------------------------
-- | This type-level function takes the type-level metadata provided
-- by generics-sop as well as the normal generics-sop code, and transforms
-- them into the record code.
--
-- Arguably, the record code is more usable than the representation
-- directly on offer by generics-sop. So it's worth asking whether
-- this representation should be included in generics-sop ...
--
-- The function will only reduce if the argument type actually is a
record , meaning it must have exactly one constructor , and that
-- constructor must have field labels attached to it.
--
type RecordCodeOf a = ToRecordCode_Datatype a (DatatypeInfoOf a) (Code a)
-- | Helper for 'RecordCodeOf', handling the datatype level. Both
-- datatypes and newtypes are acceptable. Newtypes are just handled
as one - constructor datatypes for this purpose .
--
type family
ToRecordCode_Datatype (a :: Type) (d :: DatatypeInfo) (c :: [[Type]]) :: RecordCode where
#if MIN_VERSION_generics_sop(0,5,0)
ToRecordCode_Datatype a (ADT _ _ cis _) c = ToRecordCode_Constructor a cis c
#else
ToRecordCode_Datatype a (ADT _ _ cis) c = ToRecordCode_Constructor a cis c
#endif
ToRecordCode_Datatype a (Newtype _ _ ci) c = ToRecordCode_Constructor a '[ ci ] c
-- | Helper for 'RecordCodeOf', handling the constructor level. Only
-- single-constructor types are acceptable, and the constructor must
-- contain field labels.
--
-- As an exception, we accept an empty record, even though it does
-- not explicitly define any field labels.
--
type family
ToRecordCode_Constructor (a :: Type) (cis :: [ConstructorInfo]) (c :: [[Type]]) :: RecordCode where
ToRecordCode_Constructor a '[ 'Record _ fis ] '[ ts ] = ToRecordCode_Field fis ts
ToRecordCode_Constructor a '[ 'Constructor _ ] '[ '[] ] = '[]
ToRecordCode_Constructor a '[] _ =
TypeError
( Text "The type `" :<>: ShowType a :<>: Text "' is not a record type."
:$$: Text "It has no constructors."
)
ToRecordCode_Constructor a ( _ : _ : _ ) _ =
TypeError
( Text "The type `" :<>: ShowType a :<>: Text "' is not a record type."
:$$: Text "It has more than one constructor."
)
ToRecordCode_Constructor a '[ _ ] _ =
TypeError
( Text "The type `" :<>: ShowType a :<>: Text "' is not a record type."
:$$: Text "It has no labelled fields."
)
-- | Helper for 'RecordCodeOf', handling the field level. At this point,
-- we simply zip the list of field names and the list of types.
--
type family ToRecordCode_Field (fis :: [FieldInfo]) (c :: [Type]) :: RecordCode where
ToRecordCode_Field '[] '[] = '[]
ToRecordCode_Field ( 'FieldInfo l : fis ) ( t : ts ) = '(l, t) : ToRecordCode_Field fis ts
-- * Relating the record code and the original code.
| The constraint @IsRecord a r@ states that the type ' a ' is a record type
( i.e. , has exactly one constructor and field labels ) and that ' r ' is the
-- record code associated with 'a'.
--
type IsRecord (a :: Type) (r :: RecordCode) =
IsRecord' a r (GetSingleton (Code a))
| The constraint @IsRecord ' a r xs@ states that ' a ' is a record type
-- with record code 'r', and that the types contained in 'r' correspond
-- to the list 'xs'.
--
-- If the record code computation is correct, then the record code of a
-- type is strongly related to the original generics-sop code. Extracting
-- the types out of 'r' should correspond to 'xs'. Recombining the
-- labels from 'r' with 'xs' should yield 'r' exactly. These sanity
-- properties are captured by 'ValidRecordCode'.
--
type IsRecord' (a :: Type) (r :: RecordCode) (xs :: [Type]) =
( Generic a, Code a ~ '[ xs ]
, RecordCodeOf a ~ r, ValidRecordCode r xs
)
-- | Relates a recordcode 'r' and a list of types 'xs', stating that
-- 'xs' is indeed the list of types contained in 'r'.
--
type ValidRecordCode (r :: RecordCode) (xs :: [Type]) =
( ExtractTypesFromRecordCode r ~ xs
, RecombineRecordCode (ExtractLabelsFromRecordCode r) xs ~ r
)
-- | Extracts all the types from a record code.
type family ExtractTypesFromRecordCode (r :: RecordCode) :: [Type] where
ExtractTypesFromRecordCode '[] = '[]
ExtractTypesFromRecordCode ( '(_, a) : r ) = a : ExtractTypesFromRecordCode r
-- | Extracts all the field labels from a record code.
type family ExtractLabelsFromRecordCode (r :: RecordCode) :: [FieldLabel] where
ExtractLabelsFromRecordCode '[] = '[]
ExtractLabelsFromRecordCode ( '(l, _) : r ) = l : ExtractLabelsFromRecordCode r
-- | Given a list of labels and types, recombines them into a record code.
--
-- An important aspect of this function is that it is defined by induction
-- on the list of types, and forces the list of field labels to be at least
-- as long.
--
type family RecombineRecordCode (ls :: [FieldLabel]) (ts :: [Type]) :: RecordCode where
RecombineRecordCode _ '[] = '[]
RecombineRecordCode ls (t : ts) = '(Head ls, t) : RecombineRecordCode (Tail ls) ts
--------------------------------------------------------------------------
-- Conversion between a type and its record representation.
--------------------------------------------------------------------------
-- | Convert a value into its record representation.
toRecord :: (IsRecord a _r) => a -> RecordRep a
toRecord = unsafeToRecord_NP . unZ . unSOP . from
-- | Convert an n-ary product into the corresponding record
-- representation. This is a no-op, and more efficiently
-- implented using 'unsafeToRecord_NP'. It is included here
-- to demonstrate that it actually is type-correct and also
-- to make it more obvious that it is indeed a no-op.
--
_toRecord_NP :: (ValidRecordCode r xs) => NP I xs -> Record r
_toRecord_NP Nil = Nil
_toRecord_NP (I x :* xs) = P x :* _toRecord_NP xs
-- | Fast version of 'toRecord_NP'. Not actually unsafe as
long as the internal representations of ' NP ' and ' Record '
-- are not changed.
--
unsafeToRecord_NP :: (ValidRecordCode r xs) => NP I xs -> Record r
unsafeToRecord_NP = unsafeCoerce
-- | Convert a record representation back into a value.
fromRecord :: forall a r . (IsRecord a r) => RecordRep a -> a
fromRecord = fromRecord'
where
extra type signature should not be necessary , see GHC # 21515
fromRecord' = to . SOP . Z . unsafeFromRecord_NP
-- | Convert a record representation into an n-ary product. This is a no-op,
-- and more efficiently implemented using 'unsafeFromRecord_NP'.
--
-- It is also noteworthy that we let the resulting list drive the computation.
This is compatible with the definition of based on
-- the list of types.
--
_fromRecord_NP :: forall r xs . (ValidRecordCode r xs, SListI xs) => Record r -> NP I xs
_fromRecord_NP = case sList :: SList xs of
SNil -> const Nil
SCons -> \ r -> case r of
P x :* xs -> I x :* _fromRecord_NP xs
-- | Fast version of 'fromRecord_NP'. Not actually unsafe as
long as the internal representation of ' NP ' and ' Record '
-- are not changed.
--
unsafeFromRecord_NP :: forall r xs . (ValidRecordCode r xs, SListI xs) => Record r -> NP I xs
unsafeFromRecord_NP = unsafeCoerce
--------------------------------------------------------------------------
Utilities
--------------------------------------------------------------------------
| Projection of the second component of a type - level pair ,
-- wrapped in a newtype.
--
newtype P (p :: (a, Type)) = P (Snd p)
deriving (GHC.Generic)
deriving instance Eq a => Eq (P '(l, a))
deriving instance Ord a => Ord (P '(l, a))
deriving instance Show a => Show (P '(l, a))
instance NFData a => NFData (P '(l, a)) where
rnf (P x) = rnf x
| Type - level variant of ' snd ' .
type family Snd (p :: (a, b)) :: b where
Snd '(a, b) = b
-- | Type-level variant of 'head'.
type family Head (xs :: [k]) :: k where
Head (x : xs) = x
-- | Type-level variant of 'tail'.
type family Tail (xs :: [k]) :: [k] where
Tail (x : xs) = xs
-- | Partial type-level function that extracts the only element
-- from a singleton type-level list.
--
type family GetSingleton (xs :: [k]) :: k where
GetSingleton '[ x ] = x
| null | https://raw.githubusercontent.com/kosmikus/records-sop/ef368fb9b402b4726ba642227bb8ca3f7da9da35/src/Generics/SOP/Record.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE TypeInType #
* A suitable representation for single-constructor records
* Computing the record code
* Conversion between a type and its record representation.
* Utilities
------------------------------------------------------------------------
A suitable representation for single-constructor records.
------------------------------------------------------------------------
| On the type-level, we represent fiel labels using symbols.
ways:
only a single constructor.
- In addition to the types of the fields, we store the labels
of the fields.
| The record representation of a type is a record indexed
by the record code.
| The representation of a record is just a product indexed by
a record code, containing elements of the types indicated
by the code.
Note that the representation is deliberately chosen such that
it has the same run-time representation as the product part
------------------------------------------------------------------------
Computing the record code
------------------------------------------------------------------------
| This type-level function takes the type-level metadata provided
by generics-sop as well as the normal generics-sop code, and transforms
them into the record code.
Arguably, the record code is more usable than the representation
directly on offer by generics-sop. So it's worth asking whether
this representation should be included in generics-sop ...
The function will only reduce if the argument type actually is a
constructor must have field labels attached to it.
| Helper for 'RecordCodeOf', handling the datatype level. Both
datatypes and newtypes are acceptable. Newtypes are just handled
| Helper for 'RecordCodeOf', handling the constructor level. Only
single-constructor types are acceptable, and the constructor must
contain field labels.
As an exception, we accept an empty record, even though it does
not explicitly define any field labels.
| Helper for 'RecordCodeOf', handling the field level. At this point,
we simply zip the list of field names and the list of types.
* Relating the record code and the original code.
record code associated with 'a'.
with record code 'r', and that the types contained in 'r' correspond
to the list 'xs'.
If the record code computation is correct, then the record code of a
type is strongly related to the original generics-sop code. Extracting
the types out of 'r' should correspond to 'xs'. Recombining the
labels from 'r' with 'xs' should yield 'r' exactly. These sanity
properties are captured by 'ValidRecordCode'.
| Relates a recordcode 'r' and a list of types 'xs', stating that
'xs' is indeed the list of types contained in 'r'.
| Extracts all the types from a record code.
| Extracts all the field labels from a record code.
| Given a list of labels and types, recombines them into a record code.
An important aspect of this function is that it is defined by induction
on the list of types, and forces the list of field labels to be at least
as long.
------------------------------------------------------------------------
Conversion between a type and its record representation.
------------------------------------------------------------------------
| Convert a value into its record representation.
| Convert an n-ary product into the corresponding record
representation. This is a no-op, and more efficiently
implented using 'unsafeToRecord_NP'. It is included here
to demonstrate that it actually is type-correct and also
to make it more obvious that it is indeed a no-op.
| Fast version of 'toRecord_NP'. Not actually unsafe as
are not changed.
| Convert a record representation back into a value.
| Convert a record representation into an n-ary product. This is a no-op,
and more efficiently implemented using 'unsafeFromRecord_NP'.
It is also noteworthy that we let the resulting list drive the computation.
the list of types.
| Fast version of 'fromRecord_NP'. Not actually unsafe as
are not changed.
------------------------------------------------------------------------
------------------------------------------------------------------------
wrapped in a newtype.
| Type-level variant of 'head'.
| Type-level variant of 'tail'.
| Partial type-level function that extracts the only element
from a singleton type-level list.
| # LANGUAGE CPP #
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE UndecidableInstances #
# OPTIONS_GHC -fno - warn - unticked - promoted - constructors #
# OPTIONS_GHC -fno - warn - redundant - constraints #
module Generics.SOP.Record
FieldLabel
, RecordCode
, Record
, RecordRep
, RecordCodeOf
, IsRecord
, ValidRecordCode
, ExtractTypesFromRecordCode
, ExtractLabelsFromRecordCode
, RecombineRecordCode
, toRecord
, fromRecord
, P(..)
, Snd
)
where
import Control.DeepSeq
import Generics.SOP.BasicFunctors
import Generics.SOP.NP
import Generics.SOP.NS
import Generics.SOP.Universe
import Generics.SOP.Sing
import Generics.SOP.Type.Metadata
import qualified GHC.Generics as GHC
import GHC.TypeLits
import GHC.Types
import Unsafe.Coerce
type FieldLabel = Symbol
| The record code deviates from the normal SOP code in two
- There is only one list , because we require that there is
type RecordCode = [(FieldLabel, Type)]
type RecordRep (a :: Type) = Record (RecordCodeOf a)
of the normal SOP representation .
type Record (r :: RecordCode) = NP P r
record , meaning it must have exactly one constructor , and that
type RecordCodeOf a = ToRecordCode_Datatype a (DatatypeInfoOf a) (Code a)
as one - constructor datatypes for this purpose .
type family
ToRecordCode_Datatype (a :: Type) (d :: DatatypeInfo) (c :: [[Type]]) :: RecordCode where
#if MIN_VERSION_generics_sop(0,5,0)
ToRecordCode_Datatype a (ADT _ _ cis _) c = ToRecordCode_Constructor a cis c
#else
ToRecordCode_Datatype a (ADT _ _ cis) c = ToRecordCode_Constructor a cis c
#endif
ToRecordCode_Datatype a (Newtype _ _ ci) c = ToRecordCode_Constructor a '[ ci ] c
type family
ToRecordCode_Constructor (a :: Type) (cis :: [ConstructorInfo]) (c :: [[Type]]) :: RecordCode where
ToRecordCode_Constructor a '[ 'Record _ fis ] '[ ts ] = ToRecordCode_Field fis ts
ToRecordCode_Constructor a '[ 'Constructor _ ] '[ '[] ] = '[]
ToRecordCode_Constructor a '[] _ =
TypeError
( Text "The type `" :<>: ShowType a :<>: Text "' is not a record type."
:$$: Text "It has no constructors."
)
ToRecordCode_Constructor a ( _ : _ : _ ) _ =
TypeError
( Text "The type `" :<>: ShowType a :<>: Text "' is not a record type."
:$$: Text "It has more than one constructor."
)
ToRecordCode_Constructor a '[ _ ] _ =
TypeError
( Text "The type `" :<>: ShowType a :<>: Text "' is not a record type."
:$$: Text "It has no labelled fields."
)
type family ToRecordCode_Field (fis :: [FieldInfo]) (c :: [Type]) :: RecordCode where
ToRecordCode_Field '[] '[] = '[]
ToRecordCode_Field ( 'FieldInfo l : fis ) ( t : ts ) = '(l, t) : ToRecordCode_Field fis ts
| The constraint @IsRecord a r@ states that the type ' a ' is a record type
( i.e. , has exactly one constructor and field labels ) and that ' r ' is the
type IsRecord (a :: Type) (r :: RecordCode) =
IsRecord' a r (GetSingleton (Code a))
| The constraint @IsRecord ' a r xs@ states that ' a ' is a record type
type IsRecord' (a :: Type) (r :: RecordCode) (xs :: [Type]) =
( Generic a, Code a ~ '[ xs ]
, RecordCodeOf a ~ r, ValidRecordCode r xs
)
type ValidRecordCode (r :: RecordCode) (xs :: [Type]) =
( ExtractTypesFromRecordCode r ~ xs
, RecombineRecordCode (ExtractLabelsFromRecordCode r) xs ~ r
)
type family ExtractTypesFromRecordCode (r :: RecordCode) :: [Type] where
ExtractTypesFromRecordCode '[] = '[]
ExtractTypesFromRecordCode ( '(_, a) : r ) = a : ExtractTypesFromRecordCode r
type family ExtractLabelsFromRecordCode (r :: RecordCode) :: [FieldLabel] where
ExtractLabelsFromRecordCode '[] = '[]
ExtractLabelsFromRecordCode ( '(l, _) : r ) = l : ExtractLabelsFromRecordCode r
type family RecombineRecordCode (ls :: [FieldLabel]) (ts :: [Type]) :: RecordCode where
RecombineRecordCode _ '[] = '[]
RecombineRecordCode ls (t : ts) = '(Head ls, t) : RecombineRecordCode (Tail ls) ts
toRecord :: (IsRecord a _r) => a -> RecordRep a
toRecord = unsafeToRecord_NP . unZ . unSOP . from
_toRecord_NP :: (ValidRecordCode r xs) => NP I xs -> Record r
_toRecord_NP Nil = Nil
_toRecord_NP (I x :* xs) = P x :* _toRecord_NP xs
long as the internal representations of ' NP ' and ' Record '
unsafeToRecord_NP :: (ValidRecordCode r xs) => NP I xs -> Record r
unsafeToRecord_NP = unsafeCoerce
fromRecord :: forall a r . (IsRecord a r) => RecordRep a -> a
fromRecord = fromRecord'
where
extra type signature should not be necessary , see GHC # 21515
fromRecord' = to . SOP . Z . unsafeFromRecord_NP
This is compatible with the definition of based on
_fromRecord_NP :: forall r xs . (ValidRecordCode r xs, SListI xs) => Record r -> NP I xs
_fromRecord_NP = case sList :: SList xs of
SNil -> const Nil
SCons -> \ r -> case r of
P x :* xs -> I x :* _fromRecord_NP xs
long as the internal representation of ' NP ' and ' Record '
unsafeFromRecord_NP :: forall r xs . (ValidRecordCode r xs, SListI xs) => Record r -> NP I xs
unsafeFromRecord_NP = unsafeCoerce
Utilities
| Projection of the second component of a type - level pair ,
newtype P (p :: (a, Type)) = P (Snd p)
deriving (GHC.Generic)
deriving instance Eq a => Eq (P '(l, a))
deriving instance Ord a => Ord (P '(l, a))
deriving instance Show a => Show (P '(l, a))
instance NFData a => NFData (P '(l, a)) where
rnf (P x) = rnf x
| Type - level variant of ' snd ' .
type family Snd (p :: (a, b)) :: b where
Snd '(a, b) = b
type family Head (xs :: [k]) :: k where
Head (x : xs) = x
type family Tail (xs :: [k]) :: [k] where
Tail (x : xs) = xs
type family GetSingleton (xs :: [k]) :: k where
GetSingleton '[ x ] = x
|
b9fd2e5569bff4bd039dcc45a4561a74eab4a9486c47b92a705d98e89d0fb4e9 | marick/specter-book-code | generalized.clj | (ns book-code.ch2.generalized
(:use midje.sweet commons.clojure.core))
Protocols
(defprotocol Navigator
(select* [this structure continuation]))
Generic support code
(defn navigation-worker [worker-kw selector-element]
(-> (find-protocol-impl Navigator selector-element)
(get worker-kw)))
(defn mkfn:worker-calling-continuation [worker-kw element continuation]
(let [worker (navigation-worker worker-kw element)]
(fn [structure]
(worker element structure continuation))))
(defn predict-computation [worker-kw selector final-action]
(reduce (fn [continuation element]
(mkfn:worker-calling-continuation worker-kw element continuation))
final-action
(reverse selector)))
Core functions
(defn select [selector structure]
((predict-computation :select* selector vector) structure))
;;; Implementations of different types of selector elements.
(extend-type clojure.lang.Keyword
Navigator
(select* [this structure continuation]
(continuation (get structure this))))
(extend-type clojure.lang.AFn
Navigator
(select* [this structure continuation]
(if (this structure)
(continuation structure)
nil)))
(deftype AllType [])
(def ALL (->AllType))
(extend-type AllType
Navigator
(select* [this structure continuation]
(into [] (mapcat continuation structure))))
;;; Tests
(fact "works the same for keywords"
(select [:a] nil) => [nil]
(select [:a] :something-random) => [nil]
(select [:a] {:a 1}) => [1]
(select [:a] {:not-a 1}) => [nil]
(select [:a] {}) => [nil]
(select [:a :b] {:a {:b 1}}) => [1]
(select [:a :b] {:a 1}) => [nil]
(select [:a :b] {:a {}}) => [nil])
(fact "works the same for predicates"
(select [odd?] 1) => [1]
(select [even?] 1) => nil
(select [integer? odd?] 1) => [1]
(select [integer? even?] 1) => nil
(select [integer? odd?] "hi") => nil)
(facts "combining keywords and predicates"
(select [:a map? :b] {:a 1}) => nil
(select [:a map? :b] {:a {:b 1}}) => [1]
(select [:a map? :b] {:a {}}) => [nil]
(select [map? :a] {:b 1}) => [nil]
(select [map? :a] 1) => nil)
(fact "the two forms normally return specifically vectors"
(select [:a :b] {:a {:b 1}}) => vector?
(select [odd?] 1) => vector?)
(facts "about ALL"
(fact "all by itself is a no-op"
(select [ALL] [1 2 3 4]) => [1 2 3 4])
(fact "Since ALL 'spreads' the elements, it can be used to flatten"
(select [ALL ALL] [ [1] [2 3] ])
=> [ 1 2 3 ]
(fact "... but it won't flatten deeper than the level of nesting"
(select [ALL ALL] [[0] [[1 2] 3]])
=> [ 0 [1 2] 3])
(fact "both nil and an empty vector are flattened into nothing"
(select [ALL ALL] [[1] nil [] [2]])
=> [ 1 2]))
(fact "ALL applies the rest of the selector to each element"
(select [ALL :a] [{:a 1} {:a 2} { }])
=> [1 2 nil ]
(select [ALL even?] [1 2 3 4])
=> [ 2 4]
(select [ALL :a even?] [{:a 1} {:a 2}])
=> [ 2 ])
(fact "ALL returns vectors"
(select [ALL] '(1 2 3)) => vector?
(select [ALL even?] [1 2 3]) => vector?))
| null | https://raw.githubusercontent.com/marick/specter-book-code/e416d4ce8164084057d36d29d89b17d114d1ab28/src/book_code/ch2/generalized.clj | clojure | Implementations of different types of selector elements.
Tests | (ns book-code.ch2.generalized
(:use midje.sweet commons.clojure.core))
Protocols
(defprotocol Navigator
(select* [this structure continuation]))
Generic support code
(defn navigation-worker [worker-kw selector-element]
(-> (find-protocol-impl Navigator selector-element)
(get worker-kw)))
(defn mkfn:worker-calling-continuation [worker-kw element continuation]
(let [worker (navigation-worker worker-kw element)]
(fn [structure]
(worker element structure continuation))))
(defn predict-computation [worker-kw selector final-action]
(reduce (fn [continuation element]
(mkfn:worker-calling-continuation worker-kw element continuation))
final-action
(reverse selector)))
Core functions
(defn select [selector structure]
((predict-computation :select* selector vector) structure))
(extend-type clojure.lang.Keyword
Navigator
(select* [this structure continuation]
(continuation (get structure this))))
(extend-type clojure.lang.AFn
Navigator
(select* [this structure continuation]
(if (this structure)
(continuation structure)
nil)))
(deftype AllType [])
(def ALL (->AllType))
(extend-type AllType
Navigator
(select* [this structure continuation]
(into [] (mapcat continuation structure))))
(fact "works the same for keywords"
(select [:a] nil) => [nil]
(select [:a] :something-random) => [nil]
(select [:a] {:a 1}) => [1]
(select [:a] {:not-a 1}) => [nil]
(select [:a] {}) => [nil]
(select [:a :b] {:a {:b 1}}) => [1]
(select [:a :b] {:a 1}) => [nil]
(select [:a :b] {:a {}}) => [nil])
(fact "works the same for predicates"
(select [odd?] 1) => [1]
(select [even?] 1) => nil
(select [integer? odd?] 1) => [1]
(select [integer? even?] 1) => nil
(select [integer? odd?] "hi") => nil)
(facts "combining keywords and predicates"
(select [:a map? :b] {:a 1}) => nil
(select [:a map? :b] {:a {:b 1}}) => [1]
(select [:a map? :b] {:a {}}) => [nil]
(select [map? :a] {:b 1}) => [nil]
(select [map? :a] 1) => nil)
(fact "the two forms normally return specifically vectors"
(select [:a :b] {:a {:b 1}}) => vector?
(select [odd?] 1) => vector?)
(facts "about ALL"
(fact "all by itself is a no-op"
(select [ALL] [1 2 3 4]) => [1 2 3 4])
(fact "Since ALL 'spreads' the elements, it can be used to flatten"
(select [ALL ALL] [ [1] [2 3] ])
=> [ 1 2 3 ]
(fact "... but it won't flatten deeper than the level of nesting"
(select [ALL ALL] [[0] [[1 2] 3]])
=> [ 0 [1 2] 3])
(fact "both nil and an empty vector are flattened into nothing"
(select [ALL ALL] [[1] nil [] [2]])
=> [ 1 2]))
(fact "ALL applies the rest of the selector to each element"
(select [ALL :a] [{:a 1} {:a 2} { }])
=> [1 2 nil ]
(select [ALL even?] [1 2 3 4])
=> [ 2 4]
(select [ALL :a even?] [{:a 1} {:a 2}])
=> [ 2 ])
(fact "ALL returns vectors"
(select [ALL] '(1 2 3)) => vector?
(select [ALL even?] [1 2 3]) => vector?))
|
7e08673ec71e09dd6b505b542f13e58693afb03ff5251047692842419512cda9 | IvanIvanov/fp2013 | list-to-number.scm | ; слепя две числа заедно
(define (glue-ints a b)
(+ (* a 10) b))
в началото на
Ако списъкът е само с 0ли , списък
; Може да бъде написано и с drop-while
(define (remove-leading-zeroes l)
(define (zero? n)
(= n 0))
(cond
( (null? l) (list) )
( (not (zero? (car l))) l )
(else (remove-leading-zeroes (cdr l)))))
(define (list-to-number l)
(define (list-to-number-iter l result)
(cond
( (null? l) result )
(else (list-to-number-iter (cdr l) (glue-ints result (car l))))))
(list-to-number-iter (remove-leading-zeroes l) 0)) | null | https://raw.githubusercontent.com/IvanIvanov/fp2013/2ac1bb1102cb65e0ecbfa8d2fb3ca69953ae4ecf/lab2-and-3/homework4/list-to-number.scm | scheme | слепя две числа заедно
Може да бъде написано и с drop-while | (define (glue-ints a b)
(+ (* a 10) b))
в началото на
Ако списъкът е само с 0ли , списък
(define (remove-leading-zeroes l)
(define (zero? n)
(= n 0))
(cond
( (null? l) (list) )
( (not (zero? (car l))) l )
(else (remove-leading-zeroes (cdr l)))))
(define (list-to-number l)
(define (list-to-number-iter l result)
(cond
( (null? l) result )
(else (list-to-number-iter (cdr l) (glue-ints result (car l))))))
(list-to-number-iter (remove-leading-zeroes l) 0)) |
91ff32ceaaf39fde33c1b26745a5dfe76fc9960c931813d78152f5d200251b46 | jozefg/nbe-for-mltt | check.mli | type env_entry =
Term of {term : Domain.t; tp : Domain.t}
| TopLevel of {term : Domain.t; tp : Domain.t}
type env = env_entry list
val env_to_sem_env : env -> Domain.env
type error =
Cannot_synth_term of Syntax.t
| Type_mismatch of Domain.t * Domain.t
| Expecting_universe of Domain.t
| Misc of string
val pp_error : error -> string
exception Type_error of error
val check : env:env -> size:int -> term:Syntax.t -> tp:Domain.t -> unit
val synth : env:env -> size:int -> term:Syntax.t -> Domain.t
val check_tp : env:env -> size:int -> term:Syntax.t -> unit
| null | https://raw.githubusercontent.com/jozefg/nbe-for-mltt/6e7e1985ee2aaab26d83380afaf9a8135cf6feb9/src/lib/check.mli | ocaml | type env_entry =
Term of {term : Domain.t; tp : Domain.t}
| TopLevel of {term : Domain.t; tp : Domain.t}
type env = env_entry list
val env_to_sem_env : env -> Domain.env
type error =
Cannot_synth_term of Syntax.t
| Type_mismatch of Domain.t * Domain.t
| Expecting_universe of Domain.t
| Misc of string
val pp_error : error -> string
exception Type_error of error
val check : env:env -> size:int -> term:Syntax.t -> tp:Domain.t -> unit
val synth : env:env -> size:int -> term:Syntax.t -> Domain.t
val check_tp : env:env -> size:int -> term:Syntax.t -> unit
| |
e25f6bffee066736f4153cd0f55deb3c297212e0d6ff94de1586c759d6c04575 | haskell-jp/makeMistakesToLearnHaskell | Ex03.hs | {-# OPTIONS_GHC -Wno-unused-imports #-}
module Education.MakeMistakesToLearnHaskell.Exercise.Ex03
( exercise3
) where
#include <imports/external.hs>
import Education.MakeMistakesToLearnHaskell.Exercise.Core
import Education.MakeMistakesToLearnHaskell.Exercise.Types
exercise3 :: Exercise
exercise3 = Exercise "3" $ runHaskellExercise diag3 $ Text.unlines
[ "# # ####### # # #####"
, "# # # # # # #"
, "# # # # # # #"
, "####### ##### # # # #"
, "# # # # # # #"
, "# # # # # # #"
, "# # ####### ####### ####### #####"
]
diag3 :: Diagnosis
diag3 code msg
| code `isInconsistentlyIndentedAfter` "do" = detailsDoConsistentWidth
| "parse error on input" `Text.isInfixOf` msg
&& "'" `Text.isInfixOf` code =
"HINT: In Haskell, you must surround string literals with double-quotes '\"', like \"Hello, world\"."
| ("parse error" `Text.isInfixOf` msg || "Parse error" `Text.isInfixOf` msg)
&& "top-level declaration expected." `Text.isInfixOf` msg =
"HINT: This error indicates that you haven't defined the main function."
| "Variable not in scope: main :: IO" `Text.isInfixOf` msg =
"HINT: This error indicates that you haven't defined the main function."
| "Variable not in scope:" `Text.isInfixOf` msg =
"HINT: you might have misspelled 'putStrLn'."
| "Couldn't match expected type ‘(String -> IO ())" `Text.isInfixOf` msg =
detailsForgetToWriteDo "`putStrLn`s"
| otherwise = ""
| null | https://raw.githubusercontent.com/haskell-jp/makeMistakesToLearnHaskell/554e74ce09372d8b4c3c2d1158b9ca0784f2b571/src/Education/MakeMistakesToLearnHaskell/Exercise/Ex03.hs | haskell | # OPTIONS_GHC -Wno-unused-imports # |
module Education.MakeMistakesToLearnHaskell.Exercise.Ex03
( exercise3
) where
#include <imports/external.hs>
import Education.MakeMistakesToLearnHaskell.Exercise.Core
import Education.MakeMistakesToLearnHaskell.Exercise.Types
exercise3 :: Exercise
exercise3 = Exercise "3" $ runHaskellExercise diag3 $ Text.unlines
[ "# # ####### # # #####"
, "# # # # # # #"
, "# # # # # # #"
, "####### ##### # # # #"
, "# # # # # # #"
, "# # # # # # #"
, "# # ####### ####### ####### #####"
]
diag3 :: Diagnosis
diag3 code msg
| code `isInconsistentlyIndentedAfter` "do" = detailsDoConsistentWidth
| "parse error on input" `Text.isInfixOf` msg
&& "'" `Text.isInfixOf` code =
"HINT: In Haskell, you must surround string literals with double-quotes '\"', like \"Hello, world\"."
| ("parse error" `Text.isInfixOf` msg || "Parse error" `Text.isInfixOf` msg)
&& "top-level declaration expected." `Text.isInfixOf` msg =
"HINT: This error indicates that you haven't defined the main function."
| "Variable not in scope: main :: IO" `Text.isInfixOf` msg =
"HINT: This error indicates that you haven't defined the main function."
| "Variable not in scope:" `Text.isInfixOf` msg =
"HINT: you might have misspelled 'putStrLn'."
| "Couldn't match expected type ‘(String -> IO ())" `Text.isInfixOf` msg =
detailsForgetToWriteDo "`putStrLn`s"
| otherwise = ""
|
7bb0ff0210c2f81c24faa192756a29785af8ddb5913268f1730b9aa855ebff76 | tvraman/aster-math | new-document-objects.lisp | ;;; -*- Mode: LISP -*- ;;;
(in-package :aster)
;;{{{ mbox
;;; mbox should be handled differently from ordinary text blocks.
;;; This is because they way tex works, new blocks inherit from the
sorrounding environment , whereas mbox introduced a new
;;; environment. The earlier simple approach of handling mbox like
;;; any other block will therefore cause problems
(define-text-object :macro-name "mbox"
:number-args 1
:processing-function mbox-expand
:object-name text-box
:supers (document)
)
;;}}}
;;{{{fbox
;;; For the present treating fbox like mbox, will change reading rule
;;; later to add some bells and whistles.
(define-text-object :macro-name "fbox"
:number-args 1
:processing-function fbox-expand
:object-name text-frame-box
:supers (text-box)
)
;;}}}
;;{{{sqrt Not handle optional latex argument
(define-text-object :macro-name "sqrt"
:number-args 1
:processing-function sqrt-expand
:children-are-called 'radical
:precedence mathematical-function
:object-name square-root
:supers (math-object))
;;}}}
;;{{{ integral delimiter as a macro
(define-text-object :macro-name "varint"
:number-args 1
:processing-function d-expand
:object-name integral-delimiter
:supers (integral-d))
;;}}}
{ { { \ie
(define-text-object :macro-name "ie"
:number-args 0
:processing-function ie-expand
:object-name ie
:supers (document))
;;}}}
{ { { overbrace , underbrace etc .
;;{{{overbrace
(define-text-object :macro-name "overbrace"
:number-args 1
:processing-function overbrace-expand
:object-name overbrace
:supers (math-object))
;;}}}
;;{{{overline
(define-text-object :macro-name "overline"
:number-args 1
:processing-function overline-expand
:object-name overline
:supers (math-object))
(define-reading-state 'overline
#'(lambda(state)
(afl:multi-move-to state
' ( afl : left - volume 50 )
;'(afl:right-volume 0)
)
))
;;}}}
;;{{{underbrace
(define-text-object :macro-name "underbrace"
:number-args 1
:processing-function underbrace-expand
:object-name underbrace
:supers (math-object))
;;}}}
;;{{{underline
(define-text-object :macro-name "underline"
:number-args 1
:processing-function underline-expand
:object-name underline
:supers (math-object))
;;}}}
;;}}}
;;{{{hspace
(define-text-object :macro-name "hspace"
:number-args 1
:processing-function hspace-expand
:object-name h-space
:supers (document))
;;}}}
(define-text-object :macro-name "tex"
:number-args 0
:processing-function tex-logo-expand
:precedence nil
:object-name tex-logo
:supers (document))
(define-text-object :macro-name "subgroup"
:number-args 0
:processing-function subgroup-expand
:precedence relational-operator
:object-name sub-group
:supers (binary-operator))
(define-text-object :macro-name "divides"
:number-args 2
:processing-function divides-expand
:precedence nil
:object-name divides
:children-are-called (list "divisor" "dividend")
:supers (math-object))
(define-text-object :macro-name "nonumber"
:number-args 0
:processing-function nonumber-expand
:precedence nil
:object-name no-number
:supers (document))
(define-text-object :macro-name "phantom"
:number-args 1
:processing-function phantom-expand
:precedence nil
:object-name phantom
:supers (ordinary))
(define-text-object :macro-name "vphantom"
:number-args 1
:processing-function vphantom-expand
:precedence nil
:object-name v-phantom
:supers (ordinary))
(define-text-object :macro-name "induction"
:number-args 2
:processing-function induction-expand
:precedence nil
:object-name induction
:supers (math-object)
:children-are-called nil)
(define-text-object :macro-name "contentsline"
:number-args 3
:processing-function contentsline-expand
:precedence nil
:object-name contents-line
:supers (document)
:children-are-called nil)
(define-text-object :macro-name "numberline"
:number-args 1
:processing-function numberline-expand
:precedence nil
:object-name number-line
:supers (document)
:children-are-called nil)
(define-text-object :macro-name "pagenumbering"
:number-args 1
:processing-function pagenumbering-expand
:precedence nil
:object-name pagenumbering
:supers (document)
:children-are-called nil)
(define-text-object :macro-name "ddots"
:number-args 0
:processing-function ddots-expand
:precedence nil
:object-name diagonal-dots
:supers (ordinary)
:children-are-called nil)
(define-text-object :macro-name "vdots"
:number-args 0
:processing-function v-dots-expand
:precedence nil
:object-name vertical-dots
:supers (ordinary)
:children-are-called nil)
(define-text-object :macro-name "setlength"
:number-args 2
:processing-function setlength-expand
:precedence nil
:object-name setlength
:supers (document)
:children-are-called nil)
(define-text-object :macro-name "caption"
:number-args 1
:processing-function caption-expand
:precedence nil
:object-name caption
:supers (document)
:children-are-called nil)
;;{{{latex2e objects
(define-text-object :macro-name "emph"
:number-args 1
:processing-function emph-expand
:precedence nil
:object-name emph
:supers (document)
:children-are-called nil
)
(define-text-object :macro-name "texttt"
:number-args 1
:processing-function texttt-expand
:precedence nil
:object-name texttt
:supers (document)
:children-are-called nil)
(define-text-object :macro-name "textsf"
:number-args 1
:processing-function textsf-expand
:precedence nil
:object-name textsf
:supers (document)
:children-are-called nil)
(define-text-object :macro-name "textit"
:number-args 1
:processing-function textit-expand
:precedence nil
:object-name textit
:supers (document)
:children-are-called nil)
(define-text-object :macro-name "href"
:number-args 2
:processing-function href-expand
:precedence nil
:object-name href
:supers (document)
:children-are-called '(url text))
(define-text-object :macro-name "textbf"
:number-args 1
:processing-function textbf-expand
:precedence nil
:object-name textbf
:supers (document)
:children-are-called nil)
(define-text-object :macro-name "mathrm"
:number-args 1
:processing-function mathrm-expand
:precedence nil
:object-name mathrm
:supers (math-object)
:children-are-called 'variable)
;;}}}
| null | https://raw.githubusercontent.com/tvraman/aster-math/1023f636b80aeb971ec60a1201daab2ea2d175aa/lisp/read-aloud/new-document-objects.lisp | lisp | -*- Mode: LISP -*- ;;;
{{{ mbox
mbox should be handled differently from ordinary text blocks.
This is because they way tex works, new blocks inherit from the
environment. The earlier simple approach of handling mbox like
any other block will therefore cause problems
}}}
{{{fbox
For the present treating fbox like mbox, will change reading rule
later to add some bells and whistles.
}}}
{{{sqrt Not handle optional latex argument
}}}
{{{ integral delimiter as a macro
}}}
}}}
{{{overbrace
}}}
{{{overline
'(afl:right-volume 0)
}}}
{{{underbrace
}}}
{{{underline
}}}
}}}
{{{hspace
}}}
{{{latex2e objects
}}} |
(in-package :aster)
sorrounding environment , whereas mbox introduced a new
(define-text-object :macro-name "mbox"
:number-args 1
:processing-function mbox-expand
:object-name text-box
:supers (document)
)
(define-text-object :macro-name "fbox"
:number-args 1
:processing-function fbox-expand
:object-name text-frame-box
:supers (text-box)
)
(define-text-object :macro-name "sqrt"
:number-args 1
:processing-function sqrt-expand
:children-are-called 'radical
:precedence mathematical-function
:object-name square-root
:supers (math-object))
(define-text-object :macro-name "varint"
:number-args 1
:processing-function d-expand
:object-name integral-delimiter
:supers (integral-d))
{ { { \ie
(define-text-object :macro-name "ie"
:number-args 0
:processing-function ie-expand
:object-name ie
:supers (document))
{ { { overbrace , underbrace etc .
(define-text-object :macro-name "overbrace"
:number-args 1
:processing-function overbrace-expand
:object-name overbrace
:supers (math-object))
(define-text-object :macro-name "overline"
:number-args 1
:processing-function overline-expand
:object-name overline
:supers (math-object))
(define-reading-state 'overline
#'(lambda(state)
(afl:multi-move-to state
' ( afl : left - volume 50 )
)
))
(define-text-object :macro-name "underbrace"
:number-args 1
:processing-function underbrace-expand
:object-name underbrace
:supers (math-object))
(define-text-object :macro-name "underline"
:number-args 1
:processing-function underline-expand
:object-name underline
:supers (math-object))
(define-text-object :macro-name "hspace"
:number-args 1
:processing-function hspace-expand
:object-name h-space
:supers (document))
(define-text-object :macro-name "tex"
:number-args 0
:processing-function tex-logo-expand
:precedence nil
:object-name tex-logo
:supers (document))
(define-text-object :macro-name "subgroup"
:number-args 0
:processing-function subgroup-expand
:precedence relational-operator
:object-name sub-group
:supers (binary-operator))
(define-text-object :macro-name "divides"
:number-args 2
:processing-function divides-expand
:precedence nil
:object-name divides
:children-are-called (list "divisor" "dividend")
:supers (math-object))
(define-text-object :macro-name "nonumber"
:number-args 0
:processing-function nonumber-expand
:precedence nil
:object-name no-number
:supers (document))
(define-text-object :macro-name "phantom"
:number-args 1
:processing-function phantom-expand
:precedence nil
:object-name phantom
:supers (ordinary))
(define-text-object :macro-name "vphantom"
:number-args 1
:processing-function vphantom-expand
:precedence nil
:object-name v-phantom
:supers (ordinary))
(define-text-object :macro-name "induction"
:number-args 2
:processing-function induction-expand
:precedence nil
:object-name induction
:supers (math-object)
:children-are-called nil)
(define-text-object :macro-name "contentsline"
:number-args 3
:processing-function contentsline-expand
:precedence nil
:object-name contents-line
:supers (document)
:children-are-called nil)
(define-text-object :macro-name "numberline"
:number-args 1
:processing-function numberline-expand
:precedence nil
:object-name number-line
:supers (document)
:children-are-called nil)
(define-text-object :macro-name "pagenumbering"
:number-args 1
:processing-function pagenumbering-expand
:precedence nil
:object-name pagenumbering
:supers (document)
:children-are-called nil)
(define-text-object :macro-name "ddots"
:number-args 0
:processing-function ddots-expand
:precedence nil
:object-name diagonal-dots
:supers (ordinary)
:children-are-called nil)
(define-text-object :macro-name "vdots"
:number-args 0
:processing-function v-dots-expand
:precedence nil
:object-name vertical-dots
:supers (ordinary)
:children-are-called nil)
(define-text-object :macro-name "setlength"
:number-args 2
:processing-function setlength-expand
:precedence nil
:object-name setlength
:supers (document)
:children-are-called nil)
(define-text-object :macro-name "caption"
:number-args 1
:processing-function caption-expand
:precedence nil
:object-name caption
:supers (document)
:children-are-called nil)
(define-text-object :macro-name "emph"
:number-args 1
:processing-function emph-expand
:precedence nil
:object-name emph
:supers (document)
:children-are-called nil
)
(define-text-object :macro-name "texttt"
:number-args 1
:processing-function texttt-expand
:precedence nil
:object-name texttt
:supers (document)
:children-are-called nil)
(define-text-object :macro-name "textsf"
:number-args 1
:processing-function textsf-expand
:precedence nil
:object-name textsf
:supers (document)
:children-are-called nil)
(define-text-object :macro-name "textit"
:number-args 1
:processing-function textit-expand
:precedence nil
:object-name textit
:supers (document)
:children-are-called nil)
(define-text-object :macro-name "href"
:number-args 2
:processing-function href-expand
:precedence nil
:object-name href
:supers (document)
:children-are-called '(url text))
(define-text-object :macro-name "textbf"
:number-args 1
:processing-function textbf-expand
:precedence nil
:object-name textbf
:supers (document)
:children-are-called nil)
(define-text-object :macro-name "mathrm"
:number-args 1
:processing-function mathrm-expand
:precedence nil
:object-name mathrm
:supers (math-object)
:children-are-called 'variable)
|
a1ef81d759536ddec7063e26fb4c557e79784a4df43e407b3bc6bbaf1dcaf4c2 | boris-ci/boris | Pin.hs | # LANGUAGE NoImplicitPrelude #
module Boris.Git.Pin (
Pin
, newPin
, checkPin
, waitForPin
, pullPin
) where
import Boris.Prelude
import Control.Concurrent.MVar
import System.IO
newtype Pin =
Pin { pin :: MVar () }
newPin :: IO Pin
newPin =
Pin <$> newEmptyMVar
checkPin :: Pin -> IO Bool
checkPin =
fmap isJust . tryTakeMVar . pin
waitForPin :: Pin -> IO ()
waitForPin =
void . readMVar . pin
pullPin :: Pin -> IO ()
pullPin =
void . flip tryPutMVar () . pin
| null | https://raw.githubusercontent.com/boris-ci/boris/c321187490afc889bf281442ac4ef9398b77b200/boris-git/src/Boris/Git/Pin.hs | haskell | # LANGUAGE NoImplicitPrelude #
module Boris.Git.Pin (
Pin
, newPin
, checkPin
, waitForPin
, pullPin
) where
import Boris.Prelude
import Control.Concurrent.MVar
import System.IO
newtype Pin =
Pin { pin :: MVar () }
newPin :: IO Pin
newPin =
Pin <$> newEmptyMVar
checkPin :: Pin -> IO Bool
checkPin =
fmap isJust . tryTakeMVar . pin
waitForPin :: Pin -> IO ()
waitForPin =
void . readMVar . pin
pullPin :: Pin -> IO ()
pullPin =
void . flip tryPutMVar () . pin
| |
a8b83fec53d0b1bfe20192ee049c8c0244c71a4010d5964c1c0af0ebb403d3a6 | basvandijk/nixtodo | IndexTemplater.hs | {-# language PackageImports #-}
{-# language OverloadedStrings #-}
module Nixtodo.Backend.IndexTemplater
( Config(..)
, parseConfig
, Handle
, getConfig
, with
, getHashed
, getClient
) where
import qualified "SHA" Data.Digest.Pure.SHA as SHA
import "base" Control.Concurrent.MVar (MVar, newMVar, withMVar)
import "base" Control.Monad (when)
import "base" Control.Monad.IO.Class (liftIO)
import "base" Data.Functor (void)
import "base" Data.Monoid ((<>))
import "base16-bytestring" Data.ByteString.Base16.Lazy as Base16L
import qualified "bytestring" Data.ByteString.Lazy as BL
import qualified "bytestring" Data.ByteString.Lazy.Char8 as BLC8
import qualified "configurator" Data.Configurator as C
import qualified "configurator" Data.Configurator.Types as C
import qualified "directory" System.Directory as Dir
import "filepath" System.FilePath ( (<.>), (</>) )
import qualified "filepath" System.FilePath as Fp
import qualified "fsnotify" System.FSNotify as FSNotify
import qualified "hastache" Text.Hastache as H
import qualified "hastache" Text.Hastache.Context as H
import qualified "http-types" Network.HTTP.Types.Status as Http
import "managed" Control.Monad.Managed.Safe ( Managed, managed )
import qualified "servant-server" Servant
import "tagged" Data.Tagged (Tagged(..))
import qualified "text" Data.Text as T
import qualified "text" Data.Text.Lazy.IO as TL
import qualified "unix" System.Posix.Files as Posix
import qualified "wai" Network.Wai as Wai
import "wai-app-static" Network.Wai.Application.Static ( StaticSettings, defaultFileServerSettings, staticApp, ssMaxAge )
import "wai-app-static" WaiAppStatic.Types ( MaxAge(MaxAgeForever) )
import qualified "zlib" Codec.Compression.GZip as Gz
data Config
= Config
{ cfgIndexTemplatePath :: !FilePath
, cfgSrcDir :: !FilePath
, cfgDstDir :: !FilePath
, cfgUrlPrefix :: !FilePath
, cfgCompressLevel :: !Int
}
parseConfig :: C.Config -> IO Config
parseConfig cfg = Config <$> C.require cfg "indexTemplatePath"
<*> C.require cfg "srcDir"
<*> C.require cfg "dstDir"
<*> C.require cfg "urlPrefix"
<*> C.require cfg "compressLevel"
data Handle
= Handle
{ hndlConfig :: !Config
, hndlLock :: !(MVar ())
}
getConfig :: Handle -> Config
getConfig = hndlConfig
with :: Config -> Managed Handle
with cfg = do
watchManager <- managed FSNotify.withManager
hndl <- liftIO initHndl
liftIO $ do
update hndl
void $ FSNotify.watchTree
watchManager
(cfgSrcDir cfg)
shouldHandleFsEvent
(\_ -> update hndl)
pure hndl
where
initHndl :: IO Handle
initHndl = do
lock <- newMVar ()
pure Handle
{ hndlConfig = cfg
, hndlLock = lock
}
shouldHandleFsEvent :: FSNotify.Event -> Bool
shouldHandleFsEvent FSNotify.Added{} = False
shouldHandleFsEvent FSNotify.Modified{} = True
shouldHandleFsEvent FSNotify.Removed{} = False
update :: Handle -> IO ()
update hndl = withMVar lock $ \_ -> do
currentExists <- Dir.doesDirectoryExist currentLinkFp
newRelative <- if currentExists
then otherThen <$> Posix.readSymbolicLink currentLinkFp
else pure "a"
let new = dstDir </> newRelative
newExists <- Dir.doesDirectoryExist new
when newExists $ Dir.removeDirectoryRecursive new
Dir.createDirectoryIfMissing True new
let muContext :: H.MuContext IO
muContext = H.mkStrContextM $ \fp -> do
let fullFp = cfgSrcDir cfg </> fp
bytes <- BL.readFile fullFp
let compressed = Gz.compressWith compressParams bytes
hash = sha256sum compressed
hashFpExt = hash <> "-" <> Fp.takeFileName fp
srcFp = new </> hashFpExt
srcFpGz = srcFp <.> "gz"
fullAbsFp <- Dir.makeAbsolute fullFp
Posix.createSymbolicLink fullAbsFp srcFp
BL.writeFile srcFpGz compressed
pure $ H.MuVariable $ cfgUrlPrefix cfg </> hashFpExt
indexTxt <- H.hastacheFile H.defaultConfig (cfgIndexTemplatePath cfg) muContext
TL.writeFile (new </> indexFp) indexTxt
newCurrentLinkExists <- Dir.doesDirectoryExist newCurrentLinkFp
when newCurrentLinkExists $ Posix.removeLink newCurrentLinkFp
Posix.createSymbolicLink newRelative newCurrentLinkFp
Dir.renameFile newCurrentLinkFp currentLinkFp
where
currentLinkFp, newCurrentLinkFp :: FilePath
currentLinkFp = dstDir </> currentFp
newCurrentLinkFp = currentLinkFp <.> "new"
otherThen :: FilePath -> FilePath
otherThen "a" = "b"
otherThen "b" = "a"
otherThen _ = error "Invalid current link!"
dstDir = cfgDstDir cfg
compressParams :: Gz.CompressParams
compressParams = Gz.defaultCompressParams
{ Gz.compressLevel = Gz.compressionLevel $ cfgCompressLevel cfg
, Gz.compressMemoryLevel = Gz.maxMemoryLevel
}
cfg = hndlConfig hndl
lock = hndlLock hndl
sha256sum :: BL.ByteString -> String
sha256sum = BLC8.unpack
. BL.take 10
. Base16L.encode
. SHA.bytestringDigest
. SHA.sha256
getHashed :: Handle -> Servant.Server Servant.Raw
getHashed hndl = Servant.Tagged $ staticApp staticSettings
where
staticSettings :: StaticSettings
staticSettings = (defaultFileServerSettings
(Fp.addTrailingPathSeparator
(cfgDstDir cfg </> currentFp)))
{ ssMaxAge = MaxAgeForever }
cfg = hndlConfig hndl
getClient :: Handle -> Servant.Server Servant.Raw
getClient hndl = Servant.Tagged $ requireEmptyPath $
\_req respond -> do
respond $ Wai.responseFile
Http.ok200
[ ("Cache-Control", "no-cache, no-store, must-revalidate")
, ("Expires", "0")
]
(cfgDstDir (hndlConfig hndl) </> currentFp </> indexFp)
Nothing
currentFp :: FilePath
currentFp = "current"
indexFp :: FilePath
indexFp = "index.html"
requireEmptyPath :: Wai.Middleware
requireEmptyPath application =
\req respond ->
case Wai.pathInfo req of
[] -> application req respond
_ -> respond $ Wai.responseLBS Http.notFound404 [] "not found"
| null | https://raw.githubusercontent.com/basvandijk/nixtodo/b22cc584208f74258a697e2a4143eb068af55aec/hs-pkgs/nixtodo-backend/src/Nixtodo/Backend/IndexTemplater.hs | haskell | # language PackageImports #
# language OverloadedStrings # |
module Nixtodo.Backend.IndexTemplater
( Config(..)
, parseConfig
, Handle
, getConfig
, with
, getHashed
, getClient
) where
import qualified "SHA" Data.Digest.Pure.SHA as SHA
import "base" Control.Concurrent.MVar (MVar, newMVar, withMVar)
import "base" Control.Monad (when)
import "base" Control.Monad.IO.Class (liftIO)
import "base" Data.Functor (void)
import "base" Data.Monoid ((<>))
import "base16-bytestring" Data.ByteString.Base16.Lazy as Base16L
import qualified "bytestring" Data.ByteString.Lazy as BL
import qualified "bytestring" Data.ByteString.Lazy.Char8 as BLC8
import qualified "configurator" Data.Configurator as C
import qualified "configurator" Data.Configurator.Types as C
import qualified "directory" System.Directory as Dir
import "filepath" System.FilePath ( (<.>), (</>) )
import qualified "filepath" System.FilePath as Fp
import qualified "fsnotify" System.FSNotify as FSNotify
import qualified "hastache" Text.Hastache as H
import qualified "hastache" Text.Hastache.Context as H
import qualified "http-types" Network.HTTP.Types.Status as Http
import "managed" Control.Monad.Managed.Safe ( Managed, managed )
import qualified "servant-server" Servant
import "tagged" Data.Tagged (Tagged(..))
import qualified "text" Data.Text as T
import qualified "text" Data.Text.Lazy.IO as TL
import qualified "unix" System.Posix.Files as Posix
import qualified "wai" Network.Wai as Wai
import "wai-app-static" Network.Wai.Application.Static ( StaticSettings, defaultFileServerSettings, staticApp, ssMaxAge )
import "wai-app-static" WaiAppStatic.Types ( MaxAge(MaxAgeForever) )
import qualified "zlib" Codec.Compression.GZip as Gz
data Config
= Config
{ cfgIndexTemplatePath :: !FilePath
, cfgSrcDir :: !FilePath
, cfgDstDir :: !FilePath
, cfgUrlPrefix :: !FilePath
, cfgCompressLevel :: !Int
}
parseConfig :: C.Config -> IO Config
parseConfig cfg = Config <$> C.require cfg "indexTemplatePath"
<*> C.require cfg "srcDir"
<*> C.require cfg "dstDir"
<*> C.require cfg "urlPrefix"
<*> C.require cfg "compressLevel"
data Handle
= Handle
{ hndlConfig :: !Config
, hndlLock :: !(MVar ())
}
getConfig :: Handle -> Config
getConfig = hndlConfig
with :: Config -> Managed Handle
with cfg = do
watchManager <- managed FSNotify.withManager
hndl <- liftIO initHndl
liftIO $ do
update hndl
void $ FSNotify.watchTree
watchManager
(cfgSrcDir cfg)
shouldHandleFsEvent
(\_ -> update hndl)
pure hndl
where
initHndl :: IO Handle
initHndl = do
lock <- newMVar ()
pure Handle
{ hndlConfig = cfg
, hndlLock = lock
}
shouldHandleFsEvent :: FSNotify.Event -> Bool
shouldHandleFsEvent FSNotify.Added{} = False
shouldHandleFsEvent FSNotify.Modified{} = True
shouldHandleFsEvent FSNotify.Removed{} = False
update :: Handle -> IO ()
update hndl = withMVar lock $ \_ -> do
currentExists <- Dir.doesDirectoryExist currentLinkFp
newRelative <- if currentExists
then otherThen <$> Posix.readSymbolicLink currentLinkFp
else pure "a"
let new = dstDir </> newRelative
newExists <- Dir.doesDirectoryExist new
when newExists $ Dir.removeDirectoryRecursive new
Dir.createDirectoryIfMissing True new
let muContext :: H.MuContext IO
muContext = H.mkStrContextM $ \fp -> do
let fullFp = cfgSrcDir cfg </> fp
bytes <- BL.readFile fullFp
let compressed = Gz.compressWith compressParams bytes
hash = sha256sum compressed
hashFpExt = hash <> "-" <> Fp.takeFileName fp
srcFp = new </> hashFpExt
srcFpGz = srcFp <.> "gz"
fullAbsFp <- Dir.makeAbsolute fullFp
Posix.createSymbolicLink fullAbsFp srcFp
BL.writeFile srcFpGz compressed
pure $ H.MuVariable $ cfgUrlPrefix cfg </> hashFpExt
indexTxt <- H.hastacheFile H.defaultConfig (cfgIndexTemplatePath cfg) muContext
TL.writeFile (new </> indexFp) indexTxt
newCurrentLinkExists <- Dir.doesDirectoryExist newCurrentLinkFp
when newCurrentLinkExists $ Posix.removeLink newCurrentLinkFp
Posix.createSymbolicLink newRelative newCurrentLinkFp
Dir.renameFile newCurrentLinkFp currentLinkFp
where
currentLinkFp, newCurrentLinkFp :: FilePath
currentLinkFp = dstDir </> currentFp
newCurrentLinkFp = currentLinkFp <.> "new"
otherThen :: FilePath -> FilePath
otherThen "a" = "b"
otherThen "b" = "a"
otherThen _ = error "Invalid current link!"
dstDir = cfgDstDir cfg
compressParams :: Gz.CompressParams
compressParams = Gz.defaultCompressParams
{ Gz.compressLevel = Gz.compressionLevel $ cfgCompressLevel cfg
, Gz.compressMemoryLevel = Gz.maxMemoryLevel
}
cfg = hndlConfig hndl
lock = hndlLock hndl
sha256sum :: BL.ByteString -> String
sha256sum = BLC8.unpack
. BL.take 10
. Base16L.encode
. SHA.bytestringDigest
. SHA.sha256
getHashed :: Handle -> Servant.Server Servant.Raw
getHashed hndl = Servant.Tagged $ staticApp staticSettings
where
staticSettings :: StaticSettings
staticSettings = (defaultFileServerSettings
(Fp.addTrailingPathSeparator
(cfgDstDir cfg </> currentFp)))
{ ssMaxAge = MaxAgeForever }
cfg = hndlConfig hndl
getClient :: Handle -> Servant.Server Servant.Raw
getClient hndl = Servant.Tagged $ requireEmptyPath $
\_req respond -> do
respond $ Wai.responseFile
Http.ok200
[ ("Cache-Control", "no-cache, no-store, must-revalidate")
, ("Expires", "0")
]
(cfgDstDir (hndlConfig hndl) </> currentFp </> indexFp)
Nothing
currentFp :: FilePath
currentFp = "current"
indexFp :: FilePath
indexFp = "index.html"
requireEmptyPath :: Wai.Middleware
requireEmptyPath application =
\req respond ->
case Wai.pathInfo req of
[] -> application req respond
_ -> respond $ Wai.responseLBS Http.notFound404 [] "not found"
|
d955f074727ea8a334b73c8d76a6a07389244d711c16c4c38eac38f815ae8c5e | NetComposer/nksip | core_test_client2.erl | -module(core_test_client2).
Include nkserver macros
%% -include_lib("nkserver/include/nkserver_module.hrl").
-include_lib("eunit/include/eunit.hrl").
-include_lib("nksip/include/nksip.hrl").
-include_lib("nkserver/include/nkserver_module.hrl").
-export([config/1]).
-export([sip_get_user_pass/4, sip_invite/2, sip_reinvite/2, sip_cancel/3, sip_bye/2,
sip_info/2, sip_ack/2, sip_options/2, sip_dialog_update/3, sip_session_update/3]).
config(Opts) ->
Opts#{
sip_from => "\"NkSIP Basic SUITE Test Client\" <sip:core_test_client2@nksip>",
sip_local_host => "127.0.0.1",
sip_route => "<sip:127.0.0.1;lr>"
}.
sip_get_user_pass(_User, _Realm, _Req, _Call) ->
true.
sip_invite(Req, _Call) ->
send_reply(Req, invite),
case nksip_sipmsg:header(<<"x-nk-op">>, Req) of
[<<"wait">>] ->
{ok, ReqId} = nksip_request:get_handle(Req),
lager:error("Next error about a looped_process is expected"),
{error, looped_process} = nksip_request:reply(ringing, ReqId),
spawn(
fun() ->
nksip_request:reply(ringing, ReqId),
timer:sleep(1000),
nksip_request:reply(ok, ReqId)
end),
noreply;
_ ->
{reply, {answer, nksip_sipmsg:get_meta(body, Req)}}
end.
sip_reinvite(Req, _Call) ->
send_reply(Req, reinvite),
{reply, {answer, nksip_sipmsg:get_meta(body, Req)}}.
sip_cancel(InvReq, Req, _Call) ->
{ok, 'INVITE'} = nksip_request:method(InvReq),
send_reply(Req, cancel),
ok.
sip_bye(Req, _Call) ->
send_reply(Req, bye),
{reply, ok}.
sip_info(Req, _Call) ->
send_reply(Req, info),
{reply, ok}.
sip_ack(Req, _Call) ->
send_reply(Req, ack),
ok.
sip_options(Req, _Call) ->
send_reply(Req, options),
SrvId = nksip_sipmsg:get_meta(srv_id, Req),
Ids = nksip_sipmsg:header(<<"x-nk-id">>, Req),
{ok, ReqId} = nksip_request:get_handle(Req),
Reply = {ok, [{add, "x-nk-id", [nklib_util:to_binary(SrvId)|Ids]}]},
spawn(fun() -> nksip_request:reply(Reply, ReqId) end),
noreply.
sip_dialog_update(State, Dialog, _Call) ->
case State of
start -> send_reply(Dialog, dialog_start);
stop -> send_reply(Dialog, dialog_stop);
_ -> ok
end.
sip_session_update(State, Dialog, _Call) ->
case State of
{start, _, _} -> send_reply(Dialog, session_start);
stop -> send_reply(Dialog, session_stop);
_ -> ok
end.
%%%%%%%%%%% Util %%%%%%%%%%%%%%%%%%%%
send_reply(Elem, Msg) ->
App = case Elem of
#sipmsg{} -> nksip_sipmsg:get_meta(srv_id, Elem);
#dialog{} -> nksip_dialog_lib:get_meta(srv_id, Elem)
end,
case nkserver:get(App, inline_test) of
{Ref, Pid} -> Pid ! {Ref, {App, Msg}};
_ -> ok
end.
| null | https://raw.githubusercontent.com/NetComposer/nksip/7fbcc66806635dc8ecc5d11c30322e4d1df36f0a/test/callbacks/core_test_client2.erl | erlang | -include_lib("nkserver/include/nkserver_module.hrl").
Util %%%%%%%%%%%%%%%%%%%% | -module(core_test_client2).
Include nkserver macros
-include_lib("eunit/include/eunit.hrl").
-include_lib("nksip/include/nksip.hrl").
-include_lib("nkserver/include/nkserver_module.hrl").
-export([config/1]).
-export([sip_get_user_pass/4, sip_invite/2, sip_reinvite/2, sip_cancel/3, sip_bye/2,
sip_info/2, sip_ack/2, sip_options/2, sip_dialog_update/3, sip_session_update/3]).
config(Opts) ->
Opts#{
sip_from => "\"NkSIP Basic SUITE Test Client\" <sip:core_test_client2@nksip>",
sip_local_host => "127.0.0.1",
sip_route => "<sip:127.0.0.1;lr>"
}.
sip_get_user_pass(_User, _Realm, _Req, _Call) ->
true.
sip_invite(Req, _Call) ->
send_reply(Req, invite),
case nksip_sipmsg:header(<<"x-nk-op">>, Req) of
[<<"wait">>] ->
{ok, ReqId} = nksip_request:get_handle(Req),
lager:error("Next error about a looped_process is expected"),
{error, looped_process} = nksip_request:reply(ringing, ReqId),
spawn(
fun() ->
nksip_request:reply(ringing, ReqId),
timer:sleep(1000),
nksip_request:reply(ok, ReqId)
end),
noreply;
_ ->
{reply, {answer, nksip_sipmsg:get_meta(body, Req)}}
end.
sip_reinvite(Req, _Call) ->
send_reply(Req, reinvite),
{reply, {answer, nksip_sipmsg:get_meta(body, Req)}}.
sip_cancel(InvReq, Req, _Call) ->
{ok, 'INVITE'} = nksip_request:method(InvReq),
send_reply(Req, cancel),
ok.
sip_bye(Req, _Call) ->
send_reply(Req, bye),
{reply, ok}.
sip_info(Req, _Call) ->
send_reply(Req, info),
{reply, ok}.
sip_ack(Req, _Call) ->
send_reply(Req, ack),
ok.
sip_options(Req, _Call) ->
send_reply(Req, options),
SrvId = nksip_sipmsg:get_meta(srv_id, Req),
Ids = nksip_sipmsg:header(<<"x-nk-id">>, Req),
{ok, ReqId} = nksip_request:get_handle(Req),
Reply = {ok, [{add, "x-nk-id", [nklib_util:to_binary(SrvId)|Ids]}]},
spawn(fun() -> nksip_request:reply(Reply, ReqId) end),
noreply.
sip_dialog_update(State, Dialog, _Call) ->
case State of
start -> send_reply(Dialog, dialog_start);
stop -> send_reply(Dialog, dialog_stop);
_ -> ok
end.
sip_session_update(State, Dialog, _Call) ->
case State of
{start, _, _} -> send_reply(Dialog, session_start);
stop -> send_reply(Dialog, session_stop);
_ -> ok
end.
send_reply(Elem, Msg) ->
App = case Elem of
#sipmsg{} -> nksip_sipmsg:get_meta(srv_id, Elem);
#dialog{} -> nksip_dialog_lib:get_meta(srv_id, Elem)
end,
case nkserver:get(App, inline_test) of
{Ref, Pid} -> Pid ! {Ref, {App, Msg}};
_ -> ok
end.
|
dc87edcdf89d1e7f671afd4cc5b2513bba7676d83275458e25af4cb736a658f0 | tjknoth/resyn | Type.hs | # LANGUAGE DeriveFunctor #
-- | Refinement Types
module Synquid.Type where
import Synquid.Logic
import Synquid.Util
import qualified Data.Set as Set
import Data.Set (Set)
import qualified Data.Map as Map
import Data.Map.Ordered (OMap)
import qualified Data.Map.Ordered as OMap
import Data.Map (Map)
import Data.Bifunctor
import Data.Bifoldable
import Data.Maybe (catMaybes)
{- Type skeletons -}
data BaseType r p =
BoolT |
IntT |
DatatypeT !Id ![TypeSkeleton r p] ![r] |
TypeVarT !Substitution !Id !p
deriving (Show, Eq, Ord)
-- | Type skeletons (parametrized by refinements, potentials)
data TypeSkeleton r p =
ScalarT !(BaseType r p) !r !p |
FunctionT !Id !(TypeSkeleton r p) !(TypeSkeleton r p) !Int |
LetT !Id !(TypeSkeleton r p) !(TypeSkeleton r p) |
AnyT
deriving (Show, Eq, Ord)
instance Bifunctor TypeSkeleton where
bimap f g (ScalarT b r p) = ScalarT (bimap f g b) (f r) (g p)
bimap f g (FunctionT x argT resT c) = FunctionT x (bimap f g argT) (bimap f g resT) c
bimap f g (LetT x t bodyT) = LetT x (bimap f g t) (bimap f g bodyT)
bimap _ _ AnyT = AnyT
instance Bifunctor BaseType where
bimap f g (DatatypeT x ts ps) = DatatypeT x (map (bimap f g) ts) (map f ps)
bimap _ g (TypeVarT subs x m) = TypeVarT subs x (g m)
bimap _ _ BoolT = BoolT
bimap _ _ IntT = IntT
instance Bifoldable TypeSkeleton where
bifoldMap f g (ScalarT b r p) = f r `mappend` g p `mappend` bifoldMap f g b
bifoldMap f g (FunctionT x argT resT c) = bifoldMap f g argT `mappend` bifoldMap f g resT
bifoldMap f g (LetT x t bodyT) = bifoldMap f g bodyT
bifoldMap _ _ AnyT = mempty
instance Bifoldable BaseType where
-- Ignore predicates
bifoldMap f g (DatatypeT x ts ps) = foldMap (bifoldMap f g) ts
bifoldMap _ g (TypeVarT subs x m) = g m
bifoldMap _ _ BoolT = mempty
bifoldMap _ _ IntT = mempty
-- | Unrefined typed
type SType = TypeSkeleton () Formula
-- | Refined types
type RType = TypeSkeleton Formula Formula
-- | Unrefined schemas
type SSchema = SchemaSkeleton SType
-- | Refined schemas
type RSchema = SchemaSkeleton RType
-- | Refinement base type
type RBase = BaseType Formula Formula
Ignore multiplicity and potential when comparing
equalShape :: RBase -> RBase -> Bool
equalShape (TypeVarT s name _) (TypeVarT s' name' m') = (TypeVarT s name defMultiplicity :: RBase ) == (TypeVarT s' name' defMultiplicity :: RBase)
equalShape (DatatypeT name ts ps) (DatatypeT name' ts' ps') = (name == name') && (fmap shape ts == fmap shape ts') && (ps == ps')
equalShape t t' = t == t'
defPotential = IntLit 0
defMultiplicity = IntLit 1
defCost = 0 :: Int
potentialPrefix = "p"
multiplicityPrefix = "m"
contextual x tDef (FunctionT y tArg tRes cost) = FunctionT y (contextual x tDef tArg) (contextual x tDef tRes) cost
contextual _ _ AnyT = AnyT
contextual x tDef t = LetT x tDef t
isScalarType ScalarT{} = True
-- isScalarType (LetT _ _ t) = isScalarType t
isScalarType LetT{} = True
isScalarType _ = False
baseTypeOf (ScalarT baseT _ _) = baseT
baseTypeOf (LetT _ _ t) = baseTypeOf t
baseTypeOf t = error "baseTypeOf: applied to a function type"
isFunctionType FunctionT{} = True
-- isFunctionType (LetT _ _ t) = isFunctionType t
isFunctionType _ = False
argType (FunctionT _ t _ _) = t
resType (FunctionT _ _ t _) = t
hasAny AnyT = True
hasAny (ScalarT baseT _ _) = baseHasAny baseT
where
baseHasAny (DatatypeT _ tArgs _) = any hasAny tArgs
baseHasAny _ = False
hasAny (FunctionT _ tArg tRes _) = hasAny tArg || hasAny tRes
hasAny (LetT _ tDef tBody) = hasAny tDef || hasAny tBody
-- | Convention to indicate "any datatype" (for synthesizing match scrtuinees)
anyDatatype = ScalarT (DatatypeT dontCare [] []) ftrue defPotential
toSort :: BaseType r p -> Sort
toSort BoolT = BoolS
toSort IntT = IntS
toSort (DatatypeT name tArgs _) = DataS name (map (toSort . baseTypeOf) tArgs)
toSort (TypeVarT _ name _) = VarS name
fromSort :: Sort -> RType
fromSort = flip refineSort ftrue
refineSort :: Sort -> Formula -> RType
refineSort BoolS f = ScalarT BoolT f defPotential
refineSort IntS f = ScalarT IntT f defPotential
refineSort (VarS name) f = ScalarT (TypeVarT Map.empty name defMultiplicity) f defPotential
refineSort (DataS name sArgs) f = ScalarT (DatatypeT name (map fromSort sArgs) []) f defPotential
refineSort (SetS s) f = ScalarT dt f defPotential
where
dt = DatatypeT setTypeName [fromSort s] []
refineSort AnyS _ = AnyT
typeIsData :: TypeSkeleton r p -> Bool
typeIsData (ScalarT DatatypeT{} _ _) = True
typeIsData _ = False
arity :: TypeSkeleton r p -> Int
arity (FunctionT _ _ t _) = 1 + arity t
arity (LetT _ _ t) = arity t
arity _ = 0
-- TODO: make sure the AnyT case is OK
hasSet :: TypeSkeleton r p -> Bool
hasSet (ScalarT (DatatypeT name _ _) _ _) = name == setTypeName
hasSet (FunctionT _ t1 t2 _) = hasSet t1 || hasSet t2
hasSet (LetT _ t1 t2) = hasSet t1 || hasSet t2
hasSet _ = False
lastType (FunctionT _ _ tRes _) = lastType tRes
lastType (LetT _ _ t) = lastType t
lastType t = t
allArgTypes (FunctionT x tArg tRes _) = tArg : allArgTypes tRes
allArgTypes (LetT _ _ t) = allArgTypes t
allArgTypes _ = []
allArgs (ScalarT _ _ _) = []
allArgs (FunctionT x (ScalarT baseT _ _) tRes _) = Var (toSort baseT) x : allArgs tRes
allArgs (FunctionT _ _ tRes _) = allArgs tRes
allArgs (LetT _ _ t) = allArgs t
-- | Free variables of a type
varsOfType :: RType -> Set Id
varsOfType (ScalarT baseT fml _) = varsOfBase baseT `Set.union` Set.map varName (varsOf fml) --`Set.union` Set.map varName (varsOf pot)
where
varsOfBase (DatatypeT _ tArgs pArgs) = Set.unions (map varsOfType tArgs) `Set.union` Set.map varName (Set.unions (map varsOf pArgs))
varsOfBase _ = Set.empty
varsOfType (FunctionT x tArg tRes _) = varsOfType tArg `Set.union` Set.delete x (varsOfType tRes)
varsOfType (LetT x tDef tBody) = varsOfType tDef `Set.union` Set.delete x (varsOfType tBody)
varsOfType AnyT = Set.empty
-- | Predicates mentioned in a type
predsOfType :: RType -> Set Id
predsOfType (ScalarT baseT fml _) = predsOfBase baseT `Set.union` predsOf fml --`Set.union` predsOf pot
where
predsOfBase (DatatypeT _ tArgs pArgs) = Set.unions (map predsOfType tArgs) `Set.union` Set.unions (map predsOf pArgs)
predsOfBase _ = Set.empty
predsOfType (FunctionT _ tArg tRes _) = predsOfType tArg `Set.union` predsOfType tRes
predsOfType (LetT _ tDef tBody) = predsOfType tDef `Set.union` predsOfType tBody
predsOfType AnyT = Set.empty
-- | Predicates mentioned in an integer-sorted predicate argument position,
-- or in a potential annotation
predsOfPotential :: [Bool] -> RType -> Set Id
predsOfPotential isInt t =
let go = predsOfPotential isInt
predsFromBase (DatatypeT dt tArgs pArgs) =
Set.unions (map go tArgs) `Set.union` Set.unions (map (\(_, p) -> predsOf p) (filter fst (zip isInt pArgs)))
predsFromBase _ = Set.empty in
case t of
(ScalarT baseT _ pfml) -> predsFromBase baseT `Set.union` predsOf pfml
(FunctionT _ tArg tRes _) -> go tArg `Set.union` go tRes
(LetT _ tDef tBody) -> go tDef `Set.union` go tBody
AnyT -> Set.empty
varRefinement x s = Var s valueVarName |=| Var s x
isVarRefinement (Binary Eq (Var _ v) (Var _ _)) = v == valueVarName
isVarRefinement _ = False
-- | Polymorphic type skeletons (parametrized by refinements)
data SchemaSkeleton t =
Monotype !t |
ForallT !Id !(SchemaSkeleton t) | -- Type-polymorphic
ForallP !PredSig !(SchemaSkeleton t) -- Predicate-polymorphic
deriving (Functor, Show, Eq, Ord)
instance Bifunctor SchemaSkeleton where
bimap f g ( Monotype t ) = Monotype $ bimap f g t
bimap f g ( ForallT ts sch ) = ForallT ts ( bimap f g sch )
bimap f g ( ForallP ) = ForallP ps ( bimap f g sch )
bimap f g (Monotype t) = Monotype $ bimap f g t
bimap f g (ForallT ts sch) = ForallT ts (bimap f g sch)
bimap f g (ForallP ps sch) = ForallP ps (bimap f g sch)
-}
toMonotype :: SchemaSkeleton t -> t
toMonotype (Monotype t) = t
toMonotype (ForallT _ t) = toMonotype t
toMonotype (ForallP _ t) = toMonotype t
boundVarsOf :: SchemaSkeleton t -> [Id]
boundVarsOf (ForallT a sch) = a : boundVarsOf sch
boundVarsOf _ = []
-- | Building types
bool r = ScalarT BoolT r defPotential
bool_ = bool ()
boolAll = bool ftrue
int r = ScalarT IntT r defPotential
int_ = int ()
intAll = int ftrue
intPot = ScalarT IntT ftrue
nat = int (valInt |>=| IntLit 0)
pos = int (valInt |>| IntLit 0)
vart n f = ScalarT (TypeVarT Map.empty n defMultiplicity) f defPotential
vart_ n = vart n ()
vartAll n = vart n ftrue
vartSafe n f = ScalarT ( TypeVarT Map.empty n ( IntLit 1 ) ) f defPotential
vartSafe = vart
set n f = ScalarT (DatatypeT setTypeName [tvar] []) f defPotential
where
tvar = ScalarT (TypeVarT Map.empty n defMultiplicity) ftrue defPotential
setAll n = set n ftrue
-- | Mapping from type variables to types
type TypeSubstitution = Map Id RType
-- | Mapping from (inferred) potential variables to (possible) formulas
type PotlSubstitution = OMap Id (Maybe Formula)
asSortSubst :: TypeSubstitution -> SortSubstitution
asSortSubst = Map.map (toSort . baseTypeOf)
| ' typeSubstitute ' @subst t@ : apply substitution @subst@ to free type variables in @t@
typeSubstitute :: TypeSubstitution -> RType -> RType
typeSubstitute subst (ScalarT baseT r p) = addRefinement substituteBase (sortSubstituteFml (asSortSubst subst) r)
where
substituteBase = case baseT of
(TypeVarT varSubst a m) -> case Map.lookup a subst of
Just t -> substituteInType (not . (`Map.member` subst)) varSubst $ typeSubstitute subst (updateAnnotations t m p)
Nothing -> ScalarT (TypeVarT varSubst a m) ftrue p
DatatypeT name tArgs pArgs ->
let
tArgs' = map (typeSubstitute subst) tArgs
pArgs' = map (sortSubstituteFml (asSortSubst subst)) pArgs
in ScalarT (DatatypeT name tArgs' pArgs') ftrue p
_ -> ScalarT baseT ftrue p
typeSubstitute subst (FunctionT x tArg tRes cost) = FunctionT x (typeSubstitute subst tArg) (typeSubstitute subst tRes) cost
typeSubstitute subst (LetT x tDef tBody) = LetT x (typeSubstitute subst tDef) (typeSubstitute subst tBody)
typeSubstitute _ AnyT = AnyT
noncaptureTypeSubst :: [Id] -> [RType] -> RType -> RType
noncaptureTypeSubst tVars tArgs t =
let tFresh = typeSubstitute (Map.fromList $ zip tVars (map vartAll distinctTypeVars)) t
in typeSubstitute (Map.fromList $ zip distinctTypeVars tArgs) tFresh
schemaSubstitute :: TypeSubstitution -> RSchema -> RSchema
schemaSubstitute tass (Monotype t) = Monotype $ typeSubstitute tass t
schemaSubstitute tass (ForallT a sch) = ForallT a $ schemaSubstitute (Map.delete a tass) sch
schemaSubstitute tass (ForallP sig sch) = ForallP sig $ schemaSubstitute tass sch
typeSubstitutePred :: Substitution -> RType -> RType
typeSubstitutePred pSubst t =
let tsp = typeSubstitutePred pSubst
in case t of
ScalarT (DatatypeT name tArgs pArgs) fml pot
-> ScalarT (DatatypeT name (map tsp tArgs) (map (substitutePredicate pSubst) pArgs)) (substitutePredicate pSubst fml) (substitutePredicate pSubst pot)
ScalarT baseT fml pot
-> ScalarT baseT (substitutePredicate pSubst fml) (substitutePredicate pSubst pot)
FunctionT x tArg tRes c
-> FunctionT x (tsp tArg) (tsp tRes) c
LetT x tDef tBody
-> LetT x (tsp tDef) (tsp tBody)
AnyT -> AnyT
schemaSubstitutePotl :: PotlSubstitution -> RSchema -> RSchema
schemaSubstitutePotl ts (ForallT i s) = ForallT i $ schemaSubstitutePotl ts s
schemaSubstitutePotl ts (ForallP i s) = ForallP i $ schemaSubstitutePotl ts s
schemaSubstitutePotl ts (Monotype b) = Monotype $ substitutePotl ts b
-- TODO: this assumes inferred potls can only be vars
substitutePotl :: PotlSubstitution -> RType -> RType
substitutePotl ts (ScalarT (DatatypeT di ta abs) ref v) =
ScalarT (DatatypeT di (fmap (substitutePotl ts) ta) (fmap (lookupIPotl ts) abs)) ref (lookupIPotl ts v)
substitutePotl ts (ScalarT dt ref v) =
ScalarT dt ref (lookupIPotl ts v)
substitutePotl ts (FunctionT i d c cs) = FunctionT i (substitutePotl ts d) (substitutePotl ts c) cs
substitutePotl ts (LetT i def body) = LetT i (substitutePotl ts def) (substitutePotl ts body)
substitutePotl _ AnyT = AnyT
-- TODO: This only works if the formula is only an inference var and nothing else
-- If the formula isn't only an inference var but contains one, this
-- doesn't replace it
lookupIPotl :: PotlSubstitution -> Formula -> Formula
lookupIPotl ts v@(Var IntS pVar) = case OMap.lookup pVar ts of
Just (Just x) -> x
_ -> v
lookupIPotl _ x = x
-- | 'typeVarsOf' @t@ : all type variables in @t@
typeVarsOf :: TypeSkeleton r p -> Set Id
typeVarsOf t@(ScalarT baseT _ _) = case baseT of
TypeVarT _ name _ -> Set.singleton name
DatatypeT _ tArgs _ -> Set.unions (map typeVarsOf tArgs)
_ -> Set.empty
typeVarsOf (FunctionT _ tArg tRes _) = typeVarsOf tArg `Set.union` typeVarsOf tRes
typeVarsOf (LetT _ tDef tBody) = typeVarsOf tDef `Set.union` typeVarsOf tBody
typeVarsOf _ = Set.empty
| ' updateAnnotations ' @t m p@ : " multiply " @t@ by multiplicity @m@ , then add on surplus potential @p@
updateAnnotations :: RType -> Formula -> Formula -> RType
updateAnnotations t@ScalarT{} mult = safeAddPotential (typeMultiply mult t)
schemaMultiply p = fmap (typeMultiply p)
typeMultiply :: Formula -> RType -> RType
typeMultiply fml (ScalarT t ref pot) = ScalarT (baseTypeMultiply fml t) ref (multiplyFormulas fml pot)
typeMultiply fml t = t
baseTypeMultiply :: Formula -> RBase -> RBase
baseTypeMultiply fml (TypeVarT subs name mul) = TypeVarT subs name (multiplyFormulas mul fml)
baseTypeMultiply fml (DatatypeT name tArgs pArgs) = DatatypeT name (map (typeMultiply fml) tArgs) pArgs
baseTypeMultiply fml t = t
safeAddPotential :: RType -> Formula -> RType
safeAddPotential (ScalarT base ref pot) f = ScalarT base ref (safeAddFormulas pot f)
safeAddPotential (LetT x tDef tBody) f = LetT x tDef (safeAddPotential tBody f)
safeAddPotential t _ = t
safeAddFormulas f g : Adds f to g -- if g is a conditional , it pushes f into the conditional structure
-- used as a hack to make conditional solver work w polynomials
safeAddFormulas :: Formula -> Formula -> Formula
safeAddFormulas f (Ite f1 f2 f3) = Ite f1 (addFormulas f f2) (addFormulas f f3)
safeAddFormulas f g = addFormulas f g
addPotential :: RType -> Formula -> RType
addPotential (ScalarT base ref pot) f = ScalarT base ref (addFormulas pot f)
addPotential (LetT x tDef tBody) f = LetT x tDef (addPotential tBody f)
addPotential t _ = t
subtractPotential :: RType -> Formula -> RType
subtractPotential (ScalarT base ref pot) f = ScalarT base ref (addFormulas pot (fneg f)) -- (negateFml f))
subtractPotential (LetT x tDef tBody) f = LetT x tDef (subtractPotential tBody f)
subtractPotential t _ = t
-- Extract top-level potential from a scalar type
topPotentialOf :: RType -> Maybe Formula
topPotentialOf (ScalarT _ _ p) = Just p
topPotentialOf _ = Nothing
{- Refinement types -}
-- | Forget refinements of a type
shape :: RType -> SType
shape (ScalarT (DatatypeT name tArgs pArgs) _ _) = ScalarT (DatatypeT name (map shape tArgs) (replicate (length pArgs) ())) () defPotential
shape (ScalarT IntT _ _) = ScalarT IntT () defPotential
shape (ScalarT BoolT _ _) = ScalarT BoolT () defPotential
shape (ScalarT (TypeVarT _ a _) _ _) = ScalarT (TypeVarT Map.empty a defMultiplicity) () defPotential
shape (FunctionT x tArg tFun _) = FunctionT x (shape tArg) (shape tFun) 0
shape (LetT _ _ t) = shape t
shape AnyT = AnyT
-- | Conjoin refinement to a type
addRefinement :: RType -> Formula -> RType
addRefinement (ScalarT base fml pot) fml' = if isVarRefinement fml'
then ScalarT base fml' pot -- the type of a polymorphic variable does not require any other refinements
else ScalarT base (fml `andClean` fml') pot
addRefinement (LetT x tDef tBody) fml = LetT x tDef (addRefinement tBody fml)
addRefinement t (BoolLit True) = t
addRefinement AnyT _ = AnyT
addRefinement t _ = error $ "addRefinement: applied to function type: " ++ show t
-- | Conjoin refinement to the return type
addRefinementToLast fml t@ScalarT{} = addRefinement t fml
addRefinementToLast fml (FunctionT x tArg tRes c) = FunctionT x tArg (addRefinementToLast fml tRes) c
addRefinementToLast fml (LetT x tDef tBody) = LetT x tDef (addRefinementToLast fml tBody)
-- | Conjoin refinement to the return type inside a schema
addRefinementToLastSch :: Formula -> RSchema -> RSchema
addRefinementToLastSch fml = fmap (addRefinementToLast fml)
-- | Apply variable substitution in all formulas inside a type
substituteInType :: (Id -> Bool) -> Substitution -> RType -> RType
substituteInType isBound subst (ScalarT baseT fml pot) = ScalarT (substituteBase subst baseT) (substitute subst fml) (substitute subst pot)
where
TODO : does this make sense ?
substituteBase subst (TypeVarT oldSubst a m) = TypeVarT oldSubst a (substitute subst m)
-- Looks like pending substitutions on types are not actually needed, since renamed variables are always out of scope
if isBound a
then TypeVarT oldSubst a
else TypeVarT ( oldSubst ` composeSubstitutions ` subst ) a
substituteBase subst (DatatypeT name tArgs pArgs) = DatatypeT name (map (substituteInType isBound subst) tArgs) (map (substitute subst) pArgs)
substituteBase _ baseT = baseT
substituteInType isBound subst (FunctionT x tArg tRes c) =
if Map.member x subst
then error $ unwords ["Attempt to substitute variable", x, "bound in a function type"]
else FunctionT x (substituteInType isBound subst tArg) (substituteInType isBound subst tRes) c
substituteInType isBound subst (LetT x tDef tBody) =
if Map.member x subst
then error $ unwords ["Attempt to substitute variable", x, "bound in a contextual type"]
else LetT x (substituteInType isBound subst tDef) (substituteInType isBound subst tBody)
substituteInType isBound _ AnyT = AnyT
| ' renameVar ' @old new t typ@ : rename all occurrences of @old@ in @typ@ into @new@ of type @t@
renameVar :: (Id -> Bool) -> Id -> Id -> RType -> RType -> RType
renameVar isBound old new (ScalarT b _ _) t = substituteInType isBound (Map.singleton old (Var (toSort b) new)) t
renameVar isBound old new (LetT _ _ tBody) t = renameVar isBound old new tBody t
renameVar _ _ _ _ t = t -- function arguments cannot occur in types (and AnyT is assumed to be function)
| Intersection of two types ( assuming the types were already checked for consistency )
intersection _ t AnyT = t
intersection _ AnyT t = t
intersection isBound (ScalarT baseT fml pot) (ScalarT baseT' fml' pot') = case baseT of
DatatypeT name tArgs pArgs -> let DatatypeT _ tArgs' pArgs' = baseT' in
ScalarT (DatatypeT name (zipWith (intersection isBound) tArgs tArgs') (zipWith andClean pArgs pArgs')) (fml `andClean` fml') (fmax pot pot')
_ -> ScalarT baseT (fml `andClean` fml') (fmax pot pot')
intersection isBound (FunctionT x tArg tRes c) (FunctionT y tArg' tRes' c') = FunctionT x tArg (intersection isBound tRes (renameVar isBound y x tArg tRes')) (max c c')
-- Move cost annotations to next arrow or to scalar argument type before applying function
shiftCost :: RType -> RType
shiftCost (FunctionT x argT resT c) = FunctionT x (addPotential argT (IntLit c)) resT 0
--if isScalarType resT
then FunctionT x ( addPotential argT ( IntLit c ) ) resT 0
-- else FunctionT x argT (addCostToArrow resT) 0
--where
-- addCostToArrow (FunctionT y a r cost) = FunctionT y a r (cost + c)
-- | Instantiate unknowns in a type
-- TODO: eventually will need to instantiate potential variables as well
typeApplySolution :: Solution -> RType -> RType
typeApplySolution sol = first (applySolution sol)
allRefinementsOf :: RSchema -> [Formula]
allRefinementsOf sch = allRefinementsOf' $ toMonotype sch
allRefinementsOf' (ScalarT _ ref _) = [ref]
allRefinementsOf' (FunctionT _ argT resT _) = allRefinementsOf' argT ++ allRefinementsOf' resT
allRefinementsOf' _ = error "allRefinementsOf called on contextual or any type"
-- | 'allRFormulas' @t@ : return all resource-related formulas (potentials and multiplicities) from a refinement type @t@
allRFormulas :: Map Id [Bool] -> RType -> [Formula]
allRFormulas flagMap t =
let concretePotentials = bifoldMap (const []) (: []) t
abstractPotentials = allAbstractPotentials flagMap t
in concretePotentials ++ abstractPotentials
-- collect potential annotations
-- collect resource preds
allAbstractPotentials :: Map Id [Bool] -> RType -> [Formula]
allAbstractPotentials flagMap (ScalarT b _ pot) = allAbstractPotentialsBase flagMap b
allAbstractPotentials flagMap (FunctionT _ argT resT _) = allAbstractPotentials flagMap argT ++ allAbstractPotentials flagMap resT
allAbstractPotentials flagMap (LetT _ tDef tBody) = allAbstractPotentials flagMap tDef ++ allAbstractPotentials flagMap tBody
allAbstractPotentials _ AnyT = []
allAbstractPotentialsBase :: Map Id [Bool] -> RBase -> [Formula]
allAbstractPotentialsBase flagMap (DatatypeT dt ts preds) =
case Map.lookup dt flagMap of
Nothing -> error $ "allAbstractPotentialsBase: datatype " ++ dt ++ " not found"
Just rflags -> catMaybes $ zipWith (\isRes pred -> if isRes then Just pred else Nothing) rflags preds
allAbstractPotentialsBase _ _ = []
allArgSorts :: RType -> [Sort]
allArgSorts (FunctionT _ (ScalarT b _ _) resT _) = toSort b : allArgSorts resT
allArgSorts FunctionT{} = error "allArgSorts: Non-scalar type in argument position"
allArgSorts ScalarT{} = []
allArgSorts LetT{} = error "allArgSorts: contextual type"
resultSort :: RType -> Sort
resultSort (FunctionT _ _ resT _) = resultSort resT
resultSort (ScalarT b _ _) = toSort b
isDataType DatatypeT{} = True
isDataType _ = False
getConditional :: RType -> Maybe Formula
getConditional (ScalarT _ _ f@(Ite g _ _)) = Just f
getConditional _ = Nothing
removePotentialSch :: RSchema -> RSchema
removePotentialSch = fmap removePotential
removePotential (ScalarT b r _) = ScalarT (removePotentialBase b) r fzero
removePotential (FunctionT x arg res c) = FunctionT x (removePotential arg) (removePotential res) 0
removePotential t = t
removePotentialBase (DatatypeT x ts ps) = DatatypeT x (map removePotential ts) ps
removePotentialBase b = b
-- Set strings: used for "fake" set type for typechecking measures
emptySetCtor = "Emptyset"
singletonCtor = "Singleton"
insertSetCtor = "Insert"
setTypeName = "DSet"
setTypeVar = "setTypeVar"
| null | https://raw.githubusercontent.com/tjknoth/resyn/54ff304c635f26b4b498b82be267923a65e0662d/src/Synquid/Type.hs | haskell | | Refinement Types
Type skeletons
| Type skeletons (parametrized by refinements, potentials)
Ignore predicates
| Unrefined typed
| Refined types
| Unrefined schemas
| Refined schemas
| Refinement base type
isScalarType (LetT _ _ t) = isScalarType t
isFunctionType (LetT _ _ t) = isFunctionType t
| Convention to indicate "any datatype" (for synthesizing match scrtuinees)
TODO: make sure the AnyT case is OK
| Free variables of a type
`Set.union` Set.map varName (varsOf pot)
| Predicates mentioned in a type
`Set.union` predsOf pot
| Predicates mentioned in an integer-sorted predicate argument position,
or in a potential annotation
| Polymorphic type skeletons (parametrized by refinements)
Type-polymorphic
Predicate-polymorphic
| Building types
| Mapping from type variables to types
| Mapping from (inferred) potential variables to (possible) formulas
TODO: this assumes inferred potls can only be vars
TODO: This only works if the formula is only an inference var and nothing else
If the formula isn't only an inference var but contains one, this
doesn't replace it
| 'typeVarsOf' @t@ : all type variables in @t@
if g is a conditional , it pushes f into the conditional structure
used as a hack to make conditional solver work w polynomials
(negateFml f))
Extract top-level potential from a scalar type
Refinement types
| Forget refinements of a type
| Conjoin refinement to a type
the type of a polymorphic variable does not require any other refinements
| Conjoin refinement to the return type
| Conjoin refinement to the return type inside a schema
| Apply variable substitution in all formulas inside a type
Looks like pending substitutions on types are not actually needed, since renamed variables are always out of scope
function arguments cannot occur in types (and AnyT is assumed to be function)
Move cost annotations to next arrow or to scalar argument type before applying function
if isScalarType resT
else FunctionT x argT (addCostToArrow resT) 0
where
addCostToArrow (FunctionT y a r cost) = FunctionT y a r (cost + c)
| Instantiate unknowns in a type
TODO: eventually will need to instantiate potential variables as well
| 'allRFormulas' @t@ : return all resource-related formulas (potentials and multiplicities) from a refinement type @t@
collect potential annotations
collect resource preds
Set strings: used for "fake" set type for typechecking measures | # LANGUAGE DeriveFunctor #
module Synquid.Type where
import Synquid.Logic
import Synquid.Util
import qualified Data.Set as Set
import Data.Set (Set)
import qualified Data.Map as Map
import Data.Map.Ordered (OMap)
import qualified Data.Map.Ordered as OMap
import Data.Map (Map)
import Data.Bifunctor
import Data.Bifoldable
import Data.Maybe (catMaybes)
data BaseType r p =
BoolT |
IntT |
DatatypeT !Id ![TypeSkeleton r p] ![r] |
TypeVarT !Substitution !Id !p
deriving (Show, Eq, Ord)
data TypeSkeleton r p =
ScalarT !(BaseType r p) !r !p |
FunctionT !Id !(TypeSkeleton r p) !(TypeSkeleton r p) !Int |
LetT !Id !(TypeSkeleton r p) !(TypeSkeleton r p) |
AnyT
deriving (Show, Eq, Ord)
instance Bifunctor TypeSkeleton where
bimap f g (ScalarT b r p) = ScalarT (bimap f g b) (f r) (g p)
bimap f g (FunctionT x argT resT c) = FunctionT x (bimap f g argT) (bimap f g resT) c
bimap f g (LetT x t bodyT) = LetT x (bimap f g t) (bimap f g bodyT)
bimap _ _ AnyT = AnyT
instance Bifunctor BaseType where
bimap f g (DatatypeT x ts ps) = DatatypeT x (map (bimap f g) ts) (map f ps)
bimap _ g (TypeVarT subs x m) = TypeVarT subs x (g m)
bimap _ _ BoolT = BoolT
bimap _ _ IntT = IntT
instance Bifoldable TypeSkeleton where
bifoldMap f g (ScalarT b r p) = f r `mappend` g p `mappend` bifoldMap f g b
bifoldMap f g (FunctionT x argT resT c) = bifoldMap f g argT `mappend` bifoldMap f g resT
bifoldMap f g (LetT x t bodyT) = bifoldMap f g bodyT
bifoldMap _ _ AnyT = mempty
instance Bifoldable BaseType where
bifoldMap f g (DatatypeT x ts ps) = foldMap (bifoldMap f g) ts
bifoldMap _ g (TypeVarT subs x m) = g m
bifoldMap _ _ BoolT = mempty
bifoldMap _ _ IntT = mempty
type SType = TypeSkeleton () Formula
type RType = TypeSkeleton Formula Formula
type SSchema = SchemaSkeleton SType
type RSchema = SchemaSkeleton RType
type RBase = BaseType Formula Formula
Ignore multiplicity and potential when comparing
equalShape :: RBase -> RBase -> Bool
equalShape (TypeVarT s name _) (TypeVarT s' name' m') = (TypeVarT s name defMultiplicity :: RBase ) == (TypeVarT s' name' defMultiplicity :: RBase)
equalShape (DatatypeT name ts ps) (DatatypeT name' ts' ps') = (name == name') && (fmap shape ts == fmap shape ts') && (ps == ps')
equalShape t t' = t == t'
defPotential = IntLit 0
defMultiplicity = IntLit 1
defCost = 0 :: Int
potentialPrefix = "p"
multiplicityPrefix = "m"
contextual x tDef (FunctionT y tArg tRes cost) = FunctionT y (contextual x tDef tArg) (contextual x tDef tRes) cost
contextual _ _ AnyT = AnyT
contextual x tDef t = LetT x tDef t
isScalarType ScalarT{} = True
isScalarType LetT{} = True
isScalarType _ = False
baseTypeOf (ScalarT baseT _ _) = baseT
baseTypeOf (LetT _ _ t) = baseTypeOf t
baseTypeOf t = error "baseTypeOf: applied to a function type"
isFunctionType FunctionT{} = True
isFunctionType _ = False
argType (FunctionT _ t _ _) = t
resType (FunctionT _ _ t _) = t
hasAny AnyT = True
hasAny (ScalarT baseT _ _) = baseHasAny baseT
where
baseHasAny (DatatypeT _ tArgs _) = any hasAny tArgs
baseHasAny _ = False
hasAny (FunctionT _ tArg tRes _) = hasAny tArg || hasAny tRes
hasAny (LetT _ tDef tBody) = hasAny tDef || hasAny tBody
anyDatatype = ScalarT (DatatypeT dontCare [] []) ftrue defPotential
toSort :: BaseType r p -> Sort
toSort BoolT = BoolS
toSort IntT = IntS
toSort (DatatypeT name tArgs _) = DataS name (map (toSort . baseTypeOf) tArgs)
toSort (TypeVarT _ name _) = VarS name
fromSort :: Sort -> RType
fromSort = flip refineSort ftrue
refineSort :: Sort -> Formula -> RType
refineSort BoolS f = ScalarT BoolT f defPotential
refineSort IntS f = ScalarT IntT f defPotential
refineSort (VarS name) f = ScalarT (TypeVarT Map.empty name defMultiplicity) f defPotential
refineSort (DataS name sArgs) f = ScalarT (DatatypeT name (map fromSort sArgs) []) f defPotential
refineSort (SetS s) f = ScalarT dt f defPotential
where
dt = DatatypeT setTypeName [fromSort s] []
refineSort AnyS _ = AnyT
typeIsData :: TypeSkeleton r p -> Bool
typeIsData (ScalarT DatatypeT{} _ _) = True
typeIsData _ = False
arity :: TypeSkeleton r p -> Int
arity (FunctionT _ _ t _) = 1 + arity t
arity (LetT _ _ t) = arity t
arity _ = 0
hasSet :: TypeSkeleton r p -> Bool
hasSet (ScalarT (DatatypeT name _ _) _ _) = name == setTypeName
hasSet (FunctionT _ t1 t2 _) = hasSet t1 || hasSet t2
hasSet (LetT _ t1 t2) = hasSet t1 || hasSet t2
hasSet _ = False
lastType (FunctionT _ _ tRes _) = lastType tRes
lastType (LetT _ _ t) = lastType t
lastType t = t
allArgTypes (FunctionT x tArg tRes _) = tArg : allArgTypes tRes
allArgTypes (LetT _ _ t) = allArgTypes t
allArgTypes _ = []
allArgs (ScalarT _ _ _) = []
allArgs (FunctionT x (ScalarT baseT _ _) tRes _) = Var (toSort baseT) x : allArgs tRes
allArgs (FunctionT _ _ tRes _) = allArgs tRes
allArgs (LetT _ _ t) = allArgs t
varsOfType :: RType -> Set Id
where
varsOfBase (DatatypeT _ tArgs pArgs) = Set.unions (map varsOfType tArgs) `Set.union` Set.map varName (Set.unions (map varsOf pArgs))
varsOfBase _ = Set.empty
varsOfType (FunctionT x tArg tRes _) = varsOfType tArg `Set.union` Set.delete x (varsOfType tRes)
varsOfType (LetT x tDef tBody) = varsOfType tDef `Set.union` Set.delete x (varsOfType tBody)
varsOfType AnyT = Set.empty
predsOfType :: RType -> Set Id
where
predsOfBase (DatatypeT _ tArgs pArgs) = Set.unions (map predsOfType tArgs) `Set.union` Set.unions (map predsOf pArgs)
predsOfBase _ = Set.empty
predsOfType (FunctionT _ tArg tRes _) = predsOfType tArg `Set.union` predsOfType tRes
predsOfType (LetT _ tDef tBody) = predsOfType tDef `Set.union` predsOfType tBody
predsOfType AnyT = Set.empty
predsOfPotential :: [Bool] -> RType -> Set Id
predsOfPotential isInt t =
let go = predsOfPotential isInt
predsFromBase (DatatypeT dt tArgs pArgs) =
Set.unions (map go tArgs) `Set.union` Set.unions (map (\(_, p) -> predsOf p) (filter fst (zip isInt pArgs)))
predsFromBase _ = Set.empty in
case t of
(ScalarT baseT _ pfml) -> predsFromBase baseT `Set.union` predsOf pfml
(FunctionT _ tArg tRes _) -> go tArg `Set.union` go tRes
(LetT _ tDef tBody) -> go tDef `Set.union` go tBody
AnyT -> Set.empty
varRefinement x s = Var s valueVarName |=| Var s x
isVarRefinement (Binary Eq (Var _ v) (Var _ _)) = v == valueVarName
isVarRefinement _ = False
data SchemaSkeleton t =
Monotype !t |
deriving (Functor, Show, Eq, Ord)
instance Bifunctor SchemaSkeleton where
bimap f g ( Monotype t ) = Monotype $ bimap f g t
bimap f g ( ForallT ts sch ) = ForallT ts ( bimap f g sch )
bimap f g ( ForallP ) = ForallP ps ( bimap f g sch )
bimap f g (Monotype t) = Monotype $ bimap f g t
bimap f g (ForallT ts sch) = ForallT ts (bimap f g sch)
bimap f g (ForallP ps sch) = ForallP ps (bimap f g sch)
-}
toMonotype :: SchemaSkeleton t -> t
toMonotype (Monotype t) = t
toMonotype (ForallT _ t) = toMonotype t
toMonotype (ForallP _ t) = toMonotype t
boundVarsOf :: SchemaSkeleton t -> [Id]
boundVarsOf (ForallT a sch) = a : boundVarsOf sch
boundVarsOf _ = []
bool r = ScalarT BoolT r defPotential
bool_ = bool ()
boolAll = bool ftrue
int r = ScalarT IntT r defPotential
int_ = int ()
intAll = int ftrue
intPot = ScalarT IntT ftrue
nat = int (valInt |>=| IntLit 0)
pos = int (valInt |>| IntLit 0)
vart n f = ScalarT (TypeVarT Map.empty n defMultiplicity) f defPotential
vart_ n = vart n ()
vartAll n = vart n ftrue
vartSafe n f = ScalarT ( TypeVarT Map.empty n ( IntLit 1 ) ) f defPotential
vartSafe = vart
set n f = ScalarT (DatatypeT setTypeName [tvar] []) f defPotential
where
tvar = ScalarT (TypeVarT Map.empty n defMultiplicity) ftrue defPotential
setAll n = set n ftrue
type TypeSubstitution = Map Id RType
type PotlSubstitution = OMap Id (Maybe Formula)
asSortSubst :: TypeSubstitution -> SortSubstitution
asSortSubst = Map.map (toSort . baseTypeOf)
| ' typeSubstitute ' @subst t@ : apply substitution @subst@ to free type variables in @t@
typeSubstitute :: TypeSubstitution -> RType -> RType
typeSubstitute subst (ScalarT baseT r p) = addRefinement substituteBase (sortSubstituteFml (asSortSubst subst) r)
where
substituteBase = case baseT of
(TypeVarT varSubst a m) -> case Map.lookup a subst of
Just t -> substituteInType (not . (`Map.member` subst)) varSubst $ typeSubstitute subst (updateAnnotations t m p)
Nothing -> ScalarT (TypeVarT varSubst a m) ftrue p
DatatypeT name tArgs pArgs ->
let
tArgs' = map (typeSubstitute subst) tArgs
pArgs' = map (sortSubstituteFml (asSortSubst subst)) pArgs
in ScalarT (DatatypeT name tArgs' pArgs') ftrue p
_ -> ScalarT baseT ftrue p
typeSubstitute subst (FunctionT x tArg tRes cost) = FunctionT x (typeSubstitute subst tArg) (typeSubstitute subst tRes) cost
typeSubstitute subst (LetT x tDef tBody) = LetT x (typeSubstitute subst tDef) (typeSubstitute subst tBody)
typeSubstitute _ AnyT = AnyT
noncaptureTypeSubst :: [Id] -> [RType] -> RType -> RType
noncaptureTypeSubst tVars tArgs t =
let tFresh = typeSubstitute (Map.fromList $ zip tVars (map vartAll distinctTypeVars)) t
in typeSubstitute (Map.fromList $ zip distinctTypeVars tArgs) tFresh
schemaSubstitute :: TypeSubstitution -> RSchema -> RSchema
schemaSubstitute tass (Monotype t) = Monotype $ typeSubstitute tass t
schemaSubstitute tass (ForallT a sch) = ForallT a $ schemaSubstitute (Map.delete a tass) sch
schemaSubstitute tass (ForallP sig sch) = ForallP sig $ schemaSubstitute tass sch
typeSubstitutePred :: Substitution -> RType -> RType
typeSubstitutePred pSubst t =
let tsp = typeSubstitutePred pSubst
in case t of
ScalarT (DatatypeT name tArgs pArgs) fml pot
-> ScalarT (DatatypeT name (map tsp tArgs) (map (substitutePredicate pSubst) pArgs)) (substitutePredicate pSubst fml) (substitutePredicate pSubst pot)
ScalarT baseT fml pot
-> ScalarT baseT (substitutePredicate pSubst fml) (substitutePredicate pSubst pot)
FunctionT x tArg tRes c
-> FunctionT x (tsp tArg) (tsp tRes) c
LetT x tDef tBody
-> LetT x (tsp tDef) (tsp tBody)
AnyT -> AnyT
schemaSubstitutePotl :: PotlSubstitution -> RSchema -> RSchema
schemaSubstitutePotl ts (ForallT i s) = ForallT i $ schemaSubstitutePotl ts s
schemaSubstitutePotl ts (ForallP i s) = ForallP i $ schemaSubstitutePotl ts s
schemaSubstitutePotl ts (Monotype b) = Monotype $ substitutePotl ts b
substitutePotl :: PotlSubstitution -> RType -> RType
substitutePotl ts (ScalarT (DatatypeT di ta abs) ref v) =
ScalarT (DatatypeT di (fmap (substitutePotl ts) ta) (fmap (lookupIPotl ts) abs)) ref (lookupIPotl ts v)
substitutePotl ts (ScalarT dt ref v) =
ScalarT dt ref (lookupIPotl ts v)
substitutePotl ts (FunctionT i d c cs) = FunctionT i (substitutePotl ts d) (substitutePotl ts c) cs
substitutePotl ts (LetT i def body) = LetT i (substitutePotl ts def) (substitutePotl ts body)
substitutePotl _ AnyT = AnyT
lookupIPotl :: PotlSubstitution -> Formula -> Formula
lookupIPotl ts v@(Var IntS pVar) = case OMap.lookup pVar ts of
Just (Just x) -> x
_ -> v
lookupIPotl _ x = x
typeVarsOf :: TypeSkeleton r p -> Set Id
typeVarsOf t@(ScalarT baseT _ _) = case baseT of
TypeVarT _ name _ -> Set.singleton name
DatatypeT _ tArgs _ -> Set.unions (map typeVarsOf tArgs)
_ -> Set.empty
typeVarsOf (FunctionT _ tArg tRes _) = typeVarsOf tArg `Set.union` typeVarsOf tRes
typeVarsOf (LetT _ tDef tBody) = typeVarsOf tDef `Set.union` typeVarsOf tBody
typeVarsOf _ = Set.empty
| ' updateAnnotations ' @t m p@ : " multiply " @t@ by multiplicity @m@ , then add on surplus potential @p@
updateAnnotations :: RType -> Formula -> Formula -> RType
updateAnnotations t@ScalarT{} mult = safeAddPotential (typeMultiply mult t)
schemaMultiply p = fmap (typeMultiply p)
typeMultiply :: Formula -> RType -> RType
typeMultiply fml (ScalarT t ref pot) = ScalarT (baseTypeMultiply fml t) ref (multiplyFormulas fml pot)
typeMultiply fml t = t
baseTypeMultiply :: Formula -> RBase -> RBase
baseTypeMultiply fml (TypeVarT subs name mul) = TypeVarT subs name (multiplyFormulas mul fml)
baseTypeMultiply fml (DatatypeT name tArgs pArgs) = DatatypeT name (map (typeMultiply fml) tArgs) pArgs
baseTypeMultiply fml t = t
safeAddPotential :: RType -> Formula -> RType
safeAddPotential (ScalarT base ref pot) f = ScalarT base ref (safeAddFormulas pot f)
safeAddPotential (LetT x tDef tBody) f = LetT x tDef (safeAddPotential tBody f)
safeAddPotential t _ = t
safeAddFormulas :: Formula -> Formula -> Formula
safeAddFormulas f (Ite f1 f2 f3) = Ite f1 (addFormulas f f2) (addFormulas f f3)
safeAddFormulas f g = addFormulas f g
addPotential :: RType -> Formula -> RType
addPotential (ScalarT base ref pot) f = ScalarT base ref (addFormulas pot f)
addPotential (LetT x tDef tBody) f = LetT x tDef (addPotential tBody f)
addPotential t _ = t
subtractPotential :: RType -> Formula -> RType
subtractPotential (LetT x tDef tBody) f = LetT x tDef (subtractPotential tBody f)
subtractPotential t _ = t
topPotentialOf :: RType -> Maybe Formula
topPotentialOf (ScalarT _ _ p) = Just p
topPotentialOf _ = Nothing
shape :: RType -> SType
shape (ScalarT (DatatypeT name tArgs pArgs) _ _) = ScalarT (DatatypeT name (map shape tArgs) (replicate (length pArgs) ())) () defPotential
shape (ScalarT IntT _ _) = ScalarT IntT () defPotential
shape (ScalarT BoolT _ _) = ScalarT BoolT () defPotential
shape (ScalarT (TypeVarT _ a _) _ _) = ScalarT (TypeVarT Map.empty a defMultiplicity) () defPotential
shape (FunctionT x tArg tFun _) = FunctionT x (shape tArg) (shape tFun) 0
shape (LetT _ _ t) = shape t
shape AnyT = AnyT
addRefinement :: RType -> Formula -> RType
addRefinement (ScalarT base fml pot) fml' = if isVarRefinement fml'
else ScalarT base (fml `andClean` fml') pot
addRefinement (LetT x tDef tBody) fml = LetT x tDef (addRefinement tBody fml)
addRefinement t (BoolLit True) = t
addRefinement AnyT _ = AnyT
addRefinement t _ = error $ "addRefinement: applied to function type: " ++ show t
addRefinementToLast fml t@ScalarT{} = addRefinement t fml
addRefinementToLast fml (FunctionT x tArg tRes c) = FunctionT x tArg (addRefinementToLast fml tRes) c
addRefinementToLast fml (LetT x tDef tBody) = LetT x tDef (addRefinementToLast fml tBody)
addRefinementToLastSch :: Formula -> RSchema -> RSchema
addRefinementToLastSch fml = fmap (addRefinementToLast fml)
substituteInType :: (Id -> Bool) -> Substitution -> RType -> RType
substituteInType isBound subst (ScalarT baseT fml pot) = ScalarT (substituteBase subst baseT) (substitute subst fml) (substitute subst pot)
where
TODO : does this make sense ?
substituteBase subst (TypeVarT oldSubst a m) = TypeVarT oldSubst a (substitute subst m)
if isBound a
then TypeVarT oldSubst a
else TypeVarT ( oldSubst ` composeSubstitutions ` subst ) a
substituteBase subst (DatatypeT name tArgs pArgs) = DatatypeT name (map (substituteInType isBound subst) tArgs) (map (substitute subst) pArgs)
substituteBase _ baseT = baseT
substituteInType isBound subst (FunctionT x tArg tRes c) =
if Map.member x subst
then error $ unwords ["Attempt to substitute variable", x, "bound in a function type"]
else FunctionT x (substituteInType isBound subst tArg) (substituteInType isBound subst tRes) c
substituteInType isBound subst (LetT x tDef tBody) =
if Map.member x subst
then error $ unwords ["Attempt to substitute variable", x, "bound in a contextual type"]
else LetT x (substituteInType isBound subst tDef) (substituteInType isBound subst tBody)
substituteInType isBound _ AnyT = AnyT
| ' renameVar ' @old new t typ@ : rename all occurrences of @old@ in @typ@ into @new@ of type @t@
renameVar :: (Id -> Bool) -> Id -> Id -> RType -> RType -> RType
renameVar isBound old new (ScalarT b _ _) t = substituteInType isBound (Map.singleton old (Var (toSort b) new)) t
renameVar isBound old new (LetT _ _ tBody) t = renameVar isBound old new tBody t
| Intersection of two types ( assuming the types were already checked for consistency )
intersection _ t AnyT = t
intersection _ AnyT t = t
intersection isBound (ScalarT baseT fml pot) (ScalarT baseT' fml' pot') = case baseT of
DatatypeT name tArgs pArgs -> let DatatypeT _ tArgs' pArgs' = baseT' in
ScalarT (DatatypeT name (zipWith (intersection isBound) tArgs tArgs') (zipWith andClean pArgs pArgs')) (fml `andClean` fml') (fmax pot pot')
_ -> ScalarT baseT (fml `andClean` fml') (fmax pot pot')
intersection isBound (FunctionT x tArg tRes c) (FunctionT y tArg' tRes' c') = FunctionT x tArg (intersection isBound tRes (renameVar isBound y x tArg tRes')) (max c c')
shiftCost :: RType -> RType
shiftCost (FunctionT x argT resT c) = FunctionT x (addPotential argT (IntLit c)) resT 0
then FunctionT x ( addPotential argT ( IntLit c ) ) resT 0
typeApplySolution :: Solution -> RType -> RType
typeApplySolution sol = first (applySolution sol)
allRefinementsOf :: RSchema -> [Formula]
allRefinementsOf sch = allRefinementsOf' $ toMonotype sch
allRefinementsOf' (ScalarT _ ref _) = [ref]
allRefinementsOf' (FunctionT _ argT resT _) = allRefinementsOf' argT ++ allRefinementsOf' resT
allRefinementsOf' _ = error "allRefinementsOf called on contextual or any type"
allRFormulas :: Map Id [Bool] -> RType -> [Formula]
allRFormulas flagMap t =
let concretePotentials = bifoldMap (const []) (: []) t
abstractPotentials = allAbstractPotentials flagMap t
in concretePotentials ++ abstractPotentials
allAbstractPotentials :: Map Id [Bool] -> RType -> [Formula]
allAbstractPotentials flagMap (ScalarT b _ pot) = allAbstractPotentialsBase flagMap b
allAbstractPotentials flagMap (FunctionT _ argT resT _) = allAbstractPotentials flagMap argT ++ allAbstractPotentials flagMap resT
allAbstractPotentials flagMap (LetT _ tDef tBody) = allAbstractPotentials flagMap tDef ++ allAbstractPotentials flagMap tBody
allAbstractPotentials _ AnyT = []
allAbstractPotentialsBase :: Map Id [Bool] -> RBase -> [Formula]
allAbstractPotentialsBase flagMap (DatatypeT dt ts preds) =
case Map.lookup dt flagMap of
Nothing -> error $ "allAbstractPotentialsBase: datatype " ++ dt ++ " not found"
Just rflags -> catMaybes $ zipWith (\isRes pred -> if isRes then Just pred else Nothing) rflags preds
allAbstractPotentialsBase _ _ = []
allArgSorts :: RType -> [Sort]
allArgSorts (FunctionT _ (ScalarT b _ _) resT _) = toSort b : allArgSorts resT
allArgSorts FunctionT{} = error "allArgSorts: Non-scalar type in argument position"
allArgSorts ScalarT{} = []
allArgSorts LetT{} = error "allArgSorts: contextual type"
resultSort :: RType -> Sort
resultSort (FunctionT _ _ resT _) = resultSort resT
resultSort (ScalarT b _ _) = toSort b
isDataType DatatypeT{} = True
isDataType _ = False
getConditional :: RType -> Maybe Formula
getConditional (ScalarT _ _ f@(Ite g _ _)) = Just f
getConditional _ = Nothing
removePotentialSch :: RSchema -> RSchema
removePotentialSch = fmap removePotential
removePotential (ScalarT b r _) = ScalarT (removePotentialBase b) r fzero
removePotential (FunctionT x arg res c) = FunctionT x (removePotential arg) (removePotential res) 0
removePotential t = t
removePotentialBase (DatatypeT x ts ps) = DatatypeT x (map removePotential ts) ps
removePotentialBase b = b
emptySetCtor = "Emptyset"
singletonCtor = "Singleton"
insertSetCtor = "Insert"
setTypeName = "DSet"
setTypeVar = "setTypeVar"
|
c8a63520019d5956c6b542da196daff6ce6fae50fcb17d7fb8682e85b0ff632a | mikera/alchemy | dungeon.clj | (ns mikera.alchemy.dungeon
(:use mikera.orculje.core)
(:use mikera.orculje.util)
(:use mikera.cljutils.error)
(:import [mikera.util Rand])
(:require [mikera.cljutils.find :as find])
(:require [mikera.alchemy.lib :as lib])
(:require [mikera.orculje.mapmaker :as mm]))
(defmacro and-as-> [expr sym & body]
`(as-> ~expr ~sym
~@(map (fn [b] `(and ~sym ~b)) (butlast body))
~(last body)))
(defn maybe-place-thing
([game l1 l2 t]
(or (and t (mm/place-thing game l1 l2 t))
game)))
(defn ensure-door
([game loc]
(if (seq (get-things game loc))
game
(maybe-place-thing game loc loc (lib/create game "[:is-door]")))))
(defn ensure-doors [game room]
(reduce
ensure-door
game
(:connections room)))
(defn decorate-lair [game room]
(let [lmin (:lmin room)
lmax (:lmax room)]
(let [mtype (Rand/pick ["[:is-undead]" "[:is-creature]" "[:is-goblinoid]" "[:is-snake]"])]
(as-> game game
(mm/scatter-things game lmin lmax (Rand/d 10) (lib/create game "[:is-item]" (- (lmin 2))))
(mm/scatter-things game lmin lmax (Rand/d 2 6) (lib/create game mtype (- (lmin 2))))))))
(defn decorate-store-room [game room type]
(let [lmin (:lmin room)
lmax (:lmax room)]
(mm/scatter-things game lmin lmax (Rand/d 10) #(lib/create game type))))
(defn decorate-lab [game room]
(let [lmin (:lmin room) lmax (:lmax room)]
(and-as-> game game
(maybe-place-thing game (loc-add lmin 1 1 0) (loc-add lmax -1 -1 0)
(lib/create game "[:is-apparatus]"))
(mm/scatter-things game lmin lmax (Rand/d 4) #(lib/create game "[:is-potion]")))))
(defn decorate-fountain-room [game room]
(let [lmin (:lmin room) lmax (:lmax room)]
(and-as-> game game
(maybe-place-thing game (loc-add lmin 1 1 0) (loc-add lmax -1 -1 0)
(lib/create game "[:is-fountain]"))
(mm/fill-block game lmin lmax (lib/create game "moss floor"))
(mm/scatter-things game lmin lmax (Rand/d 8) #(lib/create game "[:is-herb]")))))
(defn decorate-normal-room [game room]
(let [lmin (:lmin room)
lmax (:lmax room)]
(and-as-> game game
(if (Rand/chance 0.3) (maybe-place-thing game (loc-add lmin 1 1 0) (loc-add lmax -1 -1 0)
(lib/create game "[:is-decoration]" (- (lmin 2)))) game)
(if (Rand/chance 0.5) (maybe-place-thing game lmin lmax (lib/create game "[:is-creature]" (- (lmin 2)))) game)
(if (Rand/chance 0.5) (maybe-place-thing game lmin lmax (lib/create game "[:is-item]" (- (lmin 2)))) game)
)))
(defn decorate-designer-room [game room]
(let [lmin (:lmin room)
lmax (:lmax room)
[x1 y1 z] lmin
[x2 y2 z] lmax]
(cond
(Rand/chance 0.3)
(decorate-fountain-room game room)
(Rand/chance 0.3)
(let [pillar (Rand/pick ["wall" "pillar"])]
(as-> game game
(set-tile game (loc (inc x1) (inc y1) z) (lib/create game pillar))
(set-tile game (loc (dec x2) (inc y1) z) (lib/create game pillar))
(set-tile game (loc (inc x1) (dec y2) z) (lib/create game pillar))
(set-tile game (loc (dec x2) (dec y2) z) (lib/create game pillar))))
:else
(mm/fill-block game
(loc (inc x1) (inc y1) z)
(loc (dec x2) (dec y2) z)
(lib/create game (Rand/pick ["murky pool" "shallow pool" "deep pool" "magma pool"]))))))
(defn decorate-room [game room]
(and-as-> game game
(cond
(Rand/chance 0.06)
(decorate-lair game room)
(Rand/chance 0.3)
(decorate-normal-room game room)
(Rand/chance 0.15)
(decorate-store-room game room (Rand/pick ["[:is-food]" "[:is-potion]" "[:is-mushroom]" "[:is-ingredient]" "[:is-herb]"]))
(Rand/chance 0.07)
(decorate-lab game room)
(Rand/chance 0.2)
(decorate-designer-room game room)
:else
;; an empty room
game)
(ensure-doors game room)))
(defn decorate-rooms [game]
(reduce
decorate-room
game
(:rooms game)))
(defn generate-room [game ^mikera.orculje.engine.Location lmin
^mikera.orculje.engine.Location lmax
connections]
(let [[x1 y1 z] lmin
[x2 y2 z] lmax]
(and-as-> game game
(mm/fill-block game (loc (dec x1) (dec y1) z) (loc (inc x2) (inc y2) z) (lib/create game "wall"))
(mm/fill-block game lmin lmax (lib/create game "floor"))
(assoc game :rooms (conj (or (:rooms game) []) {:lmin lmin :lmax lmax :connections connections}))
(reduce (fn [game con]
(mm/fill-block game con con (lib/create game "floor"))) game connections))))
(def TUNNEL-DIRS [(loc 1 0 0) (loc -1 0 0) (loc 0 1 0)(loc 0 -1 0)])
(defn generate-tunnel
[game ^mikera.orculje.engine.Location lmin
^mikera.orculje.engine.Location lmax
^mikera.orculje.engine.Location lfrom
^mikera.orculje.engine.Location lto
type]
(if (= lfrom lto)
(mm/fill-block game lfrom lfrom (lib/create game "cave floor"))
(let [game (mm/fill-block game lfrom lfrom (lib/create game type))
dir (if (Rand/chance 0.3)
(Rand/pick TUNNEL-DIRS)
(if (Rand/chance 0.5)
(loc 0 (Math/signum (double (- (.y lto) (.y lfrom)))) 0)
(loc (Math/signum (double (- (.x lto) (.x lfrom)))) 0 0)))
nloc (loc-bound lmin lmax (loc-add dir lfrom))]
(recur game lmin lmax nloc lto type))))
(defn generate-caves [game ^mikera.orculje.engine.Location lmin
^mikera.orculje.engine.Location lmax
connections]
(let [cloc (rand-loc lmin lmax)]
(and-as-> game game
(reduce
(fn [game c] (generate-tunnel game lmin lmax (loc-bound lmin lmax c) cloc "cave floor"))
game
connections)
(reduce (fn [game con]
(mm/fill-block game con con (lib/create game "cave floor"))) game connections)
(if (and (== 1 (count connections)) (Rand/chance 0.5))
(maybe-place-thing game cloc cloc (lib/create game "[:is-item]" (- (lmin 2))))
game))))
(defn generate-grid-corridor [game
^mikera.orculje.engine.Location lmin
^mikera.orculje.engine.Location lmax]
(let [[x1 y1 z] lmin [x2 y2 z] lmax
lp (if (Rand/chance 0.5) (loc x1 y2 z) (loc x2 y1 z))]
(as-> game game
(mm/fill-block game lmin lp (lib/create game "floor"))
(mm/fill-block game lp lmax (lib/create game "floor")))))
(defn generate-grid [game ^mikera.orculje.engine.Location lmin
^mikera.orculje.engine.Location lmax
connections]
(let [[x1 y1 z] lmin [x2 y2 z] lmax
cloc (rand-loc lmin lmax)]
(and-as-> game game
(mm/fill-block game lmin lmax (lib/create game (Rand/pick ["rock wall" "wall"])))
(reduce
(fn [game c]
(generate-grid-corridor game (loc-bound lmin lmax c) cloc))
game
connections)
(reduce (fn [game con]
(mm/fill-block game con con (lib/create game "floor"))) game connections))))
(defn generate-block [game ^mikera.orculje.engine.Location lmin
^mikera.orculje.engine.Location lmax
connections]
(or-loop [10]
(cond
(Rand/chance 0.3) (generate-caves game lmin lmax connections)
(Rand/chance 0.1) (generate-grid game lmin lmax connections)
:else (generate-room game lmin lmax connections))))
(defn find-split [split-dir lmin lmax connections]
(let [[x1 y1 z] lmin
[x2 y2 z] lmax
w (inc (- x2 x1))
h (inc (- y2 y1))
sw (if (== 0 split-dir) w h)
sw2 (quot sw 2)]
(or-loop [20]
(let [split-point (+ 3 (Rand/r (- sw sw2 3)) (Rand/r (- sw2 3)))
split-val (+ split-point (lmin split-dir))]
(if (some (fn [^mikera.orculje.engine.Location l] (== split-val (nth l split-dir))) connections)
nil
split-point)))))
(def MAX_BLOCK_SIZE 16)
(def MIN_ZONE_SIZE 7)
(defn generate-zone [game ^mikera.orculje.engine.Location lmin
^mikera.orculje.engine.Location lmax
connections]
;; (println connections)
(let [[x1 y1 z] lmin
[x2 y2 z] lmax
w (long (inc (- x2 x1)))
h (long (inc (- y2 y1)))
split-dir (if (Rand/chance 0.8)
(if (> w h) 0 1)
(if (Rand/chance (double (/ w (+ w h)))) 0 1)) ;; prefer split on longer dimension....
conw (if (== 0 split-dir) h w) ;; width of connecting wall
]
(if (or (< w MIN_ZONE_SIZE)
(< h MIN_ZONE_SIZE)
(and (Rand/chance 0.5) (< w MAX_BLOCK_SIZE) (< h MAX_BLOCK_SIZE)))
(and game (generate-block game lmin lmax connections))
(if-let [split-point (find-split split-dir lmin lmax connections)]
(let [smax (if (== 0 split-dir)
(loc (+ x1 (dec split-point)) y2 z)
(loc x2 (+ y1 (dec split-point)) z))
smin (if (== 0 split-dir)
(loc (+ x1 (inc split-point)) y1 z)
(loc x1 (+ y1 (inc split-point)) z))
new-con (if (== split-dir 0)
(loc (+ x1 split-point) (+ y1 (Rand/r h)) z)
(loc (+ x1 (Rand/r w)) (+ y1 split-point) z))
new-con2 (if (== split-dir 0)
(loc (+ x1 split-point) (+ y1 (Rand/r h)) z)
(loc (+ x1 (Rand/r w)) (+ y1 split-point) z))
new-cons (if (and (> (* conw (Rand/nextDouble)) 10)
(< 1 (loc-dist-manhattan new-con new-con2)))
[new-con new-con2]
[new-con])]
(and-as-> game game
(or-loop [3] (generate-zone game lmin smax
(concat new-cons (find/eager-filter #(loc-within? (loc-dec lmin) (loc-inc smax) %) connections))))
(or-loop [3] (generate-zone game smin lmax
(concat new-cons (find/eager-filter #(loc-within? (loc-dec smin) (loc-inc lmax) %) connections) )))))))))
(defn generate-level [game ^mikera.orculje.engine.Location lmin
^mikera.orculje.engine.Location lmax]
(let [[x1 y1 z] lmin
[x2 y2 z] lmax]
(as-> game game
(generate-tunnel game lmin lmax (rand-loc lmin lmax) (rand-loc lmin lmax) "underground stream")
(or-loop [5]
(generate-zone game lmin lmax [])))))
(defn generate-region [game ^mikera.orculje.engine.Location lmin
^mikera.orculje.engine.Location lmax]
(let [[x1 y1 z1] lmin
[x2 y2 z2] lmax]
(and-as-> game game
(reduce
(fn [game i ]
(and game (or-loop [3]
(generate-level game (loc x1 y1 i) (loc x2 y2 i)))))
game
(range z1 (inc z2))))))
(defn connect-levels
([game lmin lmax]
(let [[x1 y1 z1] lmin
[x2 y2 z2] lmax]
(and-as-> game game
(reduce
(fn [game i ]
(or-loop [1000]
(let [x (Rand/range x1 x2)
y (Rand/range y1 y2)]
(and game (connect-levels game (loc x y i) (loc x y (inc i)) :link)))))
game
(range z1 z2)))))
([game lmin lmax _]
(and-as-> game game
(if (and game (not (get-blocking game lmin)) (not (seq (get-things game lmin))))
(add-thing game lmin (lib/create game "up staircase")))
(if (and game (not (get-blocking game lmax)) (not (seq (get-things game lmax))))
(add-thing game lmax (lib/create game "down staircase"))))))
(defn place-exit-staircase [game lmin lmax]
(let [[x1 y1 z1] lmin
[x2 y2 z2] lmax]
(as-> game game
(or
(or-loop [1000] (mm/place-thing game (loc x1 y1 z2) lmax (lib/create game "exit staircase")))
(error "Can't place exit staircase!!"))
(assoc game :start-location (location game (:last-added-id game))))))
(def DUNGEON_MIN (loc -35 -25 -11))
(def DUNGEON_MAX (loc 35 25 -1))
(def OBJECTIVE_LEVEL -10)
(defn place-philosophers-stone [game lmin lmax]
(let [[x1 y1 z1] lmin
[x2 y2 z2] lmax]
(as-> game game
(or
(or-loop [1000] (mm/place-thing game (loc x1 y1 OBJECTIVE_LEVEL) (loc x2 y2 OBJECTIVE_LEVEL) (lib/create game "The Philosopher's Stone")))
(error "Can't place philosopher's stone!!")))))
(defn generate-dungeon
"Attempts to generate dungeon. May return nil on failure"
[game]
(let [lmin DUNGEON_MIN
lmax DUNGEON_MAX]
(and-as-> game game
(assoc game :volume {:min lmin :max lmax})
(mm/fill-block game (loc-dec lmin) (loc-inc lmax) (lib/create game "rock wall"))
(generate-region game lmin lmax )
(place-exit-staircase game lmin lmax)
(place-philosophers-stone game lmin lmax)
(decorate-rooms game)
(connect-levels game lmin lmax)
(connect-levels game lmin lmax))))
(defn generate
"Main dungeon generation algorithm. Retry if generation fails!"
[game]
(let []
(loop [game game i 100]
(or (generate-dungeon game)
(when (> i 0)
(println "Retrying map generation: " i)
(recur game (dec i))))))) | null | https://raw.githubusercontent.com/mikera/alchemy/57d47eea6ecbef20e97c9a360b57d50985039bf0/src/main/clojure/mikera/alchemy/dungeon.clj | clojure | an empty room
(println connections)
prefer split on longer dimension....
width of connecting wall | (ns mikera.alchemy.dungeon
(:use mikera.orculje.core)
(:use mikera.orculje.util)
(:use mikera.cljutils.error)
(:import [mikera.util Rand])
(:require [mikera.cljutils.find :as find])
(:require [mikera.alchemy.lib :as lib])
(:require [mikera.orculje.mapmaker :as mm]))
(defmacro and-as-> [expr sym & body]
`(as-> ~expr ~sym
~@(map (fn [b] `(and ~sym ~b)) (butlast body))
~(last body)))
(defn maybe-place-thing
([game l1 l2 t]
(or (and t (mm/place-thing game l1 l2 t))
game)))
(defn ensure-door
([game loc]
(if (seq (get-things game loc))
game
(maybe-place-thing game loc loc (lib/create game "[:is-door]")))))
(defn ensure-doors [game room]
(reduce
ensure-door
game
(:connections room)))
(defn decorate-lair [game room]
(let [lmin (:lmin room)
lmax (:lmax room)]
(let [mtype (Rand/pick ["[:is-undead]" "[:is-creature]" "[:is-goblinoid]" "[:is-snake]"])]
(as-> game game
(mm/scatter-things game lmin lmax (Rand/d 10) (lib/create game "[:is-item]" (- (lmin 2))))
(mm/scatter-things game lmin lmax (Rand/d 2 6) (lib/create game mtype (- (lmin 2))))))))
(defn decorate-store-room [game room type]
(let [lmin (:lmin room)
lmax (:lmax room)]
(mm/scatter-things game lmin lmax (Rand/d 10) #(lib/create game type))))
(defn decorate-lab [game room]
(let [lmin (:lmin room) lmax (:lmax room)]
(and-as-> game game
(maybe-place-thing game (loc-add lmin 1 1 0) (loc-add lmax -1 -1 0)
(lib/create game "[:is-apparatus]"))
(mm/scatter-things game lmin lmax (Rand/d 4) #(lib/create game "[:is-potion]")))))
(defn decorate-fountain-room [game room]
(let [lmin (:lmin room) lmax (:lmax room)]
(and-as-> game game
(maybe-place-thing game (loc-add lmin 1 1 0) (loc-add lmax -1 -1 0)
(lib/create game "[:is-fountain]"))
(mm/fill-block game lmin lmax (lib/create game "moss floor"))
(mm/scatter-things game lmin lmax (Rand/d 8) #(lib/create game "[:is-herb]")))))
(defn decorate-normal-room [game room]
(let [lmin (:lmin room)
lmax (:lmax room)]
(and-as-> game game
(if (Rand/chance 0.3) (maybe-place-thing game (loc-add lmin 1 1 0) (loc-add lmax -1 -1 0)
(lib/create game "[:is-decoration]" (- (lmin 2)))) game)
(if (Rand/chance 0.5) (maybe-place-thing game lmin lmax (lib/create game "[:is-creature]" (- (lmin 2)))) game)
(if (Rand/chance 0.5) (maybe-place-thing game lmin lmax (lib/create game "[:is-item]" (- (lmin 2)))) game)
)))
(defn decorate-designer-room [game room]
(let [lmin (:lmin room)
lmax (:lmax room)
[x1 y1 z] lmin
[x2 y2 z] lmax]
(cond
(Rand/chance 0.3)
(decorate-fountain-room game room)
(Rand/chance 0.3)
(let [pillar (Rand/pick ["wall" "pillar"])]
(as-> game game
(set-tile game (loc (inc x1) (inc y1) z) (lib/create game pillar))
(set-tile game (loc (dec x2) (inc y1) z) (lib/create game pillar))
(set-tile game (loc (inc x1) (dec y2) z) (lib/create game pillar))
(set-tile game (loc (dec x2) (dec y2) z) (lib/create game pillar))))
:else
(mm/fill-block game
(loc (inc x1) (inc y1) z)
(loc (dec x2) (dec y2) z)
(lib/create game (Rand/pick ["murky pool" "shallow pool" "deep pool" "magma pool"]))))))
(defn decorate-room [game room]
(and-as-> game game
(cond
(Rand/chance 0.06)
(decorate-lair game room)
(Rand/chance 0.3)
(decorate-normal-room game room)
(Rand/chance 0.15)
(decorate-store-room game room (Rand/pick ["[:is-food]" "[:is-potion]" "[:is-mushroom]" "[:is-ingredient]" "[:is-herb]"]))
(Rand/chance 0.07)
(decorate-lab game room)
(Rand/chance 0.2)
(decorate-designer-room game room)
:else
game)
(ensure-doors game room)))
(defn decorate-rooms [game]
(reduce
decorate-room
game
(:rooms game)))
(defn generate-room [game ^mikera.orculje.engine.Location lmin
^mikera.orculje.engine.Location lmax
connections]
(let [[x1 y1 z] lmin
[x2 y2 z] lmax]
(and-as-> game game
(mm/fill-block game (loc (dec x1) (dec y1) z) (loc (inc x2) (inc y2) z) (lib/create game "wall"))
(mm/fill-block game lmin lmax (lib/create game "floor"))
(assoc game :rooms (conj (or (:rooms game) []) {:lmin lmin :lmax lmax :connections connections}))
(reduce (fn [game con]
(mm/fill-block game con con (lib/create game "floor"))) game connections))))
(def TUNNEL-DIRS [(loc 1 0 0) (loc -1 0 0) (loc 0 1 0)(loc 0 -1 0)])
(defn generate-tunnel
[game ^mikera.orculje.engine.Location lmin
^mikera.orculje.engine.Location lmax
^mikera.orculje.engine.Location lfrom
^mikera.orculje.engine.Location lto
type]
(if (= lfrom lto)
(mm/fill-block game lfrom lfrom (lib/create game "cave floor"))
(let [game (mm/fill-block game lfrom lfrom (lib/create game type))
dir (if (Rand/chance 0.3)
(Rand/pick TUNNEL-DIRS)
(if (Rand/chance 0.5)
(loc 0 (Math/signum (double (- (.y lto) (.y lfrom)))) 0)
(loc (Math/signum (double (- (.x lto) (.x lfrom)))) 0 0)))
nloc (loc-bound lmin lmax (loc-add dir lfrom))]
(recur game lmin lmax nloc lto type))))
(defn generate-caves [game ^mikera.orculje.engine.Location lmin
^mikera.orculje.engine.Location lmax
connections]
(let [cloc (rand-loc lmin lmax)]
(and-as-> game game
(reduce
(fn [game c] (generate-tunnel game lmin lmax (loc-bound lmin lmax c) cloc "cave floor"))
game
connections)
(reduce (fn [game con]
(mm/fill-block game con con (lib/create game "cave floor"))) game connections)
(if (and (== 1 (count connections)) (Rand/chance 0.5))
(maybe-place-thing game cloc cloc (lib/create game "[:is-item]" (- (lmin 2))))
game))))
(defn generate-grid-corridor [game
^mikera.orculje.engine.Location lmin
^mikera.orculje.engine.Location lmax]
(let [[x1 y1 z] lmin [x2 y2 z] lmax
lp (if (Rand/chance 0.5) (loc x1 y2 z) (loc x2 y1 z))]
(as-> game game
(mm/fill-block game lmin lp (lib/create game "floor"))
(mm/fill-block game lp lmax (lib/create game "floor")))))
(defn generate-grid [game ^mikera.orculje.engine.Location lmin
^mikera.orculje.engine.Location lmax
connections]
(let [[x1 y1 z] lmin [x2 y2 z] lmax
cloc (rand-loc lmin lmax)]
(and-as-> game game
(mm/fill-block game lmin lmax (lib/create game (Rand/pick ["rock wall" "wall"])))
(reduce
(fn [game c]
(generate-grid-corridor game (loc-bound lmin lmax c) cloc))
game
connections)
(reduce (fn [game con]
(mm/fill-block game con con (lib/create game "floor"))) game connections))))
(defn generate-block [game ^mikera.orculje.engine.Location lmin
^mikera.orculje.engine.Location lmax
connections]
(or-loop [10]
(cond
(Rand/chance 0.3) (generate-caves game lmin lmax connections)
(Rand/chance 0.1) (generate-grid game lmin lmax connections)
:else (generate-room game lmin lmax connections))))
(defn find-split [split-dir lmin lmax connections]
(let [[x1 y1 z] lmin
[x2 y2 z] lmax
w (inc (- x2 x1))
h (inc (- y2 y1))
sw (if (== 0 split-dir) w h)
sw2 (quot sw 2)]
(or-loop [20]
(let [split-point (+ 3 (Rand/r (- sw sw2 3)) (Rand/r (- sw2 3)))
split-val (+ split-point (lmin split-dir))]
(if (some (fn [^mikera.orculje.engine.Location l] (== split-val (nth l split-dir))) connections)
nil
split-point)))))
(def MAX_BLOCK_SIZE 16)
(def MIN_ZONE_SIZE 7)
(defn generate-zone [game ^mikera.orculje.engine.Location lmin
^mikera.orculje.engine.Location lmax
connections]
(let [[x1 y1 z] lmin
[x2 y2 z] lmax
w (long (inc (- x2 x1)))
h (long (inc (- y2 y1)))
split-dir (if (Rand/chance 0.8)
(if (> w h) 0 1)
]
(if (or (< w MIN_ZONE_SIZE)
(< h MIN_ZONE_SIZE)
(and (Rand/chance 0.5) (< w MAX_BLOCK_SIZE) (< h MAX_BLOCK_SIZE)))
(and game (generate-block game lmin lmax connections))
(if-let [split-point (find-split split-dir lmin lmax connections)]
(let [smax (if (== 0 split-dir)
(loc (+ x1 (dec split-point)) y2 z)
(loc x2 (+ y1 (dec split-point)) z))
smin (if (== 0 split-dir)
(loc (+ x1 (inc split-point)) y1 z)
(loc x1 (+ y1 (inc split-point)) z))
new-con (if (== split-dir 0)
(loc (+ x1 split-point) (+ y1 (Rand/r h)) z)
(loc (+ x1 (Rand/r w)) (+ y1 split-point) z))
new-con2 (if (== split-dir 0)
(loc (+ x1 split-point) (+ y1 (Rand/r h)) z)
(loc (+ x1 (Rand/r w)) (+ y1 split-point) z))
new-cons (if (and (> (* conw (Rand/nextDouble)) 10)
(< 1 (loc-dist-manhattan new-con new-con2)))
[new-con new-con2]
[new-con])]
(and-as-> game game
(or-loop [3] (generate-zone game lmin smax
(concat new-cons (find/eager-filter #(loc-within? (loc-dec lmin) (loc-inc smax) %) connections))))
(or-loop [3] (generate-zone game smin lmax
(concat new-cons (find/eager-filter #(loc-within? (loc-dec smin) (loc-inc lmax) %) connections) )))))))))
(defn generate-level [game ^mikera.orculje.engine.Location lmin
^mikera.orculje.engine.Location lmax]
(let [[x1 y1 z] lmin
[x2 y2 z] lmax]
(as-> game game
(generate-tunnel game lmin lmax (rand-loc lmin lmax) (rand-loc lmin lmax) "underground stream")
(or-loop [5]
(generate-zone game lmin lmax [])))))
(defn generate-region [game ^mikera.orculje.engine.Location lmin
^mikera.orculje.engine.Location lmax]
(let [[x1 y1 z1] lmin
[x2 y2 z2] lmax]
(and-as-> game game
(reduce
(fn [game i ]
(and game (or-loop [3]
(generate-level game (loc x1 y1 i) (loc x2 y2 i)))))
game
(range z1 (inc z2))))))
(defn connect-levels
([game lmin lmax]
(let [[x1 y1 z1] lmin
[x2 y2 z2] lmax]
(and-as-> game game
(reduce
(fn [game i ]
(or-loop [1000]
(let [x (Rand/range x1 x2)
y (Rand/range y1 y2)]
(and game (connect-levels game (loc x y i) (loc x y (inc i)) :link)))))
game
(range z1 z2)))))
([game lmin lmax _]
(and-as-> game game
(if (and game (not (get-blocking game lmin)) (not (seq (get-things game lmin))))
(add-thing game lmin (lib/create game "up staircase")))
(if (and game (not (get-blocking game lmax)) (not (seq (get-things game lmax))))
(add-thing game lmax (lib/create game "down staircase"))))))
(defn place-exit-staircase [game lmin lmax]
(let [[x1 y1 z1] lmin
[x2 y2 z2] lmax]
(as-> game game
(or
(or-loop [1000] (mm/place-thing game (loc x1 y1 z2) lmax (lib/create game "exit staircase")))
(error "Can't place exit staircase!!"))
(assoc game :start-location (location game (:last-added-id game))))))
(def DUNGEON_MIN (loc -35 -25 -11))
(def DUNGEON_MAX (loc 35 25 -1))
(def OBJECTIVE_LEVEL -10)
(defn place-philosophers-stone [game lmin lmax]
(let [[x1 y1 z1] lmin
[x2 y2 z2] lmax]
(as-> game game
(or
(or-loop [1000] (mm/place-thing game (loc x1 y1 OBJECTIVE_LEVEL) (loc x2 y2 OBJECTIVE_LEVEL) (lib/create game "The Philosopher's Stone")))
(error "Can't place philosopher's stone!!")))))
(defn generate-dungeon
"Attempts to generate dungeon. May return nil on failure"
[game]
(let [lmin DUNGEON_MIN
lmax DUNGEON_MAX]
(and-as-> game game
(assoc game :volume {:min lmin :max lmax})
(mm/fill-block game (loc-dec lmin) (loc-inc lmax) (lib/create game "rock wall"))
(generate-region game lmin lmax )
(place-exit-staircase game lmin lmax)
(place-philosophers-stone game lmin lmax)
(decorate-rooms game)
(connect-levels game lmin lmax)
(connect-levels game lmin lmax))))
(defn generate
"Main dungeon generation algorithm. Retry if generation fails!"
[game]
(let []
(loop [game game i 100]
(or (generate-dungeon game)
(when (> i 0)
(println "Retrying map generation: " i)
(recur game (dec i))))))) |
8ad5081f341116bdbe7f036009e55cda2568ed705571ce9ac2ace6b53d3c777b | eugeneia/athens | test.lisp | ;; test.lisp
(defpackage :garbage-pools.test
(:use #:cl #:garbage-pools #:lift)
(:nicknames #:gp.test)
(:export #:run-garbage-pools-tests))
(in-package #:garbage-pools.test)
(deftestsuite garbage-pools-test () ())
;;; test-cleanup-pool
(addtest (garbage-pools-test)
test-cleanup-pool
(ensure-same '(1 2 3 4)
(let ((list nil)
(pool (make-instance 'pool)))
(loop for x from 1 to 4 do
(cleanup-register x (lambda (obj) (push obj list)) pool))
(cleanup-pool pool)
list)))
;;; test-with-garbage-pool-1
(addtest (garbage-pools-test)
test-with-cleanup-pool-1
(ensure-same '(1 2 3 4 5)
(let ((list nil))
(with-garbage-pool ()
(loop for x from 1 to 5 do
(cleanup-register x (lambda (obj) (push obj list)))))
list)))
;;; test-with-cleanup-pool-2
(addtest (garbage-pools-test)
test-with-cleanup-pool-2
(ensure-same '(1 2 3 4 5)
(let ((list nil))
(with-garbage-pool (mypool)
(loop for x from 1 to 5 do
(cleanup-register x (lambda (obj) (push obj list)) mypool)))
list)))
;;; test-cleanup-object-1
(addtest (garbage-pools-test)
test-cleanup-object-1
(ensure-same '((3 . 3) (1 . 1))
(let ((res nil)
(res2 nil)
(data '((0 . 0) (1 . 1) (2 . 2) (3 . 3) (4 . 4))))
(with-garbage-pool ()
(loop for x in data do
(cleanup-register x (lambda (obj) (push obj res))))
(cleanup-object (nth 1 data))
(cleanup-object (nth 3 data))
(setq res2 res)
(setq res nil))
res2)))
;;; test-cleanup-object-2
(addtest (garbage-pools-test)
test-cleanup-object-2
(ensure-same '((0 . 0) (2 . 2) (4 . 4))
(let ((res nil)
(data '((0 . 0) (1 . 1) (2 . 2) (3 . 3) (4 . 4))))
(with-garbage-pool ()
(loop for x in data do
(cleanup-register x (lambda (obj) (push obj res))))
(cleanup-object (nth 1 data))
(cleanup-object (nth 3 data))
(setq res nil))
res)))
;;; test-object-register-and-defcleanup
(defclass test-class ()
((content :initarg :content :initform nil :accessor content)))
(defvar *cesspool*)
(defcleanup test-class (lambda (obj) (push (content obj) *cesspool*)))
(addtest (garbage-pools-test)
test-object-register-and-defcleanup-1
(ensure-same '("Hello" "world")
(let ((*cesspool* nil))
(with-garbage-pool ()
(object-register (make-instance 'test-class :content "Hello"))
(object-register (make-instance 'test-class :content "world")))
*cesspool*)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; run-garbage-pools-tests
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun run-garbage-pools-tests ()
(run-tests :suite 'garbage-pools-test)) | null | https://raw.githubusercontent.com/eugeneia/athens/cc9d456edd3891b764b0fbf0202a3e2f58865cbf/quicklisp/dists/quicklisp/software/garbage-pools-20130720-git/test.lisp | lisp | test.lisp
test-cleanup-pool
test-with-garbage-pool-1
test-with-cleanup-pool-2
test-cleanup-object-1
test-cleanup-object-2
test-object-register-and-defcleanup
run-garbage-pools-tests
|
(defpackage :garbage-pools.test
(:use #:cl #:garbage-pools #:lift)
(:nicknames #:gp.test)
(:export #:run-garbage-pools-tests))
(in-package #:garbage-pools.test)
(deftestsuite garbage-pools-test () ())
(addtest (garbage-pools-test)
test-cleanup-pool
(ensure-same '(1 2 3 4)
(let ((list nil)
(pool (make-instance 'pool)))
(loop for x from 1 to 4 do
(cleanup-register x (lambda (obj) (push obj list)) pool))
(cleanup-pool pool)
list)))
(addtest (garbage-pools-test)
test-with-cleanup-pool-1
(ensure-same '(1 2 3 4 5)
(let ((list nil))
(with-garbage-pool ()
(loop for x from 1 to 5 do
(cleanup-register x (lambda (obj) (push obj list)))))
list)))
(addtest (garbage-pools-test)
test-with-cleanup-pool-2
(ensure-same '(1 2 3 4 5)
(let ((list nil))
(with-garbage-pool (mypool)
(loop for x from 1 to 5 do
(cleanup-register x (lambda (obj) (push obj list)) mypool)))
list)))
(addtest (garbage-pools-test)
test-cleanup-object-1
(ensure-same '((3 . 3) (1 . 1))
(let ((res nil)
(res2 nil)
(data '((0 . 0) (1 . 1) (2 . 2) (3 . 3) (4 . 4))))
(with-garbage-pool ()
(loop for x in data do
(cleanup-register x (lambda (obj) (push obj res))))
(cleanup-object (nth 1 data))
(cleanup-object (nth 3 data))
(setq res2 res)
(setq res nil))
res2)))
(addtest (garbage-pools-test)
test-cleanup-object-2
(ensure-same '((0 . 0) (2 . 2) (4 . 4))
(let ((res nil)
(data '((0 . 0) (1 . 1) (2 . 2) (3 . 3) (4 . 4))))
(with-garbage-pool ()
(loop for x in data do
(cleanup-register x (lambda (obj) (push obj res))))
(cleanup-object (nth 1 data))
(cleanup-object (nth 3 data))
(setq res nil))
res)))
(defclass test-class ()
((content :initarg :content :initform nil :accessor content)))
(defvar *cesspool*)
(defcleanup test-class (lambda (obj) (push (content obj) *cesspool*)))
(addtest (garbage-pools-test)
test-object-register-and-defcleanup-1
(ensure-same '("Hello" "world")
(let ((*cesspool* nil))
(with-garbage-pool ()
(object-register (make-instance 'test-class :content "Hello"))
(object-register (make-instance 'test-class :content "world")))
*cesspool*)))
(defun run-garbage-pools-tests ()
(run-tests :suite 'garbage-pools-test)) |
f9664a4e4233bb067311a5f8ffbd16ddb38f62c5d854042156ccce3f29806307 | nboldi/c-parser-in-haskell | MiniC.hs | # LANGUAGE FlexibleContexts , MultiParamTypeClasses , TypeOperators , TupleSections #
-- | Tests for the C parser
module MiniC where
import MiniC.ParseProgram
import MiniC.Parser
import MiniC.Parser.Lexical
import MiniC.Parser.Base hiding (tuple)
import MiniC.AST
import MiniC.MiniCPP
import MiniC.Semantics
import MiniC.SymbolTable
import MiniC.Representation
import MiniC.Helpers
import MiniC.Instances
import MiniC.PrettyPrint
import MiniC.SourceNotation
import MiniC.TransformInfo
import Text.Preprocess.Parser
import SourceCode.ToSourceTree (ToSourceRose)
import SourceCode.SourceInfo (noNodeInfo)
import SourceCode.ASTElems
import GHC.Generics
import Text.Parsec
import Text.Parsec.Error
import Text.Preprocess.Rewrites
import Debug.Trace
import Data.SmartTrav
import Data.Maybe
import Data.Map(fromList)
import Data.Function
import Data.Either.Combinators
import Control.Arrow
import Control.Applicative hiding ((<|>), many)
import Control.Lens
import Control.Monad
import Control.Monad.Reader
import System.IO.Unsafe (unsafePerformIO)
import System.Timeout
import System.FilePath
import System.Directory
import Test.HUnit hiding (test)
import Test.HUnit.Find
test = tests >>= runTestTT
tests = do progTests <- programTests
return $ TestList
[ TestLabel "literalTests" literalTests
, TestLabel "exprTests" exprTests
, TestLabel "instrTests" instrTests
, TestLabel "typeTests" typeTests
, TestLabel "declarationTests" declarationTests
, TestLabel "stmtDeclTests" stmtDeclTests
, TestLabel "macroTests" macroTests
, TestLabel "ifTests" ifTests
, TestLabel "programTests" progTests
]
-- * Literal tests
literalTests = TestList $ map (\lit -> TestLabel lit $ TestCase (assertParsedAST equallyPrinted literal lit)) literals
integerLiterals = [ "1", "0", "-1", "215u", "0xFeeL", "01", "30ul", "0b011010" ]
floatLiterals = [ "0.123", "1.4324", "1e-6", "1e-6L", "0.123f", ".1E4f", "58."
, "0x1.999999999999ap-4", "0x1p-1074", "0xcc.ccccccccccdp-11" ]
charLiterals = map (\cl -> "'" ++ cl ++ "'")
[ "c", "\\n", "\\0", "\\xAA", "\\0123", "\\u00e9" ]
stringLiterals = map (\sl -> "\"" ++ sl ++ "\"")
[ "bla", "almafa\\n", "almafa\\0", "\\xAA" ]
++ ["L\"r\\u00e9sum\\u00e9\""]
compoundLiterals = [ "{}", "{ 1,2,3 }", "{ .x = 1, .y = 2 }"
, "{ [0] = 1, [2] = 3 }"
, "{ [0] = 1, 2, [2] = 3 }" ]
literals = integerLiterals
++ floatLiterals
++ charLiterals
++ stringLiterals
++ compoundLiterals
-- * Expressions tests
-- | Tests that each expression is parsed successfully and printed back the same
exprTests = TestList $ map (\expr -> TestLabel expr $ TestCase (assertEqualPrint expr)) expressions
where assertEqualPrint = assertParsedAST equallyPrinted (addVars exprVarsToAdd >> expression)
exprVarsToAdd = ["a","b","c","i","n","x","f","g","scanf","printf"]
expressions = [ "&a", "*a", "*&a++"
, "a+b", "a = c , b"
, "a += *c , b"
, "x(1)"
, "x[0]"
, "x[0][1]"
, "x[0](1)"
, "(g)()"
, "(*f)(a,b)"
, "f(a,g)"
, "a>b?a:b"
, "a?:b"
, "a>b?&a:&b"
, "(int) 1"
, "(int) a"
, "(int) (a+1)"
, "sizeof(a)"
, "sizeof(int)"
, "1+sizeof(int)"
, "sizeof( struct { int a; } )"
, "scanf(\"%d\",n)"
, "scanf(\"%d\",&n)"
, "scanf(\"%d\",a+b)"
, "printf(\"%d\",a)"
, "a[i][i].x[i]"
] ++ literals
-- * Instruction tests
-- | Tests that each statement is parsed successfully and printed back the same
instrTests
= TestList $ map (\instr -> TestLabel instr $ TestCase (assertEqualPrint instr)) instructions
where assertEqualPrint = assertParsedAST equallyPrinted (addVars instrVarsToAdd >> statement)
instrVarsToAdd = exprVarsToAdd ++ ["c","it","msg","next","sum","y"]
instructions = [ "label : a = c;"
, "a += 4;"
, "f(4); // Bazz@#&#& "
, "f( /* Bazz@#&#& */ 4);"
, "f (1);"
, "a += (b + 4);"
, "{ }"
, "{ a = b = 10; a += (b + 4); b = a - 1; }"
, "{ int a = 10; }"
, "{ int a = 10; a = 11; }"
, "{ int a = 10; a = 11; int b = 12; b += a; }"
, "if (a==4) b = 10; else { x = 0; y = 0; }"
, "if (a==4) if (b==1) c = 10;"
, "switch (x) { case 0 : msg = \"brumm\"; break; "
++ " case 1 : msg = \"brummbrumm\"; break; "
++ " default : break; "
++ "}"
, "while (x > 0) --x;"
, "while (next(it));"
, "do ++x; while (x < 100);"
, "for (i=0; i<n; ++i) { sum += i*i; }"
, "for (int i=0; i<n; ++i) { sum += i*i; }"
, "{ return 10; break; continue; }"
, "((void ( * ) (void)) 0 ) ( );"
, "asm (\"movb %bh (%eax)\");"
, "asm (\"movl %eax, %ebx\\n\\t\" \"movl $56, %esi\\n\\t\");"
, "asm (\"cld\\n\\t\" \"rep\\n\\t\" \"stosl\" : : \"c\" (count), \"a\" (fill_value), \"D\" (dest) : \"%ecx\", \"%edi\" );"
, "asm volatile (\"sidt %0\\n\" : :\"m\"(loc));"
, "return 0;"
] ++ map (++";") expressions
-- * Type tests
typeTests = TestList $ map (\typ -> TestLabel typ $ TestCase (assertEqualPrint typ)) types
where assertEqualPrint = assertParsedAST equallyPrinted (addVars typesVarsToAdd >> qualifiedType)
typesVarsToAdd = ["strlen","s1","s2","x"]
baseVarTypes = [ "void", "int", "int*"
, "int[5]", "int[]", "int*[10]"
]
varTypes = baseVarTypes ++ map (++"*") baseVarTypes
++ [ "void (*foo)(int)", "void *(*foo)(int *)", "void (*)(void)"
, "void (*) (int* (*) (int*,int), char (*) (char))"
, "int* (*) ()"
, "int* (*) (int*,int)"
, "char (*) (char)"
, "struct myType"
, "enum myType"
, "union myType"
, "char str[strlen (s1) + strlen (s2) + 1]"
, "typeof (int)"
, "typeof (int *)"
, "typeof (x[0](1))"
, "typeof (*x)"
]
funTypes = [ "void f()", "int main()", "int main(void)", "int f(int)", "int f(int a)", "int f(int,int)" ]
types = funTypes ++ varTypes
-- * Declaration tests
declarationTests = TestList $ map (\dd -> TestLabel dd $ TestCase (assertEqualPrint dd)) declarations
where assertEqualPrint = assertParsedAST equallyPrinted (addVars ddVarsToAdd >> declaration)
ddVarsToAdd = typesVarsToAdd
declarations = [ "int a;"
, "int a asm(\"r1\");"
, "struct addr *p;"
, "int[5] is;"
, "int a, b;"
, "int a, b asm(\"r1\");"
, "int (*arr2)[8];"
, "int *arr2[8];"
, "int a[];"
, "int a[8];"
, "int *a[8];"
, "int a [static 8];"
, "void f(int [static 8]);"
, "const int * a;"
, "int const * a;"
, "int const * const a;"
, "int restrict * volatile a;"
, "int const * restrict a;"
, "int a, b = 10, c;"
, "void *pt, *pt2, *pt3;"
, "int a = 1, b = 2, c = 3;"
, "int a = 1, b;"
, "int a, b = 2, c = 3;"
, "int a = 4;"
, "enum myEnum;"
, "enum myEnum { a, b, c };"
, "enum myEnum { a, b, c, };"
, "int whitespace[256] = { [' '] = 1, ['\\t'] = 1, ['\\f'] = 1, ['\\n'] = 1, ['\\r'] = 1 };"
, "int *(*(i));"
, "static void (*f)();"
, "void f() asm (\"myLab\");"
, "int main() { return 0; }"
, "int main(void) { return 0; }"
, "typedef int (*bar)(int);"
, "typedef struct { int i; } b;"
, "struct { union { int b; float c; }; int d; } foo;"
] ++ map (++" a;") varTypes
++ map (++" a = 0;") varTypes
++ map (++";") funTypes
++ map (++" {}") funTypes
stmtDeclTests = TestList []
* Macro tests
macroTests = TestList $ map (\(tu,prep) -> TestCase (assertParsedSame eqAST (addVars vars >> whole translationUnit) tu prep)) macros
where vars = ["a","b","c","f","p","printf"]
macros = [ ("\n#define a int x;\n a","int x;")
, ("\n#define declare(typ,name) typ name;\n declare(int,x)", "int x;")
, ("\n#define min(X, Y) ((X) < (Y) ? (X) : (Y))\n"
++ "int x = min(a, b), y = min(1, 2), z = min(a + 28, *p);"
, "int x = ((a) < (b) ? (a) : (b)),"
++ "y = ((1) < (2) ? (1) : (2)),"
++ "z = ((a + 28) < (*p) ? (a + 28) : (*p));"
)
, ("\n#define pair(t1,t2,name) struct name { t1 first; t2 second; };\n"
++ "pair(int,bool,ib)\n" ++ "pair(int,bool,)"
, "struct ib { int first; bool second; };\n struct { int first; bool second; };")
, ("\n#define PRINT(x) printf(#x)\n int main() { PRINT(a); }"
,"int main() { printf(\"a\"); }"
)
, ("\n#define x y\n int xx;", "int xx;")
, ("\n#define X 1\n void g() { return (X); }", "void g() { return (1); }")
, ("\n#define F(x) f x\n int main(){ F((1,2,3)); }", "int main(){ f(1,2,3); }")
, ("\n#define FAIL_IF(condition, error_code) if (condition) return (error_code)"
++ "\n int main(){ FAIL_IF(c=='(',0); }", "int main(){ if (c=='(') return (0); }")
]
ifTests = TestList $ map (\(tu,prep) -> TestCase (assertParsedSame eqAST (whole translationUnit) tu prep)) ifs
ifs = [ ("\n#ifdef D\n int x; \n#endif", "")
, ("\n#define D\n#ifdef D\n int x; \n#endif", "int x;")
, ("\n#ifdef D\nint x;\n#else\nint y;\n#endif", "int y;")
, ("\n#define D\n#ifdef D\n int x; \n#else\n int y; \n#endif", "int x;")
]
-- * Sample program tests
programTests :: IO Test
programTests =
TestList . map (\file -> TestLabel file $ TestCase (testCase file))
<$> getTestsInDir "testfiles\\ok"
where testCase file = readFile file >>= assertParsedOkCustom 1000000 file (whole translationUnit)
getTestsInDir :: String -> IO [String]
getTestsInDir dir = liftM ( map (combine dir)
. filter (not . (`elem` [".",".."]))
) (getDirectoryContents dir)
useASTSource p f src
= do res <- parseWithPreproc (whole p) "(test)" src
putStrLn $ either show f res
showASTSource p src
= do res <- parseWithPreproc (whole p) "(test)" src
putStrLn $ either show show res
prettyPrintSource p src
= do res <- parseWithPreproc (whole p) "(test)" src
putStrLn $ either show (prettyPrint . transformSourceInfo) res
prettyPrintTestFile fileName
= do src <- readFile fileName
res <- parseWithPreproc (whole translationUnit) fileName src
putStrLn $ either show (prettyPrint . transformSourceInfo) res
-- * Helper functions
addVars :: [String] -> CParser ()
addVars varsToAdd
= modifyState $ symbolTable.symbolMap .~ fromList entries
where entries = map ((unsafePerformIO.parseQualName) &&& defaultVarEntry) varsToAdd
defaultVarEntry name
= VariableEntry [] defaultType Nothing Nothing noNodeInfo
defaultType = QualifiedType (Scalar ASTNothing noNodeInfo)
(IntType Signed MiniC.AST.Int noNodeInfo)
noNodeInfo
equallyPrinted :: (ToSourceRose a BI, ToSourceRose a TemplateInfo, SmartTrav a, Functor a)
=> String -> a BI -> Maybe String
equallyPrinted s a = let ppres = (prettyPrint . transformSourceInfo) a
in if ppres == s then Nothing
else Just $ "The result of pretty printing is `" ++ ppres ++ "`"
defaultTimeoutMSecs = 100000
assertParsedOk = assertParsedOkCustom defaultTimeoutMSecs "(test)"
assertParsedAST = assertParsedASTCustom defaultTimeoutMSecs "(test)"
-- | Protect tests from infinite loops
withTimeout :: Int -> IO a -> IO a
withTimeout msecs comp
= do res <- timeout msecs comp
return $ fromMaybe (error $ "Did not terminate in "
++ show (fromIntegral msecs / 100000.0 :: Double) ++ " seconds.") res
-- | Assert that parse is successful
assertParsedOkCustom :: Int -> String -> CParser a -> String -> Assertion
assertParsedOkCustom msecs srcname
= assertParsedASTCustom msecs srcname (\_ _ -> Nothing)
| Assert parse success and check the AST with a function that returns just an error message
when the AST is not correct .
assertParsedASTCustom :: Int -> String -> (String -> a -> Maybe String) -> CParser a -> String -> Assertion
assertParsedASTCustom msecs srcname validate parser source
= withTimeout msecs $
do res <- parseWithPreproc (whole parser) srcname source
assertBool ("'" ++ source ++ "' was not accepted: " ++ show (fromLeft' res)) (isRight res)
case validate source $ fromRight' res of
Just err -> assertFailure ("'" ++ source ++ "' was not correct: " ++ err)
Nothing -> return ()
-- | Assert that the parse fails
assertSyntaxError :: (Show a) => CParser a -> String -> (String -> Bool) -> Assertion
assertSyntaxError = assertSyntaxErrorTimeout defaultTimeoutMSecs
assertSyntaxErrorTimeout :: (Show a)
=> Int -> CParser a -> String -> (String -> Bool) -> Assertion
assertSyntaxErrorTimeout msecs parser source failMess
= withTimeout msecs $
do res <- parseWithPreproc (whole parser) "(test)" source
case res of
Left pErr -> case errorMessages pErr of
err:_ -> assertBool ("`" ++ source ++ "` should fail with a correct message. Failed with: " ++ messageString err)
(failMess (messageString err))
[] -> assertFailure $ "`" ++ source ++ "` should fail with a correct message. It failed without a message"
Right val -> assertFailure $ "`" ++ source ++ "` should fail with a correct message. Parsed: " ++ show val
instance where
-- (==) = undefined
| Assert that two ASTs are structurally equivalent
eqAST :: (Functor a, Eq (a ())) => a b -> a b -> Bool
eqAST = (==) `on` fmap (const ())
| Parses two inputs with the same parser and compares the results
assertParsedSame :: (Eq a, Show a) => (a -> a -> Bool) -> CParser a -> String -> String -> Assertion
assertParsedSame = assertParsedSameTimeout defaultTimeoutMSecs
assertParsedSameTimeout :: (Eq a, Show a) => Int -> (a -> a -> Bool) -> CParser a -> String -> String -> Assertion
assertParsedSameTimeout msecs isSameAs parser s1 s2
= withTimeout msecs $
do parseRes1 <- parseWithPreproc (whole parser) "(test)" s1
parseRes2 <- parseWithPreproc (whole parser) "(test)" s2
case (parseRes1,parseRes2) of
(Right result1, Right result2) ->
assertBool ("Parse results from `" ++ s1 ++ "` and `" ++ s2 ++ "` are not the same" )
(result1 `isSameAs` result2)
(Left err, _) -> assertFailure $ "Paring of `" ++ s1 ++ "` failed with error: " ++ show err
(_, Left err) -> assertFailure $ "Paring of `" ++ s2 ++ "` failed with error: " ++ show err
| null | https://raw.githubusercontent.com/nboldi/c-parser-in-haskell/1a92132e7d1b984cf93ec89d6836cc804257b57d/MiniC.hs | haskell | | Tests for the C parser
* Literal tests
* Expressions tests
| Tests that each expression is parsed successfully and printed back the same
* Instruction tests
| Tests that each statement is parsed successfully and printed back the same
* Type tests
* Declaration tests
* Sample program tests
* Helper functions
| Protect tests from infinite loops
| Assert that parse is successful
| Assert that the parse fails
(==) = undefined
| # LANGUAGE FlexibleContexts , MultiParamTypeClasses , TypeOperators , TupleSections #
module MiniC where
import MiniC.ParseProgram
import MiniC.Parser
import MiniC.Parser.Lexical
import MiniC.Parser.Base hiding (tuple)
import MiniC.AST
import MiniC.MiniCPP
import MiniC.Semantics
import MiniC.SymbolTable
import MiniC.Representation
import MiniC.Helpers
import MiniC.Instances
import MiniC.PrettyPrint
import MiniC.SourceNotation
import MiniC.TransformInfo
import Text.Preprocess.Parser
import SourceCode.ToSourceTree (ToSourceRose)
import SourceCode.SourceInfo (noNodeInfo)
import SourceCode.ASTElems
import GHC.Generics
import Text.Parsec
import Text.Parsec.Error
import Text.Preprocess.Rewrites
import Debug.Trace
import Data.SmartTrav
import Data.Maybe
import Data.Map(fromList)
import Data.Function
import Data.Either.Combinators
import Control.Arrow
import Control.Applicative hiding ((<|>), many)
import Control.Lens
import Control.Monad
import Control.Monad.Reader
import System.IO.Unsafe (unsafePerformIO)
import System.Timeout
import System.FilePath
import System.Directory
import Test.HUnit hiding (test)
import Test.HUnit.Find
test = tests >>= runTestTT
tests = do progTests <- programTests
return $ TestList
[ TestLabel "literalTests" literalTests
, TestLabel "exprTests" exprTests
, TestLabel "instrTests" instrTests
, TestLabel "typeTests" typeTests
, TestLabel "declarationTests" declarationTests
, TestLabel "stmtDeclTests" stmtDeclTests
, TestLabel "macroTests" macroTests
, TestLabel "ifTests" ifTests
, TestLabel "programTests" progTests
]
literalTests = TestList $ map (\lit -> TestLabel lit $ TestCase (assertParsedAST equallyPrinted literal lit)) literals
integerLiterals = [ "1", "0", "-1", "215u", "0xFeeL", "01", "30ul", "0b011010" ]
floatLiterals = [ "0.123", "1.4324", "1e-6", "1e-6L", "0.123f", ".1E4f", "58."
, "0x1.999999999999ap-4", "0x1p-1074", "0xcc.ccccccccccdp-11" ]
charLiterals = map (\cl -> "'" ++ cl ++ "'")
[ "c", "\\n", "\\0", "\\xAA", "\\0123", "\\u00e9" ]
stringLiterals = map (\sl -> "\"" ++ sl ++ "\"")
[ "bla", "almafa\\n", "almafa\\0", "\\xAA" ]
++ ["L\"r\\u00e9sum\\u00e9\""]
compoundLiterals = [ "{}", "{ 1,2,3 }", "{ .x = 1, .y = 2 }"
, "{ [0] = 1, [2] = 3 }"
, "{ [0] = 1, 2, [2] = 3 }" ]
literals = integerLiterals
++ floatLiterals
++ charLiterals
++ stringLiterals
++ compoundLiterals
exprTests = TestList $ map (\expr -> TestLabel expr $ TestCase (assertEqualPrint expr)) expressions
where assertEqualPrint = assertParsedAST equallyPrinted (addVars exprVarsToAdd >> expression)
exprVarsToAdd = ["a","b","c","i","n","x","f","g","scanf","printf"]
expressions = [ "&a", "*a", "*&a++"
, "a+b", "a = c , b"
, "a += *c , b"
, "x(1)"
, "x[0]"
, "x[0][1]"
, "x[0](1)"
, "(g)()"
, "(*f)(a,b)"
, "f(a,g)"
, "a>b?a:b"
, "a?:b"
, "a>b?&a:&b"
, "(int) 1"
, "(int) a"
, "(int) (a+1)"
, "sizeof(a)"
, "sizeof(int)"
, "1+sizeof(int)"
, "sizeof( struct { int a; } )"
, "scanf(\"%d\",n)"
, "scanf(\"%d\",&n)"
, "scanf(\"%d\",a+b)"
, "printf(\"%d\",a)"
, "a[i][i].x[i]"
] ++ literals
instrTests
= TestList $ map (\instr -> TestLabel instr $ TestCase (assertEqualPrint instr)) instructions
where assertEqualPrint = assertParsedAST equallyPrinted (addVars instrVarsToAdd >> statement)
instrVarsToAdd = exprVarsToAdd ++ ["c","it","msg","next","sum","y"]
instructions = [ "label : a = c;"
, "a += 4;"
, "f(4); // Bazz@#&#& "
, "f( /* Bazz@#&#& */ 4);"
, "f (1);"
, "a += (b + 4);"
, "{ }"
, "{ a = b = 10; a += (b + 4); b = a - 1; }"
, "{ int a = 10; }"
, "{ int a = 10; a = 11; }"
, "{ int a = 10; a = 11; int b = 12; b += a; }"
, "if (a==4) b = 10; else { x = 0; y = 0; }"
, "if (a==4) if (b==1) c = 10;"
, "switch (x) { case 0 : msg = \"brumm\"; break; "
++ " case 1 : msg = \"brummbrumm\"; break; "
++ " default : break; "
++ "}"
, "while (x > 0) --x;"
, "while (next(it));"
, "do ++x; while (x < 100);"
, "for (i=0; i<n; ++i) { sum += i*i; }"
, "for (int i=0; i<n; ++i) { sum += i*i; }"
, "{ return 10; break; continue; }"
, "((void ( * ) (void)) 0 ) ( );"
, "asm (\"movb %bh (%eax)\");"
, "asm (\"movl %eax, %ebx\\n\\t\" \"movl $56, %esi\\n\\t\");"
, "asm (\"cld\\n\\t\" \"rep\\n\\t\" \"stosl\" : : \"c\" (count), \"a\" (fill_value), \"D\" (dest) : \"%ecx\", \"%edi\" );"
, "asm volatile (\"sidt %0\\n\" : :\"m\"(loc));"
, "return 0;"
] ++ map (++";") expressions
typeTests = TestList $ map (\typ -> TestLabel typ $ TestCase (assertEqualPrint typ)) types
where assertEqualPrint = assertParsedAST equallyPrinted (addVars typesVarsToAdd >> qualifiedType)
typesVarsToAdd = ["strlen","s1","s2","x"]
baseVarTypes = [ "void", "int", "int*"
, "int[5]", "int[]", "int*[10]"
]
varTypes = baseVarTypes ++ map (++"*") baseVarTypes
++ [ "void (*foo)(int)", "void *(*foo)(int *)", "void (*)(void)"
, "void (*) (int* (*) (int*,int), char (*) (char))"
, "int* (*) ()"
, "int* (*) (int*,int)"
, "char (*) (char)"
, "struct myType"
, "enum myType"
, "union myType"
, "char str[strlen (s1) + strlen (s2) + 1]"
, "typeof (int)"
, "typeof (int *)"
, "typeof (x[0](1))"
, "typeof (*x)"
]
funTypes = [ "void f()", "int main()", "int main(void)", "int f(int)", "int f(int a)", "int f(int,int)" ]
types = funTypes ++ varTypes
declarationTests = TestList $ map (\dd -> TestLabel dd $ TestCase (assertEqualPrint dd)) declarations
where assertEqualPrint = assertParsedAST equallyPrinted (addVars ddVarsToAdd >> declaration)
ddVarsToAdd = typesVarsToAdd
declarations = [ "int a;"
, "int a asm(\"r1\");"
, "struct addr *p;"
, "int[5] is;"
, "int a, b;"
, "int a, b asm(\"r1\");"
, "int (*arr2)[8];"
, "int *arr2[8];"
, "int a[];"
, "int a[8];"
, "int *a[8];"
, "int a [static 8];"
, "void f(int [static 8]);"
, "const int * a;"
, "int const * a;"
, "int const * const a;"
, "int restrict * volatile a;"
, "int const * restrict a;"
, "int a, b = 10, c;"
, "void *pt, *pt2, *pt3;"
, "int a = 1, b = 2, c = 3;"
, "int a = 1, b;"
, "int a, b = 2, c = 3;"
, "int a = 4;"
, "enum myEnum;"
, "enum myEnum { a, b, c };"
, "enum myEnum { a, b, c, };"
, "int whitespace[256] = { [' '] = 1, ['\\t'] = 1, ['\\f'] = 1, ['\\n'] = 1, ['\\r'] = 1 };"
, "int *(*(i));"
, "static void (*f)();"
, "void f() asm (\"myLab\");"
, "int main() { return 0; }"
, "int main(void) { return 0; }"
, "typedef int (*bar)(int);"
, "typedef struct { int i; } b;"
, "struct { union { int b; float c; }; int d; } foo;"
] ++ map (++" a;") varTypes
++ map (++" a = 0;") varTypes
++ map (++";") funTypes
++ map (++" {}") funTypes
stmtDeclTests = TestList []
* Macro tests
macroTests = TestList $ map (\(tu,prep) -> TestCase (assertParsedSame eqAST (addVars vars >> whole translationUnit) tu prep)) macros
where vars = ["a","b","c","f","p","printf"]
macros = [ ("\n#define a int x;\n a","int x;")
, ("\n#define declare(typ,name) typ name;\n declare(int,x)", "int x;")
, ("\n#define min(X, Y) ((X) < (Y) ? (X) : (Y))\n"
++ "int x = min(a, b), y = min(1, 2), z = min(a + 28, *p);"
, "int x = ((a) < (b) ? (a) : (b)),"
++ "y = ((1) < (2) ? (1) : (2)),"
++ "z = ((a + 28) < (*p) ? (a + 28) : (*p));"
)
, ("\n#define pair(t1,t2,name) struct name { t1 first; t2 second; };\n"
++ "pair(int,bool,ib)\n" ++ "pair(int,bool,)"
, "struct ib { int first; bool second; };\n struct { int first; bool second; };")
, ("\n#define PRINT(x) printf(#x)\n int main() { PRINT(a); }"
,"int main() { printf(\"a\"); }"
)
, ("\n#define x y\n int xx;", "int xx;")
, ("\n#define X 1\n void g() { return (X); }", "void g() { return (1); }")
, ("\n#define F(x) f x\n int main(){ F((1,2,3)); }", "int main(){ f(1,2,3); }")
, ("\n#define FAIL_IF(condition, error_code) if (condition) return (error_code)"
++ "\n int main(){ FAIL_IF(c=='(',0); }", "int main(){ if (c=='(') return (0); }")
]
ifTests = TestList $ map (\(tu,prep) -> TestCase (assertParsedSame eqAST (whole translationUnit) tu prep)) ifs
ifs = [ ("\n#ifdef D\n int x; \n#endif", "")
, ("\n#define D\n#ifdef D\n int x; \n#endif", "int x;")
, ("\n#ifdef D\nint x;\n#else\nint y;\n#endif", "int y;")
, ("\n#define D\n#ifdef D\n int x; \n#else\n int y; \n#endif", "int x;")
]
programTests :: IO Test
programTests =
TestList . map (\file -> TestLabel file $ TestCase (testCase file))
<$> getTestsInDir "testfiles\\ok"
where testCase file = readFile file >>= assertParsedOkCustom 1000000 file (whole translationUnit)
getTestsInDir :: String -> IO [String]
getTestsInDir dir = liftM ( map (combine dir)
. filter (not . (`elem` [".",".."]))
) (getDirectoryContents dir)
useASTSource p f src
= do res <- parseWithPreproc (whole p) "(test)" src
putStrLn $ either show f res
showASTSource p src
= do res <- parseWithPreproc (whole p) "(test)" src
putStrLn $ either show show res
prettyPrintSource p src
= do res <- parseWithPreproc (whole p) "(test)" src
putStrLn $ either show (prettyPrint . transformSourceInfo) res
prettyPrintTestFile fileName
= do src <- readFile fileName
res <- parseWithPreproc (whole translationUnit) fileName src
putStrLn $ either show (prettyPrint . transformSourceInfo) res
addVars :: [String] -> CParser ()
addVars varsToAdd
= modifyState $ symbolTable.symbolMap .~ fromList entries
where entries = map ((unsafePerformIO.parseQualName) &&& defaultVarEntry) varsToAdd
defaultVarEntry name
= VariableEntry [] defaultType Nothing Nothing noNodeInfo
defaultType = QualifiedType (Scalar ASTNothing noNodeInfo)
(IntType Signed MiniC.AST.Int noNodeInfo)
noNodeInfo
equallyPrinted :: (ToSourceRose a BI, ToSourceRose a TemplateInfo, SmartTrav a, Functor a)
=> String -> a BI -> Maybe String
equallyPrinted s a = let ppres = (prettyPrint . transformSourceInfo) a
in if ppres == s then Nothing
else Just $ "The result of pretty printing is `" ++ ppres ++ "`"
defaultTimeoutMSecs = 100000
assertParsedOk = assertParsedOkCustom defaultTimeoutMSecs "(test)"
assertParsedAST = assertParsedASTCustom defaultTimeoutMSecs "(test)"
withTimeout :: Int -> IO a -> IO a
withTimeout msecs comp
= do res <- timeout msecs comp
return $ fromMaybe (error $ "Did not terminate in "
++ show (fromIntegral msecs / 100000.0 :: Double) ++ " seconds.") res
assertParsedOkCustom :: Int -> String -> CParser a -> String -> Assertion
assertParsedOkCustom msecs srcname
= assertParsedASTCustom msecs srcname (\_ _ -> Nothing)
| Assert parse success and check the AST with a function that returns just an error message
when the AST is not correct .
assertParsedASTCustom :: Int -> String -> (String -> a -> Maybe String) -> CParser a -> String -> Assertion
assertParsedASTCustom msecs srcname validate parser source
= withTimeout msecs $
do res <- parseWithPreproc (whole parser) srcname source
assertBool ("'" ++ source ++ "' was not accepted: " ++ show (fromLeft' res)) (isRight res)
case validate source $ fromRight' res of
Just err -> assertFailure ("'" ++ source ++ "' was not correct: " ++ err)
Nothing -> return ()
assertSyntaxError :: (Show a) => CParser a -> String -> (String -> Bool) -> Assertion
assertSyntaxError = assertSyntaxErrorTimeout defaultTimeoutMSecs
assertSyntaxErrorTimeout :: (Show a)
=> Int -> CParser a -> String -> (String -> Bool) -> Assertion
assertSyntaxErrorTimeout msecs parser source failMess
= withTimeout msecs $
do res <- parseWithPreproc (whole parser) "(test)" source
case res of
Left pErr -> case errorMessages pErr of
err:_ -> assertBool ("`" ++ source ++ "` should fail with a correct message. Failed with: " ++ messageString err)
(failMess (messageString err))
[] -> assertFailure $ "`" ++ source ++ "` should fail with a correct message. It failed without a message"
Right val -> assertFailure $ "`" ++ source ++ "` should fail with a correct message. Parsed: " ++ show val
instance where
| Assert that two ASTs are structurally equivalent
eqAST :: (Functor a, Eq (a ())) => a b -> a b -> Bool
eqAST = (==) `on` fmap (const ())
| Parses two inputs with the same parser and compares the results
assertParsedSame :: (Eq a, Show a) => (a -> a -> Bool) -> CParser a -> String -> String -> Assertion
assertParsedSame = assertParsedSameTimeout defaultTimeoutMSecs
assertParsedSameTimeout :: (Eq a, Show a) => Int -> (a -> a -> Bool) -> CParser a -> String -> String -> Assertion
assertParsedSameTimeout msecs isSameAs parser s1 s2
= withTimeout msecs $
do parseRes1 <- parseWithPreproc (whole parser) "(test)" s1
parseRes2 <- parseWithPreproc (whole parser) "(test)" s2
case (parseRes1,parseRes2) of
(Right result1, Right result2) ->
assertBool ("Parse results from `" ++ s1 ++ "` and `" ++ s2 ++ "` are not the same" )
(result1 `isSameAs` result2)
(Left err, _) -> assertFailure $ "Paring of `" ++ s1 ++ "` failed with error: " ++ show err
(_, Left err) -> assertFailure $ "Paring of `" ++ s2 ++ "` failed with error: " ++ show err
|
d5398ac9ca0cadd561a8501766aaed8aa4d02e78b6fe35b49785c600d206c5b3 | racket/racket7 | demo2.rkt | #lang racket/base
(time
(let loop ([j 10])
(unless (zero? j)
(let ()
(define p (open-input-file "compiled/io.rktl"))
(port-count-lines! p)
(let loop ()
(define s (read-string 100 p))
(unless (eof-object? s)
(loop)))
(close-input-port p)
(loop (sub1 j))))))
(time
(let loop ([j 10])
(unless (zero? j)
(let ()
(define p (open-input-file "compiled/io.rktl"))
(port-count-lines! p)
(let loop ()
(unless (eof-object? (read-byte p))
(loop)))
(close-input-port p)
(loop (sub1 j))))))
'read-line
(time
(let loop ([j 10])
(unless (zero? j)
(let ()
(define p (host:open-input-file "compiled/io.rktl"))
(let loop ()
(unless (eof-object? (host:read-line p))
(loop)))
(host:close-input-port p)
(loop (sub1 j))))))
(time
(let loop ([j 10])
(unless (zero? j)
(let ()
(define p (open-input-file "compiled/io.rktl"))
(let loop ()
(unless (eof-object? (read-line p))
(loop)))
(close-input-port p)
(loop (sub1 j))))))
| null | https://raw.githubusercontent.com/racket/racket7/5dbb62c6bbec198b4a790f1dc08fef0c45c2e32b/racket/src/io/demo2.rkt | racket | #lang racket/base
(time
(let loop ([j 10])
(unless (zero? j)
(let ()
(define p (open-input-file "compiled/io.rktl"))
(port-count-lines! p)
(let loop ()
(define s (read-string 100 p))
(unless (eof-object? s)
(loop)))
(close-input-port p)
(loop (sub1 j))))))
(time
(let loop ([j 10])
(unless (zero? j)
(let ()
(define p (open-input-file "compiled/io.rktl"))
(port-count-lines! p)
(let loop ()
(unless (eof-object? (read-byte p))
(loop)))
(close-input-port p)
(loop (sub1 j))))))
'read-line
(time
(let loop ([j 10])
(unless (zero? j)
(let ()
(define p (host:open-input-file "compiled/io.rktl"))
(let loop ()
(unless (eof-object? (host:read-line p))
(loop)))
(host:close-input-port p)
(loop (sub1 j))))))
(time
(let loop ([j 10])
(unless (zero? j)
(let ()
(define p (open-input-file "compiled/io.rktl"))
(let loop ()
(unless (eof-object? (read-line p))
(loop)))
(close-input-port p)
(loop (sub1 j))))))
| |
fba9a9bfe893f298221045f70abdb3ec1fd110e26dd013d328a945dd32cfb763 | bvaugon/ocapic | thermostat.ml | (*************************************************************************)
(* *)
(* OCaPIC *)
(* *)
(* *)
This file is distributed under the terms of the CeCILL license .
(* See file ../../LICENSE-en. *)
(* *)
(*************************************************************************)
open Pic;;
open Lcd;;
(***)
exception StartStop;;
type kind = Nothing | Plus | Minus | Twice
(***)
80.0 ° C
32.5 ° C
2.0 ° C
let output = RD1;;
let plus_button = RD5;;
let minus_button = RD4;;
(***)
set_bit IRCF1;;
set_bit IRCF0;;
set_bit PLLEN;;
(***)
write_reg TRISD 0b11111101;;
clear_bit RD1;;
(***)
let disp = connect ~bus_size:Lcd.Four ~e:LATD2 ~rs:LATD3 ~rw:LATD6 ~bus:PORTB;;
disp.init ();;
disp.config ();;
disp.register_bitmap '\000'
0b01110_01010 0b01110_00000_00000 0b00000_00000_00000;;
disp.register_bitmap '\001'
0b00000_00100 0b01000_10100_01000 0b00100_00000_00000;;
disp.register_bitmap '\002'
0b00000_00100 0b00010_00101_00010 0b00100_00000_00000;;
disp.register_bitmap '\003'
0b00000_10000 0b01000_10100_01000 0b10000_00000_00000;;
disp.register_bitmap '\004'
0b00000_00001 0b00010_00101_00010 0b00001_00000_00000;;
disp.print_string "\00132.5\000C\002\n 32.5\000C ";;
(***)
let print_str n s =
disp.moveto n 1;
disp.print_string s;
;;
let str_of_temp temp =
if temp < max_temp then "++.+"
else if temp > min_temp then "--.-"
else Printf.sprintf "%4.1f" (float_of_int (1033 - temp) /. 11.67)
;;
let print_temp n temp = print_str n (str_of_temp temp);;
let read_temp () =
write_reg ADCON2 0b10111110;
write_reg ADCON1 0b00111110;
write_reg ADCON0 0b00000011;
while test_bit GO_NOT_DONE do () done;
(read_reg ADRESH lsl 8) lor read_reg ADRES
;;
(***)
let wtemp = ref def_temp;;
let wstr = ref "";;
let rec offset_wtemp ofs =
let old_wtemp = !wtemp in
let new_wtemp = min min_temp (max max_temp (old_wtemp + ofs)) in
if new_wtemp <> old_wtemp then
let new_wstr = str_of_temp new_wtemp in
wtemp := new_wtemp;
if !wstr = new_wstr then offset_wtemp ofs else (
wstr := new_wstr;
print_str 1 new_wstr;
);
;;
let set_wtemp temp =
if temp <> !wtemp then (
wtemp := temp;
print_temp 1 temp;
);
;;
(***)
let ctemp = ref def_temp;;
let update_ctemp () =
let otemp = !ctemp in
let temp = read_temp () in
let delta = otemp - temp in
let ntemp =
if delta > 20 || delta < -20 then temp
else (3 * otemp + temp) lsr 2
in
if ntemp <> otemp then (
print_temp 2 ntemp;
ctemp := ntemp;
);
;;
(***)
let prop = ref 0;;
let update_prop () =
let delta = min 10 (max (-10) (!ctemp - !wtemp)) in
let delta2 = if delta < 0 then -delta * delta else delta * delta in
let offset = min 10 delta2 in
let new_prop = min 100 (max 0 (!prop + offset)) in
prop := new_prop;
new_prop / 10
;;
let reset_prop () = prop := 0;;
(***)
let save_wtemp () =
let temp = !wtemp in
Eeprom.write 0 (temp mod 256);
Eeprom.write 1 (temp / 256);
;;
let restore_wtemp () =
let temp = Eeprom.read 0 + Eeprom.read 1 * 256 in
if temp >= max_temp && temp <= min_temp then set_wtemp temp;
;;
(***)
let counter = ref 0;;
let kind = ref Nothing;;
let mem_wtemp = ref 0;;
let tic_button () =
let p = not (test_bit plus_button) and m = test_bit minus_button in
match (p, m, !kind, !counter) with
| (true, false, Nothing, 0) ->
mem_wtemp := !wtemp;
offset_wtemp (-1);
kind := Plus;
incr counter;
| (true, false, Plus, 10) ->
offset_wtemp (-3);
| (true, false, Plus, _) ->
incr counter;
| (false, true, Nothing, 0) ->
mem_wtemp := !wtemp;
offset_wtemp 1;
kind := Minus;
incr counter;
| (false, true, Minus, 10) ->
offset_wtemp 3;
| (false, true, Minus, _) ->
incr counter;
| (true, true, Nothing, 0) ->
counter := 1;
kind := Twice;
| (true, true, (Plus | Minus), n) ->
if n > 0 && n < 10 then set_wtemp !mem_wtemp;
counter := 1;
kind := Twice;
| (true, true, Twice, 20) ->
raise StartStop;
| (true, true, Twice, _) ->
incr counter;
| (_, _, _, n) ->
if n > 0 then (
save_wtemp ();
counter := 0;
kind := Nothing;
);
;;
let wait_release () =
while not (test_bit plus_button) || test_bit minus_button do
Sys.sleep 50;
done;
;;
(***)
restore_wtemp ();;
let rec wait_start () = (
try
update_ctemp ();
for i = 1 to 10 do tic_button (); Sys.sleep 50; done;
wait_start
with StartStop ->
disp.moveto 1 0; disp.print_char '\003';
disp.moveto 1 7; disp.print_char '\004';
wait_release ();
wait_stop
) ()
and wait_stop () = (
try
update_ctemp ();
let prop = update_prop () in
for i = 1 to prop do tic_button (); set_bit output; Sys.sleep 50; done;
for i = prop to 9 do tic_button (); clear_bit output; Sys.sleep 50; done;
wait_stop
with StartStop ->
clear_bit output;
reset_prop ();
disp.moveto 1 0; disp.print_char '\001';
disp.moveto 1 7; disp.print_char '\002';
wait_release ();
wait_start
) ()
in
wait_stop ();;
| null | https://raw.githubusercontent.com/bvaugon/ocapic/a14cd9ec3f5022aeb5fe2264d595d7e8f1ddf58a/tests/thermostat1/thermostat.ml | ocaml | ***********************************************************************
OCaPIC
See file ../../LICENSE-en.
***********************************************************************
*
*
*
*
*
*
*
*
*
*
*
* |
This file is distributed under the terms of the CeCILL license .
open Pic;;
open Lcd;;
exception StartStop;;
type kind = Nothing | Plus | Minus | Twice
80.0 ° C
32.5 ° C
2.0 ° C
let output = RD1;;
let plus_button = RD5;;
let minus_button = RD4;;
set_bit IRCF1;;
set_bit IRCF0;;
set_bit PLLEN;;
write_reg TRISD 0b11111101;;
clear_bit RD1;;
let disp = connect ~bus_size:Lcd.Four ~e:LATD2 ~rs:LATD3 ~rw:LATD6 ~bus:PORTB;;
disp.init ();;
disp.config ();;
disp.register_bitmap '\000'
0b01110_01010 0b01110_00000_00000 0b00000_00000_00000;;
disp.register_bitmap '\001'
0b00000_00100 0b01000_10100_01000 0b00100_00000_00000;;
disp.register_bitmap '\002'
0b00000_00100 0b00010_00101_00010 0b00100_00000_00000;;
disp.register_bitmap '\003'
0b00000_10000 0b01000_10100_01000 0b10000_00000_00000;;
disp.register_bitmap '\004'
0b00000_00001 0b00010_00101_00010 0b00001_00000_00000;;
disp.print_string "\00132.5\000C\002\n 32.5\000C ";;
let print_str n s =
disp.moveto n 1;
disp.print_string s;
;;
let str_of_temp temp =
if temp < max_temp then "++.+"
else if temp > min_temp then "--.-"
else Printf.sprintf "%4.1f" (float_of_int (1033 - temp) /. 11.67)
;;
let print_temp n temp = print_str n (str_of_temp temp);;
let read_temp () =
write_reg ADCON2 0b10111110;
write_reg ADCON1 0b00111110;
write_reg ADCON0 0b00000011;
while test_bit GO_NOT_DONE do () done;
(read_reg ADRESH lsl 8) lor read_reg ADRES
;;
let wtemp = ref def_temp;;
let wstr = ref "";;
let rec offset_wtemp ofs =
let old_wtemp = !wtemp in
let new_wtemp = min min_temp (max max_temp (old_wtemp + ofs)) in
if new_wtemp <> old_wtemp then
let new_wstr = str_of_temp new_wtemp in
wtemp := new_wtemp;
if !wstr = new_wstr then offset_wtemp ofs else (
wstr := new_wstr;
print_str 1 new_wstr;
);
;;
let set_wtemp temp =
if temp <> !wtemp then (
wtemp := temp;
print_temp 1 temp;
);
;;
let ctemp = ref def_temp;;
let update_ctemp () =
let otemp = !ctemp in
let temp = read_temp () in
let delta = otemp - temp in
let ntemp =
if delta > 20 || delta < -20 then temp
else (3 * otemp + temp) lsr 2
in
if ntemp <> otemp then (
print_temp 2 ntemp;
ctemp := ntemp;
);
;;
let prop = ref 0;;
let update_prop () =
let delta = min 10 (max (-10) (!ctemp - !wtemp)) in
let delta2 = if delta < 0 then -delta * delta else delta * delta in
let offset = min 10 delta2 in
let new_prop = min 100 (max 0 (!prop + offset)) in
prop := new_prop;
new_prop / 10
;;
let reset_prop () = prop := 0;;
let save_wtemp () =
let temp = !wtemp in
Eeprom.write 0 (temp mod 256);
Eeprom.write 1 (temp / 256);
;;
let restore_wtemp () =
let temp = Eeprom.read 0 + Eeprom.read 1 * 256 in
if temp >= max_temp && temp <= min_temp then set_wtemp temp;
;;
let counter = ref 0;;
let kind = ref Nothing;;
let mem_wtemp = ref 0;;
let tic_button () =
let p = not (test_bit plus_button) and m = test_bit minus_button in
match (p, m, !kind, !counter) with
| (true, false, Nothing, 0) ->
mem_wtemp := !wtemp;
offset_wtemp (-1);
kind := Plus;
incr counter;
| (true, false, Plus, 10) ->
offset_wtemp (-3);
| (true, false, Plus, _) ->
incr counter;
| (false, true, Nothing, 0) ->
mem_wtemp := !wtemp;
offset_wtemp 1;
kind := Minus;
incr counter;
| (false, true, Minus, 10) ->
offset_wtemp 3;
| (false, true, Minus, _) ->
incr counter;
| (true, true, Nothing, 0) ->
counter := 1;
kind := Twice;
| (true, true, (Plus | Minus), n) ->
if n > 0 && n < 10 then set_wtemp !mem_wtemp;
counter := 1;
kind := Twice;
| (true, true, Twice, 20) ->
raise StartStop;
| (true, true, Twice, _) ->
incr counter;
| (_, _, _, n) ->
if n > 0 then (
save_wtemp ();
counter := 0;
kind := Nothing;
);
;;
let wait_release () =
while not (test_bit plus_button) || test_bit minus_button do
Sys.sleep 50;
done;
;;
restore_wtemp ();;
let rec wait_start () = (
try
update_ctemp ();
for i = 1 to 10 do tic_button (); Sys.sleep 50; done;
wait_start
with StartStop ->
disp.moveto 1 0; disp.print_char '\003';
disp.moveto 1 7; disp.print_char '\004';
wait_release ();
wait_stop
) ()
and wait_stop () = (
try
update_ctemp ();
let prop = update_prop () in
for i = 1 to prop do tic_button (); set_bit output; Sys.sleep 50; done;
for i = prop to 9 do tic_button (); clear_bit output; Sys.sleep 50; done;
wait_stop
with StartStop ->
clear_bit output;
reset_prop ();
disp.moveto 1 0; disp.print_char '\001';
disp.moveto 1 7; disp.print_char '\002';
wait_release ();
wait_start
) ()
in
wait_stop ();;
|
9ae37a6da8b1d7c00db4beaec2c61d976ceeb008ac7a7814cc8fceda7c542e7e | mirage/qubes-mirage-skeleton | unikernel.ml | Copyright ( C ) 2016 ,
See the README file for details .
See the README file for details. *)
open Lwt
open Qubes
let src = Logs.Src.create "unikernel" ~doc:"Main unikernel code"
module Log = (val Logs.src_log src : Logs.LOG)
Get the first IPv4 address from a list of addresses .
let rec first_v4 = function
| [] -> None
| x :: xs ->
match Ipaddr.to_v4 x with
| None -> first_v4 xs
| Some ipv4 -> Some ipv4
module Main
(DB : Qubes.S.DB)
(Stack : Mirage_stack_lwt.V4)
(Time : Mirage_time_lwt.S) = struct
Initialise DNS resolver
module Resolver = Dns_resolver_mirage.Make(Time)(Stack)
let get_required qubesDB key =
match DB.read qubesDB key with
| None -> failwith (Printf.sprintf "Required QubesDB key %S not found" key)
| Some v ->
Log.info (fun f -> f "QubesDB %S = %S" key v);
v
let start qubesDB stack _time =
Log.info (fun f -> f "Starting");
(* Start qrexec agent and GUI agent in parallel *)
let qrexec = RExec.connect ~domid:0 () in
let gui = GUI.connect ~domid:0 () in
(* Wait for clients to connect *)
qrexec >>= fun qrexec ->
let agent_listener = RExec.listen qrexec Command.handler in
gui >>= fun gui ->
Lwt.async (fun () -> GUI.listen gui);
Lwt.async (fun () ->
OS.Lifecycle.await_shutdown_request () >>= fun (`Poweroff | `Reboot) ->
RExec.disconnect qrexec
);
let resolver = Resolver.create stack in
let dns = get_required qubesDB "/qubes-primary-dns" |> Ipaddr.V4.of_string_exn in
(* Test by downloading *)
let test_host = "google.com" in
Log.info (fun f -> f "Resolving %S" test_host);
Resolver.gethostbyname resolver ~server:dns test_host >>= fun addresses ->
match first_v4 addresses with
| None -> failwith "google.com didn't resolve!"
| Some google ->
Log.info (fun f -> f "%S has IPv4 address %a" test_host Ipaddr.V4.pp google);
let tcp = Stack.tcpv4 stack in
let port = 80 in
Log.info (fun f -> f "Opening TCP connection to %a:%d" Ipaddr.V4.pp google port);
Stack.TCPV4.create_connection tcp (google, port) >>= function
| Error err -> failwith (Format.asprintf "Failed to connect to %a:%d:%a" Ipaddr.V4.pp google port Stack.TCPV4.pp_error err)
| Ok conn ->
Log.info (fun f -> f "Connected!");
Stack.TCPV4.write conn (Cstruct.of_string "GET / HTTP/1.0\r\n\r\n") >>= function
| Error _ -> failwith "Failed to write HTTP request"
| Ok () ->
let rec read_all () =
Stack.TCPV4.read conn >>= function
| Ok (`Data d) -> Log.info (fun f -> f "Received %S" (Cstruct.to_string d)); read_all ()
| Error _ -> failwith "Error reading from TCP stream"
| Ok `Eof -> Lwt.return ()
in
read_all () >>= fun () ->
Log.info (fun f -> f "Closing TCP connection");
Stack.TCPV4.close conn >>= fun () ->
Log.info (fun f -> f "Network test done. Waiting for qrexec commands...");
agent_listener
end
| null | https://raw.githubusercontent.com/mirage/qubes-mirage-skeleton/18d2f18d15efc5d1011101baeb1df72e0a07e5cd/unikernel.ml | ocaml | Start qrexec agent and GUI agent in parallel
Wait for clients to connect
Test by downloading | Copyright ( C ) 2016 ,
See the README file for details .
See the README file for details. *)
open Lwt
open Qubes
let src = Logs.Src.create "unikernel" ~doc:"Main unikernel code"
module Log = (val Logs.src_log src : Logs.LOG)
Get the first IPv4 address from a list of addresses .
let rec first_v4 = function
| [] -> None
| x :: xs ->
match Ipaddr.to_v4 x with
| None -> first_v4 xs
| Some ipv4 -> Some ipv4
module Main
(DB : Qubes.S.DB)
(Stack : Mirage_stack_lwt.V4)
(Time : Mirage_time_lwt.S) = struct
Initialise DNS resolver
module Resolver = Dns_resolver_mirage.Make(Time)(Stack)
let get_required qubesDB key =
match DB.read qubesDB key with
| None -> failwith (Printf.sprintf "Required QubesDB key %S not found" key)
| Some v ->
Log.info (fun f -> f "QubesDB %S = %S" key v);
v
let start qubesDB stack _time =
Log.info (fun f -> f "Starting");
let qrexec = RExec.connect ~domid:0 () in
let gui = GUI.connect ~domid:0 () in
qrexec >>= fun qrexec ->
let agent_listener = RExec.listen qrexec Command.handler in
gui >>= fun gui ->
Lwt.async (fun () -> GUI.listen gui);
Lwt.async (fun () ->
OS.Lifecycle.await_shutdown_request () >>= fun (`Poweroff | `Reboot) ->
RExec.disconnect qrexec
);
let resolver = Resolver.create stack in
let dns = get_required qubesDB "/qubes-primary-dns" |> Ipaddr.V4.of_string_exn in
let test_host = "google.com" in
Log.info (fun f -> f "Resolving %S" test_host);
Resolver.gethostbyname resolver ~server:dns test_host >>= fun addresses ->
match first_v4 addresses with
| None -> failwith "google.com didn't resolve!"
| Some google ->
Log.info (fun f -> f "%S has IPv4 address %a" test_host Ipaddr.V4.pp google);
let tcp = Stack.tcpv4 stack in
let port = 80 in
Log.info (fun f -> f "Opening TCP connection to %a:%d" Ipaddr.V4.pp google port);
Stack.TCPV4.create_connection tcp (google, port) >>= function
| Error err -> failwith (Format.asprintf "Failed to connect to %a:%d:%a" Ipaddr.V4.pp google port Stack.TCPV4.pp_error err)
| Ok conn ->
Log.info (fun f -> f "Connected!");
Stack.TCPV4.write conn (Cstruct.of_string "GET / HTTP/1.0\r\n\r\n") >>= function
| Error _ -> failwith "Failed to write HTTP request"
| Ok () ->
let rec read_all () =
Stack.TCPV4.read conn >>= function
| Ok (`Data d) -> Log.info (fun f -> f "Received %S" (Cstruct.to_string d)); read_all ()
| Error _ -> failwith "Error reading from TCP stream"
| Ok `Eof -> Lwt.return ()
in
read_all () >>= fun () ->
Log.info (fun f -> f "Closing TCP connection");
Stack.TCPV4.close conn >>= fun () ->
Log.info (fun f -> f "Network test done. Waiting for qrexec commands...");
agent_listener
end
|
4eaaa2aaebb67efa7943c01ff4bebb2f555994ea9c8299a28178cfe2cda24091 | brownplt/lambda-py | python-compile.rkt | #lang plai-typed/untyped
(require "python-core-syntax.rkt"
"python-phases.rkt"
"python-desugar.rkt"
"util.rkt"
"parser/parser.rkt"
(typed-in "get-structured-python.rkt"
(get-structured-python : ('a -> 'b)))
(typed-in racket/base (open-input-file : ('a -> 'b)))
(typed-in racket/base (open-input-string : ('a -> 'b))))
(define (compile-port port)
(desugar
(new-scope-phase
(get-structured-python
((parser) port)))))
(define (compile-string str)
(compile-port
(open-input-string str)))
(define (get-global-names (es : CExpr)) : (listof symbol)
(type-case CExpr es
(CModule (pre body)
;skip %locals trick
(get-global-names (CSeq-e2 body)))
(CLet (x type bind body)
(cons x (get-global-names body)))
(else (list))))
;; a more stable way to find globals in expr
;; (define (get-global-names expr-str)
;; (get-module-level-globals
;; (get-structured-python
;; (parse-python/string expr-str (get-pypath)))))
;; built-in compile function, which takes
;; source, filename, mode and code class as its arguments
(define (compile args env sto)
(check-types-pred args env sto MetaStr? MetaStr? MetaStr?
(let* ([source (MetaStr-s mval1)]
[filename (MetaStr-s mval2)]
[mode (MetaStr-s mval3)]
[code (compile-string source)]
[globals (get-global-names code)]
[code-class (fourth args)])
(some (VObjectClass 'code
(some (MetaCode code filename globals))
(hash empty)
(some code-class))))))
| null | https://raw.githubusercontent.com/brownplt/lambda-py/c3ee39502c8953d36b886e5a203f2eb51d2f495b/base/python-compile.rkt | racket | skip %locals trick
a more stable way to find globals in expr
(define (get-global-names expr-str)
(get-module-level-globals
(get-structured-python
(parse-python/string expr-str (get-pypath)))))
built-in compile function, which takes
source, filename, mode and code class as its arguments | #lang plai-typed/untyped
(require "python-core-syntax.rkt"
"python-phases.rkt"
"python-desugar.rkt"
"util.rkt"
"parser/parser.rkt"
(typed-in "get-structured-python.rkt"
(get-structured-python : ('a -> 'b)))
(typed-in racket/base (open-input-file : ('a -> 'b)))
(typed-in racket/base (open-input-string : ('a -> 'b))))
(define (compile-port port)
(desugar
(new-scope-phase
(get-structured-python
((parser) port)))))
(define (compile-string str)
(compile-port
(open-input-string str)))
(define (get-global-names (es : CExpr)) : (listof symbol)
(type-case CExpr es
(CModule (pre body)
(get-global-names (CSeq-e2 body)))
(CLet (x type bind body)
(cons x (get-global-names body)))
(else (list))))
(define (compile args env sto)
(check-types-pred args env sto MetaStr? MetaStr? MetaStr?
(let* ([source (MetaStr-s mval1)]
[filename (MetaStr-s mval2)]
[mode (MetaStr-s mval3)]
[code (compile-string source)]
[globals (get-global-names code)]
[code-class (fourth args)])
(some (VObjectClass 'code
(some (MetaCode code filename globals))
(hash empty)
(some code-class))))))
|
9943b010c1f223843ad0fd3d68b4aa5a14438b06df1cfcdad2e9991f6eb4750b | Zulu-Inuoe/clution | server.lisp | (defpackage #:qlot/server
(:use #:cl)
(:import-from #:qlot/source
#:*dist-base-url*
#:prepare
#:source-prepared
#:url-path-for
#:project.txt
#:distinfo.txt
#:releases.txt
#:systems.txt
#:archive)
(:import-from #:qlot/parser
#:prepare-qlfile)
(:import-from #:qlot/tmp
#:*tmp-directory*)
(:import-from #:qlot/util
#:*system-quicklisp-home*
#:with-quicklisp-home)
(:import-from #:alexandria
#:when-let
#:once-only
#:with-gensyms)
(:import-from #:uiop
#:copy-file)
(:export #:localhost
#:with-qlot-server))
(in-package #:qlot/server)
(defvar *handler* nil)
(defun localhost (&optional (path ""))
;; Use PATH If PATH is an URL, not an URL path.
(when (and (< 0 (length path))
(not (char= (aref path 0) #\/)))
(return-from localhost path))
(format nil "qlot~A" path))
(defun qlot-fetch (url file &key (follow-redirects t) quietly (maximum-redirects 10))
"Request URL and write the body of the response to FILE."
(declare (ignorable follow-redirects quietly maximum-redirects))
(let ((result (funcall *handler* `(:path-info ,url))))
(when (= (first result) 200)
(typecase (third result)
(list
(with-open-file (out file :direction :output :if-exists :supersede :if-does-not-exist :create)
(dolist (chunk (third result))
(princ chunk out))))
(pathname
(uiop:copy-file (third result) file)))))
(values (make-instance (intern (string '#:header) '#:ql-http) :status 200)
(probe-file file)))
(defun make-app (sources)
(flet ((make-route (source action)
(let ((action-name (symbol-name action)))
(lambda ()
(let* ((*dist-base-url* (localhost))
(res (funcall (symbol-function action) source)))
(list 200
(if (string-equal (subseq action-name (- (length action-name) 4))
".txt")
(list :content-type "text/plain")
'())
(if (stringp res)
(list res)
res)))))))
(let ((route (make-hash-table :test 'equal))
(tmp-directory *tmp-directory*))
(dolist (source sources)
(setf (gethash (localhost (url-path-for source 'project.txt)) route)
(lambda ()
(let ((*tmp-directory* tmp-directory))
(prepare source))
(dolist (action '(project.txt distinfo.txt releases.txt systems.txt archive))
(when-let (path (url-path-for source action))
(setf (gethash (localhost path) route)
(make-route source action))))
(funcall (make-route source 'project.txt)))))
(lambda (env)
(with-quicklisp-home *system-quicklisp-home*
(let ((fn (gethash (getf env :path-info) route))
(*tmp-directory* tmp-directory))
(if fn
(funcall fn)
'(404 (:content-type "text/plain") ("Not Found")))))))))
(defmacro with-qlot-server (sources &body body)
(once-only (sources)
(with-gensyms (fetch-scheme-functions)
`(let ((,fetch-scheme-functions (intern (string '#:*fetch-scheme-functions*) '#:ql-http))
(*handler* (make-app (if (pathnamep ,sources)
(prepare-qlfile ,sources)
,sources))))
(progv (list ,fetch-scheme-functions)
(list (cons '("qlot" . qlot-fetch)
(symbol-value ,fetch-scheme-functions)))
,@body)))))
| null | https://raw.githubusercontent.com/Zulu-Inuoe/clution/b72f7afe5f770ff68a066184a389c23551863f7f/cl-clution/qlfile-libs/qlot-20180131-git/server.lisp | lisp | Use PATH If PATH is an URL, not an URL path. | (defpackage #:qlot/server
(:use #:cl)
(:import-from #:qlot/source
#:*dist-base-url*
#:prepare
#:source-prepared
#:url-path-for
#:project.txt
#:distinfo.txt
#:releases.txt
#:systems.txt
#:archive)
(:import-from #:qlot/parser
#:prepare-qlfile)
(:import-from #:qlot/tmp
#:*tmp-directory*)
(:import-from #:qlot/util
#:*system-quicklisp-home*
#:with-quicklisp-home)
(:import-from #:alexandria
#:when-let
#:once-only
#:with-gensyms)
(:import-from #:uiop
#:copy-file)
(:export #:localhost
#:with-qlot-server))
(in-package #:qlot/server)
(defvar *handler* nil)
(defun localhost (&optional (path ""))
(when (and (< 0 (length path))
(not (char= (aref path 0) #\/)))
(return-from localhost path))
(format nil "qlot~A" path))
(defun qlot-fetch (url file &key (follow-redirects t) quietly (maximum-redirects 10))
"Request URL and write the body of the response to FILE."
(declare (ignorable follow-redirects quietly maximum-redirects))
(let ((result (funcall *handler* `(:path-info ,url))))
(when (= (first result) 200)
(typecase (third result)
(list
(with-open-file (out file :direction :output :if-exists :supersede :if-does-not-exist :create)
(dolist (chunk (third result))
(princ chunk out))))
(pathname
(uiop:copy-file (third result) file)))))
(values (make-instance (intern (string '#:header) '#:ql-http) :status 200)
(probe-file file)))
(defun make-app (sources)
(flet ((make-route (source action)
(let ((action-name (symbol-name action)))
(lambda ()
(let* ((*dist-base-url* (localhost))
(res (funcall (symbol-function action) source)))
(list 200
(if (string-equal (subseq action-name (- (length action-name) 4))
".txt")
(list :content-type "text/plain")
'())
(if (stringp res)
(list res)
res)))))))
(let ((route (make-hash-table :test 'equal))
(tmp-directory *tmp-directory*))
(dolist (source sources)
(setf (gethash (localhost (url-path-for source 'project.txt)) route)
(lambda ()
(let ((*tmp-directory* tmp-directory))
(prepare source))
(dolist (action '(project.txt distinfo.txt releases.txt systems.txt archive))
(when-let (path (url-path-for source action))
(setf (gethash (localhost path) route)
(make-route source action))))
(funcall (make-route source 'project.txt)))))
(lambda (env)
(with-quicklisp-home *system-quicklisp-home*
(let ((fn (gethash (getf env :path-info) route))
(*tmp-directory* tmp-directory))
(if fn
(funcall fn)
'(404 (:content-type "text/plain") ("Not Found")))))))))
(defmacro with-qlot-server (sources &body body)
(once-only (sources)
(with-gensyms (fetch-scheme-functions)
`(let ((,fetch-scheme-functions (intern (string '#:*fetch-scheme-functions*) '#:ql-http))
(*handler* (make-app (if (pathnamep ,sources)
(prepare-qlfile ,sources)
,sources))))
(progv (list ,fetch-scheme-functions)
(list (cons '("qlot" . qlot-fetch)
(symbol-value ,fetch-scheme-functions)))
,@body)))))
|
606fa47bd5e50849f1c20021edad02ebc13fc18ed8fc55182e15c15d65457b96 | v-kolesnikov/sicp | 3_01.clj | (ns sicp.chapter03.3-01)
(defn make-accumulator
[start]
(let [counter (atom start)]
(fn [x] (swap! counter + x))))
| null | https://raw.githubusercontent.com/v-kolesnikov/sicp/4298de6083440a75898e97aad658025a8cecb631/src/sicp/chapter03/3_01.clj | clojure | (ns sicp.chapter03.3-01)
(defn make-accumulator
[start]
(let [counter (atom start)]
(fn [x] (swap! counter + x))))
| |
46401edf9da5e2b80388b92b767b811235023dab95666740e2c464a4dcb6fd7a | jrheard/voke | visualize.cljs | (ns voke.world.visualize
(:require [reagent.core :as r]
[voke.util :refer [timeout]]
[voke.world.generation :as generate]))
;; Constants
(def grid-width 100)
(def grid-height 100)
(def canvas-height 800)
(def canvas-width 800)
; TODO revisit *all* of these atoms
(defonce selected-tab (r/atom :drunkard))
(defonce rng-seed (atom (.valueOf (js/Date.))))
; drunkard's
(defonce num-empty-cells (r/atom 400))
; automata
(defonce initial-fill-chance (r/atom 0.45))
(defonce first-pass-survival-threshold (r/atom 4))
(defonce first-pass-birth-threshold (r/atom 5))
(defonce smoothing-pass-survival-threshold (r/atom 4))
(defonce smoothing-pass-birth-threshold (r/atom 5))
(defonce num-iterations (r/atom 10000))
(defonce smoothing-passes (r/atom 12))
(defn reset-rng-seed! []
(reset! rng-seed (.valueOf (js/Date.))))
Canvas manipulation
(defn get-ctx []
(-> "visualization-canvas"
(js/document.getElementById)
(.getContext "2d")))
(defn draw-grid
[grid]
(let [ctx (get-ctx)
width (count (first grid))
height (count grid)
cell-width (/ canvas-width width)
cell-height (/ canvas-height height)]
(.clearRect ctx 0 0 canvas-width canvas-height)
(set! (.-fillStyle ctx) "#CCC")
(loop [x 0 y 0]
(when (< y height)
(when (= (-> grid
(get y)
(get x))
:empty)
(doto ctx
(.beginPath)
(.rect (* x cell-width) (* y cell-height) cell-width cell-height)
(.fill)))
(recur (if (identical? (dec x) width) 0 (inc x))
(if (identical? (dec x) width) (inc y) y))))))
(defn generate-grid-and-draw []
(Math/seedrandom (str @rng-seed))
(let [grid
(condp = @selected-tab
:drunkard (generate/drunkards-walk grid-width grid-height @num-empty-cells)
:automata (generate/automata grid-width
grid-height
@initial-fill-chance
@first-pass-survival-threshold
@first-pass-birth-threshold
@num-iterations
@smoothing-passes
@smoothing-pass-survival-threshold
@smoothing-pass-birth-threshold)
:final (generate/automata 200 200 0.45 4 5 400000 12 4 5))]
(draw-grid grid)))
;; Reagent components
(defn slider
[an-atom min max step]
[:input {:type "range" :value @an-atom :min min :max max :step step
:style {:width "100%"}
:on-change (fn [e]
(reset! an-atom (js/parseFloat (.-target.value e)))
(generate-grid-and-draw))}])
(defn tab
[tab-kw text]
[:a.btn.pill {:href "#"
:class (when (= @selected-tab tab-kw)
"selected")
:on-click (fn [e]
(.preventDefault e)
(reset! selected-tab tab-kw)
(generate-grid-and-draw))}
text])
(defn ui []
[:div.content
[:p "Algorithm:"]
[:div.btn-group
[tab :drunkard "Drunkard's Walk"]
[tab :automata "Cellular Automata"]
[tab :final "Voke algorithm"]]
(when (= @selected-tab :drunkard)
[:div.drunkard-specific
[:p (str "Dig until there are " @num-empty-cells " empty cells in the grid")]
[slider num-empty-cells 0 2000 10]])
(when (= @selected-tab :automata)
[:div.cellular-specific
[:p (str "Chance for a given cell to be filled during intialization pass: " @initial-fill-chance)]
[slider initial-fill-chance 0 1 0.01]
[:p (str "Mininum # of neighbors for an alive cell to survive (first pass): " @first-pass-survival-threshold)]
[slider first-pass-survival-threshold 0 8 1]
[:p (str "Mininum # of neighbors for a cell to be born (first pass): " @first-pass-birth-threshold)]
[slider first-pass-birth-threshold 0 8 1]
[:p (str "Number of times to apply automata rules to random individual cells: " @num-iterations)]
[slider num-iterations 0 40000 5000]
[:p (str "Number of smoothing passes: " @smoothing-passes)]
[slider smoothing-passes 0 12 1]
[:p (str "Mininum # of neighbors for an alive cell to survive (smoothing pass): " @smoothing-pass-survival-threshold)]
[slider smoothing-pass-survival-threshold 0 8 1]
[:p (str "Mininum # of neighbors for a cell to be born (smoothing pass): " @smoothing-pass-birth-threshold)]
[slider smoothing-pass-birth-threshold 0 8 1]])
[:div.button-wrapper
[:a.generate-button
{:href "#"
:on-click (fn [e]
(.preventDefault e)
(reset-rng-seed!)
(generate-grid-and-draw))}
"generate a new one"]]
[:canvas {:id "visualization-canvas"
:width canvas-width
:height canvas-height
:style {:border "none"
:background-color "#333"}}]])
;; Main
(defn ^:export main []
(r/render-component [ui]
(js/document.getElementById "content"))
(generate-grid-and-draw))
| null | https://raw.githubusercontent.com/jrheard/voke/15b272955d214ce0c531fb2b8d645feb217255c2/src/voke/world/visualize.cljs | clojure | Constants
TODO revisit *all* of these atoms
drunkard's
automata
Reagent components
Main | (ns voke.world.visualize
(:require [reagent.core :as r]
[voke.util :refer [timeout]]
[voke.world.generation :as generate]))
(def grid-width 100)
(def grid-height 100)
(def canvas-height 800)
(def canvas-width 800)
(defonce selected-tab (r/atom :drunkard))
(defonce rng-seed (atom (.valueOf (js/Date.))))
(defonce num-empty-cells (r/atom 400))
(defonce initial-fill-chance (r/atom 0.45))
(defonce first-pass-survival-threshold (r/atom 4))
(defonce first-pass-birth-threshold (r/atom 5))
(defonce smoothing-pass-survival-threshold (r/atom 4))
(defonce smoothing-pass-birth-threshold (r/atom 5))
(defonce num-iterations (r/atom 10000))
(defonce smoothing-passes (r/atom 12))
(defn reset-rng-seed! []
(reset! rng-seed (.valueOf (js/Date.))))
Canvas manipulation
(defn get-ctx []
(-> "visualization-canvas"
(js/document.getElementById)
(.getContext "2d")))
(defn draw-grid
[grid]
(let [ctx (get-ctx)
width (count (first grid))
height (count grid)
cell-width (/ canvas-width width)
cell-height (/ canvas-height height)]
(.clearRect ctx 0 0 canvas-width canvas-height)
(set! (.-fillStyle ctx) "#CCC")
(loop [x 0 y 0]
(when (< y height)
(when (= (-> grid
(get y)
(get x))
:empty)
(doto ctx
(.beginPath)
(.rect (* x cell-width) (* y cell-height) cell-width cell-height)
(.fill)))
(recur (if (identical? (dec x) width) 0 (inc x))
(if (identical? (dec x) width) (inc y) y))))))
(defn generate-grid-and-draw []
(Math/seedrandom (str @rng-seed))
(let [grid
(condp = @selected-tab
:drunkard (generate/drunkards-walk grid-width grid-height @num-empty-cells)
:automata (generate/automata grid-width
grid-height
@initial-fill-chance
@first-pass-survival-threshold
@first-pass-birth-threshold
@num-iterations
@smoothing-passes
@smoothing-pass-survival-threshold
@smoothing-pass-birth-threshold)
:final (generate/automata 200 200 0.45 4 5 400000 12 4 5))]
(draw-grid grid)))
(defn slider
[an-atom min max step]
[:input {:type "range" :value @an-atom :min min :max max :step step
:style {:width "100%"}
:on-change (fn [e]
(reset! an-atom (js/parseFloat (.-target.value e)))
(generate-grid-and-draw))}])
(defn tab
[tab-kw text]
[:a.btn.pill {:href "#"
:class (when (= @selected-tab tab-kw)
"selected")
:on-click (fn [e]
(.preventDefault e)
(reset! selected-tab tab-kw)
(generate-grid-and-draw))}
text])
(defn ui []
[:div.content
[:p "Algorithm:"]
[:div.btn-group
[tab :drunkard "Drunkard's Walk"]
[tab :automata "Cellular Automata"]
[tab :final "Voke algorithm"]]
(when (= @selected-tab :drunkard)
[:div.drunkard-specific
[:p (str "Dig until there are " @num-empty-cells " empty cells in the grid")]
[slider num-empty-cells 0 2000 10]])
(when (= @selected-tab :automata)
[:div.cellular-specific
[:p (str "Chance for a given cell to be filled during intialization pass: " @initial-fill-chance)]
[slider initial-fill-chance 0 1 0.01]
[:p (str "Mininum # of neighbors for an alive cell to survive (first pass): " @first-pass-survival-threshold)]
[slider first-pass-survival-threshold 0 8 1]
[:p (str "Mininum # of neighbors for a cell to be born (first pass): " @first-pass-birth-threshold)]
[slider first-pass-birth-threshold 0 8 1]
[:p (str "Number of times to apply automata rules to random individual cells: " @num-iterations)]
[slider num-iterations 0 40000 5000]
[:p (str "Number of smoothing passes: " @smoothing-passes)]
[slider smoothing-passes 0 12 1]
[:p (str "Mininum # of neighbors for an alive cell to survive (smoothing pass): " @smoothing-pass-survival-threshold)]
[slider smoothing-pass-survival-threshold 0 8 1]
[:p (str "Mininum # of neighbors for a cell to be born (smoothing pass): " @smoothing-pass-birth-threshold)]
[slider smoothing-pass-birth-threshold 0 8 1]])
[:div.button-wrapper
[:a.generate-button
{:href "#"
:on-click (fn [e]
(.preventDefault e)
(reset-rng-seed!)
(generate-grid-and-draw))}
"generate a new one"]]
[:canvas {:id "visualization-canvas"
:width canvas-width
:height canvas-height
:style {:border "none"
:background-color "#333"}}]])
(defn ^:export main []
(r/render-component [ui]
(js/document.getElementById "content"))
(generate-grid-and-draw))
|
9bb4120eef12167cbe4b7027c1472a30896d8514864d0869fb597f7ae2a6e1df | haskell/cabal | cabal.test.hs | import Test.Cabal.Prelude
` signatures ` field used with cabal - version < 2.0
main = cabalTest $
fails $ cabal "check" []
| null | https://raw.githubusercontent.com/haskell/cabal/1da1893e985a5f51e9dae384880ef16e12383a19/cabal-testsuite/PackageTests/Check/ConfiguredPackage/Sanity/VersionSignatures/cabal.test.hs | haskell | import Test.Cabal.Prelude
` signatures ` field used with cabal - version < 2.0
main = cabalTest $
fails $ cabal "check" []
| |
cd784e8a712f6969d8d9e18f2cdef9d5575fccdd1ecff8e1c2a0cc1b5cb91af7 | timbertson/vdoml | event.ml | include Event_.Event
| null | https://raw.githubusercontent.com/timbertson/vdoml/fcbf81e89df989206bdad4a92327e593078525b2/src/event.ml | ocaml | include Event_.Event
| |
1f6f9f1cf2e4a8e6a480a31c61fc615202b68a64bf98e5042e7e5a00271191f4 | samplecount/shake-language-c | Language.hs | Copyright 2012 - 2014 Samplecount S.L.
--
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.
# LANGUAGE TemplateHaskell #
module Development.Shake.Language.C.Language (
Language(..)
, defaultLanguageMap
, languageOf
) where
import Development.Shake.FilePath (takeExtension)
-- | Source language.
--
-- Currently something derived from @C@.
data Language =
C -- ^ Plain old C
| Cpp -- ^ C++
| ObjC -- ^ Objective-C
^ Objective - C with C++ ( Apple extension )
^ Assembly
deriving (Enum, Eq, Show)
-- | Default mapping from file extension to source language.
defaultLanguageMap :: [(String, Language)]
defaultLanguageMap = concatMap f [
(C, [".c"])
, (Cpp, [".cc", ".CC", ".cpp", ".CPP", ".C", ".cxx", ".CXX"])
, (ObjC, [".m"])
, (ObjCpp, [".mm", ".M"])
, (Asm, [".s", ".S"])
]
where f (lang, exts) = map (\ext -> (ext, lang)) exts
-- | Determine the source language of a file based on its extension.
languageOf :: FilePath -> Maybe Language
languageOf = flip lookup defaultLanguageMap . takeExtension
| null | https://raw.githubusercontent.com/samplecount/shake-language-c/7eba37910bf711cc4c3fe6e7f065c8108858eea4/src/Development/Shake/Language/C/Language.hs | haskell |
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.
| Source language.
Currently something derived from @C@.
^ Plain old C
^ C++
^ Objective-C
| Default mapping from file extension to source language.
| Determine the source language of a file based on its extension. | Copyright 2012 - 2014 Samplecount S.L.
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
# LANGUAGE TemplateHaskell #
module Development.Shake.Language.C.Language (
Language(..)
, defaultLanguageMap
, languageOf
) where
import Development.Shake.FilePath (takeExtension)
data Language =
^ Objective - C with C++ ( Apple extension )
^ Assembly
deriving (Enum, Eq, Show)
defaultLanguageMap :: [(String, Language)]
defaultLanguageMap = concatMap f [
(C, [".c"])
, (Cpp, [".cc", ".CC", ".cpp", ".CPP", ".C", ".cxx", ".CXX"])
, (ObjC, [".m"])
, (ObjCpp, [".mm", ".M"])
, (Asm, [".s", ".S"])
]
where f (lang, exts) = map (\ext -> (ext, lang)) exts
languageOf :: FilePath -> Maybe Language
languageOf = flip lookup defaultLanguageMap . takeExtension
|
536f8def692438e973985bf7d324465e5d8b48e6883d48e8c7ba59aeee8e152f | thheller/shadow-experiments | worker.cljs | (ns todomvc.split.worker
(:require
[shadow.experiments.grove.worker :as sw]
[todomvc.split.env :as env]
[todomvc.split.db]))
;; this is running in the worker thread
(defn ^:dev/after-load after-load []
(sw/refresh-all-queries! env/rt-ref))
(defn init []
(sw/init! env/rt-ref)) | null | https://raw.githubusercontent.com/thheller/shadow-experiments/a2170c2214778b6b9a9253166383396d64d395a4/src/dev/todomvc/split/worker.cljs | clojure | this is running in the worker thread | (ns todomvc.split.worker
(:require
[shadow.experiments.grove.worker :as sw]
[todomvc.split.env :as env]
[todomvc.split.db]))
(defn ^:dev/after-load after-load []
(sw/refresh-all-queries! env/rt-ref))
(defn init []
(sw/init! env/rt-ref)) |
340b7edb37215c39d7612eb273d0b855b5ccb251c2665f357eccb4d7396ebef0 | helium/erlang-dkg | dkg_util.erl | -module(dkg_util).
-export([allnodes/1, wrap/2, commitment_cache_fun/0]).
allnodes(N) -> lists:seq(1, N).
%% wrap a subprotocol's outbound messages with a protocol identifier
-spec wrap(Tag :: {vss, non_neg_integer()}, [{multicast, Msg :: any()} | {unicast, non_neg_integer(), Msg :: any()}]) -> [{multicast, {Tag, Msg}} | {unicast, non_neg_integer(), {Tag, Msg}}].
wrap(_, []) ->
[];
wrap(Id, [{multicast, Msg}|T]) ->
[{multicast, {Id, Msg}}|wrap(Id, T)];
wrap(Id, [{unicast, Dest, Msg}|T]) ->
[{unicast, Dest, {Id, Msg}}|wrap(Id, T)];
wrap(Id, [{callback, Msg}|T]) ->
[{callback, {Id, Msg}}|wrap(Id, T)].
commitment_cache_fun() ->
T = ets:new(t, []),
fun Self({Ser, DeSer0}) ->
ets:insert(T, {erlang:phash2(Ser), DeSer0}),
ok;
Self(Ser) ->
case ets:lookup(T, erlang:phash2(Ser)) of
[] ->
DeSer = tc_bicommitment:deserialize(Ser),
ok = Self({Ser, DeSer}),
DeSer;
[{_, Res}] ->
Res
end
end.
| null | https://raw.githubusercontent.com/helium/erlang-dkg/a22b841ae6cb31b17e547a6f208e93fa35f04b7f/src/dkg_util.erl | erlang | wrap a subprotocol's outbound messages with a protocol identifier | -module(dkg_util).
-export([allnodes/1, wrap/2, commitment_cache_fun/0]).
allnodes(N) -> lists:seq(1, N).
-spec wrap(Tag :: {vss, non_neg_integer()}, [{multicast, Msg :: any()} | {unicast, non_neg_integer(), Msg :: any()}]) -> [{multicast, {Tag, Msg}} | {unicast, non_neg_integer(), {Tag, Msg}}].
wrap(_, []) ->
[];
wrap(Id, [{multicast, Msg}|T]) ->
[{multicast, {Id, Msg}}|wrap(Id, T)];
wrap(Id, [{unicast, Dest, Msg}|T]) ->
[{unicast, Dest, {Id, Msg}}|wrap(Id, T)];
wrap(Id, [{callback, Msg}|T]) ->
[{callback, {Id, Msg}}|wrap(Id, T)].
commitment_cache_fun() ->
T = ets:new(t, []),
fun Self({Ser, DeSer0}) ->
ets:insert(T, {erlang:phash2(Ser), DeSer0}),
ok;
Self(Ser) ->
case ets:lookup(T, erlang:phash2(Ser)) of
[] ->
DeSer = tc_bicommitment:deserialize(Ser),
ok = Self({Ser, DeSer}),
DeSer;
[{_, Res}] ->
Res
end
end.
|
1d63c2f00ef7a8a42cc1adda7eb03445d540c7af8cdb66a1a4161f27755bd816 | 8c6794b6/hpc-codecov | Report.hs | # LANGUAGE CPP #
-- |
Module : Trace . Hpc . . Report
Copyright : ( c ) 2022 8c6794b6
-- License: BSD3
Maintainer : 8c6794b6 < >
--
-- Generate Codecov report data.
module Trace.Hpc.Codecov.Report
( -- * Types
Report(..)
, CoverageEntry(..)
, LineHits
, Hit(..)
-- * Functions
, genReport
, genCoverageEntries
, emitCoverageJSON
) where
-- base
import Control.Exception (ErrorCall, handle, throw, throwIO)
import Control.Monad (mplus, when)
import Control.Monad.ST (ST)
import Data.Function (on)
import Data.List (foldl', intersperse)
import System.IO (IOMode (..), hPutStrLn, stderr, stdout,
withFile)
#if !MIN_VERSION_base(4,11,0)
import Data.Monoid ((<>))
#endif
-- array
import Data.Array.Base (unsafeAt)
import Data.Array.IArray (bounds, listArray, range, (!))
import Data.Array.MArray (newArray, readArray, writeArray)
import Data.Array.ST (STUArray, runSTUArray)
import Data.Array.Unboxed (UArray)
-- bytestring
import Data.ByteString.Builder (Builder, char7, hPutBuilder, intDec,
string7, stringUtf8)
-- directory
import System.Directory (doesFileExist)
-- filepath
import System.FilePath ((<.>), (</>))
-- hpc
import Trace.Hpc.Mix (BoxLabel (..), Mix (..), MixEntry,
readMix)
import Trace.Hpc.Tix (Tix (..), TixModule (..), readTix)
import Trace.Hpc.Util (HpcPos, fromHpcPos)
Internal
import Trace.Hpc.Codecov.Exception
-- ------------------------------------------------------------------------
--
-- Exported
--
-- ------------------------------------------------------------------------
-- | Data type to hold information for generating test coverage
-- report.
data Report = Report
{ reportTix :: FilePath
^ Input tix file .
, reportMixDirs :: [FilePath]
^ Directories containing mix files referred by the tix file .
, reportSrcDirs :: [FilePath]
-- ^ Directories containing source codes referred by the mix files.
, reportExcludes :: [String]
-- ^ Module name strings to exclude from coverage report.
, reportOutFile :: Maybe FilePath
-- ^ Output file to write JSON report, if given.
, reportVerbose :: Bool
-- ^ Flag for showing verbose message during report generation.
} deriving (Eq, Show)
#if MIN_VERSION_base(4,11,0)
instance Semigroup Report where
(<>) = mappendReport
#endif
instance Monoid Report where
mempty = emptyReport
#if !MIN_VERSION_base(4,16,0)
mappend = mappendReport
#endif
emptyReport :: Report
emptyReport = Report
{ reportTix = throw NoTarget
, reportMixDirs = []
, reportSrcDirs = []
, reportExcludes = []
, reportOutFile = Nothing
, reportVerbose = False
}
mappendReport :: Report -> Report -> Report
mappendReport r1 r2 =
let extend f = ((<>) `on` f) r1 r2
in Report { reportTix = reportTix r2
, reportMixDirs = extend reportMixDirs
, reportSrcDirs = extend reportSrcDirs
, reportExcludes = extend reportExcludes
, reportOutFile = (mplus `on` reportOutFile) r1 r2
, reportVerbose = ((||) `on` reportVerbose) r1 r2
}
-- | Single file entry in coverage report.
--
-- See the
-- <-custom-coverage-format Codecov documentation>
-- for detail.
data CoverageEntry =
CoverageEntry { ce_filename :: FilePath -- ^ Source code file name.
, ce_hits :: LineHits -- ^ Line hits of the file.
} deriving (Eq, Show)
-- | Pair of line number and hit tag.
type LineHits = [(Int, Hit)]
-- | Data type to represent coverage of source code line.
data Hit
= Missed -- ^ The line is not covered at all.
| Partial -- ^ The line is partially covered.
| Full -- ^ The line is fully covered.
deriving (Eq, Show)
-- | Generate report data from options.
genReport :: Report -> IO ()
genReport rpt =
do entries <- genCoverageEntries rpt
let mb_out = reportOutFile rpt
oname = maybe "stdout" show mb_out
say rpt ("Writing JSON report to " ++ oname)
emitCoverageJSON mb_out entries
say rpt "Done"
-- | Generate test coverage entries.
genCoverageEntries :: Report -> IO [CoverageEntry]
genCoverageEntries rpt =
readTixFile rpt (reportTix rpt) >>= tixToCoverage rpt
-- | Emit simple coverage JSON data.
emitCoverageJSON ::
Maybe FilePath -- ^ 'Just' output file name, or 'Nothing' for
-- 'stdout'.
-> [CoverageEntry] -- ^ Coverage entries to write.
-> IO ()
emitCoverageJSON mb_outfile entries = wrap emit
where
wrap = maybe ($ stdout) (`withFile` WriteMode) mb_outfile
emit = flip hPutBuilder (buildJSON entries)
-- ------------------------------------------------------------------------
--
Internal
--
-- ------------------------------------------------------------------------
-- | Build simple JSON report from coverage entries.
buildJSON :: [CoverageEntry] -> Builder
buildJSON entries = contents
where
contents =
braced (key (string7 "coverage") <>
braced (listify (map report entries))) <>
char7 '\n'
report ce =
key (stringUtf8 (ce_filename ce)) <>
braced (listify (map hit (ce_hits ce)))
key x = dquote x <> char7 ':'
dquote x = char7 '"' <> x <> char7 '"'
braced x = char7 '{' <> x <> char7 '}'
listify xs = mconcat (intersperse comma xs)
comma = char7 ','
hit (n, tag) =
case tag of
Missed -> k <> char7 '0'
Partial -> k <> dquote (char7 '1' <> char7 '/' <> char7 '2')
Full -> k <> char7 '1'
where
k = key (intDec n)
tixToCoverage :: Report -> Tix -> IO [CoverageEntry]
tixToCoverage rpt (Tix tms) = mapM (tixModuleToCoverage rpt)
(excludeModules rpt tms)
tixModuleToCoverage :: Report -> TixModule -> IO CoverageEntry
tixModuleToCoverage rpt tm@(TixModule name _hash _count _ixs) =
do say rpt ("Search mix: " ++ name)
Mix path _ _ _ entries <- readMixFile (reportMixDirs rpt) tm
say rpt ("Found mix: "++ path)
let Info _ min_line max_line hits = makeInfo tm entries
lineHits = makeLineHits min_line max_line hits
path' <- ensureSrcPath rpt path
return (CoverageEntry { ce_filename = path'
, ce_hits = lineHits })
-- | Exclude modules specified in given 'Report'.
excludeModules :: Report -> [TixModule] -> [TixModule]
excludeModules rpt = filter exclude
where
exclude (TixModule pkg_slash_name _ _ _) =
let modname = case break (== '/') pkg_slash_name of
(_, '/':name) -> name
(name, _) -> name
in notElem modname (reportExcludes rpt)
-- | Read tix file from file path, return a 'Tix' data or throw
a ' ' exception .
readTixFile :: Report -> FilePath -> IO Tix
readTixFile rpt path =
do mb_tix <- readTix path
case mb_tix of
Nothing -> throwIO (TixNotFound path)
Just tix -> say rpt ("Found tix file: " ++ path) >> return tix
-- | Search mix file under given directories, return a 'Mix' data or
throw a ' ' exception .
readMixFile :: [FilePath] -> TixModule -> IO Mix
readMixFile dirs tm@(TixModule name _h _c _i) =
handle handler (readMix dirs (Right tm))
where
handler :: ErrorCall -> IO a
handler _ = throwIO (MixNotFound name dirs')
dirs' = map (</> (name <.> "mix")) dirs
-- | Ensure the given source file exist, return the ensured 'FilePath'
or throw a ' ' exception .
ensureSrcPath :: Report -> FilePath -> IO FilePath
ensureSrcPath rpt path = go [] (reportSrcDirs rpt)
where
go acc [] = throwIO (SrcNotFound path acc)
go acc (dir:dirs) =
do let path' = dir </> path
exist <- doesFileExist path'
if exist
then do say rpt ("Found source: " ++ path')
return path'
else go (path':acc) dirs
-- | Print given message to 'stderr' when the verbose flag is 'True'.
say :: Report -> String -> IO ()
say rpt msg = when (reportVerbose rpt) (hPutStrLn stderr msg)
-- | Internal type synonym to represent code line hit.
type Tick = Int
-- | Internal type used for accumulating mix entries.
data Info =
Info {-# UNPACK #-} !Int -- ^ Index count
{-# UNPACK #-} !Int -- ^ Min line number
^ line number
![(HpcPos, Tick)] -- ^ Pair of position and hit
-- | Make line hits from intermediate info.
makeLineHits :: Int -> Int -> [(HpcPos, Tick)] -> LineHits
makeLineHits min_line max_line hits = ticksToHits (runSTUArray work)
where
work =
do arr <- newArray (min_line, max_line) ignored
mapM_ (updateHit arr) hits
return arr
updateHit arr (pos, hit) =
let (ls, _, _, _) = fromHpcPos pos
in updateOne arr hit ls
updateOne :: STUArray s Int Int -> Tick -> Int -> ST s ()
updateOne arr hit i =
do prev <- readArray arr i
writeArray arr i (mergeEntry prev hit)
mergeEntry prev hit
| isIgnored prev = hit
| isMissed prev, isMissed hit = missed
| isFull prev, isFull hit = full
| otherwise = partial
-- | Convert array of ticks to list of hits.
ticksToHits :: UArray Int Tick -> LineHits
ticksToHits arr = foldr f [] (range (bounds arr))
where
f i acc =
case arr ! i of
tck | isIgnored tck -> acc
| isMissed tck -> (i, Missed) : acc
| isFull tck -> (i, Full) : acc
| otherwise -> (i, Partial) : acc
ignored, missed, partial, full :: Tick
ignored = -1
missed = 0
partial = 1
full = 2
isIgnored :: Int -> Bool
isIgnored = (== ignored)
isMissed :: Int -> Bool
isMissed = (== missed)
isFull :: Int -> Bool
isFull = (== full)
notTicked, tickedOnlyTrue, tickedOnlyFalse, ticked :: Tick
notTicked = missed
tickedOnlyTrue = partial
tickedOnlyFalse = partial
ticked = full
See also : " utils / hpc / HpcMarkup.hs " in " ghc " git repository .
makeInfo :: TixModule -> [MixEntry] -> Info
makeInfo tm = foldl' f z
where
z = Info 0 maxBound 0 []
f (Info i min_line max_line acc) (pos, boxLabel) =
let binBox = case (isTicked i, isTicked (i+1)) of
(False, False) -> acc
(True, False) -> (pos, tickedOnlyTrue) : acc
(False, True) -> (pos, tickedOnlyFalse) : acc
(True, True) -> acc
tickBox = if isTicked i
then (pos, ticked) : acc
else (pos, notTicked) : acc
acc' = case boxLabel of
ExpBox {} -> tickBox
TopLevelBox {} -> tickBox
LocalBox {} -> tickBox
BinBox _ True -> binBox
_ -> acc
(ls, _, le, _) = fromHpcPos pos
in Info (i+1) (min ls min_line) (max le max_line) acc'
-- Hope that mix file does not contain out of bound index.
isTicked n = unsafeAt arr_tix n /= 0
arr_tix :: UArray Int Int
arr_tix = listArray (0, size - 1) (map fromIntegral tixs)
TixModule _name _hash size tixs = tm
| null | https://raw.githubusercontent.com/8c6794b6/hpc-codecov/bb450af48b51e4e71057385e5a966ecd0ac6660d/src/Trace/Hpc/Codecov/Report.hs | haskell | |
License: BSD3
Generate Codecov report data.
* Types
* Functions
base
array
bytestring
directory
filepath
hpc
------------------------------------------------------------------------
Exported
------------------------------------------------------------------------
| Data type to hold information for generating test coverage
report.
^ Directories containing source codes referred by the mix files.
^ Module name strings to exclude from coverage report.
^ Output file to write JSON report, if given.
^ Flag for showing verbose message during report generation.
| Single file entry in coverage report.
See the
<-custom-coverage-format Codecov documentation>
for detail.
^ Source code file name.
^ Line hits of the file.
| Pair of line number and hit tag.
| Data type to represent coverage of source code line.
^ The line is not covered at all.
^ The line is partially covered.
^ The line is fully covered.
| Generate report data from options.
| Generate test coverage entries.
| Emit simple coverage JSON data.
^ 'Just' output file name, or 'Nothing' for
'stdout'.
^ Coverage entries to write.
------------------------------------------------------------------------
------------------------------------------------------------------------
| Build simple JSON report from coverage entries.
| Exclude modules specified in given 'Report'.
| Read tix file from file path, return a 'Tix' data or throw
| Search mix file under given directories, return a 'Mix' data or
| Ensure the given source file exist, return the ensured 'FilePath'
| Print given message to 'stderr' when the verbose flag is 'True'.
| Internal type synonym to represent code line hit.
| Internal type used for accumulating mix entries.
# UNPACK #
^ Index count
# UNPACK #
^ Min line number
^ Pair of position and hit
| Make line hits from intermediate info.
| Convert array of ticks to list of hits.
Hope that mix file does not contain out of bound index. | # LANGUAGE CPP #
Module : Trace . Hpc . . Report
Copyright : ( c ) 2022 8c6794b6
Maintainer : 8c6794b6 < >
module Trace.Hpc.Codecov.Report
Report(..)
, CoverageEntry(..)
, LineHits
, Hit(..)
, genReport
, genCoverageEntries
, emitCoverageJSON
) where
import Control.Exception (ErrorCall, handle, throw, throwIO)
import Control.Monad (mplus, when)
import Control.Monad.ST (ST)
import Data.Function (on)
import Data.List (foldl', intersperse)
import System.IO (IOMode (..), hPutStrLn, stderr, stdout,
withFile)
#if !MIN_VERSION_base(4,11,0)
import Data.Monoid ((<>))
#endif
import Data.Array.Base (unsafeAt)
import Data.Array.IArray (bounds, listArray, range, (!))
import Data.Array.MArray (newArray, readArray, writeArray)
import Data.Array.ST (STUArray, runSTUArray)
import Data.Array.Unboxed (UArray)
import Data.ByteString.Builder (Builder, char7, hPutBuilder, intDec,
string7, stringUtf8)
import System.Directory (doesFileExist)
import System.FilePath ((<.>), (</>))
import Trace.Hpc.Mix (BoxLabel (..), Mix (..), MixEntry,
readMix)
import Trace.Hpc.Tix (Tix (..), TixModule (..), readTix)
import Trace.Hpc.Util (HpcPos, fromHpcPos)
Internal
import Trace.Hpc.Codecov.Exception
data Report = Report
{ reportTix :: FilePath
^ Input tix file .
, reportMixDirs :: [FilePath]
^ Directories containing mix files referred by the tix file .
, reportSrcDirs :: [FilePath]
, reportExcludes :: [String]
, reportOutFile :: Maybe FilePath
, reportVerbose :: Bool
} deriving (Eq, Show)
#if MIN_VERSION_base(4,11,0)
instance Semigroup Report where
(<>) = mappendReport
#endif
instance Monoid Report where
mempty = emptyReport
#if !MIN_VERSION_base(4,16,0)
mappend = mappendReport
#endif
emptyReport :: Report
emptyReport = Report
{ reportTix = throw NoTarget
, reportMixDirs = []
, reportSrcDirs = []
, reportExcludes = []
, reportOutFile = Nothing
, reportVerbose = False
}
mappendReport :: Report -> Report -> Report
mappendReport r1 r2 =
let extend f = ((<>) `on` f) r1 r2
in Report { reportTix = reportTix r2
, reportMixDirs = extend reportMixDirs
, reportSrcDirs = extend reportSrcDirs
, reportExcludes = extend reportExcludes
, reportOutFile = (mplus `on` reportOutFile) r1 r2
, reportVerbose = ((||) `on` reportVerbose) r1 r2
}
data CoverageEntry =
} deriving (Eq, Show)
type LineHits = [(Int, Hit)]
data Hit
deriving (Eq, Show)
genReport :: Report -> IO ()
genReport rpt =
do entries <- genCoverageEntries rpt
let mb_out = reportOutFile rpt
oname = maybe "stdout" show mb_out
say rpt ("Writing JSON report to " ++ oname)
emitCoverageJSON mb_out entries
say rpt "Done"
genCoverageEntries :: Report -> IO [CoverageEntry]
genCoverageEntries rpt =
readTixFile rpt (reportTix rpt) >>= tixToCoverage rpt
emitCoverageJSON ::
-> IO ()
emitCoverageJSON mb_outfile entries = wrap emit
where
wrap = maybe ($ stdout) (`withFile` WriteMode) mb_outfile
emit = flip hPutBuilder (buildJSON entries)
Internal
buildJSON :: [CoverageEntry] -> Builder
buildJSON entries = contents
where
contents =
braced (key (string7 "coverage") <>
braced (listify (map report entries))) <>
char7 '\n'
report ce =
key (stringUtf8 (ce_filename ce)) <>
braced (listify (map hit (ce_hits ce)))
key x = dquote x <> char7 ':'
dquote x = char7 '"' <> x <> char7 '"'
braced x = char7 '{' <> x <> char7 '}'
listify xs = mconcat (intersperse comma xs)
comma = char7 ','
hit (n, tag) =
case tag of
Missed -> k <> char7 '0'
Partial -> k <> dquote (char7 '1' <> char7 '/' <> char7 '2')
Full -> k <> char7 '1'
where
k = key (intDec n)
tixToCoverage :: Report -> Tix -> IO [CoverageEntry]
tixToCoverage rpt (Tix tms) = mapM (tixModuleToCoverage rpt)
(excludeModules rpt tms)
tixModuleToCoverage :: Report -> TixModule -> IO CoverageEntry
tixModuleToCoverage rpt tm@(TixModule name _hash _count _ixs) =
do say rpt ("Search mix: " ++ name)
Mix path _ _ _ entries <- readMixFile (reportMixDirs rpt) tm
say rpt ("Found mix: "++ path)
let Info _ min_line max_line hits = makeInfo tm entries
lineHits = makeLineHits min_line max_line hits
path' <- ensureSrcPath rpt path
return (CoverageEntry { ce_filename = path'
, ce_hits = lineHits })
excludeModules :: Report -> [TixModule] -> [TixModule]
excludeModules rpt = filter exclude
where
exclude (TixModule pkg_slash_name _ _ _) =
let modname = case break (== '/') pkg_slash_name of
(_, '/':name) -> name
(name, _) -> name
in notElem modname (reportExcludes rpt)
a ' ' exception .
readTixFile :: Report -> FilePath -> IO Tix
readTixFile rpt path =
do mb_tix <- readTix path
case mb_tix of
Nothing -> throwIO (TixNotFound path)
Just tix -> say rpt ("Found tix file: " ++ path) >> return tix
throw a ' ' exception .
readMixFile :: [FilePath] -> TixModule -> IO Mix
readMixFile dirs tm@(TixModule name _h _c _i) =
handle handler (readMix dirs (Right tm))
where
handler :: ErrorCall -> IO a
handler _ = throwIO (MixNotFound name dirs')
dirs' = map (</> (name <.> "mix")) dirs
or throw a ' ' exception .
ensureSrcPath :: Report -> FilePath -> IO FilePath
ensureSrcPath rpt path = go [] (reportSrcDirs rpt)
where
go acc [] = throwIO (SrcNotFound path acc)
go acc (dir:dirs) =
do let path' = dir </> path
exist <- doesFileExist path'
if exist
then do say rpt ("Found source: " ++ path')
return path'
else go (path':acc) dirs
say :: Report -> String -> IO ()
say rpt msg = when (reportVerbose rpt) (hPutStrLn stderr msg)
type Tick = Int
data Info =
^ line number
makeLineHits :: Int -> Int -> [(HpcPos, Tick)] -> LineHits
makeLineHits min_line max_line hits = ticksToHits (runSTUArray work)
where
work =
do arr <- newArray (min_line, max_line) ignored
mapM_ (updateHit arr) hits
return arr
updateHit arr (pos, hit) =
let (ls, _, _, _) = fromHpcPos pos
in updateOne arr hit ls
updateOne :: STUArray s Int Int -> Tick -> Int -> ST s ()
updateOne arr hit i =
do prev <- readArray arr i
writeArray arr i (mergeEntry prev hit)
mergeEntry prev hit
| isIgnored prev = hit
| isMissed prev, isMissed hit = missed
| isFull prev, isFull hit = full
| otherwise = partial
ticksToHits :: UArray Int Tick -> LineHits
ticksToHits arr = foldr f [] (range (bounds arr))
where
f i acc =
case arr ! i of
tck | isIgnored tck -> acc
| isMissed tck -> (i, Missed) : acc
| isFull tck -> (i, Full) : acc
| otherwise -> (i, Partial) : acc
ignored, missed, partial, full :: Tick
ignored = -1
missed = 0
partial = 1
full = 2
isIgnored :: Int -> Bool
isIgnored = (== ignored)
isMissed :: Int -> Bool
isMissed = (== missed)
isFull :: Int -> Bool
isFull = (== full)
notTicked, tickedOnlyTrue, tickedOnlyFalse, ticked :: Tick
notTicked = missed
tickedOnlyTrue = partial
tickedOnlyFalse = partial
ticked = full
See also : " utils / hpc / HpcMarkup.hs " in " ghc " git repository .
makeInfo :: TixModule -> [MixEntry] -> Info
makeInfo tm = foldl' f z
where
z = Info 0 maxBound 0 []
f (Info i min_line max_line acc) (pos, boxLabel) =
let binBox = case (isTicked i, isTicked (i+1)) of
(False, False) -> acc
(True, False) -> (pos, tickedOnlyTrue) : acc
(False, True) -> (pos, tickedOnlyFalse) : acc
(True, True) -> acc
tickBox = if isTicked i
then (pos, ticked) : acc
else (pos, notTicked) : acc
acc' = case boxLabel of
ExpBox {} -> tickBox
TopLevelBox {} -> tickBox
LocalBox {} -> tickBox
BinBox _ True -> binBox
_ -> acc
(ls, _, le, _) = fromHpcPos pos
in Info (i+1) (min ls min_line) (max le max_line) acc'
isTicked n = unsafeAt arr_tix n /= 0
arr_tix :: UArray Int Int
arr_tix = listArray (0, size - 1) (map fromIntegral tixs)
TixModule _name _hash size tixs = tm
|
4f678d17f7d96418c82a7a2f5f11645d014d60ae1e0816a786ebd7aa093c0473 | input-output-hk/plutus | Main.hs | -- editorconfig-checker-disable-file
{-# LANGUAGE LambdaCase #-}
# LANGUAGE TypeApplications #
module Main where
import Prelude ((<>))
import Prelude qualified as Hs
import Control.Lens hiding (argument)
import Control.Monad ()
import Control.Monad.Trans.Except (runExceptT)
import Data.ByteString qualified as BS
import Data.Char (isSpace)
import Data.Foldable (traverse_)
import Flat qualified
import Options.Applicative as Opt hiding (action)
import System.Exit (exitFailure)
import System.IO
import Text.PrettyPrint.ANSI.Leijen (Doc, indent, line, string, text, vsep)
import Text.Printf (printf)
import PlutusBenchmark.Common (toAnonDeBruijnTerm)
import PlutusBenchmark.NoFib.Clausify qualified as Clausify
import PlutusBenchmark.NoFib.Knights qualified as Knights
import PlutusBenchmark.NoFib.LastPiece qualified as LastPiece
import PlutusBenchmark.NoFib.Prime qualified as Prime
import PlutusBenchmark.NoFib.Queens qualified as Queens
import PlutusCore qualified as PLC
import PlutusCore.Default (DefaultFun, DefaultUni)
import PlutusCore.Evaluation.Machine.ExBudget (ExBudget (..))
import PlutusCore.Evaluation.Machine.ExBudgetingDefaults qualified as PLC
import PlutusCore.Evaluation.Machine.ExMemory (ExCPU (..), ExMemory (..))
import PlutusCore.Pretty (prettyPlcClassicDebug)
import PlutusTx (getPlcNoAnn)
import PlutusTx.Code (CompiledCode, sizePlc)
import PlutusTx.Prelude hiding (fmap, mappend, traverse_, (<$), (<$>), (<*>), (<>))
import UntypedPlutusCore qualified as UPLC
import UntypedPlutusCore.Evaluation.Machine.Cek qualified as UPLC
failWithMsg :: Hs.String -> IO a
failWithMsg s = hPutStrLn stderr s >> exitFailure
-- | A program together with its arguments
data ProgAndArgs =
Clausify Clausify.StaticFormula
| Queens Hs.Integer Queens.Algorithm
| Knights Hs.Integer Hs.Integer
| LastPiece
| Prime Prime.PrimeID
| Primetest Integer
-- | The actions this program can perform
data Options
= RunPLC ProgAndArgs
| RunHaskell ProgAndArgs
| DumpPLC ProgAndArgs
| DumpFlatNamed ProgAndArgs
| DumpFlatDeBruijn ProgAndArgs
| SizesAndBudgets
-- Clausify options --
knownFormulae :: Hs.String
knownFormulae = "one of F1, F2, F3, F4, F5, F6, F7"
clausifyFormulaReader :: Hs.String -> Either Hs.String Clausify.StaticFormula
clausifyFormulaReader "F1" = Right Clausify.F1
clausifyFormulaReader "F2" = Right Clausify.F2
clausifyFormulaReader "F3" = Right Clausify.F3
clausifyFormulaReader "F4" = Right Clausify.F4
clausifyFormulaReader "F5" = Right Clausify.F5
clausifyFormulaReader "F6" = Right Clausify.F6
clausifyFormulaReader "F7" = Right Clausify.F7
clausifyFormulaReader f = Left $ "Cannot parse `" <> f <> "`. Expected " ++ knownFormulae ++ "."
clausifyOptions :: Parser ProgAndArgs
clausifyOptions =
Clausify <$> argument (eitherReader clausifyFormulaReader)
(metavar "FORMULA" <>
help ("Formula to use for benchmarking: " ++ knownFormulae ++ "."))
Knights options --
knightsOptions :: Parser ProgAndArgs
knightsOptions =
Knights <$> argument auto (metavar "DEPTH" <>
help "Maximum search depth.")
<*> argument auto (metavar "BOARD-SIZE" <>
help "Board size (NxN)")
Lastpiece options --
lastpieceOptions :: Parser ProgAndArgs
lastpieceOptions = Hs.pure LastPiece
-- Primes options --
knownPrimes :: Hs.String
knownPrimes = "P05, P08, P10, P20, P30, P40, P50, P60, P100, P150, or P200 (a prime with the indicated number of digits)"
primeIdReader :: Hs.String -> Either Hs.String Prime.PrimeID
primeIdReader "P05" = Right Prime.P5
primeIdReader "P08" = Right Prime.P8
primeIdReader "P10" = Right Prime.P10
primeIdReader "P20" = Right Prime.P20
primeIdReader "P30" = Right Prime.P30
primeIdReader "P40" = Right Prime.P40
primeIdReader "P50" = Right Prime.P50
primeIdReader "P60" = Right Prime.P60
primeIdReader "P100" = Right Prime.P100
primeIdReader "P150" = Right Prime.P150
primeIdReader "P200" = Right Prime.P200
primeIdReader f = Left $ "Cannot parse `" <> f <> "`. Possible values are " ++ knownPrimes ++"."
| Apply the primality test to one of the built - in primes
primeOptions :: Parser ProgAndArgs
primeOptions =
Prime <$> (argument (eitherReader primeIdReader)
(metavar "ID" <> help ("Identifier for known prime: " ++ knownPrimes)))
Primetest options --
| Apply the primality test to a given integer instead of one of the built - in large primes
primetestOptions :: Parser ProgAndArgs
primetestOptions =
Primetest <$> (argument auto (metavar "N" <> help "a positive integer"))
Queens options --
knownAlgorithms :: Hs.String
knownAlgorithms = "bt, bm, bjbt1, bjbt2, fc"
queensAlgorithmReader :: Hs.String -> Either Hs.String Queens.Algorithm
queensAlgorithmReader "bt" = Right Queens.Bt
queensAlgorithmReader "bm" = Right Queens.Bm
queensAlgorithmReader "bjbt1" = Right Queens.Bjbt1
queensAlgorithmReader "bjbt2" = Right Queens.Bjbt2
queensAlgorithmReader "fc" = Right Queens.Fc
queensAlgorithmReader alg = Left $ "Unknown algorithm: " <> alg <> ". Options are " ++ knownAlgorithms
queensOptions :: Parser ProgAndArgs
queensOptions =
Queens <$> argument auto (metavar "BOARD-SIZE" <>
help "Size of the playing board NxN")
<*> (argument (eitherReader queensAlgorithmReader)
(metavar "ALGORITHM" <>
help ("Algorithm to use for constraint solving. One of: " ++ knownAlgorithms)))
-- Main parsers --
progAndArgs :: Parser ProgAndArgs
progAndArgs = hsubparser
( command "clausify" (info clausifyOptions (progDesc "Run the Clausify benchmark."))
<> command "queens" (info queensOptions (progDesc "Run the Queens benchmark."))
<> command "knights" (info knightsOptions (progDesc "Run the Knights benchmark"))
<> command "lastpiece" (info lastpieceOptions (progDesc "Run the Lastpiece benchmark"))
<> command "prime" (info primeOptions (progDesc "Run the Prime benchmark on a known prime (see help)"))
<> command "primetest" (info primetestOptions (progDesc "Run the Prime benchmark on a positive integer N")) )
options :: Parser Options
options = hsubparser
( command "run"
(info (RunPLC <$> progAndArgs)
(progDesc "same as runPLC"))
<> command "run-plc"
(info (RunPLC <$> progAndArgs)
(progDesc "compile the program to Plutus Core and evaluate it using the CEK machine"))
<> command "run-hs"
(info (RunHaskell <$> progAndArgs)
(progDesc "run the program directly as Hs"))
<> command "dump-plc"
(info (DumpPLC <$> progAndArgs)
(progDesc "print the program (applied to arguments) as Plutus Core source on standard output"))
<> command "dump-flat-named"
(info (DumpFlatNamed <$> progAndArgs)
(progDesc "dump the AST as Flat, preserving names"))
<> command "dump-flat"
(info (DumpFlatDeBruijn <$> progAndArgs)
(progDesc "same as dump-flat-deBruijn, but easier to type"))
<> command "dump-flat-deBruijn"
(info (DumpFlatDeBruijn <$> progAndArgs)
(progDesc "dump the AST as Flat, with names replaced by de Bruijn indices"))
<> command "sizes-and-budgets"
(info (Hs.pure SizesAndBudgets)
(progDesc "Print the size and cpu/memory budgets of each program"))
)
---------------- Evaluation ----------------
evaluateWithCek :: UPLC.Term UPLC.NamedDeBruijn DefaultUni DefaultFun () -> UPLC.EvaluationResult (UPLC.Term UPLC.NamedDeBruijn DefaultUni DefaultFun ())
evaluateWithCek = UPLC.unsafeExtractEvaluationResult . (\(fstT,_,_) -> fstT) . UPLC.runCekDeBruijn PLC.defaultCekParameters UPLC.restrictingEnormous UPLC.noEmitter
writeFlatNamed :: UPLC.Program UPLC.NamedDeBruijn DefaultUni DefaultFun () -> IO ()
writeFlatNamed prog = BS.putStr $ Flat.flat prog
writeFlatDeBruijn ::UPLC.Program UPLC.DeBruijn DefaultUni DefaultFun () -> IO ()
writeFlatDeBruijn prog = BS.putStr . Flat.flat $ prog
description :: Hs.String
description = "This program provides operations on a number of Plutus programs "
++ "ported from the nofib Hs test suite. "
++ "The programs are written in Hs and can be run directly "
++ "or compiled into Plutus Core and run on the CEK machine. "
++ "Compiled programs can also be output in a number of formats."
knownProgs :: [Doc]
knownProgs = map text ["clausify", "knights", "lastpiece", "prime", "primetest", "queens"]
-- Extra information about the available programs. We need a Doc because if you
-- just make it a string it removes newlines and other formatting. There's some
-- manual formatting in here because the text doesn't wrap as expected, presumably
-- due to what optparse-applicative is doing internally.
footerInfo :: Doc
footerInfo = text "Most commands take the name of a program and a (possbily empty) list of arguments."
<> line <> line
<> text "The available programs are: "
<> line
<> indent 2 (vsep knownProgs)
<> line <> line
<> string ("See 'nofib-exe run <programe-name> --help' for information about the arguments\n"
++ "for a particular program.")
<> line <> line
<> string ("The 'dump' commands construct a Plutus Core term applying the program to its\n"
++ "arguments and prints the result to the terminal in the specified format.\n"
++ "You'll probably want to redirect the output to a file.")
Copied pretty much directly from plutus - tx / testlib / PlutusTx / Test.hs
measureBudget :: CompiledCode a -> (Integer, Integer)
measureBudget compiledCode =
let programE = PLC.runQuote
$ runExceptT @PLC.FreeVariableError
$ traverseOf UPLC.progTerm UPLC.unDeBruijnTerm
$ getPlcNoAnn compiledCode
in case programE of
Left _ -> (-1,-1) -- Something has gone wrong but I don't care.
Right program ->
let (_, UPLC.TallyingSt _ budget) = UPLC.runCekNoEmit PLC.defaultCekParameters UPLC.tallying $ program ^. UPLC.progTerm
ExCPU cpu = exBudgetCPU budget
ExMemory mem = exBudgetMemory budget
in (Hs.fromIntegral cpu, Hs.fromIntegral mem)
getInfo :: (Hs.String, CompiledCode a) -> (Hs.String, Integer, Integer, Integer)
getInfo (name, code) =
let size = sizePlc code
(cpu, mem) = measureBudget code
in (name, size, cpu, mem)
printSizesAndBudgets :: IO ()
printSizesAndBudgets = do
-- The applied programs to measure, which are the same as the ones in the benchmarks.
We ca n't put all of these in one list because the ' a 's in ' CompiledCode a ' are different
let clausify = [ ("clausify/F1", Clausify.mkClausifyCode Clausify.F1)
, ("clausify/F2", Clausify.mkClausifyCode Clausify.F2)
, ("clausify/F3", Clausify.mkClausifyCode Clausify.F3)
, ("clausify/F4", Clausify.mkClausifyCode Clausify.F4)
, ("clausify/F5", Clausify.mkClausifyCode Clausify.F5)
]
knights = [ ( "knights/4x4", Knights.mkKnightsCode 100 4)
, ( "knights/6x6", Knights.mkKnightsCode 100 6)
, ( "knights/8x8", Knights.mkKnightsCode 100 8)
]
primetest = [ ("primes/05digits", Prime.mkPrimalityCode Prime.P5)
, ("primes/08digits", Prime.mkPrimalityCode Prime.P8)
, ("primes/10digits", Prime.mkPrimalityCode Prime.P10)
, ("primes/20digits", Prime.mkPrimalityCode Prime.P20)
, ("primes/30digits", Prime.mkPrimalityCode Prime.P30)
, ("primes/40digits", Prime.mkPrimalityCode Prime.P40)
, ("primes/50digits", Prime.mkPrimalityCode Prime.P50)
]
queens4x4 = [ ("queens4x4/bt", Queens.mkQueensCode 4 Queens.Bt)
, ("queens4x4/bm", Queens.mkQueensCode 4 Queens.Bm)
, ("queens4x4/bjbt1", Queens.mkQueensCode 4 Queens.Bjbt1)
, ("queens4x4/bjbt2", Queens.mkQueensCode 4 Queens.Bjbt2)
, ("queens4x4/fc", Queens.mkQueensCode 4 Queens.Fc)
]
queens5x5 = [ ("queens5x5/bt" ,Queens.mkQueensCode 5 Queens.Bt)
, ("queens5x5/bm" ,Queens.mkQueensCode 5 Queens.Bm)
, ("queens5x5/bjbt1" ,Queens.mkQueensCode 5 Queens.Bjbt1)
, ("queens5x5/bjbt2" ,Queens.mkQueensCode 5 Queens.Bjbt2)
, ("queens5x5/fc" ,Queens.mkQueensCode 5 Queens.Fc)
]
statistics = map getInfo clausify ++ map getInfo knights ++ map getInfo primetest ++ map getInfo queens4x4 ++ map getInfo queens5x5
formatInfo (name, size, cpu, mem) = printf "%-20s %10d %15d %15d\n" name size cpu mem
putStrLn "Script Size CPU budget Memory budget"
putStrLn "-----------------------------------------------------------------"
traverse_ (putStr . formatInfo) statistics
main :: IO ()
main = do
execParser (info (helper <*> options) (fullDesc <> progDesc description <> footerDoc (Just footerInfo))) >>= \case
RunPLC pa ->
print . prettyPlcClassicDebug . evaluateWithCek . getTerm $ pa
RunHaskell pa ->
case pa of
Clausify formula -> print $ Clausify.runClausify formula
Knights depth boardSize -> print $ Knights.runKnights depth boardSize
LastPiece -> print $ LastPiece.runLastPiece
Queens boardSize alg -> print $ Queens.runQueens boardSize alg
Prime input -> print $ Prime.runFixedPrimalityTest input
Primetest n -> if n<0 then Hs.error "Positive number expected"
else print $ Prime.runPrimalityTest n
DumpPLC pa ->
traverse_ putStrLn $ unindent . prettyPlcClassicDebug . UPLC.Program () PLC.latestVersion . getTerm $ pa
where unindent d = map (dropWhile isSpace) $ (Hs.lines . Hs.show $ d)
DumpFlatNamed pa ->
writeFlatNamed . UPLC.Program () PLC.latestVersion . getTerm $ pa
DumpFlatDeBruijn pa ->
writeFlatDeBruijn . UPLC.Program () PLC.latestVersion . toAnonDeBruijnTerm . getTerm $ pa
SizesAndBudgets
-> printSizesAndBudgets
-- Write the output to stdout and let the user deal with redirecting it.
where getTerm :: ProgAndArgs -> UPLC.Term UPLC.NamedDeBruijn DefaultUni DefaultFun ()
getTerm =
\case
Clausify formula -> Clausify.mkClausifyTerm formula
Queens boardSize alg -> Queens.mkQueensTerm boardSize alg
Knights depth boardSize -> Knights.mkKnightsTerm depth boardSize
LastPiece -> LastPiece.mkLastPieceTerm
Prime input -> Prime.mkPrimalityBenchTerm input
Primetest n -> if n<0 then Hs.error "Positive number expected"
else Prime.mkPrimalityTestTerm n
| null | https://raw.githubusercontent.com/input-output-hk/plutus/bb9b5a18c26476fbf6b2f446ab267706426fec3a/plutus-benchmark/nofib/exe/Main.hs | haskell | editorconfig-checker-disable-file
# LANGUAGE LambdaCase #
| A program together with its arguments
| The actions this program can perform
Clausify options --
Primes options --
Main parsers --
-------------- Evaluation ----------------
Extra information about the available programs. We need a Doc because if you
just make it a string it removes newlines and other formatting. There's some
manual formatting in here because the text doesn't wrap as expected, presumably
due to what optparse-applicative is doing internally.
Something has gone wrong but I don't care.
The applied programs to measure, which are the same as the ones in the benchmarks.
Write the output to stdout and let the user deal with redirecting it. | # LANGUAGE TypeApplications #
module Main where
import Prelude ((<>))
import Prelude qualified as Hs
import Control.Lens hiding (argument)
import Control.Monad ()
import Control.Monad.Trans.Except (runExceptT)
import Data.ByteString qualified as BS
import Data.Char (isSpace)
import Data.Foldable (traverse_)
import Flat qualified
import Options.Applicative as Opt hiding (action)
import System.Exit (exitFailure)
import System.IO
import Text.PrettyPrint.ANSI.Leijen (Doc, indent, line, string, text, vsep)
import Text.Printf (printf)
import PlutusBenchmark.Common (toAnonDeBruijnTerm)
import PlutusBenchmark.NoFib.Clausify qualified as Clausify
import PlutusBenchmark.NoFib.Knights qualified as Knights
import PlutusBenchmark.NoFib.LastPiece qualified as LastPiece
import PlutusBenchmark.NoFib.Prime qualified as Prime
import PlutusBenchmark.NoFib.Queens qualified as Queens
import PlutusCore qualified as PLC
import PlutusCore.Default (DefaultFun, DefaultUni)
import PlutusCore.Evaluation.Machine.ExBudget (ExBudget (..))
import PlutusCore.Evaluation.Machine.ExBudgetingDefaults qualified as PLC
import PlutusCore.Evaluation.Machine.ExMemory (ExCPU (..), ExMemory (..))
import PlutusCore.Pretty (prettyPlcClassicDebug)
import PlutusTx (getPlcNoAnn)
import PlutusTx.Code (CompiledCode, sizePlc)
import PlutusTx.Prelude hiding (fmap, mappend, traverse_, (<$), (<$>), (<*>), (<>))
import UntypedPlutusCore qualified as UPLC
import UntypedPlutusCore.Evaluation.Machine.Cek qualified as UPLC
failWithMsg :: Hs.String -> IO a
failWithMsg s = hPutStrLn stderr s >> exitFailure
data ProgAndArgs =
Clausify Clausify.StaticFormula
| Queens Hs.Integer Queens.Algorithm
| Knights Hs.Integer Hs.Integer
| LastPiece
| Prime Prime.PrimeID
| Primetest Integer
data Options
= RunPLC ProgAndArgs
| RunHaskell ProgAndArgs
| DumpPLC ProgAndArgs
| DumpFlatNamed ProgAndArgs
| DumpFlatDeBruijn ProgAndArgs
| SizesAndBudgets
knownFormulae :: Hs.String
knownFormulae = "one of F1, F2, F3, F4, F5, F6, F7"
clausifyFormulaReader :: Hs.String -> Either Hs.String Clausify.StaticFormula
clausifyFormulaReader "F1" = Right Clausify.F1
clausifyFormulaReader "F2" = Right Clausify.F2
clausifyFormulaReader "F3" = Right Clausify.F3
clausifyFormulaReader "F4" = Right Clausify.F4
clausifyFormulaReader "F5" = Right Clausify.F5
clausifyFormulaReader "F6" = Right Clausify.F6
clausifyFormulaReader "F7" = Right Clausify.F7
clausifyFormulaReader f = Left $ "Cannot parse `" <> f <> "`. Expected " ++ knownFormulae ++ "."
clausifyOptions :: Parser ProgAndArgs
clausifyOptions =
Clausify <$> argument (eitherReader clausifyFormulaReader)
(metavar "FORMULA" <>
help ("Formula to use for benchmarking: " ++ knownFormulae ++ "."))
knightsOptions :: Parser ProgAndArgs
knightsOptions =
Knights <$> argument auto (metavar "DEPTH" <>
help "Maximum search depth.")
<*> argument auto (metavar "BOARD-SIZE" <>
help "Board size (NxN)")
lastpieceOptions :: Parser ProgAndArgs
lastpieceOptions = Hs.pure LastPiece
knownPrimes :: Hs.String
knownPrimes = "P05, P08, P10, P20, P30, P40, P50, P60, P100, P150, or P200 (a prime with the indicated number of digits)"
primeIdReader :: Hs.String -> Either Hs.String Prime.PrimeID
primeIdReader "P05" = Right Prime.P5
primeIdReader "P08" = Right Prime.P8
primeIdReader "P10" = Right Prime.P10
primeIdReader "P20" = Right Prime.P20
primeIdReader "P30" = Right Prime.P30
primeIdReader "P40" = Right Prime.P40
primeIdReader "P50" = Right Prime.P50
primeIdReader "P60" = Right Prime.P60
primeIdReader "P100" = Right Prime.P100
primeIdReader "P150" = Right Prime.P150
primeIdReader "P200" = Right Prime.P200
primeIdReader f = Left $ "Cannot parse `" <> f <> "`. Possible values are " ++ knownPrimes ++"."
| Apply the primality test to one of the built - in primes
primeOptions :: Parser ProgAndArgs
primeOptions =
Prime <$> (argument (eitherReader primeIdReader)
(metavar "ID" <> help ("Identifier for known prime: " ++ knownPrimes)))
| Apply the primality test to a given integer instead of one of the built - in large primes
primetestOptions :: Parser ProgAndArgs
primetestOptions =
Primetest <$> (argument auto (metavar "N" <> help "a positive integer"))
knownAlgorithms :: Hs.String
knownAlgorithms = "bt, bm, bjbt1, bjbt2, fc"
queensAlgorithmReader :: Hs.String -> Either Hs.String Queens.Algorithm
queensAlgorithmReader "bt" = Right Queens.Bt
queensAlgorithmReader "bm" = Right Queens.Bm
queensAlgorithmReader "bjbt1" = Right Queens.Bjbt1
queensAlgorithmReader "bjbt2" = Right Queens.Bjbt2
queensAlgorithmReader "fc" = Right Queens.Fc
queensAlgorithmReader alg = Left $ "Unknown algorithm: " <> alg <> ". Options are " ++ knownAlgorithms
queensOptions :: Parser ProgAndArgs
queensOptions =
Queens <$> argument auto (metavar "BOARD-SIZE" <>
help "Size of the playing board NxN")
<*> (argument (eitherReader queensAlgorithmReader)
(metavar "ALGORITHM" <>
help ("Algorithm to use for constraint solving. One of: " ++ knownAlgorithms)))
progAndArgs :: Parser ProgAndArgs
progAndArgs = hsubparser
( command "clausify" (info clausifyOptions (progDesc "Run the Clausify benchmark."))
<> command "queens" (info queensOptions (progDesc "Run the Queens benchmark."))
<> command "knights" (info knightsOptions (progDesc "Run the Knights benchmark"))
<> command "lastpiece" (info lastpieceOptions (progDesc "Run the Lastpiece benchmark"))
<> command "prime" (info primeOptions (progDesc "Run the Prime benchmark on a known prime (see help)"))
<> command "primetest" (info primetestOptions (progDesc "Run the Prime benchmark on a positive integer N")) )
options :: Parser Options
options = hsubparser
( command "run"
(info (RunPLC <$> progAndArgs)
(progDesc "same as runPLC"))
<> command "run-plc"
(info (RunPLC <$> progAndArgs)
(progDesc "compile the program to Plutus Core and evaluate it using the CEK machine"))
<> command "run-hs"
(info (RunHaskell <$> progAndArgs)
(progDesc "run the program directly as Hs"))
<> command "dump-plc"
(info (DumpPLC <$> progAndArgs)
(progDesc "print the program (applied to arguments) as Plutus Core source on standard output"))
<> command "dump-flat-named"
(info (DumpFlatNamed <$> progAndArgs)
(progDesc "dump the AST as Flat, preserving names"))
<> command "dump-flat"
(info (DumpFlatDeBruijn <$> progAndArgs)
(progDesc "same as dump-flat-deBruijn, but easier to type"))
<> command "dump-flat-deBruijn"
(info (DumpFlatDeBruijn <$> progAndArgs)
(progDesc "dump the AST as Flat, with names replaced by de Bruijn indices"))
<> command "sizes-and-budgets"
(info (Hs.pure SizesAndBudgets)
(progDesc "Print the size and cpu/memory budgets of each program"))
)
evaluateWithCek :: UPLC.Term UPLC.NamedDeBruijn DefaultUni DefaultFun () -> UPLC.EvaluationResult (UPLC.Term UPLC.NamedDeBruijn DefaultUni DefaultFun ())
evaluateWithCek = UPLC.unsafeExtractEvaluationResult . (\(fstT,_,_) -> fstT) . UPLC.runCekDeBruijn PLC.defaultCekParameters UPLC.restrictingEnormous UPLC.noEmitter
writeFlatNamed :: UPLC.Program UPLC.NamedDeBruijn DefaultUni DefaultFun () -> IO ()
writeFlatNamed prog = BS.putStr $ Flat.flat prog
writeFlatDeBruijn ::UPLC.Program UPLC.DeBruijn DefaultUni DefaultFun () -> IO ()
writeFlatDeBruijn prog = BS.putStr . Flat.flat $ prog
description :: Hs.String
description = "This program provides operations on a number of Plutus programs "
++ "ported from the nofib Hs test suite. "
++ "The programs are written in Hs and can be run directly "
++ "or compiled into Plutus Core and run on the CEK machine. "
++ "Compiled programs can also be output in a number of formats."
knownProgs :: [Doc]
knownProgs = map text ["clausify", "knights", "lastpiece", "prime", "primetest", "queens"]
footerInfo :: Doc
footerInfo = text "Most commands take the name of a program and a (possbily empty) list of arguments."
<> line <> line
<> text "The available programs are: "
<> line
<> indent 2 (vsep knownProgs)
<> line <> line
<> string ("See 'nofib-exe run <programe-name> --help' for information about the arguments\n"
++ "for a particular program.")
<> line <> line
<> string ("The 'dump' commands construct a Plutus Core term applying the program to its\n"
++ "arguments and prints the result to the terminal in the specified format.\n"
++ "You'll probably want to redirect the output to a file.")
Copied pretty much directly from plutus - tx / testlib / PlutusTx / Test.hs
measureBudget :: CompiledCode a -> (Integer, Integer)
measureBudget compiledCode =
let programE = PLC.runQuote
$ runExceptT @PLC.FreeVariableError
$ traverseOf UPLC.progTerm UPLC.unDeBruijnTerm
$ getPlcNoAnn compiledCode
in case programE of
Right program ->
let (_, UPLC.TallyingSt _ budget) = UPLC.runCekNoEmit PLC.defaultCekParameters UPLC.tallying $ program ^. UPLC.progTerm
ExCPU cpu = exBudgetCPU budget
ExMemory mem = exBudgetMemory budget
in (Hs.fromIntegral cpu, Hs.fromIntegral mem)
getInfo :: (Hs.String, CompiledCode a) -> (Hs.String, Integer, Integer, Integer)
getInfo (name, code) =
let size = sizePlc code
(cpu, mem) = measureBudget code
in (name, size, cpu, mem)
printSizesAndBudgets :: IO ()
printSizesAndBudgets = do
We ca n't put all of these in one list because the ' a 's in ' CompiledCode a ' are different
let clausify = [ ("clausify/F1", Clausify.mkClausifyCode Clausify.F1)
, ("clausify/F2", Clausify.mkClausifyCode Clausify.F2)
, ("clausify/F3", Clausify.mkClausifyCode Clausify.F3)
, ("clausify/F4", Clausify.mkClausifyCode Clausify.F4)
, ("clausify/F5", Clausify.mkClausifyCode Clausify.F5)
]
knights = [ ( "knights/4x4", Knights.mkKnightsCode 100 4)
, ( "knights/6x6", Knights.mkKnightsCode 100 6)
, ( "knights/8x8", Knights.mkKnightsCode 100 8)
]
primetest = [ ("primes/05digits", Prime.mkPrimalityCode Prime.P5)
, ("primes/08digits", Prime.mkPrimalityCode Prime.P8)
, ("primes/10digits", Prime.mkPrimalityCode Prime.P10)
, ("primes/20digits", Prime.mkPrimalityCode Prime.P20)
, ("primes/30digits", Prime.mkPrimalityCode Prime.P30)
, ("primes/40digits", Prime.mkPrimalityCode Prime.P40)
, ("primes/50digits", Prime.mkPrimalityCode Prime.P50)
]
queens4x4 = [ ("queens4x4/bt", Queens.mkQueensCode 4 Queens.Bt)
, ("queens4x4/bm", Queens.mkQueensCode 4 Queens.Bm)
, ("queens4x4/bjbt1", Queens.mkQueensCode 4 Queens.Bjbt1)
, ("queens4x4/bjbt2", Queens.mkQueensCode 4 Queens.Bjbt2)
, ("queens4x4/fc", Queens.mkQueensCode 4 Queens.Fc)
]
queens5x5 = [ ("queens5x5/bt" ,Queens.mkQueensCode 5 Queens.Bt)
, ("queens5x5/bm" ,Queens.mkQueensCode 5 Queens.Bm)
, ("queens5x5/bjbt1" ,Queens.mkQueensCode 5 Queens.Bjbt1)
, ("queens5x5/bjbt2" ,Queens.mkQueensCode 5 Queens.Bjbt2)
, ("queens5x5/fc" ,Queens.mkQueensCode 5 Queens.Fc)
]
statistics = map getInfo clausify ++ map getInfo knights ++ map getInfo primetest ++ map getInfo queens4x4 ++ map getInfo queens5x5
formatInfo (name, size, cpu, mem) = printf "%-20s %10d %15d %15d\n" name size cpu mem
putStrLn "Script Size CPU budget Memory budget"
putStrLn "-----------------------------------------------------------------"
traverse_ (putStr . formatInfo) statistics
main :: IO ()
main = do
execParser (info (helper <*> options) (fullDesc <> progDesc description <> footerDoc (Just footerInfo))) >>= \case
RunPLC pa ->
print . prettyPlcClassicDebug . evaluateWithCek . getTerm $ pa
RunHaskell pa ->
case pa of
Clausify formula -> print $ Clausify.runClausify formula
Knights depth boardSize -> print $ Knights.runKnights depth boardSize
LastPiece -> print $ LastPiece.runLastPiece
Queens boardSize alg -> print $ Queens.runQueens boardSize alg
Prime input -> print $ Prime.runFixedPrimalityTest input
Primetest n -> if n<0 then Hs.error "Positive number expected"
else print $ Prime.runPrimalityTest n
DumpPLC pa ->
traverse_ putStrLn $ unindent . prettyPlcClassicDebug . UPLC.Program () PLC.latestVersion . getTerm $ pa
where unindent d = map (dropWhile isSpace) $ (Hs.lines . Hs.show $ d)
DumpFlatNamed pa ->
writeFlatNamed . UPLC.Program () PLC.latestVersion . getTerm $ pa
DumpFlatDeBruijn pa ->
writeFlatDeBruijn . UPLC.Program () PLC.latestVersion . toAnonDeBruijnTerm . getTerm $ pa
SizesAndBudgets
-> printSizesAndBudgets
where getTerm :: ProgAndArgs -> UPLC.Term UPLC.NamedDeBruijn DefaultUni DefaultFun ()
getTerm =
\case
Clausify formula -> Clausify.mkClausifyTerm formula
Queens boardSize alg -> Queens.mkQueensTerm boardSize alg
Knights depth boardSize -> Knights.mkKnightsTerm depth boardSize
LastPiece -> LastPiece.mkLastPieceTerm
Prime input -> Prime.mkPrimalityBenchTerm input
Primetest n -> if n<0 then Hs.error "Positive number expected"
else Prime.mkPrimalityTestTerm n
|
98e9a8c7b199fa06e00933ffead61e52e616cf1cc87678741e396acd875aa680 | pascalpoizat/fbpmn | Model.hs | module Fbpmn.Analysis.Alloy.Model where
data AlloyProperty = Safety | SimpleTermination | CorrectTermination
data AlloyAction = Run | Check
data AlloyVerification = AlloyVerification
{ action :: AlloyAction
, property :: AlloyProperty
, nb :: Natural
}
| null | https://raw.githubusercontent.com/pascalpoizat/fbpmn/f4c4443c40d576c76969b1fc971137c41bfc5c6f/src/Fbpmn/Analysis/Alloy/Model.hs | haskell | module Fbpmn.Analysis.Alloy.Model where
data AlloyProperty = Safety | SimpleTermination | CorrectTermination
data AlloyAction = Run | Check
data AlloyVerification = AlloyVerification
{ action :: AlloyAction
, property :: AlloyProperty
, nb :: Natural
}
| |
7733a38ae205b939c637b1dda86843894d6afd6bda618d5820d6e78e98aefec0 | csabahruska/jhc-components | Locale.hs | module System.Locale where
data TimeLocale = TimeLocale {
full and abbreviated week days
full and abbreviated months
amPm :: (String, String), -- AM/PM symbols
dateTimeFmt, dateFmt, -- formatting strings
timeFmt, time12Fmt :: String
} deriving (Eq, Ord,Show)
defaultTimeLocale :: TimeLocale
defaultTimeLocale = TimeLocale {
wDays = [("Sunday", "Sun"), ("Monday", "Mon"),
("Tuesday", "Tue"), ("Wednesday", "Wed"),
("Thursday", "Thu"), ("Friday", "Fri"),
("Saturday", "Sat")],
months = [("January", "Jan"), ("February", "Feb"),
("March", "Mar"), ("April", "Apr"),
("May", "May"), ("June", "Jun"),
("July", "Jul"), ("August", "Aug"),
("September", "Sep"), ("October", "Oct"),
("November", "Nov"), ("December", "Dec")],
amPm = ("AM", "PM"),
dateTimeFmt = "%a %b %e %H:%M:%S %Z %Y",
dateFmt = "%m/%d/%y",
timeFmt = "%H:%M:%S",
time12Fmt = "%I:%M:%S %p"
}
| null | https://raw.githubusercontent.com/csabahruska/jhc-components/a7dace481d017f5a83fbfc062bdd2d099133adf1/lib/haskell-extras/System/Locale.hs | haskell | AM/PM symbols
formatting strings | module System.Locale where
data TimeLocale = TimeLocale {
full and abbreviated week days
full and abbreviated months
timeFmt, time12Fmt :: String
} deriving (Eq, Ord,Show)
defaultTimeLocale :: TimeLocale
defaultTimeLocale = TimeLocale {
wDays = [("Sunday", "Sun"), ("Monday", "Mon"),
("Tuesday", "Tue"), ("Wednesday", "Wed"),
("Thursday", "Thu"), ("Friday", "Fri"),
("Saturday", "Sat")],
months = [("January", "Jan"), ("February", "Feb"),
("March", "Mar"), ("April", "Apr"),
("May", "May"), ("June", "Jun"),
("July", "Jul"), ("August", "Aug"),
("September", "Sep"), ("October", "Oct"),
("November", "Nov"), ("December", "Dec")],
amPm = ("AM", "PM"),
dateTimeFmt = "%a %b %e %H:%M:%S %Z %Y",
dateFmt = "%m/%d/%y",
timeFmt = "%H:%M:%S",
time12Fmt = "%I:%M:%S %p"
}
|
4bcb294455901d65d29add3441c8d34c4741438bbd07d7039f647981fcfb9726 | hammerlab/prohlatype | multi_par.ml | Typing via a Parametric PHMM .
open Prohlatype
open Cmdline_options
open Cmdliner
let app_name = "multi_par"
let to_read_size_dependent
(* Allele information source *)
file_prefix_or_directory
only_class1
gen_nuc_mgd
~distance
(* Cache logic. *)
~skip_disk_cache
=
let inputs =
(* We do NOT accept selectors. *)
file_prefix_or_directory_to_allele_input_list ~distance ~selectors:[]
file_prefix_or_directory only_class1 gen_nuc_mgd
in
begin fun read_size ->
List.map inputs ~f:(fun input ->
let par_phmm_args = Cache.par_phmm_args ~input ~read_size in
match Cache.par_phmm ~skip_disk_cache par_phmm_args with
| Ok phmm -> phmm
| Error e -> raise (Phmm_construction_error e))
end
module Pd = ParPHMM_drivers
module Sequential = Pd.Sequential(Pd.Multiple_loci)
module Parallel = Pd.Parallel(Pd.Multiple_loci)
let type_
(* Input *)
file_prefix_or_directory
only_class1
gen_nuc_mgd
(* Process *)
distance
skip_disk_cache
(* What to do? *)
fastq_file_lst
number_of_reads
specific_reads
do_not_finish_singles
(* options *)
number_processes_opt
insert_p
do_not_past_threshold_filter
max_number_mismatches
read_size_override
(* outputting logic. *)
allele_depth
likelihood_report_size
zygosity_report_size
zygosity_non_zero_value
per_reads_report_size
output_format
output
(* how are we typing *)
split
not_prealigned
forward_accuracy_opt
=
let commandline = String.concat ~sep:" " (Array.to_list Sys.argv) in
Option.value_map forward_accuracy_opt ~default:()
~f:(fun fa -> Probability.dx := fa);
let log_oc, data_oc = setup_oc output output_format in
let past_threshold_filter = not do_not_past_threshold_filter in
let prealigned_transition_model = not not_prealigned in
let finish_singles = not do_not_finish_singles in
let output_opt =
{ Pd.allele_depth
; output_format
; depth =
{ Pd.Output.num_likelihoods = likelihood_report_size
; num_zygosities = to_num_zygosities
~zygosity_non_zero_value
~zygosity_report_size
; num_per_read = per_reads_report_size
}
}
in
let conf =
Pd.multiple_conf ~insert_p ?max_number_mismatches ?split
~prealigned_transition_model ~past_threshold_filter
~output_opt
commandline
in
try
let need_read_size =
to_read_size_dependent ~distance ~skip_disk_cache
file_prefix_or_directory only_class1 gen_nuc_mgd
in
match number_processes_opt with
| None ->
let init =
match read_size_override with
| None -> `Setup need_read_size
| Some r -> `Set (Sequential.init log_oc need_read_size conf r)
in
at_most_two_fastqs fastq_file_lst
~single:(Sequential.across_fastq ~log_oc ~data_oc conf
?number_of_reads ~specific_reads init)
~paired:(Sequential.across_paired ~log_oc ~data_oc ~finish_singles conf
?number_of_reads ~specific_reads init)
| Some nprocs ->
begin match read_size_override with
| None -> errored Term.exit_status_cli_error
"Must specify read size override in parallel mode."
| Some r ->
let state = Parallel.init log_oc need_read_size conf r in
at_most_two_fastqs fastq_file_lst
~single:(Parallel.across_fastq ~log_oc ~data_oc conf
?number_of_reads ~specific_reads ~nprocs state)
~paired:(Parallel.across_paired ~log_oc ~data_oc conf
?number_of_reads ~specific_reads ~nprocs state)
end
with (Phmm_construction_error e) ->
errored phmm_construction_error "%s" e
let () =
let type_ =
let doc = "Use a Parametric Profile Hidden Markov Model of HLA allele to \
type fastq samples." in
let description =
[ `P "$(tname) uses sequence information found in FASTQ files to build a \
posterior distribution over HLA gene's alleles, thereby \
providing typing information."
; `P "We use a Profile Hidden Markov Model's (PHMM) forward pass's \
emission as a likelihood function in Bayes theorem to compute the \
posterior. Since computing such a forward for $(b,each) allele \
would be computationally infeasible, we parameterize the \
internal transitions such that we are able to compute the \
emission for $(b,all) alleles with one pass."
; `P "This tool (as opposed to $(b,par_type)) \
designed to work with multiple gene, as discussed in the \
preprint: $(i,Prohlatype: A Probabilistic Framework for HLA \
Typing), and is intended for robust typing."
; `P (sprintf
"In the default mode, $(tname) will aggregate read data found \
in the passed FASTQ files into diploid zygosity and \
per allele likelihoods. The tool will report only a subset of all \
possible zygosity likelihoods (control the number with --%s). \
Furthermore, for each read $(tname) will report the most likely \
alleles, their likely emission and the position with the largest \
emission. \
The --%s argument can change the number of elements that \
are reported for each read."
zygosity_report_size_argument
per_reads_report_size_argument)
]
in
let examples =
[ `P "Type samples based on merged HLA-A:"
; `Pre (sprintf "%s path-to-IMGTHLA/alignments/A sample.fastq" app_name)
; `P "Type samples based on cDNA HLA-A and paired reads:"
; `Pre (sprintf
"%s path-to-IMGTHLA/alignments/A_nuc sample_1.fastq sample_2.fastq"
app_name)
; `P "The most common usage case:"
; `Pre (sprintf
"%s path-to-IMGTHLA/alignments/ sample_1.fastq sample_2.fastq -o sample_output"
app_name)
; `P "Consider all allele information via merging, for just traditional \
class I genes and split the passes:"
; `Pre (sprintf
"%s --%s --%s --%s 4 -o sample_output
path-to-IMGTHLA/alignments/ sample_1.fastq sample_2.fastq"
merged_argument
only_class1_flag
split_argument
app_name)
]
in
let man =
let open Manpage in
[ `S s_description
; `Blocks description
; `S s_examples
; `Blocks examples
; `S s_bugs
; `P bugs
; `S s_authors
; `P author
]
in
Term.(const type_
(* Allele information source *)
$ (file_prefix_or_directory_arg "use as reference")
$ only_class1_directory_flag
$ gen_nuc_merged_flag
(* What to do ? *)
$ defaulting_distance_flag
$ (no_cache_flag "PHMM")
(* What are we typing *)
$ fastq_file_arg
$ num_reads_arg
$ specific_read_args
$ do_not_finish_singles_flag
(* options. *)
$ number_of_processors_arg
$ insert_probability_arg
$ do_not_past_threshold_filter_flag
$ max_number_mismatches_arg
$ read_size_override_arg
(* output logic. *)
$ allele_depth_info_arg
$ likelihood_report_size_arg
$ zygosity_report_size_arg
$ zygosity_non_zero_value_arg
$ per_reads_report_size_arg
$ output_format_flag
$ output_arg
(* How are we typing *)
$ split_arg
$ not_prealigned_flag
$ forward_pass_accuracy_arg
, info app_name
~version
~doc
~man
~exits:(phmm_construction_exit_info :: default_exits))
in
Term.(exit_status (eval type_))
| null | https://raw.githubusercontent.com/hammerlab/prohlatype/3acaf7154f93675fc729971d4c76c2b133e90ce6/src/app/multi_par.ml | ocaml | Allele information source
Cache logic.
We do NOT accept selectors.
Input
Process
What to do?
options
outputting logic.
how are we typing
Allele information source
What to do ?
What are we typing
options.
output logic.
How are we typing | Typing via a Parametric PHMM .
open Prohlatype
open Cmdline_options
open Cmdliner
let app_name = "multi_par"
let to_read_size_dependent
file_prefix_or_directory
only_class1
gen_nuc_mgd
~distance
~skip_disk_cache
=
let inputs =
file_prefix_or_directory_to_allele_input_list ~distance ~selectors:[]
file_prefix_or_directory only_class1 gen_nuc_mgd
in
begin fun read_size ->
List.map inputs ~f:(fun input ->
let par_phmm_args = Cache.par_phmm_args ~input ~read_size in
match Cache.par_phmm ~skip_disk_cache par_phmm_args with
| Ok phmm -> phmm
| Error e -> raise (Phmm_construction_error e))
end
module Pd = ParPHMM_drivers
module Sequential = Pd.Sequential(Pd.Multiple_loci)
module Parallel = Pd.Parallel(Pd.Multiple_loci)
let type_
file_prefix_or_directory
only_class1
gen_nuc_mgd
distance
skip_disk_cache
fastq_file_lst
number_of_reads
specific_reads
do_not_finish_singles
number_processes_opt
insert_p
do_not_past_threshold_filter
max_number_mismatches
read_size_override
allele_depth
likelihood_report_size
zygosity_report_size
zygosity_non_zero_value
per_reads_report_size
output_format
output
split
not_prealigned
forward_accuracy_opt
=
let commandline = String.concat ~sep:" " (Array.to_list Sys.argv) in
Option.value_map forward_accuracy_opt ~default:()
~f:(fun fa -> Probability.dx := fa);
let log_oc, data_oc = setup_oc output output_format in
let past_threshold_filter = not do_not_past_threshold_filter in
let prealigned_transition_model = not not_prealigned in
let finish_singles = not do_not_finish_singles in
let output_opt =
{ Pd.allele_depth
; output_format
; depth =
{ Pd.Output.num_likelihoods = likelihood_report_size
; num_zygosities = to_num_zygosities
~zygosity_non_zero_value
~zygosity_report_size
; num_per_read = per_reads_report_size
}
}
in
let conf =
Pd.multiple_conf ~insert_p ?max_number_mismatches ?split
~prealigned_transition_model ~past_threshold_filter
~output_opt
commandline
in
try
let need_read_size =
to_read_size_dependent ~distance ~skip_disk_cache
file_prefix_or_directory only_class1 gen_nuc_mgd
in
match number_processes_opt with
| None ->
let init =
match read_size_override with
| None -> `Setup need_read_size
| Some r -> `Set (Sequential.init log_oc need_read_size conf r)
in
at_most_two_fastqs fastq_file_lst
~single:(Sequential.across_fastq ~log_oc ~data_oc conf
?number_of_reads ~specific_reads init)
~paired:(Sequential.across_paired ~log_oc ~data_oc ~finish_singles conf
?number_of_reads ~specific_reads init)
| Some nprocs ->
begin match read_size_override with
| None -> errored Term.exit_status_cli_error
"Must specify read size override in parallel mode."
| Some r ->
let state = Parallel.init log_oc need_read_size conf r in
at_most_two_fastqs fastq_file_lst
~single:(Parallel.across_fastq ~log_oc ~data_oc conf
?number_of_reads ~specific_reads ~nprocs state)
~paired:(Parallel.across_paired ~log_oc ~data_oc conf
?number_of_reads ~specific_reads ~nprocs state)
end
with (Phmm_construction_error e) ->
errored phmm_construction_error "%s" e
let () =
let type_ =
let doc = "Use a Parametric Profile Hidden Markov Model of HLA allele to \
type fastq samples." in
let description =
[ `P "$(tname) uses sequence information found in FASTQ files to build a \
posterior distribution over HLA gene's alleles, thereby \
providing typing information."
; `P "We use a Profile Hidden Markov Model's (PHMM) forward pass's \
emission as a likelihood function in Bayes theorem to compute the \
posterior. Since computing such a forward for $(b,each) allele \
would be computationally infeasible, we parameterize the \
internal transitions such that we are able to compute the \
emission for $(b,all) alleles with one pass."
; `P "This tool (as opposed to $(b,par_type)) \
designed to work with multiple gene, as discussed in the \
preprint: $(i,Prohlatype: A Probabilistic Framework for HLA \
Typing), and is intended for robust typing."
; `P (sprintf
"In the default mode, $(tname) will aggregate read data found \
in the passed FASTQ files into diploid zygosity and \
per allele likelihoods. The tool will report only a subset of all \
possible zygosity likelihoods (control the number with --%s). \
Furthermore, for each read $(tname) will report the most likely \
alleles, their likely emission and the position with the largest \
emission. \
The --%s argument can change the number of elements that \
are reported for each read."
zygosity_report_size_argument
per_reads_report_size_argument)
]
in
let examples =
[ `P "Type samples based on merged HLA-A:"
; `Pre (sprintf "%s path-to-IMGTHLA/alignments/A sample.fastq" app_name)
; `P "Type samples based on cDNA HLA-A and paired reads:"
; `Pre (sprintf
"%s path-to-IMGTHLA/alignments/A_nuc sample_1.fastq sample_2.fastq"
app_name)
; `P "The most common usage case:"
; `Pre (sprintf
"%s path-to-IMGTHLA/alignments/ sample_1.fastq sample_2.fastq -o sample_output"
app_name)
; `P "Consider all allele information via merging, for just traditional \
class I genes and split the passes:"
; `Pre (sprintf
"%s --%s --%s --%s 4 -o sample_output
path-to-IMGTHLA/alignments/ sample_1.fastq sample_2.fastq"
merged_argument
only_class1_flag
split_argument
app_name)
]
in
let man =
let open Manpage in
[ `S s_description
; `Blocks description
; `S s_examples
; `Blocks examples
; `S s_bugs
; `P bugs
; `S s_authors
; `P author
]
in
Term.(const type_
$ (file_prefix_or_directory_arg "use as reference")
$ only_class1_directory_flag
$ gen_nuc_merged_flag
$ defaulting_distance_flag
$ (no_cache_flag "PHMM")
$ fastq_file_arg
$ num_reads_arg
$ specific_read_args
$ do_not_finish_singles_flag
$ number_of_processors_arg
$ insert_probability_arg
$ do_not_past_threshold_filter_flag
$ max_number_mismatches_arg
$ read_size_override_arg
$ allele_depth_info_arg
$ likelihood_report_size_arg
$ zygosity_report_size_arg
$ zygosity_non_zero_value_arg
$ per_reads_report_size_arg
$ output_format_flag
$ output_arg
$ split_arg
$ not_prealigned_flag
$ forward_pass_accuracy_arg
, info app_name
~version
~doc
~man
~exits:(phmm_construction_exit_info :: default_exits))
in
Term.(exit_status (eval type_))
|
9dd143863174c1541e2e8798901c54c679e86c79546d1735afb49a3e3949cd1d | hexlet-codebattle/battle_asserts | string_format.clj | (ns battle-asserts.issues.string-format
(:require [clojure.test.check.generators :as gen]))
(def level :elementary)
(def tags ["strings"])
(def description
{:en "Given a number as input, return a string \"Value is `num`\", where `num` is the given number with zeros added to the beginning so that there are 5 digits in total."
:ru "Верните строку \"Value is `num`\", где `num` число переданное в функцию. Дополните число нулями слева, если в нем меньше 5 цифр."})
(def signature
{:input [{:argument-name "num" :type {:name "integer"}}]
:output {:type {:name "string"}}})
(defn arguments-generator []
(gen/tuple (gen/one-of [(gen/choose 0 9)
(gen/choose 10 99)
(gen/choose 100 999)
(gen/choose 1000 9999)
(gen/choose 10000 99999)])))
(def test-data
[{:expected "Value is 00123"
:arguments [123]}
{:expected "Value is 00005"
:arguments [5]}
{:expected "Value is 12345"
:arguments [12345]}])
(defn solution [num]
(format "Value is %05d" num))
| null | https://raw.githubusercontent.com/hexlet-codebattle/battle_asserts/e571121ee5e79543cd158ed42061268556caff56/src/battle_asserts/issues/string_format.clj | clojure | (ns battle-asserts.issues.string-format
(:require [clojure.test.check.generators :as gen]))
(def level :elementary)
(def tags ["strings"])
(def description
{:en "Given a number as input, return a string \"Value is `num`\", where `num` is the given number with zeros added to the beginning so that there are 5 digits in total."
:ru "Верните строку \"Value is `num`\", где `num` число переданное в функцию. Дополните число нулями слева, если в нем меньше 5 цифр."})
(def signature
{:input [{:argument-name "num" :type {:name "integer"}}]
:output {:type {:name "string"}}})
(defn arguments-generator []
(gen/tuple (gen/one-of [(gen/choose 0 9)
(gen/choose 10 99)
(gen/choose 100 999)
(gen/choose 1000 9999)
(gen/choose 10000 99999)])))
(def test-data
[{:expected "Value is 00123"
:arguments [123]}
{:expected "Value is 00005"
:arguments [5]}
{:expected "Value is 12345"
:arguments [12345]}])
(defn solution [num]
(format "Value is %05d" num))
| |
b5ea5d7d836f4a0a8cd218dfeb5b073910b93e6f7f86bfbbb5c797ffb14dc02a | sentenai/reinforce | EpsilonGreedy.hs | module Reinforce.Policy.EpsilonGreedy where
import Control.Monad.IO.Class
import Data.List (maximumBy)
import Data.Ord (comparing)
import Control.MonadMWCRandom
epsilonGreedy :: (MonadIO m, Ord r, Variate r, MonadMWCRandom m) => [(a, r)] -> r -> m a
epsilonGreedy acts = epsilonChoice (fst $ maximumBy (comparing snd) acts) acts
epsilonChoice :: (MonadIO m, Ord r, Variate r, MonadMWCRandom m) => a -> [(a, r)] -> r -> m a
epsilonChoice a acts eps = do
compare eps <$> uniform >>= \case
LT -> pure a
_ -> do
i <- uniformR (0, length acts)
pure . fst . head $ drop (i-1) acts
| null | https://raw.githubusercontent.com/sentenai/reinforce/03fdeea14c606f4fe2390863778c99ebe1f0a7ee/reinforce-algorithms/src/Reinforce/Policy/EpsilonGreedy.hs | haskell | module Reinforce.Policy.EpsilonGreedy where
import Control.Monad.IO.Class
import Data.List (maximumBy)
import Data.Ord (comparing)
import Control.MonadMWCRandom
epsilonGreedy :: (MonadIO m, Ord r, Variate r, MonadMWCRandom m) => [(a, r)] -> r -> m a
epsilonGreedy acts = epsilonChoice (fst $ maximumBy (comparing snd) acts) acts
epsilonChoice :: (MonadIO m, Ord r, Variate r, MonadMWCRandom m) => a -> [(a, r)] -> r -> m a
epsilonChoice a acts eps = do
compare eps <$> uniform >>= \case
LT -> pure a
_ -> do
i <- uniformR (0, length acts)
pure . fst . head $ drop (i-1) acts
| |
1e6f9768de3866df81fe23eed71f084fe5384fa577cd1006f3870602c9314f46 | fission-codes/cli | Pin.hs | -- | Pin files via the CLI
module Fission.CLI.IPFS.Pin (add) where
import Fission.Prelude
import Servant.Client
import Network.IPFS.CID.Types
import Fission.Web.Client as Client
import qualified Fission.Web.Client.IPFS as Fission
import Fission.CLI.Display.Error as CLI.Error
import qualified Fission.CLI.Display.Loader as CLI
import Fission.CLI.Display.Success as CLI.Success
add ::
( MonadUnliftIO m
, MonadLogger m
, MonadWebClient m
)
=> CID
-> m (Either ClientError CID)
add cid@(CID hash) = do
logDebug <| "Remote pinning " <> display hash
result <- CLI.withLoader 50000
<| Client.run
<| Fission.pin cid
case result of
Right _ -> do
CLI.Success.live hash
return <| Right cid
Left err -> do
CLI.Error.put' err
return <| Left err
| null | https://raw.githubusercontent.com/fission-codes/cli/dc3500babad35a6cb44835fa503d27d672cbcdb3/library/Fission/CLI/IPFS/Pin.hs | haskell | | Pin files via the CLI | module Fission.CLI.IPFS.Pin (add) where
import Fission.Prelude
import Servant.Client
import Network.IPFS.CID.Types
import Fission.Web.Client as Client
import qualified Fission.Web.Client.IPFS as Fission
import Fission.CLI.Display.Error as CLI.Error
import qualified Fission.CLI.Display.Loader as CLI
import Fission.CLI.Display.Success as CLI.Success
add ::
( MonadUnliftIO m
, MonadLogger m
, MonadWebClient m
)
=> CID
-> m (Either ClientError CID)
add cid@(CID hash) = do
logDebug <| "Remote pinning " <> display hash
result <- CLI.withLoader 50000
<| Client.run
<| Fission.pin cid
case result of
Right _ -> do
CLI.Success.live hash
return <| Right cid
Left err -> do
CLI.Error.put' err
return <| Left err
|
abe41ac61d7a1d7f5de609d9c33520397093df037523c9152ee898a1ae8523d5 | racket/typed-racket | submodule.rkt | #lang typed/racket/base/shallow
;; Test importing a flat value
(module u racket/base
(define x 3)
(provide x))
(require/typed 'u
(x Byte))
(+ x 1)
| null | https://raw.githubusercontent.com/racket/typed-racket/1dde78d165472d67ae682b68622d2b7ee3e15e1e/typed-racket-test/succeed/shallow/submodule.rkt | racket | Test importing a flat value | #lang typed/racket/base/shallow
(module u racket/base
(define x 3)
(provide x))
(require/typed 'u
(x Byte))
(+ x 1)
|
a8cac1c9d182f5641ad4f0074caa742322cf269283bcfb49760544e49ff8ba90 | sjl/dram | project.clj | (defproject dram "0.1.0-SNAPSHOT"
:description "Clojure templating that won't make you want to drink."
:url "/"
:license {:name "MIT/X11"}
:dependencies [[org.clojure/clojure "1.4.0"]
[the/parsatron "0.0.3"]])
| null | https://raw.githubusercontent.com/sjl/dram/64d620ca4f90c2ce2128b15d19e20733fedb80b8/project.clj | clojure | (defproject dram "0.1.0-SNAPSHOT"
:description "Clojure templating that won't make you want to drink."
:url "/"
:license {:name "MIT/X11"}
:dependencies [[org.clojure/clojure "1.4.0"]
[the/parsatron "0.0.3"]])
| |
528977ce77348e21c9f706a910c45c3defd0c0ff4531206856b12f39d9434204 | dselsam/arc | DyeInputs.hs | Copyright ( c ) 2020 Microsoft Corporation . All rights reserved .
Released under Apache 2.0 license as described in the file LICENSE .
Authors : , , .
# LANGUAGE ScopedTypeVariables #
{-# LANGUAGE StrictData #-}
module Solver.Tactics.DyeInputs where
import Util.Imports
import qualified Util.List as List
import Solver.SolveM
import Solver.Goal
import qualified Synth.Ex as Ex
import Synth.Ex (Ex(..), ForTrain, ForTest)
import qualified Lib.Grid as Grid
import qualified Lib.Rect as Rect
import Lib.Axis
import Lib.Grid (Grid)
import Lib.Dims (Dims (Dims))
import Lib.Rect (Rect (Rect))
import qualified Lib.Dims as Dims
import qualified Data.Set as Set
import Solver.TacticResult (TacticResult(Decompose), Reconstruct, StdReconstruct)
import qualified Solver.TacticResult as TacticResult
import Lib.Color
import Lib.Blank
import Synth1.Basic
import qualified Data.Map as Map
import qualified Data.List as List
import qualified Util.List as List
import qualified Util.Map as Map
import Solver.Synth1Context (Synth1Context(..))
import Search.DFS
import Debug.Trace
` DyeInputs ` will try to infer / synthesize the following data for every input :
- ` cOut : Color `
- ` keep : Map Color Bool `
` DyeInputs ` will then apply the following transformation to all inputs : every color
will be dyed to ` cOut ` , unless if that color is in ` keep ` .
`DyeInputs` will try to infer/synthesize the following data for every input:
- `cOut : Color`
- `keep : Map Color Bool`
`DyeInputs` will then apply the following transformation to all inputs: every color
will be dyed to `cOut`, unless if that color is in `keep`.
-}
dyeInputs :: StdGoal -> SolveM TacticResult
dyeInputs goal = find1 "dyeInputs" $ choice "dyeInputs" [
("sameDims", dyeInputsSameDims goal),
("diffDims", dyeInputsDiffDims goal)
]
dyeInputsSameDims :: StdGoal -> SolveM TacticResult
dyeInputsSameDims goal@(Goal inputs outputs ctx) = do
guard $ all (uncurry Grid.sameDims) (zip (Ex.train inputs) outputs)
-- for input-output grids `g1` and `g2`, a color `c` is `kept`
-- if for every `idx`, `Grid.get g1 idx == c` implies that `Grid.get g2 idx == c`
(trainKeepMaps :: ForTrain (Map Color Bool), outputColors :: ForTrain Color) <- unzip <$> do
flip mapM (zip (Ex.train inputs) outputs) $ \(input, output) -> do
let keepMap :: Map Color Bool = Dims.iter (Grid.dims input) Map.empty $ \acc idx -> pure $
if nonBlank $ Grid.get input idx then
Map.insertWith (&&) (Grid.get input idx) (Grid.get input idx == Grid.get output idx) acc
else acc
let otherOutputColors :: Set Color = Dims.iter (Grid.dims input) Set.empty $ \acc idx -> pure $
if (nonBlank $ Grid.get output idx) && (Map.lookup (Grid.get input idx) keepMap /= Just True)
then Set.insert (Grid.get output idx) acc
else acc
guard $ Set.size otherOutputColors == 1
pure (keepMap, Set.elemAt 0 otherOutputColors)
let trainNonKeepInputColors :: ForTrain (Set Color) = flip map trainKeepMaps $ \trainKeepMap ->
Set.fromList (map fst . filter (not . snd) . Map.assocs $ trainKeepMap)
guard $ flip all trainNonKeepInputColors $ not . null
guard $ flip any (zip trainNonKeepInputColors outputColors) $ \(vs, color) ->
(Set.size vs > 1) || (Set.size vs == 1 && (Set.elemAt 0 vs) /= color)
testKeepMaps <- runSynth11 ctx $ synthG2KeepMaps inputs trainKeepMaps
testColors <- runSynth11 ctx $ synthG2C inputs outputColors
newInputs <- flip Ex.mapM (Ex.zip3 inputs (Ex trainKeepMaps testKeepMaps) (Ex outputColors testColors)) $ \(input, keepMap, outputColor) -> pure $
flip Grid.map input $ \idx c ->
if isBlank c then blank else
case Map.lookup c keepMap of
Just True -> c
_ -> outputColor
let testNonKeepInputColors :: ForTest (Set Color) = flip map testKeepMaps $ \testKeepMap ->
Set.fromList (map fst . filter (not . snd) . Map.assocs $ testKeepMap)
let newCtx = if flip Ex.all (Ex trainNonKeepInputColors testNonKeepInputColors) $ (== 1) . Set.size
then ctx { ctxColors = ("dyeInputs", Ex.map (Set.elemAt 0) $ Ex trainNonKeepInputColors testNonKeepInputColors):ctxColors ctx }
else ctx
-- @jesse: this is an assertion/sanity check right? are you sure you want silent failures for this?
guard $ flip all (zip (Ex.train newInputs) outputs) $ \(input, output) ->
(isJust . Grid.isUniform $ input) <= (isJust . Grid.isUniform $ output)
pure $ TacticResult.Decompose (goal {inputs = newInputs, synthCtx = newCtx}) pure
dyeInputsDiffDims :: StdGoal -> SolveM TacticResult
dyeInputsDiffDims goal@(Goal inputs outputs ctx) = do
guard $ not $ all (uncurry Grid.sameDims) (zip (Ex.train inputs) outputs)
outputColors :: ForTest Color <- flip mapM outputs $ \output -> do
let vs :: Set Color = Grid.distinctVals nonBlank output
guard $ Set.size vs == 1
pure . head . Set.toList $ vs
guard $ flip any (zip (Ex.train inputs) outputColors) $ \(input, color) ->
let vs :: Set Color = Grid.distinctVals nonBlank input in
(Set.size vs > 1) || (Set.size vs == 1 && (head . Set.toList $ vs) /= color)
testColors <- runSynth11 ctx $ synthG2C inputs outputColors
let newInputs = flip Ex.map (Ex.zip inputs (Ex outputColors testColors)) $ \(input, c) ->
Grid.map (\_ x -> if nonBlank x then c else blank) input
pure $ TacticResult.Decompose (goal { inputs = newInputs }) pure
synthG2C :: Ex (Grid Color) -> ForTrain Color -> Synth1M (ForTest Color)
synthG2C inputs outputs = choice "synthG2C" [
("groupSetValueMaps", do
allColors :: [Color] <- enumGroupSetValueMaps Grid.enumColorSets (Ex.toBigList inputs)
let cs = Ex.fromBigList allColors (Ex.getInfo inputs)
guard $ Ex.train cs == outputs
pure $ Ex.test cs),
("enumColor", do
cs <- enumColorsCtx
guard $ Ex.train cs == outputs
pure $ Ex.test cs)
]
synthG2KeepMaps :: Ex (Grid Color) -> ForTrain (Map Color Bool) -> Synth1M (ForTest (Map Color Bool))
synthG2KeepMaps inputs trainKeepMaps = choice "synthG2KeepMaps" [
("uniformKeepMaps", replicate (length $ test inputs) <$> (liftO $ Map.glueMaps trainKeepMaps))]
| null | https://raw.githubusercontent.com/dselsam/arc/7e68a7ed9508bf26926b0f68336db05505f4e765/src/Solver/Tactics/DyeInputs.hs | haskell | # LANGUAGE StrictData #
for input-output grids `g1` and `g2`, a color `c` is `kept`
if for every `idx`, `Grid.get g1 idx == c` implies that `Grid.get g2 idx == c`
@jesse: this is an assertion/sanity check right? are you sure you want silent failures for this? | Copyright ( c ) 2020 Microsoft Corporation . All rights reserved .
Released under Apache 2.0 license as described in the file LICENSE .
Authors : , , .
# LANGUAGE ScopedTypeVariables #
module Solver.Tactics.DyeInputs where
import Util.Imports
import qualified Util.List as List
import Solver.SolveM
import Solver.Goal
import qualified Synth.Ex as Ex
import Synth.Ex (Ex(..), ForTrain, ForTest)
import qualified Lib.Grid as Grid
import qualified Lib.Rect as Rect
import Lib.Axis
import Lib.Grid (Grid)
import Lib.Dims (Dims (Dims))
import Lib.Rect (Rect (Rect))
import qualified Lib.Dims as Dims
import qualified Data.Set as Set
import Solver.TacticResult (TacticResult(Decompose), Reconstruct, StdReconstruct)
import qualified Solver.TacticResult as TacticResult
import Lib.Color
import Lib.Blank
import Synth1.Basic
import qualified Data.Map as Map
import qualified Data.List as List
import qualified Util.List as List
import qualified Util.Map as Map
import Solver.Synth1Context (Synth1Context(..))
import Search.DFS
import Debug.Trace
` DyeInputs ` will try to infer / synthesize the following data for every input :
- ` cOut : Color `
- ` keep : Map Color Bool `
` DyeInputs ` will then apply the following transformation to all inputs : every color
will be dyed to ` cOut ` , unless if that color is in ` keep ` .
`DyeInputs` will try to infer/synthesize the following data for every input:
- `cOut : Color`
- `keep : Map Color Bool`
`DyeInputs` will then apply the following transformation to all inputs: every color
will be dyed to `cOut`, unless if that color is in `keep`.
-}
dyeInputs :: StdGoal -> SolveM TacticResult
dyeInputs goal = find1 "dyeInputs" $ choice "dyeInputs" [
("sameDims", dyeInputsSameDims goal),
("diffDims", dyeInputsDiffDims goal)
]
dyeInputsSameDims :: StdGoal -> SolveM TacticResult
dyeInputsSameDims goal@(Goal inputs outputs ctx) = do
guard $ all (uncurry Grid.sameDims) (zip (Ex.train inputs) outputs)
(trainKeepMaps :: ForTrain (Map Color Bool), outputColors :: ForTrain Color) <- unzip <$> do
flip mapM (zip (Ex.train inputs) outputs) $ \(input, output) -> do
let keepMap :: Map Color Bool = Dims.iter (Grid.dims input) Map.empty $ \acc idx -> pure $
if nonBlank $ Grid.get input idx then
Map.insertWith (&&) (Grid.get input idx) (Grid.get input idx == Grid.get output idx) acc
else acc
let otherOutputColors :: Set Color = Dims.iter (Grid.dims input) Set.empty $ \acc idx -> pure $
if (nonBlank $ Grid.get output idx) && (Map.lookup (Grid.get input idx) keepMap /= Just True)
then Set.insert (Grid.get output idx) acc
else acc
guard $ Set.size otherOutputColors == 1
pure (keepMap, Set.elemAt 0 otherOutputColors)
let trainNonKeepInputColors :: ForTrain (Set Color) = flip map trainKeepMaps $ \trainKeepMap ->
Set.fromList (map fst . filter (not . snd) . Map.assocs $ trainKeepMap)
guard $ flip all trainNonKeepInputColors $ not . null
guard $ flip any (zip trainNonKeepInputColors outputColors) $ \(vs, color) ->
(Set.size vs > 1) || (Set.size vs == 1 && (Set.elemAt 0 vs) /= color)
testKeepMaps <- runSynth11 ctx $ synthG2KeepMaps inputs trainKeepMaps
testColors <- runSynth11 ctx $ synthG2C inputs outputColors
newInputs <- flip Ex.mapM (Ex.zip3 inputs (Ex trainKeepMaps testKeepMaps) (Ex outputColors testColors)) $ \(input, keepMap, outputColor) -> pure $
flip Grid.map input $ \idx c ->
if isBlank c then blank else
case Map.lookup c keepMap of
Just True -> c
_ -> outputColor
let testNonKeepInputColors :: ForTest (Set Color) = flip map testKeepMaps $ \testKeepMap ->
Set.fromList (map fst . filter (not . snd) . Map.assocs $ testKeepMap)
let newCtx = if flip Ex.all (Ex trainNonKeepInputColors testNonKeepInputColors) $ (== 1) . Set.size
then ctx { ctxColors = ("dyeInputs", Ex.map (Set.elemAt 0) $ Ex trainNonKeepInputColors testNonKeepInputColors):ctxColors ctx }
else ctx
guard $ flip all (zip (Ex.train newInputs) outputs) $ \(input, output) ->
(isJust . Grid.isUniform $ input) <= (isJust . Grid.isUniform $ output)
pure $ TacticResult.Decompose (goal {inputs = newInputs, synthCtx = newCtx}) pure
dyeInputsDiffDims :: StdGoal -> SolveM TacticResult
dyeInputsDiffDims goal@(Goal inputs outputs ctx) = do
guard $ not $ all (uncurry Grid.sameDims) (zip (Ex.train inputs) outputs)
outputColors :: ForTest Color <- flip mapM outputs $ \output -> do
let vs :: Set Color = Grid.distinctVals nonBlank output
guard $ Set.size vs == 1
pure . head . Set.toList $ vs
guard $ flip any (zip (Ex.train inputs) outputColors) $ \(input, color) ->
let vs :: Set Color = Grid.distinctVals nonBlank input in
(Set.size vs > 1) || (Set.size vs == 1 && (head . Set.toList $ vs) /= color)
testColors <- runSynth11 ctx $ synthG2C inputs outputColors
let newInputs = flip Ex.map (Ex.zip inputs (Ex outputColors testColors)) $ \(input, c) ->
Grid.map (\_ x -> if nonBlank x then c else blank) input
pure $ TacticResult.Decompose (goal { inputs = newInputs }) pure
synthG2C :: Ex (Grid Color) -> ForTrain Color -> Synth1M (ForTest Color)
synthG2C inputs outputs = choice "synthG2C" [
("groupSetValueMaps", do
allColors :: [Color] <- enumGroupSetValueMaps Grid.enumColorSets (Ex.toBigList inputs)
let cs = Ex.fromBigList allColors (Ex.getInfo inputs)
guard $ Ex.train cs == outputs
pure $ Ex.test cs),
("enumColor", do
cs <- enumColorsCtx
guard $ Ex.train cs == outputs
pure $ Ex.test cs)
]
synthG2KeepMaps :: Ex (Grid Color) -> ForTrain (Map Color Bool) -> Synth1M (ForTest (Map Color Bool))
synthG2KeepMaps inputs trainKeepMaps = choice "synthG2KeepMaps" [
("uniformKeepMaps", replicate (length $ test inputs) <$> (liftO $ Map.glueMaps trainKeepMaps))]
|
5d2f371ab76cfa564724feb2140e2ae1bbfe4901ed9f9193e4e52cbc4327b739 | dyzsr/ocaml-selectml | test.ml | (* TEST
* expect
*)
module Exp =
struct
type _ t =
| IntLit : int -> int t
| BoolLit : bool -> bool t
| Pair : 'a t * 'b t -> ('a * 'b) t
| App : ('a -> 'b) t * 'a t -> 'b t
| Abs : ('a -> 'b) -> ('a -> 'b) t
let rec eval : type s . s t -> s =
function
| IntLit x -> x
| BoolLit y -> y
| Pair (x,y) ->
(eval x,eval y)
| App (f,a) ->
(eval f) (eval a)
| Abs f -> f
let discern : type a. a t -> _ = function
IntLit _ -> 1
| BoolLit _ -> 2
| Pair _ -> 3
| App _ -> 4
| Abs _ -> 5
end
;;
[%%expect{|
module Exp :
sig
type _ t =
IntLit : int -> int t
| BoolLit : bool -> bool t
| Pair : 'a t * 'b t -> ('a * 'b) t
| App : ('a -> 'b) t * 'a t -> 'b t
| Abs : ('a -> 'b) -> ('a -> 'b) t
val eval : 's t -> 's
val discern : 'a t -> int
end
|}];;
module List =
struct
type zero
type _ t =
| Nil : zero t
| Cons : 'a * 'b t -> ('a * 'b) t
let head =
function
| Cons (a,b) -> a
let tail =
function
| Cons (a,b) -> b
let rec length : type a . a t -> int =
function
| Nil -> 0
| Cons (a,b) -> length b
end
;;
[%%expect{|
module List :
sig
type zero
type _ t = Nil : zero t | Cons : 'a * 'b t -> ('a * 'b) t
val head : ('a * 'b) t -> 'a
val tail : ('a * 'b) t -> 'b t
val length : 'a t -> int
end
|}];;
module Nonexhaustive =
struct
type 'a u =
| C1 : int -> int u
| C2 : bool -> bool u
type 'a v =
| C1 : int -> int v
let unexhaustive : type s . s u -> s =
function
| C2 x -> x
module M : sig type t type u end =
struct
type t = int
type u = bool
end
type 'a t =
| Foo : M.t -> M.t t
| Bar : M.u -> M.u t
let same_type : type s . s t * s t -> bool =
function
| Foo _ , Foo _ -> true
| Bar _, Bar _ -> true
end
;;
[%%expect{|
Lines 11-12, characters 6-19:
11 | ......function
12 | | C2 x -> x
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
C1 _
Lines 24-26, characters 6-30:
24 | ......function
25 | | Foo _ , Foo _ -> true
26 | | Bar _, Bar _ -> true
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
(Foo _, Bar _)
module Nonexhaustive :
sig
type 'a u = C1 : int -> int u | C2 : bool -> bool u
type 'a v = C1 : int -> int v
val unexhaustive : 's u -> 's
module M : sig type t type u end
type 'a t = Foo : M.t -> M.t t | Bar : M.u -> M.u t
val same_type : 's t * 's t -> bool
end
|}];;
module Exhaustive =
struct
type t = int
type u = bool
type 'a v =
| Foo : t -> t v
| Bar : u -> u v
let same_type : type s . s v * s v -> bool =
function
| Foo _ , Foo _ -> true
| Bar _, Bar _ -> true
end
;;
[%%expect{|
module Exhaustive :
sig
type t = int
type u = bool
type 'a v = Foo : t -> t v | Bar : u -> u v
val same_type : 's v * 's v -> bool
end
|}];;
module PR6862 = struct
class c (Some x) = object method x : int = x end
type _ opt = Just : 'a -> 'a opt | Nothing : 'a opt
class d (Just x) = object method x : int = x end
end;;
[%%expect{|
Line 2, characters 10-18:
2 | class c (Some x) = object method x : int = x end
^^^^^^^^
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
None
Line 4, characters 10-18:
4 | class d (Just x) = object method x : int = x end
^^^^^^^^
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
Nothing
module PR6862 :
sig
class c : int option -> object method x : int end
type _ opt = Just : 'a -> 'a opt | Nothing : 'a opt
class d : int opt -> object method x : int end
end
|}];;
module Exhaustive2 = struct
type _ t = Int : int t
let f (x : bool t option) = match x with None -> ()
end;;
[%%expect{|
module Exhaustive2 :
sig type _ t = Int : int t val f : bool t option -> unit end
|}];;
module PR6220 = struct
type 'a t = I : int t | F : float t
let f : int t -> int = function I -> 1
let g : int t -> int = function I -> 1 | _ -> 2 (* warn *)
end;;
[%%expect{|
Line 4, characters 43-44:
4 | let g : int t -> int = function I -> 1 | _ -> 2 (* warn *)
^
Warning 56 [unreachable-case]: this match case is unreachable.
Consider replacing it with a refutation case '<pat> -> .'
module PR6220 :
sig
type 'a t = I : int t | F : float t
val f : int t -> int
val g : int t -> int
end
|}];;
module PR6403 = struct
type (_, _) eq = Refl : ('a, 'a) eq
type empty = { bottom : 'a . 'a }
type ('a, 'b) sum = Left of 'a | Right of 'b
let notequal : ((int, bool) eq, empty) sum -> empty = function
| Right empty -> empty
end;;
[%%expect{|
module PR6403 :
sig
type (_, _) eq = Refl : ('a, 'a) eq
type empty = { bottom : 'a. 'a; }
type ('a, 'b) sum = Left of 'a | Right of 'b
val notequal : ((int, bool) eq, empty) sum -> empty
end
|}];;
module PR6437 = struct
type ('a, 'b) ctx =
| Nil : (unit, unit) ctx
| Cons : ('a, 'b) ctx -> ('a * unit, 'b * unit) ctx
type 'a var =
| O : ('a * unit) var
| S : 'a var -> ('a * unit) var
let rec f : type g1 g2. (g1, g2) ctx * g1 var -> g2 var = function
| Cons g, O -> O
| Cons g, S n -> S (f (g, n))
| _ -> .
, _ - > ( assert false )
end;;
[%%expect{|
module PR6437 :
sig
type ('a, 'b) ctx =
Nil : (unit, unit) ctx
| Cons : ('a, 'b) ctx -> ('a * unit, 'b * unit) ctx
type 'a var = O : ('a * unit) var | S : 'a var -> ('a * unit) var
val f : ('g1, 'g2) ctx * 'g1 var -> 'g2 var
end
|}];;
module PR6801 = struct
type _ value =
| String : string -> string value
| Float : float -> float value
| Any
let print_string_value (x : string value) =
match x with
| String s -> print_endline s (* warn : Any *)
end;;
[%%expect{|
Lines 8-9, characters 4-33:
8 | ....match x with
9 | | String s -> print_endline s.................
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
Any
module PR6801 :
sig
type _ value =
String : string -> string value
| Float : float -> float value
| Any
val print_string_value : string value -> unit
end
|}];;
module Existential_escape =
struct
type _ t = C : int -> int t
type u = D : 'a t -> u
let eval (D x) = x
end
;;
[%%expect{|
Line 5, characters 21-22:
5 | let eval (D x) = x
^
Error: This expression has type $D_'a t
but an expression was expected of type 'a
The type constructor $D_'a would escape its scope
|}];;
module Rectype =
struct
type (_,_) t = C : ('a,'a) t
let f : type s. (s, s*s) t -> unit =
fun C -> () (* here s = s*s! *)
end
;;
[%%expect{|
module Rectype :
sig type (_, _) t = C : ('a, 'a) t val f : ('s, 's * 's) t -> unit end
|}];;
module Or_patterns =
struct
type _ t =
| IntLit : int -> int t
| BoolLit : bool -> bool t
let rec eval : type s . s t -> unit =
function
| (IntLit _ | BoolLit _) -> ()
end
;;
[%%expect{|
module Or_patterns :
sig
type _ t = IntLit : int -> int t | BoolLit : bool -> bool t
val eval : 's t -> unit
end
|}];;
module Polymorphic_variants =
struct
type _ t =
| IntLit : int -> int t
| BoolLit : bool -> bool t
let rec eval : type s . [`A] * s t -> unit =
function
| `A, IntLit _ -> ()
| `A, BoolLit _ -> ()
end
;;
[%%expect{|
module Polymorphic_variants :
sig
type _ t = IntLit : int -> int t | BoolLit : bool -> bool t
val eval : [ `A ] * 's t -> unit
end
|}];;
module Propagation = struct
type _ t =
IntLit : int -> int t
| BoolLit : bool -> bool t
let check : type s. s t -> s = function
| IntLit n -> n
| BoolLit b -> b
let check : type s. s t -> s = fun x ->
let r = match x with
| IntLit n -> (n : s )
| BoolLit b -> b
in r
end
;;
[%%expect{|
module Propagation :
sig
type _ t = IntLit : int -> int t | BoolLit : bool -> bool t
val check : 's t -> 's
end
|}, Principal{|
Line 13, characters 19-20:
13 | | BoolLit b -> b
^
Error: This expression has type bool but an expression was expected of type s
|}];;
module Normal_constrs = struct
type a = A
type b = B
let f = function A -> 1 | B -> 2
end;;
[%%expect{|
Line 5, characters 28-29:
5 | let f = function A -> 1 | B -> 2
^
Error: This variant pattern is expected to have type a
There is no constructor B within type a
|}];;
module PR6849 = struct
type 'a t = Foo : int t
let f : int -> int = function
Foo -> 5
end;;
[%%expect{|
Line 5, characters 6-9:
5 | Foo -> 5
^^^
Error: This pattern matches values of type 'a t
but a pattern was expected which matches values of type int
|}];;
type _ t = Int : int t ;;
let ky x y = ignore (x = y); x ;;
let test : type a. a t -> a =
function Int -> ky (1 : a) 1
;;
[%%expect{|
type _ t = Int : int t
val ky : 'a -> 'a -> 'a = <fun>
val test : 'a t -> 'a = <fun>
|}];;
let test : type a. a t -> _ =
function Int -> 1 (* ok *)
;;
[%%expect{|
val test : 'a t -> int = <fun>
|}];;
let test : type a. a t -> _ =
function Int -> ky (1 : a) 1 (* fails *)
;;
[%%expect{|
Line 2, characters 18-30:
2 | function Int -> ky (1 : a) 1 (* fails *)
^^^^^^^^^^^^
Error: This expression has type a = int
but an expression was expected of type 'a
This instance of int is ambiguous:
it would escape the scope of its equation
|}];;
let test : type a. a t -> a = fun x ->
let r = match x with Int -> ky (1 : a) 1 (* fails *)
in r
;;
[%%expect{|
Line 2, characters 30-42:
2 | let r = match x with Int -> ky (1 : a) 1 (* fails *)
^^^^^^^^^^^^
Error: This expression has type a = int
but an expression was expected of type 'a
This instance of int is ambiguous:
it would escape the scope of its equation
|}];;
let test : type a. a t -> a = fun x ->
let r = match x with Int -> ky 1 (1 : a) (* fails *)
in r
;;
[%%expect{|
Line 2, characters 30-42:
2 | let r = match x with Int -> ky 1 (1 : a) (* fails *)
^^^^^^^^^^^^
Error: This expression has type a = int
but an expression was expected of type 'a
This instance of int is ambiguous:
it would escape the scope of its equation
|}];;
let test (type a) x =
let r = match (x : a t) with Int -> ky 1 1
in r
;;
[%%expect{|
val test : 'a t -> int = <fun>
|}];;
let test : type a. a t -> a = fun x ->
let r = match x with Int -> (1 : a) (* ok! *)
in r
;;
[%%expect{|
val test : 'a t -> 'a = <fun>
|}];;
let test : type a. a t -> _ = fun x ->
let r = match x with Int -> 1 (* ok! *)
in r
;;
[%%expect{|
val test : 'a t -> int = <fun>
|}];;
let test : type a. a t -> a = fun x ->
let r : a = match x with Int -> 1
in r (* ok *)
;;
[%%expect{|
val test : 'a t -> 'a = <fun>
|}];;
let test2 : type a. a t -> a option = fun x ->
let r = ref None in
begin match x with Int -> r := Some (1 : a) end;
!r (* ok *)
;;
[%%expect{|
val test2 : 'a t -> 'a option = <fun>
|}];;
let test2 : type a. a t -> a option = fun x ->
let r : a option ref = ref None in
begin match x with Int -> r := Some 1 end;
!r (* ok *)
;;
[%%expect{|
val test2 : 'a t -> 'a option = <fun>
|}];;
let test2 : type a. a t -> a option = fun x ->
let r : a option ref = ref None in
let u = ref None in
begin match x with Int -> r := Some 1; u := !r end;
!u
;; (* ok (u non-ambiguous) *)
[%%expect{|
val test2 : 'a t -> 'a option = <fun>
|}];;
let test2 : type a. a t -> a option = fun x ->
let r : a option ref = ref None in
let u = ref None in
begin match x with Int -> u := Some 1; r := !u end;
!u
;; (* fails because u : (int | a) option ref *)
[%%expect{|
Line 4, characters 46-48:
4 | begin match x with Int -> u := Some 1; r := !u end;
^^
Error: This expression has type int option
but an expression was expected of type a option
Type int is not compatible with type a = int
This instance of int is ambiguous:
it would escape the scope of its equation
|}];;
let test2 : type a. a t -> a option = fun x ->
let u = ref None in
let r : a option ref = ref None in
begin match x with Int -> r := Some 1; u := !r end;
!u
;; (* ok *)
[%%expect{|
val test2 : 'a t -> 'a option = <fun>
|}];;
let test2 : type a. a t -> a option = fun x ->
let u = ref None in
let a =
let r : a option ref = ref None in
begin match x with Int -> r := Some 1; u := !r end;
!u
in a
;; (* ok *)
[%%expect{|
val test2 : 'a t -> 'a option = <fun>
|}];;
let either = ky
let we_y1x (type a) (x : a) (v : a t) =
match v with Int -> let y = either 1 x in y
;; (* fail *)
[%%expect{|
val either : 'a -> 'a -> 'a = <fun>
Line 3, characters 44-45:
3 | match v with Int -> let y = either 1 x in y
^
Error: This expression has type a = int
but an expression was expected of type 'a
This instance of int is ambiguous:
it would escape the scope of its equation
|}];;
(* Effect of external consraints *)
let f (type a) (x : a t) y =
ignore (y : a);
let r = match x with Int -> (y : a) in (* ok *)
r
;;
[%%expect{|
val f : 'a t -> 'a -> 'a = <fun>
|}];;
let f (type a) (x : a t) y =
let r = match x with Int -> (y : a) in
ignore (y : a); (* ok *)
r
;;
[%%expect{|
val f : 'a t -> 'a -> 'a = <fun>
|}];;
let f (type a) (x : a t) y =
ignore (y : a);
let r = match x with Int -> y in (* ok *)
r
;;
[%%expect{|
val f : 'a t -> 'a -> 'a = <fun>
|}];;
let f (type a) (x : a t) y =
let r = match x with Int -> y in
ignore (y : a); (* ok *)
r
;;
[%%expect{|
val f : 'a t -> 'a -> 'a = <fun>
|}];;
let f (type a) (x : a t) (y : a) =
match x with Int -> y (* returns 'a *)
;;
[%%expect{|
val f : 'a t -> 'a -> 'a = <fun>
|}];;
(* Combination with local modules *)
let f (type a) (x : a t) y =
match x with Int ->
let module M = struct type b = a let z = (y : b) end
in M.z
;; (* fails because of aliasing... *)
[%%expect{|
Line 3, characters 46-47:
3 | let module M = struct type b = a let z = (y : b) end
^
Error: This expression has type a = int
but an expression was expected of type b = int
This instance of int is ambiguous:
it would escape the scope of its equation
|}];;
let f (type a) (x : a t) y =
match x with Int ->
let module M = struct type b = int let z = (y : b) end
in M.z
;; (* ok *)
[%%expect{|
val f : 'a t -> int -> int = <fun>
|}];;
(* Objects and variants *)
type _ h =
| Has_m : <m : int> h
| Has_b : <b : bool> h
let f : type a. a h -> a = function
| Has_m -> object method m = 1 end
| Has_b -> object method b = true end
;;
[%%expect{|
type _ h = Has_m : < m : int > h | Has_b : < b : bool > h
val f : 'a h -> 'a = <fun>
|}];;
type _ j =
| Has_A : [`A of int] j
| Has_B : [`B of bool] j
let f : type a. a j -> a = function
| Has_A -> `A 1
| Has_B -> `B true
;;
[%%expect{|
type _ j = Has_A : [ `A of int ] j | Has_B : [ `B of bool ] j
val f : 'a j -> 'a = <fun>
|}];;
type (_,_) eq = Eq : ('a,'a) eq ;;
let f : type a b. (a,b) eq -> (<m : a; ..> as 'c) -> (<m : b; ..> as 'c) =
fun Eq o -> o
;; (* fail *)
[%%expect{|
type (_, _) eq = Eq : ('a, 'a) eq
Lines 3-4, characters 4-15:
3 | ....f : type a b. (a,b) eq -> (<m : a; ..> as 'c) -> (<m : b; ..> as 'c) =
4 | fun Eq o -> o
Error: The universal type variable 'b cannot be generalized:
it is already bound to another variable.
|}];;
let f : type a b. (a,b) eq -> <m : a; ..> -> <m : b; ..> =
fun Eq o -> o
;; (* fail *)
[%%expect{|
Line 2, characters 14-15:
2 | fun Eq o -> o
^
Error: This expression has type < m : a; .. >
but an expression was expected of type < m : b; .. >
Type a is not compatible with type b = a
This instance of a is ambiguous:
it would escape the scope of its equation
|}];;
let f (type a) (type b) (eq : (a,b) eq) (o : <m : a; ..>) : <m : b; ..> =
match eq with Eq -> o ;; (* should fail *)
[%%expect{|
Line 2, characters 22-23:
2 | match eq with Eq -> o ;; (* should fail *)
^
Error: This expression has type < m : a; .. >
but an expression was expected of type < m : b; .. >
Type a is not compatible with type b = a
This instance of a is ambiguous:
it would escape the scope of its equation
|}];;
let f : type a b. (a,b) eq -> <m : a> -> <m : b> =
fun Eq o -> o
;; (* ok *)
[%%expect{|
val f : ('a, 'b) eq -> < m : 'a > -> < m : 'b > = <fun>
|}];;
let int_of_bool : (bool,int) eq = Obj.magic Eq;;
let x = object method m = true end;;
let y = (x, f int_of_bool x);;
let f : type a. (a, int) eq -> <m : a> -> bool =
fun Eq o -> ignore (o : <m : int; ..>); o#m = 3
;; (* should be ok *)
[%%expect{|
val int_of_bool : (bool, int) eq = Eq
val x : < m : bool > = <obj>
val y : < m : bool > * < m : int > = (<obj>, <obj>)
val f : ('a, int) eq -> < m : 'a > -> bool = <fun>
|}];;
let f : type a b. (a,b) eq -> < m : a; .. > -> < m : b > =
fun eq o ->
ignore (o : < m : a >);
let r : < m : b > = match eq with Eq -> o in (* fail with principal *)
r;;
[%%expect{|
val f : ('a, 'b) eq -> < m : 'a > -> < m : 'b > = <fun>
|}, Principal{|
Line 4, characters 44-45:
4 | let r : < m : b > = match eq with Eq -> o in (* fail with principal *)
^
Error: This expression has type < m : a >
but an expression was expected of type < m : b >
Type a is not compatible with type b = a
This instance of a is ambiguous:
it would escape the scope of its equation
|}];;
let f : type a b. (a,b) eq -> < m : a; .. > -> < m : b > =
fun eq o ->
let r : < m : b > = match eq with Eq -> o in (* fail *)
ignore (o : < m : a >);
r;;
[%%expect{|
Line 3, characters 44-45:
3 | let r : < m : b > = match eq with Eq -> o in (* fail *)
^
Error: This expression has type < m : a; .. >
but an expression was expected of type < m : b >
Type a is not compatible with type b = a
This instance of a is ambiguous:
it would escape the scope of its equation
|}];;
let f : type a b. (a,b) eq -> [> `A of a] -> [> `A of b] =
fun Eq o -> o ;; (* fail *)
[%%expect{|
Line 2, characters 14-15:
2 | fun Eq o -> o ;; (* fail *)
^
Error: This expression has type [> `A of a ]
but an expression was expected of type [> `A of b ]
Type a is not compatible with type b = a
This instance of a is ambiguous:
it would escape the scope of its equation
|}, Principal{|
Line 2, characters 9-15:
2 | fun Eq o -> o ;; (* fail *)
^^^^^^
Error: This expression has type ([> `A of b ] as 'a) -> 'a
but an expression was expected of type [> `A of a ] -> [> `A of b ]
Types for tag `A are incompatible
|}];;
let f (type a b) (eq : (a,b) eq) (v : [> `A of a]) : [> `A of b] =
match eq with Eq -> v ;; (* should fail *)
[%%expect{|
Line 2, characters 22-23:
2 | match eq with Eq -> v ;; (* should fail *)
^
Error: This expression has type [> `A of a ]
but an expression was expected of type [> `A of b ]
Type a is not compatible with type b = a
This instance of a is ambiguous:
it would escape the scope of its equation
|}];;
let f : type a b. (a,b) eq -> [< `A of a | `B] -> [< `A of b | `B] =
fun Eq o -> o ;; (* fail *)
[%%expect{|
Lines 1-2, characters 4-15:
1 | ....f : type a b. (a,b) eq -> [< `A of a | `B] -> [< `A of b | `B] =
2 | fun Eq o -> o..............
Error: This definition has type
'c. ('d, 'c) eq -> ([< `A of 'c & 'f & 'd | `B ] as 'e) -> 'e
which is less general than
'a 'b. ('a, 'b) eq -> ([< `A of 'b & 'h | `B ] as 'g) -> 'g
|}];;
let f : type a b. (a,b) eq -> [`A of a | `B] -> [`A of b | `B] =
fun Eq o -> o ;; (* ok *)
[%%expect{|
val f : ('a, 'b) eq -> [ `A of 'a | `B ] -> [ `A of 'b | `B ] = <fun>
|}];;
let f : type a. (a, int) eq -> [`A of a] -> bool =
fun Eq v -> match v with `A 1 -> true | _ -> false
;; (* ok *)
[%%expect{|
val f : ('a, int) eq -> [ `A of 'a ] -> bool = <fun>
|}];;
let f : type a b. (a,b) eq -> [> `A of a | `B] -> [`A of b | `B] =
fun eq o ->
ignore (o : [< `A of a | `B]);
let r : [`A of b | `B] = match eq with Eq -> o in (* fail with principal *)
r;;
[%%expect{|
val f : ('a, 'b) eq -> [ `A of 'a | `B ] -> [ `A of 'b | `B ] = <fun>
|}, Principal{|
Line 4, characters 49-50:
4 | let r : [`A of b | `B] = match eq with Eq -> o in (* fail with principal *)
^
Error: This expression has type [ `A of a | `B ]
but an expression was expected of type [ `A of b | `B ]
Type a is not compatible with type b = a
This instance of a is ambiguous:
it would escape the scope of its equation
|}];;
let f : type a b. (a,b) eq -> [> `A of a | `B] -> [`A of b | `B] =
fun eq o ->
let r : [`A of b | `B] = match eq with Eq -> o in (* fail *)
ignore (o : [< `A of a | `B]);
r;;
[%%expect{|
Line 3, characters 49-50:
3 | let r : [`A of b | `B] = match eq with Eq -> o in (* fail *)
^
Error: This expression has type [> `A of a | `B ]
but an expression was expected of type [ `A of b | `B ]
Type a is not compatible with type b = a
This instance of a is ambiguous:
it would escape the scope of its equation
|}];;
(* Pattern matching *)
type 'a t =
A of int | B of bool | C of float | D of 'a
type _ ty =
| TE : 'a ty -> 'a array ty
| TA : int ty
| TB : bool ty
| TC : float ty
| TD : string -> bool ty
let f : type a. a ty -> a t -> int = fun x y ->
match x, y with
| _, A z -> z
| _, B z -> if z then 1 else 2
| _, C z -> truncate z
| TE TC, D [|1.0|] -> 14
| TA, D 0 -> -1
| TA, D z -> z
| TD "bye", D false -> 13
| TD "hello", D true -> 12
| TB , D z - > if z then 1 else 2
| TC, D z -> truncate z
| _, D _ -> 0
;;
[%%expect{|
type 'a t = A of int | B of bool | C of float | D of 'a
type _ ty =
TE : 'a ty -> 'a array ty
| TA : int ty
| TB : bool ty
| TC : float ty
| TD : string -> bool ty
val f : 'a ty -> 'a t -> int = <fun>
|}];;
let f : type a. a ty -> a t -> int = fun x y ->
match x, y with
| _, A z -> z
| _, B z -> if z then 1 else 2
| _, C z -> truncate z
| TE TC, D [|1.0|] -> 14
| TA, D 0 -> -1
| TA, D z -> z
;; (* warn *)
[%%expect{|
Lines 2-8, characters 2-16:
2 | ..match x, y with
3 | | _, A z -> z
4 | | _, B z -> if z then 1 else 2
5 | | _, C z -> truncate z
6 | | TE TC, D [|1.0|] -> 14
7 | | TA, D 0 -> -1
8 | | TA, D z -> z
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
(TE TC, D [| 0. |])
val f : 'a ty -> 'a t -> int = <fun>
|}];;
let f : type a. a ty -> a t -> int = fun x y ->
match y, x with
| A z, _ -> z
| B z, _ -> if z then 1 else 2
| C z, _ -> truncate z
| D [|1.0|], TE TC -> 14
| D 0, TA -> -1
| D z, TA -> z
;; (* fail *)
[%%expect{|
Line 6, characters 6-13:
6 | | D [|1.0|], TE TC -> 14
^^^^^^^
Error: This pattern matches values of type 'a array
but a pattern was expected which matches values of type a
|}];;
type ('a,'b) pair = {right:'a; left:'b}
let f : type a. a ty -> a t -> int = fun x y ->
match {left=x; right=y} with
| {left=_; right=A z} -> z
| {left=_; right=B z} -> if z then 1 else 2
| {left=_; right=C z} -> truncate z
| {left=TE TC; right=D [|1.0|]} -> 14
| {left=TA; right=D 0} -> -1
| {left=TA; right=D z} -> z
;; (* fail *)
[%%expect{|
type ('a, 'b) pair = { right : 'a; left : 'b; }
Line 8, characters 25-32:
8 | | {left=TE TC; right=D [|1.0|]} -> 14
^^^^^^^
Error: This pattern matches values of type 'a array
but a pattern was expected which matches values of type a
|}];;
type ('a,'b) pair = {left:'a; right:'b}
let f : type a. a ty -> a t -> int = fun x y ->
match {left=x; right=y} with
| {left=_; right=A z} -> z
| {left=_; right=B z} -> if z then 1 else 2
| {left=_; right=C z} -> truncate z
| {left=TE TC; right=D [|1.0|]} -> 14
| {left=TA; right=D 0} -> -1
| {left=TA; right=D z} -> z
;; (* ok *)
[%%expect{|
type ('a, 'b) pair = { left : 'a; right : 'b; }
Lines 4-10, characters 2-29:
4 | ..match {left=x; right=y} with
5 | | {left=_; right=A z} -> z
6 | | {left=_; right=B z} -> if z then 1 else 2
7 | | {left=_; right=C z} -> truncate z
8 | | {left=TE TC; right=D [|1.0|]} -> 14
9 | | {left=TA; right=D 0} -> -1
10 | | {left=TA; right=D z} -> z
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
{left=TE TC; right=D [| 0. |]}
val f : 'a ty -> 'a t -> int = <fun>
|}];;
Injectivity
module M : sig type 'a t val eq : ('a t, 'b t) eq end =
struct type 'a t = int let eq = Eq end
;;
let f : type a b. (a M.t, b M.t) eq -> (a, b) eq =
function Eq -> Eq (* fail *)
;;
[%%expect{|
module M : sig type 'a t val eq : ('a t, 'b t) eq end
Line 6, characters 17-19:
6 | function Eq -> Eq (* fail *)
^^
Error: This expression has type (a, a) eq
but an expression was expected of type (a, b) eq
Type a is not compatible with type b
|}];;
let f : type a b. (a M.t * a, b M.t * b) eq -> (a, b) eq =
function Eq -> Eq (* ok *)
;;
[%%expect{|
val f : ('a M.t * 'a, 'b M.t * 'b) eq -> ('a, 'b) eq = <fun>
|}];;
let f : type a b. (a * a M.t, b * b M.t) eq -> (a, b) eq =
function Eq -> Eq (* ok *)
;;
[%%expect{|
val f : ('a * 'a M.t, 'b * 'b M.t) eq -> ('a, 'b) eq = <fun>
|}];;
(* Applications of polymorphic variants *)
type _ t =
| V1 : [`A | `B] t
| V2 : [`C | `D] t
let f : type a. a t -> a = function
| V1 -> `A
| V2 -> `C
;;
f V1;;
[%%expect{|
type _ t = V1 : [ `A | `B ] t | V2 : [ `C | `D ] t
val f : 'a t -> 'a = <fun>
- : [ `A | `B ] = `A
|}];;
PR#5425 and PR#5427
type _ int_foo =
| IF_constr : <foo:int; ..> int_foo
type _ int_bar =
| IB_constr : <bar:int; ..> int_bar
;;
let g (type t) (x:t) (e : t int_foo) (e' : t int_bar) =
let IF_constr, IB_constr = e, e' in
(x:<foo:int>)
;;
[%%expect{|
type _ int_foo = IF_constr : < foo : int; .. > int_foo
type _ int_bar = IB_constr : < bar : int; .. > int_bar
Line 10, characters 3-4:
10 | (x:<foo:int>)
^
Error: This expression has type t = < foo : int; .. >
but an expression was expected of type < foo : int >
Type $0 = < bar : int; .. > is not compatible with type < >
The second object type has no method bar
|}];;
let g (type t) (x:t) (e : t int_foo) (e' : t int_bar) =
let IF_constr, IB_constr = e, e' in
(x:<foo:int;bar:int>)
;;
[%%expect{|
Line 3, characters 3-4:
3 | (x:<foo:int;bar:int>)
^
Error: This expression has type t = < foo : int; .. >
but an expression was expected of type < bar : int; foo : int >
Type $0 = < bar : int; .. > is not compatible with type < bar : int >
The first object type has an abstract row, it cannot be closed
|}];;
let g (type t) (x:t) (e : t int_foo) (e' : t int_bar) =
let IF_constr, IB_constr = e, e' in
(x:<foo:int;bar:int;..>)
;;
[%%expect{|
Line 3, characters 2-26:
3 | (x:<foo:int;bar:int;..>)
^^^^^^^^^^^^^^^^^^^^^^^^
Error: This expression has type < bar : int; foo : int; .. >
but an expression was expected of type 'a
The type constructor $1 would escape its scope
|}, Principal{|
Line 3, characters 2-26:
3 | (x:<foo:int;bar:int;..>)
^^^^^^^^^^^^^^^^^^^^^^^^
Error: This expression has type < bar : int; foo : int; .. >
but an expression was expected of type 'a
This instance of $1 is ambiguous:
it would escape the scope of its equation
|}];;
let g (type t) (x:t) (e : t int_foo) (e' : t int_bar) : t =
let IF_constr, IB_constr = e, e' in
(x:<foo:int;bar:int;..>)
;;
[%%expect{|
val g : 't -> 't int_foo -> 't int_bar -> 't = <fun>
|}];;
let g (type t) (x:t) (e : t int_foo) (e' : t int_bar) =
let IF_constr, IB_constr = e, e' in
x, x#foo, x#bar
;;
[%%expect{|
val g : 't -> 't int_foo -> 't int_bar -> 't * int * int = <fun>
|}, Principal{|
Line 3, characters 5-10:
3 | x, x#foo, x#bar
^^^^^
Error: This expression has type int but an expression was expected of type 'a
This instance of int is ambiguous:
it would escape the scope of its equation
|}];;
(* PR#5554 *)
type 'a ty = Int : int -> int ty;;
let f : type a. a ty -> a =
fun x -> match x with Int y -> y;;
let g : type a. a ty -> a =
let () = () in
fun x -> match x with Int y -> y;;
[%%expect{|
type 'a ty = Int : int -> int ty
val f : 'a ty -> 'a = <fun>
val g : 'a ty -> 'a = <fun>
|}];;
(* Printing of anonymous variables *)
module M = struct type _ t = int end;;
module M = struct type _ t = T : int t end;;
module N = M;;
[%%expect{|
module M : sig type _ t = int end
module M : sig type _ t = T : int t end
module N = M
|}];;
(* Principality *)
(* adding a useless equation should not break inference *)
let f : type a b. (a,b) eq -> (a,int) eq -> a -> b -> _ = fun ab aint a b ->
let Eq = ab in
let x =
let Eq = aint in
if true then a else b
in ignore x
;; (* ok *)
[%%expect{|
val f : ('a, 'b) eq -> ('a, int) eq -> 'a -> 'b -> unit = <fun>
|}];;
let f : type a b. (a,b) eq -> (b,int) eq -> a -> b -> _ = fun ab bint a b ->
let Eq = ab in
let x =
let Eq = bint in
if true then a else b
in ignore x
;; (* ok *)
[%%expect{|
val f : ('a, 'b) eq -> ('b, int) eq -> 'a -> 'b -> unit = <fun>
|}];;
let f : type a b. (a,b) eq -> (a,int) eq -> a -> b -> _ = fun ab aint a b ->
let Eq = aint in
let x =
let Eq = ab in
if true then a else b
in ignore x
;; (* ok *)
[%%expect{|
Line 5, characters 24-25:
5 | if true then a else b
^
Error: This expression has type b = int
but an expression was expected of type a = int
Type b = int is not compatible with type int
This instance of int is ambiguous:
it would escape the scope of its equation
|}];;
let f : type a b. (a,b) eq -> (b,int) eq -> a -> b -> _ = fun ab bint a b ->
let Eq = bint in
let x =
let Eq = ab in
if true then a else b
in ignore x
;; (* ok *)
[%%expect{|
Line 5, characters 24-25:
5 | if true then a else b
^
Error: This expression has type b = int
but an expression was expected of type a = int
Type int is not compatible with type a = int
This instance of int is ambiguous:
it would escape the scope of its equation
|}];;
let f (type a b c) (b : bool) (w1 : (a,b) eq) (w2 : (a,int) eq) (x : a) (y : b) =
let Eq = w1 in
let Eq = w2 in
if b then x else y
;;
[%%expect{|
Line 4, characters 19-20:
4 | if b then x else y
^
Error: This expression has type b = int
but an expression was expected of type a = int
Type a = int is not compatible with type a = int
This instance of int is ambiguous:
it would escape the scope of its equation
|}];;
let f (type a b c) (b : bool) (w1 : (a,b) eq) (w2 : (a,int) eq) (x : a) (y : b) =
let Eq = w1 in
let Eq = w2 in
if b then y else x
[%%expect{|
Line 4, characters 19-20:
4 | if b then y else x
^
Error: This expression has type a = int
but an expression was expected of type b = int
This instance of int is ambiguous:
it would escape the scope of its equation
|}];;
module M = struct
type t
end
type (_,_) eq = Refl: ('a,'a) eq
let f (x:M.t) (y: (M.t, int -> int) eq) =
let Refl = y in
if true then x else fun x -> x + 1
[%%expect{|
module M : sig type t end
type (_, _) eq = Refl : ('a, 'a) eq
Line 7, characters 22-36:
7 | if true then x else fun x -> x + 1
^^^^^^^^^^^^^^
Error: This expression has type 'a -> 'b
but an expression was expected of type M.t = int -> int
This instance of int -> int is ambiguous:
it would escape the scope of its equation
|}]
(* Check got/expected when the order changes *)
module M = struct
type t
end
type (_,_) eq = Refl: ('a,'a) eq
let f (x:M.t) (y: (M.t, int -> int) eq) =
let Refl = y in
if true then fun x -> x + 1 else x
[%%expect{|
module M : sig type t end
type (_, _) eq = Refl : ('a, 'a) eq
Line 7, characters 35-36:
7 | if true then fun x -> x + 1 else x
^
Error: This expression has type M.t = int -> int
but an expression was expected of type int -> int
This instance of int -> int is ambiguous:
it would escape the scope of its equation
|}]
module M = struct
type t
end
type (_,_) eq = Refl: ('a,'a) eq
let f w (x:M.t) (y: (M.t, <m:int>) eq) =
let Refl = y in
let z = if true then x else w in
z#m
[%%expect{|
module M : sig type t end
type (_, _) eq = Refl : ('a, 'a) eq
Line 8, characters 2-3:
8 | z#m
^
Error: This expression has type M.t but an expression was expected of type
< m : 'a; .. >
This instance of < m : int > is ambiguous:
it would escape the scope of its equation
|}]
(* Check got/expected when the order changes *)
module M = struct
type t
end
type (_,_) eq = Refl: ('a,'a) eq
let f w (x:M.t) (y: (M.t, <m:int>) eq) =
let Refl = y in
let z = if true then w else x in
z#m
[%%expect{|
module M : sig type t end
type (_, _) eq = Refl : ('a, 'a) eq
Line 8, characters 2-3:
8 | z#m
^
Error: This expression has type M.t but an expression was expected of type
< m : 'a; .. >
This instance of < m : int > is ambiguous:
it would escape the scope of its equation
|}]
type (_,_) eq = Refl: ('a,'a) eq
module M = struct
type t = C : (<m:int; ..> as 'a) * ('a, <m:int; b:bool>) eq -> t
end
let f (C (x,y) : M.t) =
let g w =
let Refl = y in
let z = if true then w else x in
z#b
in ()
[%%expect{|
type (_, _) eq = Refl : ('a, 'a) eq
module M :
sig
type t =
C : (< m : int; .. > as 'a) * ('a, < b : bool; m : int >) eq -> t
end
Line 9, characters 4-5:
9 | z#b
^
Error: This expression has type $C_'a = < b : bool >
but an expression was expected of type < b : 'a; .. >
This instance of < b : bool > is ambiguous:
it would escape the scope of its equation
|}]
(* Check got/expected when the order changes *)
type (_,_) eq = Refl: ('a,'a) eq
module M = struct
type t = C : (<m:int; ..> as 'a) * ('a, <m:int; b:bool>) eq -> t
end
let f (C (x,y) : M.t) =
let g w =
let Refl = y in
let z = if true then x else w in
z#b
in ()
[%%expect{|
type (_, _) eq = Refl : ('a, 'a) eq
module M :
sig
type t =
C : (< m : int; .. > as 'a) * ('a, < b : bool; m : int >) eq -> t
end
Line 9, characters 4-5:
9 | z#b
^
Error: This expression has type $C_'a = < b : bool >
but an expression was expected of type < b : 'a; .. >
This instance of < b : bool > is ambiguous:
it would escape the scope of its equation
|}]
| null | https://raw.githubusercontent.com/dyzsr/ocaml-selectml/875544110abb3350e9fb5ec9bbadffa332c270d2/testsuite/tests/typing-gadts/test.ml | ocaml | TEST
* expect
warn
warn
warn : Any
here s = s*s!
ok
fails
fails
fails
fails
fails
fails
ok!
ok!
ok
ok
ok
ok (u non-ambiguous)
fails because u : (int | a) option ref
ok
ok
fail
Effect of external consraints
ok
ok
ok
ok
returns 'a
Combination with local modules
fails because of aliasing...
ok
Objects and variants
fail
fail
should fail
should fail
ok
should be ok
fail with principal
fail with principal
fail
fail
fail
fail
fail
should fail
should fail
fail
ok
ok
fail with principal
fail with principal
fail
fail
Pattern matching
warn
fail
fail
ok
fail
fail
ok
ok
Applications of polymorphic variants
PR#5554
Printing of anonymous variables
Principality
adding a useless equation should not break inference
ok
ok
ok
ok
Check got/expected when the order changes
Check got/expected when the order changes
Check got/expected when the order changes |
module Exp =
struct
type _ t =
| IntLit : int -> int t
| BoolLit : bool -> bool t
| Pair : 'a t * 'b t -> ('a * 'b) t
| App : ('a -> 'b) t * 'a t -> 'b t
| Abs : ('a -> 'b) -> ('a -> 'b) t
let rec eval : type s . s t -> s =
function
| IntLit x -> x
| BoolLit y -> y
| Pair (x,y) ->
(eval x,eval y)
| App (f,a) ->
(eval f) (eval a)
| Abs f -> f
let discern : type a. a t -> _ = function
IntLit _ -> 1
| BoolLit _ -> 2
| Pair _ -> 3
| App _ -> 4
| Abs _ -> 5
end
;;
[%%expect{|
module Exp :
sig
type _ t =
IntLit : int -> int t
| BoolLit : bool -> bool t
| Pair : 'a t * 'b t -> ('a * 'b) t
| App : ('a -> 'b) t * 'a t -> 'b t
| Abs : ('a -> 'b) -> ('a -> 'b) t
val eval : 's t -> 's
val discern : 'a t -> int
end
|}];;
module List =
struct
type zero
type _ t =
| Nil : zero t
| Cons : 'a * 'b t -> ('a * 'b) t
let head =
function
| Cons (a,b) -> a
let tail =
function
| Cons (a,b) -> b
let rec length : type a . a t -> int =
function
| Nil -> 0
| Cons (a,b) -> length b
end
;;
[%%expect{|
module List :
sig
type zero
type _ t = Nil : zero t | Cons : 'a * 'b t -> ('a * 'b) t
val head : ('a * 'b) t -> 'a
val tail : ('a * 'b) t -> 'b t
val length : 'a t -> int
end
|}];;
module Nonexhaustive =
struct
type 'a u =
| C1 : int -> int u
| C2 : bool -> bool u
type 'a v =
| C1 : int -> int v
let unexhaustive : type s . s u -> s =
function
| C2 x -> x
module M : sig type t type u end =
struct
type t = int
type u = bool
end
type 'a t =
| Foo : M.t -> M.t t
| Bar : M.u -> M.u t
let same_type : type s . s t * s t -> bool =
function
| Foo _ , Foo _ -> true
| Bar _, Bar _ -> true
end
;;
[%%expect{|
Lines 11-12, characters 6-19:
11 | ......function
12 | | C2 x -> x
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
C1 _
Lines 24-26, characters 6-30:
24 | ......function
25 | | Foo _ , Foo _ -> true
26 | | Bar _, Bar _ -> true
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
(Foo _, Bar _)
module Nonexhaustive :
sig
type 'a u = C1 : int -> int u | C2 : bool -> bool u
type 'a v = C1 : int -> int v
val unexhaustive : 's u -> 's
module M : sig type t type u end
type 'a t = Foo : M.t -> M.t t | Bar : M.u -> M.u t
val same_type : 's t * 's t -> bool
end
|}];;
module Exhaustive =
struct
type t = int
type u = bool
type 'a v =
| Foo : t -> t v
| Bar : u -> u v
let same_type : type s . s v * s v -> bool =
function
| Foo _ , Foo _ -> true
| Bar _, Bar _ -> true
end
;;
[%%expect{|
module Exhaustive :
sig
type t = int
type u = bool
type 'a v = Foo : t -> t v | Bar : u -> u v
val same_type : 's v * 's v -> bool
end
|}];;
module PR6862 = struct
class c (Some x) = object method x : int = x end
type _ opt = Just : 'a -> 'a opt | Nothing : 'a opt
class d (Just x) = object method x : int = x end
end;;
[%%expect{|
Line 2, characters 10-18:
2 | class c (Some x) = object method x : int = x end
^^^^^^^^
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
None
Line 4, characters 10-18:
4 | class d (Just x) = object method x : int = x end
^^^^^^^^
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
Nothing
module PR6862 :
sig
class c : int option -> object method x : int end
type _ opt = Just : 'a -> 'a opt | Nothing : 'a opt
class d : int opt -> object method x : int end
end
|}];;
module Exhaustive2 = struct
type _ t = Int : int t
let f (x : bool t option) = match x with None -> ()
end;;
[%%expect{|
module Exhaustive2 :
sig type _ t = Int : int t val f : bool t option -> unit end
|}];;
module PR6220 = struct
type 'a t = I : int t | F : float t
let f : int t -> int = function I -> 1
end;;
[%%expect{|
Line 4, characters 43-44:
^
Warning 56 [unreachable-case]: this match case is unreachable.
Consider replacing it with a refutation case '<pat> -> .'
module PR6220 :
sig
type 'a t = I : int t | F : float t
val f : int t -> int
val g : int t -> int
end
|}];;
module PR6403 = struct
type (_, _) eq = Refl : ('a, 'a) eq
type empty = { bottom : 'a . 'a }
type ('a, 'b) sum = Left of 'a | Right of 'b
let notequal : ((int, bool) eq, empty) sum -> empty = function
| Right empty -> empty
end;;
[%%expect{|
module PR6403 :
sig
type (_, _) eq = Refl : ('a, 'a) eq
type empty = { bottom : 'a. 'a; }
type ('a, 'b) sum = Left of 'a | Right of 'b
val notequal : ((int, bool) eq, empty) sum -> empty
end
|}];;
module PR6437 = struct
type ('a, 'b) ctx =
| Nil : (unit, unit) ctx
| Cons : ('a, 'b) ctx -> ('a * unit, 'b * unit) ctx
type 'a var =
| O : ('a * unit) var
| S : 'a var -> ('a * unit) var
let rec f : type g1 g2. (g1, g2) ctx * g1 var -> g2 var = function
| Cons g, O -> O
| Cons g, S n -> S (f (g, n))
| _ -> .
, _ - > ( assert false )
end;;
[%%expect{|
module PR6437 :
sig
type ('a, 'b) ctx =
Nil : (unit, unit) ctx
| Cons : ('a, 'b) ctx -> ('a * unit, 'b * unit) ctx
type 'a var = O : ('a * unit) var | S : 'a var -> ('a * unit) var
val f : ('g1, 'g2) ctx * 'g1 var -> 'g2 var
end
|}];;
module PR6801 = struct
type _ value =
| String : string -> string value
| Float : float -> float value
| Any
let print_string_value (x : string value) =
match x with
end;;
[%%expect{|
Lines 8-9, characters 4-33:
8 | ....match x with
9 | | String s -> print_endline s.................
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
Any
module PR6801 :
sig
type _ value =
String : string -> string value
| Float : float -> float value
| Any
val print_string_value : string value -> unit
end
|}];;
module Existential_escape =
struct
type _ t = C : int -> int t
type u = D : 'a t -> u
let eval (D x) = x
end
;;
[%%expect{|
Line 5, characters 21-22:
5 | let eval (D x) = x
^
Error: This expression has type $D_'a t
but an expression was expected of type 'a
The type constructor $D_'a would escape its scope
|}];;
module Rectype =
struct
type (_,_) t = C : ('a,'a) t
let f : type s. (s, s*s) t -> unit =
end
;;
[%%expect{|
module Rectype :
sig type (_, _) t = C : ('a, 'a) t val f : ('s, 's * 's) t -> unit end
|}];;
module Or_patterns =
struct
type _ t =
| IntLit : int -> int t
| BoolLit : bool -> bool t
let rec eval : type s . s t -> unit =
function
| (IntLit _ | BoolLit _) -> ()
end
;;
[%%expect{|
module Or_patterns :
sig
type _ t = IntLit : int -> int t | BoolLit : bool -> bool t
val eval : 's t -> unit
end
|}];;
module Polymorphic_variants =
struct
type _ t =
| IntLit : int -> int t
| BoolLit : bool -> bool t
let rec eval : type s . [`A] * s t -> unit =
function
| `A, IntLit _ -> ()
| `A, BoolLit _ -> ()
end
;;
[%%expect{|
module Polymorphic_variants :
sig
type _ t = IntLit : int -> int t | BoolLit : bool -> bool t
val eval : [ `A ] * 's t -> unit
end
|}];;
module Propagation = struct
type _ t =
IntLit : int -> int t
| BoolLit : bool -> bool t
let check : type s. s t -> s = function
| IntLit n -> n
| BoolLit b -> b
let check : type s. s t -> s = fun x ->
let r = match x with
| IntLit n -> (n : s )
| BoolLit b -> b
in r
end
;;
[%%expect{|
module Propagation :
sig
type _ t = IntLit : int -> int t | BoolLit : bool -> bool t
val check : 's t -> 's
end
|}, Principal{|
Line 13, characters 19-20:
13 | | BoolLit b -> b
^
Error: This expression has type bool but an expression was expected of type s
|}];;
module Normal_constrs = struct
type a = A
type b = B
let f = function A -> 1 | B -> 2
end;;
[%%expect{|
Line 5, characters 28-29:
5 | let f = function A -> 1 | B -> 2
^
Error: This variant pattern is expected to have type a
There is no constructor B within type a
|}];;
module PR6849 = struct
type 'a t = Foo : int t
let f : int -> int = function
Foo -> 5
end;;
[%%expect{|
Line 5, characters 6-9:
5 | Foo -> 5
^^^
Error: This pattern matches values of type 'a t
but a pattern was expected which matches values of type int
|}];;
type _ t = Int : int t ;;
let ky x y = ignore (x = y); x ;;
let test : type a. a t -> a =
function Int -> ky (1 : a) 1
;;
[%%expect{|
type _ t = Int : int t
val ky : 'a -> 'a -> 'a = <fun>
val test : 'a t -> 'a = <fun>
|}];;
let test : type a. a t -> _ =
;;
[%%expect{|
val test : 'a t -> int = <fun>
|}];;
let test : type a. a t -> _ =
;;
[%%expect{|
Line 2, characters 18-30:
^^^^^^^^^^^^
Error: This expression has type a = int
but an expression was expected of type 'a
This instance of int is ambiguous:
it would escape the scope of its equation
|}];;
let test : type a. a t -> a = fun x ->
in r
;;
[%%expect{|
Line 2, characters 30-42:
^^^^^^^^^^^^
Error: This expression has type a = int
but an expression was expected of type 'a
This instance of int is ambiguous:
it would escape the scope of its equation
|}];;
let test : type a. a t -> a = fun x ->
in r
;;
[%%expect{|
Line 2, characters 30-42:
^^^^^^^^^^^^
Error: This expression has type a = int
but an expression was expected of type 'a
This instance of int is ambiguous:
it would escape the scope of its equation
|}];;
let test (type a) x =
let r = match (x : a t) with Int -> ky 1 1
in r
;;
[%%expect{|
val test : 'a t -> int = <fun>
|}];;
let test : type a. a t -> a = fun x ->
in r
;;
[%%expect{|
val test : 'a t -> 'a = <fun>
|}];;
let test : type a. a t -> _ = fun x ->
in r
;;
[%%expect{|
val test : 'a t -> int = <fun>
|}];;
let test : type a. a t -> a = fun x ->
let r : a = match x with Int -> 1
;;
[%%expect{|
val test : 'a t -> 'a = <fun>
|}];;
let test2 : type a. a t -> a option = fun x ->
let r = ref None in
begin match x with Int -> r := Some (1 : a) end;
;;
[%%expect{|
val test2 : 'a t -> 'a option = <fun>
|}];;
let test2 : type a. a t -> a option = fun x ->
let r : a option ref = ref None in
begin match x with Int -> r := Some 1 end;
;;
[%%expect{|
val test2 : 'a t -> 'a option = <fun>
|}];;
let test2 : type a. a t -> a option = fun x ->
let r : a option ref = ref None in
let u = ref None in
begin match x with Int -> r := Some 1; u := !r end;
!u
[%%expect{|
val test2 : 'a t -> 'a option = <fun>
|}];;
let test2 : type a. a t -> a option = fun x ->
let r : a option ref = ref None in
let u = ref None in
begin match x with Int -> u := Some 1; r := !u end;
!u
[%%expect{|
Line 4, characters 46-48:
4 | begin match x with Int -> u := Some 1; r := !u end;
^^
Error: This expression has type int option
but an expression was expected of type a option
Type int is not compatible with type a = int
This instance of int is ambiguous:
it would escape the scope of its equation
|}];;
let test2 : type a. a t -> a option = fun x ->
let u = ref None in
let r : a option ref = ref None in
begin match x with Int -> r := Some 1; u := !r end;
!u
[%%expect{|
val test2 : 'a t -> 'a option = <fun>
|}];;
let test2 : type a. a t -> a option = fun x ->
let u = ref None in
let a =
let r : a option ref = ref None in
begin match x with Int -> r := Some 1; u := !r end;
!u
in a
[%%expect{|
val test2 : 'a t -> 'a option = <fun>
|}];;
let either = ky
let we_y1x (type a) (x : a) (v : a t) =
match v with Int -> let y = either 1 x in y
[%%expect{|
val either : 'a -> 'a -> 'a = <fun>
Line 3, characters 44-45:
3 | match v with Int -> let y = either 1 x in y
^
Error: This expression has type a = int
but an expression was expected of type 'a
This instance of int is ambiguous:
it would escape the scope of its equation
|}];;
let f (type a) (x : a t) y =
ignore (y : a);
r
;;
[%%expect{|
val f : 'a t -> 'a -> 'a = <fun>
|}];;
let f (type a) (x : a t) y =
let r = match x with Int -> (y : a) in
r
;;
[%%expect{|
val f : 'a t -> 'a -> 'a = <fun>
|}];;
let f (type a) (x : a t) y =
ignore (y : a);
r
;;
[%%expect{|
val f : 'a t -> 'a -> 'a = <fun>
|}];;
let f (type a) (x : a t) y =
let r = match x with Int -> y in
r
;;
[%%expect{|
val f : 'a t -> 'a -> 'a = <fun>
|}];;
let f (type a) (x : a t) (y : a) =
;;
[%%expect{|
val f : 'a t -> 'a -> 'a = <fun>
|}];;
let f (type a) (x : a t) y =
match x with Int ->
let module M = struct type b = a let z = (y : b) end
in M.z
[%%expect{|
Line 3, characters 46-47:
3 | let module M = struct type b = a let z = (y : b) end
^
Error: This expression has type a = int
but an expression was expected of type b = int
This instance of int is ambiguous:
it would escape the scope of its equation
|}];;
let f (type a) (x : a t) y =
match x with Int ->
let module M = struct type b = int let z = (y : b) end
in M.z
[%%expect{|
val f : 'a t -> int -> int = <fun>
|}];;
type _ h =
| Has_m : <m : int> h
| Has_b : <b : bool> h
let f : type a. a h -> a = function
| Has_m -> object method m = 1 end
| Has_b -> object method b = true end
;;
[%%expect{|
type _ h = Has_m : < m : int > h | Has_b : < b : bool > h
val f : 'a h -> 'a = <fun>
|}];;
type _ j =
| Has_A : [`A of int] j
| Has_B : [`B of bool] j
let f : type a. a j -> a = function
| Has_A -> `A 1
| Has_B -> `B true
;;
[%%expect{|
type _ j = Has_A : [ `A of int ] j | Has_B : [ `B of bool ] j
val f : 'a j -> 'a = <fun>
|}];;
type (_,_) eq = Eq : ('a,'a) eq ;;
let f : type a b. (a,b) eq -> (<m : a; ..> as 'c) -> (<m : b; ..> as 'c) =
fun Eq o -> o
[%%expect{|
type (_, _) eq = Eq : ('a, 'a) eq
Lines 3-4, characters 4-15:
3 | ....f : type a b. (a,b) eq -> (<m : a; ..> as 'c) -> (<m : b; ..> as 'c) =
4 | fun Eq o -> o
Error: The universal type variable 'b cannot be generalized:
it is already bound to another variable.
|}];;
let f : type a b. (a,b) eq -> <m : a; ..> -> <m : b; ..> =
fun Eq o -> o
[%%expect{|
Line 2, characters 14-15:
2 | fun Eq o -> o
^
Error: This expression has type < m : a; .. >
but an expression was expected of type < m : b; .. >
Type a is not compatible with type b = a
This instance of a is ambiguous:
it would escape the scope of its equation
|}];;
let f (type a) (type b) (eq : (a,b) eq) (o : <m : a; ..>) : <m : b; ..> =
[%%expect{|
Line 2, characters 22-23:
^
Error: This expression has type < m : a; .. >
but an expression was expected of type < m : b; .. >
Type a is not compatible with type b = a
This instance of a is ambiguous:
it would escape the scope of its equation
|}];;
let f : type a b. (a,b) eq -> <m : a> -> <m : b> =
fun Eq o -> o
[%%expect{|
val f : ('a, 'b) eq -> < m : 'a > -> < m : 'b > = <fun>
|}];;
let int_of_bool : (bool,int) eq = Obj.magic Eq;;
let x = object method m = true end;;
let y = (x, f int_of_bool x);;
let f : type a. (a, int) eq -> <m : a> -> bool =
fun Eq o -> ignore (o : <m : int; ..>); o#m = 3
[%%expect{|
val int_of_bool : (bool, int) eq = Eq
val x : < m : bool > = <obj>
val y : < m : bool > * < m : int > = (<obj>, <obj>)
val f : ('a, int) eq -> < m : 'a > -> bool = <fun>
|}];;
let f : type a b. (a,b) eq -> < m : a; .. > -> < m : b > =
fun eq o ->
ignore (o : < m : a >);
r;;
[%%expect{|
val f : ('a, 'b) eq -> < m : 'a > -> < m : 'b > = <fun>
|}, Principal{|
Line 4, characters 44-45:
^
Error: This expression has type < m : a >
but an expression was expected of type < m : b >
Type a is not compatible with type b = a
This instance of a is ambiguous:
it would escape the scope of its equation
|}];;
let f : type a b. (a,b) eq -> < m : a; .. > -> < m : b > =
fun eq o ->
ignore (o : < m : a >);
r;;
[%%expect{|
Line 3, characters 44-45:
^
Error: This expression has type < m : a; .. >
but an expression was expected of type < m : b >
Type a is not compatible with type b = a
This instance of a is ambiguous:
it would escape the scope of its equation
|}];;
let f : type a b. (a,b) eq -> [> `A of a] -> [> `A of b] =
[%%expect{|
Line 2, characters 14-15:
^
Error: This expression has type [> `A of a ]
but an expression was expected of type [> `A of b ]
Type a is not compatible with type b = a
This instance of a is ambiguous:
it would escape the scope of its equation
|}, Principal{|
Line 2, characters 9-15:
^^^^^^
Error: This expression has type ([> `A of b ] as 'a) -> 'a
but an expression was expected of type [> `A of a ] -> [> `A of b ]
Types for tag `A are incompatible
|}];;
let f (type a b) (eq : (a,b) eq) (v : [> `A of a]) : [> `A of b] =
[%%expect{|
Line 2, characters 22-23:
^
Error: This expression has type [> `A of a ]
but an expression was expected of type [> `A of b ]
Type a is not compatible with type b = a
This instance of a is ambiguous:
it would escape the scope of its equation
|}];;
let f : type a b. (a,b) eq -> [< `A of a | `B] -> [< `A of b | `B] =
[%%expect{|
Lines 1-2, characters 4-15:
1 | ....f : type a b. (a,b) eq -> [< `A of a | `B] -> [< `A of b | `B] =
2 | fun Eq o -> o..............
Error: This definition has type
'c. ('d, 'c) eq -> ([< `A of 'c & 'f & 'd | `B ] as 'e) -> 'e
which is less general than
'a 'b. ('a, 'b) eq -> ([< `A of 'b & 'h | `B ] as 'g) -> 'g
|}];;
let f : type a b. (a,b) eq -> [`A of a | `B] -> [`A of b | `B] =
[%%expect{|
val f : ('a, 'b) eq -> [ `A of 'a | `B ] -> [ `A of 'b | `B ] = <fun>
|}];;
let f : type a. (a, int) eq -> [`A of a] -> bool =
fun Eq v -> match v with `A 1 -> true | _ -> false
[%%expect{|
val f : ('a, int) eq -> [ `A of 'a ] -> bool = <fun>
|}];;
let f : type a b. (a,b) eq -> [> `A of a | `B] -> [`A of b | `B] =
fun eq o ->
ignore (o : [< `A of a | `B]);
r;;
[%%expect{|
val f : ('a, 'b) eq -> [ `A of 'a | `B ] -> [ `A of 'b | `B ] = <fun>
|}, Principal{|
Line 4, characters 49-50:
^
Error: This expression has type [ `A of a | `B ]
but an expression was expected of type [ `A of b | `B ]
Type a is not compatible with type b = a
This instance of a is ambiguous:
it would escape the scope of its equation
|}];;
let f : type a b. (a,b) eq -> [> `A of a | `B] -> [`A of b | `B] =
fun eq o ->
ignore (o : [< `A of a | `B]);
r;;
[%%expect{|
Line 3, characters 49-50:
^
Error: This expression has type [> `A of a | `B ]
but an expression was expected of type [ `A of b | `B ]
Type a is not compatible with type b = a
This instance of a is ambiguous:
it would escape the scope of its equation
|}];;
type 'a t =
A of int | B of bool | C of float | D of 'a
type _ ty =
| TE : 'a ty -> 'a array ty
| TA : int ty
| TB : bool ty
| TC : float ty
| TD : string -> bool ty
let f : type a. a ty -> a t -> int = fun x y ->
match x, y with
| _, A z -> z
| _, B z -> if z then 1 else 2
| _, C z -> truncate z
| TE TC, D [|1.0|] -> 14
| TA, D 0 -> -1
| TA, D z -> z
| TD "bye", D false -> 13
| TD "hello", D true -> 12
| TB , D z - > if z then 1 else 2
| TC, D z -> truncate z
| _, D _ -> 0
;;
[%%expect{|
type 'a t = A of int | B of bool | C of float | D of 'a
type _ ty =
TE : 'a ty -> 'a array ty
| TA : int ty
| TB : bool ty
| TC : float ty
| TD : string -> bool ty
val f : 'a ty -> 'a t -> int = <fun>
|}];;
let f : type a. a ty -> a t -> int = fun x y ->
match x, y with
| _, A z -> z
| _, B z -> if z then 1 else 2
| _, C z -> truncate z
| TE TC, D [|1.0|] -> 14
| TA, D 0 -> -1
| TA, D z -> z
[%%expect{|
Lines 2-8, characters 2-16:
2 | ..match x, y with
3 | | _, A z -> z
4 | | _, B z -> if z then 1 else 2
5 | | _, C z -> truncate z
6 | | TE TC, D [|1.0|] -> 14
7 | | TA, D 0 -> -1
8 | | TA, D z -> z
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
(TE TC, D [| 0. |])
val f : 'a ty -> 'a t -> int = <fun>
|}];;
let f : type a. a ty -> a t -> int = fun x y ->
match y, x with
| A z, _ -> z
| B z, _ -> if z then 1 else 2
| C z, _ -> truncate z
| D [|1.0|], TE TC -> 14
| D 0, TA -> -1
| D z, TA -> z
[%%expect{|
Line 6, characters 6-13:
6 | | D [|1.0|], TE TC -> 14
^^^^^^^
Error: This pattern matches values of type 'a array
but a pattern was expected which matches values of type a
|}];;
type ('a,'b) pair = {right:'a; left:'b}
let f : type a. a ty -> a t -> int = fun x y ->
match {left=x; right=y} with
| {left=_; right=A z} -> z
| {left=_; right=B z} -> if z then 1 else 2
| {left=_; right=C z} -> truncate z
| {left=TE TC; right=D [|1.0|]} -> 14
| {left=TA; right=D 0} -> -1
| {left=TA; right=D z} -> z
[%%expect{|
type ('a, 'b) pair = { right : 'a; left : 'b; }
Line 8, characters 25-32:
8 | | {left=TE TC; right=D [|1.0|]} -> 14
^^^^^^^
Error: This pattern matches values of type 'a array
but a pattern was expected which matches values of type a
|}];;
type ('a,'b) pair = {left:'a; right:'b}
let f : type a. a ty -> a t -> int = fun x y ->
match {left=x; right=y} with
| {left=_; right=A z} -> z
| {left=_; right=B z} -> if z then 1 else 2
| {left=_; right=C z} -> truncate z
| {left=TE TC; right=D [|1.0|]} -> 14
| {left=TA; right=D 0} -> -1
| {left=TA; right=D z} -> z
[%%expect{|
type ('a, 'b) pair = { left : 'a; right : 'b; }
Lines 4-10, characters 2-29:
4 | ..match {left=x; right=y} with
5 | | {left=_; right=A z} -> z
6 | | {left=_; right=B z} -> if z then 1 else 2
7 | | {left=_; right=C z} -> truncate z
8 | | {left=TE TC; right=D [|1.0|]} -> 14
9 | | {left=TA; right=D 0} -> -1
10 | | {left=TA; right=D z} -> z
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
{left=TE TC; right=D [| 0. |]}
val f : 'a ty -> 'a t -> int = <fun>
|}];;
Injectivity
module M : sig type 'a t val eq : ('a t, 'b t) eq end =
struct type 'a t = int let eq = Eq end
;;
let f : type a b. (a M.t, b M.t) eq -> (a, b) eq =
;;
[%%expect{|
module M : sig type 'a t val eq : ('a t, 'b t) eq end
Line 6, characters 17-19:
^^
Error: This expression has type (a, a) eq
but an expression was expected of type (a, b) eq
Type a is not compatible with type b
|}];;
let f : type a b. (a M.t * a, b M.t * b) eq -> (a, b) eq =
;;
[%%expect{|
val f : ('a M.t * 'a, 'b M.t * 'b) eq -> ('a, 'b) eq = <fun>
|}];;
let f : type a b. (a * a M.t, b * b M.t) eq -> (a, b) eq =
;;
[%%expect{|
val f : ('a * 'a M.t, 'b * 'b M.t) eq -> ('a, 'b) eq = <fun>
|}];;
type _ t =
| V1 : [`A | `B] t
| V2 : [`C | `D] t
let f : type a. a t -> a = function
| V1 -> `A
| V2 -> `C
;;
f V1;;
[%%expect{|
type _ t = V1 : [ `A | `B ] t | V2 : [ `C | `D ] t
val f : 'a t -> 'a = <fun>
- : [ `A | `B ] = `A
|}];;
PR#5425 and PR#5427
type _ int_foo =
| IF_constr : <foo:int; ..> int_foo
type _ int_bar =
| IB_constr : <bar:int; ..> int_bar
;;
let g (type t) (x:t) (e : t int_foo) (e' : t int_bar) =
let IF_constr, IB_constr = e, e' in
(x:<foo:int>)
;;
[%%expect{|
type _ int_foo = IF_constr : < foo : int; .. > int_foo
type _ int_bar = IB_constr : < bar : int; .. > int_bar
Line 10, characters 3-4:
10 | (x:<foo:int>)
^
Error: This expression has type t = < foo : int; .. >
but an expression was expected of type < foo : int >
Type $0 = < bar : int; .. > is not compatible with type < >
The second object type has no method bar
|}];;
let g (type t) (x:t) (e : t int_foo) (e' : t int_bar) =
let IF_constr, IB_constr = e, e' in
(x:<foo:int;bar:int>)
;;
[%%expect{|
Line 3, characters 3-4:
3 | (x:<foo:int;bar:int>)
^
Error: This expression has type t = < foo : int; .. >
but an expression was expected of type < bar : int; foo : int >
Type $0 = < bar : int; .. > is not compatible with type < bar : int >
The first object type has an abstract row, it cannot be closed
|}];;
let g (type t) (x:t) (e : t int_foo) (e' : t int_bar) =
let IF_constr, IB_constr = e, e' in
(x:<foo:int;bar:int;..>)
;;
[%%expect{|
Line 3, characters 2-26:
3 | (x:<foo:int;bar:int;..>)
^^^^^^^^^^^^^^^^^^^^^^^^
Error: This expression has type < bar : int; foo : int; .. >
but an expression was expected of type 'a
The type constructor $1 would escape its scope
|}, Principal{|
Line 3, characters 2-26:
3 | (x:<foo:int;bar:int;..>)
^^^^^^^^^^^^^^^^^^^^^^^^
Error: This expression has type < bar : int; foo : int; .. >
but an expression was expected of type 'a
This instance of $1 is ambiguous:
it would escape the scope of its equation
|}];;
let g (type t) (x:t) (e : t int_foo) (e' : t int_bar) : t =
let IF_constr, IB_constr = e, e' in
(x:<foo:int;bar:int;..>)
;;
[%%expect{|
val g : 't -> 't int_foo -> 't int_bar -> 't = <fun>
|}];;
let g (type t) (x:t) (e : t int_foo) (e' : t int_bar) =
let IF_constr, IB_constr = e, e' in
x, x#foo, x#bar
;;
[%%expect{|
val g : 't -> 't int_foo -> 't int_bar -> 't * int * int = <fun>
|}, Principal{|
Line 3, characters 5-10:
3 | x, x#foo, x#bar
^^^^^
Error: This expression has type int but an expression was expected of type 'a
This instance of int is ambiguous:
it would escape the scope of its equation
|}];;
type 'a ty = Int : int -> int ty;;
let f : type a. a ty -> a =
fun x -> match x with Int y -> y;;
let g : type a. a ty -> a =
let () = () in
fun x -> match x with Int y -> y;;
[%%expect{|
type 'a ty = Int : int -> int ty
val f : 'a ty -> 'a = <fun>
val g : 'a ty -> 'a = <fun>
|}];;
module M = struct type _ t = int end;;
module M = struct type _ t = T : int t end;;
module N = M;;
[%%expect{|
module M : sig type _ t = int end
module M : sig type _ t = T : int t end
module N = M
|}];;
let f : type a b. (a,b) eq -> (a,int) eq -> a -> b -> _ = fun ab aint a b ->
let Eq = ab in
let x =
let Eq = aint in
if true then a else b
in ignore x
[%%expect{|
val f : ('a, 'b) eq -> ('a, int) eq -> 'a -> 'b -> unit = <fun>
|}];;
let f : type a b. (a,b) eq -> (b,int) eq -> a -> b -> _ = fun ab bint a b ->
let Eq = ab in
let x =
let Eq = bint in
if true then a else b
in ignore x
[%%expect{|
val f : ('a, 'b) eq -> ('b, int) eq -> 'a -> 'b -> unit = <fun>
|}];;
let f : type a b. (a,b) eq -> (a,int) eq -> a -> b -> _ = fun ab aint a b ->
let Eq = aint in
let x =
let Eq = ab in
if true then a else b
in ignore x
[%%expect{|
Line 5, characters 24-25:
5 | if true then a else b
^
Error: This expression has type b = int
but an expression was expected of type a = int
Type b = int is not compatible with type int
This instance of int is ambiguous:
it would escape the scope of its equation
|}];;
let f : type a b. (a,b) eq -> (b,int) eq -> a -> b -> _ = fun ab bint a b ->
let Eq = bint in
let x =
let Eq = ab in
if true then a else b
in ignore x
[%%expect{|
Line 5, characters 24-25:
5 | if true then a else b
^
Error: This expression has type b = int
but an expression was expected of type a = int
Type int is not compatible with type a = int
This instance of int is ambiguous:
it would escape the scope of its equation
|}];;
let f (type a b c) (b : bool) (w1 : (a,b) eq) (w2 : (a,int) eq) (x : a) (y : b) =
let Eq = w1 in
let Eq = w2 in
if b then x else y
;;
[%%expect{|
Line 4, characters 19-20:
4 | if b then x else y
^
Error: This expression has type b = int
but an expression was expected of type a = int
Type a = int is not compatible with type a = int
This instance of int is ambiguous:
it would escape the scope of its equation
|}];;
let f (type a b c) (b : bool) (w1 : (a,b) eq) (w2 : (a,int) eq) (x : a) (y : b) =
let Eq = w1 in
let Eq = w2 in
if b then y else x
[%%expect{|
Line 4, characters 19-20:
4 | if b then y else x
^
Error: This expression has type a = int
but an expression was expected of type b = int
This instance of int is ambiguous:
it would escape the scope of its equation
|}];;
module M = struct
type t
end
type (_,_) eq = Refl: ('a,'a) eq
let f (x:M.t) (y: (M.t, int -> int) eq) =
let Refl = y in
if true then x else fun x -> x + 1
[%%expect{|
module M : sig type t end
type (_, _) eq = Refl : ('a, 'a) eq
Line 7, characters 22-36:
7 | if true then x else fun x -> x + 1
^^^^^^^^^^^^^^
Error: This expression has type 'a -> 'b
but an expression was expected of type M.t = int -> int
This instance of int -> int is ambiguous:
it would escape the scope of its equation
|}]
module M = struct
type t
end
type (_,_) eq = Refl: ('a,'a) eq
let f (x:M.t) (y: (M.t, int -> int) eq) =
let Refl = y in
if true then fun x -> x + 1 else x
[%%expect{|
module M : sig type t end
type (_, _) eq = Refl : ('a, 'a) eq
Line 7, characters 35-36:
7 | if true then fun x -> x + 1 else x
^
Error: This expression has type M.t = int -> int
but an expression was expected of type int -> int
This instance of int -> int is ambiguous:
it would escape the scope of its equation
|}]
module M = struct
type t
end
type (_,_) eq = Refl: ('a,'a) eq
let f w (x:M.t) (y: (M.t, <m:int>) eq) =
let Refl = y in
let z = if true then x else w in
z#m
[%%expect{|
module M : sig type t end
type (_, _) eq = Refl : ('a, 'a) eq
Line 8, characters 2-3:
8 | z#m
^
Error: This expression has type M.t but an expression was expected of type
< m : 'a; .. >
This instance of < m : int > is ambiguous:
it would escape the scope of its equation
|}]
module M = struct
type t
end
type (_,_) eq = Refl: ('a,'a) eq
let f w (x:M.t) (y: (M.t, <m:int>) eq) =
let Refl = y in
let z = if true then w else x in
z#m
[%%expect{|
module M : sig type t end
type (_, _) eq = Refl : ('a, 'a) eq
Line 8, characters 2-3:
8 | z#m
^
Error: This expression has type M.t but an expression was expected of type
< m : 'a; .. >
This instance of < m : int > is ambiguous:
it would escape the scope of its equation
|}]
type (_,_) eq = Refl: ('a,'a) eq
module M = struct
type t = C : (<m:int; ..> as 'a) * ('a, <m:int; b:bool>) eq -> t
end
let f (C (x,y) : M.t) =
let g w =
let Refl = y in
let z = if true then w else x in
z#b
in ()
[%%expect{|
type (_, _) eq = Refl : ('a, 'a) eq
module M :
sig
type t =
C : (< m : int; .. > as 'a) * ('a, < b : bool; m : int >) eq -> t
end
Line 9, characters 4-5:
9 | z#b
^
Error: This expression has type $C_'a = < b : bool >
but an expression was expected of type < b : 'a; .. >
This instance of < b : bool > is ambiguous:
it would escape the scope of its equation
|}]
type (_,_) eq = Refl: ('a,'a) eq
module M = struct
type t = C : (<m:int; ..> as 'a) * ('a, <m:int; b:bool>) eq -> t
end
let f (C (x,y) : M.t) =
let g w =
let Refl = y in
let z = if true then x else w in
z#b
in ()
[%%expect{|
type (_, _) eq = Refl : ('a, 'a) eq
module M :
sig
type t =
C : (< m : int; .. > as 'a) * ('a, < b : bool; m : int >) eq -> t
end
Line 9, characters 4-5:
9 | z#b
^
Error: This expression has type $C_'a = < b : bool >
but an expression was expected of type < b : 'a; .. >
This instance of < b : bool > is ambiguous:
it would escape the scope of its equation
|}]
|
9f853b4b72d616b77eca0cf0268dd700f8354e0db77535a2e67fa414928c3e0b | ml4tp/tcoq | indfun.mli | open Misctypes
val warn_cannot_define_graph : ?loc:Loc.t -> Pp.std_ppcmds * Pp.std_ppcmds -> unit
val warn_cannot_define_principle : ?loc:Loc.t -> Pp.std_ppcmds * Pp.std_ppcmds -> unit
val do_generate_principle :
bool ->
(Vernacexpr.fixpoint_expr * Vernacexpr.decl_notation list) list ->
unit
val functional_induction :
bool ->
Term.constr ->
(Term.constr * Term.constr bindings) option ->
Tacexpr.or_and_intro_pattern option ->
Proof_type.goal Tacmach.sigma -> Proof_type.goal list Evd.sigma
val make_graph : Globnames.global_reference -> unit
| null | https://raw.githubusercontent.com/ml4tp/tcoq/7a78c31df480fba721648f277ab0783229c8bece/plugins/funind/indfun.mli | ocaml | open Misctypes
val warn_cannot_define_graph : ?loc:Loc.t -> Pp.std_ppcmds * Pp.std_ppcmds -> unit
val warn_cannot_define_principle : ?loc:Loc.t -> Pp.std_ppcmds * Pp.std_ppcmds -> unit
val do_generate_principle :
bool ->
(Vernacexpr.fixpoint_expr * Vernacexpr.decl_notation list) list ->
unit
val functional_induction :
bool ->
Term.constr ->
(Term.constr * Term.constr bindings) option ->
Tacexpr.or_and_intro_pattern option ->
Proof_type.goal Tacmach.sigma -> Proof_type.goal list Evd.sigma
val make_graph : Globnames.global_reference -> unit
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.