_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 |
|---|---|---|---|---|---|---|---|---|
2ada8b57a391c4ecca047a7937123d7debdaf99da33fb8b224efa4ed20aaa693 | hsyl20/haskus-system | Disassembler.hs | # LANGUAGE LambdaCase #
-- | X86 disassembler
module Haskus.Arch.X86_64.Disassembler
( Disass (..)
, linearDisass
, findBlocks
)
where
import Haskus.Format.Binary.Get as G
import Haskus.Format.Binary.Buffer
import Haskus.Arch.X86_64.ISA.Insn
import Haskus.Arch.X86_64.ISA.Mode
import Haskus.Arch.X86_64.ISA.Decoder
import Haskus.Utils.List (intersect)
data Disass
= RawBytes Word Buffer [String]
| Instruction Word Buffer Insn
deriving (Show)
-- | Disassemble a whole buffer linearly
linearDisass :: ExecMode -> Buffer -> [Disass]
linearDisass m = go 0 emptyBuffer []
where
g = G.countBytes $ getInstruction m
go offset fb fbs b
| isBufferEmpty b && isBufferEmpty fb = []
| isBufferEmpty b = [RawBytes (offset - bufferSize fb) fb fbs]
go offset fb fbs b = case G.runGet g b of
Left str -> go (offset+1) (bufferSnoc fb (bufferHead b))
(reverse (str:fbs)) (bufferTail b)
Right (n,i) -> x ++ go (offset + n) emptyBuffer [] (bufferDrop n b)
where
x = if isBufferEmpty fb
then [s]
else [RawBytes (offset - bufferSize fb) fb (reverse fbs), s]
s = Instruction offset (bufferTake n b) i
-- | Find basic blocks by looking at branching/calls
-- Warning: we don't look at branch targets!
findBlocks :: [Disass] -> [[Disass]]
findBlocks = go []
where
go [] [] = []
go bs [] = [reverse bs]
go bs (d@RawBytes {}:ds) = go (d:bs) ds
go bs (d@(Instruction _ _ i):ds) =
if null (insnFamilies (insnSpec i)
`intersect` [Call,Branch,ConditionalBranch,Return])
then go (d:bs) ds
else reverse (d:bs) : go [] ds
| null | https://raw.githubusercontent.com/hsyl20/haskus-system/2f389c6ecae5b0180b464ddef51e36f6e567d690/haskus-system/src/lib/Haskus/Arch/X86_64/Disassembler.hs | haskell | | X86 disassembler
| Disassemble a whole buffer linearly
| Find basic blocks by looking at branching/calls
Warning: we don't look at branch targets! | # LANGUAGE LambdaCase #
module Haskus.Arch.X86_64.Disassembler
( Disass (..)
, linearDisass
, findBlocks
)
where
import Haskus.Format.Binary.Get as G
import Haskus.Format.Binary.Buffer
import Haskus.Arch.X86_64.ISA.Insn
import Haskus.Arch.X86_64.ISA.Mode
import Haskus.Arch.X86_64.ISA.Decoder
import Haskus.Utils.List (intersect)
data Disass
= RawBytes Word Buffer [String]
| Instruction Word Buffer Insn
deriving (Show)
linearDisass :: ExecMode -> Buffer -> [Disass]
linearDisass m = go 0 emptyBuffer []
where
g = G.countBytes $ getInstruction m
go offset fb fbs b
| isBufferEmpty b && isBufferEmpty fb = []
| isBufferEmpty b = [RawBytes (offset - bufferSize fb) fb fbs]
go offset fb fbs b = case G.runGet g b of
Left str -> go (offset+1) (bufferSnoc fb (bufferHead b))
(reverse (str:fbs)) (bufferTail b)
Right (n,i) -> x ++ go (offset + n) emptyBuffer [] (bufferDrop n b)
where
x = if isBufferEmpty fb
then [s]
else [RawBytes (offset - bufferSize fb) fb (reverse fbs), s]
s = Instruction offset (bufferTake n b) i
findBlocks :: [Disass] -> [[Disass]]
findBlocks = go []
where
go [] [] = []
go bs [] = [reverse bs]
go bs (d@RawBytes {}:ds) = go (d:bs) ds
go bs (d@(Instruction _ _ i):ds) =
if null (insnFamilies (insnSpec i)
`intersect` [Call,Branch,ConditionalBranch,Return])
then go (d:bs) ds
else reverse (d:bs) : go [] ds
|
0ed117e3ea966b00486cb62a40f1376b2e1a885cfa6da78eb61c995e1ec47190 | schlepfilter/frp | document.cljs | (ns frp.test.document
(:require [clojure.test.check]
[clojure.test.check.clojure-test
:as clojure-test
:include-macros true]
[frp.core :as frp]
[frp.document :as document]
[frp.test.helpers :as helpers :include-macros true]))
(clojure-test/defspec document
helpers/cljs-num-tests
(helpers/set-up-for-all [advance* helpers/advance]
(frp/activate)
(advance*)
(and (= @document/hidden js/document.hidden)
(= @document/visibility-state
js/document.visibilityState))))
| null | https://raw.githubusercontent.com/schlepfilter/frp/4a889f0aefd3aa17371fe1f0cdfabdad01fece8f/test/frp/test/document.cljs | clojure | (ns frp.test.document
(:require [clojure.test.check]
[clojure.test.check.clojure-test
:as clojure-test
:include-macros true]
[frp.core :as frp]
[frp.document :as document]
[frp.test.helpers :as helpers :include-macros true]))
(clojure-test/defspec document
helpers/cljs-num-tests
(helpers/set-up-for-all [advance* helpers/advance]
(frp/activate)
(advance*)
(and (= @document/hidden js/document.hidden)
(= @document/visibility-state
js/document.visibilityState))))
| |
0288029c0e5faef5cbf4afcb114cc8c000bc0b87339217cc955112367a56eae3 | 4clojure/4clojure | ring_utils.clj | (ns foreclojure.ring-utils
(:require [foreclojure.config :as config]))
(def ^{:dynamic true} *url* nil) ; url of current request
(def ^{:dynamic true} *host* nil) ; Host header sent by client
(def ^{:dynamic true} *http-scheme* nil) ; keyword, :http or :https
(defn get-host [request]
(get-in request [:headers "host"]))
(defn wrap-request-bindings [handler]
(fn [req]
(binding [*url* (:uri req)
*host* (or (get-host req) config/canonical-host)
*http-scheme* (:scheme req)]
(handler req))))
(letfn [(url-fn [host]
(if host
#(str (name (or *http-scheme* :http)) "://" host "/" %)
#(str "/" %)))]
(def universal-url (url-fn (or config/static-host config/canonical-host)))
(def static-url (url-fn config/static-host)))
| null | https://raw.githubusercontent.com/4clojure/4clojure/25dec057d9d6871ce52aee9e2c3de7efdab14373/src/foreclojure/ring_utils.clj | clojure | url of current request
Host header sent by client
keyword, :http or :https | (ns foreclojure.ring-utils
(:require [foreclojure.config :as config]))
(defn get-host [request]
(get-in request [:headers "host"]))
(defn wrap-request-bindings [handler]
(fn [req]
(binding [*url* (:uri req)
*host* (or (get-host req) config/canonical-host)
*http-scheme* (:scheme req)]
(handler req))))
(letfn [(url-fn [host]
(if host
#(str (name (or *http-scheme* :http)) "://" host "/" %)
#(str "/" %)))]
(def universal-url (url-fn (or config/static-host config/canonical-host)))
(def static-url (url-fn config/static-host)))
|
e8a642d43b7733cbf4af8ccc3c9176904cbf70ed14483a35e9b977d5612cbb9e | codinuum/cca | test.ml |
Copyright 2012 - 2020 Codinuum Software Lab < >
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 .
Copyright 2012-2020 Codinuum Software Lab <>
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.
*)
(* test.ml *)
open Printf
open Common
let cmd_name = Filename.basename(Sys.argv.(0))
let dirnames = ref []
let usage_msg = Printf.sprintf "usage: %s DIR1 DIR2" cmd_name
let speclist =
[
]
let _ = Arg.parse
speclist
(fun s -> dirnames := s::!dirnames)
(usage_msg)
let dir1, dir2 =
match !dirnames with
d1::d2::[] -> d2, d1
| _ -> Arg.usage speclist usage_msg; exit 1
class node_data (lab : string) =
object (self)
inherit Otree.data2
method label = lab
method to_string = lab
method to_rep = self#to_string
method to_elem_data = self#to_string, [], ""
method equals nd = self#label = nd#label
method eq nd = false
method digest = None
method _digest = None
method set_digest d = ()
method reset_digest = ()
end
class tree (root : node_data Otree.node2) =
object(self)
inherit [ 'node ] Otree.otree2 root true
method path idx = (self#get idx)#path#to_string
end
exception Dotfile
let file_to_tree file =
let uidgen = new UID.generator in
let rec file_to_node path =
let name = Filename.basename path in
if name = "." || name = ".." then raise Dotfile;
if (Unix.stat path).Unix.st_kind = Unix.S_DIR
then
begin
let obj = new node_data name in
let dirh = Unix.opendir path in
let nodes = ref [] in
(try
while true do
let cpath = sprintf "%s/%s" path (Unix.readdir dirh) in
try
nodes := (file_to_node cpath)::!nodes
with Dotfile -> ()
done
with End_of_file -> ());
Unix.closedir dirh;
let cmp nd1 nd2 = compare nd1#to_rep nd2#to_rep in
Otree.create_node2 uidgen obj (Array.of_list (List.fast_sort cmp !nodes))
end
else
let obj1 = new node_data name in
Otree.create_leaf2 uidgen obj1
in
new tree (file_to_node file)
let analyze tree1 tree2 eds mapping iso =
let get_lab1 i = (tree1#get i)#data#label in
let get_lab2 i = (tree2#get i)#data#label in
let proc_one = function
Edit.Relabel(i1, i2) ->
let lab1, lab2 = get_lab1 i1, get_lab2 i2 in
(try
let c =
Array.map
(fun nd ->
let i = nd#index in
if List.mem i iso then Mapping.find i mapping
else raise Not_found
) ((tree1#get i1)#children)
in
let c' =
Array.map (fun nd -> nd#index) ((tree2#get i2)#children)
in
if c = c' then printf "[RENAMED]: \"%s/%s\" --> \"%s/%s\"\n"
(tree1#path i1) lab1 (tree2#path i2) lab2
with Not_found -> ())
| Edit.Delete i ->
let lab = get_lab1 i in
printf "[DELETED]: \"%s/%s\"\n" (tree1#path i) lab
| Edit.Insert(i, _) ->
let lab = get_lab2 i in
printf "[INSERTED]: \"%s/%s\"\n" (tree2#path i) lab
in
Edit.seq_iter proc_one eds
let dtree1, dtree2 = (file_to_tree dir1), (file_to_tree dir2)
let _ = printf "dir1:\n"; dtree1#print
let _ = printf "dir2:\n"; dtree2#print
let _ = dtree1#save_dot "dir1" [] "dir1.dot"
let _ = dtree2#save_dot "dir2" [] "dir2.dot"
let cost t1 t2 i j = 1
let edits, mapping, iso = ZS.Int.find cost dtree1 dtree2
let _ = printf "\nEdit seq:\n%s\n\n" (Edit.seq_to_string edits)
let _ = analyze dtree1 dtree2 edits mapping iso
let _ = Otdiff.to_dot " test.dot " edits mapping [ ]
let _ = Otdiff.to_dot "test.dot" dtree1 dtree2 edits mapping []
*)
| null | https://raw.githubusercontent.com/codinuum/cca/88ea07f3fe3671b78518769d804fdebabcd28e90/src/otreediff/src/test.ml | ocaml | test.ml |
Copyright 2012 - 2020 Codinuum Software Lab < >
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 .
Copyright 2012-2020 Codinuum Software Lab <>
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.
*)
open Printf
open Common
let cmd_name = Filename.basename(Sys.argv.(0))
let dirnames = ref []
let usage_msg = Printf.sprintf "usage: %s DIR1 DIR2" cmd_name
let speclist =
[
]
let _ = Arg.parse
speclist
(fun s -> dirnames := s::!dirnames)
(usage_msg)
let dir1, dir2 =
match !dirnames with
d1::d2::[] -> d2, d1
| _ -> Arg.usage speclist usage_msg; exit 1
class node_data (lab : string) =
object (self)
inherit Otree.data2
method label = lab
method to_string = lab
method to_rep = self#to_string
method to_elem_data = self#to_string, [], ""
method equals nd = self#label = nd#label
method eq nd = false
method digest = None
method _digest = None
method set_digest d = ()
method reset_digest = ()
end
class tree (root : node_data Otree.node2) =
object(self)
inherit [ 'node ] Otree.otree2 root true
method path idx = (self#get idx)#path#to_string
end
exception Dotfile
let file_to_tree file =
let uidgen = new UID.generator in
let rec file_to_node path =
let name = Filename.basename path in
if name = "." || name = ".." then raise Dotfile;
if (Unix.stat path).Unix.st_kind = Unix.S_DIR
then
begin
let obj = new node_data name in
let dirh = Unix.opendir path in
let nodes = ref [] in
(try
while true do
let cpath = sprintf "%s/%s" path (Unix.readdir dirh) in
try
nodes := (file_to_node cpath)::!nodes
with Dotfile -> ()
done
with End_of_file -> ());
Unix.closedir dirh;
let cmp nd1 nd2 = compare nd1#to_rep nd2#to_rep in
Otree.create_node2 uidgen obj (Array.of_list (List.fast_sort cmp !nodes))
end
else
let obj1 = new node_data name in
Otree.create_leaf2 uidgen obj1
in
new tree (file_to_node file)
let analyze tree1 tree2 eds mapping iso =
let get_lab1 i = (tree1#get i)#data#label in
let get_lab2 i = (tree2#get i)#data#label in
let proc_one = function
Edit.Relabel(i1, i2) ->
let lab1, lab2 = get_lab1 i1, get_lab2 i2 in
(try
let c =
Array.map
(fun nd ->
let i = nd#index in
if List.mem i iso then Mapping.find i mapping
else raise Not_found
) ((tree1#get i1)#children)
in
let c' =
Array.map (fun nd -> nd#index) ((tree2#get i2)#children)
in
if c = c' then printf "[RENAMED]: \"%s/%s\" --> \"%s/%s\"\n"
(tree1#path i1) lab1 (tree2#path i2) lab2
with Not_found -> ())
| Edit.Delete i ->
let lab = get_lab1 i in
printf "[DELETED]: \"%s/%s\"\n" (tree1#path i) lab
| Edit.Insert(i, _) ->
let lab = get_lab2 i in
printf "[INSERTED]: \"%s/%s\"\n" (tree2#path i) lab
in
Edit.seq_iter proc_one eds
let dtree1, dtree2 = (file_to_tree dir1), (file_to_tree dir2)
let _ = printf "dir1:\n"; dtree1#print
let _ = printf "dir2:\n"; dtree2#print
let _ = dtree1#save_dot "dir1" [] "dir1.dot"
let _ = dtree2#save_dot "dir2" [] "dir2.dot"
let cost t1 t2 i j = 1
let edits, mapping, iso = ZS.Int.find cost dtree1 dtree2
let _ = printf "\nEdit seq:\n%s\n\n" (Edit.seq_to_string edits)
let _ = analyze dtree1 dtree2 edits mapping iso
let _ = Otdiff.to_dot " test.dot " edits mapping [ ]
let _ = Otdiff.to_dot "test.dot" dtree1 dtree2 edits mapping []
*)
|
bc50cc29cf04a2d7064e53520c8de979f42dcba38aa581750e2849a80506bde0 | kafka4beam/wolff | wolff_producers.erl | Copyright ( c ) 2018 EMQ Technologies Co. , Ltd. All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%% A per-topic gen_server which manages a number of per-partition wolff_producer workers.
-module(wolff_producers).
%% APIs
-export([start_link/3]).
-export([start_linked_producers/3, stop_linked/1]).
-export([start_supervised/3, stop_supervised/1, stop_supervised/3]).
-export([pick_producer/2, lookup_producer/2]).
%% gen_server callbacks
-export([code_change/3, handle_call/3, handle_cast/2, handle_info/2, init/1, terminate/2]).
-export_type([producers/0, config/0]).
-include("wolff.hrl").
-opaque producers() ::
#{workers := #{partition() => pid()} | ets:tab(),
partitioner := partitioner(),
client_id => wolff:client_id(),
topic => kpro:topic()
}.
-type topic() :: kpro:topic().
-type partition() :: kpro:partition().
-type config_key() :: name | partitioner | partition_count_refresh_interval_seconds |
wolff_producer:config_key().
-type config() :: #{config_key() => term()}.
-type partitioner() :: random %% default
| roundrobin
| first_key_dispatch
| fun((PartitionCount :: pos_integer(), [wolff:msg()]) -> partition())
| partition().
-define(down(Reason), {down, Reason}).
-define(rediscover_client, rediscover_client).
-define(rediscover_client_tref, rediscover_client_tref).
-define(rediscover_client_delay, 1000).
-define(init_producers, init_producers).
-define(init_producers_delay, 1000).
-define(not_initialized, not_initialized).
-define(partition_count_refresh_interval_seconds, 300).
-define(refresh_partition_count, refresh_partition_count).
%% @doc start wolff_producdrs gen_server
start_link(ClientId, Topic, Config) ->
Name = get_name(Config),
gen_server:start_link({local, Name}, ?MODULE, {ClientId, Topic, Config}, []).
%% @doc start wolff_producdrs gen_server
-spec start_linked_producers(wolff:client_id() | pid(), topic(), config()) ->
{ok, producers()} | {error, any()}.
start_linked_producers(ClientId, Topic, ProducerCfg) when is_binary(ClientId) ->
{ok, ClientPid} = wolff_client_sup:find_client(ClientId),
start_linked_producers(ClientId, ClientPid, Topic, ProducerCfg);
start_linked_producers(ClientPid, Topic, ProducerCfg) when is_pid(ClientPid) ->
ClientId = wolff_client:get_id(ClientPid),
start_linked_producers(ClientId, ClientPid, Topic, ProducerCfg).
start_linked_producers(ClientId, ClientPid, Topic, ProducerCfg) ->
case wolff_client:get_leader_connections(ClientPid, Topic) of
{ok, Connections} ->
Workers = start_link_producers(ClientId, Topic, Connections, ProducerCfg),
ok = put_partition_cnt(ClientId, Topic, maps:size(Workers)),
Partitioner = maps:get(partitioner, ProducerCfg, random),
{ok, #{client_id => ClientId,
topic => Topic,
workers => Workers,
partitioner => Partitioner}};
{error, Reason} ->
{error, Reason}
end.
stop_linked(#{workers := Workers}) when is_map(Workers) ->
lists:foreach(
fun({_, Pid}) ->
wolff_producer:stop(Pid) end,
maps:to_list(Workers)).
%% @doc Start supervised producers.
-spec start_supervised(wolff:client_id(), topic(), config()) -> {ok, producers()} | {error, any()}.
start_supervised(ClientId, Topic, ProducerCfg) ->
case wolff_producers_sup:ensure_present(ClientId, Topic, ProducerCfg) of
{ok, Pid} ->
case gen_server:call(Pid, get_workers, infinity) of
?not_initialized ->
%% This means wolff_client failed to fetch metadata
%% for this topic.
_ = wolff_producers_sup:ensure_absence(ClientId, get_name(ProducerCfg)),
{error, failed_to_initialize_producers_in_time};
Ets ->
{ok, #{client_id => ClientId,
topic => Topic,
workers => Ets,
partitioner => maps:get(partitioner, ProducerCfg, random)
}}
end;
{error, Reason} ->
{error, Reason}
end.
%% @doc Ensure workers and clean up meta data.
-spec stop_supervised(producers()) -> ok.
stop_supervised(#{client_id := ClientId, workers := NamedEts, topic := Topic}) ->
stop_supervised(ClientId, Topic, NamedEts).
%% @doc Ensure workers and clean up meta data.
-spec stop_supervised(wolff:client_id(), topic(), wolff:name()) -> ok.
stop_supervised(ClientId, Topic, NamedEts) ->
wolff_producers_sup:ensure_absence(ClientId, NamedEts),
case wolff_client_sup:find_client(ClientId) of
{ok, Pid} ->
ok = wolff_client:delete_producers_metadata(Pid, Topic);
{error, _} ->
%% not running
ok
end.
%% @doc Retrieve the per-partition producer pid.
-spec pick_producer(producers(), [wolff:msg()]) -> {partition(), pid()}.
pick_producer(#{workers := Workers,
partitioner := Partitioner,
client_id := ClientId,
topic := Topic
}, Batch) ->
Count = partition_cnt(ClientId, Topic),
Partition = pick_partition(Count, Partitioner, Batch),
do_pick_producer(Partitioner, Partition, Count, Workers).
do_pick_producer(Partitioner, Partition0, Count, Workers) ->
Pid0 = lookup_producer(Workers, Partition0),
case is_pid(Pid0) andalso is_process_alive(Pid0) of
true -> {Partition0, Pid0};
false when Partitioner =:= random ->
pick_next_alive(Workers, Partition0, Count);
false when Partitioner =:= roundrobin ->
R = {Partition1, _Pid1} = pick_next_alive(Workers, Partition0, Count),
_ = put(wolff_roundrobin, (Partition1 + 1) rem Count),
R;
false ->
erlang:error({producer_down, Pid0})
end.
pick_next_alive(Workers, Partition, Count) ->
pick_next_alive(Workers, (Partition + 1) rem Count, Count, _Tried = 1).
pick_next_alive(_Workers, _Partition, Count, Count) ->
erlang:error(all_producers_down);
pick_next_alive(Workers, Partition, Count, Tried) ->
Pid = lookup_producer(Workers, Partition),
case is_alive(Pid) of
true -> {Partition, Pid};
false -> pick_next_alive(Workers, (Partition + 1) rem Count, Count, Tried + 1)
end.
is_alive(Pid) -> is_pid(Pid) andalso is_process_alive(Pid).
lookup_producer(#{workers := Workers}, Partition) ->
lookup_producer(Workers, Partition);
lookup_producer(Workers, Partition) when is_map(Workers) ->
maps:get(Partition, Workers);
lookup_producer(Workers, Partition) ->
[{Partition, Pid}] = ets:lookup(Workers, Partition),
Pid.
pick_partition(_Count, Partition, _) when is_integer(Partition) ->
Partition;
pick_partition(Count, F, Batch) when is_function(F) ->
F(Count, Batch);
pick_partition(Count, Partitioner, _) when not is_integer(Count);
Count =< 0 ->
error({invalid_partition_count, Count, Partitioner});
pick_partition(Count, random, _) ->
rand:uniform(Count) - 1;
pick_partition(Count, roundrobin, _) ->
Partition = case get(wolff_roundrobin) of
undefined -> 0;
Number -> Number
end,
_ = put(wolff_roundrobin, (Partition + 1) rem Count),
Partition;
pick_partition(Count, first_key_dispatch, [#{key := Key} | _]) ->
erlang:phash2(Key) rem Count.
-spec init({wolff:client_id(), wolff:topic(), config()}) -> {ok, map()}.
init({ClientId, Topic, Config}) ->
erlang:process_flag(trap_exit, true),
self() ! ?rediscover_client,
{ok, #{client_id => ClientId,
client_pid => false,
topic => Topic,
config => Config,
ets => ?not_initialized,
refresh_tref => start_partition_refresh_timer(Config)
}}.
handle_info(?refresh_partition_count, #{refresh_tref := Tref, config := Config} = St0) ->
%% this message can be sent from anywhere,
so we should ensure the timer is cancelled before starting a new one
ok = ensure_timer_cancelled(Tref),
St = refresh_partition_count(St0),
{noreply, St#{refresh_tref := start_partition_refresh_timer(Config)}};
handle_info(?rediscover_client, #{client_id := ClientId,
client_pid := false
} = St0) ->
St1 = St0#{?rediscover_client_tref => false},
case wolff_client_sup:find_client(ClientId) of
{ok, Pid} ->
_ = erlang:monitor(process, Pid),
St2 = St1#{client_pid := Pid},
St3 = maybe_init_producers(St2),
St = maybe_restart_producers(St3),
{noreply, St};
{error, Reason} ->
log_error("failed_to_discover_client",
#{reason => Reason, client_id => ClientId}),
{noreply, ensure_rediscover_client_timer(St1)}
end;
handle_info(?init_producers, St) ->
%% this is a retry of last failure when initializing producer procs
{noreply, maybe_init_producers(St)};
handle_info({'DOWN', _, process, Pid, Reason}, #{client_id := ClientId,
client_pid := Pid
} = St) ->
log_error("client_pid_down", #{client_id => ClientId,
client_pid => Pid,
reason => Reason}),
%% client down, try to discover it after a delay
%% producers should all monitor client pid,
expect their ' EXIT ' signals soon
{noreply, ensure_rediscover_client_timer(St#{client_pid := false})};
handle_info({'EXIT', Pid, Reason},
#{ets := Ets,
topic := Topic,
client_id := ClientId,
client_pid := ClientPid,
config := Config
} = St) ->
case ets:match(Ets, {'$1', Pid}) of
[] ->
%% this should not happen, hence error level
log_error("unknown_EXIT_message", #{pid => Pid, reason => Reason});
[[Partition]] ->
case is_alive(ClientPid) of
true ->
%% wolff_producer is not designed to crash & restart
%% if this happens, it's likely a bug in wolff_producer module
log_error("producer_down",
#{topic => Topic, partition => Partition,
partition_worker => Pid, reason => Reason}),
ok = start_producer_and_insert_pid(Ets, ClientId, Topic, Partition, Config);
false ->
%% no client, restart will be triggered when client connection is back.
ets:insert(Ets, {Partition, ?down(Reason)})
end
end,
{noreply, St};
handle_info(Info, St) ->
log_error("unknown_info", #{info => Info}),
{noreply, St}.
handle_call(get_workers, _From, #{ets := Ets} = St) ->
{reply, Ets, St};
handle_call(Call, From, St) ->
log_error("unknown_call", #{call => Call, from => From}),
{reply, {error, unknown_call}, St}.
handle_cast(Cast, St) ->
log_error("unknown_cast", #{cast => Cast}),
{noreply, St}.
code_change(_OldVsn, St, _Extra) ->
{ok, St}.
terminate(_, _St) -> ok.
ensure_rediscover_client_timer(#{?rediscover_client_tref := false} = St) ->
Tref = erlang:send_after(?rediscover_client_delay, self(), ?rediscover_client),
St#{?rediscover_client_tref := Tref}.
log(Level, Msg, Args) -> logger:log(Level, Args#{msg => Msg}).
log_error(Msg, Args) -> log(error, Msg, Args).
log_warning(Msg, Args) -> log(warning, Msg, Args).
log_info(Msg, Args) -> log(info, Msg, Args).
start_link_producers(ClientId, Topic, Connections, Config) ->
lists:foldl(
fun({Partition, MaybeConnPid}, Acc) ->
{ok, WorkerPid} =
wolff_producer:start_link(ClientId, Topic, Partition,
MaybeConnPid, Config),
Acc#{Partition => WorkerPid}
end, #{}, Connections).
maybe_init_producers(#{ets := ?not_initialized,
topic := Topic,
client_id := ClientId,
config := Config
} = St) ->
case start_linked_producers(ClientId, Topic, Config) of
{ok, #{workers := Workers}} ->
Ets = ets:new(get_name(Config), [protected, named_table, {read_concurrency, true}]),
true = ets:insert(Ets, maps:to_list(Workers)),
St#{ets := Ets};
{error, Reason} ->
log_error("failed_to_init_producers", #{topic => Topic, reason => Reason}),
erlang:send_after(?init_producers_delay, self(), ?init_producers),
St
end;
maybe_init_producers(St) ->
St.
maybe_restart_producers(#{ets := ?not_initialized} = St) -> St;
maybe_restart_producers(#{ets := Ets,
client_id := ClientId,
topic := Topic,
config := Config
} = St) ->
lists:foreach(
fun({Partition, Pid}) ->
case is_alive(Pid) of
true -> ok;
false -> start_producer_and_insert_pid(Ets, ClientId, Topic, Partition, Config)
end
end, ets:tab2list(Ets)),
St.
get_name(Config) -> maps:get(name, Config, ?MODULE).
start_producer_and_insert_pid(Ets, ClientId, Topic, Partition, Config) ->
{ok, Pid} = wolff_producer:start_link(ClientId, Topic, Partition,
?conn_down(to_be_discovered), Config),
ets:insert(Ets, {Partition, Pid}),
ok.
%% Config is not used so far.
start_partition_refresh_timer(Config) ->
IntervalSeconds = maps:get(partition_count_refresh_interval_seconds, Config,
?partition_count_refresh_interval_seconds),
case IntervalSeconds of
0 ->
undefined;
_ ->
Interval = timer:seconds(IntervalSeconds),
erlang:send_after(Interval, self(), ?refresh_partition_count)
end.
refresh_partition_count(#{client_pid := Pid} = St) when not is_pid(Pid) ->
%% client is to be (re)discovered
St;
refresh_partition_count(#{ets := ?not_initialized} = St) ->
%% to be initialized
St;
refresh_partition_count(#{client_pid := Pid, topic := Topic} = St) ->
case wolff_client:get_leader_connections(Pid, Topic) of
{ok, Connections} ->
start_new_producers(St, Connections);
{error, Reason} ->
log_warning("failed_to_refresh_partition_count_will_retry",
#{topic => Topic, reason => Reason}),
St
end.
start_new_producers(#{client_id := ClientId,
topic := Topic,
config := Config,
ets := Ets
} = St, Connections0) ->
NowCount = length(Connections0),
%% process only the newly discovered connections
F = fun({Partition, _MaybeConnPid}) -> [] =:= ets:lookup(Ets, Partition) end,
Connections = lists:filter(F, Connections0),
Workers = start_link_producers(ClientId, Topic, Connections, Config),
true = ets:insert(Ets, maps:to_list(Workers)),
OldCount = partition_cnt(ClientId, Topic),
case OldCount < NowCount of
true ->
log_info("started_producers_for_newly_discovered_partitions",
#{workers => Workers}),
ok = put_partition_cnt(ClientId, Topic, NowCount);
false ->
ok
end,
St.
partition_cnt(ClientId, Topic) ->
persistent_term:get({?MODULE, ClientId, Topic}).
put_partition_cnt(ClientId, Topic, Count) ->
persistent_term:put({?MODULE, ClientId, Topic}, Count).
ensure_timer_cancelled(Tref) when is_reference(Tref) ->
_ = erlang:cancel_timer(Tref),
ok;
ensure_timer_cancelled(_) ->
ok.
| null | https://raw.githubusercontent.com/kafka4beam/wolff/cd20a37e658f4ae3d1468ca20e7d302822ee85dd/src/wolff_producers.erl | erlang |
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
A per-topic gen_server which manages a number of per-partition wolff_producer workers.
APIs
gen_server callbacks
default
@doc start wolff_producdrs gen_server
@doc start wolff_producdrs gen_server
@doc Start supervised producers.
This means wolff_client failed to fetch metadata
for this topic.
@doc Ensure workers and clean up meta data.
@doc Ensure workers and clean up meta data.
not running
@doc Retrieve the per-partition producer pid.
this message can be sent from anywhere,
this is a retry of last failure when initializing producer procs
client down, try to discover it after a delay
producers should all monitor client pid,
this should not happen, hence error level
wolff_producer is not designed to crash & restart
if this happens, it's likely a bug in wolff_producer module
no client, restart will be triggered when client connection is back.
Config is not used so far.
client is to be (re)discovered
to be initialized
process only the newly discovered connections | Copyright ( c ) 2018 EMQ Technologies Co. , Ltd. All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(wolff_producers).
-export([start_link/3]).
-export([start_linked_producers/3, stop_linked/1]).
-export([start_supervised/3, stop_supervised/1, stop_supervised/3]).
-export([pick_producer/2, lookup_producer/2]).
-export([code_change/3, handle_call/3, handle_cast/2, handle_info/2, init/1, terminate/2]).
-export_type([producers/0, config/0]).
-include("wolff.hrl").
-opaque producers() ::
#{workers := #{partition() => pid()} | ets:tab(),
partitioner := partitioner(),
client_id => wolff:client_id(),
topic => kpro:topic()
}.
-type topic() :: kpro:topic().
-type partition() :: kpro:partition().
-type config_key() :: name | partitioner | partition_count_refresh_interval_seconds |
wolff_producer:config_key().
-type config() :: #{config_key() => term()}.
| roundrobin
| first_key_dispatch
| fun((PartitionCount :: pos_integer(), [wolff:msg()]) -> partition())
| partition().
-define(down(Reason), {down, Reason}).
-define(rediscover_client, rediscover_client).
-define(rediscover_client_tref, rediscover_client_tref).
-define(rediscover_client_delay, 1000).
-define(init_producers, init_producers).
-define(init_producers_delay, 1000).
-define(not_initialized, not_initialized).
-define(partition_count_refresh_interval_seconds, 300).
-define(refresh_partition_count, refresh_partition_count).
start_link(ClientId, Topic, Config) ->
Name = get_name(Config),
gen_server:start_link({local, Name}, ?MODULE, {ClientId, Topic, Config}, []).
-spec start_linked_producers(wolff:client_id() | pid(), topic(), config()) ->
{ok, producers()} | {error, any()}.
start_linked_producers(ClientId, Topic, ProducerCfg) when is_binary(ClientId) ->
{ok, ClientPid} = wolff_client_sup:find_client(ClientId),
start_linked_producers(ClientId, ClientPid, Topic, ProducerCfg);
start_linked_producers(ClientPid, Topic, ProducerCfg) when is_pid(ClientPid) ->
ClientId = wolff_client:get_id(ClientPid),
start_linked_producers(ClientId, ClientPid, Topic, ProducerCfg).
start_linked_producers(ClientId, ClientPid, Topic, ProducerCfg) ->
case wolff_client:get_leader_connections(ClientPid, Topic) of
{ok, Connections} ->
Workers = start_link_producers(ClientId, Topic, Connections, ProducerCfg),
ok = put_partition_cnt(ClientId, Topic, maps:size(Workers)),
Partitioner = maps:get(partitioner, ProducerCfg, random),
{ok, #{client_id => ClientId,
topic => Topic,
workers => Workers,
partitioner => Partitioner}};
{error, Reason} ->
{error, Reason}
end.
stop_linked(#{workers := Workers}) when is_map(Workers) ->
lists:foreach(
fun({_, Pid}) ->
wolff_producer:stop(Pid) end,
maps:to_list(Workers)).
-spec start_supervised(wolff:client_id(), topic(), config()) -> {ok, producers()} | {error, any()}.
start_supervised(ClientId, Topic, ProducerCfg) ->
case wolff_producers_sup:ensure_present(ClientId, Topic, ProducerCfg) of
{ok, Pid} ->
case gen_server:call(Pid, get_workers, infinity) of
?not_initialized ->
_ = wolff_producers_sup:ensure_absence(ClientId, get_name(ProducerCfg)),
{error, failed_to_initialize_producers_in_time};
Ets ->
{ok, #{client_id => ClientId,
topic => Topic,
workers => Ets,
partitioner => maps:get(partitioner, ProducerCfg, random)
}}
end;
{error, Reason} ->
{error, Reason}
end.
-spec stop_supervised(producers()) -> ok.
stop_supervised(#{client_id := ClientId, workers := NamedEts, topic := Topic}) ->
stop_supervised(ClientId, Topic, NamedEts).
-spec stop_supervised(wolff:client_id(), topic(), wolff:name()) -> ok.
stop_supervised(ClientId, Topic, NamedEts) ->
wolff_producers_sup:ensure_absence(ClientId, NamedEts),
case wolff_client_sup:find_client(ClientId) of
{ok, Pid} ->
ok = wolff_client:delete_producers_metadata(Pid, Topic);
{error, _} ->
ok
end.
-spec pick_producer(producers(), [wolff:msg()]) -> {partition(), pid()}.
pick_producer(#{workers := Workers,
partitioner := Partitioner,
client_id := ClientId,
topic := Topic
}, Batch) ->
Count = partition_cnt(ClientId, Topic),
Partition = pick_partition(Count, Partitioner, Batch),
do_pick_producer(Partitioner, Partition, Count, Workers).
do_pick_producer(Partitioner, Partition0, Count, Workers) ->
Pid0 = lookup_producer(Workers, Partition0),
case is_pid(Pid0) andalso is_process_alive(Pid0) of
true -> {Partition0, Pid0};
false when Partitioner =:= random ->
pick_next_alive(Workers, Partition0, Count);
false when Partitioner =:= roundrobin ->
R = {Partition1, _Pid1} = pick_next_alive(Workers, Partition0, Count),
_ = put(wolff_roundrobin, (Partition1 + 1) rem Count),
R;
false ->
erlang:error({producer_down, Pid0})
end.
pick_next_alive(Workers, Partition, Count) ->
pick_next_alive(Workers, (Partition + 1) rem Count, Count, _Tried = 1).
pick_next_alive(_Workers, _Partition, Count, Count) ->
erlang:error(all_producers_down);
pick_next_alive(Workers, Partition, Count, Tried) ->
Pid = lookup_producer(Workers, Partition),
case is_alive(Pid) of
true -> {Partition, Pid};
false -> pick_next_alive(Workers, (Partition + 1) rem Count, Count, Tried + 1)
end.
is_alive(Pid) -> is_pid(Pid) andalso is_process_alive(Pid).
lookup_producer(#{workers := Workers}, Partition) ->
lookup_producer(Workers, Partition);
lookup_producer(Workers, Partition) when is_map(Workers) ->
maps:get(Partition, Workers);
lookup_producer(Workers, Partition) ->
[{Partition, Pid}] = ets:lookup(Workers, Partition),
Pid.
pick_partition(_Count, Partition, _) when is_integer(Partition) ->
Partition;
pick_partition(Count, F, Batch) when is_function(F) ->
F(Count, Batch);
pick_partition(Count, Partitioner, _) when not is_integer(Count);
Count =< 0 ->
error({invalid_partition_count, Count, Partitioner});
pick_partition(Count, random, _) ->
rand:uniform(Count) - 1;
pick_partition(Count, roundrobin, _) ->
Partition = case get(wolff_roundrobin) of
undefined -> 0;
Number -> Number
end,
_ = put(wolff_roundrobin, (Partition + 1) rem Count),
Partition;
pick_partition(Count, first_key_dispatch, [#{key := Key} | _]) ->
erlang:phash2(Key) rem Count.
-spec init({wolff:client_id(), wolff:topic(), config()}) -> {ok, map()}.
init({ClientId, Topic, Config}) ->
erlang:process_flag(trap_exit, true),
self() ! ?rediscover_client,
{ok, #{client_id => ClientId,
client_pid => false,
topic => Topic,
config => Config,
ets => ?not_initialized,
refresh_tref => start_partition_refresh_timer(Config)
}}.
handle_info(?refresh_partition_count, #{refresh_tref := Tref, config := Config} = St0) ->
so we should ensure the timer is cancelled before starting a new one
ok = ensure_timer_cancelled(Tref),
St = refresh_partition_count(St0),
{noreply, St#{refresh_tref := start_partition_refresh_timer(Config)}};
handle_info(?rediscover_client, #{client_id := ClientId,
client_pid := false
} = St0) ->
St1 = St0#{?rediscover_client_tref => false},
case wolff_client_sup:find_client(ClientId) of
{ok, Pid} ->
_ = erlang:monitor(process, Pid),
St2 = St1#{client_pid := Pid},
St3 = maybe_init_producers(St2),
St = maybe_restart_producers(St3),
{noreply, St};
{error, Reason} ->
log_error("failed_to_discover_client",
#{reason => Reason, client_id => ClientId}),
{noreply, ensure_rediscover_client_timer(St1)}
end;
handle_info(?init_producers, St) ->
{noreply, maybe_init_producers(St)};
handle_info({'DOWN', _, process, Pid, Reason}, #{client_id := ClientId,
client_pid := Pid
} = St) ->
log_error("client_pid_down", #{client_id => ClientId,
client_pid => Pid,
reason => Reason}),
expect their ' EXIT ' signals soon
{noreply, ensure_rediscover_client_timer(St#{client_pid := false})};
handle_info({'EXIT', Pid, Reason},
#{ets := Ets,
topic := Topic,
client_id := ClientId,
client_pid := ClientPid,
config := Config
} = St) ->
case ets:match(Ets, {'$1', Pid}) of
[] ->
log_error("unknown_EXIT_message", #{pid => Pid, reason => Reason});
[[Partition]] ->
case is_alive(ClientPid) of
true ->
log_error("producer_down",
#{topic => Topic, partition => Partition,
partition_worker => Pid, reason => Reason}),
ok = start_producer_and_insert_pid(Ets, ClientId, Topic, Partition, Config);
false ->
ets:insert(Ets, {Partition, ?down(Reason)})
end
end,
{noreply, St};
handle_info(Info, St) ->
log_error("unknown_info", #{info => Info}),
{noreply, St}.
handle_call(get_workers, _From, #{ets := Ets} = St) ->
{reply, Ets, St};
handle_call(Call, From, St) ->
log_error("unknown_call", #{call => Call, from => From}),
{reply, {error, unknown_call}, St}.
handle_cast(Cast, St) ->
log_error("unknown_cast", #{cast => Cast}),
{noreply, St}.
code_change(_OldVsn, St, _Extra) ->
{ok, St}.
terminate(_, _St) -> ok.
ensure_rediscover_client_timer(#{?rediscover_client_tref := false} = St) ->
Tref = erlang:send_after(?rediscover_client_delay, self(), ?rediscover_client),
St#{?rediscover_client_tref := Tref}.
log(Level, Msg, Args) -> logger:log(Level, Args#{msg => Msg}).
log_error(Msg, Args) -> log(error, Msg, Args).
log_warning(Msg, Args) -> log(warning, Msg, Args).
log_info(Msg, Args) -> log(info, Msg, Args).
start_link_producers(ClientId, Topic, Connections, Config) ->
lists:foldl(
fun({Partition, MaybeConnPid}, Acc) ->
{ok, WorkerPid} =
wolff_producer:start_link(ClientId, Topic, Partition,
MaybeConnPid, Config),
Acc#{Partition => WorkerPid}
end, #{}, Connections).
maybe_init_producers(#{ets := ?not_initialized,
topic := Topic,
client_id := ClientId,
config := Config
} = St) ->
case start_linked_producers(ClientId, Topic, Config) of
{ok, #{workers := Workers}} ->
Ets = ets:new(get_name(Config), [protected, named_table, {read_concurrency, true}]),
true = ets:insert(Ets, maps:to_list(Workers)),
St#{ets := Ets};
{error, Reason} ->
log_error("failed_to_init_producers", #{topic => Topic, reason => Reason}),
erlang:send_after(?init_producers_delay, self(), ?init_producers),
St
end;
maybe_init_producers(St) ->
St.
maybe_restart_producers(#{ets := ?not_initialized} = St) -> St;
maybe_restart_producers(#{ets := Ets,
client_id := ClientId,
topic := Topic,
config := Config
} = St) ->
lists:foreach(
fun({Partition, Pid}) ->
case is_alive(Pid) of
true -> ok;
false -> start_producer_and_insert_pid(Ets, ClientId, Topic, Partition, Config)
end
end, ets:tab2list(Ets)),
St.
get_name(Config) -> maps:get(name, Config, ?MODULE).
start_producer_and_insert_pid(Ets, ClientId, Topic, Partition, Config) ->
{ok, Pid} = wolff_producer:start_link(ClientId, Topic, Partition,
?conn_down(to_be_discovered), Config),
ets:insert(Ets, {Partition, Pid}),
ok.
start_partition_refresh_timer(Config) ->
IntervalSeconds = maps:get(partition_count_refresh_interval_seconds, Config,
?partition_count_refresh_interval_seconds),
case IntervalSeconds of
0 ->
undefined;
_ ->
Interval = timer:seconds(IntervalSeconds),
erlang:send_after(Interval, self(), ?refresh_partition_count)
end.
refresh_partition_count(#{client_pid := Pid} = St) when not is_pid(Pid) ->
St;
refresh_partition_count(#{ets := ?not_initialized} = St) ->
St;
refresh_partition_count(#{client_pid := Pid, topic := Topic} = St) ->
case wolff_client:get_leader_connections(Pid, Topic) of
{ok, Connections} ->
start_new_producers(St, Connections);
{error, Reason} ->
log_warning("failed_to_refresh_partition_count_will_retry",
#{topic => Topic, reason => Reason}),
St
end.
start_new_producers(#{client_id := ClientId,
topic := Topic,
config := Config,
ets := Ets
} = St, Connections0) ->
NowCount = length(Connections0),
F = fun({Partition, _MaybeConnPid}) -> [] =:= ets:lookup(Ets, Partition) end,
Connections = lists:filter(F, Connections0),
Workers = start_link_producers(ClientId, Topic, Connections, Config),
true = ets:insert(Ets, maps:to_list(Workers)),
OldCount = partition_cnt(ClientId, Topic),
case OldCount < NowCount of
true ->
log_info("started_producers_for_newly_discovered_partitions",
#{workers => Workers}),
ok = put_partition_cnt(ClientId, Topic, NowCount);
false ->
ok
end,
St.
partition_cnt(ClientId, Topic) ->
persistent_term:get({?MODULE, ClientId, Topic}).
put_partition_cnt(ClientId, Topic, Count) ->
persistent_term:put({?MODULE, ClientId, Topic}, Count).
ensure_timer_cancelled(Tref) when is_reference(Tref) ->
_ = erlang:cancel_timer(Tref),
ok;
ensure_timer_cancelled(_) ->
ok.
|
b2b2cdba687053a1e512a5267bbfcbba288e5d941932d1f9f15d699c2682f462 | rudymatela/express | Basic.hs | -- |
-- Module : Data.Express.Basic
Copyright : ( c ) 2019 - 2021
License : 3 - Clause BSD ( see the file LICENSE )
Maintainer : < >
--
Defines the ' ' type and _ basic _ utilities involving it , including :
--
* re - export of " Data . Express . Core "
* re - export of " Data . Express . Map "
* re - export of " Data . Express . Fold "
* re - export of " Data . Express . Hole "
--
If you 're a Express user ,
you 're probably better of importing " Data . Express " .
# LANGUAGE CPP #
module Data.Express.Basic
(
-- * Module re-exports
module Data.Express.Core
, module Data.Express.Map
, module Data.Express.Fold
, module Data.Express.Hole
)
where
import Data.Express.Core
import Data.Express.Map
import Data.Express.Fold
import Data.Express.Hole
| null | https://raw.githubusercontent.com/rudymatela/express/24193a8ea5e238404808a8ef196b0973d0383c21/src/Data/Express/Basic.hs | haskell | |
Module : Data.Express.Basic
* Module re-exports | Copyright : ( c ) 2019 - 2021
License : 3 - Clause BSD ( see the file LICENSE )
Maintainer : < >
Defines the ' ' type and _ basic _ utilities involving it , including :
* re - export of " Data . Express . Core "
* re - export of " Data . Express . Map "
* re - export of " Data . Express . Fold "
* re - export of " Data . Express . Hole "
If you 're a Express user ,
you 're probably better of importing " Data . Express " .
# LANGUAGE CPP #
module Data.Express.Basic
(
module Data.Express.Core
, module Data.Express.Map
, module Data.Express.Fold
, module Data.Express.Hole
)
where
import Data.Express.Core
import Data.Express.Map
import Data.Express.Fold
import Data.Express.Hole
|
53e964a11b0d9799d955240c9ae3166808cdafa963b8995ee3ae199a15a0ab36 | christian-marie/oauth2-server | Server.hs | --
Copyright © 2013 - 2015 Anchor Systems , Pty Ltd and Others
--
-- The code in this file, and the program it is a part of, is
-- made available to you by its authors as open source software:
-- you can redistribute it and/or modify it under the terms of
the 3 - clause BSD licence .
--
# LANGUAGE RecordWildCards #
-- |
-- Description: Start an OAuth2 server.
--
-- This module includes the top level interface to run OAuth2 servers.
--
-- For now, we hard-code an implementation that uses PostgreSQL and our
-- particular logic/handlers. The intention is for this to be modular.
module Network.OAuth2.Server
(
startServer,
module Network.OAuth2.Server.App,
module Network.OAuth2.Server.Configuration,
module Network.OAuth2.Server.Statistics,
) where
import Control.Applicative ((<$>))
import Control.Concurrent
import Control.Concurrent.Async
import Control.Concurrent.STM
import Data.Pool
import qualified Data.Streaming.Network as N
import Database.PostgreSQL.Simple
import qualified Network.Socket as S
import Network.Wai.Handler.Warp hiding (Connection)
import System.Log.Logger
import qualified System.Remote.Monitoring as EKG
import Yesod.Core.Dispatch
import qualified Yesod.Static as Static
import Network.OAuth2.Server.App
import Network.OAuth2.Server.Configuration
import Network.OAuth2.Server.Statistics
import Network.OAuth2.Server.Store hiding (logName)
import Network.OAuth2.Server.Types
import Network.Wai.Middleware.Shibboleth
logName :: String
logName = "Network.OAuth2.Server"
-- | Start the statistics-reporting thread.
startStatistics
:: TokenStore ref
=> ServerOptions
-> ref
-> GrantCounters
-> IO (TChan GrantEvent, IO ())
startStatistics ServerOptions{..} ref counters = do
debugM logName $ "Starting EKG"
srv <- EKG.forkServer optStatsHost optStatsPort
output <- newBroadcastTChanIO
input <- atomically $ dupTChan output
registerOAuth2Metrics (EKG.serverMetricStore srv) ref input counters
let stop = do
debugM logName $ "Stopping EKG"
killThread (EKG.serverThreadId srv)
threadDelay 10000
debugM logName $ "Stopped EKG"
return (output, stop)
-- | Start an OAuth2 server.
--
-- This action spawns threads which implement an OAuth2 server and an EKG
-- statistics server (see "System.Remote.Monitoring" for details).
--
-- It returns an IO action which can be used to stop both servers cleanly.
startServer
:: ServerOptions -- ^ Options
-> IO (IO (Async ())) -- ^ Stop action
startServer serverOpts@ServerOptions{..} = do
debugM logName $ "Opening API Socket"
sock <- N.bindPortTCP optServicePort optServiceHost
let createConn = connectPostgreSQL optDBString
destroyConn conn = close conn
stripes = 1
keep_alive = 10
num_conns = 20
ref@(PSQLConnPool pool) <- PSQLConnPool <$>
createPool createConn destroyConn stripes keep_alive num_conns
counters <- mkGrantCounters
(serverEventSink, serverEventStop) <- startStatistics serverOpts ref counters
let settings = setPort optServicePort $ setHost optServiceHost $ defaultSettings
-- Configure static file serving.
-- @TODO(thsutton) This should be configurable.
statics@(Static.Static _) <- Static.static optUIStaticPath
apiSrv <- async $ do
debugM logName $ "Starting API Server"
server <- toWaiAppPlain $ OAuth2Server ref serverOpts serverEventSink statics
runSettingsSocket settings sock . shibboleth optShibboleth $ server
let serverServiceStop = do
debugM logName $ "Closing API Socket"
S.close sock
async $ do
wait apiSrv
debugM logName $ "Stopped API Server"
return $ do
serverEventStop
destroyAllResources pool
serverServiceStop
| null | https://raw.githubusercontent.com/christian-marie/oauth2-server/ebb75be9d05dd52d478a6e069d32461d4e54544e/lib/Network/OAuth2/Server.hs | haskell |
The code in this file, and the program it is a part of, is
made available to you by its authors as open source software:
you can redistribute it and/or modify it under the terms of
|
Description: Start an OAuth2 server.
This module includes the top level interface to run OAuth2 servers.
For now, we hard-code an implementation that uses PostgreSQL and our
particular logic/handlers. The intention is for this to be modular.
| Start the statistics-reporting thread.
| Start an OAuth2 server.
This action spawns threads which implement an OAuth2 server and an EKG
statistics server (see "System.Remote.Monitoring" for details).
It returns an IO action which can be used to stop both servers cleanly.
^ Options
^ Stop action
Configure static file serving.
@TODO(thsutton) This should be configurable. | Copyright © 2013 - 2015 Anchor Systems , Pty Ltd and Others
the 3 - clause BSD licence .
# LANGUAGE RecordWildCards #
module Network.OAuth2.Server
(
startServer,
module Network.OAuth2.Server.App,
module Network.OAuth2.Server.Configuration,
module Network.OAuth2.Server.Statistics,
) where
import Control.Applicative ((<$>))
import Control.Concurrent
import Control.Concurrent.Async
import Control.Concurrent.STM
import Data.Pool
import qualified Data.Streaming.Network as N
import Database.PostgreSQL.Simple
import qualified Network.Socket as S
import Network.Wai.Handler.Warp hiding (Connection)
import System.Log.Logger
import qualified System.Remote.Monitoring as EKG
import Yesod.Core.Dispatch
import qualified Yesod.Static as Static
import Network.OAuth2.Server.App
import Network.OAuth2.Server.Configuration
import Network.OAuth2.Server.Statistics
import Network.OAuth2.Server.Store hiding (logName)
import Network.OAuth2.Server.Types
import Network.Wai.Middleware.Shibboleth
logName :: String
logName = "Network.OAuth2.Server"
startStatistics
:: TokenStore ref
=> ServerOptions
-> ref
-> GrantCounters
-> IO (TChan GrantEvent, IO ())
startStatistics ServerOptions{..} ref counters = do
debugM logName $ "Starting EKG"
srv <- EKG.forkServer optStatsHost optStatsPort
output <- newBroadcastTChanIO
input <- atomically $ dupTChan output
registerOAuth2Metrics (EKG.serverMetricStore srv) ref input counters
let stop = do
debugM logName $ "Stopping EKG"
killThread (EKG.serverThreadId srv)
threadDelay 10000
debugM logName $ "Stopped EKG"
return (output, stop)
startServer
startServer serverOpts@ServerOptions{..} = do
debugM logName $ "Opening API Socket"
sock <- N.bindPortTCP optServicePort optServiceHost
let createConn = connectPostgreSQL optDBString
destroyConn conn = close conn
stripes = 1
keep_alive = 10
num_conns = 20
ref@(PSQLConnPool pool) <- PSQLConnPool <$>
createPool createConn destroyConn stripes keep_alive num_conns
counters <- mkGrantCounters
(serverEventSink, serverEventStop) <- startStatistics serverOpts ref counters
let settings = setPort optServicePort $ setHost optServiceHost $ defaultSettings
statics@(Static.Static _) <- Static.static optUIStaticPath
apiSrv <- async $ do
debugM logName $ "Starting API Server"
server <- toWaiAppPlain $ OAuth2Server ref serverOpts serverEventSink statics
runSettingsSocket settings sock . shibboleth optShibboleth $ server
let serverServiceStop = do
debugM logName $ "Closing API Socket"
S.close sock
async $ do
wait apiSrv
debugM logName $ "Stopped API Server"
return $ do
serverEventStop
destroyAllResources pool
serverServiceStop
|
57867d97b9824f6a3fdefddf116ee15a4fe9a534a6c21dc1913ff000f763da9d | smallhadroncollider/taskell | Detail.hs | # LANGUAGE OverloadedLists #
module Taskell.Events.Actions.Modal.Detail
( event
, events
) where
import ClassyPrelude
import Graphics.Vty.Input.Events
import Taskell.Events.Actions.Types as A (ActionType(..))
import Taskell.Events.State (clearDate, normalMode, quit, store, undo, write)
import Taskell.Events.State.Modal.Detail as Detail
import Taskell.Events.State.Types
import Taskell.Events.State.Types.Mode (DetailItem(..), DetailMode(..))
import Taskell.IO.Keyboard.Types (Actions)
import qualified Taskell.UI.Draw.Field as F (event)
events :: Actions
events
-- general
=
[ (A.Quit, quit)
, (A.Undo, (write =<<) . undo)
, (A.Previous, previousSubtask)
, (A.Next, nextSubtask)
, (A.MoveUp, (write =<<) . (up =<<) . store)
, (A.MoveDown, (write =<<) . (down =<<) . store)
, (A.New, (Detail.insertMode =<<) . (Detail.lastSubtask =<<) . (Detail.newItem =<<) . store)
, (A.NewAbove, Detail.newAbove)
, (A.NewBelow, Detail.newBelow)
, (A.Edit, (Detail.insertMode =<<) . store)
, (A.Complete, (write =<<) . (setComplete =<<) . store)
, (A.Delete, (write =<<) . (Detail.remove =<<) . store)
, (A.DueDate, (editDue =<<) . store)
, (A.ClearDate, (write =<<) . (clearDate =<<) . store)
, (A.Detail, (editDescription =<<) . store)
]
normal :: Event -> Stateful
normal (EvKey KEsc _) = normalMode
normal _ = pure
insert :: Event -> Stateful
insert (EvKey KEsc _) s = do
item <- getCurrentItem s
case item of
DetailDescription -> (write =<<) $ finishDescription s
DetailDate -> showDetail s
(DetailItem _) -> (write =<<) . (showDetail =<<) $ finishSubtask s
insert (EvKey KEnter _) s = do
item <- getCurrentItem s
case item of
DetailDescription -> (write =<<) $ finishDescription s
DetailDate -> (write =<<) $ finishDue s
(DetailItem _) -> (Detail.newBelow =<<) . (write =<<) $ finishSubtask s
insert e s = updateField (F.event e) s
event :: Event -> Stateful
event e s = do
m <- getCurrentMode s
case m of
DetailNormal -> normal e s
(DetailInsert _) -> insert e s
| null | https://raw.githubusercontent.com/smallhadroncollider/taskell/5e5d7d3454daef4373607e6f02f599fc39045b11/src/Taskell/Events/Actions/Modal/Detail.hs | haskell | general | # LANGUAGE OverloadedLists #
module Taskell.Events.Actions.Modal.Detail
( event
, events
) where
import ClassyPrelude
import Graphics.Vty.Input.Events
import Taskell.Events.Actions.Types as A (ActionType(..))
import Taskell.Events.State (clearDate, normalMode, quit, store, undo, write)
import Taskell.Events.State.Modal.Detail as Detail
import Taskell.Events.State.Types
import Taskell.Events.State.Types.Mode (DetailItem(..), DetailMode(..))
import Taskell.IO.Keyboard.Types (Actions)
import qualified Taskell.UI.Draw.Field as F (event)
events :: Actions
events
=
[ (A.Quit, quit)
, (A.Undo, (write =<<) . undo)
, (A.Previous, previousSubtask)
, (A.Next, nextSubtask)
, (A.MoveUp, (write =<<) . (up =<<) . store)
, (A.MoveDown, (write =<<) . (down =<<) . store)
, (A.New, (Detail.insertMode =<<) . (Detail.lastSubtask =<<) . (Detail.newItem =<<) . store)
, (A.NewAbove, Detail.newAbove)
, (A.NewBelow, Detail.newBelow)
, (A.Edit, (Detail.insertMode =<<) . store)
, (A.Complete, (write =<<) . (setComplete =<<) . store)
, (A.Delete, (write =<<) . (Detail.remove =<<) . store)
, (A.DueDate, (editDue =<<) . store)
, (A.ClearDate, (write =<<) . (clearDate =<<) . store)
, (A.Detail, (editDescription =<<) . store)
]
normal :: Event -> Stateful
normal (EvKey KEsc _) = normalMode
normal _ = pure
insert :: Event -> Stateful
insert (EvKey KEsc _) s = do
item <- getCurrentItem s
case item of
DetailDescription -> (write =<<) $ finishDescription s
DetailDate -> showDetail s
(DetailItem _) -> (write =<<) . (showDetail =<<) $ finishSubtask s
insert (EvKey KEnter _) s = do
item <- getCurrentItem s
case item of
DetailDescription -> (write =<<) $ finishDescription s
DetailDate -> (write =<<) $ finishDue s
(DetailItem _) -> (Detail.newBelow =<<) . (write =<<) $ finishSubtask s
insert e s = updateField (F.event e) s
event :: Event -> Stateful
event e s = do
m <- getCurrentMode s
case m of
DetailNormal -> normal e s
(DetailInsert _) -> insert e s
|
4b90398622e66727dc4406b3b352af839726d9cf677d53dccb2bc1bba659fc6a | uim/uim | light-record.scm | ;;; light-record.scm: Lightweight record types
;;;
Copyright ( c ) 2007 - 2013 uim Project
;;;
;;; All rights reserved.
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;;
1 . Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
2 . Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
3 . Neither the name of authors nor the names of its contributors
;;; may be used to endorse or promote products derived from this software
;;; without specific prior written permission.
;;;
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ` ` AS
;;; IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
;;; THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
;;; PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
;;; CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO ,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR
;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;; In contrast to SRFI-9 standard, this record library features:
;;
;; - Automatic accessor name generation (but lost naming scheme
;; selectability)
;;
;; - No memory overhead on each record instance such as record marker
;; and type information (but lost type detectability)
;;
;; - Selectable data backend implementation such as vector and list.
;; List backend enables sharing some tail part between multiple
;; record instances
;;
;; - Composable field-specs (since record definers are not syntax)
;;
;;
;; Specification:
;;
;; <record definition> must be placed on toplevel env.
;;
;; <record definition> ::= (define-vector-record <record name> <field specs>)
;; | (define-list-record <record name> <field specs>)
;; | (define-record-generic <record name> <field specs>
;; <list2record> <record-copy>
;; <record-ref> <record-set!>)
;;
;; <record name> ::= <identifier>
;; <list2record> ::= <procedure>
;; <record-copy> ::= <procedure>
;; <record-ref> ::= <procedure>
;; <record-set!> ::= <procedure>
;;
;; <field specs> ::= ()
;; | (<field spec> . <field specs>)
;;
;; <field spec> ::= <symbol>
;; | (<symbol>)
;; | (<symbol> <default value>)
;;
;; <default value> ::= <any Scheme object>
(require-extension (srfi 1 23))
(cond-expand
(uim)
(else
(require-extension (srfi 43)))) ;; vector-copy
(require "util.scm")
(define %HYPHEN-SYM (string->symbol "-"))
(define %list-set!
(lambda (lst index val)
(set-car! (list-tail lst index)
val)))
(define vector-copy
(if (symbol-bound? 'vector-copy)
vector-copy
(lambda (v)
(list->vector (vector->list v)))))
(define record-field-spec-name
(lambda (fld-spec)
(let ((name (or (safe-car fld-spec)
fld-spec)))
(if (symbol? name)
name
(error "invalid field spec")))))
(define record-field-spec-default-value
(compose safe-car safe-cdr))
(define make-record-spec-name
(lambda (rec-name)
(symbol-append 'record-spec- rec-name)))
(define make-record-constructor-name
(lambda (rec-name)
(symbol-append 'make- rec-name)))
(define make-record-duplicator-name
(lambda (rec-name)
(symbol-append rec-name %HYPHEN-SYM 'copy)))
(define make-record-getter-name
(lambda (rec-name fld-name)
(symbol-append rec-name %HYPHEN-SYM fld-name)))
(define make-record-setter-name
(lambda (rec-name fld-name)
(symbol-append rec-name %HYPHEN-SYM 'set- fld-name '!)))
(define %make-record-constructor
(lambda (rec-name fld-specs list->record)
(let ((defaults (map record-field-spec-default-value fld-specs))
(defaults-len (length fld-specs)))
(lambda init-lst
(if (null? init-lst)
(list->record defaults)
(let ((init-lst-len (length init-lst)))
(cond
((= init-lst-len defaults-len)
(list->record init-lst))
((< init-lst-len defaults-len)
(let* ((rest-defaults (list-tail defaults init-lst-len))
(complemented-init-lst (append init-lst rest-defaults)))
(list->record complemented-init-lst)))
(else
(error "invalid initialization list for record"
rec-name)))))))))
;; To suppress redundant closure allocation, accessors for same
;; <index, type> share identical procedure. And faster short-cut
;; procedures such as car are predefined.
(define %retrieve-record-accessor
(let ((pool `(((0 . ,list-ref) . ,car)
((1 . ,list-ref) . ,cadr)
((2 . ,list-ref) . ,caddr)
((0 . ,%list-set!) . ,set-car!)
((1 . ,%list-set!) . ,(lambda (l v)
(set-car! (cdr l) v)))
((2 . ,%list-set!) . ,(lambda (l v)
(set-car! (cddr l) v))))))
(lambda (index key accessor)
(let ((pool-key (cons index key)))
(cond
((assoc pool-key pool) => cdr)
(else
(set! pool (alist-cons pool-key accessor pool))
accessor))))))
(define %make-record-getter
(lambda (index record-ref)
(let ((getter (lambda (rec)
(record-ref rec index))))
(%retrieve-record-accessor index record-ref getter))))
(define %make-record-setter
(lambda (index record-set!)
(let ((setter (lambda (rec val)
(record-set! rec index val))))
(%retrieve-record-accessor index record-set! setter))))
(define-macro %define-record-getter
(lambda (rec-name fld-name index record-ref)
(let ((getter-name (make-record-getter-name rec-name fld-name)))
`(define ,getter-name (%make-record-getter ,index ,record-ref)))))
(define-macro %define-record-setter
(lambda (rec-name fld-name index record-set!)
(let ((setter-name (make-record-setter-name rec-name fld-name)))
`(define ,setter-name (%make-record-setter ,index ,record-set!)))))
;;(define-macro %define-record-accessors
;; (lambda (rec-name fld-specs record-ref record-set!)
;; (cons 'begin
;; (map (lambda (fld-name index)
;; `(begin
;; (%define-record-getter ,rec-name ,fld-name ,index
;; ,record-ref)
;; (%define-record-setter ,rec-name ,fld-name ,index
;; ,record-set!)))
;; (map record-field-spec-name fld-specs)
;; (iota (length fld-specs))))))
(define-macro define-record-generic
(lambda (rec-name fld-specs list->record record-copy record-ref record-set!)
`(begin
;; define record field specs
(define ,(make-record-spec-name rec-name) ,fld-specs)
;; define record object constructor
(define ,(make-record-constructor-name rec-name)
(%make-record-constructor ',rec-name ,fld-specs ,list->record))
;; define record object duplicator
(define ,(make-record-duplicator-name rec-name) ,record-copy)
;; define record field accessors
,(cons 'begin
(map (lambda (fld-name index)
`(begin
(%define-record-getter ,rec-name ,fld-name ,index
,record-ref)
(%define-record-setter ,rec-name ,fld-name ,index
,record-set!)))
(map record-field-spec-name (eval fld-specs (interaction-environment)))
(iota (length (eval fld-specs (interaction-environment)))))))))
(define-macro define-vector-record
(lambda (rec-name fld-specs)
`(define-record-generic
,rec-name ,fld-specs
list->vector vector-copy vector-ref vector-set!)))
(define-macro define-list-record
(lambda (rec-name fld-specs)
`(define-record-generic
,rec-name ,fld-specs
list-copy list-copy list-ref %list-set!)))
| null | https://raw.githubusercontent.com/uim/uim/d1ac9d9315ff8c57c713b502544fef9b3a83b3e5/scm/light-record.scm | scheme | light-record.scm: Lightweight record types
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
notice, this list of conditions and the following disclaimer.
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
may be used to endorse or promote products derived from this software
without specific prior written permission.
IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
LOSS OF USE , DATA , OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
In contrast to SRFI-9 standard, this record library features:
- Automatic accessor name generation (but lost naming scheme
selectability)
- No memory overhead on each record instance such as record marker
and type information (but lost type detectability)
- Selectable data backend implementation such as vector and list.
List backend enables sharing some tail part between multiple
record instances
- Composable field-specs (since record definers are not syntax)
Specification:
<record definition> must be placed on toplevel env.
<record definition> ::= (define-vector-record <record name> <field specs>)
| (define-list-record <record name> <field specs>)
| (define-record-generic <record name> <field specs>
<list2record> <record-copy>
<record-ref> <record-set!>)
<record name> ::= <identifier>
<list2record> ::= <procedure>
<record-copy> ::= <procedure>
<record-ref> ::= <procedure>
<record-set!> ::= <procedure>
<field specs> ::= ()
| (<field spec> . <field specs>)
<field spec> ::= <symbol>
| (<symbol>)
| (<symbol> <default value>)
<default value> ::= <any Scheme object>
vector-copy
To suppress redundant closure allocation, accessors for same
<index, type> share identical procedure. And faster short-cut
procedures such as car are predefined.
(define-macro %define-record-accessors
(lambda (rec-name fld-specs record-ref record-set!)
(cons 'begin
(map (lambda (fld-name index)
`(begin
(%define-record-getter ,rec-name ,fld-name ,index
,record-ref)
(%define-record-setter ,rec-name ,fld-name ,index
,record-set!)))
(map record-field-spec-name fld-specs)
(iota (length fld-specs))))))
define record field specs
define record object constructor
define record object duplicator
define record field accessors | Copyright ( c ) 2007 - 2013 uim Project
1 . Redistributions of source code must retain the above copyright
2 . Redistributions in binary form must reproduce the above copyright
3 . Neither the name of authors nor the names of its contributors
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ` ` AS
EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO ,
LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
(require-extension (srfi 1 23))
(cond-expand
(uim)
(else
(require "util.scm")
(define %HYPHEN-SYM (string->symbol "-"))
(define %list-set!
(lambda (lst index val)
(set-car! (list-tail lst index)
val)))
(define vector-copy
(if (symbol-bound? 'vector-copy)
vector-copy
(lambda (v)
(list->vector (vector->list v)))))
(define record-field-spec-name
(lambda (fld-spec)
(let ((name (or (safe-car fld-spec)
fld-spec)))
(if (symbol? name)
name
(error "invalid field spec")))))
(define record-field-spec-default-value
(compose safe-car safe-cdr))
(define make-record-spec-name
(lambda (rec-name)
(symbol-append 'record-spec- rec-name)))
(define make-record-constructor-name
(lambda (rec-name)
(symbol-append 'make- rec-name)))
(define make-record-duplicator-name
(lambda (rec-name)
(symbol-append rec-name %HYPHEN-SYM 'copy)))
(define make-record-getter-name
(lambda (rec-name fld-name)
(symbol-append rec-name %HYPHEN-SYM fld-name)))
(define make-record-setter-name
(lambda (rec-name fld-name)
(symbol-append rec-name %HYPHEN-SYM 'set- fld-name '!)))
(define %make-record-constructor
(lambda (rec-name fld-specs list->record)
(let ((defaults (map record-field-spec-default-value fld-specs))
(defaults-len (length fld-specs)))
(lambda init-lst
(if (null? init-lst)
(list->record defaults)
(let ((init-lst-len (length init-lst)))
(cond
((= init-lst-len defaults-len)
(list->record init-lst))
((< init-lst-len defaults-len)
(let* ((rest-defaults (list-tail defaults init-lst-len))
(complemented-init-lst (append init-lst rest-defaults)))
(list->record complemented-init-lst)))
(else
(error "invalid initialization list for record"
rec-name)))))))))
(define %retrieve-record-accessor
(let ((pool `(((0 . ,list-ref) . ,car)
((1 . ,list-ref) . ,cadr)
((2 . ,list-ref) . ,caddr)
((0 . ,%list-set!) . ,set-car!)
((1 . ,%list-set!) . ,(lambda (l v)
(set-car! (cdr l) v)))
((2 . ,%list-set!) . ,(lambda (l v)
(set-car! (cddr l) v))))))
(lambda (index key accessor)
(let ((pool-key (cons index key)))
(cond
((assoc pool-key pool) => cdr)
(else
(set! pool (alist-cons pool-key accessor pool))
accessor))))))
(define %make-record-getter
(lambda (index record-ref)
(let ((getter (lambda (rec)
(record-ref rec index))))
(%retrieve-record-accessor index record-ref getter))))
(define %make-record-setter
(lambda (index record-set!)
(let ((setter (lambda (rec val)
(record-set! rec index val))))
(%retrieve-record-accessor index record-set! setter))))
(define-macro %define-record-getter
(lambda (rec-name fld-name index record-ref)
(let ((getter-name (make-record-getter-name rec-name fld-name)))
`(define ,getter-name (%make-record-getter ,index ,record-ref)))))
(define-macro %define-record-setter
(lambda (rec-name fld-name index record-set!)
(let ((setter-name (make-record-setter-name rec-name fld-name)))
`(define ,setter-name (%make-record-setter ,index ,record-set!)))))
(define-macro define-record-generic
(lambda (rec-name fld-specs list->record record-copy record-ref record-set!)
`(begin
(define ,(make-record-spec-name rec-name) ,fld-specs)
(define ,(make-record-constructor-name rec-name)
(%make-record-constructor ',rec-name ,fld-specs ,list->record))
(define ,(make-record-duplicator-name rec-name) ,record-copy)
,(cons 'begin
(map (lambda (fld-name index)
`(begin
(%define-record-getter ,rec-name ,fld-name ,index
,record-ref)
(%define-record-setter ,rec-name ,fld-name ,index
,record-set!)))
(map record-field-spec-name (eval fld-specs (interaction-environment)))
(iota (length (eval fld-specs (interaction-environment)))))))))
(define-macro define-vector-record
(lambda (rec-name fld-specs)
`(define-record-generic
,rec-name ,fld-specs
list->vector vector-copy vector-ref vector-set!)))
(define-macro define-list-record
(lambda (rec-name fld-specs)
`(define-record-generic
,rec-name ,fld-specs
list-copy list-copy list-ref %list-set!)))
|
57a78e5f3f52ca30b11a141ffd082294bbf8f3493347d085e6c2c16998786188 | microsoft/SLAyer | NSSortedList.mli | Copyright ( c ) Microsoft Corporation . All rights reserved .
(** Operations on sorted ['a list]. *)
module SortedList : sig
val is_sorted : ('a->'a->int)-> 'a list -> bool
val check_sorted : ('a->'a->int)-> 'a list -> 'a list
* Construct a SortedList from an unsorted list .
val sort : ('a->'a->int)-> 'a list -> 'a list
(** Adds an element into a sorted list, if it is not already a member. *)
val add : ('a->'a->int)-> 'a -> 'a list -> 'a list
* Merges two sorted lists using given addition operation , keeping
duplicates .
duplicates. *)
val merge : ('a->'a->int)->
('a -> 'a list -> 'a list) -> 'a list -> 'a list -> 'a list
* Unions two sorted lists using given addition operation .
val union : ('a->'a->int)->
('a -> 'a list -> 'a list) -> 'a list -> 'a list -> 'a list
val inter : ('a->'a->int)-> 'a list -> 'a list -> 'a list
val diff : ('a->'a->int)-> 'a list -> 'a list -> 'a list
val intersect : ('a->'a->int)-> 'a list -> 'a list -> bool
val diff_inter_diff : ('a->'a->int)->
'a list -> 'a list -> 'a list * 'a list * 'a list
val mem : ('a->'a->int)-> 'a -> 'a list -> bool
* Takes two sorted lists [ xs ] , [ ys ] and returns a pair of booleans
indicating whether [ xs ] is a subset of [ ys ] , and whether [ xs ] is a
superset of [ ys ] .
indicating whether [xs] is a subset of [ys], and whether [xs] is a
superset of [ys]. *)
val subsupset : ('a->'a->int)-> 'a list -> 'a list -> bool * bool
end
| null | https://raw.githubusercontent.com/microsoft/SLAyer/6f46f6999c18f415bc368b43b5ba3eb54f0b1c04/src/Library/NSSortedList.mli | ocaml | * Operations on sorted ['a list].
* Adds an element into a sorted list, if it is not already a member. | Copyright ( c ) Microsoft Corporation . All rights reserved .
module SortedList : sig
val is_sorted : ('a->'a->int)-> 'a list -> bool
val check_sorted : ('a->'a->int)-> 'a list -> 'a list
* Construct a SortedList from an unsorted list .
val sort : ('a->'a->int)-> 'a list -> 'a list
val add : ('a->'a->int)-> 'a -> 'a list -> 'a list
* Merges two sorted lists using given addition operation , keeping
duplicates .
duplicates. *)
val merge : ('a->'a->int)->
('a -> 'a list -> 'a list) -> 'a list -> 'a list -> 'a list
* Unions two sorted lists using given addition operation .
val union : ('a->'a->int)->
('a -> 'a list -> 'a list) -> 'a list -> 'a list -> 'a list
val inter : ('a->'a->int)-> 'a list -> 'a list -> 'a list
val diff : ('a->'a->int)-> 'a list -> 'a list -> 'a list
val intersect : ('a->'a->int)-> 'a list -> 'a list -> bool
val diff_inter_diff : ('a->'a->int)->
'a list -> 'a list -> 'a list * 'a list * 'a list
val mem : ('a->'a->int)-> 'a -> 'a list -> bool
* Takes two sorted lists [ xs ] , [ ys ] and returns a pair of booleans
indicating whether [ xs ] is a subset of [ ys ] , and whether [ xs ] is a
superset of [ ys ] .
indicating whether [xs] is a subset of [ys], and whether [xs] is a
superset of [ys]. *)
val subsupset : ('a->'a->int)-> 'a list -> 'a list -> bool * bool
end
|
031ab86034f9b9337bd8fe950789bfcc0bcb7da3d539c205747a44965ce28c80 | marmelab/ocaml-invader | spaceship.ml | type spaceship = {
mutable x: float;
mutable y: float;
}
let collisionBounds invader = (
invader.x -. 30.,
invader.y -. 5.,
invader.x +. 30.,
invader.y +. 5.
)
let renderAt ~x ~y =
GlMat.load_identity ();
GlMat.translate3(x, y, 0.);
GlDraw.color(0.51, 1., 0.);
GlDraw.begins `quads;
List.iter GlDraw.vertex2 [-20., -5.; -20., 5.; 20., 5.; 20., -5.];
List.iter GlDraw.vertex2 [-2., 5.; -2., 14.; 2., 14.; 2., 5.];
GlDraw.ends ()
let render spaceship =
renderAt ~x:spaceship.x ~y:spaceship.y
| null | https://raw.githubusercontent.com/marmelab/ocaml-invader/037280642cdd1b7800df4b9199aa0cdb802efe1c/src/spaceship.ml | ocaml | type spaceship = {
mutable x: float;
mutable y: float;
}
let collisionBounds invader = (
invader.x -. 30.,
invader.y -. 5.,
invader.x +. 30.,
invader.y +. 5.
)
let renderAt ~x ~y =
GlMat.load_identity ();
GlMat.translate3(x, y, 0.);
GlDraw.color(0.51, 1., 0.);
GlDraw.begins `quads;
List.iter GlDraw.vertex2 [-20., -5.; -20., 5.; 20., 5.; 20., -5.];
List.iter GlDraw.vertex2 [-2., 5.; -2., 14.; 2., 14.; 2., 5.];
GlDraw.ends ()
let render spaceship =
renderAt ~x:spaceship.x ~y:spaceship.y
| |
0da71d26384e29f3b18d9049082ee87db35d7c1a2a6317868a5a953294ba9406 | ahrefs/atd | ob_mapping.ml | open Atd.Import
open Atd.Ast
open Mapping
type ob_mapping =
(Ocaml.Repr.t, Biniou.biniou_repr) Mapping.mapping
(*
Translation of the types into the ocaml/biniou mapping.
*)
let rec mapping_of_expr (x : type_expr) : ob_mapping =
match x with
Sum (loc, l, an) ->
let ocaml_t = Ocaml.Repr.Sum (Ocaml.get_ocaml_sum Biniou an) in
let biniou_t = Biniou.Sum in
Sum (loc, Array.of_list (List.map mapping_of_variant l),
ocaml_t, biniou_t)
| Record (loc, l, an) ->
let ocaml_t = Ocaml.Repr.Record (Ocaml.get_ocaml_record Biniou an) in
let ocaml_field_prefix = Ocaml.get_ocaml_field_prefix Biniou an in
let biniou_t = Biniou.Record in
Record (loc,
Array.of_list
(List.map (mapping_of_field ocaml_field_prefix) l),
ocaml_t, biniou_t)
| Tuple (loc, l, _) ->
let ocaml_t = Ocaml.Repr.Tuple in
let biniou_t = Biniou.Tuple in
Tuple (loc, Array.of_list (List.map mapping_of_cell l),
ocaml_t, biniou_t)
| List (loc, x, an) ->
let ocaml_t = Ocaml.Repr.List (Ocaml.get_ocaml_list Biniou an) in
let biniou_t = Biniou.List (Biniou.get_biniou_list an) in
List (loc, mapping_of_expr x, ocaml_t, biniou_t)
| Option (loc, x, _) ->
let ocaml_t = Ocaml.Repr.Option in
let biniou_t = Biniou.Option in
Option (loc, mapping_of_expr x, ocaml_t, biniou_t)
| Nullable (loc, x, _) ->
let ocaml_t = Ocaml.Repr.Nullable in
let biniou_t = Biniou.Nullable in
Nullable (loc, mapping_of_expr x, ocaml_t, biniou_t)
| Shared (_, _, _) ->
failwith "Sharing is no longer supported"
| Wrap (loc, x, a) ->
let ocaml_t =
Ocaml.Repr.Wrap (Ocaml.get_ocaml_wrap ~type_param:[] Biniou loc a) in
let json_t = Biniou.Wrap in
Wrap (loc, mapping_of_expr x, ocaml_t, json_t)
| Name (loc, (_, s, l), an) ->
(match s with
"unit" ->
Unit (loc, Unit, Biniou.Unit)
| "bool" ->
Bool (loc, Bool, Biniou.Bool)
| "int" ->
let o = Ocaml.get_ocaml_int Biniou an in
let b = Biniou.get_biniou_int an in
Int (loc, Int o, Biniou.Int b)
| "float" ->
let b = Biniou.get_biniou_float an in
Float (loc, Float, Biniou.Float b)
| "string" ->
String (loc, String, Biniou.String)
| s ->
Name (loc, s, List.map mapping_of_expr l, None, None)
)
| Tvar (loc, s) ->
Tvar (loc, s)
and mapping_of_cell (cel_loc, x, an) =
{ cel_loc
; cel_value = mapping_of_expr x
; cel_arepr = Ocaml.Repr.Cell
{ Ocaml.ocaml_default = Ocaml.get_ocaml_default Biniou an
; ocaml_fname = ""
; ocaml_mutable = false
; ocaml_fdoc = Atd.Doc.get_doc cel_loc an
}
; cel_brepr = Biniou.Cell
}
and mapping_of_variant = function
| Inherit _ -> assert false
| Variant (var_loc, (var_cons, an), o) ->
{ var_loc
; var_cons
; var_arg = Option.map mapping_of_expr o
; var_arepr = Ocaml.Repr.Variant
{ Ocaml.ocaml_cons = Ocaml.get_ocaml_cons Biniou var_cons an
; ocaml_vdoc = Atd.Doc.get_doc var_loc an
}
; var_brepr = Biniou.Variant
}
and mapping_of_field ocaml_field_prefix = function
| `Inherit _ -> assert false
| `Field (f_loc, (f_name, f_kind, an), x) ->
let { Ox_mapping.ocaml_default; unwrapped } =
Ox_mapping.analyze_field Biniou f_loc f_kind an in
{ f_loc
; f_name
; f_kind
; f_value = mapping_of_expr x
; f_arepr = Ocaml.Repr.Field
{ Ocaml.ocaml_default
; ocaml_fname =
Ocaml.get_ocaml_fname Biniou (ocaml_field_prefix ^ f_name) an
; ocaml_mutable = Ocaml.get_ocaml_mutable Biniou an
; ocaml_fdoc = Atd.Doc.get_doc f_loc an
}
; f_brepr = Biniou.Field { Biniou.biniou_unwrapped = unwrapped };
}
let def_of_atd atd =
Ox_emit.def_of_atd atd ~target:Biniou ~external_:Biniou.External
~mapping_of_expr ~def:Biniou.Def
let defs_of_atd_module l =
List.map (function Atd.Ast.Type def -> def_of_atd def) l
let defs_of_atd_modules l =
List.map (fun (is_rec, l) -> (is_rec, defs_of_atd_module l)) l
| null | https://raw.githubusercontent.com/ahrefs/atd/9a3cb984a695563c04b41cdd7a1ce9454eb40e1c/atdgen/src/ob_mapping.ml | ocaml |
Translation of the types into the ocaml/biniou mapping.
| open Atd.Import
open Atd.Ast
open Mapping
type ob_mapping =
(Ocaml.Repr.t, Biniou.biniou_repr) Mapping.mapping
let rec mapping_of_expr (x : type_expr) : ob_mapping =
match x with
Sum (loc, l, an) ->
let ocaml_t = Ocaml.Repr.Sum (Ocaml.get_ocaml_sum Biniou an) in
let biniou_t = Biniou.Sum in
Sum (loc, Array.of_list (List.map mapping_of_variant l),
ocaml_t, biniou_t)
| Record (loc, l, an) ->
let ocaml_t = Ocaml.Repr.Record (Ocaml.get_ocaml_record Biniou an) in
let ocaml_field_prefix = Ocaml.get_ocaml_field_prefix Biniou an in
let biniou_t = Biniou.Record in
Record (loc,
Array.of_list
(List.map (mapping_of_field ocaml_field_prefix) l),
ocaml_t, biniou_t)
| Tuple (loc, l, _) ->
let ocaml_t = Ocaml.Repr.Tuple in
let biniou_t = Biniou.Tuple in
Tuple (loc, Array.of_list (List.map mapping_of_cell l),
ocaml_t, biniou_t)
| List (loc, x, an) ->
let ocaml_t = Ocaml.Repr.List (Ocaml.get_ocaml_list Biniou an) in
let biniou_t = Biniou.List (Biniou.get_biniou_list an) in
List (loc, mapping_of_expr x, ocaml_t, biniou_t)
| Option (loc, x, _) ->
let ocaml_t = Ocaml.Repr.Option in
let biniou_t = Biniou.Option in
Option (loc, mapping_of_expr x, ocaml_t, biniou_t)
| Nullable (loc, x, _) ->
let ocaml_t = Ocaml.Repr.Nullable in
let biniou_t = Biniou.Nullable in
Nullable (loc, mapping_of_expr x, ocaml_t, biniou_t)
| Shared (_, _, _) ->
failwith "Sharing is no longer supported"
| Wrap (loc, x, a) ->
let ocaml_t =
Ocaml.Repr.Wrap (Ocaml.get_ocaml_wrap ~type_param:[] Biniou loc a) in
let json_t = Biniou.Wrap in
Wrap (loc, mapping_of_expr x, ocaml_t, json_t)
| Name (loc, (_, s, l), an) ->
(match s with
"unit" ->
Unit (loc, Unit, Biniou.Unit)
| "bool" ->
Bool (loc, Bool, Biniou.Bool)
| "int" ->
let o = Ocaml.get_ocaml_int Biniou an in
let b = Biniou.get_biniou_int an in
Int (loc, Int o, Biniou.Int b)
| "float" ->
let b = Biniou.get_biniou_float an in
Float (loc, Float, Biniou.Float b)
| "string" ->
String (loc, String, Biniou.String)
| s ->
Name (loc, s, List.map mapping_of_expr l, None, None)
)
| Tvar (loc, s) ->
Tvar (loc, s)
and mapping_of_cell (cel_loc, x, an) =
{ cel_loc
; cel_value = mapping_of_expr x
; cel_arepr = Ocaml.Repr.Cell
{ Ocaml.ocaml_default = Ocaml.get_ocaml_default Biniou an
; ocaml_fname = ""
; ocaml_mutable = false
; ocaml_fdoc = Atd.Doc.get_doc cel_loc an
}
; cel_brepr = Biniou.Cell
}
and mapping_of_variant = function
| Inherit _ -> assert false
| Variant (var_loc, (var_cons, an), o) ->
{ var_loc
; var_cons
; var_arg = Option.map mapping_of_expr o
; var_arepr = Ocaml.Repr.Variant
{ Ocaml.ocaml_cons = Ocaml.get_ocaml_cons Biniou var_cons an
; ocaml_vdoc = Atd.Doc.get_doc var_loc an
}
; var_brepr = Biniou.Variant
}
and mapping_of_field ocaml_field_prefix = function
| `Inherit _ -> assert false
| `Field (f_loc, (f_name, f_kind, an), x) ->
let { Ox_mapping.ocaml_default; unwrapped } =
Ox_mapping.analyze_field Biniou f_loc f_kind an in
{ f_loc
; f_name
; f_kind
; f_value = mapping_of_expr x
; f_arepr = Ocaml.Repr.Field
{ Ocaml.ocaml_default
; ocaml_fname =
Ocaml.get_ocaml_fname Biniou (ocaml_field_prefix ^ f_name) an
; ocaml_mutable = Ocaml.get_ocaml_mutable Biniou an
; ocaml_fdoc = Atd.Doc.get_doc f_loc an
}
; f_brepr = Biniou.Field { Biniou.biniou_unwrapped = unwrapped };
}
let def_of_atd atd =
Ox_emit.def_of_atd atd ~target:Biniou ~external_:Biniou.External
~mapping_of_expr ~def:Biniou.Def
let defs_of_atd_module l =
List.map (function Atd.Ast.Type def -> def_of_atd def) l
let defs_of_atd_modules l =
List.map (fun (is_rec, l) -> (is_rec, defs_of_atd_module l)) l
|
1a8dc65338a5580801aa8764d27bbfb1c50c65ae2ef10d8c58ab61df4f8cfc19 | mirage/ocaml-matrix | device_lists.ml | open Json_encoding
type t = {changed: string list option; left: string list option}
[@@deriving accessor]
let encoding =
let to_tuple t = t.changed, t.left in
let of_tuple v =
let changed, left = v in
{changed; left} in
let with_tuple =
obj2 (opt "changed" (list string)) (opt "left" (list string)) in
conv to_tuple of_tuple with_tuple
| null | https://raw.githubusercontent.com/mirage/ocaml-matrix/2a58d3d41c43404741f2dfdaf1d2d0f3757b2b69/lib/matrix-ctos/device_lists.ml | ocaml | open Json_encoding
type t = {changed: string list option; left: string list option}
[@@deriving accessor]
let encoding =
let to_tuple t = t.changed, t.left in
let of_tuple v =
let changed, left = v in
{changed; left} in
let with_tuple =
obj2 (opt "changed" (list string)) (opt "left" (list string)) in
conv to_tuple of_tuple with_tuple
| |
490d3a89a67d6514fb944da8eee262989a23eb9a8c8cc0053666cd4f83651dd9 | input-output-hk/plutus-apps | Orphans.hs | {-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DerivingVia #-}
# OPTIONS_GHC -fno - warn - orphans #
module Ledger.Crypto.Orphans where
import Ledger.Builtins.Orphans ()
import Codec.Serialise (Serialise)
import Control.Newtype.Generics (Newtype)
import Data.Aeson (FromJSON, FromJSONKey, ToJSON, ToJSONKey)
import Data.Hashable (Hashable)
import Plutus.V1.Ledger.Crypto
deriving anyclass instance ToJSON PubKeyHash
deriving anyclass instance FromJSON PubKeyHash
deriving anyclass instance FromJSONKey PubKeyHash
deriving anyclass instance ToJSONKey PubKeyHash
deriving anyclass instance Newtype PubKeyHash
deriving newtype instance Serialise PubKeyHash
deriving newtype instance Hashable PubKeyHash
| null | https://raw.githubusercontent.com/input-output-hk/plutus-apps/0d35e44c615b57c8cce48d4e2d38f33e03e6f7cf/plutus-ledger/src/Ledger/Crypto/Orphans.hs | haskell | # LANGUAGE DeriveAnyClass #
# LANGUAGE DerivingVia # | # OPTIONS_GHC -fno - warn - orphans #
module Ledger.Crypto.Orphans where
import Ledger.Builtins.Orphans ()
import Codec.Serialise (Serialise)
import Control.Newtype.Generics (Newtype)
import Data.Aeson (FromJSON, FromJSONKey, ToJSON, ToJSONKey)
import Data.Hashable (Hashable)
import Plutus.V1.Ledger.Crypto
deriving anyclass instance ToJSON PubKeyHash
deriving anyclass instance FromJSON PubKeyHash
deriving anyclass instance FromJSONKey PubKeyHash
deriving anyclass instance ToJSONKey PubKeyHash
deriving anyclass instance Newtype PubKeyHash
deriving newtype instance Serialise PubKeyHash
deriving newtype instance Hashable PubKeyHash
|
39e9c866f658edd2a4171971caff31e51dd4a99c44b5906683463af0b897c927 | krdlab/haskell-oidc-client | Issuers.hs | {-# LANGUAGE OverloadedStrings #-}
|
Module : Web . OIDC.Client . Discovery . Issuers
Maintainer :
Stability : experimental
Module: Web.OIDC.Client.Discovery.Issuers
Maintainer:
Stability: experimental
-}
module Web.OIDC.Client.Discovery.Issuers
(
google
-- TODO: other services
) where
import Web.OIDC.Client.Types (IssuerLocation)
google :: IssuerLocation
google = ""
| null | https://raw.githubusercontent.com/krdlab/haskell-oidc-client/b92736ba7d458b4d8571d378ad750b3e1ddaa7c4/src/Web/OIDC/Client/Discovery/Issuers.hs | haskell | # LANGUAGE OverloadedStrings #
TODO: other services | |
Module : Web . OIDC.Client . Discovery . Issuers
Maintainer :
Stability : experimental
Module: Web.OIDC.Client.Discovery.Issuers
Maintainer:
Stability: experimental
-}
module Web.OIDC.Client.Discovery.Issuers
(
google
) where
import Web.OIDC.Client.Types (IssuerLocation)
google :: IssuerLocation
google = ""
|
b298a1156193bb82e23980fa5eda531a44593e9d4ad0b056e235837e28b31161 | sgbj/MaximaSharp | dasum.lisp | ;;; Compiled by f2cl version:
( " f2cl1.l , v 2edcbd958861 2012/05/30 03:34:52 toy $ "
" f2cl2.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl3.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl4.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl5.l , v 3fe93de3be82 2012/05/06 02:17:14 toy $ "
" f2cl6.l , v 1d5cbacbb977 2008/08/24 00:56:27 rtoy $ "
" macros.l , v 3fe93de3be82 2012/05/06 02:17:14 toy $ " )
;;; Using Lisp CMU Common Lisp 20d (20D Unicode)
;;;
;;; Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t)
;;; (:coerce-assigns :as-needed) (:array-type ':array)
;;; (:array-slicing t) (:declare-common nil)
;;; (:float-format double-float))
(in-package :blas)
(defun dasum (n dx incx)
(declare (type (array double-float (*)) dx)
(type (f2cl-lib:integer4) incx n))
(f2cl-lib:with-multi-array-data
((dx double-float dx-%data% dx-%offset%))
(prog ((i 0) (m 0) (mp1 0) (nincx 0) (dtemp 0.0) (dasum 0.0))
(declare (type (double-float) dasum dtemp)
(type (f2cl-lib:integer4) nincx mp1 m i))
(setf dasum 0.0)
(setf dtemp 0.0)
(if (or (<= n 0) (<= incx 0)) (go end_label))
(if (= incx 1) (go label20))
(setf nincx (f2cl-lib:int-mul n incx))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i incx))
((> i nincx) nil)
(tagbody
(setf dtemp
(+ dtemp
(f2cl-lib:dabs
(f2cl-lib:fref dx-%data% (i) ((1 *)) dx-%offset%))))
label10))
(setf dasum dtemp)
(go end_label)
label20
(setf m (mod n 6))
(if (= m 0) (go label40))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i m) nil)
(tagbody
(setf dtemp
(+ dtemp
(f2cl-lib:dabs
(f2cl-lib:fref dx-%data% (i) ((1 *)) dx-%offset%))))
label30))
(if (< n 6) (go label60))
label40
(setf mp1 (f2cl-lib:int-add m 1))
(f2cl-lib:fdo (i mp1 (f2cl-lib:int-add i 6))
((> i n) nil)
(tagbody
(setf dtemp
(+ dtemp
(f2cl-lib:dabs
(f2cl-lib:fref dx-%data% (i) ((1 *)) dx-%offset%))
(f2cl-lib:dabs
(f2cl-lib:fref dx-%data%
((f2cl-lib:int-add i 1))
((1 *))
dx-%offset%))
(f2cl-lib:dabs
(f2cl-lib:fref dx-%data%
((f2cl-lib:int-add i 2))
((1 *))
dx-%offset%))
(f2cl-lib:dabs
(f2cl-lib:fref dx-%data%
((f2cl-lib:int-add i 3))
((1 *))
dx-%offset%))
(f2cl-lib:dabs
(f2cl-lib:fref dx-%data%
((f2cl-lib:int-add i 4))
((1 *))
dx-%offset%))
(f2cl-lib:dabs
(f2cl-lib:fref dx-%data%
((f2cl-lib:int-add i 5))
((1 *))
dx-%offset%))))
label50))
label60
(setf dasum dtemp)
(go end_label)
end_label
(return (values dasum nil nil nil)))))
(in-package #-gcl #:cl-user #+gcl "CL-USER")
#+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or))
(eval-when (:load-toplevel :compile-toplevel :execute)
(setf (gethash 'fortran-to-lisp::dasum fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo
:arg-types '((fortran-to-lisp::integer4) (array double-float (*))
(fortran-to-lisp::integer4))
:return-values '(nil nil nil)
:calls 'nil)))
| null | https://raw.githubusercontent.com/sgbj/MaximaSharp/75067d7e045b9ed50883b5eb09803b4c8f391059/Test/bin/Debug/Maxima-5.30.0/share/maxima/5.30.0/share/lapack/blas/dasum.lisp | lisp | Compiled by f2cl version:
Using Lisp CMU Common Lisp 20d (20D Unicode)
Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t)
(:coerce-assigns :as-needed) (:array-type ':array)
(:array-slicing t) (:declare-common nil)
(:float-format double-float)) | ( " f2cl1.l , v 2edcbd958861 2012/05/30 03:34:52 toy $ "
" f2cl2.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl3.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl4.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl5.l , v 3fe93de3be82 2012/05/06 02:17:14 toy $ "
" f2cl6.l , v 1d5cbacbb977 2008/08/24 00:56:27 rtoy $ "
" macros.l , v 3fe93de3be82 2012/05/06 02:17:14 toy $ " )
(in-package :blas)
(defun dasum (n dx incx)
(declare (type (array double-float (*)) dx)
(type (f2cl-lib:integer4) incx n))
(f2cl-lib:with-multi-array-data
((dx double-float dx-%data% dx-%offset%))
(prog ((i 0) (m 0) (mp1 0) (nincx 0) (dtemp 0.0) (dasum 0.0))
(declare (type (double-float) dasum dtemp)
(type (f2cl-lib:integer4) nincx mp1 m i))
(setf dasum 0.0)
(setf dtemp 0.0)
(if (or (<= n 0) (<= incx 0)) (go end_label))
(if (= incx 1) (go label20))
(setf nincx (f2cl-lib:int-mul n incx))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i incx))
((> i nincx) nil)
(tagbody
(setf dtemp
(+ dtemp
(f2cl-lib:dabs
(f2cl-lib:fref dx-%data% (i) ((1 *)) dx-%offset%))))
label10))
(setf dasum dtemp)
(go end_label)
label20
(setf m (mod n 6))
(if (= m 0) (go label40))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i m) nil)
(tagbody
(setf dtemp
(+ dtemp
(f2cl-lib:dabs
(f2cl-lib:fref dx-%data% (i) ((1 *)) dx-%offset%))))
label30))
(if (< n 6) (go label60))
label40
(setf mp1 (f2cl-lib:int-add m 1))
(f2cl-lib:fdo (i mp1 (f2cl-lib:int-add i 6))
((> i n) nil)
(tagbody
(setf dtemp
(+ dtemp
(f2cl-lib:dabs
(f2cl-lib:fref dx-%data% (i) ((1 *)) dx-%offset%))
(f2cl-lib:dabs
(f2cl-lib:fref dx-%data%
((f2cl-lib:int-add i 1))
((1 *))
dx-%offset%))
(f2cl-lib:dabs
(f2cl-lib:fref dx-%data%
((f2cl-lib:int-add i 2))
((1 *))
dx-%offset%))
(f2cl-lib:dabs
(f2cl-lib:fref dx-%data%
((f2cl-lib:int-add i 3))
((1 *))
dx-%offset%))
(f2cl-lib:dabs
(f2cl-lib:fref dx-%data%
((f2cl-lib:int-add i 4))
((1 *))
dx-%offset%))
(f2cl-lib:dabs
(f2cl-lib:fref dx-%data%
((f2cl-lib:int-add i 5))
((1 *))
dx-%offset%))))
label50))
label60
(setf dasum dtemp)
(go end_label)
end_label
(return (values dasum nil nil nil)))))
(in-package #-gcl #:cl-user #+gcl "CL-USER")
#+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or))
(eval-when (:load-toplevel :compile-toplevel :execute)
(setf (gethash 'fortran-to-lisp::dasum fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo
:arg-types '((fortran-to-lisp::integer4) (array double-float (*))
(fortran-to-lisp::integer4))
:return-values '(nil nil nil)
:calls 'nil)))
|
2db8d3384555f5c8c2b670e5d814f04d49fcb00f33b1069873026b8cae5d9b12 | ekmett/parsnip | Mark.hs | # language MagicHash #
# language TypeApplications #
{-# language ScopedTypeVariables #-}
# language PatternSynonyms #
# language BlockArguments #
# language BangPatterns #
# language UnboxedTuples #
module Text.Parsnip.Internal.Mark
( Mark(Mark,Mk)
, minusMark
, mark, release
, snip, snipping
) where
import Data.ByteString as B
import Data.Word
import GHC.Arr
import GHC.Prim
import GHC.Ptr
import GHC.Types
import Text.Parsnip.Internal.Parser
import Text.Parsnip.Internal.Private
---------------------------------------------------------------------------------------
-- * Marks
---------------------------------------------------------------------------------------
newtype Mark s = Mark (Ptr Word8) -- unexposed, so known valid addresses
deriving (Eq,Ord,Show)
pattern Mk :: Addr# -> Mark s
pattern Mk a = Mark (Ptr a)
{-# complete Mk #-} -- if only...
instance KnownBase s => Bounded (Mark s) where
minBound = Mk (start @s)
maxBound = Mk (end @s)
# inline minBound #
# inline maxBound #
instance KnownBase s => Enum (Mark s) where
fromEnum p = minusMark p minBound
toEnum = case reflectBase @s of
!(Base _ _ l h) -> \(I# i) -> if isTrue# (0# <=# i) && isTrue# (i <=# minusAddr# h l)
then Mk (plusAddr# l i)
else error "Mark.toEnum: Out of bounds"
succ (Mk p) = if isTrue# (ltAddr# p (end @s))
then Mk (plusAddr# p 1#)
else error "Mark.succ: Out of bounds"
pred (Mk p) = if isTrue# (ltAddr# (start @s) p)
then Mk (plusAddr# p (negateInt# 1#))
else error "Mark.pred: Out of bounds"
enumFrom (Mk p) = ptrs1 p (end @s)
enumFromTo (Mk p) (Mk q) = ptrs1 p q
enumFromThen = case reflectBase @s of
!(Base _ _ l h) -> \(Mk p) (Mk q) -> if isTrue# (gtAddr# p q)
then dptrs p (minusAddr# q p) l
else ptrs p (minusAddr# q p) h
enumFromThenTo (Mk p) (Mk q) (Mk r) = if isTrue# (gtAddr# p q)
then dptrs p (minusAddr# q p) r
else ptrs p (minusAddr# q p) r
# inline fromEnum #
# inline toEnum #
# inline succ #
# inline pred #
# inline enumFrom #
# inline enumFromTo #
# inline enumFromThen #
{-# inline enumFromThenTo #-}
instance Ix (Mark s) where
range (Mk p, Mk q) = ptrs1 p q
unsafeIndex (p,_) r = minusMark r p
inRange (Mk p, Mk q) (Mk r) = isTrue# (leAddr# p r) && isTrue# (leAddr# r q)
unsafeRangeSize = uncurry minusMark
{-# inline range #-}
# inline unsafeIndex #
# inline inRange #
# inline unsafeRangeSize #
ptrs1 :: Addr# -> Addr# -> [Mark s]
ptrs1 l h
| isTrue# (leAddr# l h) = Mk l : ptrs1 (plusAddr# l 1#) h
| otherwise = []
{-# inline ptrs1 #-}
ptrs :: Addr# -> Int# -> Addr# -> [Mark s]
ptrs l d h
| isTrue# (leAddr# l h) = Mk l : ptrs (plusAddr# l d) d h
| otherwise = []
# inline ptrs #
dptrs :: Addr# -> Int# -> Addr# -> [Mark s]
dptrs h d l
| isTrue# (leAddr# l h) = Mark (Ptr h) : ptrs (plusAddr# h d) d l
| otherwise = []
# inline dptrs #
minusMark :: Mark s -> Mark s -> Int
minusMark (Mk p) (Mk q) = I# (minusAddr# p q)
# inline minusMark #
-- | Record the current position
mark :: Parser s e (Mark s)
mark = Parser \p s -> OK (Mk p) p s
# inline mark #
-- | Return to a previous location.
release :: Mark s -> Parser s e ()
release (Mk q) = Parser \_ s -> OK () q s
{-# inline release #-}
-- | To grab all the text covered by a given parser, consider using @snipping@
-- and applying it to a combinator simply recognizes the content rather than returns
-- it. 'snipping' a 'ByteString' is significantly cheaper than assembling one from
-- smaller fragments.
snip :: forall s. KnownBase s => Mark s -> Mark s -> ByteString
snip = case reflectBase @s of
!(Base x g _ _) -> \(Mk i) (Mk j) ->
if isTrue# (geAddr# i j)
then mkBS x g (minusAddr# i j)
else B.empty
# inline snip #
snipping :: forall s e a. KnownBase s => Parser s e a -> Parser s e ByteString
snipping = case reflectBase @s of
!(Base b g r _) -> \(Parser m) -> Parser \p s -> case m p s of
(# o, q, t #) ->
(# setRes
( if isTrue# (geAddr# q p)
then mkBS (b `plusAddr#` minusAddr# p r) g (minusAddr# q p)
else B.empty
) o
, q, t #)
# inline snipping #
| null | https://raw.githubusercontent.com/ekmett/parsnip/f2d2273b81177b6e5732b2f963f856efeae7a9ed/src/Text/Parsnip/Internal/Mark.hs | haskell | # language ScopedTypeVariables #
-------------------------------------------------------------------------------------
* Marks
-------------------------------------------------------------------------------------
unexposed, so known valid addresses
# complete Mk #
if only...
# inline enumFromThenTo #
# inline range #
# inline ptrs1 #
| Record the current position
| Return to a previous location.
# inline release #
| To grab all the text covered by a given parser, consider using @snipping@
and applying it to a combinator simply recognizes the content rather than returns
it. 'snipping' a 'ByteString' is significantly cheaper than assembling one from
smaller fragments. | # language MagicHash #
# language TypeApplications #
# language PatternSynonyms #
# language BlockArguments #
# language BangPatterns #
# language UnboxedTuples #
module Text.Parsnip.Internal.Mark
( Mark(Mark,Mk)
, minusMark
, mark, release
, snip, snipping
) where
import Data.ByteString as B
import Data.Word
import GHC.Arr
import GHC.Prim
import GHC.Ptr
import GHC.Types
import Text.Parsnip.Internal.Parser
import Text.Parsnip.Internal.Private
deriving (Eq,Ord,Show)
pattern Mk :: Addr# -> Mark s
pattern Mk a = Mark (Ptr a)
instance KnownBase s => Bounded (Mark s) where
minBound = Mk (start @s)
maxBound = Mk (end @s)
# inline minBound #
# inline maxBound #
instance KnownBase s => Enum (Mark s) where
fromEnum p = minusMark p minBound
toEnum = case reflectBase @s of
!(Base _ _ l h) -> \(I# i) -> if isTrue# (0# <=# i) && isTrue# (i <=# minusAddr# h l)
then Mk (plusAddr# l i)
else error "Mark.toEnum: Out of bounds"
succ (Mk p) = if isTrue# (ltAddr# p (end @s))
then Mk (plusAddr# p 1#)
else error "Mark.succ: Out of bounds"
pred (Mk p) = if isTrue# (ltAddr# (start @s) p)
then Mk (plusAddr# p (negateInt# 1#))
else error "Mark.pred: Out of bounds"
enumFrom (Mk p) = ptrs1 p (end @s)
enumFromTo (Mk p) (Mk q) = ptrs1 p q
enumFromThen = case reflectBase @s of
!(Base _ _ l h) -> \(Mk p) (Mk q) -> if isTrue# (gtAddr# p q)
then dptrs p (minusAddr# q p) l
else ptrs p (minusAddr# q p) h
enumFromThenTo (Mk p) (Mk q) (Mk r) = if isTrue# (gtAddr# p q)
then dptrs p (minusAddr# q p) r
else ptrs p (minusAddr# q p) r
# inline fromEnum #
# inline toEnum #
# inline succ #
# inline pred #
# inline enumFrom #
# inline enumFromTo #
# inline enumFromThen #
instance Ix (Mark s) where
range (Mk p, Mk q) = ptrs1 p q
unsafeIndex (p,_) r = minusMark r p
inRange (Mk p, Mk q) (Mk r) = isTrue# (leAddr# p r) && isTrue# (leAddr# r q)
unsafeRangeSize = uncurry minusMark
# inline unsafeIndex #
# inline inRange #
# inline unsafeRangeSize #
ptrs1 :: Addr# -> Addr# -> [Mark s]
ptrs1 l h
| isTrue# (leAddr# l h) = Mk l : ptrs1 (plusAddr# l 1#) h
| otherwise = []
ptrs :: Addr# -> Int# -> Addr# -> [Mark s]
ptrs l d h
| isTrue# (leAddr# l h) = Mk l : ptrs (plusAddr# l d) d h
| otherwise = []
# inline ptrs #
dptrs :: Addr# -> Int# -> Addr# -> [Mark s]
dptrs h d l
| isTrue# (leAddr# l h) = Mark (Ptr h) : ptrs (plusAddr# h d) d l
| otherwise = []
# inline dptrs #
minusMark :: Mark s -> Mark s -> Int
minusMark (Mk p) (Mk q) = I# (minusAddr# p q)
# inline minusMark #
mark :: Parser s e (Mark s)
mark = Parser \p s -> OK (Mk p) p s
# inline mark #
release :: Mark s -> Parser s e ()
release (Mk q) = Parser \_ s -> OK () q s
snip :: forall s. KnownBase s => Mark s -> Mark s -> ByteString
snip = case reflectBase @s of
!(Base x g _ _) -> \(Mk i) (Mk j) ->
if isTrue# (geAddr# i j)
then mkBS x g (minusAddr# i j)
else B.empty
# inline snip #
snipping :: forall s e a. KnownBase s => Parser s e a -> Parser s e ByteString
snipping = case reflectBase @s of
!(Base b g r _) -> \(Parser m) -> Parser \p s -> case m p s of
(# o, q, t #) ->
(# setRes
( if isTrue# (geAddr# q p)
then mkBS (b `plusAddr#` minusAddr# p r) g (minusAddr# q p)
else B.empty
) o
, q, t #)
# inline snipping #
|
f3705ef7e2cb0085265d081d85b70b46a97342b2d408bcdaba35fbd3fbc473cb | bzuilhof/AdventOfCode | day7.hs | module Day7 where
import Data.List
import Data.Char
import Data.Maybe
type Task = Char
type Constraint = (Task, Task)
type Worker = (Task, Int)
inputData :: [Constraint]
inputData = [('C','P'),('V','Q'),('T','X'),('B','U'),('Z','O'),('P','I'),('D','G'),('A','Y'),('R','O'),('J','E'),('N','S'),('X','H'),('F','L'),('S','I'),('W','Q'),('H','K'),('K','Q'),('E','L'),('Q','O'),('U','G'),('L','O'),('Y','G'),('G','I'),('M','I'),('I','O'),('A','N'),('H','O'),('T','O'),('H','U'),('A','I'),('B','R'),('V','T'),('H','M'),('C','A'),('B','G'),('L','Y'),('T','J'),('A','R'),('X','L'),('B','L'),('A','F'),('K','O'),('W','M'),('Z','N'),('Z','S'),('R','K'),('Q','L'),('G','O'),('F','Y'),('V','H'),('E','I'),('W','Y'),('U','I'),('F','K'),('M','O'),('Z','H'),('X','S'),('J','O'),('B','I'),('F','H'),('D','U'),('E','M'),('Z','X'),('P','L'),('W','H'),('C','D'),('A','X'),('Q','I'),('R','Y'),('B','A'),('N','L'),('H','G'),('Y','M'),('L','G'),('G','M'),('Z','R'),('S','Q'),('P','J'),('V','J'),('J','I'),('J','X'),('W','O'),('B','F'),('R','M'),('V','S'),('R','W'),('H','E'),('E','U'),('X','Q'),('N','G'),('T','I'),('L','M'),('H','I'),('U','M'),('C','H'),('P','H'),('J','F'),('A','O'),('X','M'),('H','L'),('W','K')]
getAvailableTask :: [Task] -> [Task] -> Maybe Task
getAvailableTask [] done = Nothing
getAvailableTask todo done = getMaybeTask avail
where constraints = nub (map snd (getConstraints done))
avail = filter (`notElem` constraints) todo
getMaybeTask :: [Task] -> Maybe Task
getMaybeTask tasks | not (null tasks) = Just (minimum tasks)
| otherwise = Nothing
getConstraints :: [Task] -> [Constraint]
getConstraints done = filter (\x -> fst x `notElem` done) inputData
calcTasks :: [Task] -> [Task] -> [Task]
calcTasks [x] _ = [x]
calcTasks todo done = firedTask : calcTasks todo' done'
where
firedTask = fromJust (getAvailableTask todo done)
todo' = filter (/= firedTask) todo
done' = firedTask : done
calcWorkers :: [Worker] -> [Task] -> [Task] -> Int -> Int
calcWorkers workers todo done c | all (== ('-', 0)) workers && null todo = c
| isJust finishedTask = calcWorkers workers' todo done' c
| ('-',0) `elem` workers && isJust availableTask = calcWorkers workers'' todo' done c
| otherwise = calcWorkers (workerNext workers) todo done (c+1)
where
finishedTask = getReadyTask workers
done' = fromJust finishedTask : done
workers' = removeTask workers (fromJust finishedTask)
workers'' = assignTask workers (fromJust availableTask)
availableTask = getAvailableTask todo done
todo' = filter (/= fromJust availableTask) todo
workerNext :: [Worker] -> [Worker]
workerNext [] = []
workerNext (x:xs) | ta /= '-' = (ta, ti-1) : workerNext xs
| otherwise = x : workerNext xs
where (ta, ti) = x
removeTask :: [Worker] -> Task -> [Worker]
removeTask [] _ = []
removeTask (x:xs) rta | rta == ta = ('-',0) : xs
| otherwise = x : removeTask xs rta
where (ta,ti) = x
getReadyTask :: [Worker] -> Maybe Task
getReadyTask [] = Nothing
getReadyTask (x:xs) | ta /= '-' && ti == 0= Just ta
| otherwise = getReadyTask xs
where (ta,ti) = x
assignTask :: [Worker] -> Task -> [Worker]
assignTask (x:xs) nt | ta == '-' = (nt, cost) : xs
| otherwise = x : assignTask xs nt
where
(ta,ti) = x
cost = fromJust (elemIndex nt ['A'..'Z']) + 61
resultP1 :: [Task]
resultP1 = calcTasks ['A'..'Z'] []
resultP2 :: Int
resultP2 = calcWorkers (replicate 5 ('-',0)) ['A'..'Z'] [] 0 | null | https://raw.githubusercontent.com/bzuilhof/AdventOfCode/e6ff762c1c766e028fb90ef62b8f4dc4adf9ecc1/2018/day7.hs | haskell | module Day7 where
import Data.List
import Data.Char
import Data.Maybe
type Task = Char
type Constraint = (Task, Task)
type Worker = (Task, Int)
inputData :: [Constraint]
inputData = [('C','P'),('V','Q'),('T','X'),('B','U'),('Z','O'),('P','I'),('D','G'),('A','Y'),('R','O'),('J','E'),('N','S'),('X','H'),('F','L'),('S','I'),('W','Q'),('H','K'),('K','Q'),('E','L'),('Q','O'),('U','G'),('L','O'),('Y','G'),('G','I'),('M','I'),('I','O'),('A','N'),('H','O'),('T','O'),('H','U'),('A','I'),('B','R'),('V','T'),('H','M'),('C','A'),('B','G'),('L','Y'),('T','J'),('A','R'),('X','L'),('B','L'),('A','F'),('K','O'),('W','M'),('Z','N'),('Z','S'),('R','K'),('Q','L'),('G','O'),('F','Y'),('V','H'),('E','I'),('W','Y'),('U','I'),('F','K'),('M','O'),('Z','H'),('X','S'),('J','O'),('B','I'),('F','H'),('D','U'),('E','M'),('Z','X'),('P','L'),('W','H'),('C','D'),('A','X'),('Q','I'),('R','Y'),('B','A'),('N','L'),('H','G'),('Y','M'),('L','G'),('G','M'),('Z','R'),('S','Q'),('P','J'),('V','J'),('J','I'),('J','X'),('W','O'),('B','F'),('R','M'),('V','S'),('R','W'),('H','E'),('E','U'),('X','Q'),('N','G'),('T','I'),('L','M'),('H','I'),('U','M'),('C','H'),('P','H'),('J','F'),('A','O'),('X','M'),('H','L'),('W','K')]
getAvailableTask :: [Task] -> [Task] -> Maybe Task
getAvailableTask [] done = Nothing
getAvailableTask todo done = getMaybeTask avail
where constraints = nub (map snd (getConstraints done))
avail = filter (`notElem` constraints) todo
getMaybeTask :: [Task] -> Maybe Task
getMaybeTask tasks | not (null tasks) = Just (minimum tasks)
| otherwise = Nothing
getConstraints :: [Task] -> [Constraint]
getConstraints done = filter (\x -> fst x `notElem` done) inputData
calcTasks :: [Task] -> [Task] -> [Task]
calcTasks [x] _ = [x]
calcTasks todo done = firedTask : calcTasks todo' done'
where
firedTask = fromJust (getAvailableTask todo done)
todo' = filter (/= firedTask) todo
done' = firedTask : done
calcWorkers :: [Worker] -> [Task] -> [Task] -> Int -> Int
calcWorkers workers todo done c | all (== ('-', 0)) workers && null todo = c
| isJust finishedTask = calcWorkers workers' todo done' c
| ('-',0) `elem` workers && isJust availableTask = calcWorkers workers'' todo' done c
| otherwise = calcWorkers (workerNext workers) todo done (c+1)
where
finishedTask = getReadyTask workers
done' = fromJust finishedTask : done
workers' = removeTask workers (fromJust finishedTask)
workers'' = assignTask workers (fromJust availableTask)
availableTask = getAvailableTask todo done
todo' = filter (/= fromJust availableTask) todo
workerNext :: [Worker] -> [Worker]
workerNext [] = []
workerNext (x:xs) | ta /= '-' = (ta, ti-1) : workerNext xs
| otherwise = x : workerNext xs
where (ta, ti) = x
removeTask :: [Worker] -> Task -> [Worker]
removeTask [] _ = []
removeTask (x:xs) rta | rta == ta = ('-',0) : xs
| otherwise = x : removeTask xs rta
where (ta,ti) = x
getReadyTask :: [Worker] -> Maybe Task
getReadyTask [] = Nothing
getReadyTask (x:xs) | ta /= '-' && ti == 0= Just ta
| otherwise = getReadyTask xs
where (ta,ti) = x
assignTask :: [Worker] -> Task -> [Worker]
assignTask (x:xs) nt | ta == '-' = (nt, cost) : xs
| otherwise = x : assignTask xs nt
where
(ta,ti) = x
cost = fromJust (elemIndex nt ['A'..'Z']) + 61
resultP1 :: [Task]
resultP1 = calcTasks ['A'..'Z'] []
resultP2 :: Int
resultP2 = calcWorkers (replicate 5 ('-',0)) ['A'..'Z'] [] 0 | |
63832398453fe1c33ab659924186c29d228c5e3af01ca224f693c8358159c3b9 | jserot/lascar | conv.mli | (**********************************************************************)
(* *)
LASCAr
(* *)
Copyright ( c ) 2017 - present , . All rights reserved .
(* *)
(* This source code is licensed under the license found in the *)
(* LICENSE file in the root directory of this source tree. *)
(* *)
(**********************************************************************)
* { 2 Functors for converting various kinds of Labeled Transition Systems }
* Functor for converting a { ! Ltsa } into a { ! } ( by removing state attributes )
module ToLts (M: Ltsa.T) : sig
include Lts.T with type state = M.state and type label = M.label
val conv: M.t -> t
end
* Functor for converting a { ! } into a { ! Ltsa } ( by adding [ unit ] state attributes )
module FromLts (M: Lts.T) : sig
include Ltsa.T with type state = M.state and type label = M.label and type attr = unit
val conv: M.t -> t
end
* Functor for converting a { ! } to an equivalent { ! Dfa } ( determinisation )
module ToDfa (N : Nfa.T) : sig
include Dfa.T with type state = N.States.t and type symbol = N.symbol
* Each state of a resulting DFA is a subset of states of the NFA
val conv: N.t -> t
end
* Functor for converting a { ! } machine into an equivalent { ! } one
module ToMealy (MM: Moore.T) : sig
include Mealy.T with type state = MM.state
val conv: MM.t -> t
* Convert a automata into a Mealy automata , by turning
- turning each state [ ( q , o ) ] into [ q ]
- turning each transitions [ ( ( q , o)/i/(q',o ' ) ] into [ q,(i / o'),q ' ]
- turning each state [(q,o)] into [q]
- turning each transitions [((q,o)/i/(q',o')] into [q,(i/o'),q']
*)
end
* Functor for converting a { ! Mealy } machine into an equivalent { ! } one
module ToMoore (ME: Mealy.T) : sig
include Moore.T with type state = ME.state * Valuation.Bool.t
val conv: ?init:state option -> ?clean:bool -> ME.t -> t
* Convert a Mealy automata into a automata , by turning each transition
[ q,(i / o'),q ' ] into a set of transitions [ ( q , o),i,(q',o ' ) ] for each possible output valuation [ o ] .
If [ init ] is not specified , all states [ ( q , o ) ] where [ q ] is an init state of the structure and [ o ]
an output configuration are marked as init states . Otherwise , the designated state is used .
Unreachable states are removed from the resulting automata unlesse the optional argument [ clean ]
is set to false
[q,(i/o'),q'] into a set of transitions [(q,o),i,(q',o')] for each possible output valuation [o].
If [init] is not specified, all states [(q,o)] where [q] is an init state of the Mealy structure and [o]
an output configuration are marked as init states. Otherwise, the designated state is used.
Unreachable states are removed from the resulting automata unlesse the optional argument [clean]
is set to false *)
end
(** Functor for transforming FSMs *)
module Fsm(F: Fsm.T) : sig
include Fsm.T with type state = F.state * F.Valuation.t
val defactorize: ?init:(Transition.Action.t list * state) option -> ?clean:bool -> Valuation.name list -> F.t -> t
* [ defactorize vars m ] returns an equivalent FSM [ m ' ] obtained by
- removing variable listed in [ vars ] from [ m ] ( all variables if [ vars= [ ] ] )
- introducing new states .
- the optional argument [ init ] can be used to designate the initial state and actions of the resulting
automata ( when the operation leads to several initial states )
- unreachable states are removed from the resulting automata unlesse the optional
argument [ clean ] is set to false
- removing variable listed in [vars] from [m] (all variables if [vars=[]])
- introducing new states.
- the optional argument [init] can be used to designate the initial state and actions of the resulting
automata (when the operation leads to several initial states)
- unreachable states are removed from the resulting automata unlesse the optional
argument [clean] is set to false
*)
(* Formally, if [m] is [(Q,I,O,V,R)] then [m'] is [(Q',I,O,V',R')] where *)
(* - Q' = Q x Domain(v) *)
(* - V' = V - {v} *)
(* - R' = U_{(t \in R}{defact(t)} *)
(* - defact(q,(conds,acts),q') = { (q,u),(conds\{v},acts\{v}),(q',u') *)
| u \in \Khi_v(conds ) , u ' \in \Phi_v(acts,\Khi_v(conds ) }
- \Khi_v(conds ) is the restriction of Domain(v ) to the values compatibles with conditions [ conds ]
( ex : If domain(v ) = { 0,1,2 } , \Khi_v("v<2 " ) = { 0,1 } )
(* - \Phi_v(acts, D) is the "image" of a domain D by the actions [acts] *)
(* (ex: \Phi_v("v:=v+1",{0,1}) = {1,2} *\) *)
end
| null | https://raw.githubusercontent.com/jserot/lascar/79bd11cd0d47545bccfc3a3571f37af065915c83/src/lib/conv.mli | ocaml | ********************************************************************
This source code is licensed under the license found in the
LICENSE file in the root directory of this source tree.
********************************************************************
* Functor for transforming FSMs
Formally, if [m] is [(Q,I,O,V,R)] then [m'] is [(Q',I,O,V',R')] where
- Q' = Q x Domain(v)
- V' = V - {v}
- R' = U_{(t \in R}{defact(t)}
- defact(q,(conds,acts),q') = { (q,u),(conds\{v},acts\{v}),(q',u')
- \Phi_v(acts, D) is the "image" of a domain D by the actions [acts]
(ex: \Phi_v("v:=v+1",{0,1}) = {1,2} *\) | LASCAr
Copyright ( c ) 2017 - present , . All rights reserved .
* { 2 Functors for converting various kinds of Labeled Transition Systems }
* Functor for converting a { ! Ltsa } into a { ! } ( by removing state attributes )
module ToLts (M: Ltsa.T) : sig
include Lts.T with type state = M.state and type label = M.label
val conv: M.t -> t
end
* Functor for converting a { ! } into a { ! Ltsa } ( by adding [ unit ] state attributes )
module FromLts (M: Lts.T) : sig
include Ltsa.T with type state = M.state and type label = M.label and type attr = unit
val conv: M.t -> t
end
* Functor for converting a { ! } to an equivalent { ! Dfa } ( determinisation )
module ToDfa (N : Nfa.T) : sig
include Dfa.T with type state = N.States.t and type symbol = N.symbol
* Each state of a resulting DFA is a subset of states of the NFA
val conv: N.t -> t
end
* Functor for converting a { ! } machine into an equivalent { ! } one
module ToMealy (MM: Moore.T) : sig
include Mealy.T with type state = MM.state
val conv: MM.t -> t
* Convert a automata into a Mealy automata , by turning
- turning each state [ ( q , o ) ] into [ q ]
- turning each transitions [ ( ( q , o)/i/(q',o ' ) ] into [ q,(i / o'),q ' ]
- turning each state [(q,o)] into [q]
- turning each transitions [((q,o)/i/(q',o')] into [q,(i/o'),q']
*)
end
* Functor for converting a { ! Mealy } machine into an equivalent { ! } one
module ToMoore (ME: Mealy.T) : sig
include Moore.T with type state = ME.state * Valuation.Bool.t
val conv: ?init:state option -> ?clean:bool -> ME.t -> t
* Convert a Mealy automata into a automata , by turning each transition
[ q,(i / o'),q ' ] into a set of transitions [ ( q , o),i,(q',o ' ) ] for each possible output valuation [ o ] .
If [ init ] is not specified , all states [ ( q , o ) ] where [ q ] is an init state of the structure and [ o ]
an output configuration are marked as init states . Otherwise , the designated state is used .
Unreachable states are removed from the resulting automata unlesse the optional argument [ clean ]
is set to false
[q,(i/o'),q'] into a set of transitions [(q,o),i,(q',o')] for each possible output valuation [o].
If [init] is not specified, all states [(q,o)] where [q] is an init state of the Mealy structure and [o]
an output configuration are marked as init states. Otherwise, the designated state is used.
Unreachable states are removed from the resulting automata unlesse the optional argument [clean]
is set to false *)
end
module Fsm(F: Fsm.T) : sig
include Fsm.T with type state = F.state * F.Valuation.t
val defactorize: ?init:(Transition.Action.t list * state) option -> ?clean:bool -> Valuation.name list -> F.t -> t
* [ defactorize vars m ] returns an equivalent FSM [ m ' ] obtained by
- removing variable listed in [ vars ] from [ m ] ( all variables if [ vars= [ ] ] )
- introducing new states .
- the optional argument [ init ] can be used to designate the initial state and actions of the resulting
automata ( when the operation leads to several initial states )
- unreachable states are removed from the resulting automata unlesse the optional
argument [ clean ] is set to false
- removing variable listed in [vars] from [m] (all variables if [vars=[]])
- introducing new states.
- the optional argument [init] can be used to designate the initial state and actions of the resulting
automata (when the operation leads to several initial states)
- unreachable states are removed from the resulting automata unlesse the optional
argument [clean] is set to false
*)
| u \in \Khi_v(conds ) , u ' \in \Phi_v(acts,\Khi_v(conds ) }
- \Khi_v(conds ) is the restriction of Domain(v ) to the values compatibles with conditions [ conds ]
( ex : If domain(v ) = { 0,1,2 } , \Khi_v("v<2 " ) = { 0,1 } )
end
|
dd7ed1819530d456a60b641abb823bcd7711108b63db245568ee13823837fced | david-christiansen/pie-hs | Elab.hs | # OPTIONS_GHC -fwarn - incomplete - patterns #
-- | Type checking and elaboration
module Pie.Elab (
-- * The type checker
synth, check, isType, same, sameType,
-- * The type checking monad
Elab(..),
*
Ctx, CtxEntry(..), SynthResult(..),
-- * Helpers
names, toEnv
) where
import Data.Char (isLetter, isMark)
import Data.Monoid ((<>))
import Data.List.NonEmpty (NonEmpty(..))
import qualified Data.Text as T
import Pie.AlphaEquiv
import Pie.Fresh
import qualified Pie.Normalize as Norm
import Pie.Panic
import Pie.Types
-- | Entries in a typing context (Γ).
data CtxEntry a
= HasType (Maybe Loc) a -- ^ An ordinary local variable binding,
-- with optional source location
| Claimed Loc a -- ^ A claim, which is not yet in scope but reserves
-- a name to be defined with a particular type
| Defined Loc a a -- ^ A top-level definition, with type then value
deriving Show
entryType :: CtxEntry a -> a
entryType (HasType _ t) = t
entryType (Defined _ t _) = t
entryType (Claimed _ t) = t
inScope :: CtxEntry a -> Bool
inScope (Claimed _ _) = False
inScope _ = True
-- | Typing contexts associate names with context entries.
type Ctx a = Bwd (Symbol, CtxEntry a)
-- | Extract the names in a context
names :: Ctx a -> [Symbol]
names None = []
names (ctx :> (x, _)) = x : names ctx
-- | Elaboration, AKA type checking, has access to a current
-- typechecking context, a current source location, and a renaming
-- from user-chosen names to machine-chosen names. Elaboration
-- produces a collection of information about the parts of the input
-- that were successfully checked, and either an error message or a
-- value.
newtype Elab a =
Elab
{ runElab ::
Ctx Value ->
Loc ->
[(Symbol, Symbol)] ->
([Located ElabInfo], Either ElabErr a)
}
instance Functor Elab where
fmap f (Elab act) =
Elab (\ ctx loc ren ->
let (info, out) = act ctx loc ren
in (info, fmap f out))
instance Applicative Elab where
pure x = Elab (\ _ _ _ -> ([], pure x))
Elab fun <*> Elab arg =
Elab (\ctx loc ren ->
let (funInfo, theFun) = fun ctx loc ren
(argInfo, theArg) = arg ctx loc ren
in (funInfo ++ argInfo, theFun <*> theArg))
instance Monad Elab where
return = pure
Elab act >>= f =
Elab (\ ctx loc ren ->
case act ctx loc ren of
(info, Left err) -> (info, Left err)
(info, Right v) ->
let (moreInfo, val) = runElab (f v) ctx loc ren
in (info ++ moreInfo, val))
logInfo :: ElabInfo -> Elab ()
logInfo info = Elab (\_ loc _ -> ([Located loc info], pure ()))
fresh :: Symbol -> Elab Symbol
fresh x =
do used <- names <$> getCtx
return (freshen used x)
failure :: [MessagePart Core] -> Elab a
failure msg = Elab (\ ctx loc _ -> ([], Left (ElabErr (Located loc msg))))
getCtx :: Elab (Ctx Value)
getCtx = Elab (\ ctx _ _ -> ([], pure ctx))
currentLoc :: Elab Loc
currentLoc = Elab (\_ loc _ -> ([], pure loc))
applyRenaming :: Symbol -> Elab Symbol
applyRenaming x =
Elab (\ _ loc ren ->
case lookup x ren of
Nothing ->
([],
Left
(ElabErr
(Located loc
([ MText (T.pack ("Unknown variable"))
, MVal (CVar x)
] ++
if ren /= []
then
[ MText (T.pack "in " <>
T.intercalate (T.pack ", ")
(map (symbolName . fst) (reverse ren)))
]
else []))))
Just y -> ([], pure y))
rename :: Symbol -> Symbol -> Elab a -> Elab a
rename from to (Elab act) =
Elab (\ ctx loc ren -> act ctx loc ((from, to) : ren))
withModifiedCtx :: (Ctx Value -> Ctx Value) -> Elab a -> Elab a
withModifiedCtx f (Elab act) =
Elab (\ctx loc ren -> act (f ctx) loc ren)
withCtxExtension :: Symbol -> Maybe Loc -> Value -> Elab a -> Elab a
withCtxExtension x loc t = withModifiedCtx (:> (x, HasType loc t))
withCtx :: Ctx Value -> Elab a -> Elab a
withCtx ctx = withModifiedCtx (const ctx)
-- | Convert a type-checking context Γ into a run-time environment ρ.
toEnv :: Ctx Value -> Env Value
toEnv None = None
toEnv (ctx :> (x, HasType _ t)) =
toEnv ctx :> (x, VNeu t (NVar x))
toEnv (ctx :> (x, Defined _ _ d)) =
toEnv ctx :> (x, d)
toEnv (ctx :> (_, Claimed _ _)) =
toEnv ctx
runNorm :: Norm.Norm a -> Elab a
runNorm n =
do usedNames <- names <$> getCtx
initEnv <- toEnv <$> getCtx
let val = Norm.runNorm n usedNames initEnv
return val
eval :: Core -> Elab Value
eval = runNorm . Norm.eval
evalInEnv :: Env Value -> Core -> Elab Value
evalInEnv env c =
do usedNames <- names <$> getCtx
return (Norm.runNorm (Norm.eval c) usedNames env)
doCar :: Value -> Elab Value
doCar = runNorm . Norm.doCar
doApply :: Value -> Value -> Elab Value
doApply fun arg = runNorm (Norm.doApply fun arg)
doApplyMany :: Value -> [Value] -> Elab Value
doApplyMany fun args = runNorm (Norm.doApplyMany fun args)
close :: Core -> Elab (Closure Value)
close e =
do env <- toEnv <$> getCtx
return (Closure env e)
instantiate :: Closure Value -> Symbol -> Value -> Elab Value
instantiate clos x v = runNorm (Norm.instantiate clos x v)
readBackType :: Value -> Elab Core
readBackType = runNorm . Norm.readBackType
readBack :: Normal -> Elab Core
readBack = runNorm . Norm.readBack
inExpr :: Expr -> ((Expr' Loc) -> Elab a) -> Elab a
inExpr (Expr loc e) act =
Elab (\ ctx _ ren ->
runElab (act e) ctx loc ren)
-- | Check whether an expression is a type.
isType :: Expr -> Elab Core
isType e =
do res <- inExpr e isType'
inExpr e (const (logInfo ExprIsType))
return res
isType' :: (Expr' Loc) -> Elab Core
on p. 371
isType' Atom = pure CAtom
ΣF on p. 371
isType' (Sigma ((loc, x, a) :| as) d) =
do a' <- isType a
aVal <- eval a'
x' <- fresh x
d' <- withCtxExtension x' (Just loc) aVal $
rename x x' $
case as of
ΣF-1
[] ->
isType d
-- ΣF-2
(nextA : ds) ->
isType' (Sigma (nextA :| ds) d)
return (CSigma x' a' d')
ΣF - Pair on p. 372
isType' (Pair a d) =
do x <- fresh (Symbol (T.pack "x"))
a' <- isType a
aVal <- eval a'
d' <- withCtxExtension x Nothing aVal $ isType d
return (CSigma x a' d')
FunF on p. 373
isType' (Pi ((loc, x, arg) :| args) r) =
do arg' <- isType arg
argVal <- eval arg'
x' <- fresh x
r' <- withCtxExtension x' (Just loc) argVal $
rename x x' $
case args of
-- FunF-1
[] ->
isType r
-- FunF-2
(nextArg : ds) ->
isType' (Pi (nextArg :| ds) r)
return (CPi x' arg' r')
FunF→ on p. 373
isType' (Arrow arg (t:|ts)) =
do x <- fresh (Symbol (T.pack "x"))
arg' <- isType arg
argVal <- eval arg'
r' <- withCtxExtension x Nothing argVal $
case ts of
FunF→1
[] ->
isType t
-- FunF→2
(ty : tys) ->
isType' (Arrow t (ty :| tys))
return (CPi x arg' r')
NatF on p. 374
isType' Nat = pure CNat
on p. 378
isType' (List e) = CList <$> isType e
VecF on p. 381
isType' (Vec e len) = CVec <$> isType e <*> check VNat len
EqF on p. 383
isType' (Eq x from to) =
do x' <- isType x
xVal <- eval x'
CEq x' <$> check xVal from <*> check xVal to
EitherF on p. 386
isType' (Either p s) = CEither <$> isType p <*> isType s
TrivF on p. 387
isType' Trivial = return CTrivial
AbsF on p. 388
isType' Absurd = return CAbsurd
UF on p. 389
isType' U = pure CU
El on p. 389
isType' other = check' VU other
-- | The result of type synthesis
data SynthResult =
SThe { theType :: Value -- ^ The type discovered for the expression
, theExpr :: Core -- ^ The elaborated form of the expression
}
deriving Show
toplevel e =
do (SThe tv e') <- synth e
t <- readBackType tv
val <- eval e'
eN <- readBack (NThe tv val)
return (CThe t eN)
-- Implements Γ ⊢ x lookup ⤳ X
findVar :: Symbol -> Ctx Value -> Elab SynthResult
findVar x None =
do loc <- currentLoc
failure [MText (T.pack "Unknown variable"), MVal (CVar x)]
findVar x (ctx' :> (y, info))
LookupStop on p. 370
| x == y && inScope info =
pure (SThe (entryType info) (CVar x))
LookupPop on p. 370
| otherwise = findVar x ctx'
-- | Attempt to synthesize a type for an expression.
synth :: Expr -> Elab SynthResult
synth e =
do res@(SThe tv _) <- inExpr e synth'
t <- readBackType tv
inExpr e (const (logInfo (ExprHasType t)))
return res
The on p. 367
synth' (The ty e) =
do ty' <- isType ty
tv <- eval ty'
e' <- check tv e
return (SThe tv (CThe ty' e'))
Hypothesis on p. 370
synth' (Var x) =
do ctx <- getCtx
x' <- applyRenaming x
findVar x' ctx
AtomI on p. 371
synth' (Tick sym)
| T.all (\ch -> isLetter ch || isMark ch || ch == '-') (symbolName sym) &&
T.length (symbolName sym) > 0 =
pure (SThe VAtom (CTick sym))
| otherwise =
failure [MText (T.pack "Atoms may contain only letters and hyphens")]
ΣE-1 on p. 372
synth' (Car pr) =
do SThe ty pr' <- synth pr
case ty of
VSigma x aT dT ->
return (SThe aT (CCar pr'))
other ->
do ty <- readBackType other
failure [MText (T.pack "Not a Σ: "), MVal ty]
ΣE-2 on p. 372
synth' (Cdr pr) =
do SThe ty pr' <- synth pr
case ty of
VSigma x aT dT ->
do a <- eval pr' >>= doCar
dV <- instantiate dT x a
return (SThe dV (CCdr pr'))
other ->
do ty <- readBackType other
failure [MText (T.pack "Not a Σ: "), MVal ty]
FunE-1 and FunE-2 on p. 374
synth' (App f (arg1 :| args)) =
do (SThe fT f') <- synth f
checkArgs f' fT (arg1 :| args)
where
checkArgs fun (VPi x dom ran) (arg1 :| args) =
do arg1' <- check dom arg1
arg1v <- eval arg1'
exprTy <- instantiate ran x arg1v
case args of
-- Fun-E1
[] -> return (SThe exprTy (CApp fun arg1'))
Fun - E2
(r:rs) -> checkArgs (CApp fun arg1') exprTy (r :| rs)
checkArgs _ other _ =
do t <- readBackType other
failure [MText (T.pack "Not a Π type: "), MVal t]
NatI-1 on p. 374
synth' Zero = pure (SThe VNat CZero)
NatI-2 on p. 375
synth' (Add1 n) =
do n' <- check VNat n
return (SThe VNat (CAdd1 n'))
NatI-3 and NatI-4 on p. 375
synth' (NatLit n)
-- NatI-3
| n <= 0 = synth' Zero
-- NatI-4
| otherwise =
do loc <- currentLoc
synth' (Add1 (Expr loc (NatLit (n - 1))))
NatE-1 on p. 375
synth' (WhichNat tgt base step) =
do tgt' <- check VNat tgt
SThe bt base' <- synth base
stepT <- evalInEnv (None :> (sym "base-type", bt))
(CPi (sym "x") CNat
(CVar (sym "base-type")))
step' <- check stepT step
bt' <- readBackType bt
return (SThe bt (CWhichNat tgt' bt' base' step'))
NatE-2 on p. 376
synth' (IterNat tgt base step) =
do tgt' <- check VNat tgt
SThe bt base' <- synth base
stepT <- evalInEnv
(None :> (sym "base-type", bt))
(CPi (sym "x") (CVar (sym "base-type")) (CVar (sym "base-type")))
step' <- check stepT step
bt' <- readBackType bt
return (SThe bt (CIterNat tgt' bt' base' step'))
NatE-3 on p. 376
synth' (RecNat tgt base step) =
do tgt' <- check VNat tgt
SThe bt base' <- synth base
stepT <- evalInEnv
(None :> (sym "base-type", bt))
(CPi (sym "n") CNat
(CPi (sym "x") (CVar (sym "base-type"))
(CVar (sym "base-type"))))
step' <- check stepT step
bt' <- readBackType bt
return (SThe bt (CRecNat tgt' bt' base' step'))
NatE-4 on p. 377
synth' (IndNat tgt mot base step) =
do tgt' <- check VNat tgt
mot' <- check (VPi (sym "x") VNat (Closure None CU)) mot
motV <- eval mot'
baseT <- doApply motV VZero
base' <- check baseT base
stepT <- evalInEnv (None :> (sym "mot", motV))
(CPi (sym "k") CNat
(CPi (sym "almost") (CApp (CVar (sym "mot")) (CVar (sym "k")))
(CApp (CVar (sym "mot")) (CAdd1 (CVar (sym "k"))))))
step' <- check stepT step
tgtV <- eval tgt'
ty <- doApply motV tgtV
return (SThe ty (CIndNat tgt' mot' base' step'))
ListI-2 on p. 378
synth' (ListCons e es) =
do SThe et e' <- synth e
es' <- check (VList et) es
return (SThe (VList et) (CListCons e' es'))
ListE-1 on p. 379
-- The mandatory "the" around the base in the book is represented by
the extra argument to CRecList in this implementation .
synth' (RecList tgt base step) =
do SThe lstT tgt' <- synth tgt
case lstT of
VList et ->
do (SThe bt base') <- synth base
stepT <- evalInEnv (None :> (sym "E", et) :> (sym "base-type", bt))
(CPi (sym "e") (CVar (sym "E"))
(CPi (sym "es") (CList (CVar (sym "E")))
(CPi (sym "almost") (CVar (sym "base-type"))
(CVar (sym "base-type")))))
step' <- check stepT step
bt' <- readBackType bt
return (SThe bt (CRecList tgt' bt' base' step'))
other ->
do t <- readBackType other
failure [MText (T.pack "Not a List type: "), MVal t]
ListE-2 on p. 380
synth' (IndList tgt mot base step) =
do SThe lstT tgt' <- synth tgt
case lstT of
VList elem ->
do motT <- evalInEnv (None :> (sym "E", elem))
(CPi (sym "es") (CList (CVar (sym "E"))) CU)
mot' <- check motT mot
motV <- eval mot'
baseT <- evalInEnv
(None :> (sym "mot", motV))
(CApp (CVar (sym "mot")) CListNil)
base' <- check baseT base
stepT <- evalInEnv
(None :> (sym "E", elem) :> (sym "mot", motV))
(CPi (sym "e") (CVar (sym "E"))
(CPi (sym "es") (CList (CVar (sym "E")))
(CPi (sym "so-far") (CApp (CVar (sym "mot"))
(CVar (sym "es")))
(CApp (CVar (sym "mot"))
(CListCons (CVar (sym "e"))
(CVar (sym "es")))))))
step' <- check stepT step
tgtV <- eval tgt'
ty <- doApply motV tgtV
return (SThe ty (CIndList tgt' mot' base' step'))
other ->
do t <- readBackType other
failure [MText (T.pack "Not a List type: "), MVal t]
VecE-1 on p. 381
synth' (VecHead es) =
do SThe esT es' <- synth es
case esT of
VVec elemT len ->
case len of
VAdd1 k ->
return (SThe elemT (CVecHead es'))
other ->
do len' <- readBack (NThe VNat len)
failure [ MText (T.pack "Expected a Vec with non-zero length, got a Vec with")
, MVal len'
, MText (T.pack "length.")]
other ->
do t <- readBackType other
failure [MText (T.pack "Expected a Vec, got a"), MVal t]
VecE-2 on p. 381
synth' (VecTail es) =
do SThe esT es' <- synth es
case esT of
VVec elemT len ->
case len of
VAdd1 k ->
return (SThe (VVec elemT k) (CVecTail es'))
other ->
do len' <- readBack (NThe VNat len)
failure [ MText (T.pack "Expected a Vec with non-zero length, got a Vec with")
, MVal len'
, MText (T.pack "length.")]
other ->
do t <- readBackType other
failure [MText (T.pack "Expected a Vec, got a"), MVal t]
VecE-3 on p. 382
synth' (IndVec len es mot base step) =
do len' <- check VNat len
lenv <- eval len'
SThe esT es' <- synth es
case esT of
VVec elem len'' ->
do same VNat lenv len''
motT <- evalInEnv (None :> (sym "E", elem))
(CPi (sym "k") CNat
(CPi (sym "es") (CVec (CVar (sym "E")) (CVar (sym "k")))
CU))
mot' <- check motT mot
motv <- eval mot'
baseT <- doApplyMany motv [VZero, VVecNil]
base' <- check baseT base
stepT <- evalInEnv (None :> (sym "E", elem) :> (sym "mot", motv))
(CPi (sym "k") CNat
(CPi (sym "e") (CVar (sym "E"))
(CPi (sym "es") (CVec (CVar (sym "E")) (CVar (sym "k")))
(CPi (sym "so-far") (CApp (CApp (CVar (sym "mot"))
(CVar (sym "k")))
(CVar (sym "es")))
(CApp (CApp (CVar (sym "mot"))
(CAdd1 (CVar (sym "k"))))
(CVecCons (CVar (sym "e"))
(CVar (sym "es"))))))))
step' <- check stepT step
lenv <- eval len'
esv <- eval es'
ty <- doApplyMany motv [lenv, esv]
return (SThe ty (CIndVec len' es' mot' base' step'))
other ->
do t <- readBackType other
failure [MText (T.pack "Expected a Vec, got a"), MVal t]
EqE-1 on p. 383
synth' (Replace tgt mot base) =
do SThe tgtT tgt' <- synth tgt
case tgtT of
VEq a from to ->
do motT <- evalInEnv (None :> (sym "A", a))
(CPi (sym "x") (CVar (sym "A"))
CU)
mot' <- check motT mot
motv <- eval mot'
baseT <- doApply motv from
base' <- check baseT base
ty <- doApply motv to
return (SThe ty (CReplace tgt' mot' base'))
other ->
do t <- readBackType other
failure [MText (T.pack "Not an = type: "), MVal t]
EqE-2 on p. 384
synth' (Cong tgt fun) =
do SThe tgtT tgt' <- synth tgt
SThe funT fun' <- synth fun
case tgtT of
VEq ty from to ->
case funT of
VPi x dom ran ->
do sameType ty dom
ran' <- instantiate ran x from
funV <- eval fun'
newFrom <- doApply funV from
newTo <- doApply funV to
ty' <- readBackType ran'
return (SThe (VEq ran' newFrom newTo) (CCong tgt' ty' fun'))
other ->
do t <- readBackType other
failure [MText (T.pack "Not an -> type: "), MVal t]
other ->
do t <- readBackType other
failure [MText (T.pack "Not an = type: "), MVal t]
EqE-3 on p. 384
synth' (Symm tgt) =
do SThe tgtT tgt' <- synth tgt
case tgtT of
VEq a from to ->
return (SThe (VEq a to from) (CSymm tgt'))
other ->
do t <- readBackType other
failure [MText (T.pack "Not an = type: "), MVal t]
EqE-4 on p. 385
synth' (Trans p1 p2) =
do SThe t1 p1' <- synth p1
SThe t2 p2' <- synth p2
case t1 of
VEq a from mid ->
case t2 of
VEq b mid' to ->
do sameType a b
same a mid mid'
return (SThe (VEq a from to) (CTrans p1' p2'))
other2 ->
do notEq <- readBackType other2
failure [ MText (T.pack "Not an = type: "), MVal notEq]
other1 ->
do notEq <- readBackType other1
failure [ MText (T.pack "Not an = type: "), MVal notEq]
EqE-5 on p. 385
synth' (IndEq tgt mot base) =
do SThe tgtT tgt' <- synth tgt
case tgtT of
VEq a from to ->
do let env = None :> (sym "a", a) :> (sym "from", from)
motTy = VPi (sym "x") a
(Closure env
(CPi (sym "eq") (CEq (CVar (sym "a")) (CVar (sym "from")) (CVar (sym "x")))
CU))
mot' <- check motTy mot
motv <- eval mot'
baseT <- doApplyMany motv [from, (VSame from)]
base' <- check baseT base
tgtv <- eval tgt'
ty <- doApplyMany motv [to, tgtv]
return (SThe ty (CIndEq tgt' mot' base'))
other ->
do notEq <- readBackType other
failure [ MText (T.pack "Not an = type: "), MVal notEq]
EitherE on p. 386
synth' (IndEither tgt mot l r) =
do SThe tgtT tgt' <- synth tgt
case tgtT of
VEither lt rt ->
do motT <- evalInEnv (None :> (sym "L", lt) :> (sym "R", rt))
(CPi (sym "x") (CEither (CVar (sym "L")) (CVar (sym "R")))
CU)
mot' <- check motT mot
motv <- eval mot'
lmt <- evalInEnv (None :> (sym "L", lt) :> (sym "mot", motv))
(CPi (sym "l") (CVar (sym "L"))
(CApp (CVar (sym "mot")) (CLeft (CVar (sym "l")))))
l' <- check lmt l
rmt <- evalInEnv (None :> (sym "R", rt) :> (sym "mot", motv))
(CPi (sym "r") (CVar (sym "R"))
(CApp (CVar (sym "mot")) (CRight (CVar (sym "r")))))
r' <- check rmt r
tgtv <- eval tgt'
ty <- evalInEnv (None :> (sym "tgt", tgtv) :> (sym "mot", motv))
(CApp (CVar (sym "mot")) (CVar (sym "tgt")))
return (SThe ty (CIndEither tgt' mot' l' r'))
other ->
do t <- readBackType other
failure [ MText (T.pack "Not Either:")
, MVal t
]
TrivI on p. 387
synth' Sole = return (SThe VTrivial CSole)
AbsE on p. 388
synth' (IndAbsurd tgt mot) =
do tgt' <- check VAbsurd tgt
mot' <- check VU mot
motv <- eval mot'
return (SThe motv (CIndAbsurd tgt' mot'))
UI-1 on p. 389
synth' Atom = pure (SThe VU CAtom)
UI-2 and UI-3 on p. 389
synth' (Sigma ((loc, x, a) :| as) d) =
do a' <- check VU a
aVal <- eval a'
x' <- fresh x
d' <- withCtxExtension x' (Just loc) aVal $
rename x x' $
case as of
UI-2
[] ->
check VU d
UI-3
((loc, y, nextA) : ds) ->
check' VU (Sigma ((loc, y, nextA) :| ds) d)
return (SThe VU (CSigma x a' d'))
UI-4 on p. 389
synth' (Pair a d) =
do a' <- check VU a
aVal <- eval a'
x <- fresh (sym "a")
d' <- withCtxExtension x Nothing aVal $ check VU d
return (SThe VU (CSigma x a' d'))
UI-5 and UI-6 on pp . 389 , 390
synth' (Pi ((loc, x, dom) :| doms) ran) =
do dom' <- check VU dom
domVal <- eval dom'
x' <- fresh x
ran' <- withCtxExtension x' (Just loc) domVal $
rename x x' $
case doms of
UI-5
[] ->
check VU ran
-- UI-6
(y : ds) ->
check' VU (Pi (y :| ds) ran)
return (SThe VU (CPi x' dom' ran'))
UI-7 and UI-8 on p. 390
synth' (Arrow dom (t:|ts)) =
do x <- fresh (Symbol (T.pack "x"))
dom' <- check VU dom
domVal <- eval dom'
ran' <- withCtxExtension x Nothing domVal $
case ts of
UI-7
[] ->
check VU t
UI-8
(ty : tys) ->
check' VU (Arrow t (ty :| tys))
return (SThe VU (CPi x dom' ran'))
UI-9 on p. 390
synth' Nat = pure (SThe VU CNat)
UI-10 on p. 390
synth' (List elem) =
do elem' <- check VU elem
return (SThe VU (CList elem'))
UI-11 on p. 390
synth' (Vec elem len) =
SThe VU <$> (CVec <$> check VU elem <*> check VNat len)
UI-12 on p. 390
synth' (Eq ty from to) =
do ty' <- check VU ty
tv <- eval ty'
from' <- check tv from
to' <- check tv to
return (SThe VU (CEq ty' from' to'))
UI-13 on p. 391
synth' (Either l r) =
do l' <- check VU l
r' <- check VU r
return (SThe VU (CEither l' r'))
UI-14 on p. 391
synth' Trivial = return (SThe VU CTrivial)
UI-15 on p. 391
synth' Absurd = return (SThe VU CAbsurd)
synth' other =
failure [ MText (T.pack "Can't synthesize a type for")
, MText (describeExpr other <> T.singleton '.')
, MText (T.pack "Try giving a type hint with \"the\".")
]
-- | Check an expression against a type.
--
The type is provided as a value , which has two benefits : all values
-- are assumed to be produced from well-typed expressions, so we can
-- assume that it is a type, and it ensures that there is no residual
-- computation to be performed at the top of the type.
check :: Value -> Expr -> Elab Core
check t e =
do res <- inExpr e (check' t)
tc <- readBackType t
inExpr e (const (logInfo (ExprHasType tc)))
return res
ΣI on p. 372
check' t (Cons a d) =
do (x, aT, dT) <- isSigma t
a' <- check aT a
av <- eval a'
dT' <- instantiate dT x av
d' <- check dT' d
return (CCons a' d')
FunI-1 and FunI-2 on p. 373
check' t (Lambda ((loc, x) :| xs) body) =
do (y, dom, ran) <- isPi t
z <- fresh x
withCtxExtension z (Just loc) dom $
do bodyT <- instantiate ran y (VNeu dom (NVar z))
case xs of
-- FunI-1
[] ->
do body' <- rename x z $
check bodyT body
return (CLambda z body')
FunI-2
(y : ys) ->
do body' <- rename x z $
check' bodyT (Lambda (y :| ys) body)
return (CLambda z body')
ListI-1 on p. 378
check' t ListNil =
do elem <- isList t
return CListNil
VecI-1 on p. 381
check' t VecNil =
do (elem, len) <- isVec t
case len of
VZero ->
return CVecNil
otherLen ->
do len' <- readBack (NThe VNat otherLen)
failure [ MVal CVecNil
, MText (T.pack "can be used where length 0 is expected, but here, length")
, MVal len'
, MText (T.pack "length.")]
VecI-2 on p. 381
check' t (VecCons e es) =
do (elem, len) <- isVec t
case len of
VAdd1 k ->
CVecCons <$> check elem e <*> check (VVec elem k) es
otherLen ->
do len' <- readBack (NThe VNat otherLen)
failure [ MText (T.pack "vec:: requires that the length have add1 at the top, but was used in a context that expects")
, MVal len'
, MText (T.pack "for the length.")]
EqI on p. 383
check' t (Same e) =
do (ty, from, to) <- isEq t
e' <- check ty e
v <- eval e'
same ty from v
same ty v to
return (CSame e')
EitherI-1 on p. 386
check' t (EitherLeft l) =
do (lt, _) <- isEither t
CLeft <$> check lt l
EitherI-2 on p. 386
check' t (EitherRight r) =
do (_, rt) <- isEither t
CRight <$> check rt r
check' t TODO =
do t' <- readBackType t
loc <- currentLoc
ctx <- getTODOctx
logInfo (FoundTODO ctx t')
return (CTODO loc t')
where
getTODOctx =
getCtx >>= processCtx
-- Note: this relies on the invariant that there are no local
-- binding forms that extend the context with definitions. If
" let " is added to , this needs revisiting .
processCtx (ctx :> (x, HasType loc ty)) =
(:>) <$> processCtx ctx <*> fmap (\t -> (x, loc, t)) (readBackType ty)
processCtx _ = return None
Switch , p. 367
-- This rule must come last because it uses a catch-all pattern.
check' t other =
do SThe t' other' <- synth' other
sameType t t'
return other'
-- | This checks the form of judgment Γ ⊢ e₁ ≡ e₂ : t, or in other
words , whether two expressions are the same with respect to a type .
--
-- The expressions and type are given as values because they must have
-- already been type checked.
same :: Value {- ^ The type -} -> Value -> Value -> Elab ()
same ty v1 v2 =
do c1 <- readBack (NThe ty v1)
c2 <- readBack (NThe ty v2)
case alphaEquiv c1 c2 of
Left (l, r) ->
do t <- readBackType ty
failure $ [ MVal c1
, MText (T.pack "is not the same")
, MVal t
, MText (T.pack "as")
, MVal c2
] ++
if l /= c1
then [ MText (T.pack "because")
, MVal l
, MText (T.pack "doesn't match")
, MVal r
]
else []
Right _ -> pure ()
-- | This checks the form of judgment Γ ⊢ t₁ ≡ t₂ type, or in other
words , whether two expressions are in fact the same type .
--
-- The types are provided as values because one must have already
-- checked that they are types prior to checking that they are the
-- same type.
sameType :: Value -> Value -> Elab ()
sameType v1 v2 =
do c1 <- readBackType v1
c2 <- readBackType v2
case alphaEquiv c1 c2 of
Left (l, r) ->
failure $ [ MVal c1
, MText (T.pack "is not the same type as")
, MVal c2
] ++
if l /= c1
then [ MText (T.pack "because")
, MVal l
, MText (T.pack "doesn't match")
, MVal r
]
else []
Right _ -> pure ()
-- The following helpers check that a type has a certain form. They
-- produce messages that assume they're running in checking mode.
expected :: String -> Value -> Elab a
expected what ty =
do t <- readBackType ty
failure [ MText (T.pack "The constructor works at")
, MText (T.pack what)
, MText (T.pack "but was used in a context expecting")
, MVal t
]
isPi :: Value -> Elab (Symbol, Value, Closure Value)
isPi (VPi x a b) = return (x, a, b)
isPi other = expected "a function type" other
isSigma :: Value -> Elab (Symbol, Value, Closure Value)
isSigma (VSigma x a b) = return (x, a, b)
isSigma other = expected "a function type" other
isList :: Value -> Elab Value
isList (VList e) = return e
isList other = expected "a list type" other
isVec :: Value -> Elab (Value, Value)
isVec (VVec e l) = return (e, l)
isVec other = expected "a Vec type" other
isEq :: Value -> Elab (Value, Value, Value)
isEq (VEq t from to) = return (t, from, to)
isEq other = expected "an equality type" other
isEither :: Value -> Elab (Value, Value)
isEither (VEither a b) = return (a, b)
isEither other = expected "an Either type" other
| null | https://raw.githubusercontent.com/david-christiansen/pie-hs/57a72035c23b6bf0b12492decb77690fea9dfa11/src/Pie/Elab.hs | haskell | | Type checking and elaboration
* The type checker
* The type checking monad
* Helpers
| Entries in a typing context (Γ).
^ An ordinary local variable binding,
with optional source location
^ A claim, which is not yet in scope but reserves
a name to be defined with a particular type
^ A top-level definition, with type then value
| Typing contexts associate names with context entries.
| Extract the names in a context
| Elaboration, AKA type checking, has access to a current
typechecking context, a current source location, and a renaming
from user-chosen names to machine-chosen names. Elaboration
produces a collection of information about the parts of the input
that were successfully checked, and either an error message or a
value.
| Convert a type-checking context Γ into a run-time environment ρ.
| Check whether an expression is a type.
ΣF-2
FunF-1
FunF-2
FunF→2
| The result of type synthesis
^ The type discovered for the expression
^ The elaborated form of the expression
Implements Γ ⊢ x lookup ⤳ X
| Attempt to synthesize a type for an expression.
Fun-E1
NatI-3
NatI-4
The mandatory "the" around the base in the book is represented by
UI-6
| Check an expression against a type.
are assumed to be produced from well-typed expressions, so we can
assume that it is a type, and it ensures that there is no residual
computation to be performed at the top of the type.
FunI-1
Note: this relies on the invariant that there are no local
binding forms that extend the context with definitions. If
This rule must come last because it uses a catch-all pattern.
| This checks the form of judgment Γ ⊢ e₁ ≡ e₂ : t, or in other
The expressions and type are given as values because they must have
already been type checked.
^ The type
| This checks the form of judgment Γ ⊢ t₁ ≡ t₂ type, or in other
The types are provided as values because one must have already
checked that they are types prior to checking that they are the
same type.
The following helpers check that a type has a certain form. They
produce messages that assume they're running in checking mode. | # OPTIONS_GHC -fwarn - incomplete - patterns #
module Pie.Elab (
synth, check, isType, same, sameType,
Elab(..),
*
Ctx, CtxEntry(..), SynthResult(..),
names, toEnv
) where
import Data.Char (isLetter, isMark)
import Data.Monoid ((<>))
import Data.List.NonEmpty (NonEmpty(..))
import qualified Data.Text as T
import Pie.AlphaEquiv
import Pie.Fresh
import qualified Pie.Normalize as Norm
import Pie.Panic
import Pie.Types
data CtxEntry a
deriving Show
entryType :: CtxEntry a -> a
entryType (HasType _ t) = t
entryType (Defined _ t _) = t
entryType (Claimed _ t) = t
inScope :: CtxEntry a -> Bool
inScope (Claimed _ _) = False
inScope _ = True
type Ctx a = Bwd (Symbol, CtxEntry a)
names :: Ctx a -> [Symbol]
names None = []
names (ctx :> (x, _)) = x : names ctx
newtype Elab a =
Elab
{ runElab ::
Ctx Value ->
Loc ->
[(Symbol, Symbol)] ->
([Located ElabInfo], Either ElabErr a)
}
instance Functor Elab where
fmap f (Elab act) =
Elab (\ ctx loc ren ->
let (info, out) = act ctx loc ren
in (info, fmap f out))
instance Applicative Elab where
pure x = Elab (\ _ _ _ -> ([], pure x))
Elab fun <*> Elab arg =
Elab (\ctx loc ren ->
let (funInfo, theFun) = fun ctx loc ren
(argInfo, theArg) = arg ctx loc ren
in (funInfo ++ argInfo, theFun <*> theArg))
instance Monad Elab where
return = pure
Elab act >>= f =
Elab (\ ctx loc ren ->
case act ctx loc ren of
(info, Left err) -> (info, Left err)
(info, Right v) ->
let (moreInfo, val) = runElab (f v) ctx loc ren
in (info ++ moreInfo, val))
logInfo :: ElabInfo -> Elab ()
logInfo info = Elab (\_ loc _ -> ([Located loc info], pure ()))
fresh :: Symbol -> Elab Symbol
fresh x =
do used <- names <$> getCtx
return (freshen used x)
failure :: [MessagePart Core] -> Elab a
failure msg = Elab (\ ctx loc _ -> ([], Left (ElabErr (Located loc msg))))
getCtx :: Elab (Ctx Value)
getCtx = Elab (\ ctx _ _ -> ([], pure ctx))
currentLoc :: Elab Loc
currentLoc = Elab (\_ loc _ -> ([], pure loc))
applyRenaming :: Symbol -> Elab Symbol
applyRenaming x =
Elab (\ _ loc ren ->
case lookup x ren of
Nothing ->
([],
Left
(ElabErr
(Located loc
([ MText (T.pack ("Unknown variable"))
, MVal (CVar x)
] ++
if ren /= []
then
[ MText (T.pack "in " <>
T.intercalate (T.pack ", ")
(map (symbolName . fst) (reverse ren)))
]
else []))))
Just y -> ([], pure y))
rename :: Symbol -> Symbol -> Elab a -> Elab a
rename from to (Elab act) =
Elab (\ ctx loc ren -> act ctx loc ((from, to) : ren))
withModifiedCtx :: (Ctx Value -> Ctx Value) -> Elab a -> Elab a
withModifiedCtx f (Elab act) =
Elab (\ctx loc ren -> act (f ctx) loc ren)
withCtxExtension :: Symbol -> Maybe Loc -> Value -> Elab a -> Elab a
withCtxExtension x loc t = withModifiedCtx (:> (x, HasType loc t))
withCtx :: Ctx Value -> Elab a -> Elab a
withCtx ctx = withModifiedCtx (const ctx)
toEnv :: Ctx Value -> Env Value
toEnv None = None
toEnv (ctx :> (x, HasType _ t)) =
toEnv ctx :> (x, VNeu t (NVar x))
toEnv (ctx :> (x, Defined _ _ d)) =
toEnv ctx :> (x, d)
toEnv (ctx :> (_, Claimed _ _)) =
toEnv ctx
runNorm :: Norm.Norm a -> Elab a
runNorm n =
do usedNames <- names <$> getCtx
initEnv <- toEnv <$> getCtx
let val = Norm.runNorm n usedNames initEnv
return val
eval :: Core -> Elab Value
eval = runNorm . Norm.eval
evalInEnv :: Env Value -> Core -> Elab Value
evalInEnv env c =
do usedNames <- names <$> getCtx
return (Norm.runNorm (Norm.eval c) usedNames env)
doCar :: Value -> Elab Value
doCar = runNorm . Norm.doCar
doApply :: Value -> Value -> Elab Value
doApply fun arg = runNorm (Norm.doApply fun arg)
doApplyMany :: Value -> [Value] -> Elab Value
doApplyMany fun args = runNorm (Norm.doApplyMany fun args)
close :: Core -> Elab (Closure Value)
close e =
do env <- toEnv <$> getCtx
return (Closure env e)
instantiate :: Closure Value -> Symbol -> Value -> Elab Value
instantiate clos x v = runNorm (Norm.instantiate clos x v)
readBackType :: Value -> Elab Core
readBackType = runNorm . Norm.readBackType
readBack :: Normal -> Elab Core
readBack = runNorm . Norm.readBack
inExpr :: Expr -> ((Expr' Loc) -> Elab a) -> Elab a
inExpr (Expr loc e) act =
Elab (\ ctx _ ren ->
runElab (act e) ctx loc ren)
isType :: Expr -> Elab Core
isType e =
do res <- inExpr e isType'
inExpr e (const (logInfo ExprIsType))
return res
isType' :: (Expr' Loc) -> Elab Core
on p. 371
isType' Atom = pure CAtom
ΣF on p. 371
isType' (Sigma ((loc, x, a) :| as) d) =
do a' <- isType a
aVal <- eval a'
x' <- fresh x
d' <- withCtxExtension x' (Just loc) aVal $
rename x x' $
case as of
ΣF-1
[] ->
isType d
(nextA : ds) ->
isType' (Sigma (nextA :| ds) d)
return (CSigma x' a' d')
ΣF - Pair on p. 372
isType' (Pair a d) =
do x <- fresh (Symbol (T.pack "x"))
a' <- isType a
aVal <- eval a'
d' <- withCtxExtension x Nothing aVal $ isType d
return (CSigma x a' d')
FunF on p. 373
isType' (Pi ((loc, x, arg) :| args) r) =
do arg' <- isType arg
argVal <- eval arg'
x' <- fresh x
r' <- withCtxExtension x' (Just loc) argVal $
rename x x' $
case args of
[] ->
isType r
(nextArg : ds) ->
isType' (Pi (nextArg :| ds) r)
return (CPi x' arg' r')
FunF→ on p. 373
isType' (Arrow arg (t:|ts)) =
do x <- fresh (Symbol (T.pack "x"))
arg' <- isType arg
argVal <- eval arg'
r' <- withCtxExtension x Nothing argVal $
case ts of
FunF→1
[] ->
isType t
(ty : tys) ->
isType' (Arrow t (ty :| tys))
return (CPi x arg' r')
NatF on p. 374
isType' Nat = pure CNat
on p. 378
isType' (List e) = CList <$> isType e
VecF on p. 381
isType' (Vec e len) = CVec <$> isType e <*> check VNat len
EqF on p. 383
isType' (Eq x from to) =
do x' <- isType x
xVal <- eval x'
CEq x' <$> check xVal from <*> check xVal to
EitherF on p. 386
isType' (Either p s) = CEither <$> isType p <*> isType s
TrivF on p. 387
isType' Trivial = return CTrivial
AbsF on p. 388
isType' Absurd = return CAbsurd
UF on p. 389
isType' U = pure CU
El on p. 389
isType' other = check' VU other
data SynthResult =
}
deriving Show
toplevel e =
do (SThe tv e') <- synth e
t <- readBackType tv
val <- eval e'
eN <- readBack (NThe tv val)
return (CThe t eN)
findVar :: Symbol -> Ctx Value -> Elab SynthResult
findVar x None =
do loc <- currentLoc
failure [MText (T.pack "Unknown variable"), MVal (CVar x)]
findVar x (ctx' :> (y, info))
LookupStop on p. 370
| x == y && inScope info =
pure (SThe (entryType info) (CVar x))
LookupPop on p. 370
| otherwise = findVar x ctx'
synth :: Expr -> Elab SynthResult
synth e =
do res@(SThe tv _) <- inExpr e synth'
t <- readBackType tv
inExpr e (const (logInfo (ExprHasType t)))
return res
The on p. 367
synth' (The ty e) =
do ty' <- isType ty
tv <- eval ty'
e' <- check tv e
return (SThe tv (CThe ty' e'))
Hypothesis on p. 370
synth' (Var x) =
do ctx <- getCtx
x' <- applyRenaming x
findVar x' ctx
AtomI on p. 371
synth' (Tick sym)
| T.all (\ch -> isLetter ch || isMark ch || ch == '-') (symbolName sym) &&
T.length (symbolName sym) > 0 =
pure (SThe VAtom (CTick sym))
| otherwise =
failure [MText (T.pack "Atoms may contain only letters and hyphens")]
ΣE-1 on p. 372
synth' (Car pr) =
do SThe ty pr' <- synth pr
case ty of
VSigma x aT dT ->
return (SThe aT (CCar pr'))
other ->
do ty <- readBackType other
failure [MText (T.pack "Not a Σ: "), MVal ty]
ΣE-2 on p. 372
synth' (Cdr pr) =
do SThe ty pr' <- synth pr
case ty of
VSigma x aT dT ->
do a <- eval pr' >>= doCar
dV <- instantiate dT x a
return (SThe dV (CCdr pr'))
other ->
do ty <- readBackType other
failure [MText (T.pack "Not a Σ: "), MVal ty]
FunE-1 and FunE-2 on p. 374
synth' (App f (arg1 :| args)) =
do (SThe fT f') <- synth f
checkArgs f' fT (arg1 :| args)
where
checkArgs fun (VPi x dom ran) (arg1 :| args) =
do arg1' <- check dom arg1
arg1v <- eval arg1'
exprTy <- instantiate ran x arg1v
case args of
[] -> return (SThe exprTy (CApp fun arg1'))
Fun - E2
(r:rs) -> checkArgs (CApp fun arg1') exprTy (r :| rs)
checkArgs _ other _ =
do t <- readBackType other
failure [MText (T.pack "Not a Π type: "), MVal t]
NatI-1 on p. 374
synth' Zero = pure (SThe VNat CZero)
NatI-2 on p. 375
synth' (Add1 n) =
do n' <- check VNat n
return (SThe VNat (CAdd1 n'))
NatI-3 and NatI-4 on p. 375
synth' (NatLit n)
| n <= 0 = synth' Zero
| otherwise =
do loc <- currentLoc
synth' (Add1 (Expr loc (NatLit (n - 1))))
NatE-1 on p. 375
synth' (WhichNat tgt base step) =
do tgt' <- check VNat tgt
SThe bt base' <- synth base
stepT <- evalInEnv (None :> (sym "base-type", bt))
(CPi (sym "x") CNat
(CVar (sym "base-type")))
step' <- check stepT step
bt' <- readBackType bt
return (SThe bt (CWhichNat tgt' bt' base' step'))
NatE-2 on p. 376
synth' (IterNat tgt base step) =
do tgt' <- check VNat tgt
SThe bt base' <- synth base
stepT <- evalInEnv
(None :> (sym "base-type", bt))
(CPi (sym "x") (CVar (sym "base-type")) (CVar (sym "base-type")))
step' <- check stepT step
bt' <- readBackType bt
return (SThe bt (CIterNat tgt' bt' base' step'))
NatE-3 on p. 376
synth' (RecNat tgt base step) =
do tgt' <- check VNat tgt
SThe bt base' <- synth base
stepT <- evalInEnv
(None :> (sym "base-type", bt))
(CPi (sym "n") CNat
(CPi (sym "x") (CVar (sym "base-type"))
(CVar (sym "base-type"))))
step' <- check stepT step
bt' <- readBackType bt
return (SThe bt (CRecNat tgt' bt' base' step'))
NatE-4 on p. 377
synth' (IndNat tgt mot base step) =
do tgt' <- check VNat tgt
mot' <- check (VPi (sym "x") VNat (Closure None CU)) mot
motV <- eval mot'
baseT <- doApply motV VZero
base' <- check baseT base
stepT <- evalInEnv (None :> (sym "mot", motV))
(CPi (sym "k") CNat
(CPi (sym "almost") (CApp (CVar (sym "mot")) (CVar (sym "k")))
(CApp (CVar (sym "mot")) (CAdd1 (CVar (sym "k"))))))
step' <- check stepT step
tgtV <- eval tgt'
ty <- doApply motV tgtV
return (SThe ty (CIndNat tgt' mot' base' step'))
ListI-2 on p. 378
synth' (ListCons e es) =
do SThe et e' <- synth e
es' <- check (VList et) es
return (SThe (VList et) (CListCons e' es'))
ListE-1 on p. 379
the extra argument to CRecList in this implementation .
synth' (RecList tgt base step) =
do SThe lstT tgt' <- synth tgt
case lstT of
VList et ->
do (SThe bt base') <- synth base
stepT <- evalInEnv (None :> (sym "E", et) :> (sym "base-type", bt))
(CPi (sym "e") (CVar (sym "E"))
(CPi (sym "es") (CList (CVar (sym "E")))
(CPi (sym "almost") (CVar (sym "base-type"))
(CVar (sym "base-type")))))
step' <- check stepT step
bt' <- readBackType bt
return (SThe bt (CRecList tgt' bt' base' step'))
other ->
do t <- readBackType other
failure [MText (T.pack "Not a List type: "), MVal t]
ListE-2 on p. 380
synth' (IndList tgt mot base step) =
do SThe lstT tgt' <- synth tgt
case lstT of
VList elem ->
do motT <- evalInEnv (None :> (sym "E", elem))
(CPi (sym "es") (CList (CVar (sym "E"))) CU)
mot' <- check motT mot
motV <- eval mot'
baseT <- evalInEnv
(None :> (sym "mot", motV))
(CApp (CVar (sym "mot")) CListNil)
base' <- check baseT base
stepT <- evalInEnv
(None :> (sym "E", elem) :> (sym "mot", motV))
(CPi (sym "e") (CVar (sym "E"))
(CPi (sym "es") (CList (CVar (sym "E")))
(CPi (sym "so-far") (CApp (CVar (sym "mot"))
(CVar (sym "es")))
(CApp (CVar (sym "mot"))
(CListCons (CVar (sym "e"))
(CVar (sym "es")))))))
step' <- check stepT step
tgtV <- eval tgt'
ty <- doApply motV tgtV
return (SThe ty (CIndList tgt' mot' base' step'))
other ->
do t <- readBackType other
failure [MText (T.pack "Not a List type: "), MVal t]
VecE-1 on p. 381
synth' (VecHead es) =
do SThe esT es' <- synth es
case esT of
VVec elemT len ->
case len of
VAdd1 k ->
return (SThe elemT (CVecHead es'))
other ->
do len' <- readBack (NThe VNat len)
failure [ MText (T.pack "Expected a Vec with non-zero length, got a Vec with")
, MVal len'
, MText (T.pack "length.")]
other ->
do t <- readBackType other
failure [MText (T.pack "Expected a Vec, got a"), MVal t]
VecE-2 on p. 381
synth' (VecTail es) =
do SThe esT es' <- synth es
case esT of
VVec elemT len ->
case len of
VAdd1 k ->
return (SThe (VVec elemT k) (CVecTail es'))
other ->
do len' <- readBack (NThe VNat len)
failure [ MText (T.pack "Expected a Vec with non-zero length, got a Vec with")
, MVal len'
, MText (T.pack "length.")]
other ->
do t <- readBackType other
failure [MText (T.pack "Expected a Vec, got a"), MVal t]
VecE-3 on p. 382
synth' (IndVec len es mot base step) =
do len' <- check VNat len
lenv <- eval len'
SThe esT es' <- synth es
case esT of
VVec elem len'' ->
do same VNat lenv len''
motT <- evalInEnv (None :> (sym "E", elem))
(CPi (sym "k") CNat
(CPi (sym "es") (CVec (CVar (sym "E")) (CVar (sym "k")))
CU))
mot' <- check motT mot
motv <- eval mot'
baseT <- doApplyMany motv [VZero, VVecNil]
base' <- check baseT base
stepT <- evalInEnv (None :> (sym "E", elem) :> (sym "mot", motv))
(CPi (sym "k") CNat
(CPi (sym "e") (CVar (sym "E"))
(CPi (sym "es") (CVec (CVar (sym "E")) (CVar (sym "k")))
(CPi (sym "so-far") (CApp (CApp (CVar (sym "mot"))
(CVar (sym "k")))
(CVar (sym "es")))
(CApp (CApp (CVar (sym "mot"))
(CAdd1 (CVar (sym "k"))))
(CVecCons (CVar (sym "e"))
(CVar (sym "es"))))))))
step' <- check stepT step
lenv <- eval len'
esv <- eval es'
ty <- doApplyMany motv [lenv, esv]
return (SThe ty (CIndVec len' es' mot' base' step'))
other ->
do t <- readBackType other
failure [MText (T.pack "Expected a Vec, got a"), MVal t]
EqE-1 on p. 383
synth' (Replace tgt mot base) =
do SThe tgtT tgt' <- synth tgt
case tgtT of
VEq a from to ->
do motT <- evalInEnv (None :> (sym "A", a))
(CPi (sym "x") (CVar (sym "A"))
CU)
mot' <- check motT mot
motv <- eval mot'
baseT <- doApply motv from
base' <- check baseT base
ty <- doApply motv to
return (SThe ty (CReplace tgt' mot' base'))
other ->
do t <- readBackType other
failure [MText (T.pack "Not an = type: "), MVal t]
EqE-2 on p. 384
synth' (Cong tgt fun) =
do SThe tgtT tgt' <- synth tgt
SThe funT fun' <- synth fun
case tgtT of
VEq ty from to ->
case funT of
VPi x dom ran ->
do sameType ty dom
ran' <- instantiate ran x from
funV <- eval fun'
newFrom <- doApply funV from
newTo <- doApply funV to
ty' <- readBackType ran'
return (SThe (VEq ran' newFrom newTo) (CCong tgt' ty' fun'))
other ->
do t <- readBackType other
failure [MText (T.pack "Not an -> type: "), MVal t]
other ->
do t <- readBackType other
failure [MText (T.pack "Not an = type: "), MVal t]
EqE-3 on p. 384
synth' (Symm tgt) =
do SThe tgtT tgt' <- synth tgt
case tgtT of
VEq a from to ->
return (SThe (VEq a to from) (CSymm tgt'))
other ->
do t <- readBackType other
failure [MText (T.pack "Not an = type: "), MVal t]
EqE-4 on p. 385
synth' (Trans p1 p2) =
do SThe t1 p1' <- synth p1
SThe t2 p2' <- synth p2
case t1 of
VEq a from mid ->
case t2 of
VEq b mid' to ->
do sameType a b
same a mid mid'
return (SThe (VEq a from to) (CTrans p1' p2'))
other2 ->
do notEq <- readBackType other2
failure [ MText (T.pack "Not an = type: "), MVal notEq]
other1 ->
do notEq <- readBackType other1
failure [ MText (T.pack "Not an = type: "), MVal notEq]
EqE-5 on p. 385
synth' (IndEq tgt mot base) =
do SThe tgtT tgt' <- synth tgt
case tgtT of
VEq a from to ->
do let env = None :> (sym "a", a) :> (sym "from", from)
motTy = VPi (sym "x") a
(Closure env
(CPi (sym "eq") (CEq (CVar (sym "a")) (CVar (sym "from")) (CVar (sym "x")))
CU))
mot' <- check motTy mot
motv <- eval mot'
baseT <- doApplyMany motv [from, (VSame from)]
base' <- check baseT base
tgtv <- eval tgt'
ty <- doApplyMany motv [to, tgtv]
return (SThe ty (CIndEq tgt' mot' base'))
other ->
do notEq <- readBackType other
failure [ MText (T.pack "Not an = type: "), MVal notEq]
EitherE on p. 386
synth' (IndEither tgt mot l r) =
do SThe tgtT tgt' <- synth tgt
case tgtT of
VEither lt rt ->
do motT <- evalInEnv (None :> (sym "L", lt) :> (sym "R", rt))
(CPi (sym "x") (CEither (CVar (sym "L")) (CVar (sym "R")))
CU)
mot' <- check motT mot
motv <- eval mot'
lmt <- evalInEnv (None :> (sym "L", lt) :> (sym "mot", motv))
(CPi (sym "l") (CVar (sym "L"))
(CApp (CVar (sym "mot")) (CLeft (CVar (sym "l")))))
l' <- check lmt l
rmt <- evalInEnv (None :> (sym "R", rt) :> (sym "mot", motv))
(CPi (sym "r") (CVar (sym "R"))
(CApp (CVar (sym "mot")) (CRight (CVar (sym "r")))))
r' <- check rmt r
tgtv <- eval tgt'
ty <- evalInEnv (None :> (sym "tgt", tgtv) :> (sym "mot", motv))
(CApp (CVar (sym "mot")) (CVar (sym "tgt")))
return (SThe ty (CIndEither tgt' mot' l' r'))
other ->
do t <- readBackType other
failure [ MText (T.pack "Not Either:")
, MVal t
]
TrivI on p. 387
synth' Sole = return (SThe VTrivial CSole)
AbsE on p. 388
synth' (IndAbsurd tgt mot) =
do tgt' <- check VAbsurd tgt
mot' <- check VU mot
motv <- eval mot'
return (SThe motv (CIndAbsurd tgt' mot'))
UI-1 on p. 389
synth' Atom = pure (SThe VU CAtom)
UI-2 and UI-3 on p. 389
synth' (Sigma ((loc, x, a) :| as) d) =
do a' <- check VU a
aVal <- eval a'
x' <- fresh x
d' <- withCtxExtension x' (Just loc) aVal $
rename x x' $
case as of
UI-2
[] ->
check VU d
UI-3
((loc, y, nextA) : ds) ->
check' VU (Sigma ((loc, y, nextA) :| ds) d)
return (SThe VU (CSigma x a' d'))
UI-4 on p. 389
synth' (Pair a d) =
do a' <- check VU a
aVal <- eval a'
x <- fresh (sym "a")
d' <- withCtxExtension x Nothing aVal $ check VU d
return (SThe VU (CSigma x a' d'))
UI-5 and UI-6 on pp . 389 , 390
synth' (Pi ((loc, x, dom) :| doms) ran) =
do dom' <- check VU dom
domVal <- eval dom'
x' <- fresh x
ran' <- withCtxExtension x' (Just loc) domVal $
rename x x' $
case doms of
UI-5
[] ->
check VU ran
(y : ds) ->
check' VU (Pi (y :| ds) ran)
return (SThe VU (CPi x' dom' ran'))
UI-7 and UI-8 on p. 390
synth' (Arrow dom (t:|ts)) =
do x <- fresh (Symbol (T.pack "x"))
dom' <- check VU dom
domVal <- eval dom'
ran' <- withCtxExtension x Nothing domVal $
case ts of
UI-7
[] ->
check VU t
UI-8
(ty : tys) ->
check' VU (Arrow t (ty :| tys))
return (SThe VU (CPi x dom' ran'))
UI-9 on p. 390
synth' Nat = pure (SThe VU CNat)
UI-10 on p. 390
synth' (List elem) =
do elem' <- check VU elem
return (SThe VU (CList elem'))
UI-11 on p. 390
synth' (Vec elem len) =
SThe VU <$> (CVec <$> check VU elem <*> check VNat len)
UI-12 on p. 390
synth' (Eq ty from to) =
do ty' <- check VU ty
tv <- eval ty'
from' <- check tv from
to' <- check tv to
return (SThe VU (CEq ty' from' to'))
UI-13 on p. 391
synth' (Either l r) =
do l' <- check VU l
r' <- check VU r
return (SThe VU (CEither l' r'))
UI-14 on p. 391
synth' Trivial = return (SThe VU CTrivial)
UI-15 on p. 391
synth' Absurd = return (SThe VU CAbsurd)
synth' other =
failure [ MText (T.pack "Can't synthesize a type for")
, MText (describeExpr other <> T.singleton '.')
, MText (T.pack "Try giving a type hint with \"the\".")
]
The type is provided as a value , which has two benefits : all values
check :: Value -> Expr -> Elab Core
check t e =
do res <- inExpr e (check' t)
tc <- readBackType t
inExpr e (const (logInfo (ExprHasType tc)))
return res
ΣI on p. 372
check' t (Cons a d) =
do (x, aT, dT) <- isSigma t
a' <- check aT a
av <- eval a'
dT' <- instantiate dT x av
d' <- check dT' d
return (CCons a' d')
FunI-1 and FunI-2 on p. 373
check' t (Lambda ((loc, x) :| xs) body) =
do (y, dom, ran) <- isPi t
z <- fresh x
withCtxExtension z (Just loc) dom $
do bodyT <- instantiate ran y (VNeu dom (NVar z))
case xs of
[] ->
do body' <- rename x z $
check bodyT body
return (CLambda z body')
FunI-2
(y : ys) ->
do body' <- rename x z $
check' bodyT (Lambda (y :| ys) body)
return (CLambda z body')
ListI-1 on p. 378
check' t ListNil =
do elem <- isList t
return CListNil
VecI-1 on p. 381
check' t VecNil =
do (elem, len) <- isVec t
case len of
VZero ->
return CVecNil
otherLen ->
do len' <- readBack (NThe VNat otherLen)
failure [ MVal CVecNil
, MText (T.pack "can be used where length 0 is expected, but here, length")
, MVal len'
, MText (T.pack "length.")]
VecI-2 on p. 381
check' t (VecCons e es) =
do (elem, len) <- isVec t
case len of
VAdd1 k ->
CVecCons <$> check elem e <*> check (VVec elem k) es
otherLen ->
do len' <- readBack (NThe VNat otherLen)
failure [ MText (T.pack "vec:: requires that the length have add1 at the top, but was used in a context that expects")
, MVal len'
, MText (T.pack "for the length.")]
EqI on p. 383
check' t (Same e) =
do (ty, from, to) <- isEq t
e' <- check ty e
v <- eval e'
same ty from v
same ty v to
return (CSame e')
EitherI-1 on p. 386
check' t (EitherLeft l) =
do (lt, _) <- isEither t
CLeft <$> check lt l
EitherI-2 on p. 386
check' t (EitherRight r) =
do (_, rt) <- isEither t
CRight <$> check rt r
check' t TODO =
do t' <- readBackType t
loc <- currentLoc
ctx <- getTODOctx
logInfo (FoundTODO ctx t')
return (CTODO loc t')
where
getTODOctx =
getCtx >>= processCtx
" let " is added to , this needs revisiting .
processCtx (ctx :> (x, HasType loc ty)) =
(:>) <$> processCtx ctx <*> fmap (\t -> (x, loc, t)) (readBackType ty)
processCtx _ = return None
Switch , p. 367
check' t other =
do SThe t' other' <- synth' other
sameType t t'
return other'
words , whether two expressions are the same with respect to a type .
same ty v1 v2 =
do c1 <- readBack (NThe ty v1)
c2 <- readBack (NThe ty v2)
case alphaEquiv c1 c2 of
Left (l, r) ->
do t <- readBackType ty
failure $ [ MVal c1
, MText (T.pack "is not the same")
, MVal t
, MText (T.pack "as")
, MVal c2
] ++
if l /= c1
then [ MText (T.pack "because")
, MVal l
, MText (T.pack "doesn't match")
, MVal r
]
else []
Right _ -> pure ()
words , whether two expressions are in fact the same type .
sameType :: Value -> Value -> Elab ()
sameType v1 v2 =
do c1 <- readBackType v1
c2 <- readBackType v2
case alphaEquiv c1 c2 of
Left (l, r) ->
failure $ [ MVal c1
, MText (T.pack "is not the same type as")
, MVal c2
] ++
if l /= c1
then [ MText (T.pack "because")
, MVal l
, MText (T.pack "doesn't match")
, MVal r
]
else []
Right _ -> pure ()
expected :: String -> Value -> Elab a
expected what ty =
do t <- readBackType ty
failure [ MText (T.pack "The constructor works at")
, MText (T.pack what)
, MText (T.pack "but was used in a context expecting")
, MVal t
]
isPi :: Value -> Elab (Symbol, Value, Closure Value)
isPi (VPi x a b) = return (x, a, b)
isPi other = expected "a function type" other
isSigma :: Value -> Elab (Symbol, Value, Closure Value)
isSigma (VSigma x a b) = return (x, a, b)
isSigma other = expected "a function type" other
isList :: Value -> Elab Value
isList (VList e) = return e
isList other = expected "a list type" other
isVec :: Value -> Elab (Value, Value)
isVec (VVec e l) = return (e, l)
isVec other = expected "a Vec type" other
isEq :: Value -> Elab (Value, Value, Value)
isEq (VEq t from to) = return (t, from, to)
isEq other = expected "an equality type" other
isEither :: Value -> Elab (Value, Value)
isEither (VEither a b) = return (a, b)
isEither other = expected "an Either type" other
|
3fc7fc550f902965b47008605d8ee689d6403c0cd505fa1532638165201d444e | 2600hz/kazoo | kz_hooks_listener.erl | %%%-----------------------------------------------------------------------------
( C ) 2013 - 2020 , 2600Hz
%%% @doc Listens for a list of events and gproc-sends them out to folks who
%%% want them
%%%
@author
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 /.
%%%
%%% @end
%%%-----------------------------------------------------------------------------
-module(kz_hooks_listener).
-behaviour(gen_listener).
-export([start_link/0]).
-export([init/1
,handle_call/3
,handle_cast/2
,handle_info/2
,handle_event/2
,terminate/2
,code_change/3
]).
-include("kazoo_events.hrl").
-include("kz_hooks.hrl").
-define(SERVER, ?MODULE).
Three main call events
-define(ALL_EVENTS, [<<"CHANNEL_CREATE">>
,<<"CHANNEL_ANSWER">>
,<<"CHANNEL_DESTROY">>
,<<"CHANNEL_BRIDGE">>
,<<"CHANNEL_UNBRIDGE">>
,<<"CHANNEL_DISCONNECTED">>
,<<"CHANNEL_CONNECTED">>
]).
-define(CALL_BINDING(Events), {'call', [{'restrict_to', Events}
,'federate'
]}).
-define(BINDINGS, []).
-define(RESPONDERS, [{{'kz_hooks_util', 'handle_call_event'}
,[{<<"call_event">>, <<"*">>}]
}
]).
-define(QUEUE_NAME, <<>>).
-define(QUEUE_OPTIONS, []).
-define(CONSUME_OPTIONS, []).
-record(state, {call_events = [] :: kz_term:ne_binaries()}).
-type state() :: #state{}.
%%%=============================================================================
%%% API
%%%=============================================================================
%%------------------------------------------------------------------------------
%% @doc Starts the server.
%% @end
%%------------------------------------------------------------------------------
-spec start_link() -> kz_types:startlink_ret().
start_link() ->
gen_listener:start_link({'local', ?SERVER}
,?MODULE
,[{'bindings', ?BINDINGS}
,{'responders', ?RESPONDERS}
,{'queue_name', ?QUEUE_NAME}
,{'queue_options', ?QUEUE_OPTIONS}
,{'consume_options', ?CONSUME_OPTIONS}
]
,[]
).
%%%=============================================================================
%%% gen_server callbacks
%%%=============================================================================
%%------------------------------------------------------------------------------
%% @doc Initializes the server.
%% @end
%%------------------------------------------------------------------------------
-spec init([]) -> {'ok', state()}.
init([]) ->
kz_log:put_callid(?MODULE),
lager:debug("started ~s", [?MODULE]),
kapi_call:declare_exchanges(),
{'ok', #state{}}.
%%------------------------------------------------------------------------------
%% @doc Handling call messages.
%% @end
%%------------------------------------------------------------------------------
-spec handle_call(any(), kz_term:pid_ref(), state()) -> kz_types:handle_call_ret_state(state()).
handle_call(_Request, _From, State) ->
{'reply', {'error', 'not_implemented'}, State}.
%%------------------------------------------------------------------------------
%% @doc Handling cast messages.
%% @end
%%------------------------------------------------------------------------------
-spec handle_cast(any(), state()) -> kz_types:handle_cast_ret_state(state()).
handle_cast({'maybe_add_binding', 'all'}, #state{call_events=Events}=State) ->
case [E || E <- ?ALL_EVENTS, not lists:member(E, Events)] of
[] -> {'noreply', State};
Es ->
lager:debug("adding bindings for ~p", [Es]),
gen_listener:add_binding(self(), ?CALL_BINDING(Es)),
{'noreply', State#state{call_events=Es ++ Events}}
end;
handle_cast({'maybe_add_binding', Event}, #state{call_events=Events}=State) ->
case lists:member(Event, Events) of
'true' -> {'noreply', State};
'false' ->
lager:debug("adding bindings for ~s", [Event]),
gen_listener:add_binding(self(), ?CALL_BINDING([Event])),
{'noreply', State#state{call_events=[Event | Events]}}
end;
handle_cast({'maybe_remove_binding', 'all'}, #state{call_events=Events}=State) ->
case [E || E <- ?ALL_EVENTS, lists:member(E, Events)] of
[] -> {'noreply', State};
Es ->
lager:debug("removing bindings for ~p", [Es]),
gen_listener:rm_binding(self(), ?CALL_BINDING(Es)),
{'noreply', State#state{call_events=Events -- Es}}
end;
handle_cast({'maybe_remove_binding', Event}, #state{call_events=Events}=State) ->
case lists:member(Event, Events) of
'true' -> {'noreply', State};
'false' ->
lager:debug("removing bindings for ~s", [Event]),
gen_listener:rm_binding(self(), ?CALL_BINDING([Event])),
{'noreply', State#state{call_events=lists:delete(Event, Events)}}
end;
handle_cast({'gen_listener', {'created_queue', _Q}}, State) ->
{'noreply', State};
handle_cast({'gen_listener', {'is_consuming', _IsConsuming}}, State) ->
{'noreply', State};
handle_cast(_Msg, State) ->
lager:debug("unhandled cast: ~p", [_Msg]),
{'noreply', State}.
%%------------------------------------------------------------------------------
%% @doc Handling all non call/cast messages.
%% @end
%%------------------------------------------------------------------------------
-spec handle_info(any(), state()) -> kz_types:handle_info_ret_state(state()).
handle_info(_Info, State) ->
lager:debug("unhandled msg: ~p", [_Info]),
{'noreply', State}.
%%------------------------------------------------------------------------------
%% @doc Allows listener to pass options to handlers.
%% @end
%%------------------------------------------------------------------------------
-spec handle_event(kz_json:object(), kz_term:proplist()) -> gen_listener:handle_event_return().
handle_event(_JObj, _State) ->
{'reply', [{'rr', 'false'}]}.
%%------------------------------------------------------------------------------
%% @doc This function is called by a `gen_server' when it is about to
%% terminate. It should be the opposite of `Module:init/1' and do any
%% necessary cleaning up. When it returns, the `gen_server' terminates
with . The return value is ignored .
%%
%% @end
%%------------------------------------------------------------------------------
-spec terminate(any(), state()) -> 'ok'.
terminate(_Reason, _State) ->
lager:debug("listener terminating: ~p", [_Reason]).
%%------------------------------------------------------------------------------
%% @doc Convert process state when code is changed.
%% @end
%%------------------------------------------------------------------------------
-spec code_change(any(), state(), any()) -> {'ok', state()}.
code_change(_OldVsn, State, _Extra) ->
{'ok', State}.
%%%=============================================================================
Internal functions
%%%=============================================================================
| null | https://raw.githubusercontent.com/2600hz/kazoo/24519b9af9792caa67f7c09bbb9d27e2418f7ad6/core/kazoo_events/src/kz_hooks_listener.erl | erlang | -----------------------------------------------------------------------------
@doc Listens for a list of events and gproc-sends them out to folks who
want them
@end
-----------------------------------------------------------------------------
=============================================================================
API
=============================================================================
------------------------------------------------------------------------------
@doc Starts the server.
@end
------------------------------------------------------------------------------
=============================================================================
gen_server callbacks
=============================================================================
------------------------------------------------------------------------------
@doc Initializes the server.
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc Handling call messages.
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc Handling cast messages.
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc Handling all non call/cast messages.
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc Allows listener to pass options to handlers.
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc This function is called by a `gen_server' when it is about to
terminate. It should be the opposite of `Module:init/1' and do any
necessary cleaning up. When it returns, the `gen_server' terminates
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc Convert process state when code is changed.
@end
------------------------------------------------------------------------------
=============================================================================
============================================================================= | ( C ) 2013 - 2020 , 2600Hz
@author
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(kz_hooks_listener).
-behaviour(gen_listener).
-export([start_link/0]).
-export([init/1
,handle_call/3
,handle_cast/2
,handle_info/2
,handle_event/2
,terminate/2
,code_change/3
]).
-include("kazoo_events.hrl").
-include("kz_hooks.hrl").
-define(SERVER, ?MODULE).
Three main call events
-define(ALL_EVENTS, [<<"CHANNEL_CREATE">>
,<<"CHANNEL_ANSWER">>
,<<"CHANNEL_DESTROY">>
,<<"CHANNEL_BRIDGE">>
,<<"CHANNEL_UNBRIDGE">>
,<<"CHANNEL_DISCONNECTED">>
,<<"CHANNEL_CONNECTED">>
]).
-define(CALL_BINDING(Events), {'call', [{'restrict_to', Events}
,'federate'
]}).
-define(BINDINGS, []).
-define(RESPONDERS, [{{'kz_hooks_util', 'handle_call_event'}
,[{<<"call_event">>, <<"*">>}]
}
]).
-define(QUEUE_NAME, <<>>).
-define(QUEUE_OPTIONS, []).
-define(CONSUME_OPTIONS, []).
-record(state, {call_events = [] :: kz_term:ne_binaries()}).
-type state() :: #state{}.
-spec start_link() -> kz_types:startlink_ret().
start_link() ->
gen_listener:start_link({'local', ?SERVER}
,?MODULE
,[{'bindings', ?BINDINGS}
,{'responders', ?RESPONDERS}
,{'queue_name', ?QUEUE_NAME}
,{'queue_options', ?QUEUE_OPTIONS}
,{'consume_options', ?CONSUME_OPTIONS}
]
,[]
).
-spec init([]) -> {'ok', state()}.
init([]) ->
kz_log:put_callid(?MODULE),
lager:debug("started ~s", [?MODULE]),
kapi_call:declare_exchanges(),
{'ok', #state{}}.
-spec handle_call(any(), kz_term:pid_ref(), state()) -> kz_types:handle_call_ret_state(state()).
handle_call(_Request, _From, State) ->
{'reply', {'error', 'not_implemented'}, State}.
-spec handle_cast(any(), state()) -> kz_types:handle_cast_ret_state(state()).
handle_cast({'maybe_add_binding', 'all'}, #state{call_events=Events}=State) ->
case [E || E <- ?ALL_EVENTS, not lists:member(E, Events)] of
[] -> {'noreply', State};
Es ->
lager:debug("adding bindings for ~p", [Es]),
gen_listener:add_binding(self(), ?CALL_BINDING(Es)),
{'noreply', State#state{call_events=Es ++ Events}}
end;
handle_cast({'maybe_add_binding', Event}, #state{call_events=Events}=State) ->
case lists:member(Event, Events) of
'true' -> {'noreply', State};
'false' ->
lager:debug("adding bindings for ~s", [Event]),
gen_listener:add_binding(self(), ?CALL_BINDING([Event])),
{'noreply', State#state{call_events=[Event | Events]}}
end;
handle_cast({'maybe_remove_binding', 'all'}, #state{call_events=Events}=State) ->
case [E || E <- ?ALL_EVENTS, lists:member(E, Events)] of
[] -> {'noreply', State};
Es ->
lager:debug("removing bindings for ~p", [Es]),
gen_listener:rm_binding(self(), ?CALL_BINDING(Es)),
{'noreply', State#state{call_events=Events -- Es}}
end;
handle_cast({'maybe_remove_binding', Event}, #state{call_events=Events}=State) ->
case lists:member(Event, Events) of
'true' -> {'noreply', State};
'false' ->
lager:debug("removing bindings for ~s", [Event]),
gen_listener:rm_binding(self(), ?CALL_BINDING([Event])),
{'noreply', State#state{call_events=lists:delete(Event, Events)}}
end;
handle_cast({'gen_listener', {'created_queue', _Q}}, State) ->
{'noreply', State};
handle_cast({'gen_listener', {'is_consuming', _IsConsuming}}, State) ->
{'noreply', State};
handle_cast(_Msg, State) ->
lager:debug("unhandled cast: ~p", [_Msg]),
{'noreply', State}.
-spec handle_info(any(), state()) -> kz_types:handle_info_ret_state(state()).
handle_info(_Info, State) ->
lager:debug("unhandled msg: ~p", [_Info]),
{'noreply', State}.
-spec handle_event(kz_json:object(), kz_term:proplist()) -> gen_listener:handle_event_return().
handle_event(_JObj, _State) ->
{'reply', [{'rr', 'false'}]}.
with . The return value is ignored .
-spec terminate(any(), state()) -> 'ok'.
terminate(_Reason, _State) ->
lager:debug("listener terminating: ~p", [_Reason]).
-spec code_change(any(), state(), any()) -> {'ok', state()}.
code_change(_OldVsn, State, _Extra) ->
{'ok', State}.
Internal functions
|
404a11debc103889215b6f5131ad54c26e51bc0aac791d0c60fa93dcde95781b | GlideAngle/flare-timing | HLint.hs | module Main (main) where
import Language.Haskell.HLint (hlint)
import System.Exit (exitFailure, exitSuccess)
arguments :: [String]
arguments =
[ "app-cmd"
, "test-suite-hlint"
]
main :: IO ()
main = do
hints <- hlint arguments
if null hints then exitSuccess else exitFailure
| null | https://raw.githubusercontent.com/GlideAngle/flare-timing/27bd34c1943496987382091441a1c2516c169263/lang-haskell/build/test-suite-hlint/HLint.hs | haskell | module Main (main) where
import Language.Haskell.HLint (hlint)
import System.Exit (exitFailure, exitSuccess)
arguments :: [String]
arguments =
[ "app-cmd"
, "test-suite-hlint"
]
main :: IO ()
main = do
hints <- hlint arguments
if null hints then exitSuccess else exitFailure
| |
5822f078ebca12fbd684307953397374a55c32d18ab66a657312fc3475fa5c2c | dym/movitz | ext2fs.lisp | Ext2 fs package -- Copyright ( C ) 2004
(require :muerte/integers)
(require :tmp/harddisk)
(require :tmp/partitions)
(require :tmp/fs)
(provide :tmp/ext2fs)
(defpackage fs.ext2
(:use muerte.cl
muerte
muerte.lib)
(:import-from muerte.x86-pc.harddisk hd-read-sectors))
(in-package fs.ext2)
(defvar *known-magic-numbers* '(#xEF53))
;Possible values of an inode's "type" attribute
(defconstant +it-format-mask+ #xf0)
(defconstant +it-socket+ #xc0)
(defconstant +it-symlink+ #xa0)
(defconstant +it-file+ #x80)
(defconstant +it-block-device+ #x60)
(defconstant +it-directory+ #x40)
(defconstant +it-char-device+ #x20)
(defconstant +it-fifo+ #x10)
;;;
;;;Classes and structures
;;;
;;The ext2-fs class is simply a container for the closures created by mount;
;;it is intended to only be passed as an argument to the generic functions in
;;the fs package
(defclass ext2-fs (fs::fs) ())
;;An ext2 superblock -- contains important information relative to the entire
;;filesystem
(defstruct superblock
(inodes_count 0 :type (unsigned-byte 32))
(blocks_count 0 :type (unsigned-byte 32))
(r_blocks_count 0 :type (unsigned-byte 32))
(free_blocks_count 0 :type (unsigned-byte 32))
(free_inodes_count 0 :type (unsigned-byte 32))
(first_data_block 0 :type (unsigned-byte 32))
(log_block_size 0 :type (unsigned-byte 32))
(log_frag_size 0 :type (unsigned-byte 32))
(blocks_per_group 0 :type (unsigned-byte 32))
(s_frags_per_group 0 :type (unsigned-byte 32))
(inodes_per_group 0 :type (unsigned-byte 32))
(s_mtime 0 :type (unsigned-byte 32))
(s_wtime 0 :type (unsigned-byte 32))
(s_mnt_count 0 :type (unsigned-byte 16))
(s_max_mnt_count 0 :type (unsigned-byte 16))
(s_magic 0 :type (unsigned-byte 16))
(s_state 0 :type (unsigned-byte 16))
(s_errors 0 :type (unsigned-byte 16))
(s_minor_rev_level 0 :type (unsigned-byte 16))
(s_lastcheck 0 :type (unsigned-byte 32))
(s_checkinterval 0 :type (unsigned-byte 32))
(s_creator_os 0 :type (unsigned-byte 32))
(s_rev_level 0 :type (unsigned-byte 32))
(s_def_resuid 0 :type (unsigned-byte 16))
(s_def_resgid 0 :type (unsigned-byte 16))
(s_first_ino 0 :type (unsigned-byte 32))
(s_inode_size 0 :type (unsigned-byte 16))
(s_block_group_nr 0 :type (unsigned-byte 16)))
92 4 s_feature_compat
96 4 s_feature_incompat
100 4 s_feature_ro_compat
104 16 s_uuid
120 16 s_volume_name
136 64 s_last_mounted
200 4 s_algo_bitmap
;;A group descriptor -- contains important info relative to a block group
(defstruct group-descriptor
(bg_block_bitmap 0 :type (unsigned-byte 32))
(bg_inode_bitmap 0 :type (unsigned-byte 32))
(inode-table 0 :type (unsigned-byte 32))
(bg_free_blocks_count 0 :type (unsigned-byte 16))
(bg_free_inodes_count 0 :type (unsigned-byte 16))
(bg_used_dirs_count 0 :type (unsigned-byte 16))
bg_reserved)
;;An inode -- represents an object in the fs (e.g. file, directory, symlink...)
(defstruct inode
type
access_rights
(uid 0 :type (unsigned-byte 16))
(size 0 :type (unsigned-byte 32))
(atime 0 :type (unsigned-byte 32))
(ctime 0 :type (unsigned-byte 32))
(mtime 0 :type (unsigned-byte 32))
(dtime 0 :type (unsigned-byte 32))
(gid 0 :type (unsigned-byte 16))
(links_count 0 :type (unsigned-byte 16))
(blocks 0 :type (unsigned-byte 32))
(flags 0 :type (unsigned-byte 32))
(osd1 0 :type (unsigned-byte 32))
block
(generation 0 :type (unsigned-byte 32))
(file_acl 0 :type (unsigned-byte 32))
(dir_acl 0 :type (unsigned-byte 32))
(faddr 0 :type (unsigned-byte 32))
(osd2 0 :type (unsigned-byte 96)))
;;;
;;;Miscellaneous functions and macros -- should be moved elsewhere
;;;
(defun exp256 (exp)
(case exp
(0 #x1)
(1 #x100)
(2 #x10000)
(3 #x1000000)
(4 #x100000000)
(t (expt 256 exp))))
(defun exp2 (exp)
(case exp
(0 1)
(1 2)
(2 4)
(3 8)
(4 16)
(t (expt 2 exp))))
(defun little-endian-to-integer (byte-array start length)
(let ((res 0))
(dotimes (i length)
(incf res (* (exp256 i) (aref byte-array (+ i start)))))
res))
(defun vconc (&rest args)
(declare (dynamic-extent args))
(apply #'concatenate 'vector args))
(define-modify-macro vconcf (&rest args) vconc)
(defun make-string-from-bytes (byte-array)
(let* ((len (length byte-array))
(str (make-string len)))
(dotimes (i len)
(setf (aref str i) (code-char (aref byte-array i))))
str))
(defun split-string (str delim)
(delete "" (loop with start = 0
with len = (length str)
for i = (position delim str :start start)
while (<= start len)
if i collect (subseq str start i) into lst
and do (setq start (1+ i))
else collect (subseq str start) into lst and return lst)
:test #'string=))
(defmacro aif (test then &optional else)
`(let ((it ,test))
(if it ,then ,else)))
(defun test-aif (x)
(aif x (print it) (print 'else)))
;;;
;;;ext2-related functions
;;;
(defun read-superblock (hdn sect)
"Initializes a superblock structure reading data from the specified hard disk and sector"
(let ((sbdata (hd-read-sectors hdn sect 1)))
(if (member (little-endian-to-integer sbdata 56 2) *known-magic-numbers*)
(make-superblock
:inodes_count (little-endian-to-integer sbdata 0 4)
:blocks_count (little-endian-to-integer sbdata 4 4)
:r_blocks_count (little-endian-to-integer sbdata 8 4)
:free_blocks_count (little-endian-to-integer sbdata 12 4)
:free_inodes_count (little-endian-to-integer sbdata 16 4)
:first_data_block (little-endian-to-integer sbdata 20 4)
:log_block_size (little-endian-to-integer sbdata 24 4)
:log_frag_size (little-endian-to-integer sbdata 28 4)
:blocks_per_group (little-endian-to-integer sbdata 32 4)
:s_frags_per_group (little-endian-to-integer sbdata 36 4)
:inodes_per_group (little-endian-to-integer sbdata 40 4)
:s_mtime (little-endian-to-integer sbdata 44 4)
:s_wtime (little-endian-to-integer sbdata 48 4)
:s_mnt_count (little-endian-to-integer sbdata 52 2)
:s_max_mnt_count (little-endian-to-integer sbdata 54 2)
:s_magic (little-endian-to-integer sbdata 56 2)
:s_state (little-endian-to-integer sbdata 58 2)
:s_errors (little-endian-to-integer sbdata 60 2)
:s_minor_rev_level (little-endian-to-integer sbdata 62 2)
:s_lastcheck (little-endian-to-integer sbdata 64 4)
:s_checkinterval (little-endian-to-integer sbdata 68 4)
:s_creator_os (little-endian-to-integer sbdata 72 4)
:s_rev_level (little-endian-to-integer sbdata 76 4)
:s_def_resuid (little-endian-to-integer sbdata 80 2)
:s_def_resgid (little-endian-to-integer sbdata 82 2))
(error "Can't read ext2 superblock -- invalid magic number. Either this is not an ext2 fs, or it is corrupted; in this case, try reading a superblock backup copy"))))
(defun read-group-descriptors (hdn sect howmany)
"Initializes an array of <howmany> group-descriptor structures reading data from the sector sect of the specified hard disk"
(let ((data (hd-read-sectors hdn sect howmany))
(arr (make-array howmany)))
(loop for i from 0 to (1- howmany)
for j = (* 32 i)
do (setf (aref arr i)
(make-group-descriptor
:bg_block_bitmap (little-endian-to-integer data j 4)
:bg_inode_bitmap (little-endian-to-integer data (+ j 4) 4)
:inode-table (little-endian-to-integer data (+ j 8) 4)
:bg_free_blocks_count (little-endian-to-integer data (+ j 12) 2)
:bg_free_inodes_count (little-endian-to-integer data (+ j 14) 2)
:bg_used_dirs_count (little-endian-to-integer data (+ j 16) 2))))
arr))
(defun read-inodes (hdn sect howmany)
"Reads some inodes"
(let* ((data (hd-read-sectors hdn sect (1+ (truncate (/ (1- howmany) 4)))))
(arr (make-array howmany :element-type 'inode))
(blockdata (make-array 15)))
; (format t "reading ~A inodes from sector ~A~%" howmany sect)
(dotimes (i howmany)
(dotimes (j 15)
(setf (aref blockdata j) (little-endian-to-integer data (+ 40 (* 4 j) (* 128 i)) 4)))
(setf (aref arr i)
(make-inode
:type (logand #xf0 (aref data (1+ (* 128 i))))
:access_rights (logand #x0fff (little-endian-to-integer data (* 128 i) 2))
:uid (little-endian-to-integer data (+ 2 (* 128 i)) 2)
:size (little-endian-to-integer data (+ 4 (* 128 i)) 4)
:links_count (little-endian-to-integer data (+ 26 (* 128 i)) 2)
:blocks (little-endian-to-integer data (+ 28 (* 128 i)) 4)
:flags (little-endian-to-integer data (+ 32 (* 128 i)) 4)
:block (copy-seq blockdata))))
arr))
;;;
;;;The "main" function, mount
;;;
(defun mount (hdn part &key (sb-sect 2) (inode-cache-size 15))
"Returns an ext2-fs instance reading data from the specified hard disk and partition"
(let* ((pstart (muerte.x86-pc.harddisk::partition-start part))
(sb (read-superblock hdn (+ pstart sb-sect)))
(blocksize (exp2 (1+ (superblock-log_block_size sb))))
(blocksize-bytes (* 512 blocksize))
(group-descriptors (read-group-descriptors
hdn
(+ pstart
(* blocksize (superblock-first_data_block sb))
blocksize)
(1+ (truncate (/ (superblock-blocks_count sb)
(superblock-blocks_per_group sb))))))
(root (aref
(read-inodes
0
(+ pstart
(* blocksize
(group-descriptor-inode-table (aref group-descriptors 0))))
2)
1))
(inode-cache (make-array inode-cache-size
:initial-element (vector nil nil)))
(inode-cache-ptr 0)
(open-files ()))
(macrolet ((dir-loop (return-value &rest loop-clauses)
`(let* ((file (%open-file inode))
(val (loop with size = (inode-size inode)
with count = 0
for num = (little-endian-to-integer
(%read-data file 4) 0 4)
for reclen = (little-endian-to-integer
(%read-data file 2) 0 2)
for strlen = (aref (%read-data file) 0)
for type = (%read-data file)
for name = (make-string-from-bytes (%read-data file strlen))
do (%read-data file (- reclen strlen 8)) ;Padding
,@loop-clauses
do (incf count reclen)
if (>= count size) return ,return-value)))
(%close-file file)
val)))
(labels ((%read-inode (num)
"Reads the inode number num from the inode table"
(let ((num0 (1- num)))
(aif (find num inode-cache :test #'equal :key #'(lambda (x) (aref x 0)))
(aref it 1)
(let* ((block-group (truncate (/ num0 (superblock-inodes_per_group sb))))
(inode (aref (read-inodes
hdn
(+ pstart
(* blocksize
(group-descriptor-inode-table
(aref group-descriptors block-group)))
(truncate (/ (- num0 (* block-group (superblock-inodes_per_group sb))) 4)))
4)
(mod (- num0 (* block-group (superblock-inodes_per_group sb))) 4))))
(setf (aref inode-cache inode-cache-ptr) (vector num inode))
(setq inode-cache-ptr (mod (1+ inode-cache-ptr) inode-cache-size))
inode))))
(%inode-block-to-address (inode blocknum)
"Converts one of the block fields of the inode structure into a physical address"
(+ pstart
(* blocksize
(cond
((< blocknum 12) (aref (inode-block inode) blocknum))
((and (>= blocknum 12)
(< blocknum (+ 12 (* 128 blocksize))))
(aref (hd-read-sectors
hdn
(+ pstart (* blocksize (aref (inode-block inode) 12)))
blocksize)
(- blocknum 12)))
;;Bi-indirect and tri-indirect blocks not implemented yet
))))
(%open-file (inode &optional (name "Unknown") (mode :read))
(let ((file-handle (gensym)))
(case mode
(:read (push (list file-handle inode 0 name :read nil)
open-files))
(t (error "Unknown mode: ~A" mode)))
file-handle))
(%close-file (handle)
(setq open-files (delete handle open-files :key #'car)))
(%read-data (handle &optional (bytes 1))
"Reads at most <bytes> bytes from the specified file. Returns as much data as could be read from the file (if bytes > 1), or :eof if the end of the file has been reached. Note that file actually means inode, i.e. this function can also read directories."
(let* ((filedata (assoc handle open-files))
(inode (second filedata))
(size (inode-size inode))
(fileptr (third filedata))
(name (fourth filedata))
(mode (fifth filedata))
(blocknum (truncate (/ fileptr blocksize-bytes))))
(when (> (+ fileptr bytes) size)
(if (and (> bytes 1) (< fileptr size))
(return-from %read-data (%read-data handle (- size fileptr)))
(return-from %read-data :eof)))
(when (< bytes 1) (return-from %read-data #()))
(if (and filedata (member mode '(:read)))
(apply #'vconc
(loop with ptr = (- fileptr (* blocknum blocksize-bytes))
with left = bytes
while (> left 0)
if (eq (sixth filedata) nil)
do (setf (sixth filedata) (hd-read-sectors hdn (%inode-block-to-address inode blocknum) blocksize))
if (<= (+ ptr left) blocksize-bytes)
collect (subseq (sixth filedata) ptr (+ ptr left)) into lst
and do (incf (third filedata) left)
and return lst
else collect (subseq (sixth filedata) ptr) into lst
do (incf blocknum)
do (setf (sixth filedata) (hd-read-sectors hdn (%inode-block-to-address inode blocknum) blocksize))
do (decf left (- blocksize-bytes ptr))
do (incf (third filedata) (- blocksize-bytes ptr))
do (setq ptr 0)))
(error "File not open for reading: ~A" name))))
(%list-dir (inode)
"Returns an array of the directory entries of inode, in the form (name <inode>)"
(dir-loop result
collect (list name (%read-inode num)) into result))
(%find-dir-entry (inode entry-name)
"Searches for a given directory entry"
(dir-loop nil
if (string= name entry-name)
return (%read-inode num)))
(%path-to-inode (path)
"Converts an (absolute) path into an inode"
(let ((path2 (split-string path #\/))
(inode root))
; (format t "path2 = ~A~% " path2)
; (read)
(if (null path2)
root
(progn
(dolist (x (butlast path2))
(setq inode (%find-dir-entry inode x))
(when (null inode)
(return)))
(if (null inode)
nil
(%find-dir-entry inode (car (last path2)))))))))
; (print (%path-to-inode "/"))
; (print (%path-to-inode "/."))
( print ( % path - to - inode " /etc/ " ) )
; (format t "Inodes per group: ~A~%" (superblock-inodes_per_group sb))
; (print (%path-to-inode "/etc/fstab"))
(make-instance 'ext2-fs
:open-file-fn #'(lambda (path &optional (mode :read))
(let ((inode (%path-to-inode path)))
(cond
((null inode)
(error "File doesn't exist: ~A" path))
((= (inode-type inode) +it-directory+)
(error "File ~A is a directory!" path))
(t (%open-file inode path mode)))))
:read-file-fn #'%read-data
:write-file-fn #'(lambda (file-handle data)
(declare (ignore file-handle data))
(warn "Not implemented!"))
:close-file-fn #'%close-file
:delete-file-fn #'(lambda (path)
(declare (ignore path))
(warn "Not implemented!"))
:list-open-files-fn #'(lambda () open-files) ;TODO!!
:list-dir-fn #'(lambda (path)
(let ((inode (%path-to-inode path)))
(if (= (inode-type inode) +it-directory+)
(%list-dir inode)
(error "~A is not a directory!" path))))
:create-dir-fn #'(lambda (path)
(declare (ignore path))
(warn "Not implemented!"))
:delete-dir-fn #'(lambda (path &optional (recursive-p nil))
(declare (ignore path recursive-p))
(warn "Not implemented!")))))))
| null | https://raw.githubusercontent.com/dym/movitz/56176e1ebe3eabc15c768df92eca7df3c197cb3d/losp/tmp/ext2fs.lisp | lisp | Possible values of an inode's "type" attribute
Classes and structures
The ext2-fs class is simply a container for the closures created by mount;
it is intended to only be passed as an argument to the generic functions in
the fs package
An ext2 superblock -- contains important information relative to the entire
filesystem
A group descriptor -- contains important info relative to a block group
An inode -- represents an object in the fs (e.g. file, directory, symlink...)
Miscellaneous functions and macros -- should be moved elsewhere
ext2-related functions
(format t "reading ~A inodes from sector ~A~%" howmany sect)
The "main" function, mount
Padding
Bi-indirect and tri-indirect blocks not implemented yet
(format t "path2 = ~A~% " path2)
(read)
(print (%path-to-inode "/"))
(print (%path-to-inode "/."))
(format t "Inodes per group: ~A~%" (superblock-inodes_per_group sb))
(print (%path-to-inode "/etc/fstab"))
TODO!! | Ext2 fs package -- Copyright ( C ) 2004
(require :muerte/integers)
(require :tmp/harddisk)
(require :tmp/partitions)
(require :tmp/fs)
(provide :tmp/ext2fs)
(defpackage fs.ext2
(:use muerte.cl
muerte
muerte.lib)
(:import-from muerte.x86-pc.harddisk hd-read-sectors))
(in-package fs.ext2)
(defvar *known-magic-numbers* '(#xEF53))
(defconstant +it-format-mask+ #xf0)
(defconstant +it-socket+ #xc0)
(defconstant +it-symlink+ #xa0)
(defconstant +it-file+ #x80)
(defconstant +it-block-device+ #x60)
(defconstant +it-directory+ #x40)
(defconstant +it-char-device+ #x20)
(defconstant +it-fifo+ #x10)
(defclass ext2-fs (fs::fs) ())
(defstruct superblock
(inodes_count 0 :type (unsigned-byte 32))
(blocks_count 0 :type (unsigned-byte 32))
(r_blocks_count 0 :type (unsigned-byte 32))
(free_blocks_count 0 :type (unsigned-byte 32))
(free_inodes_count 0 :type (unsigned-byte 32))
(first_data_block 0 :type (unsigned-byte 32))
(log_block_size 0 :type (unsigned-byte 32))
(log_frag_size 0 :type (unsigned-byte 32))
(blocks_per_group 0 :type (unsigned-byte 32))
(s_frags_per_group 0 :type (unsigned-byte 32))
(inodes_per_group 0 :type (unsigned-byte 32))
(s_mtime 0 :type (unsigned-byte 32))
(s_wtime 0 :type (unsigned-byte 32))
(s_mnt_count 0 :type (unsigned-byte 16))
(s_max_mnt_count 0 :type (unsigned-byte 16))
(s_magic 0 :type (unsigned-byte 16))
(s_state 0 :type (unsigned-byte 16))
(s_errors 0 :type (unsigned-byte 16))
(s_minor_rev_level 0 :type (unsigned-byte 16))
(s_lastcheck 0 :type (unsigned-byte 32))
(s_checkinterval 0 :type (unsigned-byte 32))
(s_creator_os 0 :type (unsigned-byte 32))
(s_rev_level 0 :type (unsigned-byte 32))
(s_def_resuid 0 :type (unsigned-byte 16))
(s_def_resgid 0 :type (unsigned-byte 16))
(s_first_ino 0 :type (unsigned-byte 32))
(s_inode_size 0 :type (unsigned-byte 16))
(s_block_group_nr 0 :type (unsigned-byte 16)))
92 4 s_feature_compat
96 4 s_feature_incompat
100 4 s_feature_ro_compat
104 16 s_uuid
120 16 s_volume_name
136 64 s_last_mounted
200 4 s_algo_bitmap
(defstruct group-descriptor
(bg_block_bitmap 0 :type (unsigned-byte 32))
(bg_inode_bitmap 0 :type (unsigned-byte 32))
(inode-table 0 :type (unsigned-byte 32))
(bg_free_blocks_count 0 :type (unsigned-byte 16))
(bg_free_inodes_count 0 :type (unsigned-byte 16))
(bg_used_dirs_count 0 :type (unsigned-byte 16))
bg_reserved)
(defstruct inode
type
access_rights
(uid 0 :type (unsigned-byte 16))
(size 0 :type (unsigned-byte 32))
(atime 0 :type (unsigned-byte 32))
(ctime 0 :type (unsigned-byte 32))
(mtime 0 :type (unsigned-byte 32))
(dtime 0 :type (unsigned-byte 32))
(gid 0 :type (unsigned-byte 16))
(links_count 0 :type (unsigned-byte 16))
(blocks 0 :type (unsigned-byte 32))
(flags 0 :type (unsigned-byte 32))
(osd1 0 :type (unsigned-byte 32))
block
(generation 0 :type (unsigned-byte 32))
(file_acl 0 :type (unsigned-byte 32))
(dir_acl 0 :type (unsigned-byte 32))
(faddr 0 :type (unsigned-byte 32))
(osd2 0 :type (unsigned-byte 96)))
(defun exp256 (exp)
(case exp
(0 #x1)
(1 #x100)
(2 #x10000)
(3 #x1000000)
(4 #x100000000)
(t (expt 256 exp))))
(defun exp2 (exp)
(case exp
(0 1)
(1 2)
(2 4)
(3 8)
(4 16)
(t (expt 2 exp))))
(defun little-endian-to-integer (byte-array start length)
(let ((res 0))
(dotimes (i length)
(incf res (* (exp256 i) (aref byte-array (+ i start)))))
res))
(defun vconc (&rest args)
(declare (dynamic-extent args))
(apply #'concatenate 'vector args))
(define-modify-macro vconcf (&rest args) vconc)
(defun make-string-from-bytes (byte-array)
(let* ((len (length byte-array))
(str (make-string len)))
(dotimes (i len)
(setf (aref str i) (code-char (aref byte-array i))))
str))
(defun split-string (str delim)
(delete "" (loop with start = 0
with len = (length str)
for i = (position delim str :start start)
while (<= start len)
if i collect (subseq str start i) into lst
and do (setq start (1+ i))
else collect (subseq str start) into lst and return lst)
:test #'string=))
(defmacro aif (test then &optional else)
`(let ((it ,test))
(if it ,then ,else)))
(defun test-aif (x)
(aif x (print it) (print 'else)))
(defun read-superblock (hdn sect)
"Initializes a superblock structure reading data from the specified hard disk and sector"
(let ((sbdata (hd-read-sectors hdn sect 1)))
(if (member (little-endian-to-integer sbdata 56 2) *known-magic-numbers*)
(make-superblock
:inodes_count (little-endian-to-integer sbdata 0 4)
:blocks_count (little-endian-to-integer sbdata 4 4)
:r_blocks_count (little-endian-to-integer sbdata 8 4)
:free_blocks_count (little-endian-to-integer sbdata 12 4)
:free_inodes_count (little-endian-to-integer sbdata 16 4)
:first_data_block (little-endian-to-integer sbdata 20 4)
:log_block_size (little-endian-to-integer sbdata 24 4)
:log_frag_size (little-endian-to-integer sbdata 28 4)
:blocks_per_group (little-endian-to-integer sbdata 32 4)
:s_frags_per_group (little-endian-to-integer sbdata 36 4)
:inodes_per_group (little-endian-to-integer sbdata 40 4)
:s_mtime (little-endian-to-integer sbdata 44 4)
:s_wtime (little-endian-to-integer sbdata 48 4)
:s_mnt_count (little-endian-to-integer sbdata 52 2)
:s_max_mnt_count (little-endian-to-integer sbdata 54 2)
:s_magic (little-endian-to-integer sbdata 56 2)
:s_state (little-endian-to-integer sbdata 58 2)
:s_errors (little-endian-to-integer sbdata 60 2)
:s_minor_rev_level (little-endian-to-integer sbdata 62 2)
:s_lastcheck (little-endian-to-integer sbdata 64 4)
:s_checkinterval (little-endian-to-integer sbdata 68 4)
:s_creator_os (little-endian-to-integer sbdata 72 4)
:s_rev_level (little-endian-to-integer sbdata 76 4)
:s_def_resuid (little-endian-to-integer sbdata 80 2)
:s_def_resgid (little-endian-to-integer sbdata 82 2))
(error "Can't read ext2 superblock -- invalid magic number. Either this is not an ext2 fs, or it is corrupted; in this case, try reading a superblock backup copy"))))
(defun read-group-descriptors (hdn sect howmany)
"Initializes an array of <howmany> group-descriptor structures reading data from the sector sect of the specified hard disk"
(let ((data (hd-read-sectors hdn sect howmany))
(arr (make-array howmany)))
(loop for i from 0 to (1- howmany)
for j = (* 32 i)
do (setf (aref arr i)
(make-group-descriptor
:bg_block_bitmap (little-endian-to-integer data j 4)
:bg_inode_bitmap (little-endian-to-integer data (+ j 4) 4)
:inode-table (little-endian-to-integer data (+ j 8) 4)
:bg_free_blocks_count (little-endian-to-integer data (+ j 12) 2)
:bg_free_inodes_count (little-endian-to-integer data (+ j 14) 2)
:bg_used_dirs_count (little-endian-to-integer data (+ j 16) 2))))
arr))
(defun read-inodes (hdn sect howmany)
"Reads some inodes"
(let* ((data (hd-read-sectors hdn sect (1+ (truncate (/ (1- howmany) 4)))))
(arr (make-array howmany :element-type 'inode))
(blockdata (make-array 15)))
(dotimes (i howmany)
(dotimes (j 15)
(setf (aref blockdata j) (little-endian-to-integer data (+ 40 (* 4 j) (* 128 i)) 4)))
(setf (aref arr i)
(make-inode
:type (logand #xf0 (aref data (1+ (* 128 i))))
:access_rights (logand #x0fff (little-endian-to-integer data (* 128 i) 2))
:uid (little-endian-to-integer data (+ 2 (* 128 i)) 2)
:size (little-endian-to-integer data (+ 4 (* 128 i)) 4)
:links_count (little-endian-to-integer data (+ 26 (* 128 i)) 2)
:blocks (little-endian-to-integer data (+ 28 (* 128 i)) 4)
:flags (little-endian-to-integer data (+ 32 (* 128 i)) 4)
:block (copy-seq blockdata))))
arr))
(defun mount (hdn part &key (sb-sect 2) (inode-cache-size 15))
"Returns an ext2-fs instance reading data from the specified hard disk and partition"
(let* ((pstart (muerte.x86-pc.harddisk::partition-start part))
(sb (read-superblock hdn (+ pstart sb-sect)))
(blocksize (exp2 (1+ (superblock-log_block_size sb))))
(blocksize-bytes (* 512 blocksize))
(group-descriptors (read-group-descriptors
hdn
(+ pstart
(* blocksize (superblock-first_data_block sb))
blocksize)
(1+ (truncate (/ (superblock-blocks_count sb)
(superblock-blocks_per_group sb))))))
(root (aref
(read-inodes
0
(+ pstart
(* blocksize
(group-descriptor-inode-table (aref group-descriptors 0))))
2)
1))
(inode-cache (make-array inode-cache-size
:initial-element (vector nil nil)))
(inode-cache-ptr 0)
(open-files ()))
(macrolet ((dir-loop (return-value &rest loop-clauses)
`(let* ((file (%open-file inode))
(val (loop with size = (inode-size inode)
with count = 0
for num = (little-endian-to-integer
(%read-data file 4) 0 4)
for reclen = (little-endian-to-integer
(%read-data file 2) 0 2)
for strlen = (aref (%read-data file) 0)
for type = (%read-data file)
for name = (make-string-from-bytes (%read-data file strlen))
,@loop-clauses
do (incf count reclen)
if (>= count size) return ,return-value)))
(%close-file file)
val)))
(labels ((%read-inode (num)
"Reads the inode number num from the inode table"
(let ((num0 (1- num)))
(aif (find num inode-cache :test #'equal :key #'(lambda (x) (aref x 0)))
(aref it 1)
(let* ((block-group (truncate (/ num0 (superblock-inodes_per_group sb))))
(inode (aref (read-inodes
hdn
(+ pstart
(* blocksize
(group-descriptor-inode-table
(aref group-descriptors block-group)))
(truncate (/ (- num0 (* block-group (superblock-inodes_per_group sb))) 4)))
4)
(mod (- num0 (* block-group (superblock-inodes_per_group sb))) 4))))
(setf (aref inode-cache inode-cache-ptr) (vector num inode))
(setq inode-cache-ptr (mod (1+ inode-cache-ptr) inode-cache-size))
inode))))
(%inode-block-to-address (inode blocknum)
"Converts one of the block fields of the inode structure into a physical address"
(+ pstart
(* blocksize
(cond
((< blocknum 12) (aref (inode-block inode) blocknum))
((and (>= blocknum 12)
(< blocknum (+ 12 (* 128 blocksize))))
(aref (hd-read-sectors
hdn
(+ pstart (* blocksize (aref (inode-block inode) 12)))
blocksize)
(- blocknum 12)))
))))
(%open-file (inode &optional (name "Unknown") (mode :read))
(let ((file-handle (gensym)))
(case mode
(:read (push (list file-handle inode 0 name :read nil)
open-files))
(t (error "Unknown mode: ~A" mode)))
file-handle))
(%close-file (handle)
(setq open-files (delete handle open-files :key #'car)))
(%read-data (handle &optional (bytes 1))
"Reads at most <bytes> bytes from the specified file. Returns as much data as could be read from the file (if bytes > 1), or :eof if the end of the file has been reached. Note that file actually means inode, i.e. this function can also read directories."
(let* ((filedata (assoc handle open-files))
(inode (second filedata))
(size (inode-size inode))
(fileptr (third filedata))
(name (fourth filedata))
(mode (fifth filedata))
(blocknum (truncate (/ fileptr blocksize-bytes))))
(when (> (+ fileptr bytes) size)
(if (and (> bytes 1) (< fileptr size))
(return-from %read-data (%read-data handle (- size fileptr)))
(return-from %read-data :eof)))
(when (< bytes 1) (return-from %read-data #()))
(if (and filedata (member mode '(:read)))
(apply #'vconc
(loop with ptr = (- fileptr (* blocknum blocksize-bytes))
with left = bytes
while (> left 0)
if (eq (sixth filedata) nil)
do (setf (sixth filedata) (hd-read-sectors hdn (%inode-block-to-address inode blocknum) blocksize))
if (<= (+ ptr left) blocksize-bytes)
collect (subseq (sixth filedata) ptr (+ ptr left)) into lst
and do (incf (third filedata) left)
and return lst
else collect (subseq (sixth filedata) ptr) into lst
do (incf blocknum)
do (setf (sixth filedata) (hd-read-sectors hdn (%inode-block-to-address inode blocknum) blocksize))
do (decf left (- blocksize-bytes ptr))
do (incf (third filedata) (- blocksize-bytes ptr))
do (setq ptr 0)))
(error "File not open for reading: ~A" name))))
(%list-dir (inode)
"Returns an array of the directory entries of inode, in the form (name <inode>)"
(dir-loop result
collect (list name (%read-inode num)) into result))
(%find-dir-entry (inode entry-name)
"Searches for a given directory entry"
(dir-loop nil
if (string= name entry-name)
return (%read-inode num)))
(%path-to-inode (path)
"Converts an (absolute) path into an inode"
(let ((path2 (split-string path #\/))
(inode root))
(if (null path2)
root
(progn
(dolist (x (butlast path2))
(setq inode (%find-dir-entry inode x))
(when (null inode)
(return)))
(if (null inode)
nil
(%find-dir-entry inode (car (last path2)))))))))
( print ( % path - to - inode " /etc/ " ) )
(make-instance 'ext2-fs
:open-file-fn #'(lambda (path &optional (mode :read))
(let ((inode (%path-to-inode path)))
(cond
((null inode)
(error "File doesn't exist: ~A" path))
((= (inode-type inode) +it-directory+)
(error "File ~A is a directory!" path))
(t (%open-file inode path mode)))))
:read-file-fn #'%read-data
:write-file-fn #'(lambda (file-handle data)
(declare (ignore file-handle data))
(warn "Not implemented!"))
:close-file-fn #'%close-file
:delete-file-fn #'(lambda (path)
(declare (ignore path))
(warn "Not implemented!"))
:list-dir-fn #'(lambda (path)
(let ((inode (%path-to-inode path)))
(if (= (inode-type inode) +it-directory+)
(%list-dir inode)
(error "~A is not a directory!" path))))
:create-dir-fn #'(lambda (path)
(declare (ignore path))
(warn "Not implemented!"))
:delete-dir-fn #'(lambda (path &optional (recursive-p nil))
(declare (ignore path recursive-p))
(warn "Not implemented!")))))))
|
03a8e0613c47df004d8f50883e71ef1ea9e915f1f2948a969d207f2129c281b8 | mirage/irmin | sync.mli |
* Copyright ( c ) 2013 - 2022 < >
*
* 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-2022 Thomas Gazagnaire <>
*
* 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.
*)
(** Store Synchronisation. *)
include Sync_intf.Sigs
* @inline
| null | https://raw.githubusercontent.com/mirage/irmin/abeee121a6db7b085b3c68af50ef24a8d8f9ed05/src/irmin/sync.mli | ocaml | * Store Synchronisation. |
* Copyright ( c ) 2013 - 2022 < >
*
* 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-2022 Thomas Gazagnaire <>
*
* 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.
*)
include Sync_intf.Sigs
* @inline
|
c12d9a8e00499592dc7e4207959bef734f9e4fc642d440cdf85e6778c6f5e4a4 | shenxs/about-scheme | space-game.rkt | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname space-game) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp")) #f)))
;;///////////////////////////////////////
(define Height 300)
(define Width 200)
(define Tank-Height 10)
(define Tank-Width 40)
(define Background (empty-scene Width Height))
(define Ufo
(overlay
(circle 5 "solid" "green")
(rectangle 30 3 "solid" "green") ))
(define Tank (rectangle Tank-Width Tank-Height "solid" "blue"))
(define Missile (triangle 10 "solid" "red"))
(define Tank-Vel 2)
(define Missile-Vel 10)
(define Ufo-Vel 1)
(define Judge-Distance 7)
( make - game Posn tank Posn / false )
(define-struct game [ufo tank missile])
;;(make-tank x v)
;;x轴的位置,v-》速度
;;(make-tank number number)
(define-struct tank [loc vel])
;;////////////////////////////////////////////////
;;辅助函数定义
;;missile->image
;;Posn->将missile加到背景
;;false-》直接返回background
(define (missile-render mis)
(cond
[(posn? mis) (place-image Missile (posn-x mis) (posn-y mis) Background ) ]
[else Background]))
;;SIGS->Image
将Tank , ufo , 可能也有missile加到background上
(define (drawer s)
(place-images
(list Ufo Tank)
(list (game-ufo s)
(make-posn (tank-loc (game-tank s)) (- Height (/ Tank-Height 2))))
(missile-render (game-missile s))))
;;posn->T/F
确定posn是否在画布内,是否超出画布
超出->false , 没超出->true
(define (in-rich? p)
(if (and (<= 0 (posn-x p) Width) (<= 0 (posn-y p) Height) ) true false))
number->number
;;产生一个在n左右为5的平均数,新的数字在画布的范围内
(define (creat-random-number n)
(cond
[(> (- Width 5) n 5) (+ n (* (random 5) (if (odd? (random 10)) 1 -1) ))]
[else n ]))
;;posn,posn->number
;;计算两个点之间的距离
(define (distance p1 p2)
(sqrt (+
(* (- (posn-x p1) (posn-x p2)) (- (posn-x p1) (posn-x p2)))
(* (- (posn-y p1) (posn-y p2)) (- (posn-y p1) (posn-y p2))))))
ufo->ufo
(define (ufo-next u)
(make-posn (creat-random-number (posn-x u))
(+ (posn-y u) Ufo-Vel) ))
;;posn->posn/false
;;如果在范围内就在y坐标减去速度,如果超出范围则改为false
(define (missile-next mis)
(cond
[(posn? mis)
(if (in-rich? mis )
(make-posn (posn-x mis) (- (posn-y mis) Missile-Vel) )
false)
]
[else mis]))
;;tank-tank
(define (tank-next-bytime t)
(make-tank
(+ (tank-loc t) (tank-vel t))
(cond [(< (tank-loc t) 0) Tank-Vel]
[(> (tank-loc t) Width) (* -1 Tank-Vel)]
[else (tank-vel t)])))
(define (tank-next-bykey tank key)
(make-tank (tank-loc tank)
(cond
[(key=? key "left") (* -1 Tank-Vel)]
[(key=? key "right") Tank-Vel]
[else (tank-vel tank)])))
(define (missile-next-by-key tank mis key )
(cond
[(and (not (posn? mis)) (key=? key " ")) (make-posn (tank-loc tank) (- Height Tank-Height))]
[else mis]))
;;state->state
(define (time-hander s)
(make-game (ufo-next (game-ufo s))
(tank-next-bytime (game-tank s))
(missile-next (game-missile s))))
;;state->state
(define (key-hander g k)
(make-game (game-ufo g)
(tank-next-bykey (game-tank g) k )
(missile-next-by-key (game-tank g) (game-missile g) k)))
(define (stop-render g)
(cond
[(not (in-rich? (game-ufo g))) true]
[(and (posn? (game-missile g)) (< (distance (game-ufo g) (game-missile g)) Judge-Distance)) true]
[else false]))
(define (judge g)
(cond
[(not (in-rich? (game-ufo g)))
(overlay (text "Game Over" 24 "red") (drawer g))]
[(and (posn? (game-missile g)) (< (distance (game-ufo g) (game-missile g)) Judge-Distance))
(overlay (text "You Win" 24 "indigo") (drawer g))]))
;;//////////////////////
;;主函数定义
(define (run asd)
(big-bang (make-game (make-posn (/ Width 2) 0) (make-tank 0 Tank-Vel) false )
[to-draw drawer]
[on-key key-hander]
[on-tick time-hander ]
[stop-when stop-render judge]
))
(run 1)
| null | https://raw.githubusercontent.com/shenxs/about-scheme/d458776a62cb0bbcbfbb2a044ed18b849f26fd0f/HTDP/space-game.rkt | racket | about the language level of this file in a form that our tools can easily process.
///////////////////////////////////////
(make-tank x v)
x轴的位置,v-》速度
(make-tank number number)
////////////////////////////////////////////////
辅助函数定义
missile->image
Posn->将missile加到背景
false-》直接返回background
SIGS->Image
posn->T/F
产生一个在n左右为5的平均数,新的数字在画布的范围内
posn,posn->number
计算两个点之间的距离
posn->posn/false
如果在范围内就在y坐标减去速度,如果超出范围则改为false
tank-tank
state->state
state->state
//////////////////////
主函数定义 | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname space-game) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp")) #f)))
(define Height 300)
(define Width 200)
(define Tank-Height 10)
(define Tank-Width 40)
(define Background (empty-scene Width Height))
(define Ufo
(overlay
(circle 5 "solid" "green")
(rectangle 30 3 "solid" "green") ))
(define Tank (rectangle Tank-Width Tank-Height "solid" "blue"))
(define Missile (triangle 10 "solid" "red"))
(define Tank-Vel 2)
(define Missile-Vel 10)
(define Ufo-Vel 1)
(define Judge-Distance 7)
( make - game Posn tank Posn / false )
(define-struct game [ufo tank missile])
(define-struct tank [loc vel])
(define (missile-render mis)
(cond
[(posn? mis) (place-image Missile (posn-x mis) (posn-y mis) Background ) ]
[else Background]))
将Tank , ufo , 可能也有missile加到background上
(define (drawer s)
(place-images
(list Ufo Tank)
(list (game-ufo s)
(make-posn (tank-loc (game-tank s)) (- Height (/ Tank-Height 2))))
(missile-render (game-missile s))))
确定posn是否在画布内,是否超出画布
超出->false , 没超出->true
(define (in-rich? p)
(if (and (<= 0 (posn-x p) Width) (<= 0 (posn-y p) Height) ) true false))
number->number
(define (creat-random-number n)
(cond
[(> (- Width 5) n 5) (+ n (* (random 5) (if (odd? (random 10)) 1 -1) ))]
[else n ]))
(define (distance p1 p2)
(sqrt (+
(* (- (posn-x p1) (posn-x p2)) (- (posn-x p1) (posn-x p2)))
(* (- (posn-y p1) (posn-y p2)) (- (posn-y p1) (posn-y p2))))))
ufo->ufo
(define (ufo-next u)
(make-posn (creat-random-number (posn-x u))
(+ (posn-y u) Ufo-Vel) ))
(define (missile-next mis)
(cond
[(posn? mis)
(if (in-rich? mis )
(make-posn (posn-x mis) (- (posn-y mis) Missile-Vel) )
false)
]
[else mis]))
(define (tank-next-bytime t)
(make-tank
(+ (tank-loc t) (tank-vel t))
(cond [(< (tank-loc t) 0) Tank-Vel]
[(> (tank-loc t) Width) (* -1 Tank-Vel)]
[else (tank-vel t)])))
(define (tank-next-bykey tank key)
(make-tank (tank-loc tank)
(cond
[(key=? key "left") (* -1 Tank-Vel)]
[(key=? key "right") Tank-Vel]
[else (tank-vel tank)])))
(define (missile-next-by-key tank mis key )
(cond
[(and (not (posn? mis)) (key=? key " ")) (make-posn (tank-loc tank) (- Height Tank-Height))]
[else mis]))
(define (time-hander s)
(make-game (ufo-next (game-ufo s))
(tank-next-bytime (game-tank s))
(missile-next (game-missile s))))
(define (key-hander g k)
(make-game (game-ufo g)
(tank-next-bykey (game-tank g) k )
(missile-next-by-key (game-tank g) (game-missile g) k)))
(define (stop-render g)
(cond
[(not (in-rich? (game-ufo g))) true]
[(and (posn? (game-missile g)) (< (distance (game-ufo g) (game-missile g)) Judge-Distance)) true]
[else false]))
(define (judge g)
(cond
[(not (in-rich? (game-ufo g)))
(overlay (text "Game Over" 24 "red") (drawer g))]
[(and (posn? (game-missile g)) (< (distance (game-ufo g) (game-missile g)) Judge-Distance))
(overlay (text "You Win" 24 "indigo") (drawer g))]))
(define (run asd)
(big-bang (make-game (make-posn (/ Width 2) 0) (make-tank 0 Tank-Vel) false )
[to-draw drawer]
[on-key key-hander]
[on-tick time-hander ]
[stop-when stop-render judge]
))
(run 1)
|
6d2952c73830ada5cba697c30827cae6d31b5d99d859e057a4d5affaa5f562f7 | wpfjtmwls/TensorFlOcaml | test_demo.ml |
Example test if one were to want to demo Tensorflowcaml
Example test if one were to want to demo Tensorflowcaml
*)
open OUnit2
open Owl
open Tfgraph
open Tfgraphst
open Mnistnet
open Random
open Printf
(* Pull data *)
let xtrain, _, ytrain = Dataset.load_mnist_train_data ()
let xtrain, ytrain = (Dense.Matrix.Generic.cast_s2d xtrain, Dense.Matrix.Generic.cast_s2d ytrain)
let xtest, _, ytest = Dataset.load_mnist_test_data ()
let xtest, ytest = (Dense.Matrix.Generic.cast_s2d xtest, Dense.Matrix.Generic.cast_s2d ytest)
let xtest_plot = xtest
Normalize data
let mean = Arr.mean ~axis:0 xtrain
let std= Arr.std ~axis:0 xtrain
let std = Arr.map (fun x -> if x = 0. then 1. else x) std
let xtrain = Arr.div (Arr.sub xtrain mean) std
let xtest = Arr.div (Arr.sub xtest mean) std
(* Extra dimensions for bias *)
let xtrain = Arr.concat_horizontal xtrain (Arr.ones [|(Arr.shape xtrain).(0);1|])
let xtest = Arr.concat_horizontal xtest (Arr.ones [|(Arr.shape xtest).(0);1|])
(* Split data in batches of size batchsize *)
let batchsize = 160
let xtrainbatches = Arr.split ~axis:0 (Array.of_list (List.init (60000 / batchsize) (fun _ -> batchsize))) xtrain
let ytrainbatches = Arr.split ~axis:0 (Array.of_list (List.init (60000 / batchsize) (fun _ -> batchsize))) ytrain
let trainbatches = List.combine (Array.to_list xtrainbatches) (Array.to_list ytrainbatches)
let xtestbatches = Arr.split ~axis:0 (Array.of_list (List.init (3200 / batchsize) (fun _ -> batchsize))) (Arr.get_slice [[0;3199];[]] xtest)
let xtestplotbatches = Arr.split ~axis:0 (Array.of_list (List.init (3200 / batchsize) (fun _ -> batchsize))) (Arr.get_slice [[0;3199];[]] xtest_plot)
let ytestbatches = Arr.split ~axis:0 (Array.of_list (List.init (3200 / batchsize) (fun _ -> batchsize))) (Arr.get_slice [[0;3199];[]] ytest)
Graph construction
let graph = Graph.empty
let graphst = GraphState.empty
let (x, graph) = graph |> Graph.placeholder (Array.to_list (Dense.Ndarray.Generic.shape xtrainbatches.(0)))
let (y, graph) = graph |> Graph.placeholder (Array.to_list (Dense.Ndarray.Generic.shape ytrainbatches.(0)))
let (loss, graph, graphst) = MnistNet.create [x;y] (MnistNet.default_name) graph graphst
let (opt, graph) = graph |> Graph.grad_descent loss 0.01
(* Load graph and graph state files *)
let graphst = GraphState.load_graphst "tests/saved-graphstates-mnist-iter-100"
(* Get Preds and Truths *)
(* Generate a random batch *)
let () = Random.init 1
let batch = Random.int (Array.length xtestbatches)
let xVal , yVal = List.hd (Array.to_list (Array.sub xtestbatches batch 1)), List.hd (Array.to_list (Array.sub ytestbatches batch 1))
let graphst = GraphState.(graphst
|> add_node x (xVal)
|> add_node y (yVal)
)
let (loss_val, graphst) = Graph.forward loss graph graphst
let smax_val = GraphState.(graphst |> get_node_by_id "MNISTNET_SOFTMAX_0")
let preds = Dense.Matrix.Generic.fold_rows (fun acc row -> let i = (snd (Arr.max_i row)).(1) in i::acc) [] smax_val
let preds = List.rev preds
let truths = Dense.Matrix.Generic.fold_rows (fun acc row -> let i = (snd (Arr.max_i row)).(1) in i::acc) [] yVal
let truths = List.rev truths
(* Plot *)
let html = ref "<html><head><title>MNIST DEMO</title><style>.row { width: 300px; float: left; }</style></head><body style='background-color:black;'><div id='rows'><h1 align='center'><font color='red'>CS 3110 TensorFlOcaml MNIST DEMO</font></h1>"
let rec demo (preds:int list) (truths:int list) (idx:int) : unit =
if idx <= (batchsize - 1) then
let z_t = Mat.get_slice [[];[0;783]] (Arr.row (xtestplotbatches.(batch)) idx) in
let z_t = Mat.reshape z_t [|28;28|] in
let filename = "demos/mnist_" ^ string_of_int idx ^ ".png" in
let imgname = "mnist_" ^ string_of_int idx ^ ".png" in
let h = Plot.create filename in
let title = "Truth : " ^ string_of_int (List.nth truths idx) ^ " Pred : " ^ string_of_int (List.nth preds idx) in
let () = Plot.set_title h title; Plot.image ~h z_t; Plot.output h in
let color = if ((List.nth truths idx) = (List.nth preds idx)) then "'white'" else "'red'" in
html := !html ^ "<div class='row'><center><img src='"^imgname^"' width='200' height='200'><p><font color="^color^">"^title^"</font></p></div></center>";
demo preds truths (idx+1)
let () = demo preds truths 0
let file = open_out "demos/demo.html"
let () = html := !html ^ "</div></body></html>"
let () = fprintf file "%s\n" !html; close_out file | null | https://raw.githubusercontent.com/wpfjtmwls/TensorFlOcaml/aa08d5da1f622e40dc0002e3879aab70b928e132/test_demo.ml | ocaml | Pull data
Extra dimensions for bias
Split data in batches of size batchsize
Load graph and graph state files
Get Preds and Truths
Generate a random batch
Plot |
Example test if one were to want to demo Tensorflowcaml
Example test if one were to want to demo Tensorflowcaml
*)
open OUnit2
open Owl
open Tfgraph
open Tfgraphst
open Mnistnet
open Random
open Printf
let xtrain, _, ytrain = Dataset.load_mnist_train_data ()
let xtrain, ytrain = (Dense.Matrix.Generic.cast_s2d xtrain, Dense.Matrix.Generic.cast_s2d ytrain)
let xtest, _, ytest = Dataset.load_mnist_test_data ()
let xtest, ytest = (Dense.Matrix.Generic.cast_s2d xtest, Dense.Matrix.Generic.cast_s2d ytest)
let xtest_plot = xtest
Normalize data
let mean = Arr.mean ~axis:0 xtrain
let std= Arr.std ~axis:0 xtrain
let std = Arr.map (fun x -> if x = 0. then 1. else x) std
let xtrain = Arr.div (Arr.sub xtrain mean) std
let xtest = Arr.div (Arr.sub xtest mean) std
let xtrain = Arr.concat_horizontal xtrain (Arr.ones [|(Arr.shape xtrain).(0);1|])
let xtest = Arr.concat_horizontal xtest (Arr.ones [|(Arr.shape xtest).(0);1|])
let batchsize = 160
let xtrainbatches = Arr.split ~axis:0 (Array.of_list (List.init (60000 / batchsize) (fun _ -> batchsize))) xtrain
let ytrainbatches = Arr.split ~axis:0 (Array.of_list (List.init (60000 / batchsize) (fun _ -> batchsize))) ytrain
let trainbatches = List.combine (Array.to_list xtrainbatches) (Array.to_list ytrainbatches)
let xtestbatches = Arr.split ~axis:0 (Array.of_list (List.init (3200 / batchsize) (fun _ -> batchsize))) (Arr.get_slice [[0;3199];[]] xtest)
let xtestplotbatches = Arr.split ~axis:0 (Array.of_list (List.init (3200 / batchsize) (fun _ -> batchsize))) (Arr.get_slice [[0;3199];[]] xtest_plot)
let ytestbatches = Arr.split ~axis:0 (Array.of_list (List.init (3200 / batchsize) (fun _ -> batchsize))) (Arr.get_slice [[0;3199];[]] ytest)
Graph construction
let graph = Graph.empty
let graphst = GraphState.empty
let (x, graph) = graph |> Graph.placeholder (Array.to_list (Dense.Ndarray.Generic.shape xtrainbatches.(0)))
let (y, graph) = graph |> Graph.placeholder (Array.to_list (Dense.Ndarray.Generic.shape ytrainbatches.(0)))
let (loss, graph, graphst) = MnistNet.create [x;y] (MnistNet.default_name) graph graphst
let (opt, graph) = graph |> Graph.grad_descent loss 0.01
let graphst = GraphState.load_graphst "tests/saved-graphstates-mnist-iter-100"
let () = Random.init 1
let batch = Random.int (Array.length xtestbatches)
let xVal , yVal = List.hd (Array.to_list (Array.sub xtestbatches batch 1)), List.hd (Array.to_list (Array.sub ytestbatches batch 1))
let graphst = GraphState.(graphst
|> add_node x (xVal)
|> add_node y (yVal)
)
let (loss_val, graphst) = Graph.forward loss graph graphst
let smax_val = GraphState.(graphst |> get_node_by_id "MNISTNET_SOFTMAX_0")
let preds = Dense.Matrix.Generic.fold_rows (fun acc row -> let i = (snd (Arr.max_i row)).(1) in i::acc) [] smax_val
let preds = List.rev preds
let truths = Dense.Matrix.Generic.fold_rows (fun acc row -> let i = (snd (Arr.max_i row)).(1) in i::acc) [] yVal
let truths = List.rev truths
let html = ref "<html><head><title>MNIST DEMO</title><style>.row { width: 300px; float: left; }</style></head><body style='background-color:black;'><div id='rows'><h1 align='center'><font color='red'>CS 3110 TensorFlOcaml MNIST DEMO</font></h1>"
let rec demo (preds:int list) (truths:int list) (idx:int) : unit =
if idx <= (batchsize - 1) then
let z_t = Mat.get_slice [[];[0;783]] (Arr.row (xtestplotbatches.(batch)) idx) in
let z_t = Mat.reshape z_t [|28;28|] in
let filename = "demos/mnist_" ^ string_of_int idx ^ ".png" in
let imgname = "mnist_" ^ string_of_int idx ^ ".png" in
let h = Plot.create filename in
let title = "Truth : " ^ string_of_int (List.nth truths idx) ^ " Pred : " ^ string_of_int (List.nth preds idx) in
let () = Plot.set_title h title; Plot.image ~h z_t; Plot.output h in
let color = if ((List.nth truths idx) = (List.nth preds idx)) then "'white'" else "'red'" in
html := !html ^ "<div class='row'><center><img src='"^imgname^"' width='200' height='200'><p><font color="^color^">"^title^"</font></p></div></center>";
demo preds truths (idx+1)
let () = demo preds truths 0
let file = open_out "demos/demo.html"
let () = html := !html ^ "</div></body></html>"
let () = fprintf file "%s\n" !html; close_out file |
151a02dacb4a4acc0669fa53129a957b3bf7dad5f608a428f301236f25ffef22 | jdreaver/eventful | DB.hs | # LANGUAGE ExistentialQuantification #
{-# LANGUAGE GADTs #-}
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE QuasiQuotes #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeFamilies #
module Cafe.DB
( openTab
, getTabUuid
, migrateTabEntity
, TabEntity (..)
, TabEntityId
, Key (..)
) where
import Control.Monad.IO.Class
import Database.Persist
import Database.Persist.Sql
import Database.Persist.TH
import Eventful
import Eventful.Store.Sqlite ()
share [mkPersist sqlSettings, mkMigrate "migrateTabEntity"] [persistLowerCase|
TabEntity sql=tabs
projectionId UUID
deriving Show
|]
-- | Opens a tab by inserting an entry into the tabs table and returning the
-- UUID.
openTab :: (MonadIO m) => SqlPersistT m (TabEntityId, UUID)
openTab = do
uuid <- liftIO uuidNextRandom
key <- insert (TabEntity uuid)
return (key, uuid)
| Given the tab i d , attempts to load the tab and return the UUID .
getTabUuid :: (MonadIO m) => TabEntityId -> SqlPersistT m (Maybe UUID)
getTabUuid tabId = fmap tabEntityProjectionId <$> get tabId
| null | https://raw.githubusercontent.com/jdreaver/eventful/3f0c604e5bb2dcf5bacf0a2e01edf6a5e9c5e22e/examples/cafe/src/Cafe/DB.hs | haskell | # LANGUAGE GADTs #
| Opens a tab by inserting an entry into the tabs table and returning the
UUID. | # LANGUAGE ExistentialQuantification #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE QuasiQuotes #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeFamilies #
module Cafe.DB
( openTab
, getTabUuid
, migrateTabEntity
, TabEntity (..)
, TabEntityId
, Key (..)
) where
import Control.Monad.IO.Class
import Database.Persist
import Database.Persist.Sql
import Database.Persist.TH
import Eventful
import Eventful.Store.Sqlite ()
share [mkPersist sqlSettings, mkMigrate "migrateTabEntity"] [persistLowerCase|
TabEntity sql=tabs
projectionId UUID
deriving Show
|]
openTab :: (MonadIO m) => SqlPersistT m (TabEntityId, UUID)
openTab = do
uuid <- liftIO uuidNextRandom
key <- insert (TabEntity uuid)
return (key, uuid)
| Given the tab i d , attempts to load the tab and return the UUID .
getTabUuid :: (MonadIO m) => TabEntityId -> SqlPersistT m (Maybe UUID)
getTabUuid tabId = fmap tabEntityProjectionId <$> get tabId
|
e9593573a1835df8abc28e583ec13f1ae3184e6c71ba548ce7c8744a07a2bf0c | abevoelker/haskellbook-solutions | sing2.hs | module Sing where
fstString :: [Char] -> [Char]
fstString x = x ++ " in the rain"
sndString :: [Char] -> [Char]
sndString x = x ++ " over the rainbow"
sing = if (x < y) then fstString x else sndString y
where x = "Singin"
y = "Somewhere"
| null | https://raw.githubusercontent.com/abevoelker/haskellbook-solutions/9e2804940b3b45bdc1b04cfa5d536097629c9498/ch5/sing2.hs | haskell | module Sing where
fstString :: [Char] -> [Char]
fstString x = x ++ " in the rain"
sndString :: [Char] -> [Char]
sndString x = x ++ " over the rainbow"
sing = if (x < y) then fstString x else sndString y
where x = "Singin"
y = "Somewhere"
| |
28f61a75061d1ae62db2c89180603b72c35c81ae331f7a9c81ead58049dfd22c | clojerl/clojerl | clojerl.reader.TaggedLiteral.erl | @private
-module('clojerl.reader.TaggedLiteral').
-include("clojerl.hrl").
-behavior('clojerl.IEquiv').
-behavior('clojerl.ILookup').
-behavior('clojerl.IStringable').
-export([?CONSTRUCTOR/2]).
-export([equiv/2]).
-export([ get/2
, get/3
]).
-export([str/1]).
-export_type([type/0]).
-type type() :: #{ ?TYPE => ?M
, tag => 'clojerl.Symbol':type()
, form => any()
}.
-spec ?CONSTRUCTOR('clojerl.Symbol':type(), any()) -> type().
?CONSTRUCTOR(Tag, Form) ->
#{ ?TYPE => ?M
, tag => Tag
, form => Form
}.
%% clojerl.IEquiv
equiv( #{?TYPE := ?M, tag := T1, form := F1}
, #{?TYPE := ?M, tag := T2, form := F2}
) ->
clj_rt:equiv(T1, T2) andalso clj_rt:equiv(F1, F2);
equiv(_, _) ->
false.
clojerl .
get(#{?TYPE := ?M} = TaggedLiteral, Key) ->
get(TaggedLiteral, Key, ?NIL).
get(#{?TYPE := ?M, tag := Tag}, tag, _) ->
Tag;
get(#{?TYPE := ?M, form := Form}, form, _) ->
Form;
get(#{?TYPE := ?M}, _, NotFound) ->
NotFound.
%% clojerl.IStringable
str(#{?TYPE := ?M, tag := Tag, form := Form}) ->
TagBin = clj_rt:str(Tag),
FormBin = clj_rt:str(Form),
<<"#", TagBin/binary, " ", FormBin/binary>>.
| null | https://raw.githubusercontent.com/clojerl/clojerl/506000465581d6349659898dd5025fa259d5cf28/src/erl/lang/clojerl.reader.TaggedLiteral.erl | erlang | clojerl.IEquiv
clojerl.IStringable | @private
-module('clojerl.reader.TaggedLiteral').
-include("clojerl.hrl").
-behavior('clojerl.IEquiv').
-behavior('clojerl.ILookup').
-behavior('clojerl.IStringable').
-export([?CONSTRUCTOR/2]).
-export([equiv/2]).
-export([ get/2
, get/3
]).
-export([str/1]).
-export_type([type/0]).
-type type() :: #{ ?TYPE => ?M
, tag => 'clojerl.Symbol':type()
, form => any()
}.
-spec ?CONSTRUCTOR('clojerl.Symbol':type(), any()) -> type().
?CONSTRUCTOR(Tag, Form) ->
#{ ?TYPE => ?M
, tag => Tag
, form => Form
}.
equiv( #{?TYPE := ?M, tag := T1, form := F1}
, #{?TYPE := ?M, tag := T2, form := F2}
) ->
clj_rt:equiv(T1, T2) andalso clj_rt:equiv(F1, F2);
equiv(_, _) ->
false.
clojerl .
get(#{?TYPE := ?M} = TaggedLiteral, Key) ->
get(TaggedLiteral, Key, ?NIL).
get(#{?TYPE := ?M, tag := Tag}, tag, _) ->
Tag;
get(#{?TYPE := ?M, form := Form}, form, _) ->
Form;
get(#{?TYPE := ?M}, _, NotFound) ->
NotFound.
str(#{?TYPE := ?M, tag := Tag, form := Form}) ->
TagBin = clj_rt:str(Tag),
FormBin = clj_rt:str(Form),
<<"#", TagBin/binary, " ", FormBin/binary>>.
|
cfa9904853876ddb5c006b459342ea815e259a853e14e47b81e7daf31cbc8e02 | ml4tp/tcoq | vm_printers.ml | open Format
open Term
open Names
open Cbytecodes
open Cemitcodes
open Vm
let ppripos (ri,pos) =
(match ri with
| Reloc_annot a ->
let sp,i = a.ci.ci_ind in
print_string
("annot : MutInd("^(string_of_mind sp)^","^(string_of_int i)^")\n")
| Reloc_const _ ->
print_string "structured constant\n"
| Reloc_getglobal kn ->
print_string ("getglob "^(string_of_con kn)^"\n"));
print_flush ()
let print_vfix () = print_string "vfix"
let print_vfix_app () = print_string "vfix_app"
let print_vswith () = print_string "switch"
let ppsort = function
| Prop(Pos) -> print_string "Set"
| Prop(Null) -> print_string "Prop"
| Type u -> print_string "Type"
let print_idkey idk =
match idk with
| ConstKey sp ->
print_string "Cons(";
print_string (string_of_con sp);
print_string ")"
| VarKey id -> print_string (Id.to_string id)
| RelKey i -> print_string "~";print_int i
let rec ppzipper z =
match z with
| Zapp args ->
let n = nargs args in
open_hbox ();
for i = 0 to n-2 do
ppvalues (arg args i);print_string ";";print_space()
done;
if n-1 >= 0 then ppvalues (arg args (n-1));
close_box()
| Zfix _ -> print_string "Zfix"
| Zswitch _ -> print_string "Zswitch"
| Zproj _ -> print_string "Zproj"
and ppstack s =
open_hovbox 0;
print_string "[";
List.iter (fun z -> ppzipper z;print_string " | ") s;
print_string "]";
close_box()
and ppatom a =
match a with
| Aid idk -> print_idkey idk
| Atype u -> print_string "Type(...)"
| Aind(sp,i) -> print_string "Ind(";
print_string (string_of_mind sp);
print_string ","; print_int i;
print_string ")"
and ppwhd whd =
match whd with
| Vsort s -> ppsort s
| Vprod _ -> print_string "product"
| Vfun _ -> print_string "function"
| Vfix _ -> print_vfix()
| Vcofix _ -> print_string "cofix"
| Vconstr_const i -> print_string "C(";print_int i;print_string")"
| Vconstr_block b -> ppvblock b
| Vatom_stk(a,s) ->
open_hbox();ppatom a;close_box();
print_string"@";ppstack s
| Vuniv_level lvl -> Feedback.msg_notice (Univ.Level.pr lvl)
and ppvblock b =
open_hbox();
print_string "Cb(";print_int (btag b);
let n = bsize b in
for i = 0 to n -1 do
print_string ",";ppvalues (bfield b i)
done;
print_string")";
close_box()
and ppvalues v =
open_hovbox 0;ppwhd (whd_val v);close_box();
print_flush()
| null | https://raw.githubusercontent.com/ml4tp/tcoq/7a78c31df480fba721648f277ab0783229c8bece/dev/vm_printers.ml | ocaml | open Format
open Term
open Names
open Cbytecodes
open Cemitcodes
open Vm
let ppripos (ri,pos) =
(match ri with
| Reloc_annot a ->
let sp,i = a.ci.ci_ind in
print_string
("annot : MutInd("^(string_of_mind sp)^","^(string_of_int i)^")\n")
| Reloc_const _ ->
print_string "structured constant\n"
| Reloc_getglobal kn ->
print_string ("getglob "^(string_of_con kn)^"\n"));
print_flush ()
let print_vfix () = print_string "vfix"
let print_vfix_app () = print_string "vfix_app"
let print_vswith () = print_string "switch"
let ppsort = function
| Prop(Pos) -> print_string "Set"
| Prop(Null) -> print_string "Prop"
| Type u -> print_string "Type"
let print_idkey idk =
match idk with
| ConstKey sp ->
print_string "Cons(";
print_string (string_of_con sp);
print_string ")"
| VarKey id -> print_string (Id.to_string id)
| RelKey i -> print_string "~";print_int i
let rec ppzipper z =
match z with
| Zapp args ->
let n = nargs args in
open_hbox ();
for i = 0 to n-2 do
ppvalues (arg args i);print_string ";";print_space()
done;
if n-1 >= 0 then ppvalues (arg args (n-1));
close_box()
| Zfix _ -> print_string "Zfix"
| Zswitch _ -> print_string "Zswitch"
| Zproj _ -> print_string "Zproj"
and ppstack s =
open_hovbox 0;
print_string "[";
List.iter (fun z -> ppzipper z;print_string " | ") s;
print_string "]";
close_box()
and ppatom a =
match a with
| Aid idk -> print_idkey idk
| Atype u -> print_string "Type(...)"
| Aind(sp,i) -> print_string "Ind(";
print_string (string_of_mind sp);
print_string ","; print_int i;
print_string ")"
and ppwhd whd =
match whd with
| Vsort s -> ppsort s
| Vprod _ -> print_string "product"
| Vfun _ -> print_string "function"
| Vfix _ -> print_vfix()
| Vcofix _ -> print_string "cofix"
| Vconstr_const i -> print_string "C(";print_int i;print_string")"
| Vconstr_block b -> ppvblock b
| Vatom_stk(a,s) ->
open_hbox();ppatom a;close_box();
print_string"@";ppstack s
| Vuniv_level lvl -> Feedback.msg_notice (Univ.Level.pr lvl)
and ppvblock b =
open_hbox();
print_string "Cb(";print_int (btag b);
let n = bsize b in
for i = 0 to n -1 do
print_string ",";ppvalues (bfield b i)
done;
print_string")";
close_box()
and ppvalues v =
open_hovbox 0;ppwhd (whd_val v);close_box();
print_flush()
| |
bdd10b288aa24adf31de7e1dfe62f30fb94dca045aba024d1dbc748c252a7809 | juspay/atlas | Kafka.hs | |
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Module : Tools . Streaming .
Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022
License : Apache 2.0 ( see the file LICENSE )
Maintainer :
Stability : experimental
Portability : non - portable
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Module : Tools.Streaming.Kafka
Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022
License : Apache 2.0 (see the file LICENSE)
Maintainer :
Stability : experimental
Portability : non-portable
-}
module Tools.Streaming.Kafka
( module Tools.Streaming.Kafka,
module Reexport,
)
where
import Beckn.Streaming.Kafka.Producer.Types as Reexport
import Beckn.Streaming.Kafka.Topic.BusinessEvent.Environment
import Beckn.Streaming.Kafka.Topic.BusinessEvent.Types as Reexport
import EulerHS.Prelude
newtype BPPKafkaEnvs = BPPKafkaEnvs
{ businessEventEnv :: KafkaBEEnv
}
deriving (Generic)
buildBPPKafkaEnvs :: IO BPPKafkaEnvs
buildBPPKafkaEnvs = do
businessEventEnv <- buildKafkaBEEnv "BPP"
return $ BPPKafkaEnvs {..}
| null | https://raw.githubusercontent.com/juspay/atlas/e64b227dc17887fb01c2554db21c08284d18a806/app/atlas-transport/src/Tools/Streaming/Kafka.hs | haskell | |
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Module : Tools . Streaming .
Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022
License : Apache 2.0 ( see the file LICENSE )
Maintainer :
Stability : experimental
Portability : non - portable
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Module : Tools.Streaming.Kafka
Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022
License : Apache 2.0 (see the file LICENSE)
Maintainer :
Stability : experimental
Portability : non-portable
-}
module Tools.Streaming.Kafka
( module Tools.Streaming.Kafka,
module Reexport,
)
where
import Beckn.Streaming.Kafka.Producer.Types as Reexport
import Beckn.Streaming.Kafka.Topic.BusinessEvent.Environment
import Beckn.Streaming.Kafka.Topic.BusinessEvent.Types as Reexport
import EulerHS.Prelude
newtype BPPKafkaEnvs = BPPKafkaEnvs
{ businessEventEnv :: KafkaBEEnv
}
deriving (Generic)
buildBPPKafkaEnvs :: IO BPPKafkaEnvs
buildBPPKafkaEnvs = do
businessEventEnv <- buildKafkaBEEnv "BPP"
return $ BPPKafkaEnvs {..}
| |
2ae1c2c1eb00b7924f7624b8db2243bd55ac179a00c33083ca0117b3ef600ff4 | kcsongor/generic-lens | Sum.hs | {-# LANGUAGE PackageImports #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Generics.Sum
Copyright : ( C ) 2020
-- License : BSD3
Maintainer : < >
-- Stability : experimental
-- Portability : non-portable
--
Magic sum operations using Generics
--
These classes need not be instantiated manually , as GHC can automatically
prove valid instances via Generics . Only the ` Generic ` class needs to
-- be derived (see examples).
--
-----------------------------------------------------------------------------
module Data.Generics.Sum
( -- *Prisms
module Data.Generics.Sum.Any
, module Data.Generics.Sum.Constructors
, module Data.Generics.Sum.Subtype
, module Data.Generics.Sum.Typed
) where
import "this" Data.Generics.Sum.Any
import "this" Data.Generics.Sum.Constructors
import "this" Data.Generics.Sum.Subtype
import "this" Data.Generics.Sum.Typed
| null | https://raw.githubusercontent.com/kcsongor/generic-lens/8e1fc7dcf444332c474fca17110d4bc554db08c8/generic-lens/src/Data/Generics/Sum.hs | haskell | # LANGUAGE PackageImports #
---------------------------------------------------------------------------
|
Module : Data.Generics.Sum
License : BSD3
Stability : experimental
Portability : non-portable
be derived (see examples).
---------------------------------------------------------------------------
*Prisms | Copyright : ( C ) 2020
Maintainer : < >
Magic sum operations using Generics
These classes need not be instantiated manually , as GHC can automatically
prove valid instances via Generics . Only the ` Generic ` class needs to
module Data.Generics.Sum
module Data.Generics.Sum.Any
, module Data.Generics.Sum.Constructors
, module Data.Generics.Sum.Subtype
, module Data.Generics.Sum.Typed
) where
import "this" Data.Generics.Sum.Any
import "this" Data.Generics.Sum.Constructors
import "this" Data.Generics.Sum.Subtype
import "this" Data.Generics.Sum.Typed
|
787bf278cc4fed613c3eb9b2da3ec1423cac8afdf07df1bbda9d5d4b94cca12e | the-dr-lazy/cascade | ProjectTable.hs | |
Module : Cascade . Api . Database . ProjectTable
Description : ! ! ! INSERT MODULE SHORT DESCRIPTION ! ! !
Copyright : ( c ) 2020 - 2021 Cascade
License : MPL 2.0
Maintainer : < > ( the-dr-lazy.github.io )
Stability : Stable
Portability : POSIX
! ! ! INSERT MODULE LONG DESCRIPTION ! ! !
Module : Cascade.Api.Database.ProjectTable
Description : !!! INSERT MODULE SHORT DESCRIPTION !!!
Copyright : (c) 2020-2021 Cascade
License : MPL 2.0
Maintainer : Mohammad Hasani <> (the-dr-lazy.github.io)
Stability : Stable
Portability : POSIX
!!! INSERT MODULE LONG DESCRIPTION !!!
-}
module Cascade.Api.Database.ProjectTable
( PrimaryKey (..)
, ProjectTable (..)
, Row
) where
import qualified Cascade.Api.Data.Project as Project
import qualified Cascade.Api.Data.WrappedC as Wrapped
import Data.Generics.Labels ()
import Database.Beam ( Beamable, C, PrimaryKey, Table (..) )
data ProjectTable (f :: Type -> Type) = Row { id :: Wrapped.C f Project.Id
, name :: C f Text
}
deriving stock (Generic)
deriving anyclass (Beamable)
instance Table ProjectTable where
newtype PrimaryKey ProjectTable f = PrimaryKey
{ unPrimaryKey :: Wrapped.C f Project.Id
}
deriving stock Generic
deriving anyclass Beamable
primaryKey = PrimaryKey . id
deriving stock instance Show (PrimaryKey ProjectTable Identity)
deriving stock instance Eq (PrimaryKey ProjectTable Identity)
type Row = ProjectTable Identity
deriving stock instance Show Row
deriving stock instance Eq Row
| null | https://raw.githubusercontent.com/the-dr-lazy/cascade/014a5589a2763ce373e8c84a211cddc479872b44/cascade-api/src/Cascade/Api/Database/ProjectTable.hs | haskell | |
Module : Cascade . Api . Database . ProjectTable
Description : ! ! ! INSERT MODULE SHORT DESCRIPTION ! ! !
Copyright : ( c ) 2020 - 2021 Cascade
License : MPL 2.0
Maintainer : < > ( the-dr-lazy.github.io )
Stability : Stable
Portability : POSIX
! ! ! INSERT MODULE LONG DESCRIPTION ! ! !
Module : Cascade.Api.Database.ProjectTable
Description : !!! INSERT MODULE SHORT DESCRIPTION !!!
Copyright : (c) 2020-2021 Cascade
License : MPL 2.0
Maintainer : Mohammad Hasani <> (the-dr-lazy.github.io)
Stability : Stable
Portability : POSIX
!!! INSERT MODULE LONG DESCRIPTION !!!
-}
module Cascade.Api.Database.ProjectTable
( PrimaryKey (..)
, ProjectTable (..)
, Row
) where
import qualified Cascade.Api.Data.Project as Project
import qualified Cascade.Api.Data.WrappedC as Wrapped
import Data.Generics.Labels ()
import Database.Beam ( Beamable, C, PrimaryKey, Table (..) )
data ProjectTable (f :: Type -> Type) = Row { id :: Wrapped.C f Project.Id
, name :: C f Text
}
deriving stock (Generic)
deriving anyclass (Beamable)
instance Table ProjectTable where
newtype PrimaryKey ProjectTable f = PrimaryKey
{ unPrimaryKey :: Wrapped.C f Project.Id
}
deriving stock Generic
deriving anyclass Beamable
primaryKey = PrimaryKey . id
deriving stock instance Show (PrimaryKey ProjectTable Identity)
deriving stock instance Eq (PrimaryKey ProjectTable Identity)
type Row = ProjectTable Identity
deriving stock instance Show Row
deriving stock instance Eq Row
| |
a18dbe08969d19f5b5a8a09d155578d8367fb6bbe81b5360617e097e1a736cc3 | heraldry/heraldicon | status.cljs | (ns heraldicon.frontend.status
(:require
[heraldicon.frontend.language :refer [tr]]))
(defn loading []
[:div [tr :string.miscellaneous/loading]])
(defn not-found []
[:div [tr :string.miscellaneous/not-found]])
(defn error-display [_error]
[:div [tr :string.miscellaneous/error]])
(defn default [subscription on-done & {:keys [on-error
on-default]
:or {on-error error-display
on-default loading}}]
(let [{:keys [status error] :as result} @subscription]
(case status
:done [on-done result]
:error [on-error error]
[on-default])))
| null | https://raw.githubusercontent.com/heraldry/heraldicon/4a4d7c860fbe5bed8b0a16acef428b186e27199b/src/heraldicon/frontend/status.cljs | clojure | (ns heraldicon.frontend.status
(:require
[heraldicon.frontend.language :refer [tr]]))
(defn loading []
[:div [tr :string.miscellaneous/loading]])
(defn not-found []
[:div [tr :string.miscellaneous/not-found]])
(defn error-display [_error]
[:div [tr :string.miscellaneous/error]])
(defn default [subscription on-done & {:keys [on-error
on-default]
:or {on-error error-display
on-default loading}}]
(let [{:keys [status error] :as result} @subscription]
(case status
:done [on-done result]
:error [on-error error]
[on-default])))
| |
a4859cd18499cf8b39472401fd188476eb6ad4f7eb61dd6d05033c08c80683c7 | jaredly/unison.rs | stdlib.scm | (import (chicken bitwise))
(import (chicken condition))
(import json)
(require-extension utf8)
(define true #t)
(define false #f)
(define (term-link v) (list 'term-link v))
(define (type-link v) (list 'type-link v))
(define (untuple term)
(if (and (list? term)
(= (length term) 3)
(equal? (car term) 'onbcm0qctbnuctpm57tkc5p16b8gfke8thjf19p4r4laokji0b606rd0frnhj103qb90lve3fohkoc1eda70491hot656s1m6kk3cn0_0))
(cons (cadr term) (untuple (caddr term)))
(if (equal? term Nil)
'()
term)))
(define (to-json v)
(let ((o (open-output-string)))
(json-write v o)
(get-output-string o)
))
(define (Debug.watch text)
(lambda (v)
(print "⚠️ " text " " (to-json (untuple v)))
v))
(define (bug v)
(print "BUG " (to-json (untuple v)))
(abort "Found a bug!")
)
(define (print-processing name)
;; Uncomment this line to debug terms that are failing to process
; (print "Evaluating " name)
'())
(define (check v name)
(if (not v)
(begin
(print "❌ Test failed! " name)
(print "Got " v)
; (print "Test failure")
)
; (print "✅ passed " name)
)
)
(define (result-is-good result)
(and (list? result)
(= (length result) 2)
(equal? (car result) 'vmc06s4f236sps61vqv35g7ridnae03uetth98aocort1825stbv7m6ncfca2j0gcane47c8db2rjtd2o6kch2lr7v2gst895pcs0m0_1)
)
)
(define (check-results v name)
(if (not (foldl
(lambda (current result)
(or (if (not (result-is-good result))
(begin
(print "❌ Test failed " name " " (to-json result))
; (abort "Test failed")
#t
) #f) current))
#f
(vector->list v)
))
; (print "✅ passed " name)
'()
)
'()
)
(define (f2c22r2a1sche28mn07brk1j45kp1bam3tr4k2j0un2hi1g7rbrud3f5mes2defqo1tpd9j38pqpg2f0efl3no0ede5ocl2am4bonm0 a)
(lambda (b) (not (equal? a b)))
)
GUID
(define (rc29vdqe019p56kupcgkg07fkib86r3oooatbmsgfbdsgpmjhsh00l307iuts3r973q5etb61vbjkes42b6adb3mkorusvmudiuorno_0 id)
(list 'rc29vdqe019p56kupcgkg07fkib86r3oooatbmsgfbdsgpmjhsh00l307iuts3r973q5etb61vbjkes42b6adb3mkorusvmudiuorno_0 id))
(define (Bytes.fromList bytes) bytes) ; yolo
; base.Map
(define (7di5ureqgi60ue42886240kbovfhko0fg85rp2thpkl8af699upsl0os1btk27te1cjdmuerad5oi9bdd04me6mjh2m25djbj236fbo_0 k)
(lambda (v) (list '7di5ureqgi60ue42886240kbovfhko0fg85rp2thpkl8af699upsl0os1btk27te1cjdmuerad5oi9bdd04me6mjh2m25djbj236fbo_0 k v)))
Cons / Nil
(define (onbcm0qctbnuctpm57tkc5p16b8gfke8thjf19p4r4laokji0b606rd0frnhj103qb90lve3fohkoc1eda70491hot656s1m6kk3cn0_0 one)
(lambda (two) (list 'onbcm0qctbnuctpm57tkc5p16b8gfke8thjf19p4r4laokji0b606rd0frnhj103qb90lve3fohkoc1eda70491hot656s1m6kk3cn0_0 one two)))
(define 568rsi7o3ghq8mmbea2sf8msdk20ohasob5s2rvjtqg2lr0vs39l1hm98urrjemsr3vo3fa52pibqu0maluq7g8sfg3h5f5re6vitj8_0
'568rsi7o3ghq8mmbea2sf8msdk20ohasob5s2rvjtqg2lr0vs39l1hm98urrjemsr3vo3fa52pibqu0maluq7g8sfg3h5f5re6vitj8_0)
(define Cons onbcm0qctbnuctpm57tkc5p16b8gfke8thjf19p4r4laokji0b606rd0frnhj103qb90lve3fohkoc1eda70491hot656s1m6kk3cn0_0 )
(define Nil 568rsi7o3ghq8mmbea2sf8msdk20ohasob5s2rvjtqg2lr0vs39l1hm98urrjemsr3vo3fa52pibqu0maluq7g8sfg3h5f5re6vitj8_0)
; Some/None
(define 5isltsdct9fhcrvud9gju8u0l9g0k9d3lelkksea3a8jdgs1uqrs5mm9p7bajj84gg8l9c9jgv9honakghmkb28fucoeb2p4v9ukmu8_0
'5isltsdct9fhcrvud9gju8u0l9g0k9d3lelkksea3a8jdgs1uqrs5mm9p7bajj84gg8l9c9jgv9honakghmkb28fucoeb2p4v9ukmu8_0)
(define (5isltsdct9fhcrvud9gju8u0l9g0k9d3lelkksea3a8jdgs1uqrs5mm9p7bajj84gg8l9c9jgv9honakghmkb28fucoeb2p4v9ukmu8_1 arg)
(list '5isltsdct9fhcrvud9gju8u0l9g0k9d3lelkksea3a8jdgs1uqrs5mm9p7bajj84gg8l9c9jgv9honakghmkb28fucoeb2p4v9ukmu8_1 arg))
(define None 5isltsdct9fhcrvud9gju8u0l9g0k9d3lelkksea3a8jdgs1uqrs5mm9p7bajj84gg8l9c9jgv9honakghmkb28fucoeb2p4v9ukmu8_0)
(define Some 5isltsdct9fhcrvud9gju8u0l9g0k9d3lelkksea3a8jdgs1uqrs5mm9p7bajj84gg8l9c9jgv9honakghmkb28fucoeb2p4v9ukmu8_1)
(define (m7uplgfko92kqdmm6u898j5h4n86587f44u7fq1vjcad1f68n35r8j2mdfdbjta5hq9o699dgn2aphteditp30g34hsh3gru68593j0 a)
(lambda (b) (- a b)))
(define (Nat.drop a)
(lambda (b)
(max 0 (- a b))))
(define (Nat.+ a)
(lambda (b)
(if (not (number? a))
(begin
(print "A is " a " " (symbol? a) " " (string? a))
(abort "a is not a number")
)
)
(natLoop (+ a b))))
(define (natLoop num)
(if (> num maxNat) (- num 1 maxNat) num))
(define (intLoop num)
(if (> num maxInt)
(+ minInt (- num 1 maxInt))
(if (< num minInt)
(+ maxInt (- num -1 minInt))
num
)
))
(define maxNat 18446744073709551615)
(define maxInt +9223372036854775807)
(define s9h25aadei68iscfiu60eldfhe9uvh0pk3knd9m965gqlejvc5jlcqs9gfcgpgvfv85n2pefvee4ca2n7mepcoqamou73g7ilscf450
maxNat)
(define p9og3s2h41natoslfjoi1do0omp82s4jiethebfd4j5p99ltbdmcua2egbiehs9tq9k65744cvugibiqdkgip21t7se4e8faktnl3k0
-9223372036854775808)
(define d75vubeoep5o8ph72v0v9qdm36n17up0d7bsbdckjapcs7k9g1kv5mnbpp3444u8fmvo2h3benmk7o3sd09g1lkrrvk4q93vv8u2n3g
maxInt)
(define minInt p9og3s2h41natoslfjoi1do0omp82s4jiethebfd4j5p99ltbdmcua2egbiehs9tq9k65744cvugibiqdkgip21t7se4e8faktnl3k0)
(define (Nat.xor a)
(lambda (b) (bitwise-xor a b)))
(define (Nat.pow a)
(lambda (b) (expt a b)))
(define (Float.* a) (lambda (b) (* a b)))
(define (Float./ a) (lambda (b) (/ a (exact->inexact b))))
(define (Float.- a) (lambda (b) (- a b)))
(define (Float.+ a) (lambda (b) (+ a b)))
(define (Float.fromText a)
(let ((v (string->number a)))
(if (equal? #f v)
None
(Some (exact->inexact v))
)
))
(define Int.toFloat exact->inexact)
(define (Float.truncate v) (inexact->exact (floor v)))
; (exact->inexact v)
; )
(define Boolean.not not)
(define (Int.- a)
(lambda (b)
(intLoop (- a b))))
(define (Int.+ a)
(lambda (b)
(intLoop (+ a b))))
(define (Nat.* a)
(lambda (b)
(* a b)))
(define (Nat.or a)
(lambda (b)
(bitwise-ior a b)))
(define (Nat.and a)
(lambda (b)
(bitwise-and a b)))
(define (Nat.shiftLeft a)
(lambda (b)
(bitwise-and (arithmetic-shift a b) maxNat)))
(define (Nat.shiftRight a)
(lambda (b)
(arithmetic-shift a (- b))))
(define (Int.toText n)
(if (>= n 0)
(string-append "+" (number->string n))
(number->string n)
))
(define Int.isEven even?)
(define Int.isOdd odd?)
(define (Int.pow a) (lambda (b) (expt a b)))
(define (Int.mod a) (lambda (b) (modulo a b)))
(define (Int.complement a) (bitwise-not a))
(define (Int.truncate0 a) (max 0 a))
(define (Nat.complement a) (- maxNat a))
(define (Int.or a) (lambda (b) (bitwise-ior a b)))
(define (Int.and a) (lambda (b) (bitwise-and a b)))
(define (Int.xor a) (lambda (b) (bitwise-xor a b)))
(define (Int.increment a) (+ a 1))
(define (Int.decrement a) (- a 1))
(define (Int./ a) (lambda (b) (quotient a b)))
(define (Int.* a) (lambda (b) (* a b)))
(define (Int.negate a) (- a))
(define Nat.toText number->string)
(define (Nat.toInt x) x)
(define (Nat.sub a) (lambda (b) (- a b)))
(define Nat.isEven even?)
(define Nat.isOdd odd?)
(define (Nat.mod a) (lambda (b) (modulo a b)))
(define (Nat.increment a) (natLoop (+ a 1)))
(define (Nat.decrement a) (max 0 (- a 1)))
(define (Nat./ a) (lambda (b) (floor (/ a b))))
(define (Nat.* a) (lambda (b) (* a b)))
(define (Int.shiftLeft a)
(lambda (b)
(arithmetic-shift a b)))
(define (Int.shiftRight a)
(lambda (b)
(arithmetic-shift a (- b))))
(import srfi-67)
(import srfi-128)
(define default-comparator (make-default-comparator))
(define (Universal.> a) (lambda (b) (>? default-comparator a b)))
(define (Universal.>= a) (lambda (b) (>=? default-comparator a b)))
(define (Universal.<= a) (lambda (b) (<=? default-comparator a b)))
(define (Universal.< a) (lambda (b) (<? default-comparator a b)))
(define (Universal.== a) (lambda (b) (=? default-comparator a b)))
(define (Universal.compare a) (lambda (b) (comparator-if<=> default-comparator a b -1 0 1)))
; --- lists ---
;; using vectors
(import srfi-133)
(define List.size vector-length)
(define (List.cons item) (lambda (vec)
(let ((dest (make-vector (+ 1 (vector-length vec)))))
(vector-copy! dest 1 vec)
(vector-set! dest 0 item)
dest)))
(define (List.snoc vec) (lambda (item)
(let ((dest (make-vector (+ 1 (vector-length vec)))))
(vector-copy! dest 0 vec)
(vector-set! dest (vector-length vec) item)
dest)))
(define (List.++ a) (lambda (b) (vector-append a b)))
(define (List.drop count) (lambda (vec)
(let ((count (min (vector-length vec) count)))
(let ((ln (- (vector-length vec) count)))
(let ((dest (make-vector ln)))
(vector-copy! dest 0 vec count)
dest)))))
(define (List.at a) (lambda (b)
(if (< a (vector-length b))
(Some (vector-ref b a))
None)))
(define (List.take ln) (lambda (vec)
(let ((ln_ (min ln (vector-length vec))))
(let ((dest (make-vector ln_)))
(vector-copy! dest 0 vec 0 ln_)
dest))))
;; using linked lists
( define List.size length )
( define List.cons cons )
; (define (List.++ a) (lambda (b) (append a b)))
( define ( List.drop a ) ( lambda ( b ) ( list - tail b a ) ) )
; (define (List.at a) (lambda (b) (list-ref b a)))
; --- text stdlib ---
(define (Text.fromCharList lst)
(apply string (vector->list lst)))
(define (Text.toCharList text)
(list->vector (string->list text))
)
(define Char.fromNat integer->char)
(define Char.toNat char->integer)
(define (Text.uncons t)
(if (> (string-length t) 0)
(Some
(
(Cons (string-ref t 0))
((Cons (substring t 1)) Nil)
)
)
None
)
)
(define (Text.!= a) (lambda (b) (not (equal? a b))))
(define (Text.++ a) (lambda (b) (string-append a b)))
(define Text.size string-length)
(define (Text.take count) (lambda (str)
(let ((count (min count (string-length str))))
(substring str 0 count))))
(define (Text.drop count) (lambda (str)
(let ((count (min count (string-length str))))
(substring str count))))
; --- abilties ---
;;; Ok, so basic idea:
;;; We maintain a stack of handlers
;;; and if you fall through an evaluation, then the handler gets put back on the stack.
;;; and if you add a handler, it gets added at the place where the handler stack pointer is at.
;;;
;;; but when you call the continuation, we reset the pointer to the top, right?
;; Ok, nother stress test.
;; While we're partway down the handler stack, do a jump down & back & stuff.
;; how do we deal?
;;
;; So like, what if the `k` continuation to jump back just keeps track of the handlers to put back on the handler stack?
;; that way, we can handle nested jumps & back.
;;
;; Yeah that's a much better setup.
(load "std-abilities2.scm") | null | https://raw.githubusercontent.com/jaredly/unison.rs/78e660aae7f77b96e373efdd65f7d5d8da4822c3/chicken/stdlib.scm | scheme | Uncomment this line to debug terms that are failing to process
(print "Evaluating " name)
(print "Test failure")
(print "✅ passed " name)
(abort "Test failed")
(print "✅ passed " name)
yolo
base.Map
Some/None
(exact->inexact v)
)
--- lists ---
using vectors
using linked lists
(define (List.++ a) (lambda (b) (append a b)))
(define (List.at a) (lambda (b) (list-ref b a)))
--- text stdlib ---
--- abilties ---
Ok, so basic idea:
We maintain a stack of handlers
and if you fall through an evaluation, then the handler gets put back on the stack.
and if you add a handler, it gets added at the place where the handler stack pointer is at.
but when you call the continuation, we reset the pointer to the top, right?
Ok, nother stress test.
While we're partway down the handler stack, do a jump down & back & stuff.
how do we deal?
So like, what if the `k` continuation to jump back just keeps track of the handlers to put back on the handler stack?
that way, we can handle nested jumps & back.
Yeah that's a much better setup. | (import (chicken bitwise))
(import (chicken condition))
(import json)
(require-extension utf8)
(define true #t)
(define false #f)
(define (term-link v) (list 'term-link v))
(define (type-link v) (list 'type-link v))
(define (untuple term)
(if (and (list? term)
(= (length term) 3)
(equal? (car term) 'onbcm0qctbnuctpm57tkc5p16b8gfke8thjf19p4r4laokji0b606rd0frnhj103qb90lve3fohkoc1eda70491hot656s1m6kk3cn0_0))
(cons (cadr term) (untuple (caddr term)))
(if (equal? term Nil)
'()
term)))
(define (to-json v)
(let ((o (open-output-string)))
(json-write v o)
(get-output-string o)
))
(define (Debug.watch text)
(lambda (v)
(print "⚠️ " text " " (to-json (untuple v)))
v))
(define (bug v)
(print "BUG " (to-json (untuple v)))
(abort "Found a bug!")
)
(define (print-processing name)
'())
(define (check v name)
(if (not v)
(begin
(print "❌ Test failed! " name)
(print "Got " v)
)
)
)
(define (result-is-good result)
(and (list? result)
(= (length result) 2)
(equal? (car result) 'vmc06s4f236sps61vqv35g7ridnae03uetth98aocort1825stbv7m6ncfca2j0gcane47c8db2rjtd2o6kch2lr7v2gst895pcs0m0_1)
)
)
(define (check-results v name)
(if (not (foldl
(lambda (current result)
(or (if (not (result-is-good result))
(begin
(print "❌ Test failed " name " " (to-json result))
#t
) #f) current))
#f
(vector->list v)
))
'()
)
'()
)
(define (f2c22r2a1sche28mn07brk1j45kp1bam3tr4k2j0un2hi1g7rbrud3f5mes2defqo1tpd9j38pqpg2f0efl3no0ede5ocl2am4bonm0 a)
(lambda (b) (not (equal? a b)))
)
GUID
(define (rc29vdqe019p56kupcgkg07fkib86r3oooatbmsgfbdsgpmjhsh00l307iuts3r973q5etb61vbjkes42b6adb3mkorusvmudiuorno_0 id)
(list 'rc29vdqe019p56kupcgkg07fkib86r3oooatbmsgfbdsgpmjhsh00l307iuts3r973q5etb61vbjkes42b6adb3mkorusvmudiuorno_0 id))
(define (7di5ureqgi60ue42886240kbovfhko0fg85rp2thpkl8af699upsl0os1btk27te1cjdmuerad5oi9bdd04me6mjh2m25djbj236fbo_0 k)
(lambda (v) (list '7di5ureqgi60ue42886240kbovfhko0fg85rp2thpkl8af699upsl0os1btk27te1cjdmuerad5oi9bdd04me6mjh2m25djbj236fbo_0 k v)))
Cons / Nil
(define (onbcm0qctbnuctpm57tkc5p16b8gfke8thjf19p4r4laokji0b606rd0frnhj103qb90lve3fohkoc1eda70491hot656s1m6kk3cn0_0 one)
(lambda (two) (list 'onbcm0qctbnuctpm57tkc5p16b8gfke8thjf19p4r4laokji0b606rd0frnhj103qb90lve3fohkoc1eda70491hot656s1m6kk3cn0_0 one two)))
(define 568rsi7o3ghq8mmbea2sf8msdk20ohasob5s2rvjtqg2lr0vs39l1hm98urrjemsr3vo3fa52pibqu0maluq7g8sfg3h5f5re6vitj8_0
'568rsi7o3ghq8mmbea2sf8msdk20ohasob5s2rvjtqg2lr0vs39l1hm98urrjemsr3vo3fa52pibqu0maluq7g8sfg3h5f5re6vitj8_0)
(define Cons onbcm0qctbnuctpm57tkc5p16b8gfke8thjf19p4r4laokji0b606rd0frnhj103qb90lve3fohkoc1eda70491hot656s1m6kk3cn0_0 )
(define Nil 568rsi7o3ghq8mmbea2sf8msdk20ohasob5s2rvjtqg2lr0vs39l1hm98urrjemsr3vo3fa52pibqu0maluq7g8sfg3h5f5re6vitj8_0)
(define 5isltsdct9fhcrvud9gju8u0l9g0k9d3lelkksea3a8jdgs1uqrs5mm9p7bajj84gg8l9c9jgv9honakghmkb28fucoeb2p4v9ukmu8_0
'5isltsdct9fhcrvud9gju8u0l9g0k9d3lelkksea3a8jdgs1uqrs5mm9p7bajj84gg8l9c9jgv9honakghmkb28fucoeb2p4v9ukmu8_0)
(define (5isltsdct9fhcrvud9gju8u0l9g0k9d3lelkksea3a8jdgs1uqrs5mm9p7bajj84gg8l9c9jgv9honakghmkb28fucoeb2p4v9ukmu8_1 arg)
(list '5isltsdct9fhcrvud9gju8u0l9g0k9d3lelkksea3a8jdgs1uqrs5mm9p7bajj84gg8l9c9jgv9honakghmkb28fucoeb2p4v9ukmu8_1 arg))
(define None 5isltsdct9fhcrvud9gju8u0l9g0k9d3lelkksea3a8jdgs1uqrs5mm9p7bajj84gg8l9c9jgv9honakghmkb28fucoeb2p4v9ukmu8_0)
(define Some 5isltsdct9fhcrvud9gju8u0l9g0k9d3lelkksea3a8jdgs1uqrs5mm9p7bajj84gg8l9c9jgv9honakghmkb28fucoeb2p4v9ukmu8_1)
(define (m7uplgfko92kqdmm6u898j5h4n86587f44u7fq1vjcad1f68n35r8j2mdfdbjta5hq9o699dgn2aphteditp30g34hsh3gru68593j0 a)
(lambda (b) (- a b)))
(define (Nat.drop a)
(lambda (b)
(max 0 (- a b))))
(define (Nat.+ a)
(lambda (b)
(if (not (number? a))
(begin
(print "A is " a " " (symbol? a) " " (string? a))
(abort "a is not a number")
)
)
(natLoop (+ a b))))
(define (natLoop num)
(if (> num maxNat) (- num 1 maxNat) num))
(define (intLoop num)
(if (> num maxInt)
(+ minInt (- num 1 maxInt))
(if (< num minInt)
(+ maxInt (- num -1 minInt))
num
)
))
(define maxNat 18446744073709551615)
(define maxInt +9223372036854775807)
(define s9h25aadei68iscfiu60eldfhe9uvh0pk3knd9m965gqlejvc5jlcqs9gfcgpgvfv85n2pefvee4ca2n7mepcoqamou73g7ilscf450
maxNat)
(define p9og3s2h41natoslfjoi1do0omp82s4jiethebfd4j5p99ltbdmcua2egbiehs9tq9k65744cvugibiqdkgip21t7se4e8faktnl3k0
-9223372036854775808)
(define d75vubeoep5o8ph72v0v9qdm36n17up0d7bsbdckjapcs7k9g1kv5mnbpp3444u8fmvo2h3benmk7o3sd09g1lkrrvk4q93vv8u2n3g
maxInt)
(define minInt p9og3s2h41natoslfjoi1do0omp82s4jiethebfd4j5p99ltbdmcua2egbiehs9tq9k65744cvugibiqdkgip21t7se4e8faktnl3k0)
(define (Nat.xor a)
(lambda (b) (bitwise-xor a b)))
(define (Nat.pow a)
(lambda (b) (expt a b)))
(define (Float.* a) (lambda (b) (* a b)))
(define (Float./ a) (lambda (b) (/ a (exact->inexact b))))
(define (Float.- a) (lambda (b) (- a b)))
(define (Float.+ a) (lambda (b) (+ a b)))
(define (Float.fromText a)
(let ((v (string->number a)))
(if (equal? #f v)
None
(Some (exact->inexact v))
)
))
(define Int.toFloat exact->inexact)
(define (Float.truncate v) (inexact->exact (floor v)))
(define Boolean.not not)
(define (Int.- a)
(lambda (b)
(intLoop (- a b))))
(define (Int.+ a)
(lambda (b)
(intLoop (+ a b))))
(define (Nat.* a)
(lambda (b)
(* a b)))
(define (Nat.or a)
(lambda (b)
(bitwise-ior a b)))
(define (Nat.and a)
(lambda (b)
(bitwise-and a b)))
(define (Nat.shiftLeft a)
(lambda (b)
(bitwise-and (arithmetic-shift a b) maxNat)))
(define (Nat.shiftRight a)
(lambda (b)
(arithmetic-shift a (- b))))
(define (Int.toText n)
(if (>= n 0)
(string-append "+" (number->string n))
(number->string n)
))
(define Int.isEven even?)
(define Int.isOdd odd?)
(define (Int.pow a) (lambda (b) (expt a b)))
(define (Int.mod a) (lambda (b) (modulo a b)))
(define (Int.complement a) (bitwise-not a))
(define (Int.truncate0 a) (max 0 a))
(define (Nat.complement a) (- maxNat a))
(define (Int.or a) (lambda (b) (bitwise-ior a b)))
(define (Int.and a) (lambda (b) (bitwise-and a b)))
(define (Int.xor a) (lambda (b) (bitwise-xor a b)))
(define (Int.increment a) (+ a 1))
(define (Int.decrement a) (- a 1))
(define (Int./ a) (lambda (b) (quotient a b)))
(define (Int.* a) (lambda (b) (* a b)))
(define (Int.negate a) (- a))
(define Nat.toText number->string)
(define (Nat.toInt x) x)
(define (Nat.sub a) (lambda (b) (- a b)))
(define Nat.isEven even?)
(define Nat.isOdd odd?)
(define (Nat.mod a) (lambda (b) (modulo a b)))
(define (Nat.increment a) (natLoop (+ a 1)))
(define (Nat.decrement a) (max 0 (- a 1)))
(define (Nat./ a) (lambda (b) (floor (/ a b))))
(define (Nat.* a) (lambda (b) (* a b)))
(define (Int.shiftLeft a)
(lambda (b)
(arithmetic-shift a b)))
(define (Int.shiftRight a)
(lambda (b)
(arithmetic-shift a (- b))))
(import srfi-67)
(import srfi-128)
(define default-comparator (make-default-comparator))
(define (Universal.> a) (lambda (b) (>? default-comparator a b)))
(define (Universal.>= a) (lambda (b) (>=? default-comparator a b)))
(define (Universal.<= a) (lambda (b) (<=? default-comparator a b)))
(define (Universal.< a) (lambda (b) (<? default-comparator a b)))
(define (Universal.== a) (lambda (b) (=? default-comparator a b)))
(define (Universal.compare a) (lambda (b) (comparator-if<=> default-comparator a b -1 0 1)))
(import srfi-133)
(define List.size vector-length)
(define (List.cons item) (lambda (vec)
(let ((dest (make-vector (+ 1 (vector-length vec)))))
(vector-copy! dest 1 vec)
(vector-set! dest 0 item)
dest)))
(define (List.snoc vec) (lambda (item)
(let ((dest (make-vector (+ 1 (vector-length vec)))))
(vector-copy! dest 0 vec)
(vector-set! dest (vector-length vec) item)
dest)))
(define (List.++ a) (lambda (b) (vector-append a b)))
(define (List.drop count) (lambda (vec)
(let ((count (min (vector-length vec) count)))
(let ((ln (- (vector-length vec) count)))
(let ((dest (make-vector ln)))
(vector-copy! dest 0 vec count)
dest)))))
(define (List.at a) (lambda (b)
(if (< a (vector-length b))
(Some (vector-ref b a))
None)))
(define (List.take ln) (lambda (vec)
(let ((ln_ (min ln (vector-length vec))))
(let ((dest (make-vector ln_)))
(vector-copy! dest 0 vec 0 ln_)
dest))))
( define List.size length )
( define List.cons cons )
( define ( List.drop a ) ( lambda ( b ) ( list - tail b a ) ) )
(define (Text.fromCharList lst)
(apply string (vector->list lst)))
(define (Text.toCharList text)
(list->vector (string->list text))
)
(define Char.fromNat integer->char)
(define Char.toNat char->integer)
(define (Text.uncons t)
(if (> (string-length t) 0)
(Some
(
(Cons (string-ref t 0))
((Cons (substring t 1)) Nil)
)
)
None
)
)
(define (Text.!= a) (lambda (b) (not (equal? a b))))
(define (Text.++ a) (lambda (b) (string-append a b)))
(define Text.size string-length)
(define (Text.take count) (lambda (str)
(let ((count (min count (string-length str))))
(substring str 0 count))))
(define (Text.drop count) (lambda (str)
(let ((count (min count (string-length str))))
(substring str count))))
(load "std-abilities2.scm") |
e3af8834705e455c7aaf5cd0b103a97a0acf8fbd25b7a5c919875512904b2c4d | RyanGlScott/text-show | Bool.hs | # LANGUAGE TemplateHaskell #
# OPTIONS_GHC -fno - warn - orphans #
|
Module : TextShow . Data . Bool
Copyright : ( C ) 2014 - 2017
License : BSD - style ( see the file LICENSE )
Maintainer :
Stability : Provisional
Portability : GHC
' TextShow ' instance for ' ' .
/Since : 2/
Module: TextShow.Data.Bool
Copyright: (C) 2014-2017 Ryan Scott
License: BSD-style (see the file LICENSE)
Maintainer: Ryan Scott
Stability: Provisional
Portability: GHC
'TextShow' instance for 'Bool'.
/Since: 2/
-}
module TextShow.Data.Bool () where
import TextShow.TH.Internal (deriveTextShow)
| /Since : 2/
$(deriveTextShow ''Bool)
| null | https://raw.githubusercontent.com/RyanGlScott/text-show/5ea297d0c7ae2d043f000c791cc12ac53f469944/src/TextShow/Data/Bool.hs | haskell | # LANGUAGE TemplateHaskell #
# OPTIONS_GHC -fno - warn - orphans #
|
Module : TextShow . Data . Bool
Copyright : ( C ) 2014 - 2017
License : BSD - style ( see the file LICENSE )
Maintainer :
Stability : Provisional
Portability : GHC
' TextShow ' instance for ' ' .
/Since : 2/
Module: TextShow.Data.Bool
Copyright: (C) 2014-2017 Ryan Scott
License: BSD-style (see the file LICENSE)
Maintainer: Ryan Scott
Stability: Provisional
Portability: GHC
'TextShow' instance for 'Bool'.
/Since: 2/
-}
module TextShow.Data.Bool () where
import TextShow.TH.Internal (deriveTextShow)
| /Since : 2/
$(deriveTextShow ''Bool)
| |
ed6b18f7d96ca213bf47d5335a479ff46f334f1c7d714811f769ca6d2649ffba | clojure-interop/google-cloud-clients | core.clj | (ns com.google.cloud.redis.v1beta1.core
(:refer-clojure :only [require comment defn ->])
(:import ))
(require '[com.google.cloud.redis.v1beta1.CloudRedisClient$ListInstancesFixedSizeCollection])
(require '[com.google.cloud.redis.v1beta1.CloudRedisClient$ListInstancesPage])
(require '[com.google.cloud.redis.v1beta1.CloudRedisClient$ListInstancesPagedResponse])
(require '[com.google.cloud.redis.v1beta1.CloudRedisClient])
(require '[com.google.cloud.redis.v1beta1.CloudRedisSettings$Builder])
(require '[com.google.cloud.redis.v1beta1.CloudRedisSettings])
| null | https://raw.githubusercontent.com/clojure-interop/google-cloud-clients/80852d0496057c22f9cdc86d6f9ffc0fa3cd7904/com.google.cloud.redis/src/com/google/cloud/redis/v1beta1/core.clj | clojure | (ns com.google.cloud.redis.v1beta1.core
(:refer-clojure :only [require comment defn ->])
(:import ))
(require '[com.google.cloud.redis.v1beta1.CloudRedisClient$ListInstancesFixedSizeCollection])
(require '[com.google.cloud.redis.v1beta1.CloudRedisClient$ListInstancesPage])
(require '[com.google.cloud.redis.v1beta1.CloudRedisClient$ListInstancesPagedResponse])
(require '[com.google.cloud.redis.v1beta1.CloudRedisClient])
(require '[com.google.cloud.redis.v1beta1.CloudRedisSettings$Builder])
(require '[com.google.cloud.redis.v1beta1.CloudRedisSettings])
| |
5782a0c6002a58a9cd65bc38e976fc6de4ad2ee37c37046fa33bd61022d91931 | ocurrent/ocurrent | engine.ml | open Capnp_rpc_lwt
type t = Api.Service.Engine.t Capability.t
module Engine = Api.Client.Engine
let active_jobs t =
let open Engine.ActiveJobs in
let request = Capability.Request.create_no_args () in
Capability.call_for_value t method_id request |> Lwt_result.map Results.ids_get_list
let job t id =
let open Engine.Job in
let request, params = Capability.Request.create Params.init_pointer in
Params.id_set params id;
Capability.call_for_caps t method_id request Results.job_get_pipelined
| null | https://raw.githubusercontent.com/ocurrent/ocurrent/344af83279e9ba17f5f32d0a0351c228a6f42863/lib_rpc/engine.ml | ocaml | open Capnp_rpc_lwt
type t = Api.Service.Engine.t Capability.t
module Engine = Api.Client.Engine
let active_jobs t =
let open Engine.ActiveJobs in
let request = Capability.Request.create_no_args () in
Capability.call_for_value t method_id request |> Lwt_result.map Results.ids_get_list
let job t id =
let open Engine.Job in
let request, params = Capability.Request.create Params.init_pointer in
Params.id_set params id;
Capability.call_for_caps t method_id request Results.job_get_pipelined
| |
8234fd0cf4a5c3c9d1d38ba0642fe443121cb40cc14f686a66e5f10daf5b2623 | pink-gorilla/ui-gorilla | pprint.cljs | (ns ui.pprint
(:require
[cljs.pprint :as pp]
[sci.core :as sci]))
(defn pprint [& args]
(binding [*print-fn* @sci/print-fn]
(apply pp/pprint args)))
(defn print-table [& args]
(binding [*print-fn* @sci/print-fn]
(apply pp/print-table args)))
(def pns (sci/create-ns 'cljs.pprint nil))
(def pprint-namespace
{'pprint (sci/copy-var pprint pns)
'print-table (sci/copy-var print-table pns)})
; {:namespaces {'cljs.pprint pprint-namespace}}
; (:require [cljs.pprint :as pprint]))
( pprint / cl - format nil " ~,2f " 1.2345 ) ; = > returns " 1.23 "
( pprint / cl - format true " ~,2f " 1.2345 ) ; = > prints " 1.23 " , returns nil | null | https://raw.githubusercontent.com/pink-gorilla/ui-gorilla/3cc408b398d30a8e54c15f863fbabece9f036209/src/ui/pprint.cljs | clojure | {:namespaces {'cljs.pprint pprint-namespace}}
(:require [cljs.pprint :as pprint]))
= > returns " 1.23 "
= > prints " 1.23 " , returns nil | (ns ui.pprint
(:require
[cljs.pprint :as pp]
[sci.core :as sci]))
(defn pprint [& args]
(binding [*print-fn* @sci/print-fn]
(apply pp/pprint args)))
(defn print-table [& args]
(binding [*print-fn* @sci/print-fn]
(apply pp/print-table args)))
(def pns (sci/create-ns 'cljs.pprint nil))
(def pprint-namespace
{'pprint (sci/copy-var pprint pns)
'print-table (sci/copy-var print-table pns)})
|
f302d8620784a7e979b267f1ffcbb8d6217d5377c5b3bed7095ad0102c1e5258 | karlhof26/gimp-scheme | FU_edges_frames.scm | ; FU_edges_frames.scm
version 2.8 [ gimphelp.org ]
last modified / tested by
02/14/2014 on GIMP-2.8.10
;
; modified 01/06/2008
modified We d Oct 1 , 2008 by
; modified again 11/20/2008 for gimp-2.6
02/14/2014 convwert to RGB if needed
; 05/29/2020 converted to work on Gimp 2.10.18
;==============================================================
;
; Installation:
; This script should be placed in the user or system-wide script folder.
;
; Windows Vista/7/8)
C:\Program Files\GIMP 2\share\gimp\2.0\scripts
; or
C:\Users\YOUR - NAME\.gimp-2.8\scripts
;
Windows XP
C:\Program Files\GIMP 2\share\gimp\2.0\scripts
; or
; C:\Documents and Settings\yourname\.gimp-2.8\scripts
;
; Linux
/home / yourname/.gimp-2.8 / scripts
; or
; Linux system-wide
; /usr/share/gimp/2.0/scripts
;
;==============================================================
;
; LICENSE
;
; This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
; (at your option) any later version.
;
; This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
; GNU General Public License for more details.
;
You should have received a copy of the GNU General Public License
; along with this program. If not, see </>.
;
;==============================================================
; Original information
;
; edge_sign.scm --- prepare photograph for publishing on Internet
; originally frame.scm
;
Copyright ( C ) 2006 by
;
Author : < >
;
; These scripts are suitable for publishing photographs on Internet.
; They resizes a picture, then add a border, (one of the commands
; drops a shadow as well) and add the author's name in the bottom
; right corner.
;
There are three commands script - fu - frame - modern , -poster and
; -negative. The former rounds the corners and drops a shadow on a
; white background. The latter rounds the corners and adds a black
; border. Both add a signature which has to be modified in the
script as Script - Fu is very limited and does n't allow for any
; default values that are not constant.
;==============================================================
(define (FU-frame-hover image drawable width signature-text font-name)
(if (<= width 128.0)
(begin
( gimp - message " set too small . Reset to 128 " )
(set! width 128.0)
)
(begin
( gimp - message " kept . " )
)
)
(gimp-display-new
(FU-frame-hover-batch image drawable width signature-text font-name))
(gimp-displays-flush)
)
(define (FU-frame-negative image drawable targetwidth signature-text font-name)
(let* (
(revisedwidth 50.0)
)
( gimp - message ( number->string targetwidth ) )
(if (<= targetwidth 128.0)
(begin
( gimp - message " set too small . Reset to 128 " )
(set! targetwidth 128.0)
)
(begin
( gimp - message " kept . " )
)
)
(gimp-display-new
(FU-frame-negative-batch image drawable targetwidth signature-text font-name))
(gimp-displays-flush)
)
)
(define (FU-frame-poster image drawable width border-colour signature-text font-name)
(if (<= width 128.0)
(begin
( gimp - message " set too small . Reset to 128 " )
(set! width 128.0)
)
(begin
( gimp - message " kept . " )
)
)
(gimp-display-new
(FU-frame-poster-batch image drawable width border-colour signature-text font-name))
(gimp-displays-flush)
)
(define (%top-layer image)
(aref (cadr (gimp-image-get-layers image)) 0)
)
(define (FU-frame-hover-batch image drawable width signature-text font-name)
(let* (
(new-image (car (gimp-image-duplicate image)))
(drawable (car (gimp-image-get-active-drawable new-image)))
(height (* (car (gimp-image-height new-image))
(/ width (car (gimp-image-width new-image)))))
;; just an index of dimension
(size (/ (sqrt (* width height)) 20))
(foreground (car (gimp-context-get-foreground)))
(background (car (gimp-context-get-background)))
)
(gimp-image-undo-group-start new-image)
(if (not (= RGB (car (gimp-image-base-type new-image))))
(gimp-image-convert-rgb new-image)
)
(script-fu-guides-remove new-image drawable)
(gimp-image-scale new-image width height)
(plug-in-unsharp-mask RUN-NONINTERACTIVE image drawable
(* size 0.15) ; radius (constant found empirically)
0.3 ; amount
0 ; threshold
)
(gimp-context-set-foreground '(0 0 0))
(gimp-context-set-background '(255 255 255))
(script-fu-round-corners new-image
drawable
(trunc (* size 1.3)) ; edge radius ; was /2
TRUE ; add drop shadow
(trunc (/ size 3)) ; shadow x offset
(trunc (/ size 3)) ; shadow y offset
(trunc (/ size 2)) ; shadow blur radius
TRUE ; add background ; was T
do n't make another copy as we just made one
FALSE)
(if (> size 20)
(begin
( gimp - message " size > 20 " )
(gimp-image-set-active-layer new-image (%top-layer new-image))
(let* ((text-layer (car (gimp-text-fontname new-image
-1 ; drawable, -1 = new layer
0
0
signature-text
(/ size 6) ; border
TRUE ; antialias
(max 10 (/ size 2)) ; text size
PIXELS ; size unit
font-name)))
(text-width (car (gimp-drawable-width text-layer)))
(text-height (car (gimp-drawable-height text-layer)))
)
(gimp-layer-set-offsets text-layer
(- (car (gimp-image-width new-image)) text-width (log size))
(- (car (gimp-image-height new-image)) text-height))
)
)
(begin
(gimp-message "Size small. No signature in border. Use 512 or higher.")
)
)
(gimp-image-merge-visible-layers new-image 0)
(gimp-context-set-foreground foreground)
(gimp-context-set-background background)
(gimp-image-undo-group-end new-image)
;; return the new image so that batch scripts can do something
;; with it
new-image)
)
(define (FU-frame-negative-batch image drawable width signature-text font-name)
(let* (
(new-image (car (gimp-image-duplicate image)))
(drawable (car (gimp-image-get-active-drawable new-image)))
(height (* (car (gimp-image-height new-image))
(/ width (car (gimp-image-width new-image)))))
(size (/ (sqrt (* width height)) 20))
(foreground (car (gimp-context-get-foreground)))
(background (car (gimp-context-get-background)))
(black-layer (car (gimp-layer-new new-image
width ; (car (gimp-image-width new-image))
height ; (car (gimp-image-height new-image))
RGB-IMAGE
"Black layer"
100
LAYER-MODE-NORMAL)))
)
(gimp-image-undo-group-start new-image)
(if (not (= RGB (car (gimp-image-base-type new-image))))
(gimp-image-convert-rgb new-image)
)
(script-fu-guides-remove new-image drawable)
(gimp-image-scale new-image width height)
(plug-in-unsharp-mask RUN-NONINTERACTIVE image drawable
(* size 0.15) ; radius
0.3 ; amount
0 ; threshold
)
(gimp-context-set-foreground '(0 0 0)) ; ws 250 250 250
(gimp-context-set-background '(0 0 0))
(script-fu-round-corners new-image
drawable
edge radius ; was / 3
FALSE ; no shadow
0 ; shadow x offset
0 ; shadow y offset
0 ; shadow blur radius
FALSE ; add background
do n't make another copy as we just made one
FALSE)
(gimp-image-insert-layer new-image black-layer 0 1)
(gimp-edit-fill black-layer FILL-BACKGROUND)
(gimp-context-set-foreground '(200 200 200))
;(gimp-display-new new-image)
;(quit)
(gimp-image-merge-visible-layers new-image 0)
(let ((background-layer (%top-layer new-image)))
(if (> size 20)
(begin
(let* (
(text-layer (car (gimp-text-fontname new-image
-1 ; drawable, -1 = new layer
0
0
signature-text
1 ; border
TRUE ; antialias
(max 10 (/ size 2)) ; text size
PIXELS ; size unit
font-name)))
(text-width (car (gimp-drawable-width text-layer)))
(text-height (car (gimp-drawable-height text-layer)))
)
(script-fu-addborder new-image background-layer
text-height text-height '(0 0 0) 0)
(gimp-layer-set-offsets text-layer
(- (car (gimp-image-width new-image)) text-width (log size))
(- (car (gimp-image-height new-image)) text-height))
(gimp-image-raise-item-to-top new-image text-layer)
)
(gimp-image-merge-visible-layers new-image 0)
)
(begin
(gimp-message "Size small. No Signature in border. Use 512 or higher.")
;(gimp-message (number->string size))
(script-fu-addborder new-image background-layer
(round (* size 0.75)) (round (* size 0.75)) '(0 0 0) 0)
)
)
)
(gimp-context-set-foreground foreground)
(gimp-context-set-background background)
(gimp-image-undo-group-end new-image)
;; return the new image so that batch scripts can do something
;; with it
new-image
)
)
(define (FU-frame-poster-batch image drawable width border-colour signature-text font-name)
(let* (
(new-image (car (gimp-image-duplicate image)))
(drawable (car (gimp-image-get-active-drawable new-image)))
(height (* (car (gimp-image-height new-image))
(/ width (car (gimp-image-width new-image)))))
(size (/ (sqrt (* width height)) 20))
(inverted-border-colour (mapcar (lambda (value)
(- 255 value))
border-colour))
(foreground (car (gimp-context-get-foreground)))
(background (car (gimp-context-get-background)))
)
(gimp-image-undo-group-start new-image)
(if (not (= RGB (car (gimp-image-base-type new-image))))
(gimp-image-convert-rgb new-image)
)
(script-fu-guides-remove new-image drawable)
(gimp-image-scale new-image width height)
(plug-in-unsharp-mask RUN-NONINTERACTIVE image drawable
(* size 0.15) ; radius
0.3 ; amount
0 ; threshold
)
(gimp-context-set-foreground inverted-border-colour)
(gimp-context-set-background border-colour)
(let (
(thickness (max 1 (trunc (/ (log size) 2))))
)
(script-fu-addborder new-image (%top-layer new-image)
thickness thickness
inverted-border-colour
0)
)
(gimp-image-merge-visible-layers new-image 0)
(let ((background-layer (%top-layer new-image)))
(if (> size 20)
(begin
(let* (
(text-layer (car (gimp-text-fontname new-image
-1 ; drawable, -1 = new layer
0
0
signature-text
1 ; border
TRUE ; antialias
;; text size (cursive fonts need more space)
(max 10 (/ size 1.5))
PIXELS ; size unit
font-name)))
(text-width (car (gimp-drawable-width text-layer)))
(text-height (car (gimp-drawable-height text-layer)))
)
(script-fu-addborder new-image background-layer
text-height text-height border-colour 0)
(gimp-layer-set-offsets text-layer
(- (car (gimp-image-width new-image)) text-width (log size))
(- (car (gimp-image-height new-image)) text-height))
(gimp-image-raise-item-to-top new-image text-layer)
)
)
(begin
(gimp-message "Size small. No signature in border. Use 512 or higher.")
(script-fu-addborder new-image background-layer
size size border-colour 0)
)
)
)
(gimp-image-merge-visible-layers new-image 0)
(gimp-context-set-foreground foreground)
(gimp-context-set-background background)
(gimp-image-undo-group-end new-image)
;; return the new image so that batch scripts can do something
;; with it
new-image
)
)
(script-fu-register "FU-frame-hover"
"Frame like a hover with drop shadow and round corners..."
"Resize, frame and sign a photograph for publishing on Internet (\"hover\" style). Creates a new image. \nfile:FU_edges_frames.scm"
"Walter Pelissero <>"
"Walter Pelissero"
"2006/07/13"
"*"
SF-IMAGE "Image" 0
SF-DRAWABLE "Drawable" 0
SF-ADJUSTMENT "Image width" '(640 128 4096 128 10 0 1)
SF-STRING "Signature" "Your Name"
SF-FONT "Font" "sans"
)
(script-fu-menu-register "FU-frame-hover"
"<Toolbox>/Script-Fu/Edges")
(script-fu-register "FU-frame-negative"
"Frame like a negative slide with round corners..."
"Resize, frame and sign a photograph for publishing on Internet (\"slide\" style). Creates a new image. \nfile:FU_edges_frames.scm"
"Walter Pelissero <>"
"Walter Pelissero"
"2006/07/13"
"*"
SF-IMAGE "Image" 0
SF-DRAWABLE "Drawable" 0
SF-ADJUSTMENT "Image target width" '(640 128 4096 128 10 0 1)
SF-STRING "Signature" "Your Name"
SF-FONT "Font" "sans"
)
(script-fu-register "FU-frame-poster"
"Frame like poster with straight corners..."
"Resize, frame and sign a photograph for publishing on Internet (\"poster\" style). Creates a new image. \nfile:FU_edges_frames.scm"
"Walter Pelissero <>"
"Walter Pelissero"
"2006/09/06"
"*"
SF-IMAGE "Image" 0
SF-DRAWABLE "Drawable" 0
SF-ADJUSTMENT "Image target width" '(640 128 4096 128 10 0 1)
SF-COLOR "Border colour" '(0 0 0)
SF-STRING "Signature" "Your Name"
SF-FONT "Font" "sans"
)
(script-fu-menu-register "FU-frame-negative"
"<Toolbox>/Script-Fu/Edges")
(script-fu-menu-register "FU-frame-poster"
"<Toolbox>/Script-Fu/Edges")
;end of script | null | https://raw.githubusercontent.com/karlhof26/gimp-scheme/bcaaae384fa57fd919607d5599989e6dfcc7f7c7/FU_edges_frames.scm | scheme | FU_edges_frames.scm
modified 01/06/2008
modified again 11/20/2008 for gimp-2.6
05/29/2020 converted to work on Gimp 2.10.18
==============================================================
Installation:
This script should be placed in the user or system-wide script folder.
Windows Vista/7/8)
or
or
C:\Documents and Settings\yourname\.gimp-2.8\scripts
Linux
or
Linux system-wide
/usr/share/gimp/2.0/scripts
==============================================================
LICENSE
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program. If not, see </>.
==============================================================
Original information
edge_sign.scm --- prepare photograph for publishing on Internet
originally frame.scm
These scripts are suitable for publishing photographs on Internet.
They resizes a picture, then add a border, (one of the commands
drops a shadow as well) and add the author's name in the bottom
right corner.
-negative. The former rounds the corners and drops a shadow on a
white background. The latter rounds the corners and adds a black
border. Both add a signature which has to be modified in the
default values that are not constant.
==============================================================
just an index of dimension
radius (constant found empirically)
amount
threshold
edge radius ; was /2
add drop shadow
shadow x offset
shadow y offset
shadow blur radius
add background ; was T
drawable, -1 = new layer
border
antialias
text size
size unit
return the new image so that batch scripts can do something
with it
(car (gimp-image-width new-image))
(car (gimp-image-height new-image))
radius
amount
threshold
ws 250 250 250
was / 3
no shadow
shadow x offset
shadow y offset
shadow blur radius
add background
(gimp-display-new new-image)
(quit)
drawable, -1 = new layer
border
antialias
text size
size unit
(gimp-message (number->string size))
return the new image so that batch scripts can do something
with it
radius
amount
threshold
drawable, -1 = new layer
border
antialias
text size (cursive fonts need more space)
size unit
return the new image so that batch scripts can do something
with it
end of script | version 2.8 [ gimphelp.org ]
last modified / tested by
02/14/2014 on GIMP-2.8.10
modified We d Oct 1 , 2008 by
02/14/2014 convwert to RGB if needed
C:\Program Files\GIMP 2\share\gimp\2.0\scripts
C:\Users\YOUR - NAME\.gimp-2.8\scripts
Windows XP
C:\Program Files\GIMP 2\share\gimp\2.0\scripts
/home / yourname/.gimp-2.8 / scripts
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
Copyright ( C ) 2006 by
Author : < >
There are three commands script - fu - frame - modern , -poster and
script as Script - Fu is very limited and does n't allow for any
(define (FU-frame-hover image drawable width signature-text font-name)
(if (<= width 128.0)
(begin
( gimp - message " set too small . Reset to 128 " )
(set! width 128.0)
)
(begin
( gimp - message " kept . " )
)
)
(gimp-display-new
(FU-frame-hover-batch image drawable width signature-text font-name))
(gimp-displays-flush)
)
(define (FU-frame-negative image drawable targetwidth signature-text font-name)
(let* (
(revisedwidth 50.0)
)
( gimp - message ( number->string targetwidth ) )
(if (<= targetwidth 128.0)
(begin
( gimp - message " set too small . Reset to 128 " )
(set! targetwidth 128.0)
)
(begin
( gimp - message " kept . " )
)
)
(gimp-display-new
(FU-frame-negative-batch image drawable targetwidth signature-text font-name))
(gimp-displays-flush)
)
)
(define (FU-frame-poster image drawable width border-colour signature-text font-name)
(if (<= width 128.0)
(begin
( gimp - message " set too small . Reset to 128 " )
(set! width 128.0)
)
(begin
( gimp - message " kept . " )
)
)
(gimp-display-new
(FU-frame-poster-batch image drawable width border-colour signature-text font-name))
(gimp-displays-flush)
)
(define (%top-layer image)
(aref (cadr (gimp-image-get-layers image)) 0)
)
(define (FU-frame-hover-batch image drawable width signature-text font-name)
(let* (
(new-image (car (gimp-image-duplicate image)))
(drawable (car (gimp-image-get-active-drawable new-image)))
(height (* (car (gimp-image-height new-image))
(/ width (car (gimp-image-width new-image)))))
(size (/ (sqrt (* width height)) 20))
(foreground (car (gimp-context-get-foreground)))
(background (car (gimp-context-get-background)))
)
(gimp-image-undo-group-start new-image)
(if (not (= RGB (car (gimp-image-base-type new-image))))
(gimp-image-convert-rgb new-image)
)
(script-fu-guides-remove new-image drawable)
(gimp-image-scale new-image width height)
(plug-in-unsharp-mask RUN-NONINTERACTIVE image drawable
)
(gimp-context-set-foreground '(0 0 0))
(gimp-context-set-background '(255 255 255))
(script-fu-round-corners new-image
drawable
do n't make another copy as we just made one
FALSE)
(if (> size 20)
(begin
( gimp - message " size > 20 " )
(gimp-image-set-active-layer new-image (%top-layer new-image))
(let* ((text-layer (car (gimp-text-fontname new-image
0
0
signature-text
font-name)))
(text-width (car (gimp-drawable-width text-layer)))
(text-height (car (gimp-drawable-height text-layer)))
)
(gimp-layer-set-offsets text-layer
(- (car (gimp-image-width new-image)) text-width (log size))
(- (car (gimp-image-height new-image)) text-height))
)
)
(begin
(gimp-message "Size small. No signature in border. Use 512 or higher.")
)
)
(gimp-image-merge-visible-layers new-image 0)
(gimp-context-set-foreground foreground)
(gimp-context-set-background background)
(gimp-image-undo-group-end new-image)
new-image)
)
(define (FU-frame-negative-batch image drawable width signature-text font-name)
(let* (
(new-image (car (gimp-image-duplicate image)))
(drawable (car (gimp-image-get-active-drawable new-image)))
(height (* (car (gimp-image-height new-image))
(/ width (car (gimp-image-width new-image)))))
(size (/ (sqrt (* width height)) 20))
(foreground (car (gimp-context-get-foreground)))
(background (car (gimp-context-get-background)))
(black-layer (car (gimp-layer-new new-image
RGB-IMAGE
"Black layer"
100
LAYER-MODE-NORMAL)))
)
(gimp-image-undo-group-start new-image)
(if (not (= RGB (car (gimp-image-base-type new-image))))
(gimp-image-convert-rgb new-image)
)
(script-fu-guides-remove new-image drawable)
(gimp-image-scale new-image width height)
(plug-in-unsharp-mask RUN-NONINTERACTIVE image drawable
)
(gimp-context-set-background '(0 0 0))
(script-fu-round-corners new-image
drawable
do n't make another copy as we just made one
FALSE)
(gimp-image-insert-layer new-image black-layer 0 1)
(gimp-edit-fill black-layer FILL-BACKGROUND)
(gimp-context-set-foreground '(200 200 200))
(gimp-image-merge-visible-layers new-image 0)
(let ((background-layer (%top-layer new-image)))
(if (> size 20)
(begin
(let* (
(text-layer (car (gimp-text-fontname new-image
0
0
signature-text
font-name)))
(text-width (car (gimp-drawable-width text-layer)))
(text-height (car (gimp-drawable-height text-layer)))
)
(script-fu-addborder new-image background-layer
text-height text-height '(0 0 0) 0)
(gimp-layer-set-offsets text-layer
(- (car (gimp-image-width new-image)) text-width (log size))
(- (car (gimp-image-height new-image)) text-height))
(gimp-image-raise-item-to-top new-image text-layer)
)
(gimp-image-merge-visible-layers new-image 0)
)
(begin
(gimp-message "Size small. No Signature in border. Use 512 or higher.")
(script-fu-addborder new-image background-layer
(round (* size 0.75)) (round (* size 0.75)) '(0 0 0) 0)
)
)
)
(gimp-context-set-foreground foreground)
(gimp-context-set-background background)
(gimp-image-undo-group-end new-image)
new-image
)
)
(define (FU-frame-poster-batch image drawable width border-colour signature-text font-name)
(let* (
(new-image (car (gimp-image-duplicate image)))
(drawable (car (gimp-image-get-active-drawable new-image)))
(height (* (car (gimp-image-height new-image))
(/ width (car (gimp-image-width new-image)))))
(size (/ (sqrt (* width height)) 20))
(inverted-border-colour (mapcar (lambda (value)
(- 255 value))
border-colour))
(foreground (car (gimp-context-get-foreground)))
(background (car (gimp-context-get-background)))
)
(gimp-image-undo-group-start new-image)
(if (not (= RGB (car (gimp-image-base-type new-image))))
(gimp-image-convert-rgb new-image)
)
(script-fu-guides-remove new-image drawable)
(gimp-image-scale new-image width height)
(plug-in-unsharp-mask RUN-NONINTERACTIVE image drawable
)
(gimp-context-set-foreground inverted-border-colour)
(gimp-context-set-background border-colour)
(let (
(thickness (max 1 (trunc (/ (log size) 2))))
)
(script-fu-addborder new-image (%top-layer new-image)
thickness thickness
inverted-border-colour
0)
)
(gimp-image-merge-visible-layers new-image 0)
(let ((background-layer (%top-layer new-image)))
(if (> size 20)
(begin
(let* (
(text-layer (car (gimp-text-fontname new-image
0
0
signature-text
(max 10 (/ size 1.5))
font-name)))
(text-width (car (gimp-drawable-width text-layer)))
(text-height (car (gimp-drawable-height text-layer)))
)
(script-fu-addborder new-image background-layer
text-height text-height border-colour 0)
(gimp-layer-set-offsets text-layer
(- (car (gimp-image-width new-image)) text-width (log size))
(- (car (gimp-image-height new-image)) text-height))
(gimp-image-raise-item-to-top new-image text-layer)
)
)
(begin
(gimp-message "Size small. No signature in border. Use 512 or higher.")
(script-fu-addborder new-image background-layer
size size border-colour 0)
)
)
)
(gimp-image-merge-visible-layers new-image 0)
(gimp-context-set-foreground foreground)
(gimp-context-set-background background)
(gimp-image-undo-group-end new-image)
new-image
)
)
(script-fu-register "FU-frame-hover"
"Frame like a hover with drop shadow and round corners..."
"Resize, frame and sign a photograph for publishing on Internet (\"hover\" style). Creates a new image. \nfile:FU_edges_frames.scm"
"Walter Pelissero <>"
"Walter Pelissero"
"2006/07/13"
"*"
SF-IMAGE "Image" 0
SF-DRAWABLE "Drawable" 0
SF-ADJUSTMENT "Image width" '(640 128 4096 128 10 0 1)
SF-STRING "Signature" "Your Name"
SF-FONT "Font" "sans"
)
(script-fu-menu-register "FU-frame-hover"
"<Toolbox>/Script-Fu/Edges")
(script-fu-register "FU-frame-negative"
"Frame like a negative slide with round corners..."
"Resize, frame and sign a photograph for publishing on Internet (\"slide\" style). Creates a new image. \nfile:FU_edges_frames.scm"
"Walter Pelissero <>"
"Walter Pelissero"
"2006/07/13"
"*"
SF-IMAGE "Image" 0
SF-DRAWABLE "Drawable" 0
SF-ADJUSTMENT "Image target width" '(640 128 4096 128 10 0 1)
SF-STRING "Signature" "Your Name"
SF-FONT "Font" "sans"
)
(script-fu-register "FU-frame-poster"
"Frame like poster with straight corners..."
"Resize, frame and sign a photograph for publishing on Internet (\"poster\" style). Creates a new image. \nfile:FU_edges_frames.scm"
"Walter Pelissero <>"
"Walter Pelissero"
"2006/09/06"
"*"
SF-IMAGE "Image" 0
SF-DRAWABLE "Drawable" 0
SF-ADJUSTMENT "Image target width" '(640 128 4096 128 10 0 1)
SF-COLOR "Border colour" '(0 0 0)
SF-STRING "Signature" "Your Name"
SF-FONT "Font" "sans"
)
(script-fu-menu-register "FU-frame-negative"
"<Toolbox>/Script-Fu/Edges")
(script-fu-menu-register "FU-frame-poster"
"<Toolbox>/Script-Fu/Edges")
|
ec0613c82e1c7ac756ca43c81fc4208e4380e1b8cfb06cde6a9da74d210c4b64 | shonfeder/nomad | defaults.ml | (** Default content *)
(** Default ocamlformat file *)
let ocamlformat ?(dir = Fpath.v ".") () : File.t =
let path = Fpath.(dir / ".ocamlformat") in
let content =
{|exp-grouping = preserve
break-fun-sig = fit-or-vertical
break-fun-decl = fit-or-vertical
wrap-fun-args = false
dock-collection-brackets = false
align-cases = true
break-cases = all
break-separators = before
break-infix = fit-or-vertical
if-then-else = k-r
nested-match = align
type-decl = sparse
|}
in
{ path; content }
let default_dune_project ~name ~author ~username =
let dune_version = "2.9" in
[%string
{|(lang dune $(dune_version))
(cram enable)
(generate_opam_files true)
(name $name)
(license MIT)
(authors "$author")
(maintainers "$author")
(source (github $username/$name))
(package
(name $name)
(synopsis "Short description")
(description "Longer description")
(depends
(dune (> $dune_version))
ocaml
(alcotest :with-test)
(qcheck :with-test)
(qcheck-alcotest :with-test)
))
|}]
let dune_project ~dir ~name ({ author; username; dune_project; _ } : Config.t) : (File.t, Rresult.R.msg) Result.t =
let open Result.Let in
let+ content = match dune_project with
| None -> Ok (default_dune_project ~name ~author ~username)
| Some path ->
let open Bos in
let* content = Bos.OS.File.read Fpath.(v path) in
let+ pat = Pat.of_string content in
let defs = Astring.String.Map.(
empty
|> add "NAME" name
|> add "USERNAME" username
|> add "AUTHOR" author
)
in
Pat.format defs pat
in
let path = Fpath.(dir / "dune-project") in
File.{ path; content }
let gitignore ?(dir = Fpath.v ".") () : File.t =
let path = Fpath.(dir / ".gitignore") in
let content =
{|
# Dune build directory
_build/
# Opam switch directory
_opam/
|}
in
{ path; content }
let opam_template ~name ?(dir = Fpath.v ".") () : File.t =
let path = Fpath.(dir / [%string {|$(name).opam.template|}]) in
let content =
{|pin-depends: [
["{package}.dev" "git+https://{forge}/{username}/{repo}.git"]
]
|}
in
{ path; content }
| null | https://raw.githubusercontent.com/shonfeder/nomad/aff078bfebdaaa67c0e7f1610491f64bc55b4881/lib/defaults.ml | ocaml | * Default content
* Default ocamlformat file |
let ocamlformat ?(dir = Fpath.v ".") () : File.t =
let path = Fpath.(dir / ".ocamlformat") in
let content =
{|exp-grouping = preserve
break-fun-sig = fit-or-vertical
break-fun-decl = fit-or-vertical
wrap-fun-args = false
dock-collection-brackets = false
align-cases = true
break-cases = all
break-separators = before
break-infix = fit-or-vertical
if-then-else = k-r
nested-match = align
type-decl = sparse
|}
in
{ path; content }
let default_dune_project ~name ~author ~username =
let dune_version = "2.9" in
[%string
{|(lang dune $(dune_version))
(cram enable)
(generate_opam_files true)
(name $name)
(license MIT)
(authors "$author")
(maintainers "$author")
(source (github $username/$name))
(package
(name $name)
(synopsis "Short description")
(description "Longer description")
(depends
(dune (> $dune_version))
ocaml
(alcotest :with-test)
(qcheck :with-test)
(qcheck-alcotest :with-test)
))
|}]
let dune_project ~dir ~name ({ author; username; dune_project; _ } : Config.t) : (File.t, Rresult.R.msg) Result.t =
let open Result.Let in
let+ content = match dune_project with
| None -> Ok (default_dune_project ~name ~author ~username)
| Some path ->
let open Bos in
let* content = Bos.OS.File.read Fpath.(v path) in
let+ pat = Pat.of_string content in
let defs = Astring.String.Map.(
empty
|> add "NAME" name
|> add "USERNAME" username
|> add "AUTHOR" author
)
in
Pat.format defs pat
in
let path = Fpath.(dir / "dune-project") in
File.{ path; content }
let gitignore ?(dir = Fpath.v ".") () : File.t =
let path = Fpath.(dir / ".gitignore") in
let content =
{|
# Dune build directory
_build/
# Opam switch directory
_opam/
|}
in
{ path; content }
let opam_template ~name ?(dir = Fpath.v ".") () : File.t =
let path = Fpath.(dir / [%string {|$(name).opam.template|}]) in
let content =
{|pin-depends: [
["{package}.dev" "git+https://{forge}/{username}/{repo}.git"]
]
|}
in
{ path; content }
|
4c9d3f49ec793703b3fab66fe62a6be280fc55c0f6ac62b0b9781c3538b7fcdf | KingoftheHomeless/in-other-words | Internal.hs | # LANGUAGE DerivingVia #
# OPTIONS_HADDOCK not - home #
module Control.Effect.Internal where
import Data.Coerce
import Data.Kind (Constraint)
import Data.Functor.Identity
import Data.Monoid
import Control.Monad.Trans
import Control.Monad.Trans.Identity
import Control.Effect.Internal.Membership
import Control.Effect.Internal.Union
import Control.Effect.Internal.Utils
import Control.Effect.Internal.Derive
import Control.Effect.Internal.Itself
-- | The class of effect carriers, and the underlying mechanism with which
-- effects are implemented.
--
-- Each carrier is able to implement a number of /derived/ effects,
and /primitive/ effects . Users usually only interact with derived
-- effects, as these determine the effects that users have access to.
--
-- The standard interpretation tools are typically powerful enough to
-- let you avoid making instances of this class directly. If you need to make
-- your own instance of 'Carrier', import "Control.Effect.Carrier" and consult the
[ wiki]( / KingoftheHomeless / in - other - words / wiki / Advanced - topics#novel - carriers ) .
class Monad m => Carrier m where
-- | The derived effects that @m@ carries. Each derived effect is eventually
-- reformulated into terms of the primitive effects @'Prims' m@ or other
-- effects in @'Derivs' m@.
--
-- In application code, you gain access to effects by placing membership
constraints upon @'Derivs ' m@. You can use ' Eff ' or ' Effs ' for this
-- purpose.
--
-- Although rarely relevant for users, @'Derivs' m@ can also contain effects
-- that aren't expressed in terms of other effects, as longs as the handlers
-- for those effects can be lifted generically using 'lift'. Such effects don't
-- need to be part of @'Prims' m@, which is exclusively for primitive effects
-- whose handlers need special treatment to be lifted.
--
For example , first order effects such as ' Control . Effect . State . State '
-- never need to be part of @'Prims' m@. Certain higher-order effects -
-- such as 'Control.Effect.Cont.Cont' - can also be handled such that they
-- never need to be primitive.
type Derivs m :: [Effect]
-- | The primitive effects that @m@ carries. These are higher-order effects
-- whose handlers aren't expressed in terms of other effects, and thus need to
-- be lifted on a carrier-by-carrier basis.
--
-- __Never place membership constraints on @'Prims' m@.__
-- You should only gain access to effects by placing membership constraints
-- on @'Derivs' m@.
--
-- /However/, running interpreters may place other kinds of constraints upon
-- @'Prims' m@, namely /threading constraints/, marked by the use of
' ' .
-- If you want to run such an effect interpreter inside application code, you
-- have to propagate such threading constraints through your application.
--
-- @'Prims' m@ should only contain higher-order effects that can't be lifted
-- generically using 'lift'. Any other effects can be placed in @'Derivs' m@.
type Prims m :: [Effect]
-- | An @m@-based 'Algebra' (i.e effect handler) over the union
-- of the primitive effects:
-- effects that aren't formulated in terms of other effects.
See ' Prims ' .
algPrims :: Algebra' (Prims m) m a
-- | Any 'Carrier' @m@ must provide a way to describe the derived effects it
-- carries in terms of the primitive effects.
--
-- 'reformulate' is that decription: given any monad @z@ such that
-- @z@ lifts @m@, then a @z@-based 'Algebra' (i.e. effect handler)
-- over the derived effects can be created out of a @z@-based 'Algebra' over
-- the primitive effects.
reformulate :: Monad z
=> Reformulation' (Derivs m) (Prims m) m z a
-- | An @m@-based algebra (i.e. effect handler) over the union of derived
-- effects (see @'Derivs' m@).
--
-- This is what 'send' makes use of.
--
-- 'algDerivs' is subject to the law:
--
-- @
algDerivs = ' reformulate ' i d ' algPrims '
-- @
--
-- which serves as the default implementation.
algDerivs :: Algebra' (Derivs m) m a
algDerivs = reformulate id algPrims
# INLINE algDerivs #
deriving newtype instance Carrier m => Carrier (Alt m)
deriving newtype instance Carrier m => Carrier (Ap m)
-- | (Morally) a type synonym for
@('Member ' e ( ' Derivs ' m ) , ' Carrier ' m)@.
-- This and 'Effs' are the typical methods to gain
-- access to effects.
--
Unlike ' Member ' , ' Eff ' gives ' Bundle ' special treatment .
As a side - effect , ' Eff ' will get stuck if is a type variable .
--
If you need access to some completely polymorphic effect ,
use ' e ( ' Derivs ' m ) , ' Carrier ' m)@ instead of @Eff e m@.
type Eff e m = Effs '[e] m
| A variant of ' Eff ' that takes a list of effects , and expands them into
-- multiple 'Member' constraints on @'Derivs' m@.
This and ' Eff ' are the typical methods to gain access to effects .
--
Like ' Eff ' , ' Effs ' gives ' Bundle ' special treatment .
-- As a side-effect, 'Effs' will get stuck if any element of the list
-- is a type variable.
--
If you need access to some completetely polymorphic effect ,
use a separate @'Member ' e ( ' Derivs ' m)@ constraint .
type Effs es m = (EffMembers es (Derivs m), Carrier m)
-- | Perform an action of an effect.
--
-- 'send' should be used to create actions of your own effects.
-- For example:
--
-- @
-- data CheckString :: Effect where
CheckString : : String - > CheckString m
--
checkString : : m = > String - > m
-- checkString str = send (CheckString str)
-- @
--
send :: (Member e (Derivs m), Carrier m) => e m a -> m a
send = algDerivs . inj
# INLINE send #
deriving via (m :: Type -> Type) instance Carrier m => Carrier (IdentityT m)
-- | A constraint that @'Prims' m@ satisfies all the constraints in the list
@cs@.
--
-- This is used for /threading constraints/.
--
-- Every interpreter that relies on an underlying
-- non-trivial monad transformer -- such as 'Control.Effect.State.runState',
which uses ' Control . . Trans . State . Strict . StateT ' internally --
-- must be able to lift all primitive effect handlers of the monad it's transforming
-- so that the resulting transformed monad can also handle the primitive effects.
--
-- The ability of a monad transformer to lift handlers of a particular
-- primitive effect is called /threading/ that effect. /Threading constraints/
-- correspond to the requirement that the primitive effects of the monad that's
-- being transformed can be thread by certain monad transformers.
--
-- For example, the 'Control.Effect.State.runState' places the threading
-- constraint 'Control.Effect.State.StateThreads' on @'Prims' m@, so that
@'Control . Effect . State . StateC ' s m@ can carry all primitive effects that
-- @m@ does.
--
' ' is used to handle threading constraints .
-- @'Threaders' '['Control.Effect.State.StateThreads', 'Control.Effect.Error.ExceptThreads'] m p@
-- allows you to use 'Control.Effect.State.runState' and
-- 'Control.Effect.Error.runError' with the carrier @m@.
--
-- Sometimes, you may want to have a local effect which you interpret
inside of application code , such as a local ' Control . Effect . State . State '
or ' Control . Effect . Error . Error ' effect . In such cases , /try to use/
[ split interpretation]( / KingoftheHomeless / in - other - words / wiki / Advanced - Topics#abstract - effect - interpretation ) of using interpreters with threading constraints/
/inside of application code./ If you ca n't , then using ' '
-- is necessary to propagate the threading constraints
-- throughout the application.
--
_ _ The third argument @p@ should always be a polymorphic type variable , which _ _
-- __you can simply provide and ignore.__
-- It exists as a work-around to the fact that many threading constraints
-- /don't actually work/ if they operate on @'Prims' m@ directly, since
-- threading constraints often involve quantified constraints, which are fragile
in combination with type families -- like ' Prims ' .
--
-- So @'Threaders' '['Control.Effect.State.StateThreads'] m p@
does n't expand to @'Control . Effect . State . StateThreads ' ( ' Prims ' m)@ , but rather ,
@(p ~ ' Prims ' m , ' Control . Effect . State . StateThreads ' p)@
type Threaders cs m p = (p ~ Prims m, SatisfiesAll p cs)
type family SatisfiesAll (q :: k) cs :: Constraint where
SatisfiesAll q '[] = ()
SatisfiesAll q (c ': cs) = (c q, SatisfiesAll q cs)
-- | The identity carrier, which carries no effects at all.
type RunC = Identity
-- | Extract the final result from a computation of which no effects remain
-- to be handled.
run :: RunC a -> a
run = runIdentity
# INLINE run #
instance Carrier Identity where
type Derivs Identity = '[]
type Prims Identity = '[]
algPrims = absurdU
# INLINE algPrims #
reformulate _ _ = absurdU
# INLINE reformulate #
algDerivs = absurdU
# INLINE algDerivs #
deriving newtype instance Carrier m => Carrier (Itself m)
newtype SubsumeC (e :: Effect) m a = SubsumeC {
unSubsumeC :: m a
}
deriving ( Functor, Applicative, Monad
, Alternative, MonadPlus
, MonadFix, MonadFail, MonadIO
, MonadThrow, MonadCatch, MonadMask
, MonadBase b, MonadBaseControl b
)
via m
deriving (MonadTrans, MonadTransControl) via IdentityT
instance ( Carrier m
, Member e (Derivs m)
)
=> Carrier (SubsumeC e m) where
type Derivs (SubsumeC e m) = e ': Derivs m
type Prims (SubsumeC e m) = Prims m
algPrims = coerce (algPrims @m)
# INLINE algPrims #
reformulate n alg = powerAlg' (reformulate (n .# SubsumeC) alg) $ \e ->
reformulate (n .# SubsumeC) alg (Union membership e)
# INLINE reformulate #
algDerivs = powerAlg' (coerce (algDerivs @m)) $ \e ->
coerceAlg (algDerivs @m) (Union membership e)
# INLINE algDerivs #
-- | Interpret an effect in terms of another, identical effect.
--
This is very rarely useful , but one use - case is to transform
-- reinterpreters into regular interpreters.
--
-- For example,
-- @'subsume' . 'Control.Effect.reinterpretSimple' \@e h@ is morally equivalent
-- to @'Control.Effect.interpretSimple' \@e h@
subsume :: ( Carrier m
, Member e (Derivs m)
)
=> SubsumeC e m a
-> m a
subsume = unSubsumeC
{-# INLINE subsume #-}
| null | https://raw.githubusercontent.com/KingoftheHomeless/in-other-words/b3574738bf8786a641c281c16202926ba674f7e2/src/Control/Effect/Internal.hs | haskell | | The class of effect carriers, and the underlying mechanism with which
effects are implemented.
Each carrier is able to implement a number of /derived/ effects,
effects, as these determine the effects that users have access to.
The standard interpretation tools are typically powerful enough to
let you avoid making instances of this class directly. If you need to make
your own instance of 'Carrier', import "Control.Effect.Carrier" and consult the
| The derived effects that @m@ carries. Each derived effect is eventually
reformulated into terms of the primitive effects @'Prims' m@ or other
effects in @'Derivs' m@.
In application code, you gain access to effects by placing membership
purpose.
Although rarely relevant for users, @'Derivs' m@ can also contain effects
that aren't expressed in terms of other effects, as longs as the handlers
for those effects can be lifted generically using 'lift'. Such effects don't
need to be part of @'Prims' m@, which is exclusively for primitive effects
whose handlers need special treatment to be lifted.
never need to be part of @'Prims' m@. Certain higher-order effects -
such as 'Control.Effect.Cont.Cont' - can also be handled such that they
never need to be primitive.
| The primitive effects that @m@ carries. These are higher-order effects
whose handlers aren't expressed in terms of other effects, and thus need to
be lifted on a carrier-by-carrier basis.
__Never place membership constraints on @'Prims' m@.__
You should only gain access to effects by placing membership constraints
on @'Derivs' m@.
/However/, running interpreters may place other kinds of constraints upon
@'Prims' m@, namely /threading constraints/, marked by the use of
If you want to run such an effect interpreter inside application code, you
have to propagate such threading constraints through your application.
@'Prims' m@ should only contain higher-order effects that can't be lifted
generically using 'lift'. Any other effects can be placed in @'Derivs' m@.
| An @m@-based 'Algebra' (i.e effect handler) over the union
of the primitive effects:
effects that aren't formulated in terms of other effects.
| Any 'Carrier' @m@ must provide a way to describe the derived effects it
carries in terms of the primitive effects.
'reformulate' is that decription: given any monad @z@ such that
@z@ lifts @m@, then a @z@-based 'Algebra' (i.e. effect handler)
over the derived effects can be created out of a @z@-based 'Algebra' over
the primitive effects.
| An @m@-based algebra (i.e. effect handler) over the union of derived
effects (see @'Derivs' m@).
This is what 'send' makes use of.
'algDerivs' is subject to the law:
@
@
which serves as the default implementation.
| (Morally) a type synonym for
This and 'Effs' are the typical methods to gain
access to effects.
multiple 'Member' constraints on @'Derivs' m@.
As a side-effect, 'Effs' will get stuck if any element of the list
is a type variable.
| Perform an action of an effect.
'send' should be used to create actions of your own effects.
For example:
@
data CheckString :: Effect where
checkString str = send (CheckString str)
@
| A constraint that @'Prims' m@ satisfies all the constraints in the list
This is used for /threading constraints/.
Every interpreter that relies on an underlying
non-trivial monad transformer -- such as 'Control.Effect.State.runState',
must be able to lift all primitive effect handlers of the monad it's transforming
so that the resulting transformed monad can also handle the primitive effects.
The ability of a monad transformer to lift handlers of a particular
primitive effect is called /threading/ that effect. /Threading constraints/
correspond to the requirement that the primitive effects of the monad that's
being transformed can be thread by certain monad transformers.
For example, the 'Control.Effect.State.runState' places the threading
constraint 'Control.Effect.State.StateThreads' on @'Prims' m@, so that
@m@ does.
@'Threaders' '['Control.Effect.State.StateThreads', 'Control.Effect.Error.ExceptThreads'] m p@
allows you to use 'Control.Effect.State.runState' and
'Control.Effect.Error.runError' with the carrier @m@.
Sometimes, you may want to have a local effect which you interpret
is necessary to propagate the threading constraints
throughout the application.
__you can simply provide and ignore.__
It exists as a work-around to the fact that many threading constraints
/don't actually work/ if they operate on @'Prims' m@ directly, since
threading constraints often involve quantified constraints, which are fragile
like ' Prims ' .
So @'Threaders' '['Control.Effect.State.StateThreads'] m p@
| The identity carrier, which carries no effects at all.
| Extract the final result from a computation of which no effects remain
to be handled.
| Interpret an effect in terms of another, identical effect.
reinterpreters into regular interpreters.
For example,
@'subsume' . 'Control.Effect.reinterpretSimple' \@e h@ is morally equivalent
to @'Control.Effect.interpretSimple' \@e h@
# INLINE subsume # | # LANGUAGE DerivingVia #
# OPTIONS_HADDOCK not - home #
module Control.Effect.Internal where
import Data.Coerce
import Data.Kind (Constraint)
import Data.Functor.Identity
import Data.Monoid
import Control.Monad.Trans
import Control.Monad.Trans.Identity
import Control.Effect.Internal.Membership
import Control.Effect.Internal.Union
import Control.Effect.Internal.Utils
import Control.Effect.Internal.Derive
import Control.Effect.Internal.Itself
and /primitive/ effects . Users usually only interact with derived
[ wiki]( / KingoftheHomeless / in - other - words / wiki / Advanced - topics#novel - carriers ) .
class Monad m => Carrier m where
constraints upon @'Derivs ' m@. You can use ' Eff ' or ' Effs ' for this
For example , first order effects such as ' Control . Effect . State . State '
type Derivs m :: [Effect]
' ' .
type Prims m :: [Effect]
See ' Prims ' .
algPrims :: Algebra' (Prims m) m a
reformulate :: Monad z
=> Reformulation' (Derivs m) (Prims m) m z a
algDerivs = ' reformulate ' i d ' algPrims '
algDerivs :: Algebra' (Derivs m) m a
algDerivs = reformulate id algPrims
# INLINE algDerivs #
deriving newtype instance Carrier m => Carrier (Alt m)
deriving newtype instance Carrier m => Carrier (Ap m)
@('Member ' e ( ' Derivs ' m ) , ' Carrier ' m)@.
Unlike ' Member ' , ' Eff ' gives ' Bundle ' special treatment .
As a side - effect , ' Eff ' will get stuck if is a type variable .
If you need access to some completely polymorphic effect ,
use ' e ( ' Derivs ' m ) , ' Carrier ' m)@ instead of @Eff e m@.
type Eff e m = Effs '[e] m
| A variant of ' Eff ' that takes a list of effects , and expands them into
This and ' Eff ' are the typical methods to gain access to effects .
Like ' Eff ' , ' Effs ' gives ' Bundle ' special treatment .
If you need access to some completetely polymorphic effect ,
use a separate @'Member ' e ( ' Derivs ' m)@ constraint .
type Effs es m = (EffMembers es (Derivs m), Carrier m)
CheckString : : String - > CheckString m
checkString : : m = > String - > m
send :: (Member e (Derivs m), Carrier m) => e m a -> m a
send = algDerivs . inj
# INLINE send #
deriving via (m :: Type -> Type) instance Carrier m => Carrier (IdentityT m)
@cs@.
@'Control . Effect . State . StateC ' s m@ can carry all primitive effects that
' ' is used to handle threading constraints .
inside of application code , such as a local ' Control . Effect . State . State '
or ' Control . Effect . Error . Error ' effect . In such cases , /try to use/
[ split interpretation]( / KingoftheHomeless / in - other - words / wiki / Advanced - Topics#abstract - effect - interpretation ) of using interpreters with threading constraints/
/inside of application code./ If you ca n't , then using ' '
_ _ The third argument @p@ should always be a polymorphic type variable , which _ _
does n't expand to @'Control . Effect . State . StateThreads ' ( ' Prims ' m)@ , but rather ,
@(p ~ ' Prims ' m , ' Control . Effect . State . StateThreads ' p)@
type Threaders cs m p = (p ~ Prims m, SatisfiesAll p cs)
type family SatisfiesAll (q :: k) cs :: Constraint where
SatisfiesAll q '[] = ()
SatisfiesAll q (c ': cs) = (c q, SatisfiesAll q cs)
type RunC = Identity
run :: RunC a -> a
run = runIdentity
# INLINE run #
instance Carrier Identity where
type Derivs Identity = '[]
type Prims Identity = '[]
algPrims = absurdU
# INLINE algPrims #
reformulate _ _ = absurdU
# INLINE reformulate #
algDerivs = absurdU
# INLINE algDerivs #
deriving newtype instance Carrier m => Carrier (Itself m)
newtype SubsumeC (e :: Effect) m a = SubsumeC {
unSubsumeC :: m a
}
deriving ( Functor, Applicative, Monad
, Alternative, MonadPlus
, MonadFix, MonadFail, MonadIO
, MonadThrow, MonadCatch, MonadMask
, MonadBase b, MonadBaseControl b
)
via m
deriving (MonadTrans, MonadTransControl) via IdentityT
instance ( Carrier m
, Member e (Derivs m)
)
=> Carrier (SubsumeC e m) where
type Derivs (SubsumeC e m) = e ': Derivs m
type Prims (SubsumeC e m) = Prims m
algPrims = coerce (algPrims @m)
# INLINE algPrims #
reformulate n alg = powerAlg' (reformulate (n .# SubsumeC) alg) $ \e ->
reformulate (n .# SubsumeC) alg (Union membership e)
# INLINE reformulate #
algDerivs = powerAlg' (coerce (algDerivs @m)) $ \e ->
coerceAlg (algDerivs @m) (Union membership e)
# INLINE algDerivs #
This is very rarely useful , but one use - case is to transform
subsume :: ( Carrier m
, Member e (Derivs m)
)
=> SubsumeC e m a
-> m a
subsume = unSubsumeC
|
e5b92aed56a9f5ce363adf2d59f46bdb6a0053dc15b384f3eea9828b280a05f3 | pirapira/coq2rust | nativecode.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2013
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
open Errors
open Names
open Term
open Context
open Declarations
open Util
open Nativevalues
open Primitives
open Nativeinstr
open Nativelambda
open Pre_env
* This file defines the mllambda code generation phase of the native
compiler . mllambda represents a fragment of ML , and can easily be printed
to OCaml code .
compiler. mllambda represents a fragment of ML, and can easily be printed
to OCaml code. *)
(** Local names **)
type lname = { lname : name; luid : int }
let dummy_lname = { lname = Anonymous; luid = -1 }
module LNord =
struct
type t = lname
let compare l1 l2 = l1.luid - l2.luid
end
module LNmap = Map.Make(LNord)
module LNset = Set.Make(LNord)
let lname_ctr = ref (-1)
let reset_lname = lname_ctr := -1
let fresh_lname n =
incr lname_ctr;
{ lname = n; luid = !lname_ctr }
(** Global names **)
type gname =
| Gind of string * inductive (* prefix, inductive name *)
| Gconstruct of string * constructor (* prefix, constructor name *)
| Gconstant of string * constant (* prefix, constant name *)
| Gproj of string * constant (* prefix, constant name *)
| Gcase of label option * int
| Gpred of label option * int
| Gfixtype of label option * int
| Gnorm of label option * int
| Gnormtbl of label option * int
| Ginternal of string
| Grel of int
| Gnamed of identifier
let eq_gname gn1 gn2 =
match gn1, gn2 with
| Gind (s1, ind1), Gind (s2, ind2) -> String.equal s1 s2 && eq_ind ind1 ind2
| Gconstruct (s1, c1), Gconstruct (s2, c2) ->
String.equal s1 s2 && eq_constructor c1 c2
| Gconstant (s1, c1), Gconstant (s2, c2) ->
String.equal s1 s2 && Constant.equal c1 c2
| Gcase (None, i1), Gcase (None, i2) -> Int.equal i1 i2
| Gcase (Some l1, i1), Gcase (Some l2, i2) -> Int.equal i1 i2 && Label.equal l1 l2
| Gpred (None, i1), Gpred (None, i2) -> Int.equal i1 i2
| Gpred (Some l1, i1), Gpred (Some l2, i2) -> Int.equal i1 i2 && Label.equal l1 l2
| Gfixtype (None, i1), Gfixtype (None, i2) -> Int.equal i1 i2
| Gfixtype (Some l1, i1), Gfixtype (Some l2, i2) ->
Int.equal i1 i2 && Label.equal l1 l2
| Gnorm (None, i1), Gnorm (None, i2) -> Int.equal i1 i2
| Gnorm (Some l1, i1), Gnorm (Some l2, i2) -> Int.equal i1 i2 && Label.equal l1 l2
| Gnormtbl (None, i1), Gnormtbl (None, i2) -> Int.equal i1 i2
| Gnormtbl (Some l1, i1), Gnormtbl (Some l2, i2) ->
Int.equal i1 i2 && Label.equal l1 l2
| Ginternal s1, Ginternal s2 -> String.equal s1 s2
| Grel i1, Grel i2 -> Int.equal i1 i2
| Gnamed id1, Gnamed id2 -> Id.equal id1 id2
| _ -> false
open Hashset.Combine
let gname_hash gn = match gn with
| Gind (s, i) -> combinesmall 1 (combine (String.hash s) (ind_hash i))
| Gconstruct (s, c) -> combinesmall 2 (combine (String.hash s) (constructor_hash c))
| Gconstant (s, c) -> combinesmall 3 (combine (String.hash s) (Constant.hash c))
| Gcase (l, i) -> combinesmall 4 (combine (Option.hash Label.hash l) (Int.hash i))
| Gpred (l, i) -> combinesmall 5 (combine (Option.hash Label.hash l) (Int.hash i))
| Gfixtype (l, i) -> combinesmall 6 (combine (Option.hash Label.hash l) (Int.hash i))
| Gnorm (l, i) -> combinesmall 7 (combine (Option.hash Label.hash l) (Int.hash i))
| Gnormtbl (l, i) -> combinesmall 8 (combine (Option.hash Label.hash l) (Int.hash i))
| Ginternal s -> combinesmall 9 (String.hash s)
| Grel i -> combinesmall 10 (Int.hash i)
| Gnamed id -> combinesmall 11 (Id.hash id)
| Gproj (s, p) -> combinesmall 12 (combine (String.hash s) (Constant.hash p))
let case_ctr = ref (-1)
let reset_gcase () = case_ctr := -1
let fresh_gcase l =
incr case_ctr;
Gcase (l,!case_ctr)
let pred_ctr = ref (-1)
let reset_gpred () = pred_ctr := -1
let fresh_gpred l =
incr pred_ctr;
Gpred (l,!pred_ctr)
let fixtype_ctr = ref (-1)
let reset_gfixtype () = fixtype_ctr := -1
let fresh_gfixtype l =
incr fixtype_ctr;
Gfixtype (l,!fixtype_ctr)
let norm_ctr = ref (-1)
let reset_norm () = norm_ctr := -1
let fresh_gnorm l =
incr norm_ctr;
Gnorm (l,!norm_ctr)
let normtbl_ctr = ref (-1)
let reset_normtbl () = normtbl_ctr := -1
let fresh_gnormtbl l =
incr normtbl_ctr;
Gnormtbl (l,!normtbl_ctr)
(** Symbols (pre-computed values) **)
type symbol =
| SymbValue of Nativevalues.t
| SymbSort of sorts
| SymbName of name
| SymbConst of constant
| SymbMatch of annot_sw
| SymbInd of inductive
| SymbMeta of metavariable
| SymbEvar of existential
let dummy_symb = SymbValue (dummy_value ())
let eq_symbol sy1 sy2 =
match sy1, sy2 with
| SymbValue v1, SymbValue v2 -> Pervasives.(=) v1 v2 (** FIXME: how is this even valid? *)
| SymbSort s1, SymbSort s2 -> Sorts.equal s1 s2
| SymbName n1, SymbName n2 -> Name.equal n1 n2
| SymbConst kn1, SymbConst kn2 -> Constant.equal kn1 kn2
| SymbMatch sw1, SymbMatch sw2 -> eq_annot_sw sw1 sw2
| SymbInd ind1, SymbInd ind2 -> eq_ind ind1 ind2
| SymbMeta m1, SymbMeta m2 -> Int.equal m1 m2
| SymbEvar (evk1,args1), SymbEvar (evk2,args2) ->
Evar.equal evk1 evk2 && Array.for_all2 eq_constr args1 args2
| _, _ -> false
let hash_symbol symb =
match symb with
| SymbValue v -> combinesmall 1 (Hashtbl.hash v) (** FIXME *)
| SymbSort s -> combinesmall 2 (Sorts.hash s)
| SymbName name -> combinesmall 3 (Name.hash name)
| SymbConst c -> combinesmall 4 (Constant.hash c)
| SymbMatch sw -> combinesmall 5 (hash_annot_sw sw)
| SymbInd ind -> combinesmall 6 (ind_hash ind)
| SymbMeta m -> combinesmall 7 m
| SymbEvar (evk,args) ->
let evh = Evar.hash evk in
let hl = Array.fold_left (fun h t -> combine h (Constr.hash t)) evh args in
combinesmall 8 hl
module HashedTypeSymbol = struct
type t = symbol
let equal = eq_symbol
let hash = hash_symbol
end
module HashtblSymbol = Hashtbl.Make(HashedTypeSymbol)
let symb_tbl = HashtblSymbol.create 211
let clear_symb_tbl () = HashtblSymbol.clear symb_tbl
let get_value tbl i =
match tbl.(i) with
| SymbValue v -> v
| _ -> anomaly (Pp.str "get_value failed")
let get_sort tbl i =
match tbl.(i) with
| SymbSort s -> s
| _ -> anomaly (Pp.str "get_sort failed")
let get_name tbl i =
match tbl.(i) with
| SymbName id -> id
| _ -> anomaly (Pp.str "get_name failed")
let get_const tbl i =
match tbl.(i) with
| SymbConst kn -> kn
| _ -> anomaly (Pp.str "get_const failed")
let get_match tbl i =
match tbl.(i) with
| SymbMatch case_info -> case_info
| _ -> anomaly (Pp.str "get_match failed")
let get_ind tbl i =
match tbl.(i) with
| SymbInd ind -> ind
| _ -> anomaly (Pp.str "get_ind failed")
let get_meta tbl i =
match tbl.(i) with
| SymbMeta m -> m
| _ -> anomaly (Pp.str "get_meta failed")
let get_evar tbl i =
match tbl.(i) with
| SymbEvar ev -> ev
| _ -> anomaly (Pp.str "get_evar failed")
let push_symbol x =
try HashtblSymbol.find symb_tbl x
with Not_found ->
let i = HashtblSymbol.length symb_tbl in
HashtblSymbol.add symb_tbl x i; i
let symbols_tbl_name = Ginternal "symbols_tbl"
let get_symbols_tbl () =
let tbl = Array.make (HashtblSymbol.length symb_tbl) dummy_symb in
HashtblSymbol.iter (fun x i -> tbl.(i) <- x) symb_tbl; tbl
(** Lambda to Mllambda **)
type primitive =
| Mk_prod
| Mk_sort
| Mk_ind
| Mk_const
| Mk_sw
| Mk_fix of rec_pos * int
| Mk_cofix of int
| Mk_rel of int
| Mk_var of identifier
| Mk_proj
| Is_accu
| Is_int
| Cast_accu
| Upd_cofix
| Force_cofix
| Mk_uint
| Mk_int
| Mk_bool
| Val_to_int
| Mk_I31_accu
| Decomp_uint
| Mk_meta
| Mk_evar
| MLand
| MLle
| MLlt
| MLinteq
| MLlsl
| MLlsr
| MLland
| MLlor
| MLlxor
| MLadd
| MLsub
| MLmul
| MLmagic
| Coq_primitive of Primitives.t * (prefix * constant) option
let eq_primitive p1 p2 =
match p1, p2 with
| Mk_prod, Mk_prod -> true
| Mk_sort, Mk_sort -> true
| Mk_ind, Mk_ind -> true
| Mk_const, Mk_const -> true
| Mk_sw, Mk_sw -> true
| Mk_fix (rp1, i1), Mk_fix (rp2, i2) -> Int.equal i1 i2 && eq_rec_pos rp1 rp2
| Mk_cofix i1, Mk_cofix i2 -> Int.equal i1 i2
| Mk_rel i1, Mk_rel i2 -> Int.equal i1 i2
| Mk_var id1, Mk_var id2 -> Id.equal id1 id2
| Is_accu, Is_accu -> true
| Cast_accu, Cast_accu -> true
| Upd_cofix, Upd_cofix -> true
| Force_cofix, Force_cofix -> true
| Mk_meta, Mk_meta -> true
| Mk_evar, Mk_evar -> true
| Mk_proj, Mk_proj -> true
| _ -> false
let primitive_hash = function
| Mk_prod -> 1
| Mk_sort -> 2
| Mk_ind -> 3
| Mk_const -> 4
| Mk_sw -> 5
| Mk_fix (r, i) ->
let h = Array.fold_left (fun h i -> combine h (Int.hash i)) 0 r in
combinesmall 6 (combine h (Int.hash i))
| Mk_cofix i ->
combinesmall 7 (Int.hash i)
| Mk_rel i ->
combinesmall 8 (Int.hash i)
| Mk_var id ->
combinesmall 9 (Id.hash id)
| Is_accu -> 10
| Is_int -> 11
| Cast_accu -> 12
| Upd_cofix -> 13
| Force_cofix -> 14
| Mk_uint -> 15
| Mk_int -> 16
| Mk_bool -> 17
| Val_to_int -> 18
| Mk_I31_accu -> 19
| Decomp_uint -> 20
| Mk_meta -> 21
| Mk_evar -> 22
| MLand -> 23
| MLle -> 24
| MLlt -> 25
| MLinteq -> 26
| MLlsl -> 27
| MLlsr -> 28
| MLland -> 29
| MLlor -> 30
| MLlxor -> 31
| MLadd -> 32
| MLsub -> 33
| MLmul -> 34
| MLmagic -> 35
| Coq_primitive (prim, None) -> combinesmall 36 (Primitives.hash prim)
| Coq_primitive (prim, Some (prefix,kn)) ->
combinesmall 37 (combine3 (String.hash prefix) (Constant.hash kn) (Primitives.hash prim))
| Mk_proj -> 38
type mllambda =
| MLlocal of lname
| MLglobal of gname
| MLprimitive of primitive
| MLlam of lname array * mllambda
| MLletrec of (lname * lname array * mllambda) array * mllambda
| MLlet of lname * mllambda * mllambda
| MLapp of mllambda * mllambda array
| MLif of mllambda * mllambda * mllambda
| MLmatch of annot_sw * mllambda * mllambda * mllam_branches
(* argument, prefix, accu branch, branches *)
| MLconstruct of string * constructor * mllambda array
(* prefix, constructor name, arguments *)
| MLint of int
| MLuint of Uint31.t
| MLsetref of string * mllambda
| MLsequence of mllambda * mllambda
and mllam_branches = ((constructor * lname option array) list * mllambda) array
let push_lnames n env lns =
snd (Array.fold_left (fun (i,r) x -> (i+1, LNmap.add x i r)) (n,env) lns)
let opush_lnames n env lns =
let oadd x i r = match x with Some ln -> LNmap.add ln i r | None -> r in
snd (Array.fold_left (fun (i,r) x -> (i+1, oadd x i r)) (n,env) lns)
Alpha - equivalence on mllambda
eq_mllambda gn2 n env1 env2 t1 t2 tests if t1 = t2 modulo = gn2
let rec eq_mllambda gn1 gn2 n env1 env2 t1 t2 =
match t1, t2 with
| MLlocal ln1, MLlocal ln2 ->
Int.equal (LNmap.find ln1 env1) (LNmap.find ln2 env2)
| MLglobal gn1', MLglobal gn2' ->
eq_gname gn1' gn2' || (eq_gname gn1 gn1' && eq_gname gn2 gn2')
| MLprimitive prim1, MLprimitive prim2 -> eq_primitive prim1 prim2
| MLlam (lns1, ml1), MLlam (lns2, ml2) ->
Int.equal (Array.length lns1) (Array.length lns2) &&
let env1 = push_lnames n env1 lns1 in
let env2 = push_lnames n env2 lns2 in
eq_mllambda gn1 gn2 (n+Array.length lns1) env1 env2 ml1 ml2
| MLletrec (defs1, body1), MLletrec (defs2, body2) ->
Int.equal (Array.length defs1) (Array.length defs2) &&
let lns1 = Array.map (fun (x,_,_) -> x) defs1 in
let lns2 = Array.map (fun (x,_,_) -> x) defs2 in
let env1 = push_lnames n env1 lns1 in
let env2 = push_lnames n env2 lns2 in
let n = n + Array.length defs1 in
eq_letrec gn1 gn2 n env1 env2 defs1 defs2 &&
eq_mllambda gn1 gn2 n env1 env2 body1 body2
| MLlet (ln1, def1, body1), MLlet (ln2, def2, body2) ->
eq_mllambda gn1 gn2 n env1 env2 def1 def2 &&
let env1 = LNmap.add ln1 n env1 in
let env2 = LNmap.add ln2 n env2 in
eq_mllambda gn1 gn2 (n+1) env1 env2 body1 body2
| MLapp (ml1, args1), MLapp (ml2, args2) ->
eq_mllambda gn1 gn2 n env1 env2 ml1 ml2 &&
Array.equal (eq_mllambda gn1 gn2 n env1 env2) args1 args2
| MLif (cond1,br1,br'1), MLif (cond2,br2,br'2) ->
eq_mllambda gn1 gn2 n env1 env2 cond1 cond2 &&
eq_mllambda gn1 gn2 n env1 env2 br1 br2 &&
eq_mllambda gn1 gn2 n env1 env2 br'1 br'2
| MLmatch (annot1, c1, accu1, br1), MLmatch (annot2, c2, accu2, br2) ->
eq_annot_sw annot1 annot2 &&
eq_mllambda gn1 gn2 n env1 env2 c1 c2 &&
eq_mllambda gn1 gn2 n env1 env2 accu1 accu2 &&
eq_mllam_branches gn1 gn2 n env1 env2 br1 br2
| MLconstruct (pf1, cs1, args1), MLconstruct (pf2, cs2, args2) ->
String.equal pf1 pf2 &&
eq_constructor cs1 cs2 &&
Array.equal (eq_mllambda gn1 gn2 n env1 env2) args1 args2
| MLint i1, MLint i2 ->
Int.equal i1 i2
| MLuint i1, MLuint i2 ->
Uint31.equal i1 i2
| MLsetref (id1, ml1), MLsetref (id2, ml2) ->
String.equal id1 id2 &&
eq_mllambda gn1 gn2 n env1 env2 ml1 ml2
| MLsequence (ml1, ml'1), MLsequence (ml2, ml'2) ->
eq_mllambda gn1 gn2 n env1 env2 ml1 ml2 &&
eq_mllambda gn1 gn2 n env1 env2 ml'1 ml'2
| _, _ -> false
and eq_letrec gn1 gn2 n env1 env2 defs1 defs2 =
let eq_def (_,args1,ml1) (_,args2,ml2) =
Int.equal (Array.length args1) (Array.length args2) &&
let env1 = push_lnames n env1 args1 in
let env2 = push_lnames n env2 args2 in
eq_mllambda gn1 gn2 (n + Array.length args1) env1 env2 ml1 ml2
in
Array.equal eq_def defs1 defs2
(* we require here that patterns have the same order, which may be too strong *)
and eq_mllam_branches gn1 gn2 n env1 env2 br1 br2 =
let eq_cargs (cs1, args1) (cs2, args2) body1 body2 =
Int.equal (Array.length args1) (Array.length args2) &&
eq_constructor cs1 cs2 &&
let env1 = opush_lnames n env1 args1 in
let env2 = opush_lnames n env2 args2 in
eq_mllambda gn1 gn2 (n + Array.length args1) env1 env2 body1 body2
in
let eq_branch (ptl1,body1) (ptl2,body2) =
List.equal (fun pt1 pt2 -> eq_cargs pt1 pt2 body1 body2) ptl1 ptl2
in
Array.equal eq_branch br1 br2
hash_mllambda gn n env t computes the hash for t ignoring occurences of gn
let rec hash_mllambda gn n env t =
match t with
| MLlocal ln -> combinesmall 1 (LNmap.find ln env)
| MLglobal gn' -> combinesmall 2 (if eq_gname gn gn' then 0 else gname_hash gn')
| MLprimitive prim -> combinesmall 3 (primitive_hash prim)
| MLlam (lns, ml) ->
let env = push_lnames n env lns in
combinesmall 4 (combine (Array.length lns) (hash_mllambda gn (n+1) env ml))
| MLletrec (defs, body) ->
let lns = Array.map (fun (x,_,_) -> x) defs in
let env = push_lnames n env lns in
let n = n + Array.length defs in
let h = combine (hash_mllambda gn n env body) (Array.length defs) in
combinesmall 5 (hash_mllambda_letrec gn n env h defs)
| MLlet (ln, def, body) ->
let hdef = hash_mllambda gn n env def in
let env = LNmap.add ln n env in
combinesmall 6 (combine hdef (hash_mllambda gn (n+1) env body))
| MLapp (ml, args) ->
let h = hash_mllambda gn n env ml in
combinesmall 7 (hash_mllambda_array gn n env h args)
| MLif (cond,br,br') ->
let hcond = hash_mllambda gn n env cond in
let hbr = hash_mllambda gn n env br in
let hbr' = hash_mllambda gn n env br' in
combinesmall 8 (combine3 hcond hbr hbr')
| MLmatch (annot, c, accu, br) ->
let hannot = hash_annot_sw annot in
let hc = hash_mllambda gn n env c in
let haccu = hash_mllambda gn n env accu in
combinesmall 9 (hash_mllam_branches gn n env (combine3 hannot hc haccu) br)
| MLconstruct (pf, cs, args) ->
let hpf = String.hash pf in
let hcs = constructor_hash cs in
combinesmall 10 (hash_mllambda_array gn n env (combine hpf hcs) args)
| MLint i ->
combinesmall 11 i
| MLuint i ->
combinesmall 12 (Uint31.to_int i)
| MLsetref (id, ml) ->
let hid = String.hash id in
let hml = hash_mllambda gn n env ml in
combinesmall 13 (combine hid hml)
| MLsequence (ml, ml') ->
let hml = hash_mllambda gn n env ml in
let hml' = hash_mllambda gn n env ml' in
combinesmall 14 (combine hml hml')
and hash_mllambda_letrec gn n env init defs =
let hash_def (_,args,ml) =
let env = push_lnames n env args in
let nargs = Array.length args in
combine nargs (hash_mllambda gn (n + nargs) env ml)
in
Array.fold_left (fun acc t -> combine (hash_def t) acc) init defs
and hash_mllambda_array gn n env init arr =
Array.fold_left (fun acc t -> combine (hash_mllambda gn n env t) acc) init arr
and hash_mllam_branches gn n env init br =
let hash_cargs (cs, args) body =
let nargs = Array.length args in
let hcs = constructor_hash cs in
let env = opush_lnames n env args in
let hbody = hash_mllambda gn (n + nargs) env body in
combine3 nargs hcs hbody
in
let hash_branch acc (ptl,body) =
List.fold_left (fun acc t -> combine (hash_cargs t body) acc) acc ptl
in
Array.fold_left hash_branch init br
let fv_lam l =
let rec aux l bind fv =
match l with
| MLlocal l ->
if LNset.mem l bind then fv else LNset.add l fv
| MLglobal _ | MLprimitive _ | MLint _ | MLuint _ -> fv
| MLlam (ln,body) ->
let bind = Array.fold_right LNset.add ln bind in
aux body bind fv
| MLletrec(bodies,def) ->
let bind =
Array.fold_right (fun (id,_,_) b -> LNset.add id b) bodies bind in
let fv_body (_,ln,body) fv =
let bind = Array.fold_right LNset.add ln bind in
aux body bind fv in
Array.fold_right fv_body bodies (aux def bind fv)
| MLlet(l,def,body) ->
aux body (LNset.add l bind) (aux def bind fv)
| MLapp(f,args) ->
let fv_arg arg fv = aux arg bind fv in
Array.fold_right fv_arg args (aux f bind fv)
| MLif(t,b1,b2) ->
aux t bind (aux b1 bind (aux b2 bind fv))
| MLmatch(_,a,p,bs) ->
let fv = aux a bind (aux p bind fv) in
let fv_bs (cargs, body) fv =
let bind =
List.fold_right (fun (_,args) bind ->
Array.fold_right
(fun o bind -> match o with
| Some l -> LNset.add l bind
| _ -> bind) args bind)
cargs bind in
aux body bind fv in
Array.fold_right fv_bs bs fv
(* argument, accu branch, branches *)
| MLconstruct (_,_,p) ->
Array.fold_right (fun a fv -> aux a bind fv) p fv
| MLsetref(_,l) -> aux l bind fv
| MLsequence(l1,l2) -> aux l1 bind (aux l2 bind fv) in
aux l LNset.empty LNset.empty
let mkMLlam params body =
if Array.is_empty params then body
else
match body with
| MLlam (params', body) -> MLlam(Array.append params params', body)
| _ -> MLlam(params,body)
let mkMLapp f args =
if Array.is_empty args then f
else
match f with
| MLapp(f,args') -> MLapp(f,Array.append args' args)
| _ -> MLapp(f,args)
let empty_params = [||]
let decompose_MLlam c =
match c with
| MLlam(ids,c) -> ids,c
| _ -> empty_params,c
(*s Global declaration *)
type global =
| Gtblname of * identifier array
| Gtblnorm of gname * lname array * mllambda array
| Gtblfixtype of gname * lname array * mllambda array
| Glet of gname * mllambda
| Gletcase of
gname * lname array * annot_sw * mllambda * mllambda * mllam_branches
| Gopen of string
| Gtype of inductive * int array
(* ind name, arities of constructors *)
| Gcomment of string
(* Alpha-equivalence on globals *)
let eq_global g1 g2 =
match g1, g2 with
| Gtblnorm (gn1,lns1,mls1), Gtblnorm (gn2,lns2,mls2)
| Gtblfixtype (gn1,lns1,mls1), Gtblfixtype (gn2,lns2,mls2) ->
Int.equal (Array.length lns1) (Array.length lns2) &&
Int.equal (Array.length mls1) (Array.length mls2) &&
let env1 = push_lnames 0 LNmap.empty lns1 in
let env2 = push_lnames 0 LNmap.empty lns2 in
Array.for_all2 (eq_mllambda gn1 gn2 (Array.length lns1) env1 env2) mls1 mls2
| Glet (gn1, def1), Glet (gn2, def2) ->
eq_mllambda gn1 gn2 0 LNmap.empty LNmap.empty def1 def2
| Gletcase (gn1,lns1,annot1,c1,accu1,br1),
Gletcase (gn2,lns2,annot2,c2,accu2,br2) ->
Int.equal (Array.length lns1) (Array.length lns2) &&
let env1 = push_lnames 0 LNmap.empty lns1 in
let env2 = push_lnames 0 LNmap.empty lns2 in
let t1 = MLmatch (annot1,c1,accu1,br1) in
let t2 = MLmatch (annot2,c2,accu2,br2) in
eq_mllambda gn1 gn2 (Array.length lns1) env1 env2 t1 t2
| Gopen s1, Gopen s2 -> String.equal s1 s2
| Gtype (ind1, arr1), Gtype (ind2, arr2) ->
eq_ind ind1 ind2 && Array.equal Int.equal arr1 arr2
| Gcomment s1, Gcomment s2 -> String.equal s1 s2
| _, _ -> false
let hash_global g =
match g with
| Gtblnorm (gn,lns,mls) ->
let nlns = Array.length lns in
let nmls = Array.length mls in
let env = push_lnames 0 LNmap.empty lns in
let hmls = hash_mllambda_array gn nlns env (combine nlns nmls) mls in
combinesmall 1 hmls
| Gtblfixtype (gn,lns,mls) ->
let nlns = Array.length lns in
let nmls = Array.length mls in
let env = push_lnames 0 LNmap.empty lns in
let hmls = hash_mllambda_array gn nlns env (combine nlns nmls) mls in
combinesmall 2 hmls
| Glet (gn, def) ->
combinesmall 3 (hash_mllambda gn 0 LNmap.empty def)
| Gletcase (gn,lns,annot,c,accu,br) ->
let nlns = Array.length lns in
let env = push_lnames 0 LNmap.empty lns in
let t = MLmatch (annot,c,accu,br) in
combinesmall 4 (combine nlns (hash_mllambda gn nlns env t))
| Gopen s -> combinesmall 5 (String.hash s)
| Gtype (ind, arr) ->
combinesmall 6 (combine (ind_hash ind) (Array.fold_left combine 0 arr))
| Gcomment s -> combinesmall 7 (String.hash s)
let global_stack = ref ([] : global list)
module HashedTypeGlobal = struct
type t = global
let equal = eq_global
let hash = hash_global
end
module HashtblGlobal = Hashtbl.Make(HashedTypeGlobal)
let global_tbl = HashtblGlobal.create 19991
let clear_global_tbl () = HashtblGlobal.clear global_tbl
let push_global gn t =
try HashtblGlobal.find global_tbl t
with Not_found ->
(global_stack := t :: !global_stack;
HashtblGlobal.add global_tbl t gn; gn)
let push_global_let gn body =
push_global gn (Glet (gn,body))
let push_global_fixtype gn params body =
push_global gn (Gtblfixtype (gn,params,body))
let push_global_norm gn params body =
push_global gn (Gtblnorm (gn, params, body))
let push_global_case gn params annot a accu bs =
push_global gn (Gletcase (gn, params, annot, a, accu, bs))
(*s Compilation environment *)
type env =
{ env_rel : mllambda list; (* (MLlocal lname) list *)
env_bound : int; (* length of env_rel *)
(* free variables *)
env_urel : (int * mllambda) list ref; (* list of unbound rel *)
env_named : (identifier * mllambda) list ref }
let empty_env () =
{ env_rel = [];
env_bound = 0;
env_urel = ref [];
env_named = ref []
}
let push_rel env id =
let local = fresh_lname id in
local, { env with
env_rel = MLlocal local :: env.env_rel;
env_bound = env.env_bound + 1
}
let push_rels env ids =
let lnames, env_rel =
Array.fold_left (fun (names,env_rel) id ->
let local = fresh_lname id in
(local::names, MLlocal local::env_rel)) ([],env.env_rel) ids in
Array.of_list (List.rev lnames), { env with
env_rel = env_rel;
env_bound = env.env_bound + Array.length ids
}
let get_rel env id i =
if i <= env.env_bound then
List.nth env.env_rel (i-1)
else
let i = i - env.env_bound in
try Int.List.assoc i !(env.env_urel)
with Not_found ->
let local = MLlocal (fresh_lname id) in
env.env_urel := (i,local) :: !(env.env_urel);
local
let get_var env id =
try Id.List.assoc id !(env.env_named)
with Not_found ->
let local = MLlocal (fresh_lname (Name id)) in
env.env_named := (id, local)::!(env.env_named);
local
(*s Traduction of lambda to mllambda *)
let get_prod_name codom =
match codom with
| MLlam(ids,_) -> ids.(0).lname
| _ -> assert false
let get_lname (_,l) =
match l with
| MLlocal id -> id
| _ -> invalid_arg "Nativecode.get_lname"
let fv_params env =
let fvn, fvr = !(env.env_named), !(env.env_urel) in
let size = List.length fvn + List.length fvr in
if Int.equal size 0 then empty_params
else begin
let params = Array.make size dummy_lname in
let fvn = ref fvn in
let i = ref 0 in
while not (List.is_empty !fvn) do
params.(!i) <- get_lname (List.hd !fvn);
fvn := List.tl !fvn;
incr i
done;
let fvr = ref fvr in
while not (List.is_empty !fvr) do
params.(!i) <- get_lname (List.hd !fvr);
fvr := List.tl !fvr;
incr i
done;
params
end
let generalize_fv env body =
mkMLlam (fv_params env) body
let empty_args = [||]
let fv_args env fvn fvr =
let size = List.length fvn + List.length fvr in
if Int.equal size 0 then empty_args
else
begin
let args = Array.make size (MLint 0) in
let fvn = ref fvn in
let i = ref 0 in
while not (List.is_empty !fvn) do
args.(!i) <- get_var env (fst (List.hd !fvn));
fvn := List.tl !fvn;
incr i
done;
let fvr = ref fvr in
while not (List.is_empty !fvr) do
let (k,_ as kml) = List.hd !fvr in
let n = get_lname kml in
args.(!i) <- get_rel env n.lname k;
fvr := List.tl !fvr;
incr i
done;
args
end
let get_value_code i =
MLapp (MLglobal (Ginternal "get_value"),
[|MLglobal symbols_tbl_name; MLint i|])
let get_sort_code i =
MLapp (MLglobal (Ginternal "get_sort"),
[|MLglobal symbols_tbl_name; MLint i|])
let get_name_code i =
MLapp (MLglobal (Ginternal "get_name"),
[|MLglobal symbols_tbl_name; MLint i|])
let get_const_code i =
MLapp (MLglobal (Ginternal "get_const"),
[|MLglobal symbols_tbl_name; MLint i|])
let get_match_code i =
MLapp (MLglobal (Ginternal "get_match"),
[|MLglobal symbols_tbl_name; MLint i|])
let get_ind_code i =
MLapp (MLglobal (Ginternal "get_ind"),
[|MLglobal symbols_tbl_name; MLint i|])
let get_meta_code i =
MLapp (MLglobal (Ginternal "get_meta"),
[|MLglobal symbols_tbl_name; MLint i|])
let get_evar_code i =
MLapp (MLglobal (Ginternal "get_evar"),
[|MLglobal symbols_tbl_name; MLint i|])
type rlist =
| Rnil
| Rcons of (constructor * lname option array) list ref * LNset.t * mllambda * rlist'
and rlist' = rlist ref
let rm_params fv params =
Array.map (fun l -> if LNset.mem l fv then Some l else None) params
let rec insert cargs body rl =
match !rl with
| Rnil ->
let fv = fv_lam body in
let (c,params) = cargs in
let params = rm_params fv params in
rl:= Rcons(ref [(c,params)], fv, body, ref Rnil)
| Rcons(l,fv,body',rl) ->
(** ppedrot: It seems we only want to factorize common branches. It should
not matter to do so with a subapproximation by (==). *)
if body == body' then
let (c,params) = cargs in
let params = rm_params fv params in
l := (c,params)::!l
else insert cargs body rl
let rec to_list rl =
match !rl with
| Rnil -> []
| Rcons(l,_,body,tl) -> (!l,body)::to_list tl
let merge_branches t =
let newt = ref Rnil in
Array.iter (fun (c,args,body) -> insert (c,args) body newt) t;
Array.of_list (to_list newt)
type prim_aux =
| PAprim of string * constant * Primitives.t * prim_aux array
| PAml of mllambda
let add_check cond args =
let aux cond a =
match a with
| PAml(MLint _) -> cond
| PAml ml ->
FIXME : use explicit equality function
if List.mem ml cond then cond else ml::cond
| _ -> cond
in
Array.fold_left aux cond args
let extract_prim ml_of l =
let decl = ref [] in
let cond = ref [] in
let rec aux l =
match l with
| Lprim(prefix,kn,p,args) ->
let args = Array.map aux args in
cond := add_check !cond args;
PAprim(prefix,kn,p,args)
| Lrel _ | Lvar _ | Luint _ | Lval _ | Lconst _ -> PAml (ml_of l)
| _ ->
let x = fresh_lname Anonymous in
decl := (x,ml_of l)::!decl;
PAml (MLlocal x) in
let res = aux l in
(!decl, !cond, res)
let app_prim p args = MLapp(MLprimitive p, args)
let to_int v =
match v with
| MLapp(MLprimitive Mk_uint, t) ->
begin match t.(0) with
| MLuint i -> MLint (Uint31.to_int i)
| _ -> MLapp(MLprimitive Val_to_int, [|v|])
end
| MLapp(MLprimitive Mk_int, t) -> t.(0)
| _ -> MLapp(MLprimitive Val_to_int, [|v|])
let of_int v =
match v with
| MLapp(MLprimitive Val_to_int, t) -> t.(0)
| _ -> MLapp(MLprimitive Mk_int,[|v|])
let compile_prim decl cond paux =
let args_to_int args =
for i = 0 to Array.length args - 1 do
args.(i ) < - to_int args.(i )
done ;
args in
let args_to_int args =
for i = 0 to Array.length args - 1 do
args.(i) <- to_int args.(i)
done;
args in
*)
let rec opt_prim_aux paux =
match paux with
| PAprim(prefix, kn, op, args) ->
let args = Array.map opt_prim_aux args in
app_prim (Coq_primitive(op,None)) args
TODO : check if this inling was useful
begin match op with
| Int31lt - >
if Sys.word_size = 64 then
app_prim Mk_bool [ |(app_prim MLlt ( args_to_int args))| ]
else app_prim ( Coq_primitive ( Primitives . Int31lt , None ) ) args
| Int31le - >
if Sys.word_size = 64 then
app_prim Mk_bool [ |(app_prim MLle ( args_to_int args))| ]
else app_prim ( Coq_primitive ( Primitives . Int31le , None ) ) args
| Int31lsl - > of_int ( mk_lsl ( args_to_int args ) )
| Int31lsr - > of_int ( mk_lsr ( args_to_int args ) )
| Int31land - > of_int ( mk_land ( args_to_int args ) )
| Int31lor - > of_int ( mk_lor ( args_to_int args ) )
| Int31lxor - > of_int ( ( args_to_int args ) )
| Int31add - > of_int ( ( args_to_int args ) )
| Int31sub - > of_int ( mk_sub ( args_to_int args ) )
| Int31mul - > of_int ( mk_mul ( args_to_int args ) )
| _ - > app_prim ( Coq_primitive(op , None ) ) args
end
TODO: check if this inling was useful
begin match op with
| Int31lt ->
if Sys.word_size = 64 then
app_prim Mk_bool [|(app_prim MLlt (args_to_int args))|]
else app_prim (Coq_primitive (Primitives.Int31lt,None)) args
| Int31le ->
if Sys.word_size = 64 then
app_prim Mk_bool [|(app_prim MLle (args_to_int args))|]
else app_prim (Coq_primitive (Primitives.Int31le, None)) args
| Int31lsl -> of_int (mk_lsl (args_to_int args))
| Int31lsr -> of_int (mk_lsr (args_to_int args))
| Int31land -> of_int (mk_land (args_to_int args))
| Int31lor -> of_int (mk_lor (args_to_int args))
| Int31lxor -> of_int (mk_lxor (args_to_int args))
| Int31add -> of_int (mk_add (args_to_int args))
| Int31sub -> of_int (mk_sub (args_to_int args))
| Int31mul -> of_int (mk_mul (args_to_int args))
| _ -> app_prim (Coq_primitive(op,None)) args
end *)
| PAml ml -> ml
and naive_prim_aux paux =
match paux with
| PAprim(prefix, kn, op, args) ->
app_prim (Coq_primitive(op, Some (prefix, kn))) (Array.map naive_prim_aux args)
| PAml ml -> ml in
let compile_cond cond paux =
match cond with
| [] -> opt_prim_aux paux
| [c1] ->
MLif(app_prim Is_int [|c1|], opt_prim_aux paux, naive_prim_aux paux)
| c1::cond ->
let cond =
List.fold_left
(fun ml c -> app_prim MLland [| ml; to_int c|])
(app_prim MLland [|to_int c1; MLint 0 |]) cond in
let cond = app_prim MLmagic [|cond|] in
MLif(cond, naive_prim_aux paux, opt_prim_aux paux) in
let add_decl decl body =
List.fold_left (fun body (x,d) -> MLlet(x,d,body)) body decl in
add_decl decl (compile_cond cond paux)
let rec ml_of_lam env l t =
match t with
| Lrel(id ,i) -> get_rel env id i
| Lvar id -> get_var env id
| Lmeta(mv,ty) ->
let tyn = fresh_lname Anonymous in
let i = push_symbol (SymbMeta mv) in
MLapp(MLprimitive Mk_meta, [|get_meta_code i; MLlocal tyn|])
| Levar(ev,ty) ->
let tyn = fresh_lname Anonymous in
let i = push_symbol (SymbEvar ev) in
MLlet(tyn, ml_of_lam env l ty,
MLapp(MLprimitive Mk_evar, [|get_evar_code i;MLlocal tyn|]))
| Lprod(dom,codom) ->
let dom = ml_of_lam env l dom in
let codom = ml_of_lam env l codom in
let n = get_prod_name codom in
let i = push_symbol (SymbName n) in
MLapp(MLprimitive Mk_prod, [|get_name_code i;dom;codom|])
| Llam(ids,body) ->
let lnames,env = push_rels env ids in
MLlam(lnames, ml_of_lam env l body)
| Llet(id,def,body) ->
let def = ml_of_lam env l def in
let lname, env = push_rel env id in
let body = ml_of_lam env l body in
MLlet(lname,def,body)
| Lapp(f,args) ->
MLapp(ml_of_lam env l f, Array.map (ml_of_lam env l) args)
| Lconst (prefix,c) -> MLglobal(Gconstant (prefix,c))
| Lproj (prefix,c) -> MLglobal(Gproj (prefix,c))
| Lprim _ ->
let decl,cond,paux = extract_prim (ml_of_lam env l) t in
compile_prim decl cond paux
| Lcase (annot,p,a,bs) ->
let compilation of p
let rec case_uid fv a_uid =
match a_uid with
| Accu _ = > mk_sw ( predicate_uid fv_pred ) ( case_uid fv ) a_uid
| Ci argsi = > compilation of branches
compile case = case_uid fv ( compilation of a )
let rec case_uid fv a_uid =
match a_uid with
| Accu _ => mk_sw (predicate_uid fv_pred) (case_uid fv) a_uid
| Ci argsi => compilation of branches
compile case = case_uid fv (compilation of a) *)
(* Compilation of the predicate *)
(* Remark: if we do not want to compile the predicate we
should a least compute the fv, then store the lambda representation
of the predicate (not the mllambda) *)
let env_p = empty_env () in
let pn = fresh_gpred l in
let mlp = ml_of_lam env_p l p in
let mlp = generalize_fv env_p mlp in
let (pfvn,pfvr) = !(env_p.env_named), !(env_p.env_urel) in
let pn = push_global_let pn mlp in
(* Compilation of the case *)
let env_c = empty_env () in
let a_uid = fresh_lname Anonymous in
let la_uid = MLlocal a_uid in
(* compilation of branches *)
let ml_br (c,params, body) =
let lnames, env = push_rels env_c params in
(c, lnames, ml_of_lam env l body) in
let bs = Array.map ml_br bs in
let cn = fresh_gcase l in
(* Compilation of accu branch *)
let pred = MLapp(MLglobal pn, fv_args env_c pfvn pfvr) in
let (fvn, fvr) = !(env_c.env_named), !(env_c.env_urel) in
let cn_fv = mkMLapp (MLglobal cn) (fv_args env_c fvn fvr) in
(* remark : the call to fv_args does not add free variables in env_c *)
let i = push_symbol (SymbMatch annot) in
let accu =
MLapp(MLprimitive Mk_sw,
[| get_match_code i; MLapp (MLprimitive Cast_accu, [|la_uid|]);
pred;
cn_fv |]) in
let body = ] , MLmatch(annot , la_uid , accu , bs ) ) in
let case = generalize_fv env_c body in
let case = generalize_fv env_c body in *)
let cn = push_global_case cn (Array.append (fv_params env_c) [|a_uid|])
annot la_uid accu (merge_branches bs)
in
(* Final result *)
let arg = ml_of_lam env l a in
let force =
if annot.asw_finite then arg
else MLapp(MLprimitive Force_cofix, [|arg|]) in
mkMLapp (MLapp (MLglobal cn, fv_args env fvn fvr)) [|force|]
| Lif(t,bt,bf) ->
MLif(ml_of_lam env l t, ml_of_lam env l bt, ml_of_lam env l bf)
| Lfix ((rec_pos,start), (ids, tt, tb)) ->
let type_f fvt = [ | type fix | ]
let norm_f1 fv f1 .. fn params1 = body1
..
let fv f1 .. fn paramsn = bodyn
let norm fv f1 .. fn =
[ |norm_f1 fv f1 .. fn ; .. ; fv f1 .. fn| ]
compile fix =
let rec f1 params1 =
if is_accu rec_pos.(1 ) then ( type_f fvt ) ( norm fv ) params1
else norm_f1 fv f1 .. fn params1
and .. and fn paramsn =
if is_accu rec_pos.(n ) then ( type_f fvt ) ( norm fv ) paramsn
else fv f1 .. fv paramsn in
start
let norm_f1 fv f1 .. fn params1 = body1
..
let norm_fn fv f1 .. fn paramsn = bodyn
let norm fv f1 .. fn =
[|norm_f1 fv f1 .. fn; ..; norm_fn fv f1 .. fn|]
compile fix =
let rec f1 params1 =
if is_accu rec_pos.(1) then mk_fix (type_f fvt) (norm fv) params1
else norm_f1 fv f1 .. fn params1
and .. and fn paramsn =
if is_accu rec_pos.(n) then mk_fix (type_f fvt) (norm fv) paramsn
else norm_fn fv f1 .. fv paramsn in
start
*)
(* Compilation of type *)
let env_t = empty_env () in
let ml_t = Array.map (ml_of_lam env_t l) tt in
let params_t = fv_params env_t in
let args_t = fv_args env !(env_t.env_named) !(env_t.env_urel) in
let gft = fresh_gfixtype l in
let gft = push_global_fixtype gft params_t ml_t in
let mk_type = MLapp(MLglobal gft, args_t) in
(* Compilation of norm_i *)
let ndef = Array.length ids in
let lf,env_n = push_rels (empty_env ()) ids in
let t_params = Array.make ndef [||] in
let t_norm_f = Array.make ndef (Gnorm (l,-1)) in
let mk_let envi (id,def) t = MLlet (id,def,t) in
let mk_lam_or_let (params,lets,env) (id,def) =
let ln,env' = push_rel env id in
match def with
| None -> (ln::params,lets,env')
| Some lam -> (params, (ln,ml_of_lam env l lam)::lets,env')
in
let ml_of_fix i body =
let varsi, bodyi = decompose_Llam_Llet body in
let paramsi,letsi,envi =
Array.fold_left mk_lam_or_let ([],[],env_n) varsi
in
let paramsi,letsi =
Array.of_list (List.rev paramsi), Array.of_list (List.rev letsi)
in
t_norm_f.(i) <- fresh_gnorm l;
let bodyi = ml_of_lam envi l bodyi in
t_params.(i) <- paramsi;
let bodyi = Array.fold_right (mk_let envi) letsi bodyi in
mkMLlam paramsi bodyi
in
let tnorm = Array.mapi ml_of_fix tb in
let fvn,fvr = !(env_n.env_named), !(env_n.env_urel) in
let fv_params = fv_params env_n in
let fv_args' = Array.map (fun id -> MLlocal id) fv_params in
let norm_params = Array.append fv_params lf in
let t_norm_f = Array.mapi (fun i body ->
push_global_let (t_norm_f.(i)) (mkMLlam norm_params body)) tnorm in
let norm = fresh_gnormtbl l in
let norm = push_global_norm norm fv_params
(Array.map (fun g -> mkMLapp (MLglobal g) fv_args') t_norm_f) in
(* Compilation of fix *)
let fv_args = fv_args env fvn fvr in
let lf, env = push_rels env ids in
let lf_args = Array.map (fun id -> MLlocal id) lf in
let mk_norm = MLapp(MLglobal norm, fv_args) in
let mkrec i lname =
let paramsi = t_params.(i) in
let reci = MLlocal (paramsi.(rec_pos.(i))) in
let pargsi = Array.map (fun id -> MLlocal id) paramsi in
let body =
MLif(MLapp(MLprimitive Is_accu,[|reci|]),
mkMLapp
(MLapp(MLprimitive (Mk_fix(rec_pos,i)),
[|mk_type; mk_norm|]))
pargsi,
MLapp(MLglobal t_norm_f.(i),
Array.concat [fv_args;lf_args;pargsi]))
in
(lname, paramsi, body) in
MLletrec(Array.mapi mkrec lf, lf_args.(start))
| Lcofix (start, (ids, tt, tb)) ->
(* Compilation of type *)
let env_t = empty_env () in
let ml_t = Array.map (ml_of_lam env_t l) tt in
let params_t = fv_params env_t in
let args_t = fv_args env !(env_t.env_named) !(env_t.env_urel) in
let gft = fresh_gfixtype l in
let gft = push_global_fixtype gft params_t ml_t in
let mk_type = MLapp(MLglobal gft, args_t) in
(* Compilation of norm_i *)
let ndef = Array.length ids in
let lf,env_n = push_rels (empty_env ()) ids in
let t_params = Array.make ndef [||] in
let t_norm_f = Array.make ndef (Gnorm (l,-1)) in
let ml_of_fix i body =
let idsi,bodyi = decompose_Llam body in
let paramsi, envi = push_rels env_n idsi in
t_norm_f.(i) <- fresh_gnorm l;
let bodyi = ml_of_lam envi l bodyi in
t_params.(i) <- paramsi;
mkMLlam paramsi bodyi in
let tnorm = Array.mapi ml_of_fix tb in
let fvn,fvr = !(env_n.env_named), !(env_n.env_urel) in
let fv_params = fv_params env_n in
let fv_args' = Array.map (fun id -> MLlocal id) fv_params in
let norm_params = Array.append fv_params lf in
let t_norm_f = Array.mapi (fun i body ->
push_global_let (t_norm_f.(i)) (mkMLlam norm_params body)) tnorm in
let norm = fresh_gnormtbl l in
let norm = push_global_norm norm fv_params
(Array.map (fun g -> mkMLapp (MLglobal g) fv_args') t_norm_f) in
(* Compilation of fix *)
let fv_args = fv_args env fvn fvr in
let mk_norm = MLapp(MLglobal norm, fv_args) in
let lnorm = fresh_lname Anonymous in
let ltype = fresh_lname Anonymous in
let lf, env = push_rels env ids in
let lf_args = Array.map (fun id -> MLlocal id) lf in
let upd i lname cont =
let paramsi = t_params.(i) in
let pargsi = Array.map (fun id -> MLlocal id) paramsi in
let uniti = fresh_lname Anonymous in
let body =
MLlam(Array.append paramsi [|uniti|],
MLapp(MLglobal t_norm_f.(i),
Array.concat [fv_args;lf_args;pargsi])) in
MLsequence(MLapp(MLprimitive Upd_cofix, [|lf_args.(i);body|]),
cont) in
let upd = Array.fold_right_i upd lf lf_args.(start) in
let mk_let i lname cont =
MLlet(lname,
MLapp(MLprimitive(Mk_cofix i),[| MLlocal ltype; MLlocal lnorm|]),
cont) in
let init = Array.fold_right_i mk_let lf upd in
MLlet(lnorm, mk_norm, MLlet(ltype, mk_type, init))
let mkrec i lname =
let paramsi = t_params.(i ) in
let pargsi = Array.map ( fun i d - > MLlocal i d ) paramsi in
let uniti = fresh_lname Anonymous in
let body =
MLapp ( MLprimitive(Mk_cofix i ) ,
[ |mk_type;mk_norm ;
MLlam([|uniti| ] ,
) ,
Array.concat [ fv_args;lf_args;pargsi]))| ] ) in
( lname , paramsi , body ) in
, lf_args.(start ) )
let mkrec i lname =
let paramsi = t_params.(i) in
let pargsi = Array.map (fun id -> MLlocal id) paramsi in
let uniti = fresh_lname Anonymous in
let body =
MLapp( MLprimitive(Mk_cofix i),
[|mk_type;mk_norm;
MLlam([|uniti|],
MLapp(MLglobal t_norm_f.(i),
Array.concat [fv_args;lf_args;pargsi]))|]) in
(lname, paramsi, body) in
MLletrec(Array.mapi mkrec lf, lf_args.(start)) *)
| Lmakeblock (prefix,cn,_,args) ->
MLconstruct(prefix,cn,Array.map (ml_of_lam env l) args)
| Lconstruct (prefix, cn) ->
MLglobal (Gconstruct (prefix, cn))
| Luint v ->
(match v with
| UintVal i -> MLapp(MLprimitive Mk_uint, [|MLuint i|])
| UintDigits (prefix,cn,ds) ->
let c = MLglobal (Gconstruct (prefix, cn)) in
let ds = Array.map (ml_of_lam env l) ds in
let i31 = MLapp (MLprimitive Mk_I31_accu, [|c|]) in
MLapp(i31, ds)
| UintDecomp (prefix,cn,t) ->
let c = MLglobal (Gconstruct (prefix, cn)) in
let t = ml_of_lam env l t in
MLapp (MLprimitive Decomp_uint, [|c;t|]))
| Lval v ->
let i = push_symbol (SymbValue v) in get_value_code i
| Lsort s ->
let i = push_symbol (SymbSort s) in
MLapp(MLprimitive Mk_sort, [|get_sort_code i|])
| Lind (prefix, ind) -> MLglobal (Gind (prefix, ind))
| Llazy -> MLglobal (Ginternal "lazy")
| Lforce -> MLglobal (Ginternal "Lazy.force")
let mllambda_of_lambda auxdefs l t =
let env = empty_env () in
global_stack := auxdefs;
let ml = ml_of_lam env l t in
let fv_rel = !(env.env_urel) in
let fv_named = !(env.env_named) in
(* build the free variables *)
let get_lname (_,t) =
match t with
| MLlocal x -> x
| _ -> assert false in
let params =
List.append (List.map get_lname fv_rel) (List.map get_lname fv_named) in
if List.is_empty params then
(!global_stack, ([],[]), ml)
(* final result : global list, fv, ml *)
else
(!global_stack, (fv_named, fv_rel), mkMLlam (Array.of_list params) ml)
(** Code optimization **)
(** Optimization of match and fix *)
let can_subst l =
match l with
| MLlocal _ | MLint _ | MLuint _ | MLglobal _ -> true
| _ -> false
let subst s l =
if LNmap.is_empty s then l
else
let rec aux l =
match l with
| MLlocal id -> (try LNmap.find id s with Not_found -> l)
| MLglobal _ | MLprimitive _ | MLint _ | MLuint _ -> l
| MLlam(params,body) -> MLlam(params, aux body)
| MLletrec(defs,body) ->
let arec (f,params,body) = (f,params,aux body) in
MLletrec(Array.map arec defs, aux body)
| MLlet(id,def,body) -> MLlet(id,aux def, aux body)
| MLapp(f,args) -> MLapp(aux f, Array.map aux args)
| MLif(t,b1,b2) -> MLif(aux t, aux b1, aux b2)
| MLmatch(annot,a,accu,bs) ->
let auxb (cargs,body) = (cargs,aux body) in
MLmatch(annot,a,aux accu, Array.map auxb bs)
| MLconstruct(prefix,c,args) -> MLconstruct(prefix,c,Array.map aux args)
| MLsetref(s,l1) -> MLsetref(s,aux l1)
| MLsequence(l1,l2) -> MLsequence(aux l1, aux l2)
in
aux l
let add_subst id v s =
match v with
| MLlocal id' when Int.equal id.luid id'.luid -> s
| _ -> LNmap.add id v s
let subst_norm params args s =
let len = Array.length params in
assert (Int.equal (Array.length args) len && Array.for_all can_subst args);
let s = ref s in
for i = 0 to len - 1 do
s := add_subst params.(i) args.(i) !s
done;
!s
let subst_case params args s =
let len = Array.length params in
assert (len > 0 &&
Int.equal (Array.length args) len &&
let r = ref true and i = ref 0 in
(* we test all arguments excepted the last *)
while !i < len - 1 && !r do r := can_subst args.(!i); incr i done;
!r);
let s = ref s in
for i = 0 to len - 2 do
s := add_subst params.(i) args.(i) !s
done;
!s, params.(len-1), args.(len-1)
let empty_gdef = Int.Map.empty, Int.Map.empty
let get_norm (gnorm, _) i = Int.Map.find i gnorm
let get_case (_, gcase) i = Int.Map.find i gcase
let all_lam n bs =
let f (_, l) =
match l with
| MLlam(params, _) -> Int.equal (Array.length params) n
| _ -> false in
Array.for_all f bs
let commutative_cut annot a accu bs args =
let mkb (c,b) =
match b with
| MLlam(params, body) ->
(c, Array.fold_left2 (fun body x v -> MLlet(x,v,body)) body params args)
| _ -> assert false in
MLmatch(annot, a, mkMLapp accu args, Array.map mkb bs)
let optimize gdef l =
let rec optimize s l =
match l with
| MLlocal id -> (try LNmap.find id s with Not_found -> l)
| MLglobal _ | MLprimitive _ | MLint _ | MLuint _ -> l
| MLlam(params,body) ->
MLlam(params, optimize s body)
| MLletrec(decls,body) ->
let opt_rec (f,params,body) = (f,params,optimize s body ) in
MLletrec(Array.map opt_rec decls, optimize s body)
| MLlet(id,def,body) ->
let def = optimize s def in
if can_subst def then optimize (add_subst id def s) body
else MLlet(id,def,optimize s body)
| MLapp(f, args) ->
let args = Array.map (optimize s) args in
begin match f with
| MLglobal (Gnorm (_,i)) ->
(try
let params,body = get_norm gdef i in
let s = subst_norm params args s in
optimize s body
with Not_found -> MLapp(optimize s f, args))
| MLglobal (Gcase (_,i)) ->
(try
let params,body = get_case gdef i in
let s, id, arg = subst_case params args s in
if can_subst arg then optimize (add_subst id arg s) body
else MLlet(id, arg, optimize s body)
with Not_found -> MLapp(optimize s f, args))
| _ ->
let f = optimize s f in
match f with
| MLmatch (annot,a,accu,bs) ->
if all_lam (Array.length args) bs then
commutative_cut annot a accu bs args
else MLapp(f, args)
| _ -> MLapp(f, args)
end
| MLif(t,b1,b2) ->
let t = optimize s t in
let b1 = optimize s b1 in
let b2 = optimize s b2 in
begin match t, b2 with
| MLapp(MLprimitive Is_accu,[| l1 |]), MLmatch(annot, l2, _, bs)
when l1 == l2 -> MLmatch(annot, l1, b1, bs) (** approximation *)
| _, _ -> MLif(t, b1, b2)
end
| MLmatch(annot,a,accu,bs) ->
let opt_b (cargs,body) = (cargs,optimize s body) in
MLmatch(annot, optimize s a, subst s accu, Array.map opt_b bs)
| MLconstruct(prefix,c,args) ->
MLconstruct(prefix,c,Array.map (optimize s) args)
| MLsetref(r,l) -> MLsetref(r, optimize s l)
| MLsequence(l1,l2) -> MLsequence(optimize s l1, optimize s l2)
in
optimize LNmap.empty l
let optimize_stk stk =
let add_global gdef g =
match g with
| Glet (Gnorm (_,i), body) ->
let (gnorm, gcase) = gdef in
(Int.Map.add i (decompose_MLlam body) gnorm, gcase)
| Gletcase(Gcase (_,i), params, annot,a,accu,bs) ->
let (gnorm,gcase) = gdef in
(gnorm, Int.Map.add i (params,MLmatch(annot,a,accu,bs)) gcase)
| Gletcase _ -> assert false
| _ -> gdef in
let gdef = List.fold_left add_global empty_gdef stk in
let optimize_global g =
match g with
| Glet(Gconstant (prefix, c), body) ->
Glet(Gconstant (prefix, c), optimize gdef body)
| _ -> g in
List.map optimize_global stk
(** Printing to ocaml **)
(* Redefine a bunch of functions in module Names to generate names
acceptable to OCaml. *)
let string_of_id s = Unicode.ascii_of_ident (string_of_id s)
let string_of_label l = Unicode.ascii_of_ident (string_of_label l)
let string_of_dirpath = function
| [] -> "_"
| sl -> String.concat "_" (List.rev_map string_of_id sl)
The first letter of the file name has to be a capital to be accepted by
(* OCaml as a module identifier. *)
let string_of_dirpath s = "N"^string_of_dirpath s
let mod_uid_of_dirpath dir = string_of_dirpath (repr_dirpath dir)
let link_info_of_dirpath dir =
Linked (mod_uid_of_dirpath dir ^ ".")
let string_of_name x =
match x with
| Anonymous -> "anonymous" (* assert false *)
| Name id -> string_of_id id
let string_of_label_def l =
match l with
| None -> ""
| Some l -> string_of_label l
(* Relativization of module paths *)
let rec list_of_mp acc = function
| MPdot (mp,l) -> list_of_mp (string_of_label l::acc) mp
| MPfile dp ->
let dp = repr_dirpath dp in
string_of_dirpath dp :: acc
| MPbound mbid -> ("X"^string_of_id (id_of_mbid mbid))::acc
let list_of_mp mp = list_of_mp [] mp
let string_of_kn kn =
let (mp,dp,l) = repr_kn kn in
let mp = list_of_mp mp in
String.concat "_" mp ^ "_" ^ string_of_label l
let string_of_con c = string_of_kn (user_con c)
let string_of_mind mind = string_of_kn (user_mind mind)
let string_of_gname g =
match g with
| Gind (prefix, (mind, i)) ->
Format.sprintf "%sindaccu_%s_%i" prefix (string_of_mind mind) i
| Gconstruct (prefix, ((mind, i), j)) ->
Format.sprintf "%sconstruct_%s_%i_%i" prefix (string_of_mind mind) i (j-1)
| Gconstant (prefix, c) ->
Format.sprintf "%sconst_%s" prefix (string_of_con c)
| Gproj (prefix, c) ->
Format.sprintf "%sproj_%s" prefix (string_of_con c)
| Gcase (l,i) ->
Format.sprintf "case_%s_%i" (string_of_label_def l) i
| Gpred (l,i) ->
Format.sprintf "pred_%s_%i" (string_of_label_def l) i
| Gfixtype (l,i) ->
Format.sprintf "fixtype_%s_%i" (string_of_label_def l) i
| Gnorm (l,i) ->
Format.sprintf "norm_%s_%i" (string_of_label_def l) i
| Ginternal s -> Format.sprintf "%s" s
| Gnormtbl (l,i) ->
Format.sprintf "normtbl_%s_%i" (string_of_label_def l) i
| Grel i ->
Format.sprintf "rel_%i" i
| Gnamed id ->
Format.sprintf "named_%s" (string_of_id id)
let pp_gname fmt g =
Format.fprintf fmt "%s" (string_of_gname g)
let pp_lname fmt ln =
let s = Unicode.ascii_of_ident (string_of_name ln.lname) in
Format.fprintf fmt "x_%s_%i" s ln.luid
let pp_ldecls fmt ids =
let len = Array.length ids in
for i = 0 to len - 1 do
Format.fprintf fmt " (%a : Nativevalues.t)" pp_lname ids.(i)
done
let string_of_construct prefix ((mind,i),j) =
let id = Format.sprintf "Construct_%s_%i_%i" (string_of_mind mind) i (j-1) in
prefix ^ id
let pp_int fmt i =
if i < 0 then Format.fprintf fmt "(%i)" i else Format.fprintf fmt "%i" i
let pp_mllam fmt l =
let rec pp_mllam fmt l =
match l with
| MLlocal ln -> Format.fprintf fmt "@[%a@]" pp_lname ln
| MLglobal g -> Format.fprintf fmt "@[%a@]" pp_gname g
| MLprimitive p -> Format.fprintf fmt "@[%a@]" pp_primitive p
| MLlam(ids,body) ->
Format.fprintf fmt "@[(fun%a@ ->@\n %a)@]"
pp_ldecls ids pp_mllam body
| MLletrec(defs, body) ->
Format.fprintf fmt "@[%a@ in@\n%a@]" pp_letrec defs
pp_mllam body
| MLlet(id,def,body) ->
Format.fprintf fmt "@[(let@ %a@ =@\n %a@ in@\n%a)@]"
pp_lname id pp_mllam def pp_mllam body
| MLapp(f, args) ->
Format.fprintf fmt "@[%a@ %a@]" pp_mllam f (pp_args true) args
| MLif(t,l1,l2) ->
Format.fprintf fmt "@[(if %a then@\n %a@\nelse@\n %a)@]"
pp_mllam t pp_mllam l1 pp_mllam l2
| MLmatch (annot, c, accu_br, br) ->
let mind,i = annot.asw_ind in
let prefix = annot.asw_prefix in
let accu = Format.sprintf "%sAccu_%s_%i" prefix (string_of_mind mind) i in
Format.fprintf fmt
"@[begin match Obj.magic (%a) with@\n| %s _ ->@\n %a@\n%aend@]"
pp_mllam c accu pp_mllam accu_br (pp_branches prefix) br
| MLconstruct(prefix,c,args) ->
Format.fprintf fmt "@[(Obj.magic (%s%a) : Nativevalues.t)@]"
(string_of_construct prefix c) pp_cargs args
| MLint i -> pp_int fmt i
| MLuint i -> Format.fprintf fmt "(Uint31.of_int %a)" pp_int (Uint31.to_int i)
| MLsetref (s, body) ->
Format.fprintf fmt "@[%s@ :=@\n %a@]" s pp_mllam body
| MLsequence(l1,l2) ->
Format.fprintf fmt "@[%a;@\n%a@]" pp_mllam l1 pp_mllam l2
and pp_letrec fmt defs =
let len = Array.length defs in
let pp_one_rec i (fn, argsn, body) =
Format.fprintf fmt "%a%a =@\n %a"
pp_lname fn
pp_ldecls argsn pp_mllam body in
Format.fprintf fmt "@[let rec ";
pp_one_rec 0 defs.(0);
for i = 1 to len - 1 do
Format.fprintf fmt "@\nand ";
pp_one_rec i defs.(i)
done;
and pp_blam fmt l =
match l with
| MLprimitive (Mk_prod | Mk_sort) (* FIXME: why this special case? *)
| MLlam _ | MLletrec _ | MLlet _ | MLapp _ | MLif _ ->
Format.fprintf fmt "(%a)" pp_mllam l
| MLconstruct(_,_,args) when Array.length args > 0 ->
Format.fprintf fmt "(%a)" pp_mllam l
| _ -> pp_mllam fmt l
and pp_args sep fmt args =
let sep = if sep then " " else "," in
let len = Array.length args in
if len > 0 then begin
Format.fprintf fmt "%a" pp_blam args.(0);
for i = 1 to len - 1 do
Format.fprintf fmt "%s%a" sep pp_blam args.(i)
done
end
and pp_cargs fmt args =
let len = Array.length args in
match len with
| 0 -> ()
| 1 -> Format.fprintf fmt " %a" pp_blam args.(0)
| _ -> Format.fprintf fmt "(%a)" (pp_args false) args
and pp_cparam fmt param =
match param with
| Some l -> pp_mllam fmt (MLlocal l)
| None -> Format.fprintf fmt "_"
and pp_cparams fmt params =
let len = Array.length params in
match len with
| 0 -> ()
| 1 -> Format.fprintf fmt " %a" pp_cparam params.(0)
| _ ->
let aux fmt params =
Format.fprintf fmt "%a" pp_cparam params.(0);
for i = 1 to len - 1 do
Format.fprintf fmt ",%a" pp_cparam params.(i)
done in
Format.fprintf fmt "(%a)" aux params
and pp_branches prefix fmt bs =
let pp_branch (cargs,body) =
let pp_c fmt (cn,args) =
Format.fprintf fmt "| %s%a "
(string_of_construct prefix cn) pp_cparams args in
let rec pp_cargs fmt cargs =
match cargs with
| [] -> ()
| cargs::cargs' ->
Format.fprintf fmt "%a%a" pp_c cargs pp_cargs cargs' in
Format.fprintf fmt "%a ->@\n %a@\n"
pp_cargs cargs pp_mllam body
in
Array.iter pp_branch bs
and pp_primitive fmt = function
| Mk_prod -> Format.fprintf fmt "mk_prod_accu"
| Mk_sort -> Format.fprintf fmt "mk_sort_accu"
| Mk_ind -> Format.fprintf fmt "mk_ind_accu"
| Mk_const -> Format.fprintf fmt "mk_constant_accu"
| Mk_sw -> Format.fprintf fmt "mk_sw_accu"
| Mk_fix(rec_pos,start) ->
let pp_rec_pos fmt rec_pos =
Format.fprintf fmt "@[[| %i" rec_pos.(0);
for i = 1 to Array.length rec_pos - 1 do
Format.fprintf fmt "; %i" rec_pos.(i)
done;
Format.fprintf fmt " |]@]" in
Format.fprintf fmt "mk_fix_accu %a %i" pp_rec_pos rec_pos start
| Mk_cofix(start) -> Format.fprintf fmt "mk_cofix_accu %i" start
| Mk_rel i -> Format.fprintf fmt "mk_rel_accu %i" i
| Mk_var id ->
Format.fprintf fmt "mk_var_accu (Names.id_of_string \"%s\")" (string_of_id id)
| Mk_proj -> Format.fprintf fmt "mk_proj_accu"
| Is_accu -> Format.fprintf fmt "is_accu"
| Is_int -> Format.fprintf fmt "is_int"
| Cast_accu -> Format.fprintf fmt "cast_accu"
| Upd_cofix -> Format.fprintf fmt "upd_cofix"
| Force_cofix -> Format.fprintf fmt "force_cofix"
| Mk_uint -> Format.fprintf fmt "mk_uint"
| Mk_int -> Format.fprintf fmt "mk_int"
| Mk_bool -> Format.fprintf fmt "mk_bool"
| Val_to_int -> Format.fprintf fmt "val_to_int"
| Mk_I31_accu -> Format.fprintf fmt "mk_I31_accu"
| Decomp_uint -> Format.fprintf fmt "decomp_uint"
| Mk_meta -> Format.fprintf fmt "mk_meta_accu"
| Mk_evar -> Format.fprintf fmt "mk_evar_accu"
| MLand -> Format.fprintf fmt "(&&)"
| MLle -> Format.fprintf fmt "(<=)"
| MLlt -> Format.fprintf fmt "(<)"
| MLinteq -> Format.fprintf fmt "(==)"
| MLlsl -> Format.fprintf fmt "(lsl)"
| MLlsr -> Format.fprintf fmt "(lsr)"
| MLland -> Format.fprintf fmt "(land)"
| MLlor -> Format.fprintf fmt "(lor)"
| MLlxor -> Format.fprintf fmt "(lxor)"
| MLadd -> Format.fprintf fmt "(+)"
| MLsub -> Format.fprintf fmt "(-)"
| MLmul -> Format.fprintf fmt "( * )"
| MLmagic -> Format.fprintf fmt "Obj.magic"
| Coq_primitive (op,None) ->
Format.fprintf fmt "no_check_%s" (Primitives.to_string op)
| Coq_primitive (op, Some (prefix,kn)) ->
Format.fprintf fmt "%s %a" (Primitives.to_string op)
pp_mllam (MLglobal (Gconstant (prefix,kn)))
in
Format.fprintf fmt "@[%a@]" pp_mllam l
let pp_array fmt t =
let len = Array.length t in
Format.fprintf fmt "@[[|";
for i = 0 to len - 2 do
Format.fprintf fmt "%a; " pp_mllam t.(i)
done;
if len > 0 then
Format.fprintf fmt "%a" pp_mllam t.(len - 1);
Format.fprintf fmt "|]@]"
let pp_global fmt g =
match g with
| Glet (gn, c) ->
let ids, c = decompose_MLlam c in
Format.fprintf fmt "@[let %a%a =@\n %a@]@\n@." pp_gname gn
pp_ldecls ids
pp_mllam c
| Gopen s ->
Format.fprintf fmt "@[open %s@]@." s
| Gtype ((mind, i), lar) ->
let l = string_of_mind mind in
let rec aux s ar =
if Int.equal ar 0 then s else aux (s^" * Nativevalues.t") (ar-1) in
let pp_const_sig i fmt j ar =
let sig_str = if ar > 0 then aux "of Nativevalues.t" (ar-1) else "" in
Format.fprintf fmt " | Construct_%s_%i_%i %s@\n" l i j sig_str
in
let pp_const_sigs i fmt lar =
Format.fprintf fmt " | Accu_%s_%i of Nativevalues.t@\n" l i;
Array.iteri (pp_const_sig i fmt) lar
in
Format.fprintf fmt "@[type ind_%s_%i =@\n%a@]@\n@." l i (pp_const_sigs i) lar
| Gtblfixtype (g, params, t) ->
Format.fprintf fmt "@[let %a %a =@\n %a@]@\n@." pp_gname g
pp_ldecls params pp_array t
| Gtblnorm (g, params, t) ->
Format.fprintf fmt "@[let %a %a =@\n %a@]@\n@." pp_gname g
pp_ldecls params pp_array t
| Gletcase(gn,params,annot,a,accu,bs) ->
Format.fprintf fmt "@[(* Hash = %i *)@\nlet rec %a %a =@\n %a@]@\n@."
(hash_global g)
pp_gname gn pp_ldecls params
pp_mllam (MLmatch(annot,a,accu,bs))
| Gcomment s ->
Format.fprintf fmt "@[(* %s *)@]@." s
(** Compilation of elements in environment **)
let rec compile_with_fv env sigma auxdefs l t =
let (auxdefs,(fv_named,fv_rel),ml) = mllambda_of_lambda auxdefs l t in
if List.is_empty fv_named && List.is_empty fv_rel then (auxdefs,ml)
else apply_fv env sigma (fv_named,fv_rel) auxdefs ml
and apply_fv env sigma (fv_named,fv_rel) auxdefs ml =
let get_rel_val (n,_) auxdefs =
(*
match !(lookup_rel_native_val n env) with
| NVKnone ->
*)
compile_rel env sigma auxdefs n
| NVKvalue ( v , d ) - > assert false
in
let get_named_val (id,_) auxdefs =
(*
match !(lookup_named_native_val id env) with
| NVKnone ->
*)
compile_named env sigma auxdefs id
| NVKvalue ( v , d ) - > assert false
in
let auxdefs = List.fold_right get_rel_val fv_rel auxdefs in
let auxdefs = List.fold_right get_named_val fv_named auxdefs in
let lvl = rel_context_length env.env_rel_context in
let fv_rel = List.map (fun (n,_) -> MLglobal (Grel (lvl-n))) fv_rel in
let fv_named = List.map (fun (id,_) -> MLglobal (Gnamed id)) fv_named in
let aux_name = fresh_lname Anonymous in
auxdefs, MLlet(aux_name, ml, mkMLapp (MLlocal aux_name) (Array.of_list (fv_rel@fv_named)))
and compile_rel env sigma auxdefs n =
let (_,body,_) = lookup_rel n env.env_rel_context in
let n = rel_context_length env.env_rel_context - n in
match body with
| Some t ->
let code = lambda_of_constr env sigma t in
let auxdefs,code = compile_with_fv env sigma auxdefs None code in
Glet(Grel n, code)::auxdefs
| None ->
Glet(Grel n, MLprimitive (Mk_rel n))::auxdefs
and compile_named env sigma auxdefs id =
let (_,body,_) = lookup_named id env.env_named_context in
match body with
| Some t ->
let code = lambda_of_constr env sigma t in
let auxdefs,code = compile_with_fv env sigma auxdefs None code in
Glet(Gnamed id, code)::auxdefs
| None ->
Glet(Gnamed id, MLprimitive (Mk_var id))::auxdefs
let compile_constant env sigma prefix ~interactive con cb =
match cb.const_proj with
| None ->
begin match cb.const_body with
| Def t ->
let t = Mod_subst.force_constr t in
let code = lambda_of_constr env sigma t in
if !Flags.debug then Pp.msg_debug (Pp.str "Generated lambda code");
let is_lazy = is_lazy prefix t in
let code = if is_lazy then mk_lazy code else code in
let name =
if interactive then LinkedInteractive prefix
else Linked prefix
in
let l = con_label con in
let auxdefs,code = compile_with_fv env sigma [] (Some l) code in
if !Flags.debug then Pp.msg_debug (Pp.str "Generated mllambda code");
let code =
optimize_stk (Glet(Gconstant ("",con),code)::auxdefs)
in
if !Flags.debug then Pp.msg_debug (Pp.str "Optimized mllambda code");
code, name
| _ ->
let i = push_symbol (SymbConst con) in
[Glet(Gconstant ("",con), MLapp (MLprimitive Mk_const, [|get_const_code i|]))],
if interactive then LinkedInteractive prefix
else Linked prefix
end
| Some pb ->
let mind = pb.proj_ind in
let ind = (mind,0) in
let mib = lookup_mind mind env in
let oib = mib.mind_packets.(0) in
let tbl = oib.mind_reloc_tbl in
(* Building info *)
let prefix = get_mind_prefix env mind in
let ci = { ci_ind = ind; ci_npar = mib.mind_nparams;
ci_cstr_nargs = [|0|];
FIXME
FIXME
let asw = { asw_ind = ind; asw_prefix = prefix; asw_ci = ci;
asw_reloc = tbl; asw_finite = true } in
let c_uid = fresh_lname Anonymous in
let _, arity = tbl.(0) in
let ci_uid = fresh_lname Anonymous in
let cargs = Array.init arity
(fun i -> if Int.equal i pb.proj_arg then Some ci_uid else None)
in
let i = push_symbol (SymbConst con) in
let accu = MLapp (MLprimitive Cast_accu, [|MLlocal c_uid|]) in
let accu_br = MLapp (MLprimitive Mk_proj, [|get_const_code i;accu|]) in
let code = MLmatch(asw,MLlocal c_uid,accu_br,[|[((ind,1),cargs)],MLlocal ci_uid|]) in
let gn = Gproj ("",con) in
let fargs = Array.init (pb.proj_npars + 1) (fun _ -> fresh_lname Anonymous) in
let arg = fargs.(pb.proj_npars) in
Glet(Gconstant ("",con), mkMLlam fargs (MLapp (MLglobal gn, [|MLlocal
arg|])))::
[Glet(gn, mkMLlam [|c_uid|] code)], Linked prefix
let loaded_native_files = ref ([] : string list)
let is_loaded_native_file s = String.List.mem s !loaded_native_files
let register_native_file s =
if not (is_loaded_native_file s) then
loaded_native_files := s :: !loaded_native_files
let is_code_loaded ~interactive name =
match !name with
| NotLinked -> false
| LinkedInteractive s ->
if (interactive && is_loaded_native_file s) then true
else (name := NotLinked; false)
| Linked s ->
if is_loaded_native_file s then true
else (name := NotLinked; false)
let param_name = Name (id_of_string "params")
let arg_name = Name (id_of_string "arg")
let compile_mind prefix ~interactive mb mind stack =
let f i stack ob =
let gtype = Gtype((mind, i), Array.map snd ob.mind_reloc_tbl) in
let j = push_symbol (SymbInd (mind,i)) in
let name = Gind ("", (mind, i)) in
let accu =
Glet(name, MLapp (MLprimitive Mk_ind, [|get_ind_code j|]))
in
let nparams = mb.mind_nparams in
let params =
Array.init nparams (fun i -> {lname = param_name; luid = i}) in
let add_construct j acc (_,arity) =
let args = Array.init arity (fun k -> {lname = arg_name; luid = k}) in
let c = (mind,i), (j+1) in
Glet(Gconstruct ("",c),
mkMLlam (Array.append params args)
(MLconstruct("", c, Array.map (fun id -> MLlocal id) args)))::acc
in
Array.fold_left_i add_construct (gtype::accu::stack) ob.mind_reloc_tbl
in
Array.fold_left_i f stack mb.mind_packets
type code_location_update =
link_info ref * link_info
type code_location_updates =
code_location_update Mindmap_env.t * code_location_update Cmap_env.t
type linkable_code = global list * code_location_updates
let empty_updates = Mindmap_env.empty, Cmap_env.empty
let compile_mind_deps env prefix ~interactive
(comp_stack, (mind_updates, const_updates) as init) mind =
let mib,nameref = lookup_mind_key mind env in
if is_code_loaded ~interactive nameref
|| Mindmap_env.mem mind mind_updates
then init
else
let comp_stack =
compile_mind prefix ~interactive mib mind comp_stack
in
let name =
if interactive then LinkedInteractive prefix
else Linked prefix
in
let upd = (nameref, name) in
let mind_updates = Mindmap_env.add mind upd mind_updates in
(comp_stack, (mind_updates, const_updates))
(* This function compiles all necessary dependencies of t, and generates code in
reverse order, as well as linking information updates *)
let rec compile_deps env sigma prefix ~interactive init t =
match kind_of_term t with
| Ind ((mind,_),u) -> compile_mind_deps env prefix ~interactive init mind
| Const (c,u) ->
let c = get_allias env c in
let cb,(nameref,_) = lookup_constant_key c env in
let (_, (_, const_updates)) = init in
if is_code_loaded ~interactive nameref
|| (Cmap_env.mem c const_updates)
then init
else
let comp_stack, (mind_updates, const_updates) = match cb.const_body with
| Def t ->
compile_deps env sigma prefix ~interactive init (Mod_subst.force_constr t)
| _ -> init
in
let code, name =
compile_constant env sigma prefix ~interactive c cb
in
let comp_stack = code@comp_stack in
let const_updates = Cmap_env.add c (nameref, name) const_updates in
comp_stack, (mind_updates, const_updates)
| Construct (((mind,_),_),u) -> compile_mind_deps env prefix ~interactive init mind
| Proj (p,c) ->
let term = mkApp (mkConst (Projection.constant p), [|c|]) in
compile_deps env sigma prefix ~interactive init term
| Case (ci, p, c, ac) ->
let mind = fst ci.ci_ind in
let init = compile_mind_deps env prefix ~interactive init mind in
fold_constr (compile_deps env sigma prefix ~interactive) init t
| _ -> fold_constr (compile_deps env sigma prefix ~interactive) init t
let compile_constant_field env prefix con acc cb =
let (gl, _) =
compile_constant ~interactive:false env empty_evars prefix
con cb
in
gl@acc
let compile_mind_field prefix mp l acc mb =
let mind = MutInd.make2 mp l in
compile_mind prefix ~interactive:false mb mind acc
let mk_open s = Gopen s
let mk_internal_let s code =
Glet(Ginternal s, code)
ML Code for conversion function
let mk_conv_code env sigma prefix t1 t2 =
clear_symb_tbl ();
clear_global_tbl ();
let gl, (mind_updates, const_updates) =
let init = ([], empty_updates) in
compile_deps env sigma prefix ~interactive:true init t1
in
let gl, (mind_updates, const_updates) =
let init = (gl, (mind_updates, const_updates)) in
compile_deps env sigma prefix ~interactive:true init t2
in
let code1 = lambda_of_constr env sigma t1 in
let code2 = lambda_of_constr env sigma t2 in
let (gl,code1) = compile_with_fv env sigma gl None code1 in
let (gl,code2) = compile_with_fv env sigma gl None code2 in
let t1 = mk_internal_let "t1" code1 in
let t2 = mk_internal_let "t2" code2 in
let g1 = MLglobal (Ginternal "t1") in
let g2 = MLglobal (Ginternal "t2") in
let setref1 = Glet(Ginternal "_", MLsetref("rt1",g1)) in
let setref2 = Glet(Ginternal "_", MLsetref("rt2",g2)) in
let gl = List.rev (setref2 :: setref1 :: t2 :: t1 :: gl) in
let header = Glet(Ginternal "symbols_tbl",
MLapp (MLglobal (Ginternal "get_symbols_tbl"),
[|MLglobal (Ginternal "()")|])) in
header::gl, (mind_updates, const_updates)
let mk_norm_code env sigma prefix t =
clear_symb_tbl ();
clear_global_tbl ();
let gl, (mind_updates, const_updates) =
let init = ([], empty_updates) in
compile_deps env sigma prefix ~interactive:true init t
in
let code = lambda_of_constr env sigma t in
let (gl,code) = compile_with_fv env sigma gl None code in
let t1 = mk_internal_let "t1" code in
let g1 = MLglobal (Ginternal "t1") in
let setref = Glet(Ginternal "_", MLsetref("rt1",g1)) in
let gl = List.rev (setref :: t1 :: gl) in
let header = Glet(Ginternal "symbols_tbl",
MLapp (MLglobal (Ginternal "get_symbols_tbl"),
[|MLglobal (Ginternal "()")|])) in
header::gl, (mind_updates, const_updates)
let mk_library_header dir =
let libname = Format.sprintf "(str_decode \"%s\")" (str_encode dir) in
[Glet(Ginternal "symbols_tbl",
MLapp (MLglobal (Ginternal "get_library_symbols_tbl"),
[|MLglobal (Ginternal libname)|]))]
let update_location (r,v) = r := v
let update_locations (ind_updates,const_updates) =
Mindmap_env.iter (fun _ -> update_location) ind_updates;
Cmap_env.iter (fun _ -> update_location) const_updates
let add_header_comment mlcode s =
Gcomment s :: mlcode
vim : set filetype = = marker :
| null | https://raw.githubusercontent.com/pirapira/coq2rust/22e8aaefc723bfb324ca2001b2b8e51fcc923543/kernel/nativecode.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
* Local names *
* Global names *
prefix, inductive name
prefix, constructor name
prefix, constant name
prefix, constant name
* Symbols (pre-computed values) *
* FIXME: how is this even valid?
* FIXME
* Lambda to Mllambda *
argument, prefix, accu branch, branches
prefix, constructor name, arguments
we require here that patterns have the same order, which may be too strong
argument, accu branch, branches
s Global declaration
ind name, arities of constructors
Alpha-equivalence on globals
s Compilation environment
(MLlocal lname) list
length of env_rel
free variables
list of unbound rel
s Traduction of lambda to mllambda
* ppedrot: It seems we only want to factorize common branches. It should
not matter to do so with a subapproximation by (==).
Compilation of the predicate
Remark: if we do not want to compile the predicate we
should a least compute the fv, then store the lambda representation
of the predicate (not the mllambda)
Compilation of the case
compilation of branches
Compilation of accu branch
remark : the call to fv_args does not add free variables in env_c
Final result
Compilation of type
Compilation of norm_i
Compilation of fix
Compilation of type
Compilation of norm_i
Compilation of fix
build the free variables
final result : global list, fv, ml
* Code optimization *
* Optimization of match and fix
we test all arguments excepted the last
* approximation
* Printing to ocaml *
Redefine a bunch of functions in module Names to generate names
acceptable to OCaml.
OCaml as a module identifier.
assert false
Relativization of module paths
FIXME: why this special case?
* Compilation of elements in environment *
match !(lookup_rel_native_val n env) with
| NVKnone ->
match !(lookup_named_native_val id env) with
| NVKnone ->
Building info
This function compiles all necessary dependencies of t, and generates code in
reverse order, as well as linking information updates | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2013
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Errors
open Names
open Term
open Context
open Declarations
open Util
open Nativevalues
open Primitives
open Nativeinstr
open Nativelambda
open Pre_env
* This file defines the mllambda code generation phase of the native
compiler . mllambda represents a fragment of ML , and can easily be printed
to OCaml code .
compiler. mllambda represents a fragment of ML, and can easily be printed
to OCaml code. *)
type lname = { lname : name; luid : int }
let dummy_lname = { lname = Anonymous; luid = -1 }
module LNord =
struct
type t = lname
let compare l1 l2 = l1.luid - l2.luid
end
module LNmap = Map.Make(LNord)
module LNset = Set.Make(LNord)
let lname_ctr = ref (-1)
let reset_lname = lname_ctr := -1
let fresh_lname n =
incr lname_ctr;
{ lname = n; luid = !lname_ctr }
type gname =
| Gcase of label option * int
| Gpred of label option * int
| Gfixtype of label option * int
| Gnorm of label option * int
| Gnormtbl of label option * int
| Ginternal of string
| Grel of int
| Gnamed of identifier
let eq_gname gn1 gn2 =
match gn1, gn2 with
| Gind (s1, ind1), Gind (s2, ind2) -> String.equal s1 s2 && eq_ind ind1 ind2
| Gconstruct (s1, c1), Gconstruct (s2, c2) ->
String.equal s1 s2 && eq_constructor c1 c2
| Gconstant (s1, c1), Gconstant (s2, c2) ->
String.equal s1 s2 && Constant.equal c1 c2
| Gcase (None, i1), Gcase (None, i2) -> Int.equal i1 i2
| Gcase (Some l1, i1), Gcase (Some l2, i2) -> Int.equal i1 i2 && Label.equal l1 l2
| Gpred (None, i1), Gpred (None, i2) -> Int.equal i1 i2
| Gpred (Some l1, i1), Gpred (Some l2, i2) -> Int.equal i1 i2 && Label.equal l1 l2
| Gfixtype (None, i1), Gfixtype (None, i2) -> Int.equal i1 i2
| Gfixtype (Some l1, i1), Gfixtype (Some l2, i2) ->
Int.equal i1 i2 && Label.equal l1 l2
| Gnorm (None, i1), Gnorm (None, i2) -> Int.equal i1 i2
| Gnorm (Some l1, i1), Gnorm (Some l2, i2) -> Int.equal i1 i2 && Label.equal l1 l2
| Gnormtbl (None, i1), Gnormtbl (None, i2) -> Int.equal i1 i2
| Gnormtbl (Some l1, i1), Gnormtbl (Some l2, i2) ->
Int.equal i1 i2 && Label.equal l1 l2
| Ginternal s1, Ginternal s2 -> String.equal s1 s2
| Grel i1, Grel i2 -> Int.equal i1 i2
| Gnamed id1, Gnamed id2 -> Id.equal id1 id2
| _ -> false
open Hashset.Combine
let gname_hash gn = match gn with
| Gind (s, i) -> combinesmall 1 (combine (String.hash s) (ind_hash i))
| Gconstruct (s, c) -> combinesmall 2 (combine (String.hash s) (constructor_hash c))
| Gconstant (s, c) -> combinesmall 3 (combine (String.hash s) (Constant.hash c))
| Gcase (l, i) -> combinesmall 4 (combine (Option.hash Label.hash l) (Int.hash i))
| Gpred (l, i) -> combinesmall 5 (combine (Option.hash Label.hash l) (Int.hash i))
| Gfixtype (l, i) -> combinesmall 6 (combine (Option.hash Label.hash l) (Int.hash i))
| Gnorm (l, i) -> combinesmall 7 (combine (Option.hash Label.hash l) (Int.hash i))
| Gnormtbl (l, i) -> combinesmall 8 (combine (Option.hash Label.hash l) (Int.hash i))
| Ginternal s -> combinesmall 9 (String.hash s)
| Grel i -> combinesmall 10 (Int.hash i)
| Gnamed id -> combinesmall 11 (Id.hash id)
| Gproj (s, p) -> combinesmall 12 (combine (String.hash s) (Constant.hash p))
let case_ctr = ref (-1)
let reset_gcase () = case_ctr := -1
let fresh_gcase l =
incr case_ctr;
Gcase (l,!case_ctr)
let pred_ctr = ref (-1)
let reset_gpred () = pred_ctr := -1
let fresh_gpred l =
incr pred_ctr;
Gpred (l,!pred_ctr)
let fixtype_ctr = ref (-1)
let reset_gfixtype () = fixtype_ctr := -1
let fresh_gfixtype l =
incr fixtype_ctr;
Gfixtype (l,!fixtype_ctr)
let norm_ctr = ref (-1)
let reset_norm () = norm_ctr := -1
let fresh_gnorm l =
incr norm_ctr;
Gnorm (l,!norm_ctr)
let normtbl_ctr = ref (-1)
let reset_normtbl () = normtbl_ctr := -1
let fresh_gnormtbl l =
incr normtbl_ctr;
Gnormtbl (l,!normtbl_ctr)
type symbol =
| SymbValue of Nativevalues.t
| SymbSort of sorts
| SymbName of name
| SymbConst of constant
| SymbMatch of annot_sw
| SymbInd of inductive
| SymbMeta of metavariable
| SymbEvar of existential
let dummy_symb = SymbValue (dummy_value ())
let eq_symbol sy1 sy2 =
match sy1, sy2 with
| SymbSort s1, SymbSort s2 -> Sorts.equal s1 s2
| SymbName n1, SymbName n2 -> Name.equal n1 n2
| SymbConst kn1, SymbConst kn2 -> Constant.equal kn1 kn2
| SymbMatch sw1, SymbMatch sw2 -> eq_annot_sw sw1 sw2
| SymbInd ind1, SymbInd ind2 -> eq_ind ind1 ind2
| SymbMeta m1, SymbMeta m2 -> Int.equal m1 m2
| SymbEvar (evk1,args1), SymbEvar (evk2,args2) ->
Evar.equal evk1 evk2 && Array.for_all2 eq_constr args1 args2
| _, _ -> false
let hash_symbol symb =
match symb with
| SymbSort s -> combinesmall 2 (Sorts.hash s)
| SymbName name -> combinesmall 3 (Name.hash name)
| SymbConst c -> combinesmall 4 (Constant.hash c)
| SymbMatch sw -> combinesmall 5 (hash_annot_sw sw)
| SymbInd ind -> combinesmall 6 (ind_hash ind)
| SymbMeta m -> combinesmall 7 m
| SymbEvar (evk,args) ->
let evh = Evar.hash evk in
let hl = Array.fold_left (fun h t -> combine h (Constr.hash t)) evh args in
combinesmall 8 hl
module HashedTypeSymbol = struct
type t = symbol
let equal = eq_symbol
let hash = hash_symbol
end
module HashtblSymbol = Hashtbl.Make(HashedTypeSymbol)
let symb_tbl = HashtblSymbol.create 211
let clear_symb_tbl () = HashtblSymbol.clear symb_tbl
let get_value tbl i =
match tbl.(i) with
| SymbValue v -> v
| _ -> anomaly (Pp.str "get_value failed")
let get_sort tbl i =
match tbl.(i) with
| SymbSort s -> s
| _ -> anomaly (Pp.str "get_sort failed")
let get_name tbl i =
match tbl.(i) with
| SymbName id -> id
| _ -> anomaly (Pp.str "get_name failed")
let get_const tbl i =
match tbl.(i) with
| SymbConst kn -> kn
| _ -> anomaly (Pp.str "get_const failed")
let get_match tbl i =
match tbl.(i) with
| SymbMatch case_info -> case_info
| _ -> anomaly (Pp.str "get_match failed")
let get_ind tbl i =
match tbl.(i) with
| SymbInd ind -> ind
| _ -> anomaly (Pp.str "get_ind failed")
let get_meta tbl i =
match tbl.(i) with
| SymbMeta m -> m
| _ -> anomaly (Pp.str "get_meta failed")
let get_evar tbl i =
match tbl.(i) with
| SymbEvar ev -> ev
| _ -> anomaly (Pp.str "get_evar failed")
let push_symbol x =
try HashtblSymbol.find symb_tbl x
with Not_found ->
let i = HashtblSymbol.length symb_tbl in
HashtblSymbol.add symb_tbl x i; i
let symbols_tbl_name = Ginternal "symbols_tbl"
let get_symbols_tbl () =
let tbl = Array.make (HashtblSymbol.length symb_tbl) dummy_symb in
HashtblSymbol.iter (fun x i -> tbl.(i) <- x) symb_tbl; tbl
type primitive =
| Mk_prod
| Mk_sort
| Mk_ind
| Mk_const
| Mk_sw
| Mk_fix of rec_pos * int
| Mk_cofix of int
| Mk_rel of int
| Mk_var of identifier
| Mk_proj
| Is_accu
| Is_int
| Cast_accu
| Upd_cofix
| Force_cofix
| Mk_uint
| Mk_int
| Mk_bool
| Val_to_int
| Mk_I31_accu
| Decomp_uint
| Mk_meta
| Mk_evar
| MLand
| MLle
| MLlt
| MLinteq
| MLlsl
| MLlsr
| MLland
| MLlor
| MLlxor
| MLadd
| MLsub
| MLmul
| MLmagic
| Coq_primitive of Primitives.t * (prefix * constant) option
let eq_primitive p1 p2 =
match p1, p2 with
| Mk_prod, Mk_prod -> true
| Mk_sort, Mk_sort -> true
| Mk_ind, Mk_ind -> true
| Mk_const, Mk_const -> true
| Mk_sw, Mk_sw -> true
| Mk_fix (rp1, i1), Mk_fix (rp2, i2) -> Int.equal i1 i2 && eq_rec_pos rp1 rp2
| Mk_cofix i1, Mk_cofix i2 -> Int.equal i1 i2
| Mk_rel i1, Mk_rel i2 -> Int.equal i1 i2
| Mk_var id1, Mk_var id2 -> Id.equal id1 id2
| Is_accu, Is_accu -> true
| Cast_accu, Cast_accu -> true
| Upd_cofix, Upd_cofix -> true
| Force_cofix, Force_cofix -> true
| Mk_meta, Mk_meta -> true
| Mk_evar, Mk_evar -> true
| Mk_proj, Mk_proj -> true
| _ -> false
let primitive_hash = function
| Mk_prod -> 1
| Mk_sort -> 2
| Mk_ind -> 3
| Mk_const -> 4
| Mk_sw -> 5
| Mk_fix (r, i) ->
let h = Array.fold_left (fun h i -> combine h (Int.hash i)) 0 r in
combinesmall 6 (combine h (Int.hash i))
| Mk_cofix i ->
combinesmall 7 (Int.hash i)
| Mk_rel i ->
combinesmall 8 (Int.hash i)
| Mk_var id ->
combinesmall 9 (Id.hash id)
| Is_accu -> 10
| Is_int -> 11
| Cast_accu -> 12
| Upd_cofix -> 13
| Force_cofix -> 14
| Mk_uint -> 15
| Mk_int -> 16
| Mk_bool -> 17
| Val_to_int -> 18
| Mk_I31_accu -> 19
| Decomp_uint -> 20
| Mk_meta -> 21
| Mk_evar -> 22
| MLand -> 23
| MLle -> 24
| MLlt -> 25
| MLinteq -> 26
| MLlsl -> 27
| MLlsr -> 28
| MLland -> 29
| MLlor -> 30
| MLlxor -> 31
| MLadd -> 32
| MLsub -> 33
| MLmul -> 34
| MLmagic -> 35
| Coq_primitive (prim, None) -> combinesmall 36 (Primitives.hash prim)
| Coq_primitive (prim, Some (prefix,kn)) ->
combinesmall 37 (combine3 (String.hash prefix) (Constant.hash kn) (Primitives.hash prim))
| Mk_proj -> 38
type mllambda =
| MLlocal of lname
| MLglobal of gname
| MLprimitive of primitive
| MLlam of lname array * mllambda
| MLletrec of (lname * lname array * mllambda) array * mllambda
| MLlet of lname * mllambda * mllambda
| MLapp of mllambda * mllambda array
| MLif of mllambda * mllambda * mllambda
| MLmatch of annot_sw * mllambda * mllambda * mllam_branches
| MLconstruct of string * constructor * mllambda array
| MLint of int
| MLuint of Uint31.t
| MLsetref of string * mllambda
| MLsequence of mllambda * mllambda
and mllam_branches = ((constructor * lname option array) list * mllambda) array
let push_lnames n env lns =
snd (Array.fold_left (fun (i,r) x -> (i+1, LNmap.add x i r)) (n,env) lns)
let opush_lnames n env lns =
let oadd x i r = match x with Some ln -> LNmap.add ln i r | None -> r in
snd (Array.fold_left (fun (i,r) x -> (i+1, oadd x i r)) (n,env) lns)
Alpha - equivalence on mllambda
eq_mllambda gn2 n env1 env2 t1 t2 tests if t1 = t2 modulo = gn2
let rec eq_mllambda gn1 gn2 n env1 env2 t1 t2 =
match t1, t2 with
| MLlocal ln1, MLlocal ln2 ->
Int.equal (LNmap.find ln1 env1) (LNmap.find ln2 env2)
| MLglobal gn1', MLglobal gn2' ->
eq_gname gn1' gn2' || (eq_gname gn1 gn1' && eq_gname gn2 gn2')
| MLprimitive prim1, MLprimitive prim2 -> eq_primitive prim1 prim2
| MLlam (lns1, ml1), MLlam (lns2, ml2) ->
Int.equal (Array.length lns1) (Array.length lns2) &&
let env1 = push_lnames n env1 lns1 in
let env2 = push_lnames n env2 lns2 in
eq_mllambda gn1 gn2 (n+Array.length lns1) env1 env2 ml1 ml2
| MLletrec (defs1, body1), MLletrec (defs2, body2) ->
Int.equal (Array.length defs1) (Array.length defs2) &&
let lns1 = Array.map (fun (x,_,_) -> x) defs1 in
let lns2 = Array.map (fun (x,_,_) -> x) defs2 in
let env1 = push_lnames n env1 lns1 in
let env2 = push_lnames n env2 lns2 in
let n = n + Array.length defs1 in
eq_letrec gn1 gn2 n env1 env2 defs1 defs2 &&
eq_mllambda gn1 gn2 n env1 env2 body1 body2
| MLlet (ln1, def1, body1), MLlet (ln2, def2, body2) ->
eq_mllambda gn1 gn2 n env1 env2 def1 def2 &&
let env1 = LNmap.add ln1 n env1 in
let env2 = LNmap.add ln2 n env2 in
eq_mllambda gn1 gn2 (n+1) env1 env2 body1 body2
| MLapp (ml1, args1), MLapp (ml2, args2) ->
eq_mllambda gn1 gn2 n env1 env2 ml1 ml2 &&
Array.equal (eq_mllambda gn1 gn2 n env1 env2) args1 args2
| MLif (cond1,br1,br'1), MLif (cond2,br2,br'2) ->
eq_mllambda gn1 gn2 n env1 env2 cond1 cond2 &&
eq_mllambda gn1 gn2 n env1 env2 br1 br2 &&
eq_mllambda gn1 gn2 n env1 env2 br'1 br'2
| MLmatch (annot1, c1, accu1, br1), MLmatch (annot2, c2, accu2, br2) ->
eq_annot_sw annot1 annot2 &&
eq_mllambda gn1 gn2 n env1 env2 c1 c2 &&
eq_mllambda gn1 gn2 n env1 env2 accu1 accu2 &&
eq_mllam_branches gn1 gn2 n env1 env2 br1 br2
| MLconstruct (pf1, cs1, args1), MLconstruct (pf2, cs2, args2) ->
String.equal pf1 pf2 &&
eq_constructor cs1 cs2 &&
Array.equal (eq_mllambda gn1 gn2 n env1 env2) args1 args2
| MLint i1, MLint i2 ->
Int.equal i1 i2
| MLuint i1, MLuint i2 ->
Uint31.equal i1 i2
| MLsetref (id1, ml1), MLsetref (id2, ml2) ->
String.equal id1 id2 &&
eq_mllambda gn1 gn2 n env1 env2 ml1 ml2
| MLsequence (ml1, ml'1), MLsequence (ml2, ml'2) ->
eq_mllambda gn1 gn2 n env1 env2 ml1 ml2 &&
eq_mllambda gn1 gn2 n env1 env2 ml'1 ml'2
| _, _ -> false
and eq_letrec gn1 gn2 n env1 env2 defs1 defs2 =
let eq_def (_,args1,ml1) (_,args2,ml2) =
Int.equal (Array.length args1) (Array.length args2) &&
let env1 = push_lnames n env1 args1 in
let env2 = push_lnames n env2 args2 in
eq_mllambda gn1 gn2 (n + Array.length args1) env1 env2 ml1 ml2
in
Array.equal eq_def defs1 defs2
and eq_mllam_branches gn1 gn2 n env1 env2 br1 br2 =
let eq_cargs (cs1, args1) (cs2, args2) body1 body2 =
Int.equal (Array.length args1) (Array.length args2) &&
eq_constructor cs1 cs2 &&
let env1 = opush_lnames n env1 args1 in
let env2 = opush_lnames n env2 args2 in
eq_mllambda gn1 gn2 (n + Array.length args1) env1 env2 body1 body2
in
let eq_branch (ptl1,body1) (ptl2,body2) =
List.equal (fun pt1 pt2 -> eq_cargs pt1 pt2 body1 body2) ptl1 ptl2
in
Array.equal eq_branch br1 br2
hash_mllambda gn n env t computes the hash for t ignoring occurences of gn
let rec hash_mllambda gn n env t =
match t with
| MLlocal ln -> combinesmall 1 (LNmap.find ln env)
| MLglobal gn' -> combinesmall 2 (if eq_gname gn gn' then 0 else gname_hash gn')
| MLprimitive prim -> combinesmall 3 (primitive_hash prim)
| MLlam (lns, ml) ->
let env = push_lnames n env lns in
combinesmall 4 (combine (Array.length lns) (hash_mllambda gn (n+1) env ml))
| MLletrec (defs, body) ->
let lns = Array.map (fun (x,_,_) -> x) defs in
let env = push_lnames n env lns in
let n = n + Array.length defs in
let h = combine (hash_mllambda gn n env body) (Array.length defs) in
combinesmall 5 (hash_mllambda_letrec gn n env h defs)
| MLlet (ln, def, body) ->
let hdef = hash_mllambda gn n env def in
let env = LNmap.add ln n env in
combinesmall 6 (combine hdef (hash_mllambda gn (n+1) env body))
| MLapp (ml, args) ->
let h = hash_mllambda gn n env ml in
combinesmall 7 (hash_mllambda_array gn n env h args)
| MLif (cond,br,br') ->
let hcond = hash_mllambda gn n env cond in
let hbr = hash_mllambda gn n env br in
let hbr' = hash_mllambda gn n env br' in
combinesmall 8 (combine3 hcond hbr hbr')
| MLmatch (annot, c, accu, br) ->
let hannot = hash_annot_sw annot in
let hc = hash_mllambda gn n env c in
let haccu = hash_mllambda gn n env accu in
combinesmall 9 (hash_mllam_branches gn n env (combine3 hannot hc haccu) br)
| MLconstruct (pf, cs, args) ->
let hpf = String.hash pf in
let hcs = constructor_hash cs in
combinesmall 10 (hash_mllambda_array gn n env (combine hpf hcs) args)
| MLint i ->
combinesmall 11 i
| MLuint i ->
combinesmall 12 (Uint31.to_int i)
| MLsetref (id, ml) ->
let hid = String.hash id in
let hml = hash_mllambda gn n env ml in
combinesmall 13 (combine hid hml)
| MLsequence (ml, ml') ->
let hml = hash_mllambda gn n env ml in
let hml' = hash_mllambda gn n env ml' in
combinesmall 14 (combine hml hml')
and hash_mllambda_letrec gn n env init defs =
let hash_def (_,args,ml) =
let env = push_lnames n env args in
let nargs = Array.length args in
combine nargs (hash_mllambda gn (n + nargs) env ml)
in
Array.fold_left (fun acc t -> combine (hash_def t) acc) init defs
and hash_mllambda_array gn n env init arr =
Array.fold_left (fun acc t -> combine (hash_mllambda gn n env t) acc) init arr
and hash_mllam_branches gn n env init br =
let hash_cargs (cs, args) body =
let nargs = Array.length args in
let hcs = constructor_hash cs in
let env = opush_lnames n env args in
let hbody = hash_mllambda gn (n + nargs) env body in
combine3 nargs hcs hbody
in
let hash_branch acc (ptl,body) =
List.fold_left (fun acc t -> combine (hash_cargs t body) acc) acc ptl
in
Array.fold_left hash_branch init br
let fv_lam l =
let rec aux l bind fv =
match l with
| MLlocal l ->
if LNset.mem l bind then fv else LNset.add l fv
| MLglobal _ | MLprimitive _ | MLint _ | MLuint _ -> fv
| MLlam (ln,body) ->
let bind = Array.fold_right LNset.add ln bind in
aux body bind fv
| MLletrec(bodies,def) ->
let bind =
Array.fold_right (fun (id,_,_) b -> LNset.add id b) bodies bind in
let fv_body (_,ln,body) fv =
let bind = Array.fold_right LNset.add ln bind in
aux body bind fv in
Array.fold_right fv_body bodies (aux def bind fv)
| MLlet(l,def,body) ->
aux body (LNset.add l bind) (aux def bind fv)
| MLapp(f,args) ->
let fv_arg arg fv = aux arg bind fv in
Array.fold_right fv_arg args (aux f bind fv)
| MLif(t,b1,b2) ->
aux t bind (aux b1 bind (aux b2 bind fv))
| MLmatch(_,a,p,bs) ->
let fv = aux a bind (aux p bind fv) in
let fv_bs (cargs, body) fv =
let bind =
List.fold_right (fun (_,args) bind ->
Array.fold_right
(fun o bind -> match o with
| Some l -> LNset.add l bind
| _ -> bind) args bind)
cargs bind in
aux body bind fv in
Array.fold_right fv_bs bs fv
| MLconstruct (_,_,p) ->
Array.fold_right (fun a fv -> aux a bind fv) p fv
| MLsetref(_,l) -> aux l bind fv
| MLsequence(l1,l2) -> aux l1 bind (aux l2 bind fv) in
aux l LNset.empty LNset.empty
let mkMLlam params body =
if Array.is_empty params then body
else
match body with
| MLlam (params', body) -> MLlam(Array.append params params', body)
| _ -> MLlam(params,body)
let mkMLapp f args =
if Array.is_empty args then f
else
match f with
| MLapp(f,args') -> MLapp(f,Array.append args' args)
| _ -> MLapp(f,args)
let empty_params = [||]
let decompose_MLlam c =
match c with
| MLlam(ids,c) -> ids,c
| _ -> empty_params,c
type global =
| Gtblname of * identifier array
| Gtblnorm of gname * lname array * mllambda array
| Gtblfixtype of gname * lname array * mllambda array
| Glet of gname * mllambda
| Gletcase of
gname * lname array * annot_sw * mllambda * mllambda * mllam_branches
| Gopen of string
| Gtype of inductive * int array
| Gcomment of string
let eq_global g1 g2 =
match g1, g2 with
| Gtblnorm (gn1,lns1,mls1), Gtblnorm (gn2,lns2,mls2)
| Gtblfixtype (gn1,lns1,mls1), Gtblfixtype (gn2,lns2,mls2) ->
Int.equal (Array.length lns1) (Array.length lns2) &&
Int.equal (Array.length mls1) (Array.length mls2) &&
let env1 = push_lnames 0 LNmap.empty lns1 in
let env2 = push_lnames 0 LNmap.empty lns2 in
Array.for_all2 (eq_mllambda gn1 gn2 (Array.length lns1) env1 env2) mls1 mls2
| Glet (gn1, def1), Glet (gn2, def2) ->
eq_mllambda gn1 gn2 0 LNmap.empty LNmap.empty def1 def2
| Gletcase (gn1,lns1,annot1,c1,accu1,br1),
Gletcase (gn2,lns2,annot2,c2,accu2,br2) ->
Int.equal (Array.length lns1) (Array.length lns2) &&
let env1 = push_lnames 0 LNmap.empty lns1 in
let env2 = push_lnames 0 LNmap.empty lns2 in
let t1 = MLmatch (annot1,c1,accu1,br1) in
let t2 = MLmatch (annot2,c2,accu2,br2) in
eq_mllambda gn1 gn2 (Array.length lns1) env1 env2 t1 t2
| Gopen s1, Gopen s2 -> String.equal s1 s2
| Gtype (ind1, arr1), Gtype (ind2, arr2) ->
eq_ind ind1 ind2 && Array.equal Int.equal arr1 arr2
| Gcomment s1, Gcomment s2 -> String.equal s1 s2
| _, _ -> false
let hash_global g =
match g with
| Gtblnorm (gn,lns,mls) ->
let nlns = Array.length lns in
let nmls = Array.length mls in
let env = push_lnames 0 LNmap.empty lns in
let hmls = hash_mllambda_array gn nlns env (combine nlns nmls) mls in
combinesmall 1 hmls
| Gtblfixtype (gn,lns,mls) ->
let nlns = Array.length lns in
let nmls = Array.length mls in
let env = push_lnames 0 LNmap.empty lns in
let hmls = hash_mllambda_array gn nlns env (combine nlns nmls) mls in
combinesmall 2 hmls
| Glet (gn, def) ->
combinesmall 3 (hash_mllambda gn 0 LNmap.empty def)
| Gletcase (gn,lns,annot,c,accu,br) ->
let nlns = Array.length lns in
let env = push_lnames 0 LNmap.empty lns in
let t = MLmatch (annot,c,accu,br) in
combinesmall 4 (combine nlns (hash_mllambda gn nlns env t))
| Gopen s -> combinesmall 5 (String.hash s)
| Gtype (ind, arr) ->
combinesmall 6 (combine (ind_hash ind) (Array.fold_left combine 0 arr))
| Gcomment s -> combinesmall 7 (String.hash s)
let global_stack = ref ([] : global list)
module HashedTypeGlobal = struct
type t = global
let equal = eq_global
let hash = hash_global
end
module HashtblGlobal = Hashtbl.Make(HashedTypeGlobal)
let global_tbl = HashtblGlobal.create 19991
let clear_global_tbl () = HashtblGlobal.clear global_tbl
let push_global gn t =
try HashtblGlobal.find global_tbl t
with Not_found ->
(global_stack := t :: !global_stack;
HashtblGlobal.add global_tbl t gn; gn)
let push_global_let gn body =
push_global gn (Glet (gn,body))
let push_global_fixtype gn params body =
push_global gn (Gtblfixtype (gn,params,body))
let push_global_norm gn params body =
push_global gn (Gtblnorm (gn, params, body))
let push_global_case gn params annot a accu bs =
push_global gn (Gletcase (gn, params, annot, a, accu, bs))
type env =
env_named : (identifier * mllambda) list ref }
let empty_env () =
{ env_rel = [];
env_bound = 0;
env_urel = ref [];
env_named = ref []
}
let push_rel env id =
let local = fresh_lname id in
local, { env with
env_rel = MLlocal local :: env.env_rel;
env_bound = env.env_bound + 1
}
let push_rels env ids =
let lnames, env_rel =
Array.fold_left (fun (names,env_rel) id ->
let local = fresh_lname id in
(local::names, MLlocal local::env_rel)) ([],env.env_rel) ids in
Array.of_list (List.rev lnames), { env with
env_rel = env_rel;
env_bound = env.env_bound + Array.length ids
}
let get_rel env id i =
if i <= env.env_bound then
List.nth env.env_rel (i-1)
else
let i = i - env.env_bound in
try Int.List.assoc i !(env.env_urel)
with Not_found ->
let local = MLlocal (fresh_lname id) in
env.env_urel := (i,local) :: !(env.env_urel);
local
let get_var env id =
try Id.List.assoc id !(env.env_named)
with Not_found ->
let local = MLlocal (fresh_lname (Name id)) in
env.env_named := (id, local)::!(env.env_named);
local
let get_prod_name codom =
match codom with
| MLlam(ids,_) -> ids.(0).lname
| _ -> assert false
let get_lname (_,l) =
match l with
| MLlocal id -> id
| _ -> invalid_arg "Nativecode.get_lname"
let fv_params env =
let fvn, fvr = !(env.env_named), !(env.env_urel) in
let size = List.length fvn + List.length fvr in
if Int.equal size 0 then empty_params
else begin
let params = Array.make size dummy_lname in
let fvn = ref fvn in
let i = ref 0 in
while not (List.is_empty !fvn) do
params.(!i) <- get_lname (List.hd !fvn);
fvn := List.tl !fvn;
incr i
done;
let fvr = ref fvr in
while not (List.is_empty !fvr) do
params.(!i) <- get_lname (List.hd !fvr);
fvr := List.tl !fvr;
incr i
done;
params
end
let generalize_fv env body =
mkMLlam (fv_params env) body
let empty_args = [||]
let fv_args env fvn fvr =
let size = List.length fvn + List.length fvr in
if Int.equal size 0 then empty_args
else
begin
let args = Array.make size (MLint 0) in
let fvn = ref fvn in
let i = ref 0 in
while not (List.is_empty !fvn) do
args.(!i) <- get_var env (fst (List.hd !fvn));
fvn := List.tl !fvn;
incr i
done;
let fvr = ref fvr in
while not (List.is_empty !fvr) do
let (k,_ as kml) = List.hd !fvr in
let n = get_lname kml in
args.(!i) <- get_rel env n.lname k;
fvr := List.tl !fvr;
incr i
done;
args
end
let get_value_code i =
MLapp (MLglobal (Ginternal "get_value"),
[|MLglobal symbols_tbl_name; MLint i|])
let get_sort_code i =
MLapp (MLglobal (Ginternal "get_sort"),
[|MLglobal symbols_tbl_name; MLint i|])
let get_name_code i =
MLapp (MLglobal (Ginternal "get_name"),
[|MLglobal symbols_tbl_name; MLint i|])
let get_const_code i =
MLapp (MLglobal (Ginternal "get_const"),
[|MLglobal symbols_tbl_name; MLint i|])
let get_match_code i =
MLapp (MLglobal (Ginternal "get_match"),
[|MLglobal symbols_tbl_name; MLint i|])
let get_ind_code i =
MLapp (MLglobal (Ginternal "get_ind"),
[|MLglobal symbols_tbl_name; MLint i|])
let get_meta_code i =
MLapp (MLglobal (Ginternal "get_meta"),
[|MLglobal symbols_tbl_name; MLint i|])
let get_evar_code i =
MLapp (MLglobal (Ginternal "get_evar"),
[|MLglobal symbols_tbl_name; MLint i|])
type rlist =
| Rnil
| Rcons of (constructor * lname option array) list ref * LNset.t * mllambda * rlist'
and rlist' = rlist ref
let rm_params fv params =
Array.map (fun l -> if LNset.mem l fv then Some l else None) params
let rec insert cargs body rl =
match !rl with
| Rnil ->
let fv = fv_lam body in
let (c,params) = cargs in
let params = rm_params fv params in
rl:= Rcons(ref [(c,params)], fv, body, ref Rnil)
| Rcons(l,fv,body',rl) ->
if body == body' then
let (c,params) = cargs in
let params = rm_params fv params in
l := (c,params)::!l
else insert cargs body rl
let rec to_list rl =
match !rl with
| Rnil -> []
| Rcons(l,_,body,tl) -> (!l,body)::to_list tl
let merge_branches t =
let newt = ref Rnil in
Array.iter (fun (c,args,body) -> insert (c,args) body newt) t;
Array.of_list (to_list newt)
type prim_aux =
| PAprim of string * constant * Primitives.t * prim_aux array
| PAml of mllambda
let add_check cond args =
let aux cond a =
match a with
| PAml(MLint _) -> cond
| PAml ml ->
FIXME : use explicit equality function
if List.mem ml cond then cond else ml::cond
| _ -> cond
in
Array.fold_left aux cond args
let extract_prim ml_of l =
let decl = ref [] in
let cond = ref [] in
let rec aux l =
match l with
| Lprim(prefix,kn,p,args) ->
let args = Array.map aux args in
cond := add_check !cond args;
PAprim(prefix,kn,p,args)
| Lrel _ | Lvar _ | Luint _ | Lval _ | Lconst _ -> PAml (ml_of l)
| _ ->
let x = fresh_lname Anonymous in
decl := (x,ml_of l)::!decl;
PAml (MLlocal x) in
let res = aux l in
(!decl, !cond, res)
let app_prim p args = MLapp(MLprimitive p, args)
let to_int v =
match v with
| MLapp(MLprimitive Mk_uint, t) ->
begin match t.(0) with
| MLuint i -> MLint (Uint31.to_int i)
| _ -> MLapp(MLprimitive Val_to_int, [|v|])
end
| MLapp(MLprimitive Mk_int, t) -> t.(0)
| _ -> MLapp(MLprimitive Val_to_int, [|v|])
let of_int v =
match v with
| MLapp(MLprimitive Val_to_int, t) -> t.(0)
| _ -> MLapp(MLprimitive Mk_int,[|v|])
let compile_prim decl cond paux =
let args_to_int args =
for i = 0 to Array.length args - 1 do
args.(i ) < - to_int args.(i )
done ;
args in
let args_to_int args =
for i = 0 to Array.length args - 1 do
args.(i) <- to_int args.(i)
done;
args in
*)
let rec opt_prim_aux paux =
match paux with
| PAprim(prefix, kn, op, args) ->
let args = Array.map opt_prim_aux args in
app_prim (Coq_primitive(op,None)) args
TODO : check if this inling was useful
begin match op with
| Int31lt - >
if Sys.word_size = 64 then
app_prim Mk_bool [ |(app_prim MLlt ( args_to_int args))| ]
else app_prim ( Coq_primitive ( Primitives . Int31lt , None ) ) args
| Int31le - >
if Sys.word_size = 64 then
app_prim Mk_bool [ |(app_prim MLle ( args_to_int args))| ]
else app_prim ( Coq_primitive ( Primitives . Int31le , None ) ) args
| Int31lsl - > of_int ( mk_lsl ( args_to_int args ) )
| Int31lsr - > of_int ( mk_lsr ( args_to_int args ) )
| Int31land - > of_int ( mk_land ( args_to_int args ) )
| Int31lor - > of_int ( mk_lor ( args_to_int args ) )
| Int31lxor - > of_int ( ( args_to_int args ) )
| Int31add - > of_int ( ( args_to_int args ) )
| Int31sub - > of_int ( mk_sub ( args_to_int args ) )
| Int31mul - > of_int ( mk_mul ( args_to_int args ) )
| _ - > app_prim ( Coq_primitive(op , None ) ) args
end
TODO: check if this inling was useful
begin match op with
| Int31lt ->
if Sys.word_size = 64 then
app_prim Mk_bool [|(app_prim MLlt (args_to_int args))|]
else app_prim (Coq_primitive (Primitives.Int31lt,None)) args
| Int31le ->
if Sys.word_size = 64 then
app_prim Mk_bool [|(app_prim MLle (args_to_int args))|]
else app_prim (Coq_primitive (Primitives.Int31le, None)) args
| Int31lsl -> of_int (mk_lsl (args_to_int args))
| Int31lsr -> of_int (mk_lsr (args_to_int args))
| Int31land -> of_int (mk_land (args_to_int args))
| Int31lor -> of_int (mk_lor (args_to_int args))
| Int31lxor -> of_int (mk_lxor (args_to_int args))
| Int31add -> of_int (mk_add (args_to_int args))
| Int31sub -> of_int (mk_sub (args_to_int args))
| Int31mul -> of_int (mk_mul (args_to_int args))
| _ -> app_prim (Coq_primitive(op,None)) args
end *)
| PAml ml -> ml
and naive_prim_aux paux =
match paux with
| PAprim(prefix, kn, op, args) ->
app_prim (Coq_primitive(op, Some (prefix, kn))) (Array.map naive_prim_aux args)
| PAml ml -> ml in
let compile_cond cond paux =
match cond with
| [] -> opt_prim_aux paux
| [c1] ->
MLif(app_prim Is_int [|c1|], opt_prim_aux paux, naive_prim_aux paux)
| c1::cond ->
let cond =
List.fold_left
(fun ml c -> app_prim MLland [| ml; to_int c|])
(app_prim MLland [|to_int c1; MLint 0 |]) cond in
let cond = app_prim MLmagic [|cond|] in
MLif(cond, naive_prim_aux paux, opt_prim_aux paux) in
let add_decl decl body =
List.fold_left (fun body (x,d) -> MLlet(x,d,body)) body decl in
add_decl decl (compile_cond cond paux)
let rec ml_of_lam env l t =
match t with
| Lrel(id ,i) -> get_rel env id i
| Lvar id -> get_var env id
| Lmeta(mv,ty) ->
let tyn = fresh_lname Anonymous in
let i = push_symbol (SymbMeta mv) in
MLapp(MLprimitive Mk_meta, [|get_meta_code i; MLlocal tyn|])
| Levar(ev,ty) ->
let tyn = fresh_lname Anonymous in
let i = push_symbol (SymbEvar ev) in
MLlet(tyn, ml_of_lam env l ty,
MLapp(MLprimitive Mk_evar, [|get_evar_code i;MLlocal tyn|]))
| Lprod(dom,codom) ->
let dom = ml_of_lam env l dom in
let codom = ml_of_lam env l codom in
let n = get_prod_name codom in
let i = push_symbol (SymbName n) in
MLapp(MLprimitive Mk_prod, [|get_name_code i;dom;codom|])
| Llam(ids,body) ->
let lnames,env = push_rels env ids in
MLlam(lnames, ml_of_lam env l body)
| Llet(id,def,body) ->
let def = ml_of_lam env l def in
let lname, env = push_rel env id in
let body = ml_of_lam env l body in
MLlet(lname,def,body)
| Lapp(f,args) ->
MLapp(ml_of_lam env l f, Array.map (ml_of_lam env l) args)
| Lconst (prefix,c) -> MLglobal(Gconstant (prefix,c))
| Lproj (prefix,c) -> MLglobal(Gproj (prefix,c))
| Lprim _ ->
let decl,cond,paux = extract_prim (ml_of_lam env l) t in
compile_prim decl cond paux
| Lcase (annot,p,a,bs) ->
let compilation of p
let rec case_uid fv a_uid =
match a_uid with
| Accu _ = > mk_sw ( predicate_uid fv_pred ) ( case_uid fv ) a_uid
| Ci argsi = > compilation of branches
compile case = case_uid fv ( compilation of a )
let rec case_uid fv a_uid =
match a_uid with
| Accu _ => mk_sw (predicate_uid fv_pred) (case_uid fv) a_uid
| Ci argsi => compilation of branches
compile case = case_uid fv (compilation of a) *)
let env_p = empty_env () in
let pn = fresh_gpred l in
let mlp = ml_of_lam env_p l p in
let mlp = generalize_fv env_p mlp in
let (pfvn,pfvr) = !(env_p.env_named), !(env_p.env_urel) in
let pn = push_global_let pn mlp in
let env_c = empty_env () in
let a_uid = fresh_lname Anonymous in
let la_uid = MLlocal a_uid in
let ml_br (c,params, body) =
let lnames, env = push_rels env_c params in
(c, lnames, ml_of_lam env l body) in
let bs = Array.map ml_br bs in
let cn = fresh_gcase l in
let pred = MLapp(MLglobal pn, fv_args env_c pfvn pfvr) in
let (fvn, fvr) = !(env_c.env_named), !(env_c.env_urel) in
let cn_fv = mkMLapp (MLglobal cn) (fv_args env_c fvn fvr) in
let i = push_symbol (SymbMatch annot) in
let accu =
MLapp(MLprimitive Mk_sw,
[| get_match_code i; MLapp (MLprimitive Cast_accu, [|la_uid|]);
pred;
cn_fv |]) in
let body = ] , MLmatch(annot , la_uid , accu , bs ) ) in
let case = generalize_fv env_c body in
let case = generalize_fv env_c body in *)
let cn = push_global_case cn (Array.append (fv_params env_c) [|a_uid|])
annot la_uid accu (merge_branches bs)
in
let arg = ml_of_lam env l a in
let force =
if annot.asw_finite then arg
else MLapp(MLprimitive Force_cofix, [|arg|]) in
mkMLapp (MLapp (MLglobal cn, fv_args env fvn fvr)) [|force|]
| Lif(t,bt,bf) ->
MLif(ml_of_lam env l t, ml_of_lam env l bt, ml_of_lam env l bf)
| Lfix ((rec_pos,start), (ids, tt, tb)) ->
let type_f fvt = [ | type fix | ]
let norm_f1 fv f1 .. fn params1 = body1
..
let fv f1 .. fn paramsn = bodyn
let norm fv f1 .. fn =
[ |norm_f1 fv f1 .. fn ; .. ; fv f1 .. fn| ]
compile fix =
let rec f1 params1 =
if is_accu rec_pos.(1 ) then ( type_f fvt ) ( norm fv ) params1
else norm_f1 fv f1 .. fn params1
and .. and fn paramsn =
if is_accu rec_pos.(n ) then ( type_f fvt ) ( norm fv ) paramsn
else fv f1 .. fv paramsn in
start
let norm_f1 fv f1 .. fn params1 = body1
..
let norm_fn fv f1 .. fn paramsn = bodyn
let norm fv f1 .. fn =
[|norm_f1 fv f1 .. fn; ..; norm_fn fv f1 .. fn|]
compile fix =
let rec f1 params1 =
if is_accu rec_pos.(1) then mk_fix (type_f fvt) (norm fv) params1
else norm_f1 fv f1 .. fn params1
and .. and fn paramsn =
if is_accu rec_pos.(n) then mk_fix (type_f fvt) (norm fv) paramsn
else norm_fn fv f1 .. fv paramsn in
start
*)
let env_t = empty_env () in
let ml_t = Array.map (ml_of_lam env_t l) tt in
let params_t = fv_params env_t in
let args_t = fv_args env !(env_t.env_named) !(env_t.env_urel) in
let gft = fresh_gfixtype l in
let gft = push_global_fixtype gft params_t ml_t in
let mk_type = MLapp(MLglobal gft, args_t) in
let ndef = Array.length ids in
let lf,env_n = push_rels (empty_env ()) ids in
let t_params = Array.make ndef [||] in
let t_norm_f = Array.make ndef (Gnorm (l,-1)) in
let mk_let envi (id,def) t = MLlet (id,def,t) in
let mk_lam_or_let (params,lets,env) (id,def) =
let ln,env' = push_rel env id in
match def with
| None -> (ln::params,lets,env')
| Some lam -> (params, (ln,ml_of_lam env l lam)::lets,env')
in
let ml_of_fix i body =
let varsi, bodyi = decompose_Llam_Llet body in
let paramsi,letsi,envi =
Array.fold_left mk_lam_or_let ([],[],env_n) varsi
in
let paramsi,letsi =
Array.of_list (List.rev paramsi), Array.of_list (List.rev letsi)
in
t_norm_f.(i) <- fresh_gnorm l;
let bodyi = ml_of_lam envi l bodyi in
t_params.(i) <- paramsi;
let bodyi = Array.fold_right (mk_let envi) letsi bodyi in
mkMLlam paramsi bodyi
in
let tnorm = Array.mapi ml_of_fix tb in
let fvn,fvr = !(env_n.env_named), !(env_n.env_urel) in
let fv_params = fv_params env_n in
let fv_args' = Array.map (fun id -> MLlocal id) fv_params in
let norm_params = Array.append fv_params lf in
let t_norm_f = Array.mapi (fun i body ->
push_global_let (t_norm_f.(i)) (mkMLlam norm_params body)) tnorm in
let norm = fresh_gnormtbl l in
let norm = push_global_norm norm fv_params
(Array.map (fun g -> mkMLapp (MLglobal g) fv_args') t_norm_f) in
let fv_args = fv_args env fvn fvr in
let lf, env = push_rels env ids in
let lf_args = Array.map (fun id -> MLlocal id) lf in
let mk_norm = MLapp(MLglobal norm, fv_args) in
let mkrec i lname =
let paramsi = t_params.(i) in
let reci = MLlocal (paramsi.(rec_pos.(i))) in
let pargsi = Array.map (fun id -> MLlocal id) paramsi in
let body =
MLif(MLapp(MLprimitive Is_accu,[|reci|]),
mkMLapp
(MLapp(MLprimitive (Mk_fix(rec_pos,i)),
[|mk_type; mk_norm|]))
pargsi,
MLapp(MLglobal t_norm_f.(i),
Array.concat [fv_args;lf_args;pargsi]))
in
(lname, paramsi, body) in
MLletrec(Array.mapi mkrec lf, lf_args.(start))
| Lcofix (start, (ids, tt, tb)) ->
let env_t = empty_env () in
let ml_t = Array.map (ml_of_lam env_t l) tt in
let params_t = fv_params env_t in
let args_t = fv_args env !(env_t.env_named) !(env_t.env_urel) in
let gft = fresh_gfixtype l in
let gft = push_global_fixtype gft params_t ml_t in
let mk_type = MLapp(MLglobal gft, args_t) in
let ndef = Array.length ids in
let lf,env_n = push_rels (empty_env ()) ids in
let t_params = Array.make ndef [||] in
let t_norm_f = Array.make ndef (Gnorm (l,-1)) in
let ml_of_fix i body =
let idsi,bodyi = decompose_Llam body in
let paramsi, envi = push_rels env_n idsi in
t_norm_f.(i) <- fresh_gnorm l;
let bodyi = ml_of_lam envi l bodyi in
t_params.(i) <- paramsi;
mkMLlam paramsi bodyi in
let tnorm = Array.mapi ml_of_fix tb in
let fvn,fvr = !(env_n.env_named), !(env_n.env_urel) in
let fv_params = fv_params env_n in
let fv_args' = Array.map (fun id -> MLlocal id) fv_params in
let norm_params = Array.append fv_params lf in
let t_norm_f = Array.mapi (fun i body ->
push_global_let (t_norm_f.(i)) (mkMLlam norm_params body)) tnorm in
let norm = fresh_gnormtbl l in
let norm = push_global_norm norm fv_params
(Array.map (fun g -> mkMLapp (MLglobal g) fv_args') t_norm_f) in
let fv_args = fv_args env fvn fvr in
let mk_norm = MLapp(MLglobal norm, fv_args) in
let lnorm = fresh_lname Anonymous in
let ltype = fresh_lname Anonymous in
let lf, env = push_rels env ids in
let lf_args = Array.map (fun id -> MLlocal id) lf in
let upd i lname cont =
let paramsi = t_params.(i) in
let pargsi = Array.map (fun id -> MLlocal id) paramsi in
let uniti = fresh_lname Anonymous in
let body =
MLlam(Array.append paramsi [|uniti|],
MLapp(MLglobal t_norm_f.(i),
Array.concat [fv_args;lf_args;pargsi])) in
MLsequence(MLapp(MLprimitive Upd_cofix, [|lf_args.(i);body|]),
cont) in
let upd = Array.fold_right_i upd lf lf_args.(start) in
let mk_let i lname cont =
MLlet(lname,
MLapp(MLprimitive(Mk_cofix i),[| MLlocal ltype; MLlocal lnorm|]),
cont) in
let init = Array.fold_right_i mk_let lf upd in
MLlet(lnorm, mk_norm, MLlet(ltype, mk_type, init))
let mkrec i lname =
let paramsi = t_params.(i ) in
let pargsi = Array.map ( fun i d - > MLlocal i d ) paramsi in
let uniti = fresh_lname Anonymous in
let body =
MLapp ( MLprimitive(Mk_cofix i ) ,
[ |mk_type;mk_norm ;
MLlam([|uniti| ] ,
) ,
Array.concat [ fv_args;lf_args;pargsi]))| ] ) in
( lname , paramsi , body ) in
, lf_args.(start ) )
let mkrec i lname =
let paramsi = t_params.(i) in
let pargsi = Array.map (fun id -> MLlocal id) paramsi in
let uniti = fresh_lname Anonymous in
let body =
MLapp( MLprimitive(Mk_cofix i),
[|mk_type;mk_norm;
MLlam([|uniti|],
MLapp(MLglobal t_norm_f.(i),
Array.concat [fv_args;lf_args;pargsi]))|]) in
(lname, paramsi, body) in
MLletrec(Array.mapi mkrec lf, lf_args.(start)) *)
| Lmakeblock (prefix,cn,_,args) ->
MLconstruct(prefix,cn,Array.map (ml_of_lam env l) args)
| Lconstruct (prefix, cn) ->
MLglobal (Gconstruct (prefix, cn))
| Luint v ->
(match v with
| UintVal i -> MLapp(MLprimitive Mk_uint, [|MLuint i|])
| UintDigits (prefix,cn,ds) ->
let c = MLglobal (Gconstruct (prefix, cn)) in
let ds = Array.map (ml_of_lam env l) ds in
let i31 = MLapp (MLprimitive Mk_I31_accu, [|c|]) in
MLapp(i31, ds)
| UintDecomp (prefix,cn,t) ->
let c = MLglobal (Gconstruct (prefix, cn)) in
let t = ml_of_lam env l t in
MLapp (MLprimitive Decomp_uint, [|c;t|]))
| Lval v ->
let i = push_symbol (SymbValue v) in get_value_code i
| Lsort s ->
let i = push_symbol (SymbSort s) in
MLapp(MLprimitive Mk_sort, [|get_sort_code i|])
| Lind (prefix, ind) -> MLglobal (Gind (prefix, ind))
| Llazy -> MLglobal (Ginternal "lazy")
| Lforce -> MLglobal (Ginternal "Lazy.force")
let mllambda_of_lambda auxdefs l t =
let env = empty_env () in
global_stack := auxdefs;
let ml = ml_of_lam env l t in
let fv_rel = !(env.env_urel) in
let fv_named = !(env.env_named) in
let get_lname (_,t) =
match t with
| MLlocal x -> x
| _ -> assert false in
let params =
List.append (List.map get_lname fv_rel) (List.map get_lname fv_named) in
if List.is_empty params then
(!global_stack, ([],[]), ml)
else
(!global_stack, (fv_named, fv_rel), mkMLlam (Array.of_list params) ml)
let can_subst l =
match l with
| MLlocal _ | MLint _ | MLuint _ | MLglobal _ -> true
| _ -> false
let subst s l =
if LNmap.is_empty s then l
else
let rec aux l =
match l with
| MLlocal id -> (try LNmap.find id s with Not_found -> l)
| MLglobal _ | MLprimitive _ | MLint _ | MLuint _ -> l
| MLlam(params,body) -> MLlam(params, aux body)
| MLletrec(defs,body) ->
let arec (f,params,body) = (f,params,aux body) in
MLletrec(Array.map arec defs, aux body)
| MLlet(id,def,body) -> MLlet(id,aux def, aux body)
| MLapp(f,args) -> MLapp(aux f, Array.map aux args)
| MLif(t,b1,b2) -> MLif(aux t, aux b1, aux b2)
| MLmatch(annot,a,accu,bs) ->
let auxb (cargs,body) = (cargs,aux body) in
MLmatch(annot,a,aux accu, Array.map auxb bs)
| MLconstruct(prefix,c,args) -> MLconstruct(prefix,c,Array.map aux args)
| MLsetref(s,l1) -> MLsetref(s,aux l1)
| MLsequence(l1,l2) -> MLsequence(aux l1, aux l2)
in
aux l
let add_subst id v s =
match v with
| MLlocal id' when Int.equal id.luid id'.luid -> s
| _ -> LNmap.add id v s
let subst_norm params args s =
let len = Array.length params in
assert (Int.equal (Array.length args) len && Array.for_all can_subst args);
let s = ref s in
for i = 0 to len - 1 do
s := add_subst params.(i) args.(i) !s
done;
!s
let subst_case params args s =
let len = Array.length params in
assert (len > 0 &&
Int.equal (Array.length args) len &&
let r = ref true and i = ref 0 in
while !i < len - 1 && !r do r := can_subst args.(!i); incr i done;
!r);
let s = ref s in
for i = 0 to len - 2 do
s := add_subst params.(i) args.(i) !s
done;
!s, params.(len-1), args.(len-1)
let empty_gdef = Int.Map.empty, Int.Map.empty
let get_norm (gnorm, _) i = Int.Map.find i gnorm
let get_case (_, gcase) i = Int.Map.find i gcase
let all_lam n bs =
let f (_, l) =
match l with
| MLlam(params, _) -> Int.equal (Array.length params) n
| _ -> false in
Array.for_all f bs
let commutative_cut annot a accu bs args =
let mkb (c,b) =
match b with
| MLlam(params, body) ->
(c, Array.fold_left2 (fun body x v -> MLlet(x,v,body)) body params args)
| _ -> assert false in
MLmatch(annot, a, mkMLapp accu args, Array.map mkb bs)
let optimize gdef l =
let rec optimize s l =
match l with
| MLlocal id -> (try LNmap.find id s with Not_found -> l)
| MLglobal _ | MLprimitive _ | MLint _ | MLuint _ -> l
| MLlam(params,body) ->
MLlam(params, optimize s body)
| MLletrec(decls,body) ->
let opt_rec (f,params,body) = (f,params,optimize s body ) in
MLletrec(Array.map opt_rec decls, optimize s body)
| MLlet(id,def,body) ->
let def = optimize s def in
if can_subst def then optimize (add_subst id def s) body
else MLlet(id,def,optimize s body)
| MLapp(f, args) ->
let args = Array.map (optimize s) args in
begin match f with
| MLglobal (Gnorm (_,i)) ->
(try
let params,body = get_norm gdef i in
let s = subst_norm params args s in
optimize s body
with Not_found -> MLapp(optimize s f, args))
| MLglobal (Gcase (_,i)) ->
(try
let params,body = get_case gdef i in
let s, id, arg = subst_case params args s in
if can_subst arg then optimize (add_subst id arg s) body
else MLlet(id, arg, optimize s body)
with Not_found -> MLapp(optimize s f, args))
| _ ->
let f = optimize s f in
match f with
| MLmatch (annot,a,accu,bs) ->
if all_lam (Array.length args) bs then
commutative_cut annot a accu bs args
else MLapp(f, args)
| _ -> MLapp(f, args)
end
| MLif(t,b1,b2) ->
let t = optimize s t in
let b1 = optimize s b1 in
let b2 = optimize s b2 in
begin match t, b2 with
| MLapp(MLprimitive Is_accu,[| l1 |]), MLmatch(annot, l2, _, bs)
| _, _ -> MLif(t, b1, b2)
end
| MLmatch(annot,a,accu,bs) ->
let opt_b (cargs,body) = (cargs,optimize s body) in
MLmatch(annot, optimize s a, subst s accu, Array.map opt_b bs)
| MLconstruct(prefix,c,args) ->
MLconstruct(prefix,c,Array.map (optimize s) args)
| MLsetref(r,l) -> MLsetref(r, optimize s l)
| MLsequence(l1,l2) -> MLsequence(optimize s l1, optimize s l2)
in
optimize LNmap.empty l
let optimize_stk stk =
let add_global gdef g =
match g with
| Glet (Gnorm (_,i), body) ->
let (gnorm, gcase) = gdef in
(Int.Map.add i (decompose_MLlam body) gnorm, gcase)
| Gletcase(Gcase (_,i), params, annot,a,accu,bs) ->
let (gnorm,gcase) = gdef in
(gnorm, Int.Map.add i (params,MLmatch(annot,a,accu,bs)) gcase)
| Gletcase _ -> assert false
| _ -> gdef in
let gdef = List.fold_left add_global empty_gdef stk in
let optimize_global g =
match g with
| Glet(Gconstant (prefix, c), body) ->
Glet(Gconstant (prefix, c), optimize gdef body)
| _ -> g in
List.map optimize_global stk
let string_of_id s = Unicode.ascii_of_ident (string_of_id s)
let string_of_label l = Unicode.ascii_of_ident (string_of_label l)
let string_of_dirpath = function
| [] -> "_"
| sl -> String.concat "_" (List.rev_map string_of_id sl)
The first letter of the file name has to be a capital to be accepted by
let string_of_dirpath s = "N"^string_of_dirpath s
let mod_uid_of_dirpath dir = string_of_dirpath (repr_dirpath dir)
let link_info_of_dirpath dir =
Linked (mod_uid_of_dirpath dir ^ ".")
let string_of_name x =
match x with
| Name id -> string_of_id id
let string_of_label_def l =
match l with
| None -> ""
| Some l -> string_of_label l
let rec list_of_mp acc = function
| MPdot (mp,l) -> list_of_mp (string_of_label l::acc) mp
| MPfile dp ->
let dp = repr_dirpath dp in
string_of_dirpath dp :: acc
| MPbound mbid -> ("X"^string_of_id (id_of_mbid mbid))::acc
let list_of_mp mp = list_of_mp [] mp
let string_of_kn kn =
let (mp,dp,l) = repr_kn kn in
let mp = list_of_mp mp in
String.concat "_" mp ^ "_" ^ string_of_label l
let string_of_con c = string_of_kn (user_con c)
let string_of_mind mind = string_of_kn (user_mind mind)
let string_of_gname g =
match g with
| Gind (prefix, (mind, i)) ->
Format.sprintf "%sindaccu_%s_%i" prefix (string_of_mind mind) i
| Gconstruct (prefix, ((mind, i), j)) ->
Format.sprintf "%sconstruct_%s_%i_%i" prefix (string_of_mind mind) i (j-1)
| Gconstant (prefix, c) ->
Format.sprintf "%sconst_%s" prefix (string_of_con c)
| Gproj (prefix, c) ->
Format.sprintf "%sproj_%s" prefix (string_of_con c)
| Gcase (l,i) ->
Format.sprintf "case_%s_%i" (string_of_label_def l) i
| Gpred (l,i) ->
Format.sprintf "pred_%s_%i" (string_of_label_def l) i
| Gfixtype (l,i) ->
Format.sprintf "fixtype_%s_%i" (string_of_label_def l) i
| Gnorm (l,i) ->
Format.sprintf "norm_%s_%i" (string_of_label_def l) i
| Ginternal s -> Format.sprintf "%s" s
| Gnormtbl (l,i) ->
Format.sprintf "normtbl_%s_%i" (string_of_label_def l) i
| Grel i ->
Format.sprintf "rel_%i" i
| Gnamed id ->
Format.sprintf "named_%s" (string_of_id id)
let pp_gname fmt g =
Format.fprintf fmt "%s" (string_of_gname g)
let pp_lname fmt ln =
let s = Unicode.ascii_of_ident (string_of_name ln.lname) in
Format.fprintf fmt "x_%s_%i" s ln.luid
let pp_ldecls fmt ids =
let len = Array.length ids in
for i = 0 to len - 1 do
Format.fprintf fmt " (%a : Nativevalues.t)" pp_lname ids.(i)
done
let string_of_construct prefix ((mind,i),j) =
let id = Format.sprintf "Construct_%s_%i_%i" (string_of_mind mind) i (j-1) in
prefix ^ id
let pp_int fmt i =
if i < 0 then Format.fprintf fmt "(%i)" i else Format.fprintf fmt "%i" i
let pp_mllam fmt l =
let rec pp_mllam fmt l =
match l with
| MLlocal ln -> Format.fprintf fmt "@[%a@]" pp_lname ln
| MLglobal g -> Format.fprintf fmt "@[%a@]" pp_gname g
| MLprimitive p -> Format.fprintf fmt "@[%a@]" pp_primitive p
| MLlam(ids,body) ->
Format.fprintf fmt "@[(fun%a@ ->@\n %a)@]"
pp_ldecls ids pp_mllam body
| MLletrec(defs, body) ->
Format.fprintf fmt "@[%a@ in@\n%a@]" pp_letrec defs
pp_mllam body
| MLlet(id,def,body) ->
Format.fprintf fmt "@[(let@ %a@ =@\n %a@ in@\n%a)@]"
pp_lname id pp_mllam def pp_mllam body
| MLapp(f, args) ->
Format.fprintf fmt "@[%a@ %a@]" pp_mllam f (pp_args true) args
| MLif(t,l1,l2) ->
Format.fprintf fmt "@[(if %a then@\n %a@\nelse@\n %a)@]"
pp_mllam t pp_mllam l1 pp_mllam l2
| MLmatch (annot, c, accu_br, br) ->
let mind,i = annot.asw_ind in
let prefix = annot.asw_prefix in
let accu = Format.sprintf "%sAccu_%s_%i" prefix (string_of_mind mind) i in
Format.fprintf fmt
"@[begin match Obj.magic (%a) with@\n| %s _ ->@\n %a@\n%aend@]"
pp_mllam c accu pp_mllam accu_br (pp_branches prefix) br
| MLconstruct(prefix,c,args) ->
Format.fprintf fmt "@[(Obj.magic (%s%a) : Nativevalues.t)@]"
(string_of_construct prefix c) pp_cargs args
| MLint i -> pp_int fmt i
| MLuint i -> Format.fprintf fmt "(Uint31.of_int %a)" pp_int (Uint31.to_int i)
| MLsetref (s, body) ->
Format.fprintf fmt "@[%s@ :=@\n %a@]" s pp_mllam body
| MLsequence(l1,l2) ->
Format.fprintf fmt "@[%a;@\n%a@]" pp_mllam l1 pp_mllam l2
and pp_letrec fmt defs =
let len = Array.length defs in
let pp_one_rec i (fn, argsn, body) =
Format.fprintf fmt "%a%a =@\n %a"
pp_lname fn
pp_ldecls argsn pp_mllam body in
Format.fprintf fmt "@[let rec ";
pp_one_rec 0 defs.(0);
for i = 1 to len - 1 do
Format.fprintf fmt "@\nand ";
pp_one_rec i defs.(i)
done;
and pp_blam fmt l =
match l with
| MLlam _ | MLletrec _ | MLlet _ | MLapp _ | MLif _ ->
Format.fprintf fmt "(%a)" pp_mllam l
| MLconstruct(_,_,args) when Array.length args > 0 ->
Format.fprintf fmt "(%a)" pp_mllam l
| _ -> pp_mllam fmt l
and pp_args sep fmt args =
let sep = if sep then " " else "," in
let len = Array.length args in
if len > 0 then begin
Format.fprintf fmt "%a" pp_blam args.(0);
for i = 1 to len - 1 do
Format.fprintf fmt "%s%a" sep pp_blam args.(i)
done
end
and pp_cargs fmt args =
let len = Array.length args in
match len with
| 0 -> ()
| 1 -> Format.fprintf fmt " %a" pp_blam args.(0)
| _ -> Format.fprintf fmt "(%a)" (pp_args false) args
and pp_cparam fmt param =
match param with
| Some l -> pp_mllam fmt (MLlocal l)
| None -> Format.fprintf fmt "_"
and pp_cparams fmt params =
let len = Array.length params in
match len with
| 0 -> ()
| 1 -> Format.fprintf fmt " %a" pp_cparam params.(0)
| _ ->
let aux fmt params =
Format.fprintf fmt "%a" pp_cparam params.(0);
for i = 1 to len - 1 do
Format.fprintf fmt ",%a" pp_cparam params.(i)
done in
Format.fprintf fmt "(%a)" aux params
and pp_branches prefix fmt bs =
let pp_branch (cargs,body) =
let pp_c fmt (cn,args) =
Format.fprintf fmt "| %s%a "
(string_of_construct prefix cn) pp_cparams args in
let rec pp_cargs fmt cargs =
match cargs with
| [] -> ()
| cargs::cargs' ->
Format.fprintf fmt "%a%a" pp_c cargs pp_cargs cargs' in
Format.fprintf fmt "%a ->@\n %a@\n"
pp_cargs cargs pp_mllam body
in
Array.iter pp_branch bs
and pp_primitive fmt = function
| Mk_prod -> Format.fprintf fmt "mk_prod_accu"
| Mk_sort -> Format.fprintf fmt "mk_sort_accu"
| Mk_ind -> Format.fprintf fmt "mk_ind_accu"
| Mk_const -> Format.fprintf fmt "mk_constant_accu"
| Mk_sw -> Format.fprintf fmt "mk_sw_accu"
| Mk_fix(rec_pos,start) ->
let pp_rec_pos fmt rec_pos =
Format.fprintf fmt "@[[| %i" rec_pos.(0);
for i = 1 to Array.length rec_pos - 1 do
Format.fprintf fmt "; %i" rec_pos.(i)
done;
Format.fprintf fmt " |]@]" in
Format.fprintf fmt "mk_fix_accu %a %i" pp_rec_pos rec_pos start
| Mk_cofix(start) -> Format.fprintf fmt "mk_cofix_accu %i" start
| Mk_rel i -> Format.fprintf fmt "mk_rel_accu %i" i
| Mk_var id ->
Format.fprintf fmt "mk_var_accu (Names.id_of_string \"%s\")" (string_of_id id)
| Mk_proj -> Format.fprintf fmt "mk_proj_accu"
| Is_accu -> Format.fprintf fmt "is_accu"
| Is_int -> Format.fprintf fmt "is_int"
| Cast_accu -> Format.fprintf fmt "cast_accu"
| Upd_cofix -> Format.fprintf fmt "upd_cofix"
| Force_cofix -> Format.fprintf fmt "force_cofix"
| Mk_uint -> Format.fprintf fmt "mk_uint"
| Mk_int -> Format.fprintf fmt "mk_int"
| Mk_bool -> Format.fprintf fmt "mk_bool"
| Val_to_int -> Format.fprintf fmt "val_to_int"
| Mk_I31_accu -> Format.fprintf fmt "mk_I31_accu"
| Decomp_uint -> Format.fprintf fmt "decomp_uint"
| Mk_meta -> Format.fprintf fmt "mk_meta_accu"
| Mk_evar -> Format.fprintf fmt "mk_evar_accu"
| MLand -> Format.fprintf fmt "(&&)"
| MLle -> Format.fprintf fmt "(<=)"
| MLlt -> Format.fprintf fmt "(<)"
| MLinteq -> Format.fprintf fmt "(==)"
| MLlsl -> Format.fprintf fmt "(lsl)"
| MLlsr -> Format.fprintf fmt "(lsr)"
| MLland -> Format.fprintf fmt "(land)"
| MLlor -> Format.fprintf fmt "(lor)"
| MLlxor -> Format.fprintf fmt "(lxor)"
| MLadd -> Format.fprintf fmt "(+)"
| MLsub -> Format.fprintf fmt "(-)"
| MLmul -> Format.fprintf fmt "( * )"
| MLmagic -> Format.fprintf fmt "Obj.magic"
| Coq_primitive (op,None) ->
Format.fprintf fmt "no_check_%s" (Primitives.to_string op)
| Coq_primitive (op, Some (prefix,kn)) ->
Format.fprintf fmt "%s %a" (Primitives.to_string op)
pp_mllam (MLglobal (Gconstant (prefix,kn)))
in
Format.fprintf fmt "@[%a@]" pp_mllam l
let pp_array fmt t =
let len = Array.length t in
Format.fprintf fmt "@[[|";
for i = 0 to len - 2 do
Format.fprintf fmt "%a; " pp_mllam t.(i)
done;
if len > 0 then
Format.fprintf fmt "%a" pp_mllam t.(len - 1);
Format.fprintf fmt "|]@]"
let pp_global fmt g =
match g with
| Glet (gn, c) ->
let ids, c = decompose_MLlam c in
Format.fprintf fmt "@[let %a%a =@\n %a@]@\n@." pp_gname gn
pp_ldecls ids
pp_mllam c
| Gopen s ->
Format.fprintf fmt "@[open %s@]@." s
| Gtype ((mind, i), lar) ->
let l = string_of_mind mind in
let rec aux s ar =
if Int.equal ar 0 then s else aux (s^" * Nativevalues.t") (ar-1) in
let pp_const_sig i fmt j ar =
let sig_str = if ar > 0 then aux "of Nativevalues.t" (ar-1) else "" in
Format.fprintf fmt " | Construct_%s_%i_%i %s@\n" l i j sig_str
in
let pp_const_sigs i fmt lar =
Format.fprintf fmt " | Accu_%s_%i of Nativevalues.t@\n" l i;
Array.iteri (pp_const_sig i fmt) lar
in
Format.fprintf fmt "@[type ind_%s_%i =@\n%a@]@\n@." l i (pp_const_sigs i) lar
| Gtblfixtype (g, params, t) ->
Format.fprintf fmt "@[let %a %a =@\n %a@]@\n@." pp_gname g
pp_ldecls params pp_array t
| Gtblnorm (g, params, t) ->
Format.fprintf fmt "@[let %a %a =@\n %a@]@\n@." pp_gname g
pp_ldecls params pp_array t
| Gletcase(gn,params,annot,a,accu,bs) ->
Format.fprintf fmt "@[(* Hash = %i *)@\nlet rec %a %a =@\n %a@]@\n@."
(hash_global g)
pp_gname gn pp_ldecls params
pp_mllam (MLmatch(annot,a,accu,bs))
| Gcomment s ->
Format.fprintf fmt "@[(* %s *)@]@." s
let rec compile_with_fv env sigma auxdefs l t =
let (auxdefs,(fv_named,fv_rel),ml) = mllambda_of_lambda auxdefs l t in
if List.is_empty fv_named && List.is_empty fv_rel then (auxdefs,ml)
else apply_fv env sigma (fv_named,fv_rel) auxdefs ml
and apply_fv env sigma (fv_named,fv_rel) auxdefs ml =
let get_rel_val (n,_) auxdefs =
compile_rel env sigma auxdefs n
| NVKvalue ( v , d ) - > assert false
in
let get_named_val (id,_) auxdefs =
compile_named env sigma auxdefs id
| NVKvalue ( v , d ) - > assert false
in
let auxdefs = List.fold_right get_rel_val fv_rel auxdefs in
let auxdefs = List.fold_right get_named_val fv_named auxdefs in
let lvl = rel_context_length env.env_rel_context in
let fv_rel = List.map (fun (n,_) -> MLglobal (Grel (lvl-n))) fv_rel in
let fv_named = List.map (fun (id,_) -> MLglobal (Gnamed id)) fv_named in
let aux_name = fresh_lname Anonymous in
auxdefs, MLlet(aux_name, ml, mkMLapp (MLlocal aux_name) (Array.of_list (fv_rel@fv_named)))
and compile_rel env sigma auxdefs n =
let (_,body,_) = lookup_rel n env.env_rel_context in
let n = rel_context_length env.env_rel_context - n in
match body with
| Some t ->
let code = lambda_of_constr env sigma t in
let auxdefs,code = compile_with_fv env sigma auxdefs None code in
Glet(Grel n, code)::auxdefs
| None ->
Glet(Grel n, MLprimitive (Mk_rel n))::auxdefs
and compile_named env sigma auxdefs id =
let (_,body,_) = lookup_named id env.env_named_context in
match body with
| Some t ->
let code = lambda_of_constr env sigma t in
let auxdefs,code = compile_with_fv env sigma auxdefs None code in
Glet(Gnamed id, code)::auxdefs
| None ->
Glet(Gnamed id, MLprimitive (Mk_var id))::auxdefs
let compile_constant env sigma prefix ~interactive con cb =
match cb.const_proj with
| None ->
begin match cb.const_body with
| Def t ->
let t = Mod_subst.force_constr t in
let code = lambda_of_constr env sigma t in
if !Flags.debug then Pp.msg_debug (Pp.str "Generated lambda code");
let is_lazy = is_lazy prefix t in
let code = if is_lazy then mk_lazy code else code in
let name =
if interactive then LinkedInteractive prefix
else Linked prefix
in
let l = con_label con in
let auxdefs,code = compile_with_fv env sigma [] (Some l) code in
if !Flags.debug then Pp.msg_debug (Pp.str "Generated mllambda code");
let code =
optimize_stk (Glet(Gconstant ("",con),code)::auxdefs)
in
if !Flags.debug then Pp.msg_debug (Pp.str "Optimized mllambda code");
code, name
| _ ->
let i = push_symbol (SymbConst con) in
[Glet(Gconstant ("",con), MLapp (MLprimitive Mk_const, [|get_const_code i|]))],
if interactive then LinkedInteractive prefix
else Linked prefix
end
| Some pb ->
let mind = pb.proj_ind in
let ind = (mind,0) in
let mib = lookup_mind mind env in
let oib = mib.mind_packets.(0) in
let tbl = oib.mind_reloc_tbl in
let prefix = get_mind_prefix env mind in
let ci = { ci_ind = ind; ci_npar = mib.mind_nparams;
ci_cstr_nargs = [|0|];
FIXME
FIXME
let asw = { asw_ind = ind; asw_prefix = prefix; asw_ci = ci;
asw_reloc = tbl; asw_finite = true } in
let c_uid = fresh_lname Anonymous in
let _, arity = tbl.(0) in
let ci_uid = fresh_lname Anonymous in
let cargs = Array.init arity
(fun i -> if Int.equal i pb.proj_arg then Some ci_uid else None)
in
let i = push_symbol (SymbConst con) in
let accu = MLapp (MLprimitive Cast_accu, [|MLlocal c_uid|]) in
let accu_br = MLapp (MLprimitive Mk_proj, [|get_const_code i;accu|]) in
let code = MLmatch(asw,MLlocal c_uid,accu_br,[|[((ind,1),cargs)],MLlocal ci_uid|]) in
let gn = Gproj ("",con) in
let fargs = Array.init (pb.proj_npars + 1) (fun _ -> fresh_lname Anonymous) in
let arg = fargs.(pb.proj_npars) in
Glet(Gconstant ("",con), mkMLlam fargs (MLapp (MLglobal gn, [|MLlocal
arg|])))::
[Glet(gn, mkMLlam [|c_uid|] code)], Linked prefix
let loaded_native_files = ref ([] : string list)
let is_loaded_native_file s = String.List.mem s !loaded_native_files
let register_native_file s =
if not (is_loaded_native_file s) then
loaded_native_files := s :: !loaded_native_files
let is_code_loaded ~interactive name =
match !name with
| NotLinked -> false
| LinkedInteractive s ->
if (interactive && is_loaded_native_file s) then true
else (name := NotLinked; false)
| Linked s ->
if is_loaded_native_file s then true
else (name := NotLinked; false)
let param_name = Name (id_of_string "params")
let arg_name = Name (id_of_string "arg")
let compile_mind prefix ~interactive mb mind stack =
let f i stack ob =
let gtype = Gtype((mind, i), Array.map snd ob.mind_reloc_tbl) in
let j = push_symbol (SymbInd (mind,i)) in
let name = Gind ("", (mind, i)) in
let accu =
Glet(name, MLapp (MLprimitive Mk_ind, [|get_ind_code j|]))
in
let nparams = mb.mind_nparams in
let params =
Array.init nparams (fun i -> {lname = param_name; luid = i}) in
let add_construct j acc (_,arity) =
let args = Array.init arity (fun k -> {lname = arg_name; luid = k}) in
let c = (mind,i), (j+1) in
Glet(Gconstruct ("",c),
mkMLlam (Array.append params args)
(MLconstruct("", c, Array.map (fun id -> MLlocal id) args)))::acc
in
Array.fold_left_i add_construct (gtype::accu::stack) ob.mind_reloc_tbl
in
Array.fold_left_i f stack mb.mind_packets
type code_location_update =
link_info ref * link_info
type code_location_updates =
code_location_update Mindmap_env.t * code_location_update Cmap_env.t
type linkable_code = global list * code_location_updates
let empty_updates = Mindmap_env.empty, Cmap_env.empty
let compile_mind_deps env prefix ~interactive
(comp_stack, (mind_updates, const_updates) as init) mind =
let mib,nameref = lookup_mind_key mind env in
if is_code_loaded ~interactive nameref
|| Mindmap_env.mem mind mind_updates
then init
else
let comp_stack =
compile_mind prefix ~interactive mib mind comp_stack
in
let name =
if interactive then LinkedInteractive prefix
else Linked prefix
in
let upd = (nameref, name) in
let mind_updates = Mindmap_env.add mind upd mind_updates in
(comp_stack, (mind_updates, const_updates))
let rec compile_deps env sigma prefix ~interactive init t =
match kind_of_term t with
| Ind ((mind,_),u) -> compile_mind_deps env prefix ~interactive init mind
| Const (c,u) ->
let c = get_allias env c in
let cb,(nameref,_) = lookup_constant_key c env in
let (_, (_, const_updates)) = init in
if is_code_loaded ~interactive nameref
|| (Cmap_env.mem c const_updates)
then init
else
let comp_stack, (mind_updates, const_updates) = match cb.const_body with
| Def t ->
compile_deps env sigma prefix ~interactive init (Mod_subst.force_constr t)
| _ -> init
in
let code, name =
compile_constant env sigma prefix ~interactive c cb
in
let comp_stack = code@comp_stack in
let const_updates = Cmap_env.add c (nameref, name) const_updates in
comp_stack, (mind_updates, const_updates)
| Construct (((mind,_),_),u) -> compile_mind_deps env prefix ~interactive init mind
| Proj (p,c) ->
let term = mkApp (mkConst (Projection.constant p), [|c|]) in
compile_deps env sigma prefix ~interactive init term
| Case (ci, p, c, ac) ->
let mind = fst ci.ci_ind in
let init = compile_mind_deps env prefix ~interactive init mind in
fold_constr (compile_deps env sigma prefix ~interactive) init t
| _ -> fold_constr (compile_deps env sigma prefix ~interactive) init t
let compile_constant_field env prefix con acc cb =
let (gl, _) =
compile_constant ~interactive:false env empty_evars prefix
con cb
in
gl@acc
let compile_mind_field prefix mp l acc mb =
let mind = MutInd.make2 mp l in
compile_mind prefix ~interactive:false mb mind acc
let mk_open s = Gopen s
let mk_internal_let s code =
Glet(Ginternal s, code)
ML Code for conversion function
let mk_conv_code env sigma prefix t1 t2 =
clear_symb_tbl ();
clear_global_tbl ();
let gl, (mind_updates, const_updates) =
let init = ([], empty_updates) in
compile_deps env sigma prefix ~interactive:true init t1
in
let gl, (mind_updates, const_updates) =
let init = (gl, (mind_updates, const_updates)) in
compile_deps env sigma prefix ~interactive:true init t2
in
let code1 = lambda_of_constr env sigma t1 in
let code2 = lambda_of_constr env sigma t2 in
let (gl,code1) = compile_with_fv env sigma gl None code1 in
let (gl,code2) = compile_with_fv env sigma gl None code2 in
let t1 = mk_internal_let "t1" code1 in
let t2 = mk_internal_let "t2" code2 in
let g1 = MLglobal (Ginternal "t1") in
let g2 = MLglobal (Ginternal "t2") in
let setref1 = Glet(Ginternal "_", MLsetref("rt1",g1)) in
let setref2 = Glet(Ginternal "_", MLsetref("rt2",g2)) in
let gl = List.rev (setref2 :: setref1 :: t2 :: t1 :: gl) in
let header = Glet(Ginternal "symbols_tbl",
MLapp (MLglobal (Ginternal "get_symbols_tbl"),
[|MLglobal (Ginternal "()")|])) in
header::gl, (mind_updates, const_updates)
let mk_norm_code env sigma prefix t =
clear_symb_tbl ();
clear_global_tbl ();
let gl, (mind_updates, const_updates) =
let init = ([], empty_updates) in
compile_deps env sigma prefix ~interactive:true init t
in
let code = lambda_of_constr env sigma t in
let (gl,code) = compile_with_fv env sigma gl None code in
let t1 = mk_internal_let "t1" code in
let g1 = MLglobal (Ginternal "t1") in
let setref = Glet(Ginternal "_", MLsetref("rt1",g1)) in
let gl = List.rev (setref :: t1 :: gl) in
let header = Glet(Ginternal "symbols_tbl",
MLapp (MLglobal (Ginternal "get_symbols_tbl"),
[|MLglobal (Ginternal "()")|])) in
header::gl, (mind_updates, const_updates)
let mk_library_header dir =
let libname = Format.sprintf "(str_decode \"%s\")" (str_encode dir) in
[Glet(Ginternal "symbols_tbl",
MLapp (MLglobal (Ginternal "get_library_symbols_tbl"),
[|MLglobal (Ginternal libname)|]))]
let update_location (r,v) = r := v
let update_locations (ind_updates,const_updates) =
Mindmap_env.iter (fun _ -> update_location) ind_updates;
Cmap_env.iter (fun _ -> update_location) const_updates
let add_header_comment mlcode s =
Gcomment s :: mlcode
vim : set filetype = = marker :
|
7c24feabd7ea3f4d3f3ba91d6046d0baeb20ba0dca83789e81d73c3407ba8de7 | yetibot/core | util.clj | (ns yetibot.core.db.util
(:require
[clojure.set :refer [union]]
[clojure.spec.alpha :as s]
[clojure.string :refer [blank? join split]]
[cuerdas.core :refer [kebab snake]]
[clojure.java.jdbc :as sql]
[taoensso.timbre :refer [info color-str]]
[yetibot.core.config :refer [get-config]]))
(s/def ::url string?)
(s/def ::prefix string?)
(s/def ::table (s/keys :req-un [::prefix]))
(s/def ::db-config (s/keys :req-un [::url]
:opt-un [::table]))
(def default-db-url "postgresql:5432/yetibot")
(def default-table-prefix "yetibot_")
(defn default-fields
"All tables get these fields by default"
[]
[[:id :serial "PRIMARY KEY"]
[:created-at :timestamp "NOT NULL" "DEFAULT CURRENT_TIMESTAMP"]])
(comment
(default-fields)
)
(defn config []
(merge
;; default
{:url default-db-url
:table {:prefix default-table-prefix}}
(:value (get-config ::db-config [:db]))))
(comment
(config)
)
(defn qualified-table-name
[table-name]
(str (-> (config) :table :prefix) table-name))
(comment
(qualified-table-name "hello")
)
(defn create
[table entity]
(sql/with-db-connection [db-conn (:url (config))]
(sql/insert!
db-conn
(qualified-table-name table)
entity
{:entities snake})))
(defn delete
[table id]
(sql/with-db-connection [db-conn (:url (config))]
(sql/delete!
db-conn
(qualified-table-name table)
["id = ?" id])))
(defn find-all
([table] (find-all table {}))
([table {:keys [identifiers]}]
(sql/with-db-connection [db-conn (:url (config))]
(sql/query
db-conn
[(str "SELECT * FROM "
(qualified-table-name table))]
{:identifiers (or identifiers kebab)}))))
(defn transform-where-map
"Return a vector of where-keys and where-args to use in a select or update"
[where-map]
(if (empty? where-map)
["" []]
(let [where-keys (join " AND " (map (fn [[k _]] (str (snake k) "=?")) where-map))
where-args (vals where-map)]
[where-keys where-args])))
(comment
(transform-where-map {:foo "bar"})
(transform-where-map {:foo "bar" :bar "baz"})
(transform-where-map {})
)
(defn empty-where?
[where]
(not (and where
(not (blank? (first where)))
)))
;; this check is too aggressive, omit
( not ( empty ? ( second where ) ) ) ) ) )
(defn combine-wheres
[where1 where2]
(cond
(empty-where? where2) where1
(empty-where? where1) where2
:else (let [[w1-query w1-args] where1
[w2-query w2-args] where2]
[(str w1-query " AND " w2-query)
(into (vec w1-args)
(vec w2-args))])))
(def merge-fn
"Merge functions for specific keys supported by `query`"
{:select/clause (fn [x y]
(join ", " (concat (split x #",\s*") (split y #",\s*"))))
:where/clause (fn [x y] (str x " AND " y))})
(defn merge-queries
[& qs]
(let [ks (reduce union (map (comp set keys) qs))]
(reduce
(fn [acc i]
(into acc
(for [k ks
:let [left (k acc)
right (k i)]
:when (or (k acc) (k i))]
[k
(cond
;; both - merge them
(and left right) ((get merge-fn k into) (k acc) (k i))
;; left only
(and left (not right)) left
;; right only
(and right (not left)) right)])))
{}
qs)))
(defn generate-sql-query
"Generates SQL query string based on table and query-map args.
Allows us to seperate the generation of the SQL query and the
execution of said query"
[table query-map]
(let [{;; provide either where/map
;; or where/clause and where/args
;; or both (they will be combined)
select-clause :select/clause
where-map :where/map
where-clause :where/clause
where-args :where/args
;; optional
group-clause :group/clause
having-clause :having/clause
order-clause :order/clause
offset-clause :offset/clause
limit-clause :limit/clause} query-map
select-clause (or select-clause "*")
[where-clause where-args] (combine-wheres
(transform-where-map where-map)
[where-clause where-args])]
(into [(str "SELECT " select-clause
" FROM " (qualified-table-name table)
(when-not (blank? where-clause)
(str " WHERE " where-clause))
(when group-clause (str " GROUP BY " group-clause))
(when having-clause (str " HAVING " having-clause))
(when order-clause (str " ORDER BY " order-clause))
(when offset-clause (str " OFFSET " offset-clause))
(when limit-clause (str " LIMIT " limit-clause)))]
where-args)))
(comment
(generate-sql-query
"hello"
{:select/clause "*"
:where/map {:id 123}
:where/clause "is_awesome = ?"
:where/args [true]
:group/clause "id"
:having/clause "SUM(points) > 0"
:order/clause "id"
:offset/clause 10
:limit/clause 1})
(generate-sql-query "hello" {:select/clause "COUNT(*) as count"})
)
(defn query
"SELECT query of table arg, allowing for complex WHERE clauses that contain
predicates and/or expressions, based on provided query-map arg."
[table query-map]
(let [sql-query (generate-sql-query table query-map)]
(info "db query" (color-str :blue (pr-str sql-query)))
(seq
(sql/with-db-connection
[db-conn (:url (config))]
(sql/query db-conn
sql-query
{:identifiers (or (:query/identifiers query-map) kebab)})))))
(defn update-where
[table where-map attrs]
(let [[where-keys where-args] (transform-where-map where-map)]
(sql/with-db-connection [db-conn (:url (config))]
(sql/update!
db-conn
(qualified-table-name table)
;; transform attr keys to snake case
(into {} (for [[k v] attrs] [(snake k) v]))
(apply vector where-keys where-args)))))
(defn entity-count
[table]
(-> (query table {:select/clause "COUNT(*) as count"})
first
:count))
| null | https://raw.githubusercontent.com/yetibot/core/e35cc772622e91aec3ad7f411a99fff09acbd3f9/src/yetibot/core/db/util.clj | clojure | default
this check is too aggressive, omit
both - merge them
left only
right only
provide either where/map
or where/clause and where/args
or both (they will be combined)
optional
transform attr keys to snake case | (ns yetibot.core.db.util
(:require
[clojure.set :refer [union]]
[clojure.spec.alpha :as s]
[clojure.string :refer [blank? join split]]
[cuerdas.core :refer [kebab snake]]
[clojure.java.jdbc :as sql]
[taoensso.timbre :refer [info color-str]]
[yetibot.core.config :refer [get-config]]))
(s/def ::url string?)
(s/def ::prefix string?)
(s/def ::table (s/keys :req-un [::prefix]))
(s/def ::db-config (s/keys :req-un [::url]
:opt-un [::table]))
(def default-db-url "postgresql:5432/yetibot")
(def default-table-prefix "yetibot_")
(defn default-fields
"All tables get these fields by default"
[]
[[:id :serial "PRIMARY KEY"]
[:created-at :timestamp "NOT NULL" "DEFAULT CURRENT_TIMESTAMP"]])
(comment
(default-fields)
)
(defn config []
(merge
{:url default-db-url
:table {:prefix default-table-prefix}}
(:value (get-config ::db-config [:db]))))
(comment
(config)
)
(defn qualified-table-name
[table-name]
(str (-> (config) :table :prefix) table-name))
(comment
(qualified-table-name "hello")
)
(defn create
[table entity]
(sql/with-db-connection [db-conn (:url (config))]
(sql/insert!
db-conn
(qualified-table-name table)
entity
{:entities snake})))
(defn delete
[table id]
(sql/with-db-connection [db-conn (:url (config))]
(sql/delete!
db-conn
(qualified-table-name table)
["id = ?" id])))
(defn find-all
([table] (find-all table {}))
([table {:keys [identifiers]}]
(sql/with-db-connection [db-conn (:url (config))]
(sql/query
db-conn
[(str "SELECT * FROM "
(qualified-table-name table))]
{:identifiers (or identifiers kebab)}))))
(defn transform-where-map
"Return a vector of where-keys and where-args to use in a select or update"
[where-map]
(if (empty? where-map)
["" []]
(let [where-keys (join " AND " (map (fn [[k _]] (str (snake k) "=?")) where-map))
where-args (vals where-map)]
[where-keys where-args])))
(comment
(transform-where-map {:foo "bar"})
(transform-where-map {:foo "bar" :bar "baz"})
(transform-where-map {})
)
(defn empty-where?
[where]
(not (and where
(not (blank? (first where)))
)))
( not ( empty ? ( second where ) ) ) ) ) )
(defn combine-wheres
[where1 where2]
(cond
(empty-where? where2) where1
(empty-where? where1) where2
:else (let [[w1-query w1-args] where1
[w2-query w2-args] where2]
[(str w1-query " AND " w2-query)
(into (vec w1-args)
(vec w2-args))])))
(def merge-fn
"Merge functions for specific keys supported by `query`"
{:select/clause (fn [x y]
(join ", " (concat (split x #",\s*") (split y #",\s*"))))
:where/clause (fn [x y] (str x " AND " y))})
(defn merge-queries
[& qs]
(let [ks (reduce union (map (comp set keys) qs))]
(reduce
(fn [acc i]
(into acc
(for [k ks
:let [left (k acc)
right (k i)]
:when (or (k acc) (k i))]
[k
(cond
(and left right) ((get merge-fn k into) (k acc) (k i))
(and left (not right)) left
(and right (not left)) right)])))
{}
qs)))
(defn generate-sql-query
"Generates SQL query string based on table and query-map args.
Allows us to seperate the generation of the SQL query and the
execution of said query"
[table query-map]
select-clause :select/clause
where-map :where/map
where-clause :where/clause
where-args :where/args
group-clause :group/clause
having-clause :having/clause
order-clause :order/clause
offset-clause :offset/clause
limit-clause :limit/clause} query-map
select-clause (or select-clause "*")
[where-clause where-args] (combine-wheres
(transform-where-map where-map)
[where-clause where-args])]
(into [(str "SELECT " select-clause
" FROM " (qualified-table-name table)
(when-not (blank? where-clause)
(str " WHERE " where-clause))
(when group-clause (str " GROUP BY " group-clause))
(when having-clause (str " HAVING " having-clause))
(when order-clause (str " ORDER BY " order-clause))
(when offset-clause (str " OFFSET " offset-clause))
(when limit-clause (str " LIMIT " limit-clause)))]
where-args)))
(comment
(generate-sql-query
"hello"
{:select/clause "*"
:where/map {:id 123}
:where/clause "is_awesome = ?"
:where/args [true]
:group/clause "id"
:having/clause "SUM(points) > 0"
:order/clause "id"
:offset/clause 10
:limit/clause 1})
(generate-sql-query "hello" {:select/clause "COUNT(*) as count"})
)
(defn query
"SELECT query of table arg, allowing for complex WHERE clauses that contain
predicates and/or expressions, based on provided query-map arg."
[table query-map]
(let [sql-query (generate-sql-query table query-map)]
(info "db query" (color-str :blue (pr-str sql-query)))
(seq
(sql/with-db-connection
[db-conn (:url (config))]
(sql/query db-conn
sql-query
{:identifiers (or (:query/identifiers query-map) kebab)})))))
(defn update-where
[table where-map attrs]
(let [[where-keys where-args] (transform-where-map where-map)]
(sql/with-db-connection [db-conn (:url (config))]
(sql/update!
db-conn
(qualified-table-name table)
(into {} (for [[k v] attrs] [(snake k) v]))
(apply vector where-keys where-args)))))
(defn entity-count
[table]
(-> (query table {:select/clause "COUNT(*) as count"})
first
:count))
|
bb5cf9978cc335abc35dbc748f8c646a500952af6aea65b22e36403b2848a3a0 | IvanRublev/year_progress_bot | year_progress_bot_app_tests.erl | -module(year_progress_bot_app_tests).
-include_lib("eunit/include/eunit.hrl").
start_test_() ->
{foreach,
fun() ->
meck:new(db),
meck:expect(db, create_schema, fun() -> ok end),
meck:new(year_progress_bot_sup),
meck:expect(year_progress_bot_sup, start_link, fun() -> ok end),
meck:new(cowboy),
meck:expect(cowboy, start_clear, fun(_,_,_) -> {ok, {}} end),
meck:expect(cowboy, stop_listener, fun(_) -> ok end),
meck:new(cowboy_router),
meck:expect(cowboy_router, compile, fun(_) -> dspch end),
meck:new(telegram),
meck:expect(telegram, register_webhook, fun() -> ok end),
application:set_env([
{year_progress_bot, [
{tel_token, "tel_token"},
{tel_host, "tel_host"},
{port, 12345},
{webhook_path, "/some_uuid_path"}
]}
], [{persistent, true}])
end,
fun(_) ->
meck:unload(telegram),
meck:unload(cowboy_router),
meck:unload(cowboy),
meck:unload(year_progress_bot_sup),
meck:unload(db)
end,
[fun should_create_db_schemas_on_start/1,
fun should_start_bot_supervisor/1,
fun should_compile_route_to_endpoints/1,
fun should_start_endpoint/1,
fun should_stop_endpoint_on_stop/1,
fun should_register_webhook_on_telegram/1]}.
should_create_db_schemas_on_start(_) ->
year_progress_bot_app:start({}, {}),
?_assert(meck:called(db, create_schema, [])).
should_start_bot_supervisor(_) ->
year_progress_bot_app:start({}, {}),
?_assert(meck:called(year_progress_bot_sup, start_link, [])).
should_compile_route_to_endpoints(_) ->
year_progress_bot_app:start({}, {}),
?_assert(meck:called(cowboy_router, compile, [[
{'_', [
{"/some_uuid_path", endpoint, []},
{"/health", health, []}
]}
]])).
should_start_endpoint(_) ->
year_progress_bot_app:start({}, {}),
?_assert(meck:called(cowboy, start_clear, [http, [{port, 12345}], #{env => #{dispatch => dspch}}])).
should_stop_endpoint_on_stop(_) ->
year_progress_bot_app:stop(shutdown),
?_assert(meck:called(cowboy, stop_listener, [http])).
should_register_webhook_on_telegram(_) ->
year_progress_bot_app:start({}, {}),
?_assert(meck:called(telegram, register_webhook, '_')).
| null | https://raw.githubusercontent.com/IvanRublev/year_progress_bot/c3e85a5598d768933d5fb676c74d92fa8033cf60/apps/year_progress_bot/test/year_progress_bot_app_tests.erl | erlang | -module(year_progress_bot_app_tests).
-include_lib("eunit/include/eunit.hrl").
start_test_() ->
{foreach,
fun() ->
meck:new(db),
meck:expect(db, create_schema, fun() -> ok end),
meck:new(year_progress_bot_sup),
meck:expect(year_progress_bot_sup, start_link, fun() -> ok end),
meck:new(cowboy),
meck:expect(cowboy, start_clear, fun(_,_,_) -> {ok, {}} end),
meck:expect(cowboy, stop_listener, fun(_) -> ok end),
meck:new(cowboy_router),
meck:expect(cowboy_router, compile, fun(_) -> dspch end),
meck:new(telegram),
meck:expect(telegram, register_webhook, fun() -> ok end),
application:set_env([
{year_progress_bot, [
{tel_token, "tel_token"},
{tel_host, "tel_host"},
{port, 12345},
{webhook_path, "/some_uuid_path"}
]}
], [{persistent, true}])
end,
fun(_) ->
meck:unload(telegram),
meck:unload(cowboy_router),
meck:unload(cowboy),
meck:unload(year_progress_bot_sup),
meck:unload(db)
end,
[fun should_create_db_schemas_on_start/1,
fun should_start_bot_supervisor/1,
fun should_compile_route_to_endpoints/1,
fun should_start_endpoint/1,
fun should_stop_endpoint_on_stop/1,
fun should_register_webhook_on_telegram/1]}.
should_create_db_schemas_on_start(_) ->
year_progress_bot_app:start({}, {}),
?_assert(meck:called(db, create_schema, [])).
should_start_bot_supervisor(_) ->
year_progress_bot_app:start({}, {}),
?_assert(meck:called(year_progress_bot_sup, start_link, [])).
should_compile_route_to_endpoints(_) ->
year_progress_bot_app:start({}, {}),
?_assert(meck:called(cowboy_router, compile, [[
{'_', [
{"/some_uuid_path", endpoint, []},
{"/health", health, []}
]}
]])).
should_start_endpoint(_) ->
year_progress_bot_app:start({}, {}),
?_assert(meck:called(cowboy, start_clear, [http, [{port, 12345}], #{env => #{dispatch => dspch}}])).
should_stop_endpoint_on_stop(_) ->
year_progress_bot_app:stop(shutdown),
?_assert(meck:called(cowboy, stop_listener, [http])).
should_register_webhook_on_telegram(_) ->
year_progress_bot_app:start({}, {}),
?_assert(meck:called(telegram, register_webhook, '_')).
| |
436557d5621bdf3d2363aa8a0ca73b2a2200dc0c4b7a5b44248d1ceacef672be | serokell/blockchain-util | Constraints.hs | # LANGUAGE AllowAmbiguousTypes #
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE RankNTypes #-}
# LANGUAGE ScopedTypeVariables #
module Snowdrop.Dba.AVLp.Constraints where
import qualified Data.Tree.AVL as AVL
import Snowdrop.Hetero (HKey, HVal)
class AVL.Hash h (HKey x) (HVal x) => AvlHashC h x
instance AVL.Hash h (HKey x) (HVal x) => AvlHashC h x
| null | https://raw.githubusercontent.com/serokell/blockchain-util/a6428c6841e7002605a115002f58eff78ff9f128/snowdrop-dba-avlp/src/Snowdrop/Dba/AVLp/Constraints.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE DataKinds #
# LANGUAGE RankNTypes # | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE ScopedTypeVariables #
module Snowdrop.Dba.AVLp.Constraints where
import qualified Data.Tree.AVL as AVL
import Snowdrop.Hetero (HKey, HVal)
class AVL.Hash h (HKey x) (HVal x) => AvlHashC h x
instance AVL.Hash h (HKey x) (HVal x) => AvlHashC h x
|
802d285462ac79c574e68bc4e7252b56b18d4cfa310cb2f6d639e91b0e4dd8e4 | andorp/bead | Page.hs | {-# LANGUAGE OverloadedStrings #-}
module Bead.View.Content.UserSubmissions.Page (
userSubmissions
) where
import Data.Function (on)
import Data.List (sortBy)
import Data.String (fromString)
import Data.Time (UTCTime)
import qualified Bead.Controller.Pages as Pages
import qualified Bead.Controller.UserStories as Story
import Bead.Domain.Shared.Evaluation
import Bead.View.Content
import Bead.View.Content.Bootstrap ((.|.))
import qualified Bead.View.Content.Bootstrap as Bootstrap
import Bead.View.Content.VisualConstants
import Text.Blaze.Html5 as H
import Text.Printf (printf)
userSubmissions = ViewHandler userSubmissionPage
userSubmissionPage :: GETContentHandler
userSubmissionPage = withUserState $ \s -> do
username <- getParameter usernamePrm
aKey <- getParameter assignmentKeyPrm
mDesc <- userStory $ do
Story.isAdministratedAssignment aKey
Story.userSubmissions username aKey
page <- case mDesc of
Nothing -> return unauthorized
Just d -> do
tc <- userTimeZoneToLocalTimeConverter
return $ userSubmissionHtml tc d
return page
unauthorized :: IHtml
unauthorized = do
msg <- getI18N
return . fromString . msg $ msg_UserSubmissions_NonAccessibleSubmissions "This submission cannot be accessed by this user."
userSubmissionHtml :: UserTimeConverter -> UserSubmissionDesc -> IHtml
userSubmissionHtml ut u = do
msg <- getI18N
return $ do
Bootstrap.rowColMd12 $ Bootstrap.table $ tbody $ do
(msg $ msg_UserSubmissions_Course "Course:") .|. (fromString $ usCourse u)
(msg $ msg_UserSubmissions_Assignment "Assignment:") .|. (fromString $ usAssignmentName u)
(msg $ msg_UserSubmissions_Student "Student:") .|. (fromString $ usStudent u)
Bootstrap.rowColMd12 $ h3 $
fromString $ msg $ msg_UserSubmissions_SubmittedSolutions "Submissions"
i18n msg . submissionTable ut . sortDescendingByTime $ usSubmissions u
where
submissionTime (_submissionKey, time, _submissionInfo) = time
sortDescendingByTime = reverse . sortBy (compare `on` submissionTime)
submissionTable :: UserTimeConverter -> [(SubmissionKey, UTCTime, SubmissionInfo)] -> IHtml
submissionTable userTime submissions = do
msg <- getI18N
return $ Bootstrap.rowColMd12 $ Bootstrap.listGroup $ do
mapM_ (line msg) submissions
where
line msg (sk,t,si) =
let (link, date) = linkAndDate si sk t
in Bootstrap.listGroupLinkItem
link
(do Bootstrap.badge (submissionInfo msg si); fromString date)
linkAndDate si sk t = case siEvaluationKey si of
Nothing -> ( (routeOf (Pages.evaluation sk ())), (fromString . showDate $ userTime t) )
Just ek -> ( (routeOf (Pages.modifyEvaluation sk ek ())) , (showDate $ userTime t) )
submissionInfo msg = fromString . submissionInfoCata
(msg $ msg_UserSubmissions_NotFound "Not found")
(msg $ msg_UserSubmissions_NonEvaluated "Not evaluated")
(msg . bool (msg_UserSubmissions_Tests_Passed "Tests are passed") (msg_UserSubmissions_Tests_Failed "Tests are failed"))
(const (evaluationDataMap bin pct free . evResult))
where
bin (Binary b) = msg $ resultCata (msg_UserSubmissions_Accepted "Accepted")
(msg_UserSubmissions_Rejected "Rejected")
b
pct (Percentage (Scores [x])) = fromString $ printf "%3.0f%%" (100 * x)
pct (Percentage _) = fromString "Error: ???%"
free (FreeForm resultText)
| length resultText < displayableFreeFormResultLength = resultText
| otherwise = msg $ msg_UserSubmissions_FreeForm "Evaluated"
| null | https://raw.githubusercontent.com/andorp/bead/280dc9c3d5cfe1b9aac0f2f802c705ae65f02ac2/src/Bead/View/Content/UserSubmissions/Page.hs | haskell | # LANGUAGE OverloadedStrings # | module Bead.View.Content.UserSubmissions.Page (
userSubmissions
) where
import Data.Function (on)
import Data.List (sortBy)
import Data.String (fromString)
import Data.Time (UTCTime)
import qualified Bead.Controller.Pages as Pages
import qualified Bead.Controller.UserStories as Story
import Bead.Domain.Shared.Evaluation
import Bead.View.Content
import Bead.View.Content.Bootstrap ((.|.))
import qualified Bead.View.Content.Bootstrap as Bootstrap
import Bead.View.Content.VisualConstants
import Text.Blaze.Html5 as H
import Text.Printf (printf)
userSubmissions = ViewHandler userSubmissionPage
userSubmissionPage :: GETContentHandler
userSubmissionPage = withUserState $ \s -> do
username <- getParameter usernamePrm
aKey <- getParameter assignmentKeyPrm
mDesc <- userStory $ do
Story.isAdministratedAssignment aKey
Story.userSubmissions username aKey
page <- case mDesc of
Nothing -> return unauthorized
Just d -> do
tc <- userTimeZoneToLocalTimeConverter
return $ userSubmissionHtml tc d
return page
unauthorized :: IHtml
unauthorized = do
msg <- getI18N
return . fromString . msg $ msg_UserSubmissions_NonAccessibleSubmissions "This submission cannot be accessed by this user."
userSubmissionHtml :: UserTimeConverter -> UserSubmissionDesc -> IHtml
userSubmissionHtml ut u = do
msg <- getI18N
return $ do
Bootstrap.rowColMd12 $ Bootstrap.table $ tbody $ do
(msg $ msg_UserSubmissions_Course "Course:") .|. (fromString $ usCourse u)
(msg $ msg_UserSubmissions_Assignment "Assignment:") .|. (fromString $ usAssignmentName u)
(msg $ msg_UserSubmissions_Student "Student:") .|. (fromString $ usStudent u)
Bootstrap.rowColMd12 $ h3 $
fromString $ msg $ msg_UserSubmissions_SubmittedSolutions "Submissions"
i18n msg . submissionTable ut . sortDescendingByTime $ usSubmissions u
where
submissionTime (_submissionKey, time, _submissionInfo) = time
sortDescendingByTime = reverse . sortBy (compare `on` submissionTime)
submissionTable :: UserTimeConverter -> [(SubmissionKey, UTCTime, SubmissionInfo)] -> IHtml
submissionTable userTime submissions = do
msg <- getI18N
return $ Bootstrap.rowColMd12 $ Bootstrap.listGroup $ do
mapM_ (line msg) submissions
where
line msg (sk,t,si) =
let (link, date) = linkAndDate si sk t
in Bootstrap.listGroupLinkItem
link
(do Bootstrap.badge (submissionInfo msg si); fromString date)
linkAndDate si sk t = case siEvaluationKey si of
Nothing -> ( (routeOf (Pages.evaluation sk ())), (fromString . showDate $ userTime t) )
Just ek -> ( (routeOf (Pages.modifyEvaluation sk ek ())) , (showDate $ userTime t) )
submissionInfo msg = fromString . submissionInfoCata
(msg $ msg_UserSubmissions_NotFound "Not found")
(msg $ msg_UserSubmissions_NonEvaluated "Not evaluated")
(msg . bool (msg_UserSubmissions_Tests_Passed "Tests are passed") (msg_UserSubmissions_Tests_Failed "Tests are failed"))
(const (evaluationDataMap bin pct free . evResult))
where
bin (Binary b) = msg $ resultCata (msg_UserSubmissions_Accepted "Accepted")
(msg_UserSubmissions_Rejected "Rejected")
b
pct (Percentage (Scores [x])) = fromString $ printf "%3.0f%%" (100 * x)
pct (Percentage _) = fromString "Error: ???%"
free (FreeForm resultText)
| length resultText < displayableFreeFormResultLength = resultText
| otherwise = msg $ msg_UserSubmissions_FreeForm "Evaluated"
|
76bf096e2b57bbfa2be05a5bab8b047fede8ca2d0e688b5dcbe36e38aae51328 | huangz1990/real-world-haskell-cn | foldl.hs | -- file: ch04/foldl.hs
foldl :: (a -> b -> a) -> a -> [b] -> a
foldl step zero (x:xs) = foldl step (step zero x) xs
foldl _ zero [] = zero
| null | https://raw.githubusercontent.com/huangz1990/real-world-haskell-cn/f67b07dd846b1950d17ff941d650089fcbbe9586/code/ch04/foldl.hs | haskell | file: ch04/foldl.hs |
foldl :: (a -> b -> a) -> a -> [b] -> a
foldl step zero (x:xs) = foldl step (step zero x) xs
foldl _ zero [] = zero
|
1954dcf0bed88d2af1b57f53fa098a930712f45dab81c1e1a12de130edf567bd | broom-lang/broom | Platform.ml | type t = Node
| null | https://raw.githubusercontent.com/broom-lang/broom/e817d0588ae7ac881f61654503910852238d6297/compiler/lib/Platform.ml | ocaml | type t = Node
| |
2ca04d6c97c39aa0f969f69d7dbd72a00dc5c17d470b31dbf29072a7b79c9317 | jarvinet/scheme | b1.scm | (define (b1 n)
(if (b)
1
2))
(define (b2 n)
(if (integer-less-than n n)
1
2))
(define (b3 n)
(if (b)
1
(b)))
(define (b4 n)
(if (< n 2)
1
2))
| null | https://raw.githubusercontent.com/jarvinet/scheme/47633d7fc4d82d739a62ceec75c111f6549b1650/bin/test/b1.scm | scheme | (define (b1 n)
(if (b)
1
2))
(define (b2 n)
(if (integer-less-than n n)
1
2))
(define (b3 n)
(if (b)
1
(b)))
(define (b4 n)
(if (< n 2)
1
2))
| |
0f910375d9189df683eaff5e872eb641b531a5be3ddd20aa36c2582a4fe9cad7 | ltoth/unison | copy.ml | Unison file synchronizer : src / copy.ml
Copyright 1999 - 2010 ,
This program is free software : you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
( at your option ) any later version .
This program is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU General Public License for more details .
You should have received a copy of the GNU General Public License
along with this program . If not , see < / > .
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see </>.
*)
let (>>=) = Lwt.bind
let debug = Trace.debug "copy"
(****)
let protect f g =
try
f ()
with Sys_error _ | Unix.Unix_error _ | Util.Transient _ as e ->
begin try g () with Sys_error _ | Unix.Unix_error _ -> () end;
raise e
let lwt_protect f g =
Lwt.catch f
(fun e ->
begin match e with
Sys_error _ | Unix.Unix_error _ | Util.Transient _ ->
begin try g () with Sys_error _ | Unix.Unix_error _ -> () end
| _ ->
()
end;
Lwt.fail e)
(****)
(* Check whether the source file has been modified during synchronization *)
let checkContentsChangeLocal
fspathFrom pathFrom archDesc archDig archStamp archRess paranoid =
let info = Fileinfo.get true fspathFrom pathFrom in
let clearlyModified =
info.Fileinfo.typ <> `FILE
|| Props.length info.Fileinfo.desc <> Props.length archDesc
|| Osx.ressLength info.Fileinfo.osX.Osx.ressInfo <>
Osx.ressLength archRess
in
let dataClearlyUnchanged =
not clearlyModified
&& Props.same_time info.Fileinfo.desc archDesc
&& not (Fpcache.excelFile pathFrom)
&& match archStamp with
Some (Fileinfo.InodeStamp inode) -> info.Fileinfo.inode = inode
| Some (Fileinfo.CtimeStamp ctime) -> true
| None -> false
in
let ressClearlyUnchanged =
not clearlyModified
&& Osx.ressUnchanged archRess info.Fileinfo.osX.Osx.ressInfo
None dataClearlyUnchanged
in
if dataClearlyUnchanged && ressClearlyUnchanged then begin
if paranoid && not (Os.isPseudoFingerprint archDig) then begin
let newDig = Os.fingerprint fspathFrom pathFrom info in
if archDig <> newDig then begin
Update.markPossiblyUpdated fspathFrom pathFrom;
raise (Util.Transient (Printf.sprintf
"The source file %s\n\
has been modified but the fast update detection mechanism\n\
failed to detect it. Try running once with the fastcheck\n\
option set to 'no'."
(Fspath.toPrintString (Fspath.concat fspathFrom pathFrom))))
end
end
end else if
clearlyModified
|| archDig <> Os.fingerprint fspathFrom pathFrom info
then
raise (Util.Transient (Printf.sprintf
"The source file %s\nhas been modified during synchronization. \
Transfer aborted."
(Fspath.toPrintString (Fspath.concat fspathFrom pathFrom))))
let checkContentsChangeOnRoot =
Remote.registerRootCmd
"checkContentsChange"
(fun (fspathFrom,
(pathFrom, archDesc, archDig, archStamp, archRess, paranoid)) ->
checkContentsChangeLocal
fspathFrom pathFrom archDesc archDig archStamp archRess paranoid;
Lwt.return ())
let checkContentsChange
root pathFrom archDesc archDig archStamp archRess paranoid =
checkContentsChangeOnRoot
root (pathFrom, archDesc, archDig, archStamp, archRess, paranoid)
(****)
let fileIsTransferred fspathTo pathTo desc fp ress =
let info = Fileinfo.get false fspathTo pathTo in
(info,
info.Fileinfo.typ = `FILE
&&
Props.length info.Fileinfo.desc = Props.length desc
&&
Osx.ressLength info.Fileinfo.osX.Osx.ressInfo =
Osx.ressLength ress
&&
let fp' = Os.fingerprint fspathTo pathTo info in
fp' = fp)
We slice the files in 1 GB chunks because that 's the limit for
Fingerprint.subfile on 32 bit architectures
Fingerprint.subfile on 32 bit architectures *)
let fingerprintLimit = Uutil.Filesize.ofInt64 1072693248L
let rec fingerprintPrefix fspath path offset len accu =
if len = Uutil.Filesize.zero then accu else begin
let l = min len fingerprintLimit in
let fp = Fingerprint.subfile (Fspath.concat fspath path) offset l in
fingerprintPrefix fspath path
(Int64.add offset (Uutil.Filesize.toInt64 l)) (Uutil.Filesize.sub len l)
(fp :: accu)
end
let fingerprintPrefixRemotely =
Remote.registerServerCmd
"fingerprintSubfile"
(fun _ (fspath, path, len) ->
Lwt.return (fingerprintPrefix fspath path 0L len []))
let appendThreshold = Uutil.Filesize.ofInt (1024 * 1024)
let validFilePrefix connFrom fspathFrom pathFrom fspathTo pathTo info desc =
let len = Props.length info.Fileinfo.desc in
if
info.Fileinfo.typ = `FILE &&
len >= appendThreshold && len < Props.length desc
then begin
Lwt.try_bind
(fun () ->
fingerprintPrefixRemotely connFrom (fspathFrom, pathFrom, len))
(fun fpFrom ->
let fpTo = fingerprintPrefix fspathTo pathTo 0L len [] in
Lwt.return (if fpFrom = fpTo then Some len else None))
(fun _ ->
Lwt.return None)
end else
Lwt.return None
type transferStatus =
Success of Fileinfo.t
| Failure of string
(* Paranoid check: recompute the transferred file's digest to match it
with the archive's *)
let paranoidCheck fspathTo pathTo realPathTo desc fp ress =
let info = Fileinfo.get false fspathTo pathTo in
let fp' = Os.fingerprint fspathTo pathTo info in
if fp' <> fp (* && not (Os.isPseudoFingerprint fp) *) then begin
Lwt.return (Failure (Os.reasonForFingerprintMismatch fp fp'))
end else
Lwt.return (Success info)
let saveTempFileLocal (fspathTo, (pathTo, realPathTo, reason)) =
let savepath =
Os.tempPath ~fresh:true fspathTo
(match Path.deconstructRev realPathTo with
Some (nm, _) -> Path.addSuffixToFinalName
(Path.child Path.empty nm) "-bad"
| None -> Path.fromString "bad")
in
Os.rename "save temp" fspathTo pathTo fspathTo savepath;
Lwt.fail
(Util.Transient
(Printf.sprintf
"The file %s was incorrectly transferred (fingerprint mismatch in %s) \
-- temp file saved as %s"
(Path.toString pathTo)
reason
(Fspath.toDebugString (Fspath.concat fspathTo savepath))))
let saveTempFileOnRoot =
Remote.registerRootCmd "saveTempFile" saveTempFileLocal
(****)
let removeOldTempFile fspathTo pathTo =
if Os.exists fspathTo pathTo then begin
debug (fun() -> Util.msg "Removing old temp file %s / %s\n"
(Fspath.toDebugString fspathTo) (Path.toString pathTo));
Os.delete fspathTo pathTo
end
let openFileIn fspath path kind =
match kind with
`DATA ->
Fs.open_in_bin (Fspath.concat fspath path)
| `DATA_APPEND len ->
let ch = Fs.open_in_bin (Fspath.concat fspath path) in
LargeFile.seek_in ch (Uutil.Filesize.toInt64 len);
ch
| `RESS ->
Osx.openRessIn fspath path
let openFileOut fspath path kind len =
match kind with
`DATA ->
let fullpath = Fspath.concat fspath path in
let flags = [Unix.O_WRONLY;Unix.O_CREAT] in
let perm = 0o600 in
begin match Util.osType with
`Win32 ->
Fs.open_out_gen
[Open_wronly; Open_creat; Open_excl; Open_binary] perm fullpath
| `Unix ->
let fd =
try
Fs.openfile fullpath (Unix.O_EXCL :: flags) perm
with
Unix.Unix_error
((Unix.EOPNOTSUPP | Unix.EUNKNOWNERR 524), _, _) ->
O_EXCL not supported under a Netware NFS - mounted filesystem .
Solaris and Linux report different errors .
Solaris and Linux report different errors. *)
Fs.openfile fullpath (Unix.O_TRUNC :: flags) perm
in
Unix.out_channel_of_descr fd
end
| `DATA_APPEND len ->
let fullpath = Fspath.concat fspath path in
let perm = 0o600 in
let ch = Fs.open_out_gen [Open_wronly; Open_binary] perm fullpath in
Fs.chmod fullpath perm;
LargeFile.seek_out ch (Uutil.Filesize.toInt64 len);
ch
| `RESS ->
Osx.openRessOut fspath path len
let setFileinfo fspathTo pathTo realPathTo update desc =
match update with
`Update _ -> Fileinfo.set fspathTo pathTo (`Copy realPathTo) desc
| `Copy -> Fileinfo.set fspathTo pathTo (`Set Props.fileDefault) desc
(****)
let copyContents fspathFrom pathFrom fspathTo pathTo fileKind fileLength ido =
let use_id f = match ido with Some id -> f id | None -> () in
let inFd = openFileIn fspathFrom pathFrom fileKind in
protect
(fun () ->
let outFd = openFileOut fspathTo pathTo fileKind fileLength in
protect
(fun () ->
Uutil.readWriteBounded inFd outFd fileLength
(fun l ->
use_id (fun id ->
Uutil.showProgress id (Uutil.Filesize.ofInt l) "l"));
close_in inFd;
close_out outFd)
(fun () -> close_out_noerr outFd))
(fun () -> close_in_noerr inFd)
let localFile
fspathFrom pathFrom fspathTo pathTo realPathTo update desc ressLength ido =
Util.convertUnixErrorsToTransient
"copying locally"
(fun () ->
debug (fun () ->
Util.msg "Copy.localFile %s / %s to %s / %s\n"
(Fspath.toDebugString fspathFrom) (Path.toString pathFrom)
(Fspath.toDebugString fspathTo) (Path.toString pathTo));
removeOldTempFile fspathTo pathTo;
copyContents
fspathFrom pathFrom fspathTo pathTo `DATA (Props.length desc) ido;
if ressLength > Uutil.Filesize.zero then
copyContents
fspathFrom pathFrom fspathTo pathTo `RESS ressLength ido;
setFileinfo fspathTo pathTo realPathTo update desc)
(****)
let tryCopyMovedFile fspathTo pathTo realPathTo update desc fp ress id =
if not (Prefs.read Xferhint.xferbycopying) then None else
Util.convertUnixErrorsToTransient "tryCopyMovedFile" (fun() ->
debug (fun () -> Util.msg "tryCopyMovedFile: -> %s /%s/\n"
(Path.toString pathTo) (Os.fullfingerprint_to_string fp));
match Xferhint.lookup fp with
None ->
None
| Some (candidateFspath, candidatePath, hintHandle) ->
debug (fun () ->
Util.msg
"tryCopyMovedFile: found match at %s,%s. Try local copying\n"
(Fspath.toDebugString candidateFspath)
(Path.toString candidatePath));
try
If is the replica root , the argument
[ true ] is correct . Otherwise , we do n't expect to point
to a symlink , and therefore we still get the correct
result .
[true] is correct. Otherwise, we don't expect to point
to a symlink, and therefore we still get the correct
result. *)
let info = Fileinfo.get true candidateFspath candidatePath in
if
info.Fileinfo.typ <> `ABSENT &&
Props.length info.Fileinfo.desc = Props.length desc
then begin
localFile
candidateFspath candidatePath fspathTo pathTo realPathTo
update desc (Osx.ressLength ress) (Some id);
let (info, isTransferred) =
fileIsTransferred fspathTo pathTo desc fp ress in
if isTransferred then begin
debug (fun () -> Util.msg "tryCopyMoveFile: success.\n");
let msg =
Printf.sprintf
"Shortcut: copied %s/%s from local file %s/%s\n"
(Fspath.toPrintString fspathTo)
(Path.toString realPathTo)
(Fspath.toPrintString candidateFspath)
(Path.toString candidatePath)
in
Some (info, msg)
end else begin
debug (fun () ->
Util.msg "tryCopyMoveFile: candidate file %s modified!\n"
(Path.toString candidatePath));
Xferhint.deleteEntry hintHandle;
None
end
end else begin
debug (fun () ->
Util.msg "tryCopyMoveFile: candidate file %s disappeared!\n"
(Path.toString candidatePath));
Xferhint.deleteEntry hintHandle;
None
end
with
Util.Transient s ->
debug (fun () ->
Util.msg
"tryCopyMovedFile: local copy from %s didn't work [%s]"
(Path.toString candidatePath) s);
Xferhint.deleteEntry hintHandle;
None)
(****)
(* The file transfer functions here depend on an external module
'transfer' that implements a generic transmission and the rsync
algorithm for optimizing the file transfer in the case where a
similar file already exists on the target. *)
let rsyncActivated =
Prefs.createBool "rsync" true
"!activate the rsync transfer mode"
("Unison uses the 'rsync algorithm' for 'diffs-only' transfer "
^ "of updates to large files. Setting this flag to false makes Unison "
^ "use whole-file transfers instead. Under normal circumstances, "
^ "there is no reason to do this, but if you are having trouble with "
^ "repeated 'rsync failure' errors, setting it to "
^ "false should permit you to synchronize the offending files.")
let decompressor = ref Remote.MsgIdMap.empty
let processTransferInstruction conn (file_id, ti) =
Util.convertUnixErrorsToTransient
"processing a transfer instruction"
(fun () ->
ignore (Remote.MsgIdMap.find file_id !decompressor ti))
let marshalTransferInstruction =
(fun (file_id, (data, pos, len)) rem ->
(Remote.encodeInt file_id :: (data, pos, len) :: rem,
len + Remote.intSize)),
(fun buf pos ->
let len = Bytearray.length buf - pos - Remote.intSize in
(Remote.decodeInt buf pos, (buf, pos + Remote.intSize, len)))
let streamTransferInstruction =
Remote.registerStreamCmd
"processTransferInstruction" marshalTransferInstruction
processTransferInstruction
let showPrefixProgress id kind =
match kind with
`DATA_APPEND len -> Uutil.showProgress id len "r"
| _ -> ()
let compress conn
(biOpt, fspathFrom, pathFrom, fileKind, sizeFrom, id, file_id) =
Lwt.catch
(fun () ->
streamTransferInstruction conn
(fun processTransferInstructionRemotely ->
(* We abort the file transfer on error if it has not
already started *)
if fileKind <> `RESS then Abort.check id;
let infd = openFileIn fspathFrom pathFrom fileKind in
lwt_protect
(fun () ->
showPrefixProgress id fileKind;
let showProgress count =
Uutil.showProgress id (Uutil.Filesize.ofInt count) "r" in
let compr =
match biOpt with
None ->
Transfer.send infd sizeFrom showProgress
| Some bi ->
Transfer.Rsync.rsyncCompress
bi infd sizeFrom showProgress
in
compr
(fun ti -> processTransferInstructionRemotely (file_id, ti))
>>= fun () ->
close_in infd;
Lwt.return ())
(fun () ->
close_in_noerr infd)))
(fun e ->
(* We cannot wrap the code above with the handler below,
as the code is executed asynchronously. *)
Util.convertUnixErrorsToTransient "transferring file contents"
(fun () -> raise e))
let compressRemotely = Remote.registerServerCmd "compress" compress
let close_all infd outfd =
Util.convertUnixErrorsToTransient
"closing files"
(fun () ->
begin match !infd with
Some fd -> close_in fd; infd := None
| None -> ()
end;
begin match !outfd with
Some fd -> close_out fd; outfd := None
| None -> ()
end)
let close_all_no_error infd outfd =
begin match !infd with
Some fd -> close_in_noerr fd
| None -> ()
end;
begin match !outfd with
Some fd -> close_out_noerr fd
| None -> ()
end
(* Lazy creation of the destination file *)
let destinationFd fspath path kind len outfd id =
match !outfd with
None ->
(* We abort the file transfer on error if it has not
already started *)
if kind <> `RESS then Abort.check id;
let fd = openFileOut fspath path kind len in
showPrefixProgress id kind;
outfd := Some fd;
fd
| Some fd ->
fd
(* Lazy opening of the reference file (for rsync algorithm) *)
let referenceFd fspath path kind infd =
match !infd with
None ->
let fd = openFileIn fspath path kind in
infd := Some fd;
fd
| Some fd ->
fd
let rsyncReg = Lwt_util.make_region (40 * 1024)
let rsyncThrottle useRsync srcFileSize destFileSize f =
if not useRsync then f () else
let l = Transfer.Rsync.memoryFootprint srcFileSize destFileSize in
Lwt_util.run_in_region rsyncReg l f
let transferFileContents
connFrom fspathFrom pathFrom fspathTo pathTo realPathTo update
fileKind srcFileSize id =
(* We delay the opening of the files so that there are not too many
temporary files remaining after a crash, and that they are not
too many files simultaneously opened. *)
let outfd = ref None in
let infd = ref None in
let showProgress count =
Uutil.showProgress id (Uutil.Filesize.ofInt count) "r" in
let destFileSize =
match update with
`Copy ->
Uutil.Filesize.zero
| `Update (destFileDataSize, destFileRessSize) ->
match fileKind with
`DATA | `DATA_APPEND _ -> destFileDataSize
| `RESS -> destFileRessSize
in
let useRsync =
Prefs.read rsyncActivated
&&
Transfer.Rsync.aboveRsyncThreshold destFileSize
&&
Transfer.Rsync.aboveRsyncThreshold srcFileSize
in
rsyncThrottle useRsync srcFileSize destFileSize (fun () ->
let (bi, decompr) =
if useRsync then
Util.convertUnixErrorsToTransient
"preprocessing file"
(fun () ->
let ifd = referenceFd fspathTo realPathTo fileKind infd in
let (bi, blockSize) =
protect
(fun () -> Transfer.Rsync.rsyncPreprocess
ifd srcFileSize destFileSize)
(fun () -> close_in_noerr ifd)
in
close_all infd outfd;
(Some bi,
Rsync decompressor
fun ti ->
let ifd = referenceFd fspathTo realPathTo fileKind infd in
let fd =
destinationFd
fspathTo pathTo fileKind srcFileSize outfd id in
let eof =
Transfer.Rsync.rsyncDecompress blockSize ifd fd showProgress ti
in
if eof then close_all infd outfd))
else
(None,
(* Simple generic decompressor *)
fun ti ->
let fd =
destinationFd fspathTo pathTo fileKind srcFileSize outfd id in
let eof = Transfer.receive fd showProgress ti in
if eof then close_all infd outfd)
in
let file_id = Remote.newMsgId () in
Lwt.catch
(fun () ->
decompressor := Remote.MsgIdMap.add file_id decompr !decompressor;
compressRemotely connFrom
(bi, fspathFrom, pathFrom, fileKind, srcFileSize, id, file_id)
>>= fun () ->
decompressor :=
For GC
close_all infd outfd;
JV : FIX : the file descriptors are already closed ...
Lwt.return ())
(fun e ->
decompressor :=
For GC
close_all_no_error infd outfd;
Lwt.fail e))
(****)
let transferRessourceForkAndSetFileinfo
connFrom fspathFrom pathFrom fspathTo pathTo realPathTo
update desc fp ress id =
Resource fork
let ressLength = Osx.ressLength ress in
begin if ressLength > Uutil.Filesize.zero then
transferFileContents
connFrom fspathFrom pathFrom fspathTo pathTo realPathTo update
`RESS ressLength id
else
Lwt.return ()
end >>= fun () ->
setFileinfo fspathTo pathTo realPathTo update desc;
paranoidCheck fspathTo pathTo realPathTo desc fp ress
let reallyTransferFile
connFrom fspathFrom pathFrom fspathTo pathTo realPathTo
update desc fp ress id tempInfo =
debug (fun() -> Util.msg "reallyTransferFile(%s,%s) -> (%s,%s,%s,%s)\n"
(Fspath.toDebugString fspathFrom) (Path.toString pathFrom)
(Fspath.toDebugString fspathTo) (Path.toString pathTo)
(Path.toString realPathTo) (Props.toString desc));
validFilePrefix connFrom fspathFrom pathFrom fspathTo pathTo tempInfo desc
>>= fun prefixLen ->
begin match prefixLen with
None ->
removeOldTempFile fspathTo pathTo
| Some len ->
debug
(fun() ->
Util.msg "Keeping %s bytes previously transferred for file %s\n"
(Uutil.Filesize.toString len) (Path.toString pathFrom))
end;
(* Data fork *)
transferFileContents
connFrom fspathFrom pathFrom fspathTo pathTo realPathTo update
(match prefixLen with None -> `DATA | Some l -> `DATA_APPEND l)
(Props.length desc) id >>= fun () ->
transferRessourceForkAndSetFileinfo
connFrom fspathFrom pathFrom fspathTo pathTo realPathTo
update desc fp ress id
(****)
let filesBeingTransferred = Hashtbl.create 17
let wakeupNextTransfer fp =
match
try
Some (Queue.take (Hashtbl.find filesBeingTransferred fp))
with Queue.Empty ->
None
with
None ->
Hashtbl.remove filesBeingTransferred fp
| Some next ->
Lwt.wakeup next ()
let executeTransfer fp f =
Lwt.try_bind f
(fun res -> wakeupNextTransfer fp; Lwt.return res)
(fun e -> wakeupNextTransfer fp; Lwt.fail e)
Keep track of which file contents are being transferred , and delay
the transfer of a file with the same contents as another file being
currently transferred . This way , the second transfer can be
skipped and replaced by a local copy .
the transfer of a file with the same contents as another file being
currently transferred. This way, the second transfer can be
skipped and replaced by a local copy. *)
let rec registerFileTransfer pathTo fp f =
if not (Prefs.read Xferhint.xferbycopying) then f () else
match
try Some (Hashtbl.find filesBeingTransferred fp) with Not_found -> None
with
None ->
let q = Queue.create () in
Hashtbl.add filesBeingTransferred fp q;
executeTransfer fp f
| Some q ->
debug (fun () -> Util.msg "delaying tranfer of file %s\n"
(Path.toString pathTo));
let res = Lwt.wait () in
Queue.push res q;
res >>= fun () ->
executeTransfer fp f
(****)
let copyprog =
Prefs.createString "copyprog" "rsync --partial --inplace --compress"
"!external program for copying large files"
("A string giving the name of an "
^ "external program that can be used to copy large files efficiently "
^ "(plus command-line switches telling it to copy files in-place). "
^ "The default setting invokes {\\tt rsync} with appropriate "
^ "options---most users should not need to change it.")
let copyprogrest =
Prefs.createString
"copyprogrest" "rsync --partial --append-verify --compress"
"!variant of copyprog for resuming partial transfers"
("A variant of {\\tt copyprog} that names an external program "
^ "that should be used to continue the transfer of a large file "
^ "that has already been partially transferred. Typically, "
^ "{\\tt copyprogrest} will just be {\\tt copyprog} "
^ "with one extra option (e.g., {\\tt --partial}, for rsync). "
^ "The default setting invokes {\\tt rsync} with appropriate "
^ "options---most users should not need to change it.")
let copythreshold =
Prefs.createInt "copythreshold" (-1)
"!use copyprog on files bigger than this (if >=0, in Kb)"
("A number indicating above what filesize (in kilobytes) Unison should "
^ "use the external "
^ "copying utility specified by {\\tt copyprog}. Specifying 0 will cause "
^ "{\\em all} copies to use the external program; "
^ "a negative number will prevent any files from using it. "
^ "The default is -1. "
^ "See \\sectionref{speeding}{Making Unison Faster on Large Files} "
^ "for more information.")
let copyquoterem =
Prefs.createBoolWithDefault "copyquoterem"
"!add quotes to remote file name for copyprog (true/false/default)"
("When set to {\\tt true}, this flag causes Unison to add an extra layer "
^ "of quotes to the remote path passed to the external copy program. "
^ "This is needed by rsync, for example, which internally uses an ssh "
^ "connection requiring an extra level of quoting for paths containing "
^ "spaces. When this flag is set to {\\tt default}, extra quotes are "
^ "added if the value of {\\tt copyprog} contains the string "
^ "{\\tt rsync}.")
let copymax =
Prefs.createInt "copymax" 1
"!maximum number of simultaneous copyprog transfers"
("A number indicating how many instances of the external copying utility \
Unison is allowed to run simultaneously (default to 1).")
let formatConnectionInfo root =
match root with
Common.Local, _ -> ""
| Common.Remote h, _ ->
(* Find the (unique) nonlocal root *)
match
Safelist.find (function Clroot.ConnectLocal _ -> false | _ -> true)
(Safelist.map Clroot.parseRoot (Globals.rawRoots()))
with
Clroot.ConnectByShell (_,rawhost,uo,_,_) ->
(match uo with None -> "" | Some u -> u ^ "@")
^ rawhost ^ ":"
(* Note that we don't do anything with the port -- hopefully
this will not affect many people. If we did want to include it,
we'd have to fiddle with the rsync parameters in a slightly
deeper way. *)
| Clroot.ConnectBySocket (h',_,_) ->
h ^ ":"
| Clroot.ConnectLocal _ -> assert false
let shouldUseExternalCopyprog update desc =
Prefs.read copyprog <> ""
&& Prefs.read copythreshold >= 0
&& Props.length desc >= Uutil.Filesize.ofInt64 (Int64.of_int 1)
&& Props.length desc >=
Uutil.Filesize.ofInt64
(Int64.mul (Int64.of_int 1000)
(Int64.of_int (Prefs.read copythreshold)))
&& update = `Copy
let prepareExternalTransfer fspathTo pathTo =
let info = Fileinfo.get false fspathTo pathTo in
match info.Fileinfo.typ with
`FILE when Props.length info.Fileinfo.desc > Uutil.Filesize.zero ->
let perms = Props.perms info.Fileinfo.desc in
let perms' = perms lor 0o600 in
begin try
Fs.chmod (Fspath.concat fspathTo pathTo) perms'
with Unix.Unix_error _ -> () end;
true
| `ABSENT ->
false
| _ ->
debug (fun() -> Util.msg "Removing old temp file %s / %s\n"
(Fspath.toDebugString fspathTo) (Path.toString pathTo));
Os.delete fspathTo pathTo;
false
let finishExternalTransferLocal connFrom
(fspathFrom, pathFrom, fspathTo, pathTo, realPathTo,
update, desc, fp, ress, id) =
let info = Fileinfo.get false fspathTo pathTo in
if
info.Fileinfo.typ <> `FILE ||
Props.length info.Fileinfo.desc <> Props.length desc
then
raise (Util.Transient (Printf.sprintf
"External copy program did not create target file (or bad length): %s"
(Path.toString pathTo)));
transferRessourceForkAndSetFileinfo
connFrom fspathFrom pathFrom fspathTo pathTo realPathTo
update desc fp ress id >>= fun res ->
Xferhint.insertEntry fspathTo pathTo fp;
Lwt.return res
let finishExternalTransferOnRoot =
Remote.registerRootCmdWithConnection
"finishExternalTransfer" finishExternalTransferLocal
let copyprogReg = Lwt_util.make_region 1
let transferFileUsingExternalCopyprog
rootFrom pathFrom rootTo fspathTo pathTo realPathTo
update desc fp ress id useExistingTarget =
Uutil.showProgress id Uutil.Filesize.zero "ext";
let prog =
if useExistingTarget then
Prefs.read copyprogrest
else
Prefs.read copyprog
in
let extraquotes = Prefs.read copyquoterem = `True
|| ( Prefs.read copyquoterem = `Default
&& Util.findsubstring "rsync" prog <> None) in
let addquotes root s =
match root with
| Common.Local, _ -> s
| Common.Remote _, _ -> if extraquotes then Uutil.quotes s else s in
let fromSpec =
(formatConnectionInfo rootFrom)
^ (addquotes rootFrom
(Fspath.toString (Fspath.concat (snd rootFrom) pathFrom))) in
let toSpec =
(formatConnectionInfo rootTo)
^ (addquotes rootTo
(Fspath.toString (Fspath.concat fspathTo pathTo))) in
let cmd = prog ^ " "
^ (Uutil.quotes fromSpec) ^ " "
^ (Uutil.quotes toSpec) in
Trace.log (Printf.sprintf "%s\n" cmd);
Lwt_util.resize_region copyprogReg (Prefs.read copymax);
Lwt_util.run_in_region copyprogReg 1
(fun () -> External.runExternalProgram cmd) >>= fun (_, log) ->
debug (fun() ->
let l = Util.trimWhitespace log in
Util.msg "transferFileUsingExternalCopyprog %s: returned...\n%s%s"
(Path.toString pathFrom)
l (if l="" then "" else "\n"));
Uutil.showProgress id (Props.length desc) "ext";
finishExternalTransferOnRoot rootTo rootFrom
(snd rootFrom, pathFrom, fspathTo, pathTo, realPathTo,
update, desc, fp, ress, id)
(****)
let transferFileLocal connFrom
(fspathFrom, pathFrom, fspathTo, pathTo, realPathTo,
update, desc, fp, ress, id) =
let (tempInfo, isTransferred) =
fileIsTransferred fspathTo pathTo desc fp ress in
if isTransferred then begin
(* File is already fully transferred (from some interrupted
previous transfer). *)
(* Make sure permissions are right. *)
let msg =
Printf.sprintf
"%s/%s has already been transferred\n"
(Fspath.toDebugString fspathTo) (Path.toString realPathTo)
in
let len = Uutil.Filesize.add (Props.length desc) (Osx.ressLength ress) in
Uutil.showProgress id len "alr";
setFileinfo fspathTo pathTo realPathTo update desc;
Xferhint.insertEntry fspathTo pathTo fp;
Lwt.return (`DONE (Success tempInfo, Some msg))
end else
registerFileTransfer pathTo fp
(fun () ->
match
tryCopyMovedFile fspathTo pathTo realPathTo update desc fp ress id
with
Some (info, msg) ->
(* Transfer was performed by copying *)
Xferhint.insertEntry fspathTo pathTo fp;
Lwt.return (`DONE (Success info, Some msg))
| None ->
if shouldUseExternalCopyprog update desc then
Lwt.return (`EXTERNAL (prepareExternalTransfer fspathTo pathTo))
else begin
reallyTransferFile
connFrom fspathFrom pathFrom fspathTo pathTo realPathTo
update desc fp ress id tempInfo >>= fun status ->
Xferhint.insertEntry fspathTo pathTo fp;
Lwt.return (`DONE (status, None))
end)
let transferFileOnRoot =
Remote.registerRootCmdWithConnection "transferFile" transferFileLocal
We limit the size of the output buffers to about 512 KB
( we can not go above the limit below plus 64 )
(we cannot go above the limit below plus 64) *)
let transferFileReg = Lwt_util.make_region 440
let bufferSize sz =
min 64 ((truncate (Uutil.Filesize.toFloat sz) + 1023) / 1024)
(* Token queue *)
+
8 (* Read buffer *)
let transferFile
rootFrom pathFrom rootTo fspathTo pathTo realPathTo
update desc fp ress id =
let f () =
Abort.check id;
transferFileOnRoot rootTo rootFrom
(snd rootFrom, pathFrom, fspathTo, pathTo, realPathTo,
update, desc, fp, ress, id) >>= fun status ->
match status with
`DONE (status, msg) ->
begin match msg with
Some msg ->
(* If the file was already present or transferred by copying
on the server, we need to update the amount of data
transferred so far here. *)
if fst rootTo <> Common.Local then begin
let len =
Uutil.Filesize.add (Props.length desc) (Osx.ressLength ress)
in
Uutil.showProgress id len "rem"
end;
Trace.log msg
| None ->
()
end;
Lwt.return status
| `EXTERNAL useExistingTarget ->
transferFileUsingExternalCopyprog
rootFrom pathFrom rootTo fspathTo pathTo realPathTo
update desc fp ress id useExistingTarget
in
When streaming , we only transfer one file at a time , so we do n't
need to limit the number of concurrent transfers
need to limit the number of concurrent transfers *)
if Prefs.read Remote.streamingActivated then
f ()
else
let bufSz = bufferSize (max (Props.length desc) (Osx.ressLength ress)) in
Lwt_util.run_in_region transferFileReg bufSz f
(****)
let file rootFrom pathFrom rootTo fspathTo pathTo realPathTo
update desc fp stamp ress id =
debug (fun() -> Util.msg "copyRegFile(%s,%s) -> (%s,%s,%s,%s,%s)\n"
(Common.root2string rootFrom) (Path.toString pathFrom)
(Common.root2string rootTo) (Path.toString realPathTo)
(Fspath.toDebugString fspathTo) (Path.toString pathTo)
(Props.toString desc));
let timer = Trace.startTimer "Transmitting file" in
begin match rootFrom, rootTo with
(Common.Local, fspathFrom), (Common.Local, realFspathTo) ->
localFile
fspathFrom pathFrom fspathTo pathTo realPathTo
update desc (Osx.ressLength ress) (Some id);
paranoidCheck fspathTo pathTo realPathTo desc fp ress
| _ ->
transferFile
rootFrom pathFrom rootTo fspathTo pathTo realPathTo
update desc fp ress id
end >>= fun status ->
Trace.showTimer timer;
match status with
Success info ->
checkContentsChange rootFrom pathFrom desc fp stamp ress false
>>= fun () ->
Lwt.return info
| Failure reason ->
(* Maybe we failed because the source file was modified.
We check this before reporting a failure *)
checkContentsChange rootFrom pathFrom desc fp stamp ress true
>>= fun () ->
(* This function always fails! *)
saveTempFileOnRoot rootTo (pathTo, realPathTo, reason)
| null | https://raw.githubusercontent.com/ltoth/unison/e763510165e3d93c5140a4c5f2ea0dcbf5825a0c/copy.ml | ocaml | **
**
Check whether the source file has been modified during synchronization
**
Paranoid check: recompute the transferred file's digest to match it
with the archive's
&& not (Os.isPseudoFingerprint fp)
**
**
**
**
The file transfer functions here depend on an external module
'transfer' that implements a generic transmission and the rsync
algorithm for optimizing the file transfer in the case where a
similar file already exists on the target.
We abort the file transfer on error if it has not
already started
We cannot wrap the code above with the handler below,
as the code is executed asynchronously.
Lazy creation of the destination file
We abort the file transfer on error if it has not
already started
Lazy opening of the reference file (for rsync algorithm)
We delay the opening of the files so that there are not too many
temporary files remaining after a crash, and that they are not
too many files simultaneously opened.
Simple generic decompressor
**
Data fork
**
**
Find the (unique) nonlocal root
Note that we don't do anything with the port -- hopefully
this will not affect many people. If we did want to include it,
we'd have to fiddle with the rsync parameters in a slightly
deeper way.
**
File is already fully transferred (from some interrupted
previous transfer).
Make sure permissions are right.
Transfer was performed by copying
Token queue
Read buffer
If the file was already present or transferred by copying
on the server, we need to update the amount of data
transferred so far here.
**
Maybe we failed because the source file was modified.
We check this before reporting a failure
This function always fails! | Unison file synchronizer : src / copy.ml
Copyright 1999 - 2010 ,
This program is free software : you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
( at your option ) any later version .
This program is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU General Public License for more details .
You should have received a copy of the GNU General Public License
along with this program . If not , see < / > .
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see </>.
*)
let (>>=) = Lwt.bind
let debug = Trace.debug "copy"
let protect f g =
try
f ()
with Sys_error _ | Unix.Unix_error _ | Util.Transient _ as e ->
begin try g () with Sys_error _ | Unix.Unix_error _ -> () end;
raise e
let lwt_protect f g =
Lwt.catch f
(fun e ->
begin match e with
Sys_error _ | Unix.Unix_error _ | Util.Transient _ ->
begin try g () with Sys_error _ | Unix.Unix_error _ -> () end
| _ ->
()
end;
Lwt.fail e)
let checkContentsChangeLocal
fspathFrom pathFrom archDesc archDig archStamp archRess paranoid =
let info = Fileinfo.get true fspathFrom pathFrom in
let clearlyModified =
info.Fileinfo.typ <> `FILE
|| Props.length info.Fileinfo.desc <> Props.length archDesc
|| Osx.ressLength info.Fileinfo.osX.Osx.ressInfo <>
Osx.ressLength archRess
in
let dataClearlyUnchanged =
not clearlyModified
&& Props.same_time info.Fileinfo.desc archDesc
&& not (Fpcache.excelFile pathFrom)
&& match archStamp with
Some (Fileinfo.InodeStamp inode) -> info.Fileinfo.inode = inode
| Some (Fileinfo.CtimeStamp ctime) -> true
| None -> false
in
let ressClearlyUnchanged =
not clearlyModified
&& Osx.ressUnchanged archRess info.Fileinfo.osX.Osx.ressInfo
None dataClearlyUnchanged
in
if dataClearlyUnchanged && ressClearlyUnchanged then begin
if paranoid && not (Os.isPseudoFingerprint archDig) then begin
let newDig = Os.fingerprint fspathFrom pathFrom info in
if archDig <> newDig then begin
Update.markPossiblyUpdated fspathFrom pathFrom;
raise (Util.Transient (Printf.sprintf
"The source file %s\n\
has been modified but the fast update detection mechanism\n\
failed to detect it. Try running once with the fastcheck\n\
option set to 'no'."
(Fspath.toPrintString (Fspath.concat fspathFrom pathFrom))))
end
end
end else if
clearlyModified
|| archDig <> Os.fingerprint fspathFrom pathFrom info
then
raise (Util.Transient (Printf.sprintf
"The source file %s\nhas been modified during synchronization. \
Transfer aborted."
(Fspath.toPrintString (Fspath.concat fspathFrom pathFrom))))
let checkContentsChangeOnRoot =
Remote.registerRootCmd
"checkContentsChange"
(fun (fspathFrom,
(pathFrom, archDesc, archDig, archStamp, archRess, paranoid)) ->
checkContentsChangeLocal
fspathFrom pathFrom archDesc archDig archStamp archRess paranoid;
Lwt.return ())
let checkContentsChange
root pathFrom archDesc archDig archStamp archRess paranoid =
checkContentsChangeOnRoot
root (pathFrom, archDesc, archDig, archStamp, archRess, paranoid)
let fileIsTransferred fspathTo pathTo desc fp ress =
let info = Fileinfo.get false fspathTo pathTo in
(info,
info.Fileinfo.typ = `FILE
&&
Props.length info.Fileinfo.desc = Props.length desc
&&
Osx.ressLength info.Fileinfo.osX.Osx.ressInfo =
Osx.ressLength ress
&&
let fp' = Os.fingerprint fspathTo pathTo info in
fp' = fp)
We slice the files in 1 GB chunks because that 's the limit for
Fingerprint.subfile on 32 bit architectures
Fingerprint.subfile on 32 bit architectures *)
let fingerprintLimit = Uutil.Filesize.ofInt64 1072693248L
let rec fingerprintPrefix fspath path offset len accu =
if len = Uutil.Filesize.zero then accu else begin
let l = min len fingerprintLimit in
let fp = Fingerprint.subfile (Fspath.concat fspath path) offset l in
fingerprintPrefix fspath path
(Int64.add offset (Uutil.Filesize.toInt64 l)) (Uutil.Filesize.sub len l)
(fp :: accu)
end
let fingerprintPrefixRemotely =
Remote.registerServerCmd
"fingerprintSubfile"
(fun _ (fspath, path, len) ->
Lwt.return (fingerprintPrefix fspath path 0L len []))
let appendThreshold = Uutil.Filesize.ofInt (1024 * 1024)
let validFilePrefix connFrom fspathFrom pathFrom fspathTo pathTo info desc =
let len = Props.length info.Fileinfo.desc in
if
info.Fileinfo.typ = `FILE &&
len >= appendThreshold && len < Props.length desc
then begin
Lwt.try_bind
(fun () ->
fingerprintPrefixRemotely connFrom (fspathFrom, pathFrom, len))
(fun fpFrom ->
let fpTo = fingerprintPrefix fspathTo pathTo 0L len [] in
Lwt.return (if fpFrom = fpTo then Some len else None))
(fun _ ->
Lwt.return None)
end else
Lwt.return None
type transferStatus =
Success of Fileinfo.t
| Failure of string
let paranoidCheck fspathTo pathTo realPathTo desc fp ress =
let info = Fileinfo.get false fspathTo pathTo in
let fp' = Os.fingerprint fspathTo pathTo info in
Lwt.return (Failure (Os.reasonForFingerprintMismatch fp fp'))
end else
Lwt.return (Success info)
let saveTempFileLocal (fspathTo, (pathTo, realPathTo, reason)) =
let savepath =
Os.tempPath ~fresh:true fspathTo
(match Path.deconstructRev realPathTo with
Some (nm, _) -> Path.addSuffixToFinalName
(Path.child Path.empty nm) "-bad"
| None -> Path.fromString "bad")
in
Os.rename "save temp" fspathTo pathTo fspathTo savepath;
Lwt.fail
(Util.Transient
(Printf.sprintf
"The file %s was incorrectly transferred (fingerprint mismatch in %s) \
-- temp file saved as %s"
(Path.toString pathTo)
reason
(Fspath.toDebugString (Fspath.concat fspathTo savepath))))
let saveTempFileOnRoot =
Remote.registerRootCmd "saveTempFile" saveTempFileLocal
let removeOldTempFile fspathTo pathTo =
if Os.exists fspathTo pathTo then begin
debug (fun() -> Util.msg "Removing old temp file %s / %s\n"
(Fspath.toDebugString fspathTo) (Path.toString pathTo));
Os.delete fspathTo pathTo
end
let openFileIn fspath path kind =
match kind with
`DATA ->
Fs.open_in_bin (Fspath.concat fspath path)
| `DATA_APPEND len ->
let ch = Fs.open_in_bin (Fspath.concat fspath path) in
LargeFile.seek_in ch (Uutil.Filesize.toInt64 len);
ch
| `RESS ->
Osx.openRessIn fspath path
let openFileOut fspath path kind len =
match kind with
`DATA ->
let fullpath = Fspath.concat fspath path in
let flags = [Unix.O_WRONLY;Unix.O_CREAT] in
let perm = 0o600 in
begin match Util.osType with
`Win32 ->
Fs.open_out_gen
[Open_wronly; Open_creat; Open_excl; Open_binary] perm fullpath
| `Unix ->
let fd =
try
Fs.openfile fullpath (Unix.O_EXCL :: flags) perm
with
Unix.Unix_error
((Unix.EOPNOTSUPP | Unix.EUNKNOWNERR 524), _, _) ->
O_EXCL not supported under a Netware NFS - mounted filesystem .
Solaris and Linux report different errors .
Solaris and Linux report different errors. *)
Fs.openfile fullpath (Unix.O_TRUNC :: flags) perm
in
Unix.out_channel_of_descr fd
end
| `DATA_APPEND len ->
let fullpath = Fspath.concat fspath path in
let perm = 0o600 in
let ch = Fs.open_out_gen [Open_wronly; Open_binary] perm fullpath in
Fs.chmod fullpath perm;
LargeFile.seek_out ch (Uutil.Filesize.toInt64 len);
ch
| `RESS ->
Osx.openRessOut fspath path len
let setFileinfo fspathTo pathTo realPathTo update desc =
match update with
`Update _ -> Fileinfo.set fspathTo pathTo (`Copy realPathTo) desc
| `Copy -> Fileinfo.set fspathTo pathTo (`Set Props.fileDefault) desc
let copyContents fspathFrom pathFrom fspathTo pathTo fileKind fileLength ido =
let use_id f = match ido with Some id -> f id | None -> () in
let inFd = openFileIn fspathFrom pathFrom fileKind in
protect
(fun () ->
let outFd = openFileOut fspathTo pathTo fileKind fileLength in
protect
(fun () ->
Uutil.readWriteBounded inFd outFd fileLength
(fun l ->
use_id (fun id ->
Uutil.showProgress id (Uutil.Filesize.ofInt l) "l"));
close_in inFd;
close_out outFd)
(fun () -> close_out_noerr outFd))
(fun () -> close_in_noerr inFd)
let localFile
fspathFrom pathFrom fspathTo pathTo realPathTo update desc ressLength ido =
Util.convertUnixErrorsToTransient
"copying locally"
(fun () ->
debug (fun () ->
Util.msg "Copy.localFile %s / %s to %s / %s\n"
(Fspath.toDebugString fspathFrom) (Path.toString pathFrom)
(Fspath.toDebugString fspathTo) (Path.toString pathTo));
removeOldTempFile fspathTo pathTo;
copyContents
fspathFrom pathFrom fspathTo pathTo `DATA (Props.length desc) ido;
if ressLength > Uutil.Filesize.zero then
copyContents
fspathFrom pathFrom fspathTo pathTo `RESS ressLength ido;
setFileinfo fspathTo pathTo realPathTo update desc)
let tryCopyMovedFile fspathTo pathTo realPathTo update desc fp ress id =
if not (Prefs.read Xferhint.xferbycopying) then None else
Util.convertUnixErrorsToTransient "tryCopyMovedFile" (fun() ->
debug (fun () -> Util.msg "tryCopyMovedFile: -> %s /%s/\n"
(Path.toString pathTo) (Os.fullfingerprint_to_string fp));
match Xferhint.lookup fp with
None ->
None
| Some (candidateFspath, candidatePath, hintHandle) ->
debug (fun () ->
Util.msg
"tryCopyMovedFile: found match at %s,%s. Try local copying\n"
(Fspath.toDebugString candidateFspath)
(Path.toString candidatePath));
try
If is the replica root , the argument
[ true ] is correct . Otherwise , we do n't expect to point
to a symlink , and therefore we still get the correct
result .
[true] is correct. Otherwise, we don't expect to point
to a symlink, and therefore we still get the correct
result. *)
let info = Fileinfo.get true candidateFspath candidatePath in
if
info.Fileinfo.typ <> `ABSENT &&
Props.length info.Fileinfo.desc = Props.length desc
then begin
localFile
candidateFspath candidatePath fspathTo pathTo realPathTo
update desc (Osx.ressLength ress) (Some id);
let (info, isTransferred) =
fileIsTransferred fspathTo pathTo desc fp ress in
if isTransferred then begin
debug (fun () -> Util.msg "tryCopyMoveFile: success.\n");
let msg =
Printf.sprintf
"Shortcut: copied %s/%s from local file %s/%s\n"
(Fspath.toPrintString fspathTo)
(Path.toString realPathTo)
(Fspath.toPrintString candidateFspath)
(Path.toString candidatePath)
in
Some (info, msg)
end else begin
debug (fun () ->
Util.msg "tryCopyMoveFile: candidate file %s modified!\n"
(Path.toString candidatePath));
Xferhint.deleteEntry hintHandle;
None
end
end else begin
debug (fun () ->
Util.msg "tryCopyMoveFile: candidate file %s disappeared!\n"
(Path.toString candidatePath));
Xferhint.deleteEntry hintHandle;
None
end
with
Util.Transient s ->
debug (fun () ->
Util.msg
"tryCopyMovedFile: local copy from %s didn't work [%s]"
(Path.toString candidatePath) s);
Xferhint.deleteEntry hintHandle;
None)
let rsyncActivated =
Prefs.createBool "rsync" true
"!activate the rsync transfer mode"
("Unison uses the 'rsync algorithm' for 'diffs-only' transfer "
^ "of updates to large files. Setting this flag to false makes Unison "
^ "use whole-file transfers instead. Under normal circumstances, "
^ "there is no reason to do this, but if you are having trouble with "
^ "repeated 'rsync failure' errors, setting it to "
^ "false should permit you to synchronize the offending files.")
let decompressor = ref Remote.MsgIdMap.empty
let processTransferInstruction conn (file_id, ti) =
Util.convertUnixErrorsToTransient
"processing a transfer instruction"
(fun () ->
ignore (Remote.MsgIdMap.find file_id !decompressor ti))
let marshalTransferInstruction =
(fun (file_id, (data, pos, len)) rem ->
(Remote.encodeInt file_id :: (data, pos, len) :: rem,
len + Remote.intSize)),
(fun buf pos ->
let len = Bytearray.length buf - pos - Remote.intSize in
(Remote.decodeInt buf pos, (buf, pos + Remote.intSize, len)))
let streamTransferInstruction =
Remote.registerStreamCmd
"processTransferInstruction" marshalTransferInstruction
processTransferInstruction
let showPrefixProgress id kind =
match kind with
`DATA_APPEND len -> Uutil.showProgress id len "r"
| _ -> ()
let compress conn
(biOpt, fspathFrom, pathFrom, fileKind, sizeFrom, id, file_id) =
Lwt.catch
(fun () ->
streamTransferInstruction conn
(fun processTransferInstructionRemotely ->
if fileKind <> `RESS then Abort.check id;
let infd = openFileIn fspathFrom pathFrom fileKind in
lwt_protect
(fun () ->
showPrefixProgress id fileKind;
let showProgress count =
Uutil.showProgress id (Uutil.Filesize.ofInt count) "r" in
let compr =
match biOpt with
None ->
Transfer.send infd sizeFrom showProgress
| Some bi ->
Transfer.Rsync.rsyncCompress
bi infd sizeFrom showProgress
in
compr
(fun ti -> processTransferInstructionRemotely (file_id, ti))
>>= fun () ->
close_in infd;
Lwt.return ())
(fun () ->
close_in_noerr infd)))
(fun e ->
Util.convertUnixErrorsToTransient "transferring file contents"
(fun () -> raise e))
let compressRemotely = Remote.registerServerCmd "compress" compress
let close_all infd outfd =
Util.convertUnixErrorsToTransient
"closing files"
(fun () ->
begin match !infd with
Some fd -> close_in fd; infd := None
| None -> ()
end;
begin match !outfd with
Some fd -> close_out fd; outfd := None
| None -> ()
end)
let close_all_no_error infd outfd =
begin match !infd with
Some fd -> close_in_noerr fd
| None -> ()
end;
begin match !outfd with
Some fd -> close_out_noerr fd
| None -> ()
end
let destinationFd fspath path kind len outfd id =
match !outfd with
None ->
if kind <> `RESS then Abort.check id;
let fd = openFileOut fspath path kind len in
showPrefixProgress id kind;
outfd := Some fd;
fd
| Some fd ->
fd
let referenceFd fspath path kind infd =
match !infd with
None ->
let fd = openFileIn fspath path kind in
infd := Some fd;
fd
| Some fd ->
fd
let rsyncReg = Lwt_util.make_region (40 * 1024)
let rsyncThrottle useRsync srcFileSize destFileSize f =
if not useRsync then f () else
let l = Transfer.Rsync.memoryFootprint srcFileSize destFileSize in
Lwt_util.run_in_region rsyncReg l f
let transferFileContents
connFrom fspathFrom pathFrom fspathTo pathTo realPathTo update
fileKind srcFileSize id =
let outfd = ref None in
let infd = ref None in
let showProgress count =
Uutil.showProgress id (Uutil.Filesize.ofInt count) "r" in
let destFileSize =
match update with
`Copy ->
Uutil.Filesize.zero
| `Update (destFileDataSize, destFileRessSize) ->
match fileKind with
`DATA | `DATA_APPEND _ -> destFileDataSize
| `RESS -> destFileRessSize
in
let useRsync =
Prefs.read rsyncActivated
&&
Transfer.Rsync.aboveRsyncThreshold destFileSize
&&
Transfer.Rsync.aboveRsyncThreshold srcFileSize
in
rsyncThrottle useRsync srcFileSize destFileSize (fun () ->
let (bi, decompr) =
if useRsync then
Util.convertUnixErrorsToTransient
"preprocessing file"
(fun () ->
let ifd = referenceFd fspathTo realPathTo fileKind infd in
let (bi, blockSize) =
protect
(fun () -> Transfer.Rsync.rsyncPreprocess
ifd srcFileSize destFileSize)
(fun () -> close_in_noerr ifd)
in
close_all infd outfd;
(Some bi,
Rsync decompressor
fun ti ->
let ifd = referenceFd fspathTo realPathTo fileKind infd in
let fd =
destinationFd
fspathTo pathTo fileKind srcFileSize outfd id in
let eof =
Transfer.Rsync.rsyncDecompress blockSize ifd fd showProgress ti
in
if eof then close_all infd outfd))
else
(None,
fun ti ->
let fd =
destinationFd fspathTo pathTo fileKind srcFileSize outfd id in
let eof = Transfer.receive fd showProgress ti in
if eof then close_all infd outfd)
in
let file_id = Remote.newMsgId () in
Lwt.catch
(fun () ->
decompressor := Remote.MsgIdMap.add file_id decompr !decompressor;
compressRemotely connFrom
(bi, fspathFrom, pathFrom, fileKind, srcFileSize, id, file_id)
>>= fun () ->
decompressor :=
For GC
close_all infd outfd;
JV : FIX : the file descriptors are already closed ...
Lwt.return ())
(fun e ->
decompressor :=
For GC
close_all_no_error infd outfd;
Lwt.fail e))
let transferRessourceForkAndSetFileinfo
connFrom fspathFrom pathFrom fspathTo pathTo realPathTo
update desc fp ress id =
Resource fork
let ressLength = Osx.ressLength ress in
begin if ressLength > Uutil.Filesize.zero then
transferFileContents
connFrom fspathFrom pathFrom fspathTo pathTo realPathTo update
`RESS ressLength id
else
Lwt.return ()
end >>= fun () ->
setFileinfo fspathTo pathTo realPathTo update desc;
paranoidCheck fspathTo pathTo realPathTo desc fp ress
let reallyTransferFile
connFrom fspathFrom pathFrom fspathTo pathTo realPathTo
update desc fp ress id tempInfo =
debug (fun() -> Util.msg "reallyTransferFile(%s,%s) -> (%s,%s,%s,%s)\n"
(Fspath.toDebugString fspathFrom) (Path.toString pathFrom)
(Fspath.toDebugString fspathTo) (Path.toString pathTo)
(Path.toString realPathTo) (Props.toString desc));
validFilePrefix connFrom fspathFrom pathFrom fspathTo pathTo tempInfo desc
>>= fun prefixLen ->
begin match prefixLen with
None ->
removeOldTempFile fspathTo pathTo
| Some len ->
debug
(fun() ->
Util.msg "Keeping %s bytes previously transferred for file %s\n"
(Uutil.Filesize.toString len) (Path.toString pathFrom))
end;
transferFileContents
connFrom fspathFrom pathFrom fspathTo pathTo realPathTo update
(match prefixLen with None -> `DATA | Some l -> `DATA_APPEND l)
(Props.length desc) id >>= fun () ->
transferRessourceForkAndSetFileinfo
connFrom fspathFrom pathFrom fspathTo pathTo realPathTo
update desc fp ress id
let filesBeingTransferred = Hashtbl.create 17
let wakeupNextTransfer fp =
match
try
Some (Queue.take (Hashtbl.find filesBeingTransferred fp))
with Queue.Empty ->
None
with
None ->
Hashtbl.remove filesBeingTransferred fp
| Some next ->
Lwt.wakeup next ()
let executeTransfer fp f =
Lwt.try_bind f
(fun res -> wakeupNextTransfer fp; Lwt.return res)
(fun e -> wakeupNextTransfer fp; Lwt.fail e)
Keep track of which file contents are being transferred , and delay
the transfer of a file with the same contents as another file being
currently transferred . This way , the second transfer can be
skipped and replaced by a local copy .
the transfer of a file with the same contents as another file being
currently transferred. This way, the second transfer can be
skipped and replaced by a local copy. *)
let rec registerFileTransfer pathTo fp f =
if not (Prefs.read Xferhint.xferbycopying) then f () else
match
try Some (Hashtbl.find filesBeingTransferred fp) with Not_found -> None
with
None ->
let q = Queue.create () in
Hashtbl.add filesBeingTransferred fp q;
executeTransfer fp f
| Some q ->
debug (fun () -> Util.msg "delaying tranfer of file %s\n"
(Path.toString pathTo));
let res = Lwt.wait () in
Queue.push res q;
res >>= fun () ->
executeTransfer fp f
let copyprog =
Prefs.createString "copyprog" "rsync --partial --inplace --compress"
"!external program for copying large files"
("A string giving the name of an "
^ "external program that can be used to copy large files efficiently "
^ "(plus command-line switches telling it to copy files in-place). "
^ "The default setting invokes {\\tt rsync} with appropriate "
^ "options---most users should not need to change it.")
let copyprogrest =
Prefs.createString
"copyprogrest" "rsync --partial --append-verify --compress"
"!variant of copyprog for resuming partial transfers"
("A variant of {\\tt copyprog} that names an external program "
^ "that should be used to continue the transfer of a large file "
^ "that has already been partially transferred. Typically, "
^ "{\\tt copyprogrest} will just be {\\tt copyprog} "
^ "with one extra option (e.g., {\\tt --partial}, for rsync). "
^ "The default setting invokes {\\tt rsync} with appropriate "
^ "options---most users should not need to change it.")
let copythreshold =
Prefs.createInt "copythreshold" (-1)
"!use copyprog on files bigger than this (if >=0, in Kb)"
("A number indicating above what filesize (in kilobytes) Unison should "
^ "use the external "
^ "copying utility specified by {\\tt copyprog}. Specifying 0 will cause "
^ "{\\em all} copies to use the external program; "
^ "a negative number will prevent any files from using it. "
^ "The default is -1. "
^ "See \\sectionref{speeding}{Making Unison Faster on Large Files} "
^ "for more information.")
let copyquoterem =
Prefs.createBoolWithDefault "copyquoterem"
"!add quotes to remote file name for copyprog (true/false/default)"
("When set to {\\tt true}, this flag causes Unison to add an extra layer "
^ "of quotes to the remote path passed to the external copy program. "
^ "This is needed by rsync, for example, which internally uses an ssh "
^ "connection requiring an extra level of quoting for paths containing "
^ "spaces. When this flag is set to {\\tt default}, extra quotes are "
^ "added if the value of {\\tt copyprog} contains the string "
^ "{\\tt rsync}.")
let copymax =
Prefs.createInt "copymax" 1
"!maximum number of simultaneous copyprog transfers"
("A number indicating how many instances of the external copying utility \
Unison is allowed to run simultaneously (default to 1).")
let formatConnectionInfo root =
match root with
Common.Local, _ -> ""
| Common.Remote h, _ ->
match
Safelist.find (function Clroot.ConnectLocal _ -> false | _ -> true)
(Safelist.map Clroot.parseRoot (Globals.rawRoots()))
with
Clroot.ConnectByShell (_,rawhost,uo,_,_) ->
(match uo with None -> "" | Some u -> u ^ "@")
^ rawhost ^ ":"
| Clroot.ConnectBySocket (h',_,_) ->
h ^ ":"
| Clroot.ConnectLocal _ -> assert false
let shouldUseExternalCopyprog update desc =
Prefs.read copyprog <> ""
&& Prefs.read copythreshold >= 0
&& Props.length desc >= Uutil.Filesize.ofInt64 (Int64.of_int 1)
&& Props.length desc >=
Uutil.Filesize.ofInt64
(Int64.mul (Int64.of_int 1000)
(Int64.of_int (Prefs.read copythreshold)))
&& update = `Copy
let prepareExternalTransfer fspathTo pathTo =
let info = Fileinfo.get false fspathTo pathTo in
match info.Fileinfo.typ with
`FILE when Props.length info.Fileinfo.desc > Uutil.Filesize.zero ->
let perms = Props.perms info.Fileinfo.desc in
let perms' = perms lor 0o600 in
begin try
Fs.chmod (Fspath.concat fspathTo pathTo) perms'
with Unix.Unix_error _ -> () end;
true
| `ABSENT ->
false
| _ ->
debug (fun() -> Util.msg "Removing old temp file %s / %s\n"
(Fspath.toDebugString fspathTo) (Path.toString pathTo));
Os.delete fspathTo pathTo;
false
let finishExternalTransferLocal connFrom
(fspathFrom, pathFrom, fspathTo, pathTo, realPathTo,
update, desc, fp, ress, id) =
let info = Fileinfo.get false fspathTo pathTo in
if
info.Fileinfo.typ <> `FILE ||
Props.length info.Fileinfo.desc <> Props.length desc
then
raise (Util.Transient (Printf.sprintf
"External copy program did not create target file (or bad length): %s"
(Path.toString pathTo)));
transferRessourceForkAndSetFileinfo
connFrom fspathFrom pathFrom fspathTo pathTo realPathTo
update desc fp ress id >>= fun res ->
Xferhint.insertEntry fspathTo pathTo fp;
Lwt.return res
let finishExternalTransferOnRoot =
Remote.registerRootCmdWithConnection
"finishExternalTransfer" finishExternalTransferLocal
let copyprogReg = Lwt_util.make_region 1
let transferFileUsingExternalCopyprog
rootFrom pathFrom rootTo fspathTo pathTo realPathTo
update desc fp ress id useExistingTarget =
Uutil.showProgress id Uutil.Filesize.zero "ext";
let prog =
if useExistingTarget then
Prefs.read copyprogrest
else
Prefs.read copyprog
in
let extraquotes = Prefs.read copyquoterem = `True
|| ( Prefs.read copyquoterem = `Default
&& Util.findsubstring "rsync" prog <> None) in
let addquotes root s =
match root with
| Common.Local, _ -> s
| Common.Remote _, _ -> if extraquotes then Uutil.quotes s else s in
let fromSpec =
(formatConnectionInfo rootFrom)
^ (addquotes rootFrom
(Fspath.toString (Fspath.concat (snd rootFrom) pathFrom))) in
let toSpec =
(formatConnectionInfo rootTo)
^ (addquotes rootTo
(Fspath.toString (Fspath.concat fspathTo pathTo))) in
let cmd = prog ^ " "
^ (Uutil.quotes fromSpec) ^ " "
^ (Uutil.quotes toSpec) in
Trace.log (Printf.sprintf "%s\n" cmd);
Lwt_util.resize_region copyprogReg (Prefs.read copymax);
Lwt_util.run_in_region copyprogReg 1
(fun () -> External.runExternalProgram cmd) >>= fun (_, log) ->
debug (fun() ->
let l = Util.trimWhitespace log in
Util.msg "transferFileUsingExternalCopyprog %s: returned...\n%s%s"
(Path.toString pathFrom)
l (if l="" then "" else "\n"));
Uutil.showProgress id (Props.length desc) "ext";
finishExternalTransferOnRoot rootTo rootFrom
(snd rootFrom, pathFrom, fspathTo, pathTo, realPathTo,
update, desc, fp, ress, id)
let transferFileLocal connFrom
(fspathFrom, pathFrom, fspathTo, pathTo, realPathTo,
update, desc, fp, ress, id) =
let (tempInfo, isTransferred) =
fileIsTransferred fspathTo pathTo desc fp ress in
if isTransferred then begin
let msg =
Printf.sprintf
"%s/%s has already been transferred\n"
(Fspath.toDebugString fspathTo) (Path.toString realPathTo)
in
let len = Uutil.Filesize.add (Props.length desc) (Osx.ressLength ress) in
Uutil.showProgress id len "alr";
setFileinfo fspathTo pathTo realPathTo update desc;
Xferhint.insertEntry fspathTo pathTo fp;
Lwt.return (`DONE (Success tempInfo, Some msg))
end else
registerFileTransfer pathTo fp
(fun () ->
match
tryCopyMovedFile fspathTo pathTo realPathTo update desc fp ress id
with
Some (info, msg) ->
Xferhint.insertEntry fspathTo pathTo fp;
Lwt.return (`DONE (Success info, Some msg))
| None ->
if shouldUseExternalCopyprog update desc then
Lwt.return (`EXTERNAL (prepareExternalTransfer fspathTo pathTo))
else begin
reallyTransferFile
connFrom fspathFrom pathFrom fspathTo pathTo realPathTo
update desc fp ress id tempInfo >>= fun status ->
Xferhint.insertEntry fspathTo pathTo fp;
Lwt.return (`DONE (status, None))
end)
let transferFileOnRoot =
Remote.registerRootCmdWithConnection "transferFile" transferFileLocal
We limit the size of the output buffers to about 512 KB
( we can not go above the limit below plus 64 )
(we cannot go above the limit below plus 64) *)
let transferFileReg = Lwt_util.make_region 440
let bufferSize sz =
min 64 ((truncate (Uutil.Filesize.toFloat sz) + 1023) / 1024)
+
let transferFile
rootFrom pathFrom rootTo fspathTo pathTo realPathTo
update desc fp ress id =
let f () =
Abort.check id;
transferFileOnRoot rootTo rootFrom
(snd rootFrom, pathFrom, fspathTo, pathTo, realPathTo,
update, desc, fp, ress, id) >>= fun status ->
match status with
`DONE (status, msg) ->
begin match msg with
Some msg ->
if fst rootTo <> Common.Local then begin
let len =
Uutil.Filesize.add (Props.length desc) (Osx.ressLength ress)
in
Uutil.showProgress id len "rem"
end;
Trace.log msg
| None ->
()
end;
Lwt.return status
| `EXTERNAL useExistingTarget ->
transferFileUsingExternalCopyprog
rootFrom pathFrom rootTo fspathTo pathTo realPathTo
update desc fp ress id useExistingTarget
in
When streaming , we only transfer one file at a time , so we do n't
need to limit the number of concurrent transfers
need to limit the number of concurrent transfers *)
if Prefs.read Remote.streamingActivated then
f ()
else
let bufSz = bufferSize (max (Props.length desc) (Osx.ressLength ress)) in
Lwt_util.run_in_region transferFileReg bufSz f
let file rootFrom pathFrom rootTo fspathTo pathTo realPathTo
update desc fp stamp ress id =
debug (fun() -> Util.msg "copyRegFile(%s,%s) -> (%s,%s,%s,%s,%s)\n"
(Common.root2string rootFrom) (Path.toString pathFrom)
(Common.root2string rootTo) (Path.toString realPathTo)
(Fspath.toDebugString fspathTo) (Path.toString pathTo)
(Props.toString desc));
let timer = Trace.startTimer "Transmitting file" in
begin match rootFrom, rootTo with
(Common.Local, fspathFrom), (Common.Local, realFspathTo) ->
localFile
fspathFrom pathFrom fspathTo pathTo realPathTo
update desc (Osx.ressLength ress) (Some id);
paranoidCheck fspathTo pathTo realPathTo desc fp ress
| _ ->
transferFile
rootFrom pathFrom rootTo fspathTo pathTo realPathTo
update desc fp ress id
end >>= fun status ->
Trace.showTimer timer;
match status with
Success info ->
checkContentsChange rootFrom pathFrom desc fp stamp ress false
>>= fun () ->
Lwt.return info
| Failure reason ->
checkContentsChange rootFrom pathFrom desc fp stamp ress true
>>= fun () ->
saveTempFileOnRoot rootTo (pathTo, realPathTo, reason)
|
f092fcae7de760a29c9c56d5b1da4fa3e2e4916c88d9c1b28bf04000f9d1c54d | janestreet/async_smtp | reject_or_error.ml | open! Core
open! Async
type t =
{ reject : Smtp_reply.t option [@sexp.option]
; error : Error.t
; here : Source_code_position.t option [@sexp.option]
}
[@@deriving sexp_of]
let error t =
match t.here with
| None -> t.error
| Some here ->
Error.of_thunk (fun () ->
sprintf !"%{Error#hum}\nat %{Source_code_position}" t.error here)
;;
let reject t = t.reject
let of_error ?reject ~here error = { reject; error; here = Some here }
let of_exn ?reject ~here exn = of_error ?reject ~here (Error.of_exn exn)
let of_string ?reject ~here msg = of_error ?reject ~here (Error.of_string msg)
let createf ?reject ~here fmt = ksprintf (of_string ?reject ~here) fmt
let of_reject ~here reject =
of_error ~reject ~here (Error.create "REJECT" reject [%sexp_of: Smtp_reply.t])
;;
let of_list ts =
{ reject = List.find_map ts ~f:reject
; error = Error.of_list (List.map ts ~f:error)
; here = None
}
;;
let tag_error ~tag t = { t with error = Error.tag t.error ~tag }
let maybe_tag_error ?tag t =
match tag with
| None -> t
| Some tag -> tag_error ~tag t
;;
let tag_here ~here t =
match t.here with
| None -> { t with here = Some here }
| Some here' ->
if Source_code_position.equal here here'
then t
else { t with here = Some here; error = error t }
;;
let maybe_tag_here ?here t =
match here with
| None -> t
| Some here -> tag_here ~here t
;;
let tag ~tag ?here t = tag_error ~tag t |> maybe_tag_here ?here
let tag' ?tag ?here t = maybe_tag_error ?tag t |> maybe_tag_here ?here
| null | https://raw.githubusercontent.com/janestreet/async_smtp/c2c1f8b7b27f571a99d2f21e8a31ce150fbd6ced/src/reject_or_error.ml | ocaml | open! Core
open! Async
type t =
{ reject : Smtp_reply.t option [@sexp.option]
; error : Error.t
; here : Source_code_position.t option [@sexp.option]
}
[@@deriving sexp_of]
let error t =
match t.here with
| None -> t.error
| Some here ->
Error.of_thunk (fun () ->
sprintf !"%{Error#hum}\nat %{Source_code_position}" t.error here)
;;
let reject t = t.reject
let of_error ?reject ~here error = { reject; error; here = Some here }
let of_exn ?reject ~here exn = of_error ?reject ~here (Error.of_exn exn)
let of_string ?reject ~here msg = of_error ?reject ~here (Error.of_string msg)
let createf ?reject ~here fmt = ksprintf (of_string ?reject ~here) fmt
let of_reject ~here reject =
of_error ~reject ~here (Error.create "REJECT" reject [%sexp_of: Smtp_reply.t])
;;
let of_list ts =
{ reject = List.find_map ts ~f:reject
; error = Error.of_list (List.map ts ~f:error)
; here = None
}
;;
let tag_error ~tag t = { t with error = Error.tag t.error ~tag }
let maybe_tag_error ?tag t =
match tag with
| None -> t
| Some tag -> tag_error ~tag t
;;
let tag_here ~here t =
match t.here with
| None -> { t with here = Some here }
| Some here' ->
if Source_code_position.equal here here'
then t
else { t with here = Some here; error = error t }
;;
let maybe_tag_here ?here t =
match here with
| None -> t
| Some here -> tag_here ~here t
;;
let tag ~tag ?here t = tag_error ~tag t |> maybe_tag_here ?here
let tag' ?tag ?here t = maybe_tag_error ?tag t |> maybe_tag_here ?here
| |
646cd988edceb1d522d247217e32af3293e08f9e0e2e6232271973cfa0ae565e | Drup/furl | furl.ml | open Furl_utils
*
{ 2 Meta - variables }
To better read this file , here is the method of variable naming :
For type variables :
- f is a function type
- r is a return type of the associated f
- c are for types related to converter , used with r or f
- x is the intermediate type for type - level concatenation of diff - list .
For variables :
- re , r are for regular expressions
- i d is Re 's markid
- a is for atom
- p is for path
- q is for query
- cl is for converter list
- w is for witness ( see section matching )
- k is for kontinuation ( with a k ) .
is heavily recommended to browse this code .
{2 Meta-variables}
To better read this file, here is the method of variable naming:
For type variables:
- f is a function type
- r is a return type of the associated f
- c are for types related to converter, used with r or f
- x is the intermediate type for type-level concatenation of diff-list.
For variables:
- re, r are for regular expressions
- id is Re's markid
- a is for atom
- p is for path
- q is for query
- cl is for converter list
- w is for witness (see section matching)
- k is for kontinuation (with a k).
Merlin is heavily recommended to browse this code.
*)
* { 2 The various types }
type 'a atom = 'a Tyre.t
module Types = struct
(* type ('f, 'r) atom = *)
(* | PathConst : string -> ('r, 'r) atom *)
(* | Path : 'a Tyre.t -> ('r, 'r -> 'a) atom *)
type ('fu, 'return) path =
| Host : string -> ('r, 'r) path
| Rel : ('r, 'r) path
| PathConst :
('f, 'r) path * string
-> ('f, 'r) path
| PathAtom :
('f,'a -> 'r) path * 'a atom
-> ('f, 'r) path
type ('fu, 'return) query =
| Nil : ('r,'r) query
| Any : ('r,'r) query
| QueryAtom : string * 'a atom
* ( 'f, 'r) query
-> ('a -> 'f, 'r) query
type slash = Slash | NoSlash | MaybeSlash
(** A convertible url is a path and a query (and potentially a slash).
The type is the concatenation of both types.
*)
type ('f,'r) url =
| Url : slash
* ('f, 'x ) path
* ( 'x, 'r) query
-> ('f, 'r) url
end
We need the constructors in scope ,
disambiguation does n't work on GADTs .
disambiguation doesn't work on GADTs. *)
open Tyre.Internal
open Types
(** {2 Combinators} *)
module Path = struct
type ('f,'r) t = ('f,'r) Types.path
let host s = Host s
let relative = Rel
let add path b = PathConst(path,b)
let add_atom path b = PathAtom(path,b)
let rec concat
: type f r x.
(f,x ) t ->
( x,r) t ->
(f, r) t
= fun p1 p2 -> match p2 with
| Host _ -> p1
| Rel -> p1
| PathConst (p,s) -> PathConst(concat p1 p, s)
| PathAtom (p,a) -> PathAtom(concat p1 p, a)
end
module Query = struct
type ('f,'r) t = ('f,'r) Types.query
let nil : _ t = Nil
let any = Any
let add n x query = QueryAtom (n,x,query)
let rec make_any
: type f r . (f,r) t -> (f,r) t
= function
| Nil -> Any
| Any -> Any
| QueryAtom (n,x,q) -> QueryAtom(n,x,make_any q)
let rec concat
: type f r x.
(f,x ) t ->
( x,r) t ->
(f, r) t
= fun q1 q2 -> match q1 with
| Nil -> q2
| Any -> make_any q2
| QueryAtom (n,x,q) -> QueryAtom (n,x, concat q q2)
end
module Url = struct
type ('f,'r) t = ('f,'r) url
type slash = Types.slash = Slash | NoSlash | MaybeSlash
let make ?(slash=NoSlash) path query : _ t =
Url (slash, path, query)
let prefix_path path = function
| Url (slash, path', query) ->
Url (slash, Path.concat path path', query)
let add_query query = function
| Url (slash, path, query') ->
Url (slash, path, Query.concat query' query)
end
let nil = Query.nil
let any = Query.any
let ( ** ) (n,x) q = Query.add n x q
let host = Path.host
let rel = Path.relative
let (/) = Path.add
let (/%) = Path.add_atom
let (/?) path query = Url.make ~slash:NoSlash path query
let (//?) path query = Url.make ~slash:Slash path query
let (/??) path query = Url.make ~slash:MaybeSlash path query
let (~$) f = f ()
* { 2 Finalization }
(** An url with an empty list of converters.
It can be evaluated/extracted/matched against.
*)
type ('f, 'r) t = ('f, 'r) Url.t
* { 2 Evaluation functions }
(** Evaluation is the act of filling the holes.
The process is rather straightforward using, once again, continuations.
*)
let eval_atom p x = Tyre.(eval (Internal.to_t p) x)
let eval_top_atom : type a. a raw -> a -> string list
= function
| Opt p -> (function None -> [] | Some x -> [eval_atom p x])
| Rep p ->
fun l -> Seq.to_list @@ Seq.map (eval_atom p) l
| e -> fun x -> [eval_atom e x]
let rec eval_path
: type r f.
(f,r) Path.t ->
(string option -> string list -> r) ->
f
= fun p k -> match p with
| Host s -> k (Some s) []
| Rel -> k None []
| PathConst (p, s) ->
eval_path p @@ fun h r -> k h (s :: r)
| PathAtom (p, a) ->
eval_path p @@ fun h r x ->
k h (eval_top_atom (from_t a) x @ r)
let rec eval_query
: type r f.
(f,r) Query.t ->
((string * string list) list -> r) ->
f
= fun q k -> match q with
| Nil -> k []
| Any -> k []
| QueryAtom (n,a,q) ->
fun x -> eval_query q @@ fun r ->
k ((n, eval_top_atom (from_t a) x) :: r)
let keval
: ('a, 'b) url -> (Uri.t -> 'b) -> 'a
= fun (Url(slash,p,q)) k ->
eval_path p @@ fun host path ->
eval_query q @@ fun query ->
k @@
let path = match slash with
| Slash -> "" :: path
| NoSlash
| MaybeSlash -> path
in Uri.make
?host
~path:(String.concat "/" @@ List.rev path)
~query ()
let eval url = keval url (fun x -> x)
* { 2 matching }
* Matching is the act of extracting the information contained in a url
using a formatted url .
This is not straightforward .
We proceed in two steps :
1 . Construct a regular expression matching the desired url .
2 . Extract the information from the substrings once the url is matched .
using a formatted url.
This is not straightforward.
We proceed in two steps:
1. Construct a regular expression matching the desired url.
2. Extract the information from the substrings once the url is matched.
*)
* { 3 Regexp construction }
The functions associated with this step are named re _ *
In order to record how we constructed the regexp and how to later
extract information , we build a witness containing all the tools we need .
For each types ( atom , query , path , uri ) , these witnesses are named re _ * .
{ 4 Principles of construction of the regexp }
Each alternative is marked with { ! Re.mark } . We store the markid in order
to be able to guess the branch matched .
The path is simply a concatenation of the regular expressions , separated
by / , with the particular treatment of lists .
query elements can appear in any order , so we reorder the
key by alphabetical order ( both in the incoming query and the extraction ) .
We register the permutation as a mapping from indexes to matching group .
The functions associated with this step are named re_*
In order to record how we constructed the regexp and how to later
extract information, we build a witness containing all the tools we need.
For each types (atom, query, path, uri), these witnesses are named re_*.
{4 Principles of construction of the regexp}
Each alternative is marked with {!Re.mark}. We store the markid in order
to be able to guess the branch matched.
The path is simply a concatenation of the regular expressions, separated
by /, with the particular treatment of lists.
query elements can appear in any order, so we reorder the
key by alphabetical order (both in the incoming query and the extraction).
We register the permutation as a mapping from indexes to matching group.
*)
(** The sorting criteria for queries. It must be used both for
regexp construction and extraction.
*)
let sort_query l =
List.sort (fun (x,_) (y,_) -> compare (x: string) y) l
type 'a re_atom = 'a Tyre.Internal.wit
let re_atom re = Tyre.Internal.build re
(** Top level atoms are specialized for path and query, see documentation. *)
let re_atom_path
: type a . int -> a raw -> int * a re_atom * Re.t
=
let open Re in
fun i -> function
| Rep e ->
let _, w, re = re_atom 1 e in
(i+1), Rep (i, w, Re.compile re),
group @@ Furl_re.list ~component:`Path 0 @@ no_group re
| Opt e ->
let i', w, re = re_atom i e in
let id, re = mark re in
i', Opt (id,w),
seq [alt [epsilon ; seq [Furl_re.slash ; re]]]
| e ->
let i', w, re = re_atom i e in
i', w, seq [Furl_re.slash; re]
let re_atom_query
: type a . int -> a raw -> int * a re_atom * Re.t
=
let open Re in
fun i -> function
| Rep e ->
let _, w, re = re_atom 1 e in
(i+1), Rep (i, w, Re.compile re),
group @@ Furl_re.list ~component:`Query_value 0 @@ no_group re
| e -> re_atom i e
type (_,_) re_path =
| Start : ('r,'r) re_path
| PathAtom :
('f, 'a -> 'r) re_path * 'a re_atom
-> ('f, 'r) re_path
let rec re_path
: type r f .
int -> (f, r) Path.t ->
int * (f, r) re_path * Re.t list
= let open Re in fun i -> function
| Host s ->
let re = Re.str @@ Uri.pct_encode ~component:`Host s in
i, Start, [re]
| Rel -> i, Start, []
| PathConst (p,s) ->
let i', p, re = re_path i p in
i', p,
str s :: Furl_re.slash :: re
| PathAtom (p,a) ->
let i', wp, rp = re_path i p in
let i'', wa, ra = re_atom_path i' @@ from_t a in
i'',
PathAtom (wp, wa),
ra :: rp
type ('fu,'ret) re_query =
| Nil : ('r,'r) re_query
| Any : ('r,'r) re_query
| Cons :
'a re_atom * ('f,'r) re_query
-> ('a -> 'f,'r) re_query
let rec collect_re_query
: type r f .
(f, r) Query.t ->
(f, r) re_query * bool * (string * (Re.t * int)) list
= function
| Nil -> Nil, false, []
| Any -> Any, true, []
| QueryAtom (s,a,q) ->
let grps, wa, ra = re_atom_query 0 @@ from_t a in
let wq, b_any, rq = collect_re_query q in
Cons (wa, wq), b_any, (s, (ra, grps)) :: rq
let rec shift_lits : type a . int -> a re_atom -> a re_atom =
fun shift -> function
| Lit i -> Lit (i+shift)
| Conv (x, f) -> Conv (shift_lits shift x, f)
| Opt (m, x) -> Opt (m, shift_lits shift x)
| Alt (m, x1, x2) -> Alt (m, shift_lits shift x1, shift_lits shift x2)
| Seq (x1, x2) -> Seq (shift_lits shift x1, shift_lits shift x2)
| Rep (i, x, r) -> Rep (shift+i, x, r)
let rec permut_query :
type r f . int -> int array -> (r, f) re_query -> (r, f) re_query =
fun n permutation -> function
| Nil -> Nil
| Any -> Any
| Cons (wa, wq) ->
let shift = permutation.(n) in
let wa = shift_lits shift wa in
Cons (wa, permut_query (n+1) permutation wq)
let re_query current_idx q =
let wq, b, rql = collect_re_query q in
let rel = sort_query rql in
let p =
build_permutation current_idx (fun (_,(_,i)) -> i) rql rel
in
let wq = permut_query 0 p wq in
wq, b, rel
type ('f,'r) re_url =
| ReUrl :
('f, 'x ) re_path
* ( 'x, 'r) re_query
-> ('f, 'r) re_url
let re_url
: type f r. (f,r) Url.t -> (f,r) re_url * Re.t
= function Url(slash,p,q) ->
let end_path = match slash with
| NoSlash -> Re.epsilon
| Slash -> Re.char '/'
| MaybeSlash -> Re.(opt @@ char '/')
in
let idx, wp, rp = re_path 1 p in
match q with
| Nil ->
ReUrl (wp, Nil),
Re.seq @@ List.rev (end_path :: rp)
| Any ->
let end_re = Re.(opt @@ seq [Re.char '?' ; rep any]) in
ReUrl (wp, Nil),
Re.seq @@ List.rev_append rp [end_path; end_re]
| _ ->
let wq, any_query, rel = re_query idx q in
let query_sep = Furl_re.query_sep ~any:any_query in
let add_around_query =
if not any_query then fun x -> x
else fun l -> Re.(rep any) :: l
in
let re =
rel
|> List.fold_left (fun l (s,(re,_)) ->
Re.seq [Re.str (s ^ "=") ; re ] :: l
) []
|> intersperse query_sep
|> add_around_query
|> List.rev
|> add_around_query
in
let re =
Re.seq @@ List.rev_append rp (end_path :: Re.char '?' :: re)
in
ReUrl(wp,wq), re
let get_re url = snd @@ re_url url
* { 3 Extraction . }
(** Extracting atom is just a matter of following the witness.
We just need to take care of counting where we are in the matching groups.
*)
let extract_atom = extract
(** Since path is in reversed order, we proceed by continuation.
*)
let rec extract_path
: type f x r.
original:string ->
(f,x) re_path ->
Re.Group.t ->
(x -> r) ->
(f -> r)
= fun ~original wp subs k -> match wp with
| Start -> k
| PathAtom (rep, rea) ->
let v = extract_atom ~original rea subs in
let k f = k (f v) in
extract_path ~original rep subs k
(** Query are in the right order, we can proceed in direct style. *)
let rec extract_query
: type x r.
original:string ->
(x,r) re_query ->
Re.Group.t ->
x -> r
= fun ~original wq subs f -> match wq with
| Nil -> f
| Any -> f
| Cons (rea,req) ->
let v = extract_atom ~original rea subs in
extract_query ~original req subs (f v)
let extract_url
: type r f.
original:string ->
(f, r) re_url ->
Re.Group.t -> f -> r
= fun ~original (ReUrl (wp, wq)) subs f ->
let k = extract_query ~original wq subs in
let k = extract_path ~original wp subs k in
k f
let prepare_uri uri =
uri
|> Uri.query
|> sort_query
|> Uri.with_query uri
|> Uri.path_and_query
let extract url =
let re_url, re = re_url url in
let re = Re.(compile @@ whole_string re) in
fun ~f uri ->
let s = prepare_uri uri in
let subs = Re.exec re s in
extract_url ~original:s re_url subs f
* { 4 Multiple match }
type 'r route = Route : ('f, 'r) t * 'f -> 'r route
let route url f = Route (url, f)
let (-->) = route
type 'r re_ex =
ReEx : 'f * Re.Mark.t * ('f, 'r) re_url -> 'r re_ex
It 's important to keep the order here , since Re will choose
the first regexp if there is ambiguity .
the first regexp if there is ambiguity.
*)
let rec build_info_list = function
| [] -> [], []
| Route (url, f) :: l ->
let rel, wl = build_info_list l in
let re_url, re = re_url url in
let id, re = Re.mark re in
re::rel, ReEx (f, id, re_url)::wl
let rec find_and_trigger
: type r. original:string -> Re.Group.t -> r re_ex list -> r
= fun ~original subs -> function
| [] ->
Invariant : At least one of the regexp of the alternative matches .
assert false
| ReEx (f, id, re_url) :: l ->
if Re.Mark.test subs id then extract_url ~original re_url subs f
else find_and_trigger ~original subs l
let match_url
: type r.
default:(Uri.t -> r) -> r route list -> Uri.t -> r
= fun ~default l ->
let rel, wl = build_info_list l in
let re = Re.(compile @@ whole_string @@ alt rel) in
fun uri ->
let s = prepare_uri uri in
try
let subs = Re.exec re s in
find_and_trigger ~original:s subs wl
with
Not_found -> default uri
| null | https://raw.githubusercontent.com/Drup/furl/ed4b2909b4b5a586541f8112323fa1fe2778eaa1/src/furl.ml | ocaml | type ('f, 'r) atom =
| PathConst : string -> ('r, 'r) atom
| Path : 'a Tyre.t -> ('r, 'r -> 'a) atom
* A convertible url is a path and a query (and potentially a slash).
The type is the concatenation of both types.
* {2 Combinators}
* An url with an empty list of converters.
It can be evaluated/extracted/matched against.
* Evaluation is the act of filling the holes.
The process is rather straightforward using, once again, continuations.
* The sorting criteria for queries. It must be used both for
regexp construction and extraction.
* Top level atoms are specialized for path and query, see documentation.
* Extracting atom is just a matter of following the witness.
We just need to take care of counting where we are in the matching groups.
* Since path is in reversed order, we proceed by continuation.
* Query are in the right order, we can proceed in direct style. | open Furl_utils
*
{ 2 Meta - variables }
To better read this file , here is the method of variable naming :
For type variables :
- f is a function type
- r is a return type of the associated f
- c are for types related to converter , used with r or f
- x is the intermediate type for type - level concatenation of diff - list .
For variables :
- re , r are for regular expressions
- i d is Re 's markid
- a is for atom
- p is for path
- q is for query
- cl is for converter list
- w is for witness ( see section matching )
- k is for kontinuation ( with a k ) .
is heavily recommended to browse this code .
{2 Meta-variables}
To better read this file, here is the method of variable naming:
For type variables:
- f is a function type
- r is a return type of the associated f
- c are for types related to converter, used with r or f
- x is the intermediate type for type-level concatenation of diff-list.
For variables:
- re, r are for regular expressions
- id is Re's markid
- a is for atom
- p is for path
- q is for query
- cl is for converter list
- w is for witness (see section matching)
- k is for kontinuation (with a k).
Merlin is heavily recommended to browse this code.
*)
* { 2 The various types }
type 'a atom = 'a Tyre.t
module Types = struct
type ('fu, 'return) path =
| Host : string -> ('r, 'r) path
| Rel : ('r, 'r) path
| PathConst :
('f, 'r) path * string
-> ('f, 'r) path
| PathAtom :
('f,'a -> 'r) path * 'a atom
-> ('f, 'r) path
type ('fu, 'return) query =
| Nil : ('r,'r) query
| Any : ('r,'r) query
| QueryAtom : string * 'a atom
* ( 'f, 'r) query
-> ('a -> 'f, 'r) query
type slash = Slash | NoSlash | MaybeSlash
type ('f,'r) url =
| Url : slash
* ('f, 'x ) path
* ( 'x, 'r) query
-> ('f, 'r) url
end
We need the constructors in scope ,
disambiguation does n't work on GADTs .
disambiguation doesn't work on GADTs. *)
open Tyre.Internal
open Types
module Path = struct
type ('f,'r) t = ('f,'r) Types.path
let host s = Host s
let relative = Rel
let add path b = PathConst(path,b)
let add_atom path b = PathAtom(path,b)
let rec concat
: type f r x.
(f,x ) t ->
( x,r) t ->
(f, r) t
= fun p1 p2 -> match p2 with
| Host _ -> p1
| Rel -> p1
| PathConst (p,s) -> PathConst(concat p1 p, s)
| PathAtom (p,a) -> PathAtom(concat p1 p, a)
end
module Query = struct
type ('f,'r) t = ('f,'r) Types.query
let nil : _ t = Nil
let any = Any
let add n x query = QueryAtom (n,x,query)
let rec make_any
: type f r . (f,r) t -> (f,r) t
= function
| Nil -> Any
| Any -> Any
| QueryAtom (n,x,q) -> QueryAtom(n,x,make_any q)
let rec concat
: type f r x.
(f,x ) t ->
( x,r) t ->
(f, r) t
= fun q1 q2 -> match q1 with
| Nil -> q2
| Any -> make_any q2
| QueryAtom (n,x,q) -> QueryAtom (n,x, concat q q2)
end
module Url = struct
type ('f,'r) t = ('f,'r) url
type slash = Types.slash = Slash | NoSlash | MaybeSlash
let make ?(slash=NoSlash) path query : _ t =
Url (slash, path, query)
let prefix_path path = function
| Url (slash, path', query) ->
Url (slash, Path.concat path path', query)
let add_query query = function
| Url (slash, path, query') ->
Url (slash, path, Query.concat query' query)
end
let nil = Query.nil
let any = Query.any
let ( ** ) (n,x) q = Query.add n x q
let host = Path.host
let rel = Path.relative
let (/) = Path.add
let (/%) = Path.add_atom
let (/?) path query = Url.make ~slash:NoSlash path query
let (//?) path query = Url.make ~slash:Slash path query
let (/??) path query = Url.make ~slash:MaybeSlash path query
let (~$) f = f ()
* { 2 Finalization }
type ('f, 'r) t = ('f, 'r) Url.t
* { 2 Evaluation functions }
let eval_atom p x = Tyre.(eval (Internal.to_t p) x)
let eval_top_atom : type a. a raw -> a -> string list
= function
| Opt p -> (function None -> [] | Some x -> [eval_atom p x])
| Rep p ->
fun l -> Seq.to_list @@ Seq.map (eval_atom p) l
| e -> fun x -> [eval_atom e x]
let rec eval_path
: type r f.
(f,r) Path.t ->
(string option -> string list -> r) ->
f
= fun p k -> match p with
| Host s -> k (Some s) []
| Rel -> k None []
| PathConst (p, s) ->
eval_path p @@ fun h r -> k h (s :: r)
| PathAtom (p, a) ->
eval_path p @@ fun h r x ->
k h (eval_top_atom (from_t a) x @ r)
let rec eval_query
: type r f.
(f,r) Query.t ->
((string * string list) list -> r) ->
f
= fun q k -> match q with
| Nil -> k []
| Any -> k []
| QueryAtom (n,a,q) ->
fun x -> eval_query q @@ fun r ->
k ((n, eval_top_atom (from_t a) x) :: r)
let keval
: ('a, 'b) url -> (Uri.t -> 'b) -> 'a
= fun (Url(slash,p,q)) k ->
eval_path p @@ fun host path ->
eval_query q @@ fun query ->
k @@
let path = match slash with
| Slash -> "" :: path
| NoSlash
| MaybeSlash -> path
in Uri.make
?host
~path:(String.concat "/" @@ List.rev path)
~query ()
let eval url = keval url (fun x -> x)
* { 2 matching }
* Matching is the act of extracting the information contained in a url
using a formatted url .
This is not straightforward .
We proceed in two steps :
1 . Construct a regular expression matching the desired url .
2 . Extract the information from the substrings once the url is matched .
using a formatted url.
This is not straightforward.
We proceed in two steps:
1. Construct a regular expression matching the desired url.
2. Extract the information from the substrings once the url is matched.
*)
* { 3 Regexp construction }
The functions associated with this step are named re _ *
In order to record how we constructed the regexp and how to later
extract information , we build a witness containing all the tools we need .
For each types ( atom , query , path , uri ) , these witnesses are named re _ * .
{ 4 Principles of construction of the regexp }
Each alternative is marked with { ! Re.mark } . We store the markid in order
to be able to guess the branch matched .
The path is simply a concatenation of the regular expressions , separated
by / , with the particular treatment of lists .
query elements can appear in any order , so we reorder the
key by alphabetical order ( both in the incoming query and the extraction ) .
We register the permutation as a mapping from indexes to matching group .
The functions associated with this step are named re_*
In order to record how we constructed the regexp and how to later
extract information, we build a witness containing all the tools we need.
For each types (atom, query, path, uri), these witnesses are named re_*.
{4 Principles of construction of the regexp}
Each alternative is marked with {!Re.mark}. We store the markid in order
to be able to guess the branch matched.
The path is simply a concatenation of the regular expressions, separated
by /, with the particular treatment of lists.
query elements can appear in any order, so we reorder the
key by alphabetical order (both in the incoming query and the extraction).
We register the permutation as a mapping from indexes to matching group.
*)
let sort_query l =
List.sort (fun (x,_) (y,_) -> compare (x: string) y) l
type 'a re_atom = 'a Tyre.Internal.wit
let re_atom re = Tyre.Internal.build re
let re_atom_path
: type a . int -> a raw -> int * a re_atom * Re.t
=
let open Re in
fun i -> function
| Rep e ->
let _, w, re = re_atom 1 e in
(i+1), Rep (i, w, Re.compile re),
group @@ Furl_re.list ~component:`Path 0 @@ no_group re
| Opt e ->
let i', w, re = re_atom i e in
let id, re = mark re in
i', Opt (id,w),
seq [alt [epsilon ; seq [Furl_re.slash ; re]]]
| e ->
let i', w, re = re_atom i e in
i', w, seq [Furl_re.slash; re]
let re_atom_query
: type a . int -> a raw -> int * a re_atom * Re.t
=
let open Re in
fun i -> function
| Rep e ->
let _, w, re = re_atom 1 e in
(i+1), Rep (i, w, Re.compile re),
group @@ Furl_re.list ~component:`Query_value 0 @@ no_group re
| e -> re_atom i e
type (_,_) re_path =
| Start : ('r,'r) re_path
| PathAtom :
('f, 'a -> 'r) re_path * 'a re_atom
-> ('f, 'r) re_path
let rec re_path
: type r f .
int -> (f, r) Path.t ->
int * (f, r) re_path * Re.t list
= let open Re in fun i -> function
| Host s ->
let re = Re.str @@ Uri.pct_encode ~component:`Host s in
i, Start, [re]
| Rel -> i, Start, []
| PathConst (p,s) ->
let i', p, re = re_path i p in
i', p,
str s :: Furl_re.slash :: re
| PathAtom (p,a) ->
let i', wp, rp = re_path i p in
let i'', wa, ra = re_atom_path i' @@ from_t a in
i'',
PathAtom (wp, wa),
ra :: rp
type ('fu,'ret) re_query =
| Nil : ('r,'r) re_query
| Any : ('r,'r) re_query
| Cons :
'a re_atom * ('f,'r) re_query
-> ('a -> 'f,'r) re_query
let rec collect_re_query
: type r f .
(f, r) Query.t ->
(f, r) re_query * bool * (string * (Re.t * int)) list
= function
| Nil -> Nil, false, []
| Any -> Any, true, []
| QueryAtom (s,a,q) ->
let grps, wa, ra = re_atom_query 0 @@ from_t a in
let wq, b_any, rq = collect_re_query q in
Cons (wa, wq), b_any, (s, (ra, grps)) :: rq
let rec shift_lits : type a . int -> a re_atom -> a re_atom =
fun shift -> function
| Lit i -> Lit (i+shift)
| Conv (x, f) -> Conv (shift_lits shift x, f)
| Opt (m, x) -> Opt (m, shift_lits shift x)
| Alt (m, x1, x2) -> Alt (m, shift_lits shift x1, shift_lits shift x2)
| Seq (x1, x2) -> Seq (shift_lits shift x1, shift_lits shift x2)
| Rep (i, x, r) -> Rep (shift+i, x, r)
let rec permut_query :
type r f . int -> int array -> (r, f) re_query -> (r, f) re_query =
fun n permutation -> function
| Nil -> Nil
| Any -> Any
| Cons (wa, wq) ->
let shift = permutation.(n) in
let wa = shift_lits shift wa in
Cons (wa, permut_query (n+1) permutation wq)
let re_query current_idx q =
let wq, b, rql = collect_re_query q in
let rel = sort_query rql in
let p =
build_permutation current_idx (fun (_,(_,i)) -> i) rql rel
in
let wq = permut_query 0 p wq in
wq, b, rel
type ('f,'r) re_url =
| ReUrl :
('f, 'x ) re_path
* ( 'x, 'r) re_query
-> ('f, 'r) re_url
let re_url
: type f r. (f,r) Url.t -> (f,r) re_url * Re.t
= function Url(slash,p,q) ->
let end_path = match slash with
| NoSlash -> Re.epsilon
| Slash -> Re.char '/'
| MaybeSlash -> Re.(opt @@ char '/')
in
let idx, wp, rp = re_path 1 p in
match q with
| Nil ->
ReUrl (wp, Nil),
Re.seq @@ List.rev (end_path :: rp)
| Any ->
let end_re = Re.(opt @@ seq [Re.char '?' ; rep any]) in
ReUrl (wp, Nil),
Re.seq @@ List.rev_append rp [end_path; end_re]
| _ ->
let wq, any_query, rel = re_query idx q in
let query_sep = Furl_re.query_sep ~any:any_query in
let add_around_query =
if not any_query then fun x -> x
else fun l -> Re.(rep any) :: l
in
let re =
rel
|> List.fold_left (fun l (s,(re,_)) ->
Re.seq [Re.str (s ^ "=") ; re ] :: l
) []
|> intersperse query_sep
|> add_around_query
|> List.rev
|> add_around_query
in
let re =
Re.seq @@ List.rev_append rp (end_path :: Re.char '?' :: re)
in
ReUrl(wp,wq), re
let get_re url = snd @@ re_url url
* { 3 Extraction . }
let extract_atom = extract
let rec extract_path
: type f x r.
original:string ->
(f,x) re_path ->
Re.Group.t ->
(x -> r) ->
(f -> r)
= fun ~original wp subs k -> match wp with
| Start -> k
| PathAtom (rep, rea) ->
let v = extract_atom ~original rea subs in
let k f = k (f v) in
extract_path ~original rep subs k
let rec extract_query
: type x r.
original:string ->
(x,r) re_query ->
Re.Group.t ->
x -> r
= fun ~original wq subs f -> match wq with
| Nil -> f
| Any -> f
| Cons (rea,req) ->
let v = extract_atom ~original rea subs in
extract_query ~original req subs (f v)
let extract_url
: type r f.
original:string ->
(f, r) re_url ->
Re.Group.t -> f -> r
= fun ~original (ReUrl (wp, wq)) subs f ->
let k = extract_query ~original wq subs in
let k = extract_path ~original wp subs k in
k f
let prepare_uri uri =
uri
|> Uri.query
|> sort_query
|> Uri.with_query uri
|> Uri.path_and_query
let extract url =
let re_url, re = re_url url in
let re = Re.(compile @@ whole_string re) in
fun ~f uri ->
let s = prepare_uri uri in
let subs = Re.exec re s in
extract_url ~original:s re_url subs f
* { 4 Multiple match }
type 'r route = Route : ('f, 'r) t * 'f -> 'r route
let route url f = Route (url, f)
let (-->) = route
type 'r re_ex =
ReEx : 'f * Re.Mark.t * ('f, 'r) re_url -> 'r re_ex
It 's important to keep the order here , since Re will choose
the first regexp if there is ambiguity .
the first regexp if there is ambiguity.
*)
let rec build_info_list = function
| [] -> [], []
| Route (url, f) :: l ->
let rel, wl = build_info_list l in
let re_url, re = re_url url in
let id, re = Re.mark re in
re::rel, ReEx (f, id, re_url)::wl
let rec find_and_trigger
: type r. original:string -> Re.Group.t -> r re_ex list -> r
= fun ~original subs -> function
| [] ->
Invariant : At least one of the regexp of the alternative matches .
assert false
| ReEx (f, id, re_url) :: l ->
if Re.Mark.test subs id then extract_url ~original re_url subs f
else find_and_trigger ~original subs l
let match_url
: type r.
default:(Uri.t -> r) -> r route list -> Uri.t -> r
= fun ~default l ->
let rel, wl = build_info_list l in
let re = Re.(compile @@ whole_string @@ alt rel) in
fun uri ->
let s = prepare_uri uri in
try
let subs = Re.exec re s in
find_and_trigger ~original:s subs wl
with
Not_found -> default uri
|
b7fab6a5ea1073dca180c3cd8c154467b22e109b654ac9b5ce29823266d5088c | ivankelly/gambit | dc#.scm | ;==============================================================================
File : " dc#.scm " , Time - stamp : < 2007 - 04 - 04 14:25:51 feeley >
Copyright ( c ) 2005 - 2007 by , All Rights Reserved .
;==============================================================================
(##namespace ("dc#"
; special forms
spawn
recv
; procedures
self
pid?
make-tag
!
?
!?
make-tcp-node
goto
on
spawn-thread
current-node
current-node-id
current-node-name
become-tcp-node
default-tcp-node-port-number
default-tcp-node-name
))
;------------------------------------------------------------------------------
; Implementation of the basic Termite special forms:
;
; (spawn X) returns a reference to a newly created process which
; evaluates X
;
; (recv ...) retrieves oldest message from the mailbox that matches
; a pattern
(##define-macro (spawn . body)
`(spawn-thread (lambda () ,@body)))
(##define-macro (recv . clauses)
(define (parse-clauses clauses rev-pattern-clauses cont)
(cond ((null? clauses)
(cont (reverse rev-pattern-clauses)
#f))
((and (pair? (car clauses))
(eq? (car (car clauses)) 'after:))
(cond ((not (null? (cdr clauses)))
(error "after clause must be last"))
((not (>= (length (car clauses)) 2))
(error "after clause must specify timeout"))
(else
(cont (reverse rev-pattern-clauses)
(car clauses)))))
(else
(parse-clauses (cdr clauses)
(cons (car clauses) rev-pattern-clauses)
cont))))
(define (gen-clauses subject clauses gen-fail)
(if (null? clauses)
(gen-fail)
(gen-fail-binding subject
(cdr clauses)
(lambda (gen-fail)
(gen-clause subject
(car clauses)
gen-fail))
gen-fail)))
(define (gen-fail-binding subject clauses gen-body gen-fail)
(if (null? clauses)
(gen-body gen-fail)
(let ((fail-var (gensym)))
`(let ((,fail-var
(lambda ()
,(gen-clauses subject clauses gen-fail))))
,(gen-body (lambda () `(,fail-var)))))))
(define (gen-complete exprs)
(gen-begin (cons `(thread-mailbox-extract-and-rewind) exprs)))
(define (gen-clause subject clause gen-fail)
(let ((pattern (car clause)))
(gen-match subject
pattern
(lambda ()
(let ((second (cadr clause)))
(if (eq? second 'with:)
`(if ,(caddr clause)
,(gen-complete (cdddr clause))
,(gen-fail))
(gen-complete (cdr clause)))))
gen-fail)))
(define (gen-matches subject-and-patterns gen-success gen-fail)
(if (null? subject-and-patterns)
(gen-success)
(let ((subj-and-pat (car subject-and-patterns)))
(gen-match (car subj-and-pat)
(cdr subj-and-pat)
(lambda ()
(gen-matches (cdr subject-and-patterns)
gen-success
gen-fail))
gen-fail))))
(define (gen-match subject pattern gen-success gen-fail)
(cond ((eq? pattern '_)
(gen-success))
((symbol? pattern)
`(let ((,pattern ,subject))
,(gen-success)))
((or (number? pattern)
(boolean? pattern)
(string? pattern)
(char? pattern)
(keyword? pattern))
(gen-match-literal subject pattern gen-success gen-fail))
((and (pair? pattern)
(pair? (cdr pattern))
(null? (cddr pattern))
(eq? (car pattern) 'quote))
(gen-match-literal subject (cadr pattern) gen-success gen-fail))
((and (pair? pattern)
(pair? (cdr pattern))
(null? (cddr pattern))
(eq? (car pattern) 'unquote))
(gen-match-expression subject (cadr pattern) gen-success gen-fail))
((pair? pattern)
(gen-match-pair subject pattern gen-success gen-fail))
((null? pattern)
`(if (null? ,subject)
,(gen-success)
,(gen-fail)))
((vector? pattern)
(gen-match-vector subject pattern gen-success gen-fail))
(else
(error "gen-match encountered an unknown pattern" pattern))))
(define (gen-match-literal subject pattern gen-success gen-fail)
`(if (equal? ,subject ',pattern)
,(gen-success)
,(gen-fail)))
(define (gen-match-expression subject pattern gen-success gen-fail)
`(if (equal? ,subject ,pattern)
,(gen-success)
,(gen-fail)))
(define (gen-match-pair subject pattern gen-success gen-fail)
(force-var
subject
(lambda (subject-var)
`(if (pair? ,subject-var)
,(gen-matches (list (cons `(car ,subject-var) (car pattern))
(cons `(cdr ,subject-var) (cdr pattern)))
gen-success
gen-fail)
,(gen-fail)))))
(define (gen-match-vector subject pattern gen-success gen-fail)
(force-var
subject
(lambda (subject-var)
(let ((len (vector-length pattern)))
`(if (and (vector? ,subject-var)
(= (vector-length ,subject-var) ,len))
,(gen-matches (map (lambda (i)
(cons `(vector-ref ,subject-var ,i)
(vector-ref pattern i)))
(iota len))
gen-success
gen-fail)
,(gen-fail))))))
(define (force-var subject proc)
(if (symbol? subject)
(proc subject)
(let ((var (gensym)))
`(let ((,var ,subject))
,(proc var)))))
(define (gen-begin exprs)
(cond ((null? exprs)
`(void))
((null? (cdr exprs))
(car exprs))
(else
`(begin ,@exprs))))
(define (iota n)
(define (iot n lst)
(if (= n 0)
lst
(iot (- n 1) (cons (- n 1) lst))))
(iot n '()))
(parse-clauses
clauses
'()
(lambda (pattern-clauses after-clause)
(let* ((subject-var
(gensym))
(loop-var
(gensym))
(body
(gen-clauses subject-var
pattern-clauses
(lambda ()
`(,loop-var)))))
(if after-clause
(let ((timeout-var (gensym)))
`(let ((,timeout-var (timeout->time ,(cadr after-clause))))
(let ,loop-var ()
(let ((,subject-var
(thread-mailbox-next ,timeout-var #!void)))
(if (eq? ,subject-var #!void)
,(gen-begin (cddr after-clause))
,body)))))
`(let ,loop-var ()
(let ((,subject-var
(thread-mailbox-next)))
,body)))))))
;==============================================================================
| null | https://raw.githubusercontent.com/ivankelly/gambit/7377246988d0982ceeb10f4249e96badf3ff9a8f/examples/distr-comp/dc%23.scm | scheme | ==============================================================================
==============================================================================
special forms
procedures
------------------------------------------------------------------------------
Implementation of the basic Termite special forms:
(spawn X) returns a reference to a newly created process which
evaluates X
(recv ...) retrieves oldest message from the mailbox that matches
a pattern
============================================================================== |
File : " dc#.scm " , Time - stamp : < 2007 - 04 - 04 14:25:51 feeley >
Copyright ( c ) 2005 - 2007 by , All Rights Reserved .
(##namespace ("dc#"
spawn
recv
self
pid?
make-tag
!
?
!?
make-tcp-node
goto
on
spawn-thread
current-node
current-node-id
current-node-name
become-tcp-node
default-tcp-node-port-number
default-tcp-node-name
))
(##define-macro (spawn . body)
`(spawn-thread (lambda () ,@body)))
(##define-macro (recv . clauses)
(define (parse-clauses clauses rev-pattern-clauses cont)
(cond ((null? clauses)
(cont (reverse rev-pattern-clauses)
#f))
((and (pair? (car clauses))
(eq? (car (car clauses)) 'after:))
(cond ((not (null? (cdr clauses)))
(error "after clause must be last"))
((not (>= (length (car clauses)) 2))
(error "after clause must specify timeout"))
(else
(cont (reverse rev-pattern-clauses)
(car clauses)))))
(else
(parse-clauses (cdr clauses)
(cons (car clauses) rev-pattern-clauses)
cont))))
(define (gen-clauses subject clauses gen-fail)
(if (null? clauses)
(gen-fail)
(gen-fail-binding subject
(cdr clauses)
(lambda (gen-fail)
(gen-clause subject
(car clauses)
gen-fail))
gen-fail)))
(define (gen-fail-binding subject clauses gen-body gen-fail)
(if (null? clauses)
(gen-body gen-fail)
(let ((fail-var (gensym)))
`(let ((,fail-var
(lambda ()
,(gen-clauses subject clauses gen-fail))))
,(gen-body (lambda () `(,fail-var)))))))
(define (gen-complete exprs)
(gen-begin (cons `(thread-mailbox-extract-and-rewind) exprs)))
(define (gen-clause subject clause gen-fail)
(let ((pattern (car clause)))
(gen-match subject
pattern
(lambda ()
(let ((second (cadr clause)))
(if (eq? second 'with:)
`(if ,(caddr clause)
,(gen-complete (cdddr clause))
,(gen-fail))
(gen-complete (cdr clause)))))
gen-fail)))
(define (gen-matches subject-and-patterns gen-success gen-fail)
(if (null? subject-and-patterns)
(gen-success)
(let ((subj-and-pat (car subject-and-patterns)))
(gen-match (car subj-and-pat)
(cdr subj-and-pat)
(lambda ()
(gen-matches (cdr subject-and-patterns)
gen-success
gen-fail))
gen-fail))))
(define (gen-match subject pattern gen-success gen-fail)
(cond ((eq? pattern '_)
(gen-success))
((symbol? pattern)
`(let ((,pattern ,subject))
,(gen-success)))
((or (number? pattern)
(boolean? pattern)
(string? pattern)
(char? pattern)
(keyword? pattern))
(gen-match-literal subject pattern gen-success gen-fail))
((and (pair? pattern)
(pair? (cdr pattern))
(null? (cddr pattern))
(eq? (car pattern) 'quote))
(gen-match-literal subject (cadr pattern) gen-success gen-fail))
((and (pair? pattern)
(pair? (cdr pattern))
(null? (cddr pattern))
(eq? (car pattern) 'unquote))
(gen-match-expression subject (cadr pattern) gen-success gen-fail))
((pair? pattern)
(gen-match-pair subject pattern gen-success gen-fail))
((null? pattern)
`(if (null? ,subject)
,(gen-success)
,(gen-fail)))
((vector? pattern)
(gen-match-vector subject pattern gen-success gen-fail))
(else
(error "gen-match encountered an unknown pattern" pattern))))
(define (gen-match-literal subject pattern gen-success gen-fail)
`(if (equal? ,subject ',pattern)
,(gen-success)
,(gen-fail)))
(define (gen-match-expression subject pattern gen-success gen-fail)
`(if (equal? ,subject ,pattern)
,(gen-success)
,(gen-fail)))
(define (gen-match-pair subject pattern gen-success gen-fail)
(force-var
subject
(lambda (subject-var)
`(if (pair? ,subject-var)
,(gen-matches (list (cons `(car ,subject-var) (car pattern))
(cons `(cdr ,subject-var) (cdr pattern)))
gen-success
gen-fail)
,(gen-fail)))))
(define (gen-match-vector subject pattern gen-success gen-fail)
(force-var
subject
(lambda (subject-var)
(let ((len (vector-length pattern)))
`(if (and (vector? ,subject-var)
(= (vector-length ,subject-var) ,len))
,(gen-matches (map (lambda (i)
(cons `(vector-ref ,subject-var ,i)
(vector-ref pattern i)))
(iota len))
gen-success
gen-fail)
,(gen-fail))))))
(define (force-var subject proc)
(if (symbol? subject)
(proc subject)
(let ((var (gensym)))
`(let ((,var ,subject))
,(proc var)))))
(define (gen-begin exprs)
(cond ((null? exprs)
`(void))
((null? (cdr exprs))
(car exprs))
(else
`(begin ,@exprs))))
(define (iota n)
(define (iot n lst)
(if (= n 0)
lst
(iot (- n 1) (cons (- n 1) lst))))
(iot n '()))
(parse-clauses
clauses
'()
(lambda (pattern-clauses after-clause)
(let* ((subject-var
(gensym))
(loop-var
(gensym))
(body
(gen-clauses subject-var
pattern-clauses
(lambda ()
`(,loop-var)))))
(if after-clause
(let ((timeout-var (gensym)))
`(let ((,timeout-var (timeout->time ,(cadr after-clause))))
(let ,loop-var ()
(let ((,subject-var
(thread-mailbox-next ,timeout-var #!void)))
(if (eq? ,subject-var #!void)
,(gen-begin (cddr after-clause))
,body)))))
`(let ,loop-var ()
(let ((,subject-var
(thread-mailbox-next)))
,body)))))))
|
b688ea20cecdb1c3d106dcc00be2bdddd5c4abfd824cf414f727cfd38359eddf | ghcjs/ghcjs-base | Internal.hs | {-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE ForeignFunctionInterface #
# LANGUAGE JavaScriptFFI #
# LANGUAGE UnboxedTuples #
# LANGUAGE GHCForeignImportPrim #
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE UnliftedFFITypes #-}
module JavaScript.Object.Internal
( Object(..)
, create
, allProps
, listProps
, getProp
, unsafeGetProp
, setProp
, unsafeSetProp
, isInstanceOf
) where
import Data.JSString
import Data.Typeable
import qualified GHCJS.Prim as Prim
import GHCJS.Types
import qualified JavaScript.Array as JA
import JavaScript.Array.Internal (JSArray, SomeJSArray(..))
import Unsafe.Coerce
import qualified GHC.Exts as Exts
newtype Object = Object JSVal deriving (Typeable)
instance IsJSVal Object
-- | create an empty object
create :: IO Object
create = js_create
# INLINE create #
allProps :: Object -> IO JSArray
allProps o = js_allProps o
# INLINE allProps #
listProps :: Object -> IO [JSString]
listProps o = unsafeCoerce (js_listProps o)
# INLINE listProps #
| get a property from an object . If accessing the property results in
an exception , the exception is converted to a JSException . Since exception
handling code prevents some optimizations in some JS engines , you may want
to use unsafeGetProp instead
an exception, the exception is converted to a JSException. Since exception
handling code prevents some optimizations in some JS engines, you may want
to use unsafeGetProp instead
-}
getProp :: JSString -> Object -> IO JSVal
getProp p o = js_getProp p o
{-# INLINE getProp #-}
unsafeGetProp :: JSString -> Object -> IO JSVal
unsafeGetProp p o = js_unsafeGetProp p o
# INLINE unsafeGetProp #
setProp :: JSString -> JSVal -> Object -> IO ()
setProp p v o = js_setProp p v o
# INLINE setProp #
unsafeSetProp :: JSString -> JSVal -> Object -> IO ()
unsafeSetProp p v o = js_unsafeSetProp p v o
{-# INLINE unsafeSetProp #-}
isInstanceOf :: Object -> JSVal -> Bool
isInstanceOf o s = js_isInstanceOf o s
# INLINE isInstanceOf #
-- -----------------------------------------------------------------------------
foreign import javascript unsafe "$r = {};"
js_create :: IO Object
foreign import javascript safe "$2[$1]"
js_getProp :: JSString -> Object -> IO JSVal
foreign import javascript unsafe "$2[$1]"
js_unsafeGetProp :: JSString -> Object -> IO JSVal
foreign import javascript safe "$3[$1] = $2"
js_setProp :: JSString -> JSVal -> Object -> IO ()
foreign import javascript unsafe "$3[$1] = $2"
js_unsafeSetProp :: JSString -> JSVal -> Object -> IO ()
foreign import javascript unsafe "$1 instanceof $2"
js_isInstanceOf :: Object -> JSVal -> Bool
foreign import javascript unsafe "h$allProps"
js_allProps :: Object -> IO JSArray
foreign import javascript unsafe "h$listProps"
js_listProps :: Object -> IO Exts.Any -- [JSString]
| null | https://raw.githubusercontent.com/ghcjs/ghcjs-base/18f31dec5d9eae1ef35ff8bbf163394942efd227/JavaScript/Object/Internal.hs | haskell | # LANGUAGE DeriveDataTypeable #
# LANGUAGE EmptyDataDecls #
# LANGUAGE UnliftedFFITypes #
| create an empty object
# INLINE getProp #
# INLINE unsafeSetProp #
-----------------------------------------------------------------------------
[JSString] | # LANGUAGE ForeignFunctionInterface #
# LANGUAGE JavaScriptFFI #
# LANGUAGE UnboxedTuples #
# LANGUAGE GHCForeignImportPrim #
module JavaScript.Object.Internal
( Object(..)
, create
, allProps
, listProps
, getProp
, unsafeGetProp
, setProp
, unsafeSetProp
, isInstanceOf
) where
import Data.JSString
import Data.Typeable
import qualified GHCJS.Prim as Prim
import GHCJS.Types
import qualified JavaScript.Array as JA
import JavaScript.Array.Internal (JSArray, SomeJSArray(..))
import Unsafe.Coerce
import qualified GHC.Exts as Exts
newtype Object = Object JSVal deriving (Typeable)
instance IsJSVal Object
create :: IO Object
create = js_create
# INLINE create #
allProps :: Object -> IO JSArray
allProps o = js_allProps o
# INLINE allProps #
listProps :: Object -> IO [JSString]
listProps o = unsafeCoerce (js_listProps o)
# INLINE listProps #
| get a property from an object . If accessing the property results in
an exception , the exception is converted to a JSException . Since exception
handling code prevents some optimizations in some JS engines , you may want
to use unsafeGetProp instead
an exception, the exception is converted to a JSException. Since exception
handling code prevents some optimizations in some JS engines, you may want
to use unsafeGetProp instead
-}
getProp :: JSString -> Object -> IO JSVal
getProp p o = js_getProp p o
unsafeGetProp :: JSString -> Object -> IO JSVal
unsafeGetProp p o = js_unsafeGetProp p o
# INLINE unsafeGetProp #
setProp :: JSString -> JSVal -> Object -> IO ()
setProp p v o = js_setProp p v o
# INLINE setProp #
unsafeSetProp :: JSString -> JSVal -> Object -> IO ()
unsafeSetProp p v o = js_unsafeSetProp p v o
isInstanceOf :: Object -> JSVal -> Bool
isInstanceOf o s = js_isInstanceOf o s
# INLINE isInstanceOf #
foreign import javascript unsafe "$r = {};"
js_create :: IO Object
foreign import javascript safe "$2[$1]"
js_getProp :: JSString -> Object -> IO JSVal
foreign import javascript unsafe "$2[$1]"
js_unsafeGetProp :: JSString -> Object -> IO JSVal
foreign import javascript safe "$3[$1] = $2"
js_setProp :: JSString -> JSVal -> Object -> IO ()
foreign import javascript unsafe "$3[$1] = $2"
js_unsafeSetProp :: JSString -> JSVal -> Object -> IO ()
foreign import javascript unsafe "$1 instanceof $2"
js_isInstanceOf :: Object -> JSVal -> Bool
foreign import javascript unsafe "h$allProps"
js_allProps :: Object -> IO JSArray
foreign import javascript unsafe "h$listProps"
|
9a098b6011e5a9550bb337a3bc1bb17cba24d5f69acdd880f13840b91ca4439e | MinaProtocol/mina | mina_base.ml | (** Make {!Mina_base} submodules available through the normal path *)
module Signed_command_payload = Mina_base_signed_command_payload
module Signed_command = Mina_base_signed_command
module Payment_payload = Mina_base_payment_payload
module Stake_delegation = Mina_base_stake_delegation
module New_token_payload = Mina_base_new_token_payload
module New_account_payload = Mina_base_new_account_payload
module Minting_payload = Mina_base_minting_payload
module Signature = Mina_base_signature
module Signed_command_memo = Mina_base_signed_command_memo
module Token_id = Mina_base_token_id
module Account_update = Mina_base_account_update
module Zkapp_command = Mina_base_zkapp_command
module Account_id = Mina_base_account_id
module Zkapp_basic = Mina_base_zkapp_basic
module Zkapp_state = Mina_base_zkapp_state
module Zkapp_precondition = Mina_base_zkapp_precondition
module Verification_key_wire = Mina_base_verification_key_wire
module Permissions = Mina_base_permissions
module Account = Mina_base_account
module Ledger_hash = Mina_base_ledger_hash
module Epoch_data = Mina_base_epoch_data
module Epoch_ledger = Mina_base_epoch_ledger
module Epoch_seed = Mina_base_epoch_seed
module Fee_transfer = Mina_base_fee_transfer
module Coinbase_fee_transfer = Mina_base_coinbase_fee_transfer
module Coinbase = Mina_base_coinbase
module With_stack_hash = Mina_base_with_stack_hash
module Control = Mina_base_control
module User_command = Mina_base_user_command
module Pending_coinbase = Mina_base_pending_coinbase
module Fee_excess = Mina_base_fee_excess
module Transaction_status = Mina_base_transaction_status
module Call_stack_digest = Mina_base_call_stack_digest
module Stack_frame = Mina_base_stack_frame
module Sok_message = Mina_base_sok_message
module Fee_with_prover = Mina_base_fee_with_prover
module State_body_hash = Mina_base_state_body_hash
module Frozen_ledger_hash = Mina_base_frozen_ledger_hash
module Frozen_ledger_hash0 = Mina_base_frozen_ledger_hash0
module Staged_ledger_hash = Mina_base_staged_ledger_hash
module Protocol_constants_checked = Mina_base_protocol_constants_checked
module State_hash = Mina_base_state_hash
module Proof = Mina_base_proof
module With_status = Mina_base_with_status
| null | https://raw.githubusercontent.com/MinaProtocol/mina/7a380064e215dc6aa152b76a7c3254949e383b1f/src/lib/mina_wire_types/mina_base/mina_base.ml | ocaml | * Make {!Mina_base} submodules available through the normal path |
module Signed_command_payload = Mina_base_signed_command_payload
module Signed_command = Mina_base_signed_command
module Payment_payload = Mina_base_payment_payload
module Stake_delegation = Mina_base_stake_delegation
module New_token_payload = Mina_base_new_token_payload
module New_account_payload = Mina_base_new_account_payload
module Minting_payload = Mina_base_minting_payload
module Signature = Mina_base_signature
module Signed_command_memo = Mina_base_signed_command_memo
module Token_id = Mina_base_token_id
module Account_update = Mina_base_account_update
module Zkapp_command = Mina_base_zkapp_command
module Account_id = Mina_base_account_id
module Zkapp_basic = Mina_base_zkapp_basic
module Zkapp_state = Mina_base_zkapp_state
module Zkapp_precondition = Mina_base_zkapp_precondition
module Verification_key_wire = Mina_base_verification_key_wire
module Permissions = Mina_base_permissions
module Account = Mina_base_account
module Ledger_hash = Mina_base_ledger_hash
module Epoch_data = Mina_base_epoch_data
module Epoch_ledger = Mina_base_epoch_ledger
module Epoch_seed = Mina_base_epoch_seed
module Fee_transfer = Mina_base_fee_transfer
module Coinbase_fee_transfer = Mina_base_coinbase_fee_transfer
module Coinbase = Mina_base_coinbase
module With_stack_hash = Mina_base_with_stack_hash
module Control = Mina_base_control
module User_command = Mina_base_user_command
module Pending_coinbase = Mina_base_pending_coinbase
module Fee_excess = Mina_base_fee_excess
module Transaction_status = Mina_base_transaction_status
module Call_stack_digest = Mina_base_call_stack_digest
module Stack_frame = Mina_base_stack_frame
module Sok_message = Mina_base_sok_message
module Fee_with_prover = Mina_base_fee_with_prover
module State_body_hash = Mina_base_state_body_hash
module Frozen_ledger_hash = Mina_base_frozen_ledger_hash
module Frozen_ledger_hash0 = Mina_base_frozen_ledger_hash0
module Staged_ledger_hash = Mina_base_staged_ledger_hash
module Protocol_constants_checked = Mina_base_protocol_constants_checked
module State_hash = Mina_base_state_hash
module Proof = Mina_base_proof
module With_status = Mina_base_with_status
|
8790d9886a5fc8bd69ec3163a6108037a464d917fbc4774bc6c317c2aa418446 | TheAlgorithms/Haskell | Problem1.hs | module ProjectEuler.Problem1.Problem1 where
solList = filter (\n -> (rem n 5 == 0) || (rem n 3 == 0)) [1..999]
main = do
print $ sum solList | null | https://raw.githubusercontent.com/TheAlgorithms/Haskell/9dcabef99fb8995a760ff25a9e0d659114c0b9d3/src/ProjectEuler/Problem1/Problem1.hs | haskell | module ProjectEuler.Problem1.Problem1 where
solList = filter (\n -> (rem n 5 == 0) || (rem n 3 == 0)) [1..999]
main = do
print $ sum solList | |
31736b4f206547f8ff64248a6b573a5aaabada5a76342a1f3afd7aa5d9512f42 | kadena-io/pact | Alloc.hs | # LANGUAGE AllowAmbiguousTypes #
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE GADTs #-}
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
| Monadic contexts , more restricted than ' Symbolic ' , that only allow
-- allocation of quantified symbolic variables.
module Pact.Analyze.Alloc
( MonadAlloc (singForAll, singExists, singFree)
, forAll, exists, free
, Alloc
, runAlloc
) where
import Control.Monad.Except (ExceptT)
import Control.Monad.Reader (ReaderT)
import qualified Control.Monad.State.Lazy as LS
import Control.Monad.State.Strict (StateT)
import Control.Monad.Trans (MonadTrans (lift))
import Control.Monad.Trans.Maybe (MaybeT)
import qualified Control.Monad.Writer.Lazy as LW
import Control.Monad.Writer.Strict (WriterT)
import Data.SBV (Symbolic)
import qualified Data.SBV as SBV
import Pact.Analyze.Types (Concrete, S, SingI (sing), SingTy,
sansProv, withSymVal)
import Pact.Analyze.Util (sbvForall, sbvExists)
-- | A restricted symbolic context in which only quantified variable allocation
-- is permitted.
class Monad m => MonadAlloc m where
singForAll :: String -> SingTy a -> m (S (Concrete a)) -- ^ universally quantified
singExists :: String -> SingTy a -> m (S (Concrete a)) -- ^ existentially quantified
singFree :: String -> SingTy a -> m (S (Concrete a)) -- ^ quantified per the context of sat vs prove
default singForAll
:: (MonadTrans t, MonadAlloc m', m ~ t m')
=> String -> SingTy a -> m (S (Concrete a))
singForAll name ty = lift (singForAll name ty)
default singExists
:: (MonadTrans t, MonadAlloc m', m ~ t m')
=> String -> SingTy a -> m (S (Concrete a))
singExists name ty = lift (singExists name ty)
default singFree
:: (MonadTrans t, MonadAlloc m', m ~ t m')
=> String -> SingTy a -> m (S (Concrete a))
singFree name = lift . singFree name
forAll :: forall a m. (MonadAlloc m, SingI a) => String -> m (S (Concrete a))
forAll name = singForAll name (sing @a)
exists :: forall a m. (MonadAlloc m, SingI a) => String -> m (S (Concrete a))
exists name = singExists name (sing @a)
free :: forall a m. (MonadAlloc m, SingI a) => String -> m (S (Concrete a))
free name = singFree name (sing @a)
instance MonadAlloc m => MonadAlloc (ExceptT e m)
instance MonadAlloc m => MonadAlloc (MaybeT m)
instance MonadAlloc m => MonadAlloc (ReaderT r m)
instance MonadAlloc m => MonadAlloc (StateT s m)
instance MonadAlloc m => MonadAlloc (LS.StateT s m)
instance (MonadAlloc m, Monoid w) => MonadAlloc (WriterT w m)
instance (MonadAlloc m, Monoid w) => MonadAlloc (LW.WriterT w m)
-- * Standard 'MonadAlloc' implementation; 'Symbolic' restricted to use only
-- use quantified variable allocation.
-- TODO: implement @AllocT@ now that sbv has @SymbolicT@.
newtype Alloc a = Alloc { runAlloc :: Symbolic a }
deriving (Functor, Applicative, Monad)
instance MonadAlloc Alloc where
singForAll name ty = Alloc $ withSymVal ty $ sansProv <$> sbvForall name
singExists name ty = Alloc $ withSymVal ty $ sansProv <$> sbvExists name
singFree name ty = Alloc $ withSymVal ty $ sansProv <$> SBV.free name
| null | https://raw.githubusercontent.com/kadena-io/pact/bc69144ff39f6405a248f31855eca7d3a9232c2b/src-tool/Pact/Analyze/Alloc.hs | haskell | # LANGUAGE DefaultSignatures #
# LANGUAGE DeriveFunctor #
# LANGUAGE GADTs #
allocation of quantified symbolic variables.
| A restricted symbolic context in which only quantified variable allocation
is permitted.
^ universally quantified
^ existentially quantified
^ quantified per the context of sat vs prove
* Standard 'MonadAlloc' implementation; 'Symbolic' restricted to use only
use quantified variable allocation.
TODO: implement @AllocT@ now that sbv has @SymbolicT@. | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
| Monadic contexts , more restricted than ' Symbolic ' , that only allow
module Pact.Analyze.Alloc
( MonadAlloc (singForAll, singExists, singFree)
, forAll, exists, free
, Alloc
, runAlloc
) where
import Control.Monad.Except (ExceptT)
import Control.Monad.Reader (ReaderT)
import qualified Control.Monad.State.Lazy as LS
import Control.Monad.State.Strict (StateT)
import Control.Monad.Trans (MonadTrans (lift))
import Control.Monad.Trans.Maybe (MaybeT)
import qualified Control.Monad.Writer.Lazy as LW
import Control.Monad.Writer.Strict (WriterT)
import Data.SBV (Symbolic)
import qualified Data.SBV as SBV
import Pact.Analyze.Types (Concrete, S, SingI (sing), SingTy,
sansProv, withSymVal)
import Pact.Analyze.Util (sbvForall, sbvExists)
class Monad m => MonadAlloc m where
default singForAll
:: (MonadTrans t, MonadAlloc m', m ~ t m')
=> String -> SingTy a -> m (S (Concrete a))
singForAll name ty = lift (singForAll name ty)
default singExists
:: (MonadTrans t, MonadAlloc m', m ~ t m')
=> String -> SingTy a -> m (S (Concrete a))
singExists name ty = lift (singExists name ty)
default singFree
:: (MonadTrans t, MonadAlloc m', m ~ t m')
=> String -> SingTy a -> m (S (Concrete a))
singFree name = lift . singFree name
forAll :: forall a m. (MonadAlloc m, SingI a) => String -> m (S (Concrete a))
forAll name = singForAll name (sing @a)
exists :: forall a m. (MonadAlloc m, SingI a) => String -> m (S (Concrete a))
exists name = singExists name (sing @a)
free :: forall a m. (MonadAlloc m, SingI a) => String -> m (S (Concrete a))
free name = singFree name (sing @a)
instance MonadAlloc m => MonadAlloc (ExceptT e m)
instance MonadAlloc m => MonadAlloc (MaybeT m)
instance MonadAlloc m => MonadAlloc (ReaderT r m)
instance MonadAlloc m => MonadAlloc (StateT s m)
instance MonadAlloc m => MonadAlloc (LS.StateT s m)
instance (MonadAlloc m, Monoid w) => MonadAlloc (WriterT w m)
instance (MonadAlloc m, Monoid w) => MonadAlloc (LW.WriterT w m)
newtype Alloc a = Alloc { runAlloc :: Symbolic a }
deriving (Functor, Applicative, Monad)
instance MonadAlloc Alloc where
singForAll name ty = Alloc $ withSymVal ty $ sansProv <$> sbvForall name
singExists name ty = Alloc $ withSymVal ty $ sansProv <$> sbvExists name
singFree name ty = Alloc $ withSymVal ty $ sansProv <$> SBV.free name
|
84f32b04784984ce5501533c7067b31fcdb111fda7da4fd9510c6e4b0d2f107a | mmottl/aifad | split_impl.ml |
AIFAD - Automated Induction of Functions over
Author :
email :
WWW :
Copyright ( C ) 2002 Austrian Research Institute for Artificial Intelligence
Copyright ( C ) 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.1 of the License , or ( at your option ) any later version .
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. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 USA
AIFAD - Automated Induction of Functions over Algebraic Datatypes
Author: Markus Mottl
email:
WWW:
Copyright (C) 2002 Austrian Research Institute for Artificial Intelligence
Copyright (C) 2003- Markus Mottl
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*)
open Utils
open Algdt_types
open Algdt_utils
open Model_types
open Model_utils
open Factor
open Dshave
module Make (Spec : Split_intf.SPEC) = struct
open Spec
(* Split (co-)domain variables on some domain variable *)
(* (left, X (x, y), right) -> (left, x, y, right) *)
let split dom_ixs ix_cnt dvars cvars dvar_ix =
let n_dvars_1 = Array.length dvars - 1 in
let n_cvars_1 = Array.length cvars - 1 in
let { samples = dsamples; tp = dtp; histo = dhisto } = dvars.(dvar_ix) in
let subs_tps = dfspec.(dtp) in
let n_splits = Array.length dhisto in
let split_dvars = Array.make n_splits [||] in
let split_cvars = Array.make n_splits [||] in
let split_dom_ixs = Array.make n_splits [||] in
let split_ix_cnt = Array.make n_splits ix_cnt in
for split_cnstr = 0 to n_splits - 1 do
let freq = dhisto.(split_cnstr) in
let sub_tps = subs_tps.(split_cnstr) in
let n_dsubs = Array.length sub_tps in
let n_new_dvars = n_dvars_1 + n_dsubs in
let new_dvars = Array.make n_new_dvars dummy_var in
let new_dom_ixs = Array.make n_new_dvars dummy_sh_el in
for i = 0 to dvar_ix - 1 do
let cur_dvar = dvars.(i) in
new_dvars.(i) <-
{
samples = Array.make freq dummy_fdsum;
tp = cur_dvar.tp;
histo = Array.make (Array.length cur_dvar.histo) 0;
}
done;
Array.blit dom_ixs 0 new_dom_ixs 0 dvar_ix;
let n_dsubs_1 = n_dsubs - 1 in
for i = 0 to n_dsubs_1 do
let tp = sub_tps.(i) in
let ofs = dvar_ix + i in
new_dvars.(ofs) <-
{
samples = Array.make freq dummy_fdsum;
tp = tp;
histo = Array.make (Array.length dfspec.(tp)) 0;
};
new_dom_ixs.(ofs) <- FinVar (ix_cnt + i)
done;
let dvar_ix1 = dvar_ix + 1 in
for i = dvar_ix1 to n_dvars_1 do
let cur_dvar = dvars.(i) in
new_dvars.(i + n_dsubs_1) <-
{
samples = Array.make freq dummy_fdsum;
tp = cur_dvar.tp;
histo = Array.make (Array.length cur_dvar.histo) 0;
}
done;
let n_last = n_dvars_1 - dvar_ix in
Array.blit dom_ixs dvar_ix1 new_dom_ixs (dvar_ix + n_dsubs) n_last;
split_dvars.(split_cnstr) <- new_dvars;
split_dom_ixs.(split_cnstr) <- new_dom_ixs;
split_ix_cnt.(split_cnstr) <- ix_cnt + n_dsubs;
let make_new_cvar cvar =
{
samples = Array.make freq dummy_fdsum;
tp = cvar.tp;
histo = Array.make (Array.length cvar.histo) 0;
} in
split_cvars.(split_cnstr) <- Array.map make_new_cvar cvars
done;
let split_ixs = Array.make n_splits 0 in
for sample_ix = 0 to Array.length dsamples - 1 do
match dsamples.(sample_ix) with
| FDAtom split_cnstr ->
let new_sample_ix = split_ixs.(split_cnstr) in
split_ixs.(split_cnstr) <- new_sample_ix + 1;
let new_dvars = split_dvars.(split_cnstr) in
for i = 0 to dvar_ix - 1 do
let { histo = new_dhisto } as new_dvar = new_dvars.(i) in
let dsample = dvars.(i).samples.(sample_ix) in
new_dvar.samples.(new_sample_ix) <- dsample;
let dcnstr = fdsum_cnstr dsample in
new_dhisto.(dcnstr) <- new_dhisto.(dcnstr) + 1
done;
for i = dvar_ix + 1 to n_dvars_1 do
let { histo = new_dhisto } as new_dvar = new_dvars.(i - 1) in
let dsample = dvars.(i).samples.(sample_ix) in
new_dvar.samples.(new_sample_ix) <- dsample;
let dcnstr = fdsum_cnstr dsample in
new_dhisto.(dcnstr) <- new_dhisto.(dcnstr) + 1
done;
let new_cvars = split_cvars.(split_cnstr) in
for i = 0 to n_cvars_1 do
let { histo = new_chisto } as new_cvar = new_cvars.(i) in
let csample = cvars.(i).samples.(sample_ix) in
new_cvar.samples.(new_sample_ix) <- csample;
let ccnstr = fdsum_cnstr csample in
new_chisto.(ccnstr) <- new_chisto.(ccnstr) + 1
done
| FDStrct (split_cnstr, subs) ->
let new_sample_ix = split_ixs.(split_cnstr) in
split_ixs.(split_cnstr) <- new_sample_ix + 1;
let new_dvars = split_dvars.(split_cnstr) in
let n_dsubs = Array.length subs in
for i = 0 to dvar_ix - 1 do
let { histo = new_dhisto } as new_dvar = new_dvars.(i) in
let dsample = dvars.(i).samples.(sample_ix) in
new_dvar.samples.(new_sample_ix) <- dsample;
let dcnstr = fdsum_cnstr dsample in
new_dhisto.(dcnstr) <- new_dhisto.(dcnstr) + 1
done;
let n_dsubs_1 = n_dsubs - 1 in
for i = 0 to n_dsubs_1 do
let { histo = new_dhisto } as new_dvar = new_dvars.(dvar_ix + i) in
let dsample = subs.(i) in
new_dvar.samples.(new_sample_ix) <- dsample;
let dcnstr = fdsum_cnstr dsample in
new_dhisto.(dcnstr) <- new_dhisto.(dcnstr) + 1
done;
for i = dvar_ix + 1 to n_dvars_1 do
let { histo = new_dhisto } as new_dvar = new_dvars.(i + n_dsubs_1) in
let dsample = dvars.(i).samples.(sample_ix) in
new_dvar.samples.(new_sample_ix) <- dsample;
let dcnstr = fdsum_cnstr dsample in
new_dhisto.(dcnstr) <- new_dhisto.(dcnstr) + 1
done;
let new_cvars = split_cvars.(split_cnstr) in
for i = 0 to n_cvars_1 do
let { histo = new_chisto } as new_cvar = new_cvars.(i) in
let csample = cvars.(i).samples.(sample_ix) in
new_cvar.samples.(new_sample_ix) <- csample;
let ccnstr = fdsum_cnstr csample in
new_chisto.(ccnstr) <- new_chisto.(ccnstr) + 1
done
done;
split_dom_ixs, split_ix_cnt, split_dvars, split_cvars
(* Compute sum-model from optional shave-info *)
let rec calc_sum_mod tp cnstr = function
| None -> FDAtom cnstr
| Some (_, ShInfo (pos_infos, vars)) ->
let sub_tps = cfspec.(tp).(cnstr) in
let subs = Array.make (Array.length sub_tps) dummy_fdsum in
let acti sub_ix (var_ix, subcnstr, sub_info) =
subs.(sub_ix) <- calc_sum_mod vars.(var_ix).tp subcnstr sub_info in
List.iteri acti pos_infos;
FDStrct (cnstr, subs)
(* Compute variable model from pos-infos *)
let rec var_mod_of_pos_info_loop cvars var_mods = function
| sh_ix, cnstr, None -> var_mods.(sh_ix) <- VarFree (FDAtom cnstr)
| sh_ix, cnstr, (Some (0, _) as sub_sh_info) ->
let sum_mod = calc_sum_mod cvars.(sh_ix).tp cnstr sub_sh_info in
var_mods.(sh_ix) <- VarFree sum_mod
| sh_ix, cnstr, Some (_, ShInfo (sub_infos, sub_vars)) ->
let sub_var_mods = Array.make (Array.length sub_vars) Var in
List.iter (var_mod_of_pos_info_loop sub_vars sub_var_mods) sub_infos;
var_mods.(sh_ix) <- make_strct_var_mods cnstr sub_var_mods
let var_mods_of_pos_infos cvars pos_infos =
let var_mods = Array.make (Array.length cvars) Var in
List.iter (var_mod_of_pos_info_loop cvars var_mods) pos_infos;
var_mods
(* Shave codomain variables with redundant constructors *)
let most_prob_cval cvars = Val (most_prob_csums cvars)
let cnt_some acc = function Some _ -> acc + 1 | _ -> acc
let rec blit_models_loop maybe_models models maybe_models_ix models_ix =
if models_ix >= 0 then
let new_maybe_models_ix = maybe_models_ix - 1 in
match maybe_models.(maybe_models_ix) with
| Some model ->
models.(models_ix) <- model;
blit_models_loop maybe_models models new_maybe_models_ix (models_ix - 1)
| None -> blit_models_loop maybe_models models new_maybe_models_ix models_ix
let factorized_shave sh_ix_ofs sh_cnstr model def_mod =
match factorize_models [| model; def_mod |] with
| FactorNone -> MatchMod (Shave (sh_ix_ofs, sh_cnstr, model, def_mod))
| FactorVal model -> model
| FactorLet (models, var_mods) ->
Let (Shave (sh_ix_ofs, sh_cnstr, models.(0), models.(1)), var_mods)
let rec calc_model dom_ixs ix_cnt dvars cvars =
let cshave_info, n_sh_cvars = calc_shave_info cfspec cvars in
match cshave_info with
| ShInfo ((sh_ix, cnstr, pos_infos) :: rest, cvars) when n_sh_cvars = 0 ->
let first_fdsum = calc_sum_mod cvars.(sh_ix).tp cnstr pos_infos in
let fdsums = Array.make (Array.length cvars) first_fdsum in
let rec loop value_ix = function
| [] -> Val fdsums
| (sh_ix, cnstr, sh_info) :: rest ->
fdsums.(value_ix) <- calc_sum_mod cvars.(sh_ix).tp cnstr sh_info;
loop (value_ix + 1) rest in
loop 1 rest
| ShInfo (pos_infos, cvars) ->
let dshave_info, n_sh_dvars = calc_shave_info dfspec dvars in
if n_sh_dvars = 0 then
let sh_cvars = vars_of_pos_infos n_sh_cvars cvars pos_infos in
let most_prob_sh_sums = most_prob_csums sh_cvars in
let var_mods = var_mods_of_pos_infos cvars pos_infos in
Val (subst_fdsums var_mods most_prob_sh_sums)
else
let new_dom_ixs, sh_dvars = dshave dom_ixs dshave_info n_sh_dvars in
if pos_infos = [] then make_match_mod new_dom_ixs ix_cnt sh_dvars cvars
else
let sh_cvars = vars_of_pos_infos n_sh_cvars cvars pos_infos in
match calc_match_mod new_dom_ixs ix_cnt sh_dvars sh_cvars with
| Some (Val sums) ->
Val (subst_fdsums (var_mods_of_pos_infos cvars pos_infos) sums)
| Some (Let (match_mod, inner_var_mods)) ->
let outer_var_mods = var_mods_of_pos_infos cvars pos_infos in
Let (match_mod, subst_var_mods outer_var_mods inner_var_mods)
| Some (MatchMod match_mod) ->
Let (match_mod, var_mods_of_pos_infos cvars pos_infos)
| None -> most_prob_cval cvars
and make_match_mod dom_ixs ix_cnt dvars cvars =
match calc_match_mod dom_ixs ix_cnt dvars cvars with
| Some model -> model
| None -> most_prob_cval cvars
and calc_match_mod dom_ixs ix_cnt dvars cvars =
match find_split dom_ixs dvars cvars with
| None as none -> none
| Some best_ix ->
match dom_ixs.(best_ix) with
| FinVar cnv_best_ix ->
Some (calc_split_mod dom_ixs ix_cnt dvars cvars best_ix cnv_best_ix)
| ShVar (shaved, last_ix) ->
let best_ix_1 = best_ix - 1 in
let best_ix1 = best_ix + 1 in
let inner_loop ix_cnt sh_ix sh_tp sh_cnstr =
let left_bnd = shave_lbound ix_cnt sh_ix dom_ixs best_ix_1 in
let right_bnd = shave_rbound ix_cnt sh_ix dom_ixs best_ix1 in
let new_ix_cnt = ix_cnt + Array.length dfspec.(sh_tp).(sh_cnstr) in
let def_mod =
if split_null_branches then
calc_def_mod dom_ixs ix_cnt dvars cvars left_bnd right_bnd
else most_prob_cval cvars in
new_ix_cnt, def_mod in
let rec loop ix_cnt ofs = function
| OneEl (sh_ix, sh_tp, sh_cnstr) ->
let sh_ix_ofs = sh_ix + ofs in
let new_ix_cnt, def_mod =
inner_loop ix_cnt sh_ix_ofs sh_tp sh_cnstr in
let split_mod =
calc_split_mod
dom_ixs new_ix_cnt dvars cvars best_ix (ix_cnt + last_ix) in
factorized_shave sh_ix_ofs sh_cnstr split_mod def_mod
| OneCons ((sh_ix, sh_tp, sh_cnstr), rest) ->
let sh_ix_ofs = sh_ix + ofs in
let new_ix_cnt, def_mod =
inner_loop ix_cnt sh_ix_ofs sh_tp sh_cnstr in
let model = loop new_ix_cnt ix_cnt rest in
factorized_shave sh_ix_ofs sh_cnstr model def_mod in
Some (loop ix_cnt 0 shaved)
and calc_split_mod dom_ixs ix_cnt dvars cvars best_ix cnv_best_ix =
let is_partial = ref false in
let split_dom_ixs, split_ix_cnt, split_dvars, split_cvars =
split dom_ixs ix_cnt dvars cvars best_ix in
let n_splits = Array.length split_dvars in
let maybe_models = Array.make n_splits None in
let n_splits_1 = n_splits - 1 in
for split_cnstr = 0 to n_splits_1 do
let new_cvars = split_cvars.(split_cnstr) in
if array_is_empty new_cvars.(0).samples then is_partial := true
else
let new_dvars = split_dvars.(split_cnstr) in
let new_dom_ixs = split_dom_ixs.(split_cnstr) in
let new_ix_cnt = split_ix_cnt.(split_cnstr) in
let model = calc_model new_dom_ixs new_ix_cnt new_dvars new_cvars in
maybe_models.(split_cnstr) <- Some model
done;
if !is_partial then (
let def_mod =
if split_null_branches then
calc_def_mod dom_ixs ix_cnt dvars cvars best_ix (best_ix + 1)
else most_prob_cval cvars in
let n_models = Array.fold_left cnt_some 1 maybe_models in
let models = Array.make n_models def_mod in
blit_models_loop maybe_models models n_splits_1 (n_models - 2);
match factorize_models models with
| FactorNone -> MatchMod (PSplit (cnv_best_ix, maybe_models, def_mod))
| FactorVal model -> model
| FactorLet (models, var_mods) ->
let match_mod =
let ix_ref = ref 0 in
let cnv = function
| None as maybe_model -> maybe_model
| Some _ ->
let ix = !ix_ref in
ix_ref := ix + 1;
Some models.(ix) in
let new_maybe_models = Array.map cnv maybe_models in
PSplit (cnv_best_ix, new_maybe_models, models.(n_splits_1)) in
Let (match_mod, var_mods))
else
let models = unlift_opts maybe_models in
match factorize_models models with
| FactorNone -> MatchMod (Split (cnv_best_ix, models))
| FactorVal model -> model
| FactorLet (models, var_mods) ->
Let (Split (cnv_best_ix, models), var_mods)
and calc_def_mod dom_ixs ix_cnt dvars cvars from upto =
let n_rest = Array.length dvars - upto in
let n_new_dvars = n_rest + from in
if n_new_dvars = 0 then most_prob_cval cvars
else (
let new_dvars = Array.make n_new_dvars dvars.(0) in
let new_dom_ixs = Array.make n_new_dvars dom_ixs.(0) in
let from_1 = max (from - 1) 0 in
Array.blit dvars 1 new_dvars 1 from_1;
Array.blit dom_ixs 1 new_dom_ixs 1 from_1;
Array.blit dvars upto new_dvars from n_rest;
Array.blit dom_ixs upto new_dom_ixs from n_rest;
make_match_mod new_dom_ixs ix_cnt new_dvars cvars)
(* Derive a model from domain and codomain variables *)
let derive_model dvars cvars =
if array_is_empty cvars then failwith "derive_model: no codomain variables";
if array_is_empty cvars.(0).samples then
failwith "derive_model: no samples";
let n_dvars = Array.length dvars in
calc_model (dom_ixs_iota n_dvars) n_dvars dvars cvars
end
| null | https://raw.githubusercontent.com/mmottl/aifad/b06786f5cd60992548405078a903ee3d962ea969/src/split_impl.ml | ocaml | Split (co-)domain variables on some domain variable
(left, X (x, y), right) -> (left, x, y, right)
Compute sum-model from optional shave-info
Compute variable model from pos-infos
Shave codomain variables with redundant constructors
Derive a model from domain and codomain variables |
AIFAD - Automated Induction of Functions over
Author :
email :
WWW :
Copyright ( C ) 2002 Austrian Research Institute for Artificial Intelligence
Copyright ( C ) 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.1 of the License , or ( at your option ) any later version .
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. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 USA
AIFAD - Automated Induction of Functions over Algebraic Datatypes
Author: Markus Mottl
email:
WWW:
Copyright (C) 2002 Austrian Research Institute for Artificial Intelligence
Copyright (C) 2003- Markus Mottl
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*)
open Utils
open Algdt_types
open Algdt_utils
open Model_types
open Model_utils
open Factor
open Dshave
module Make (Spec : Split_intf.SPEC) = struct
open Spec
let split dom_ixs ix_cnt dvars cvars dvar_ix =
let n_dvars_1 = Array.length dvars - 1 in
let n_cvars_1 = Array.length cvars - 1 in
let { samples = dsamples; tp = dtp; histo = dhisto } = dvars.(dvar_ix) in
let subs_tps = dfspec.(dtp) in
let n_splits = Array.length dhisto in
let split_dvars = Array.make n_splits [||] in
let split_cvars = Array.make n_splits [||] in
let split_dom_ixs = Array.make n_splits [||] in
let split_ix_cnt = Array.make n_splits ix_cnt in
for split_cnstr = 0 to n_splits - 1 do
let freq = dhisto.(split_cnstr) in
let sub_tps = subs_tps.(split_cnstr) in
let n_dsubs = Array.length sub_tps in
let n_new_dvars = n_dvars_1 + n_dsubs in
let new_dvars = Array.make n_new_dvars dummy_var in
let new_dom_ixs = Array.make n_new_dvars dummy_sh_el in
for i = 0 to dvar_ix - 1 do
let cur_dvar = dvars.(i) in
new_dvars.(i) <-
{
samples = Array.make freq dummy_fdsum;
tp = cur_dvar.tp;
histo = Array.make (Array.length cur_dvar.histo) 0;
}
done;
Array.blit dom_ixs 0 new_dom_ixs 0 dvar_ix;
let n_dsubs_1 = n_dsubs - 1 in
for i = 0 to n_dsubs_1 do
let tp = sub_tps.(i) in
let ofs = dvar_ix + i in
new_dvars.(ofs) <-
{
samples = Array.make freq dummy_fdsum;
tp = tp;
histo = Array.make (Array.length dfspec.(tp)) 0;
};
new_dom_ixs.(ofs) <- FinVar (ix_cnt + i)
done;
let dvar_ix1 = dvar_ix + 1 in
for i = dvar_ix1 to n_dvars_1 do
let cur_dvar = dvars.(i) in
new_dvars.(i + n_dsubs_1) <-
{
samples = Array.make freq dummy_fdsum;
tp = cur_dvar.tp;
histo = Array.make (Array.length cur_dvar.histo) 0;
}
done;
let n_last = n_dvars_1 - dvar_ix in
Array.blit dom_ixs dvar_ix1 new_dom_ixs (dvar_ix + n_dsubs) n_last;
split_dvars.(split_cnstr) <- new_dvars;
split_dom_ixs.(split_cnstr) <- new_dom_ixs;
split_ix_cnt.(split_cnstr) <- ix_cnt + n_dsubs;
let make_new_cvar cvar =
{
samples = Array.make freq dummy_fdsum;
tp = cvar.tp;
histo = Array.make (Array.length cvar.histo) 0;
} in
split_cvars.(split_cnstr) <- Array.map make_new_cvar cvars
done;
let split_ixs = Array.make n_splits 0 in
for sample_ix = 0 to Array.length dsamples - 1 do
match dsamples.(sample_ix) with
| FDAtom split_cnstr ->
let new_sample_ix = split_ixs.(split_cnstr) in
split_ixs.(split_cnstr) <- new_sample_ix + 1;
let new_dvars = split_dvars.(split_cnstr) in
for i = 0 to dvar_ix - 1 do
let { histo = new_dhisto } as new_dvar = new_dvars.(i) in
let dsample = dvars.(i).samples.(sample_ix) in
new_dvar.samples.(new_sample_ix) <- dsample;
let dcnstr = fdsum_cnstr dsample in
new_dhisto.(dcnstr) <- new_dhisto.(dcnstr) + 1
done;
for i = dvar_ix + 1 to n_dvars_1 do
let { histo = new_dhisto } as new_dvar = new_dvars.(i - 1) in
let dsample = dvars.(i).samples.(sample_ix) in
new_dvar.samples.(new_sample_ix) <- dsample;
let dcnstr = fdsum_cnstr dsample in
new_dhisto.(dcnstr) <- new_dhisto.(dcnstr) + 1
done;
let new_cvars = split_cvars.(split_cnstr) in
for i = 0 to n_cvars_1 do
let { histo = new_chisto } as new_cvar = new_cvars.(i) in
let csample = cvars.(i).samples.(sample_ix) in
new_cvar.samples.(new_sample_ix) <- csample;
let ccnstr = fdsum_cnstr csample in
new_chisto.(ccnstr) <- new_chisto.(ccnstr) + 1
done
| FDStrct (split_cnstr, subs) ->
let new_sample_ix = split_ixs.(split_cnstr) in
split_ixs.(split_cnstr) <- new_sample_ix + 1;
let new_dvars = split_dvars.(split_cnstr) in
let n_dsubs = Array.length subs in
for i = 0 to dvar_ix - 1 do
let { histo = new_dhisto } as new_dvar = new_dvars.(i) in
let dsample = dvars.(i).samples.(sample_ix) in
new_dvar.samples.(new_sample_ix) <- dsample;
let dcnstr = fdsum_cnstr dsample in
new_dhisto.(dcnstr) <- new_dhisto.(dcnstr) + 1
done;
let n_dsubs_1 = n_dsubs - 1 in
for i = 0 to n_dsubs_1 do
let { histo = new_dhisto } as new_dvar = new_dvars.(dvar_ix + i) in
let dsample = subs.(i) in
new_dvar.samples.(new_sample_ix) <- dsample;
let dcnstr = fdsum_cnstr dsample in
new_dhisto.(dcnstr) <- new_dhisto.(dcnstr) + 1
done;
for i = dvar_ix + 1 to n_dvars_1 do
let { histo = new_dhisto } as new_dvar = new_dvars.(i + n_dsubs_1) in
let dsample = dvars.(i).samples.(sample_ix) in
new_dvar.samples.(new_sample_ix) <- dsample;
let dcnstr = fdsum_cnstr dsample in
new_dhisto.(dcnstr) <- new_dhisto.(dcnstr) + 1
done;
let new_cvars = split_cvars.(split_cnstr) in
for i = 0 to n_cvars_1 do
let { histo = new_chisto } as new_cvar = new_cvars.(i) in
let csample = cvars.(i).samples.(sample_ix) in
new_cvar.samples.(new_sample_ix) <- csample;
let ccnstr = fdsum_cnstr csample in
new_chisto.(ccnstr) <- new_chisto.(ccnstr) + 1
done
done;
split_dom_ixs, split_ix_cnt, split_dvars, split_cvars
let rec calc_sum_mod tp cnstr = function
| None -> FDAtom cnstr
| Some (_, ShInfo (pos_infos, vars)) ->
let sub_tps = cfspec.(tp).(cnstr) in
let subs = Array.make (Array.length sub_tps) dummy_fdsum in
let acti sub_ix (var_ix, subcnstr, sub_info) =
subs.(sub_ix) <- calc_sum_mod vars.(var_ix).tp subcnstr sub_info in
List.iteri acti pos_infos;
FDStrct (cnstr, subs)
let rec var_mod_of_pos_info_loop cvars var_mods = function
| sh_ix, cnstr, None -> var_mods.(sh_ix) <- VarFree (FDAtom cnstr)
| sh_ix, cnstr, (Some (0, _) as sub_sh_info) ->
let sum_mod = calc_sum_mod cvars.(sh_ix).tp cnstr sub_sh_info in
var_mods.(sh_ix) <- VarFree sum_mod
| sh_ix, cnstr, Some (_, ShInfo (sub_infos, sub_vars)) ->
let sub_var_mods = Array.make (Array.length sub_vars) Var in
List.iter (var_mod_of_pos_info_loop sub_vars sub_var_mods) sub_infos;
var_mods.(sh_ix) <- make_strct_var_mods cnstr sub_var_mods
let var_mods_of_pos_infos cvars pos_infos =
let var_mods = Array.make (Array.length cvars) Var in
List.iter (var_mod_of_pos_info_loop cvars var_mods) pos_infos;
var_mods
let most_prob_cval cvars = Val (most_prob_csums cvars)
let cnt_some acc = function Some _ -> acc + 1 | _ -> acc
let rec blit_models_loop maybe_models models maybe_models_ix models_ix =
if models_ix >= 0 then
let new_maybe_models_ix = maybe_models_ix - 1 in
match maybe_models.(maybe_models_ix) with
| Some model ->
models.(models_ix) <- model;
blit_models_loop maybe_models models new_maybe_models_ix (models_ix - 1)
| None -> blit_models_loop maybe_models models new_maybe_models_ix models_ix
let factorized_shave sh_ix_ofs sh_cnstr model def_mod =
match factorize_models [| model; def_mod |] with
| FactorNone -> MatchMod (Shave (sh_ix_ofs, sh_cnstr, model, def_mod))
| FactorVal model -> model
| FactorLet (models, var_mods) ->
Let (Shave (sh_ix_ofs, sh_cnstr, models.(0), models.(1)), var_mods)
let rec calc_model dom_ixs ix_cnt dvars cvars =
let cshave_info, n_sh_cvars = calc_shave_info cfspec cvars in
match cshave_info with
| ShInfo ((sh_ix, cnstr, pos_infos) :: rest, cvars) when n_sh_cvars = 0 ->
let first_fdsum = calc_sum_mod cvars.(sh_ix).tp cnstr pos_infos in
let fdsums = Array.make (Array.length cvars) first_fdsum in
let rec loop value_ix = function
| [] -> Val fdsums
| (sh_ix, cnstr, sh_info) :: rest ->
fdsums.(value_ix) <- calc_sum_mod cvars.(sh_ix).tp cnstr sh_info;
loop (value_ix + 1) rest in
loop 1 rest
| ShInfo (pos_infos, cvars) ->
let dshave_info, n_sh_dvars = calc_shave_info dfspec dvars in
if n_sh_dvars = 0 then
let sh_cvars = vars_of_pos_infos n_sh_cvars cvars pos_infos in
let most_prob_sh_sums = most_prob_csums sh_cvars in
let var_mods = var_mods_of_pos_infos cvars pos_infos in
Val (subst_fdsums var_mods most_prob_sh_sums)
else
let new_dom_ixs, sh_dvars = dshave dom_ixs dshave_info n_sh_dvars in
if pos_infos = [] then make_match_mod new_dom_ixs ix_cnt sh_dvars cvars
else
let sh_cvars = vars_of_pos_infos n_sh_cvars cvars pos_infos in
match calc_match_mod new_dom_ixs ix_cnt sh_dvars sh_cvars with
| Some (Val sums) ->
Val (subst_fdsums (var_mods_of_pos_infos cvars pos_infos) sums)
| Some (Let (match_mod, inner_var_mods)) ->
let outer_var_mods = var_mods_of_pos_infos cvars pos_infos in
Let (match_mod, subst_var_mods outer_var_mods inner_var_mods)
| Some (MatchMod match_mod) ->
Let (match_mod, var_mods_of_pos_infos cvars pos_infos)
| None -> most_prob_cval cvars
and make_match_mod dom_ixs ix_cnt dvars cvars =
match calc_match_mod dom_ixs ix_cnt dvars cvars with
| Some model -> model
| None -> most_prob_cval cvars
and calc_match_mod dom_ixs ix_cnt dvars cvars =
match find_split dom_ixs dvars cvars with
| None as none -> none
| Some best_ix ->
match dom_ixs.(best_ix) with
| FinVar cnv_best_ix ->
Some (calc_split_mod dom_ixs ix_cnt dvars cvars best_ix cnv_best_ix)
| ShVar (shaved, last_ix) ->
let best_ix_1 = best_ix - 1 in
let best_ix1 = best_ix + 1 in
let inner_loop ix_cnt sh_ix sh_tp sh_cnstr =
let left_bnd = shave_lbound ix_cnt sh_ix dom_ixs best_ix_1 in
let right_bnd = shave_rbound ix_cnt sh_ix dom_ixs best_ix1 in
let new_ix_cnt = ix_cnt + Array.length dfspec.(sh_tp).(sh_cnstr) in
let def_mod =
if split_null_branches then
calc_def_mod dom_ixs ix_cnt dvars cvars left_bnd right_bnd
else most_prob_cval cvars in
new_ix_cnt, def_mod in
let rec loop ix_cnt ofs = function
| OneEl (sh_ix, sh_tp, sh_cnstr) ->
let sh_ix_ofs = sh_ix + ofs in
let new_ix_cnt, def_mod =
inner_loop ix_cnt sh_ix_ofs sh_tp sh_cnstr in
let split_mod =
calc_split_mod
dom_ixs new_ix_cnt dvars cvars best_ix (ix_cnt + last_ix) in
factorized_shave sh_ix_ofs sh_cnstr split_mod def_mod
| OneCons ((sh_ix, sh_tp, sh_cnstr), rest) ->
let sh_ix_ofs = sh_ix + ofs in
let new_ix_cnt, def_mod =
inner_loop ix_cnt sh_ix_ofs sh_tp sh_cnstr in
let model = loop new_ix_cnt ix_cnt rest in
factorized_shave sh_ix_ofs sh_cnstr model def_mod in
Some (loop ix_cnt 0 shaved)
and calc_split_mod dom_ixs ix_cnt dvars cvars best_ix cnv_best_ix =
let is_partial = ref false in
let split_dom_ixs, split_ix_cnt, split_dvars, split_cvars =
split dom_ixs ix_cnt dvars cvars best_ix in
let n_splits = Array.length split_dvars in
let maybe_models = Array.make n_splits None in
let n_splits_1 = n_splits - 1 in
for split_cnstr = 0 to n_splits_1 do
let new_cvars = split_cvars.(split_cnstr) in
if array_is_empty new_cvars.(0).samples then is_partial := true
else
let new_dvars = split_dvars.(split_cnstr) in
let new_dom_ixs = split_dom_ixs.(split_cnstr) in
let new_ix_cnt = split_ix_cnt.(split_cnstr) in
let model = calc_model new_dom_ixs new_ix_cnt new_dvars new_cvars in
maybe_models.(split_cnstr) <- Some model
done;
if !is_partial then (
let def_mod =
if split_null_branches then
calc_def_mod dom_ixs ix_cnt dvars cvars best_ix (best_ix + 1)
else most_prob_cval cvars in
let n_models = Array.fold_left cnt_some 1 maybe_models in
let models = Array.make n_models def_mod in
blit_models_loop maybe_models models n_splits_1 (n_models - 2);
match factorize_models models with
| FactorNone -> MatchMod (PSplit (cnv_best_ix, maybe_models, def_mod))
| FactorVal model -> model
| FactorLet (models, var_mods) ->
let match_mod =
let ix_ref = ref 0 in
let cnv = function
| None as maybe_model -> maybe_model
| Some _ ->
let ix = !ix_ref in
ix_ref := ix + 1;
Some models.(ix) in
let new_maybe_models = Array.map cnv maybe_models in
PSplit (cnv_best_ix, new_maybe_models, models.(n_splits_1)) in
Let (match_mod, var_mods))
else
let models = unlift_opts maybe_models in
match factorize_models models with
| FactorNone -> MatchMod (Split (cnv_best_ix, models))
| FactorVal model -> model
| FactorLet (models, var_mods) ->
Let (Split (cnv_best_ix, models), var_mods)
and calc_def_mod dom_ixs ix_cnt dvars cvars from upto =
let n_rest = Array.length dvars - upto in
let n_new_dvars = n_rest + from in
if n_new_dvars = 0 then most_prob_cval cvars
else (
let new_dvars = Array.make n_new_dvars dvars.(0) in
let new_dom_ixs = Array.make n_new_dvars dom_ixs.(0) in
let from_1 = max (from - 1) 0 in
Array.blit dvars 1 new_dvars 1 from_1;
Array.blit dom_ixs 1 new_dom_ixs 1 from_1;
Array.blit dvars upto new_dvars from n_rest;
Array.blit dom_ixs upto new_dom_ixs from n_rest;
make_match_mod new_dom_ixs ix_cnt new_dvars cvars)
let derive_model dvars cvars =
if array_is_empty cvars then failwith "derive_model: no codomain variables";
if array_is_empty cvars.(0).samples then
failwith "derive_model: no samples";
let n_dvars = Array.length dvars in
calc_model (dom_ixs_iota n_dvars) n_dvars dvars cvars
end
|
7bf901a3a576895ce791c5e7686a971d809fa68a9b08344d7490d5f0c6f9ea9d | hraberg/shen.clj | install.clj | (ns shen.install
(:use [clojure.java.io :only (file reader writer)]
[clojure.pprint :only (pprint)])
(:require [clojure.string :as s]
[shen.primitives])
(:import [java.io StringReader PushbackReader FileNotFoundException]
[java.util.regex Pattern])
(:gen-class))
(def shen-namespaces '[sys writer core prolog yacc declarations load macros reader
sequent toplevel track t-star types])
(def kl-dir (->> ["../../K Lambda" "shen/klambda"]
(map file) (filter #(.exists %)) first))
(def cleanup-symbols-pattern
(re-pattern (str "(\\s+|\\()("
(s/join "|" (map #(Pattern/quote %) [":" ";" "{" "}" ":-" ":="
"/." "@p" "@s" "@v"
"shen-@s-macro"
"shen-@v-help"
"shen-i/o-macro"
"shen-put/get-macro"
"XV/Y"]))
")(\\s*\\)|\\s+?)"
"(?!~)")))
(defn cleanup-symbols
[kl] (s/replace kl
cleanup-symbols-pattern
"$1(intern \"$2\")$3"))
(defn read-kl [kl]
(with-open [r (PushbackReader. (StringReader. (cleanup-symbols kl)))]
(doall
(take-while (complement nil?)
(repeatedly #(read r false nil))))))
(defn read-kl-file [file]
(try
(cons `(c/comment ~(str file)) (read-kl (slurp file)))
(catch Exception e
(println file e))))
(defn header [ns]
`(~'ns ~ns
(:use [shen.primitives])
(:require [clojure.core :as ~'c])
(:refer-clojure :only [])
(:gen-class)))
(def missing-declarations '#{shen-kl-to-lisp FORMAT READ-CHAR})
(defn declarations [clj]
(into missing-declarations
(map second (filter #(= 'defun (first %)) clj))))
(defn write-clj-file [dir name forms]
(with-open [w (writer (file dir (str name ".clj")))]
(binding [*out* w]
(doseq [f forms]
(pprint f)
(println)))))
(defn project-version []
(-> (slurp "project.clj") read-string (nth 2)))
(defn kl-to-clj
([] (kl-to-clj kl-dir
*compile-path*))
([dir to-dir]
(.mkdirs (file to-dir))
(let [shen (mapcat read-kl-file
(map #(file dir (str % ".kl")) shen-namespaces))
dcl (declarations shen)]
(write-clj-file to-dir "shen"
(concat [(header 'shen)]
[`(c/declare ~@(filter symbol? dcl))]
['(c/intern 'shen.globals (c/with-meta '*language* {:dynamic true}) "Clojure")]
[(concat '(c/intern 'shen.globals (c/with-meta '*port* {:dynamic true}))
[(project-version)])]
(map #(shen.primitives/shen-kl-to-clj %)
(remove string? shen))
['(c/load "shen/overwrite")]
['(c/defn -main [] (shen-shen))])))))
(defn install []
(try
(require 'shen)
(catch FileNotFoundException _
(println "Creating shen.clj")
(kl-to-clj))))
(defn swank [port]
(try
(require 'swank.swank)
(with-out-str
((resolve 'swank.swank/start-repl) port))
(println "Swank connection opened on" port)
(catch FileNotFoundException _)))
(defn -main []
(install)
(require 'shen)
(binding [*ns* (the-ns 'shen)]
(swank 4005)
((resolve 'shen/-main))))
(when *compile-files*
(install))
(defn repl? []
(->> (Thread/currentThread) .getStackTrace seq
(map str) (some (partial re-find #"clojure.main.repl"))))
(when (repl?)
(-main))
| null | https://raw.githubusercontent.com/hraberg/shen.clj/41bf09e61dd3a9df03cf929f0e8415087b730396/src/shen/install.clj | clojure | (ns shen.install
(:use [clojure.java.io :only (file reader writer)]
[clojure.pprint :only (pprint)])
(:require [clojure.string :as s]
[shen.primitives])
(:import [java.io StringReader PushbackReader FileNotFoundException]
[java.util.regex Pattern])
(:gen-class))
(def shen-namespaces '[sys writer core prolog yacc declarations load macros reader
sequent toplevel track t-star types])
(def kl-dir (->> ["../../K Lambda" "shen/klambda"]
(map file) (filter #(.exists %)) first))
(def cleanup-symbols-pattern
(re-pattern (str "(\\s+|\\()("
(s/join "|" (map #(Pattern/quote %) [":" ";" "{" "}" ":-" ":="
"/." "@p" "@s" "@v"
"shen-@s-macro"
"shen-@v-help"
"shen-i/o-macro"
"shen-put/get-macro"
"XV/Y"]))
")(\\s*\\)|\\s+?)"
"(?!~)")))
(defn cleanup-symbols
[kl] (s/replace kl
cleanup-symbols-pattern
"$1(intern \"$2\")$3"))
(defn read-kl [kl]
(with-open [r (PushbackReader. (StringReader. (cleanup-symbols kl)))]
(doall
(take-while (complement nil?)
(repeatedly #(read r false nil))))))
(defn read-kl-file [file]
(try
(cons `(c/comment ~(str file)) (read-kl (slurp file)))
(catch Exception e
(println file e))))
(defn header [ns]
`(~'ns ~ns
(:use [shen.primitives])
(:require [clojure.core :as ~'c])
(:refer-clojure :only [])
(:gen-class)))
(def missing-declarations '#{shen-kl-to-lisp FORMAT READ-CHAR})
(defn declarations [clj]
(into missing-declarations
(map second (filter #(= 'defun (first %)) clj))))
(defn write-clj-file [dir name forms]
(with-open [w (writer (file dir (str name ".clj")))]
(binding [*out* w]
(doseq [f forms]
(pprint f)
(println)))))
(defn project-version []
(-> (slurp "project.clj") read-string (nth 2)))
(defn kl-to-clj
([] (kl-to-clj kl-dir
*compile-path*))
([dir to-dir]
(.mkdirs (file to-dir))
(let [shen (mapcat read-kl-file
(map #(file dir (str % ".kl")) shen-namespaces))
dcl (declarations shen)]
(write-clj-file to-dir "shen"
(concat [(header 'shen)]
[`(c/declare ~@(filter symbol? dcl))]
['(c/intern 'shen.globals (c/with-meta '*language* {:dynamic true}) "Clojure")]
[(concat '(c/intern 'shen.globals (c/with-meta '*port* {:dynamic true}))
[(project-version)])]
(map #(shen.primitives/shen-kl-to-clj %)
(remove string? shen))
['(c/load "shen/overwrite")]
['(c/defn -main [] (shen-shen))])))))
(defn install []
(try
(require 'shen)
(catch FileNotFoundException _
(println "Creating shen.clj")
(kl-to-clj))))
(defn swank [port]
(try
(require 'swank.swank)
(with-out-str
((resolve 'swank.swank/start-repl) port))
(println "Swank connection opened on" port)
(catch FileNotFoundException _)))
(defn -main []
(install)
(require 'shen)
(binding [*ns* (the-ns 'shen)]
(swank 4005)
((resolve 'shen/-main))))
(when *compile-files*
(install))
(defn repl? []
(->> (Thread/currentThread) .getStackTrace seq
(map str) (some (partial re-find #"clojure.main.repl"))))
(when (repl?)
(-main))
| |
754b60dac7f74752ac1cc9b8a5d0b426d846c3ab1a154204fbd2422900b7ebe7 | oden-lang/oden | Instantiate.hs | module Oden.Output.Instantiate where
import Text.PrettyPrint.Leijen
import Oden.Compiler.Instantiate
import Oden.Output
import Oden.Pretty ()
instance OdenOutput InstantiateError where
outputType _ = Error
name TypeMismatch{} = "Instantiate.TypeMismatch"
name SubstitutionFailed{} = "Instantiate.SubstitutionFailed"
header TypeMismatch{} _ =
text "Type mismatch in instantiation"
header (SubstitutionFailed _ tvar _) s =
text "Substitution failed for type variable " <+> code s (pretty tvar)
details (TypeMismatch _ pt mt) s =
text "Polymorphic type" <+> code s (pretty pt)
<+> text "cannot be instantiated to" <+> code s (pretty mt)
details (SubstitutionFailed _ _ vars) s =
text "Type variables in context:" <+> hcat (map (code s . pretty) vars)
sourceInfo (TypeMismatch si _ _) = Just si
sourceInfo (SubstitutionFailed si _ _) = Just si
| null | https://raw.githubusercontent.com/oden-lang/oden/10c99b59c8b77c4db51ade9a4d8f9573db7f4d14/src/Oden/Output/Instantiate.hs | haskell | module Oden.Output.Instantiate where
import Text.PrettyPrint.Leijen
import Oden.Compiler.Instantiate
import Oden.Output
import Oden.Pretty ()
instance OdenOutput InstantiateError where
outputType _ = Error
name TypeMismatch{} = "Instantiate.TypeMismatch"
name SubstitutionFailed{} = "Instantiate.SubstitutionFailed"
header TypeMismatch{} _ =
text "Type mismatch in instantiation"
header (SubstitutionFailed _ tvar _) s =
text "Substitution failed for type variable " <+> code s (pretty tvar)
details (TypeMismatch _ pt mt) s =
text "Polymorphic type" <+> code s (pretty pt)
<+> text "cannot be instantiated to" <+> code s (pretty mt)
details (SubstitutionFailed _ _ vars) s =
text "Type variables in context:" <+> hcat (map (code s . pretty) vars)
sourceInfo (TypeMismatch si _ _) = Just si
sourceInfo (SubstitutionFailed si _ _) = Just si
| |
90fd16eaedcdde389910b555a93c0c5c3aa1cc6e67b2771074059f3354d612b1 | geostarling/guix-packages | clojure.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2019 < >
Copyright © 2020 < >
Copyright © 2020 < >
;;;
;;; This file is not part of GNU Guix.
;;;
GNU is free software ; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (nongnu packages clojure)
#:use-module (gnu packages compression)
#:use-module (gnu packages gcc)
#:use-module (gnu packages readline)
#:use-module (guix build-system copy)
#:use-module (guix build-system gnu)
#:use-module (guix build-system trivial)
#:use-module (guix download)
#:use-module (guix git-download)
#:use-module (guix packages)
#:use-module (nonguix build-system binary)
#:use-module ((guix licenses) #:prefix license:))
;; This is a hidden package, as it does not really serve a purpose on its own.
(define leiningen-jar
(package
(name "leiningen-jar")
(version "2.9.10")
(source (origin
(method url-fetch)
(uri "-f20d-4580-a277-e06b5eec3b6b")
(file-name "leiningen-standalone.jar")
(sha256
(base32
"1ja9q8lav83h5qhayjgc39f6yyvk1n5f6gfwznn561xm007m6a52"))))
(build-system trivial-build-system)
(arguments
`(#:modules ((guix build utils))
#:builder (begin
(use-modules (guix build utils))
(let ((source (assoc-ref %build-inputs "source"))
(jar-dir (string-append %output "/share/")))
(mkdir-p jar-dir)
(copy-file source
(string-append jar-dir "leiningen-standalone.jar"))))))
(home-page "")
(synopsis "Automate Clojure projects without setting your hair on fire")
(description "Leiningen is a Clojure tool with a focus on project
automation and declarative configuration. It gets out of your way and
lets you focus on your code.")
(license license:epl1.0)))
(define-public leiningen
(package
(inherit leiningen-jar)
(name "leiningen")
(version "2.9.10")
(source (origin
(method git-fetch)
(uri (git-reference
(url "")
(commit version)))
(file-name (git-file-name name version))
(sha256
(base32
"1hl62ykq7sckfpgg5l3wpzq5smh6s572xnadr988vpl97l2x1g4y"))))
(build-system gnu-build-system)
(arguments
`(#:tests? #f
#:phases (modify-phases %standard-phases
(delete 'configure)
(delete 'build)
(replace 'install
(lambda _
(let* ((lein-pkg (string-append (assoc-ref %build-inputs "source") "/bin/lein-pkg"))
(lein-jar (string-append (assoc-ref %build-inputs "leiningen-jar")
"/share/leiningen-standalone.jar"))
(bin-dir (string-append %output "/bin"))
(lein (string-append bin-dir "/lein")))
(mkdir-p bin-dir)
(copy-file lein-pkg lein)
(patch-shebang lein)
(chmod lein #o555)
(substitute* lein
(("LEIN_JAR=.*") (string-append "LEIN_JAR=" lein-jar)))
#t))))))
(inputs
`(("leiningen-jar" ,leiningen-jar)))))
(define-public clj-kondo
(package
(name "clj-kondo")
(version "2022.06.22")
(source (origin
(method url-fetch/zipbomb)
(uri (string-append
"-kondo/clj-kondo/releases/download/v"
version "/clj-kondo-" version "-linux-amd64.zip"))
(sha256
(base32
"057h48kf14pdnnyvgmbqkga1bspbr4ag22q2279s14c2c9bcinzz"))))
(build-system binary-build-system)
(arguments
`(#:patchelf-plan
'(("clj-kondo" ("gcc:lib" "zlib")))
#:install-plan
'(("clj-kondo" "/bin/"))
#:phases
(modify-phases %standard-phases
(add-after 'unpack 'chmod
(lambda _
(chmod "clj-kondo" #o755))))))
(native-inputs
`(("unzip" ,unzip)))
(inputs
`(("gcc:lib" ,gcc "lib")
("zlib" ,zlib)))
(supported-systems '("x86_64-linux"))
(home-page "-kondo/clj-kondo")
(synopsis "Linter for Clojure code")
(description "Clj-kondo performs static analysis on Clojure, ClojureScript
and EDN, without the need of a running REPL.")
(license license:epl1.0)))
| null | https://raw.githubusercontent.com/geostarling/guix-packages/c54114d9d228a6cd789cfecf4570db0dd0ab3f54/nongnu/packages/clojure.scm | scheme | GNU Guix --- Functional package management for GNU
This file is not part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
This is a hidden package, as it does not really serve a purpose on its own. | Copyright © 2019 < >
Copyright © 2020 < >
Copyright © 2020 < >
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 (nongnu packages clojure)
#:use-module (gnu packages compression)
#:use-module (gnu packages gcc)
#:use-module (gnu packages readline)
#:use-module (guix build-system copy)
#:use-module (guix build-system gnu)
#:use-module (guix build-system trivial)
#:use-module (guix download)
#:use-module (guix git-download)
#:use-module (guix packages)
#:use-module (nonguix build-system binary)
#:use-module ((guix licenses) #:prefix license:))
(define leiningen-jar
(package
(name "leiningen-jar")
(version "2.9.10")
(source (origin
(method url-fetch)
(uri "-f20d-4580-a277-e06b5eec3b6b")
(file-name "leiningen-standalone.jar")
(sha256
(base32
"1ja9q8lav83h5qhayjgc39f6yyvk1n5f6gfwznn561xm007m6a52"))))
(build-system trivial-build-system)
(arguments
`(#:modules ((guix build utils))
#:builder (begin
(use-modules (guix build utils))
(let ((source (assoc-ref %build-inputs "source"))
(jar-dir (string-append %output "/share/")))
(mkdir-p jar-dir)
(copy-file source
(string-append jar-dir "leiningen-standalone.jar"))))))
(home-page "")
(synopsis "Automate Clojure projects without setting your hair on fire")
(description "Leiningen is a Clojure tool with a focus on project
automation and declarative configuration. It gets out of your way and
lets you focus on your code.")
(license license:epl1.0)))
(define-public leiningen
(package
(inherit leiningen-jar)
(name "leiningen")
(version "2.9.10")
(source (origin
(method git-fetch)
(uri (git-reference
(url "")
(commit version)))
(file-name (git-file-name name version))
(sha256
(base32
"1hl62ykq7sckfpgg5l3wpzq5smh6s572xnadr988vpl97l2x1g4y"))))
(build-system gnu-build-system)
(arguments
`(#:tests? #f
#:phases (modify-phases %standard-phases
(delete 'configure)
(delete 'build)
(replace 'install
(lambda _
(let* ((lein-pkg (string-append (assoc-ref %build-inputs "source") "/bin/lein-pkg"))
(lein-jar (string-append (assoc-ref %build-inputs "leiningen-jar")
"/share/leiningen-standalone.jar"))
(bin-dir (string-append %output "/bin"))
(lein (string-append bin-dir "/lein")))
(mkdir-p bin-dir)
(copy-file lein-pkg lein)
(patch-shebang lein)
(chmod lein #o555)
(substitute* lein
(("LEIN_JAR=.*") (string-append "LEIN_JAR=" lein-jar)))
#t))))))
(inputs
`(("leiningen-jar" ,leiningen-jar)))))
(define-public clj-kondo
(package
(name "clj-kondo")
(version "2022.06.22")
(source (origin
(method url-fetch/zipbomb)
(uri (string-append
"-kondo/clj-kondo/releases/download/v"
version "/clj-kondo-" version "-linux-amd64.zip"))
(sha256
(base32
"057h48kf14pdnnyvgmbqkga1bspbr4ag22q2279s14c2c9bcinzz"))))
(build-system binary-build-system)
(arguments
`(#:patchelf-plan
'(("clj-kondo" ("gcc:lib" "zlib")))
#:install-plan
'(("clj-kondo" "/bin/"))
#:phases
(modify-phases %standard-phases
(add-after 'unpack 'chmod
(lambda _
(chmod "clj-kondo" #o755))))))
(native-inputs
`(("unzip" ,unzip)))
(inputs
`(("gcc:lib" ,gcc "lib")
("zlib" ,zlib)))
(supported-systems '("x86_64-linux"))
(home-page "-kondo/clj-kondo")
(synopsis "Linter for Clojure code")
(description "Clj-kondo performs static analysis on Clojure, ClojureScript
and EDN, without the need of a running REPL.")
(license license:epl1.0)))
|
5c67f959cc3f6c95e14330d1bb8463fe1cb9d4e9b97f38cce86a2aa5af1c7153 | emotiq/emotiq | custom-xml.lisp | -*- Mode : LISP ; Syntax : ANSI - Common - Lisp ; Base : 10 -*-
;; See the file LICENCE for licence information.
(in-package :sdle-store-xml)
(defstore-xml (obj structure-object stream)
(with-tag ("STRUCTURE-OBJECT" stream)
(princ-and-store "CLASS" (type-of obj) stream)
(xml-dump-type-object obj stream)))
(defrestore-xml (structure-object place)
(restore-xml-type-object place))
(defstore-xml (obj single-float stream)
(with-tag ("SINGLE-FLOAT" stream)
(princ-and-store "BITS" (sb-kernel::single-float-bits obj)
stream)))
(defrestore-xml (single-float stream)
(sb-kernel::make-single-float
(restore-first (get-child "BITS" stream))))
(defstore-xml (obj double-float stream)
(with-tag ("DOUBLE-FLOAT" stream)
(princ-and-store "HIGH-BITS" (sb-kernel::double-float-high-bits obj)
stream)
(princ-and-store "LOW-BITS" (sb-kernel::double-float-low-bits obj)
stream)))
(defrestore-xml (double-float stream)
(sb-kernel::make-double-float (restore-first (get-child "HIGH-BITS" stream))
(restore-first (get-child "LOW-BITS" stream))))
EOF | null | https://raw.githubusercontent.com/emotiq/emotiq/9af78023f670777895a3dac29a2bbe98e19b6249/src/sdle-store/sbcl/custom-xml.lisp | lisp | Syntax : ANSI - Common - Lisp ; Base : 10 -*-
See the file LICENCE for licence information. |
(in-package :sdle-store-xml)
(defstore-xml (obj structure-object stream)
(with-tag ("STRUCTURE-OBJECT" stream)
(princ-and-store "CLASS" (type-of obj) stream)
(xml-dump-type-object obj stream)))
(defrestore-xml (structure-object place)
(restore-xml-type-object place))
(defstore-xml (obj single-float stream)
(with-tag ("SINGLE-FLOAT" stream)
(princ-and-store "BITS" (sb-kernel::single-float-bits obj)
stream)))
(defrestore-xml (single-float stream)
(sb-kernel::make-single-float
(restore-first (get-child "BITS" stream))))
(defstore-xml (obj double-float stream)
(with-tag ("DOUBLE-FLOAT" stream)
(princ-and-store "HIGH-BITS" (sb-kernel::double-float-high-bits obj)
stream)
(princ-and-store "LOW-BITS" (sb-kernel::double-float-low-bits obj)
stream)))
(defrestore-xml (double-float stream)
(sb-kernel::make-double-float (restore-first (get-child "HIGH-BITS" stream))
(restore-first (get-child "LOW-BITS" stream))))
EOF |
9c31af217cebc2679006e024b844fecbea8cc18bd9670408fff9bea400e585cf | Clojure2D/clojure2d-examples | ray.clj | (ns rt4.the-next-week.ch05c.ray
(:require [fastmath.vector :as v]
[fastmath.core :as m]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(m/use-primitive-operators)
(defprotocol RayProto
(at [ray t]))
(defrecord Ray [origin direction ^double time]
RayProto
(at [_ t] (v/add origin (v/mult direction t))))
(defn ray
([m] (map->Ray (merge {:time 0.0} m)))
([origin direction] (->Ray origin direction 0.0))
([origin direction time] (->Ray origin direction time)))
| null | https://raw.githubusercontent.com/Clojure2D/clojure2d-examples/ead92d6f17744b91070e6308157364ad4eab8a1b/src/rt4/the_next_week/ch05c/ray.clj | clojure | (ns rt4.the-next-week.ch05c.ray
(:require [fastmath.vector :as v]
[fastmath.core :as m]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(m/use-primitive-operators)
(defprotocol RayProto
(at [ray t]))
(defrecord Ray [origin direction ^double time]
RayProto
(at [_ t] (v/add origin (v/mult direction t))))
(defn ray
([m] (map->Ray (merge {:time 0.0} m)))
([origin direction] (->Ray origin direction 0.0))
([origin direction time] (->Ray origin direction time)))
| |
d1c14ad3908301cc1ca857b790d4f9f3957788a1580baaa21ae157e5f8f2d4ee | composewell/streamly | Char.hs | # OPTIONS_GHC -Wno - deprecations -Wno - orphans #
--
Module : Streamly . Unicode .
Copyright : ( c ) 2021 Composewell Technologies
-- License : BSD-3-Clause
-- Maintainer :
-- Stability : experimental
Portability : GHC
--------------------------------------------------------------------------------
-- Imports
--------------------------------------------------------------------------------
import Control.DeepSeq (NFData(..))
import Streamly.Internal.Data.Array (Array)
import System.FilePath (dropExtensions, takeFileName)
import System.FilePath.Posix ((</>))
import Gauge.Main (Benchmark, bench, bgroup, defaultMain, env, nfIO)
import Streamly.Internal.Unicode.Char
( NormalizationMode(NFC, NFD, NFKC, NFKD)
, normalize
)
import Streamly.Benchmark.Common (o_1_space_prefix)
import qualified Streamly.Internal.Data.Array as Array
import qualified Streamly.Internal.Data.Stream.StreamD as IsStream
import qualified System.Directory as Dir
--------------------------------------------------------------------------------
Utilities
--------------------------------------------------------------------------------
moduleName :: String
moduleName = "Unicode.Char"
dataDir :: FilePath
dataDir = "benchmark/Streamly/Benchmark/Unicode/data"
Truncate or expand all datasets to this size to provide a normalized
-- measurement view across all datasets and to reduce the effect of noise
-- because of the datasets being too small.
dataSetSize :: Int
dataSetSize = 1000000
Unboxed arrays are fully evaluated .
instance NFData (Array a) where
# INLINE rnf #
rnf _ = ()
makeBench ::
(String, Array Char -> IO ()) -> (String, IO (Array Char)) -> Benchmark
makeBench (implName, func) (dataName, setup) =
env setup (bench (implName ++ "/" ++ dataName) . nfIO . func)
strInput :: FilePath -> (String, IO String)
strInput file = (dataName file, fmap (take dataSetSize . cycle) (readFile file))
where
dataName = dropExtensions . takeFileName
arrInput :: FilePath -> (String, IO (Array Char))
arrInput file = second (fmap Array.fromList) (strInput file)
where
second f (a, b) = (a, f b)
--------------------------------------------------------------------------------
-- Benchmarks
--------------------------------------------------------------------------------
benchFunctions :: [(String, Array Char -> IO ())]
benchFunctions =
[ ("NFD", IsStream.drain . normalize NFD . Array.read)
, ("NFKD", IsStream.drain . normalize NFKD . Array.read)
, ("NFC", IsStream.drain . normalize NFC . Array.read)
, ("NFKC", IsStream.drain . normalize NFKC . Array.read)
]
main :: IO ()
main = do
cdir <- Dir.getCurrentDirectory
dataFiles <- fmap (dataDir </>) <$> Dir.listDirectory (cdir </> dataDir)
defaultMain
[ bgroup
(o_1_space_prefix moduleName)
(makeBench <$> benchFunctions <*> map arrInput dataFiles)
]
| null | https://raw.githubusercontent.com/composewell/streamly/8629a0e806f5eea87d23650c540aa04176f25c43/benchmark/Streamly/Benchmark/Unicode/Char.hs | haskell |
License : BSD-3-Clause
Maintainer :
Stability : experimental
------------------------------------------------------------------------------
Imports
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
measurement view across all datasets and to reduce the effect of noise
because of the datasets being too small.
------------------------------------------------------------------------------
Benchmarks
------------------------------------------------------------------------------ | # OPTIONS_GHC -Wno - deprecations -Wno - orphans #
Module : Streamly . Unicode .
Copyright : ( c ) 2021 Composewell Technologies
Portability : GHC
import Control.DeepSeq (NFData(..))
import Streamly.Internal.Data.Array (Array)
import System.FilePath (dropExtensions, takeFileName)
import System.FilePath.Posix ((</>))
import Gauge.Main (Benchmark, bench, bgroup, defaultMain, env, nfIO)
import Streamly.Internal.Unicode.Char
( NormalizationMode(NFC, NFD, NFKC, NFKD)
, normalize
)
import Streamly.Benchmark.Common (o_1_space_prefix)
import qualified Streamly.Internal.Data.Array as Array
import qualified Streamly.Internal.Data.Stream.StreamD as IsStream
import qualified System.Directory as Dir
Utilities
moduleName :: String
moduleName = "Unicode.Char"
dataDir :: FilePath
dataDir = "benchmark/Streamly/Benchmark/Unicode/data"
Truncate or expand all datasets to this size to provide a normalized
dataSetSize :: Int
dataSetSize = 1000000
Unboxed arrays are fully evaluated .
instance NFData (Array a) where
# INLINE rnf #
rnf _ = ()
makeBench ::
(String, Array Char -> IO ()) -> (String, IO (Array Char)) -> Benchmark
makeBench (implName, func) (dataName, setup) =
env setup (bench (implName ++ "/" ++ dataName) . nfIO . func)
strInput :: FilePath -> (String, IO String)
strInput file = (dataName file, fmap (take dataSetSize . cycle) (readFile file))
where
dataName = dropExtensions . takeFileName
arrInput :: FilePath -> (String, IO (Array Char))
arrInput file = second (fmap Array.fromList) (strInput file)
where
second f (a, b) = (a, f b)
benchFunctions :: [(String, Array Char -> IO ())]
benchFunctions =
[ ("NFD", IsStream.drain . normalize NFD . Array.read)
, ("NFKD", IsStream.drain . normalize NFKD . Array.read)
, ("NFC", IsStream.drain . normalize NFC . Array.read)
, ("NFKC", IsStream.drain . normalize NFKC . Array.read)
]
main :: IO ()
main = do
cdir <- Dir.getCurrentDirectory
dataFiles <- fmap (dataDir </>) <$> Dir.listDirectory (cdir </> dataDir)
defaultMain
[ bgroup
(o_1_space_prefix moduleName)
(makeBench <$> benchFunctions <*> map arrInput dataFiles)
]
|
84d8318b7e77eec0720998ab94f02fdd520fd6639b5ce7c33c48ce97459c14fc | uim/uim | wnn-key-custom.scm | ;;; wnn-custom.scm: Customization variables for wnn.scm
;;;
Copyright ( c ) 2003 - 2013 uim Project
;;;
;;; All rights reserved.
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
1 . Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
2 . Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
3 . Neither the name of authors nor the names of its contributors
;;; may be used to endorse or promote products derived from this software
;;; without specific prior written permission.
;;;
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ` ` AS IS '' AND
;;; ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR LIABLE
FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
;;; OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT
;;; LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
;;; OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
;;; SUCH DAMAGE.
;;;;
(require "i18n.scm")
(define-custom-group 'wnn-keys1
(N_ "Wnn key bindings 1")
(N_ "long description will be here."))
(define-custom-group 'wnn-keys2
(N_ "Wnn key bindings 2")
(N_ "long description will be here."))
(define-custom-group 'wnn-keys3
(N_ "Wnn key bindings 3")
(N_ "long description will be here."))
(define-custom-group 'wnn-keys4
(N_ "Wnn key bindings 4")
(N_ "long description will be here."))
(define-custom 'wnn-next-segment-key '(generic-go-right-key)
'(wnn-keys1)
'(key)
(N_ "[Wnn] next segment")
(N_ "long description will be here"))
(define-custom 'wnn-prev-segment-key '(generic-go-left-key)
'(wnn-keys1)
'(key)
(N_ "[Wnn] previous segment")
(N_ "long description will be here"))
(define-custom 'wnn-extend-segment-key '("<IgnoreCase><Control>o" "<Shift>right")
'(wnn-keys1)
'(key)
(N_ "[Wnn] extend segment")
(N_ "long description will be here"))
(define-custom 'wnn-shrink-segment-key '("<IgnoreCase><Control>i" "<Shift>left")
'(wnn-keys1)
'(key)
(N_ "[Wnn] shrink segment")
(N_ "long description will be here"))
(define-custom 'wnn-transpose-as-hiragana-key '("F6" "Muhenkan")
'(wnn-keys1)
'(key)
(N_ "[Wnn] convert to hiragana")
(N_ "long description will be here"))
(define-custom 'wnn-transpose-as-katakana-key '("F7" "Muhenkan")
'(wnn-keys1)
'(key)
(N_ "[Wnn] convert to katakana")
(N_ "long description will be here"))
(define-custom 'wnn-transpose-as-halfkana-key '("F8" "Muhenkan")
'(wnn-keys1)
'(key)
(N_ "[Wnn] convert to halfwidth katakana")
(N_ "long description will be here"))
(define-custom 'wnn-transpose-as-halfwidth-alnum-key '("F10")
'(wnn-keys1)
'(key)
(N_ "[Wnn] convert to halfwidth alphanumeric")
(N_ "long description will be here"))
(define-custom 'wnn-transpose-as-fullwidth-alnum-key '("F9")
'(wnn-keys1)
'(key)
(N_ "[Wnn] convert to fullwidth alphanumeric")
(N_ "long description will be here"))
(define-custom 'wnn-commit-as-opposite-kana-key '("<IgnoreCase><Shift>q") ;; "Q"
'(wnn-keys1)
'(key)
(N_ "[Wnn] commit as transposed kana")
(N_ "long description will be here"))
;;
;; overriding generic keys
;;
(define-custom 'wnn-on-key '("<Control>\\" generic-on-key)
'(wnn-keys2)
'(key)
(N_ "[Wnn] on")
(N_ "long description will be here"))
;;(define-custom 'wnn-off-key '("l" generic-on-key)
(define-custom 'wnn-off-key '("<Control>\\" generic-off-key)
'(wnn-keys2)
'(key)
(N_ "[Wnn] off")
(N_ "long description will be here"))
(define-custom 'wnn-begin-conv-key '(generic-begin-conv-key)
'(wnn-keys2)
'(key)
(N_ "[Wnn] begin conversion")
(N_ "long description will be here"))
(define-custom 'wnn-commit-key '(generic-commit-key)
'(wnn-keys2)
'(key)
(N_ "[Wnn] commit")
(N_ "long description will be here"))
(define-custom 'wnn-cancel-key '(generic-cancel-key)
'(wnn-keys2)
'(key)
(N_ "[Wnn] cancel")
(N_ "long description will be here"))
(define-custom 'wnn-next-candidate-key '(generic-next-candidate-key)
'(wnn-keys2)
'(key)
(N_ "[Wnn] next candidate")
(N_ "long description will be here"))
(define-custom 'wnn-prev-candidate-key '(generic-prev-candidate-key)
'(wnn-keys2)
'(key)
(N_ "[Wnn] previous candidate")
(N_ "long description will be here"))
(define-custom 'wnn-next-page-key '(generic-next-page-key)
'(wnn-keys2)
'(key)
(N_ "[Wnn] next page of candidate window")
(N_ "long description will be here"))
(define-custom 'wnn-prev-page-key '(generic-prev-page-key)
'(wnn-keys2)
'(key)
(N_ "[Wnn] previous page of candidate window")
(N_ "long description will be here"))
;;
;; overriding generic keys (advanced)
;;
(define-custom 'wnn-beginning-of-preedit-key '(generic-beginning-of-preedit-key)
'(wnn-keys3)
'(key)
(N_ "[Wnn] beginning of preedit")
(N_ "long description will be here"))
(define-custom 'wnn-end-of-preedit-key '(generic-end-of-preedit-key)
'(wnn-keys3)
'(key)
(N_ "[Wnn] end of preedit")
(N_ "long description will be here"))
(define-custom 'wnn-kill-key '(generic-kill-key)
'(wnn-keys3)
'(key)
(N_ "[Wnn] erase after cursor")
(N_ "long description will be here"))
(define-custom 'wnn-kill-backward-key '(generic-kill-backward-key)
'(wnn-keys3)
'(key)
(N_ "[Wnn] erase before cursor")
(N_ "long description will be here"))
(define-custom 'wnn-backspace-key '(generic-backspace-key)
'(wnn-keys3)
'(key)
(N_ "[Wnn] backspace")
(N_ "long description will be here"))
(define-custom 'wnn-delete-key '(generic-delete-key)
'(wnn-keys3)
'(key)
(N_ "[Wnn] delete")
(N_ "long description will be here"))
(define-custom 'wnn-go-left-key '(generic-go-left-key)
'(wnn-keys3)
'(key)
(N_ "[Wnn] go left")
(N_ "long description will be here"))
(define-custom 'wnn-go-right-key '(generic-go-right-key)
'(wnn-keys3)
'(key)
(N_ "[Wnn] go right")
(N_ "long description will be here"))
(define-custom 'wnn-vi-escape-key '("escape" "<Control>[")
'(wnn-keys3)
'(key)
(N_ "[Wnn] ESC keys on vi-cooperative mode")
(N_ "long description will be here"))
;;
;; ja advanced
;;
(define-custom 'wnn-hiragana-key '("<Shift>F6")
'(wnn-keys4 mode-transition)
'(key)
(N_ "[Wnn] hiragana mode")
(N_ "long description will be here"))
(define-custom 'wnn-katakana-key '("<Shift>F7")
'(wnn-keys4 mode-transition)
'(key)
(N_ "[Wnn] katakana mode")
(N_ "long description will be here"))
(define-custom 'wnn-halfkana-key '("<Shift>F8")
'(wnn-keys4 mode-transition)
'(key)
(N_ "[Wnn] halfwidth katakana mode")
(N_ "long description will be here"))
(define-custom 'wnn-halfwidth-alnum-key '("<Shift>F10")
'(wnn-keys4 mode-transition)
'(key)
(N_ "[Wnn] halfwidth alphanumeric mode")
(N_ "long description will be here"))
(define-custom 'wnn-fullwidth-alnum-key '("<Shift>F9")
'(wnn-keys4 mode-transition)
'(key)
(N_ "[Wnn] fullwidth alphanumeric mode")
(N_ "long description will be here"))
(define-custom 'wnn-kana-toggle-key '()
'(wnn-keys4 advanced)
'(key)
(N_ "[Wnn] toggle hiragana/katakana mode")
(N_ "long description will be here"))
(define-custom 'wnn-alkana-toggle-key '()
'(wnn-keys4 advanced)
'(key)
(N_ "[Wnn] toggle kana/alphanumeric mode")
(N_ "long description will be here"))
(define-custom 'wnn-next-prediction-key '("tab" "down" "<IgnoreCase><Control>n" "<IgnoreCase><Control>i")
'(wnn-keys4 wnn-prediction)
'(key)
(N_ "[Wnn] Next prediction candidate")
(N_ "long description will be here"))
(define-custom 'wnn-prev-prediction-key '(generic-prev-candidate-key)
'(wnn-keys4 wnn-prediction)
'(key)
(N_ "[Wnn] Previous prediction candidate")
(N_ "long description will be here"))
| null | https://raw.githubusercontent.com/uim/uim/d1ac9d9315ff8c57c713b502544fef9b3a83b3e5/scm/wnn-key-custom.scm | scheme | wnn-custom.scm: Customization variables for wnn.scm
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
notice, this list of conditions and the following disclaimer.
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
may be used to endorse or promote products derived from this software
without specific prior written permission.
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
"Q"
overriding generic keys
(define-custom 'wnn-off-key '("l" generic-on-key)
overriding generic keys (advanced)
ja advanced
| Copyright ( c ) 2003 - 2013 uim Project
1 . Redistributions of source code must retain the above copyright
2 . Redistributions in binary form must reproduce the above copyright
3 . Neither the name of authors nor the names of its contributors
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ` ` AS IS '' AND
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR LIABLE
FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT
(require "i18n.scm")
(define-custom-group 'wnn-keys1
(N_ "Wnn key bindings 1")
(N_ "long description will be here."))
(define-custom-group 'wnn-keys2
(N_ "Wnn key bindings 2")
(N_ "long description will be here."))
(define-custom-group 'wnn-keys3
(N_ "Wnn key bindings 3")
(N_ "long description will be here."))
(define-custom-group 'wnn-keys4
(N_ "Wnn key bindings 4")
(N_ "long description will be here."))
(define-custom 'wnn-next-segment-key '(generic-go-right-key)
'(wnn-keys1)
'(key)
(N_ "[Wnn] next segment")
(N_ "long description will be here"))
(define-custom 'wnn-prev-segment-key '(generic-go-left-key)
'(wnn-keys1)
'(key)
(N_ "[Wnn] previous segment")
(N_ "long description will be here"))
(define-custom 'wnn-extend-segment-key '("<IgnoreCase><Control>o" "<Shift>right")
'(wnn-keys1)
'(key)
(N_ "[Wnn] extend segment")
(N_ "long description will be here"))
(define-custom 'wnn-shrink-segment-key '("<IgnoreCase><Control>i" "<Shift>left")
'(wnn-keys1)
'(key)
(N_ "[Wnn] shrink segment")
(N_ "long description will be here"))
(define-custom 'wnn-transpose-as-hiragana-key '("F6" "Muhenkan")
'(wnn-keys1)
'(key)
(N_ "[Wnn] convert to hiragana")
(N_ "long description will be here"))
(define-custom 'wnn-transpose-as-katakana-key '("F7" "Muhenkan")
'(wnn-keys1)
'(key)
(N_ "[Wnn] convert to katakana")
(N_ "long description will be here"))
(define-custom 'wnn-transpose-as-halfkana-key '("F8" "Muhenkan")
'(wnn-keys1)
'(key)
(N_ "[Wnn] convert to halfwidth katakana")
(N_ "long description will be here"))
(define-custom 'wnn-transpose-as-halfwidth-alnum-key '("F10")
'(wnn-keys1)
'(key)
(N_ "[Wnn] convert to halfwidth alphanumeric")
(N_ "long description will be here"))
(define-custom 'wnn-transpose-as-fullwidth-alnum-key '("F9")
'(wnn-keys1)
'(key)
(N_ "[Wnn] convert to fullwidth alphanumeric")
(N_ "long description will be here"))
'(wnn-keys1)
'(key)
(N_ "[Wnn] commit as transposed kana")
(N_ "long description will be here"))
(define-custom 'wnn-on-key '("<Control>\\" generic-on-key)
'(wnn-keys2)
'(key)
(N_ "[Wnn] on")
(N_ "long description will be here"))
(define-custom 'wnn-off-key '("<Control>\\" generic-off-key)
'(wnn-keys2)
'(key)
(N_ "[Wnn] off")
(N_ "long description will be here"))
(define-custom 'wnn-begin-conv-key '(generic-begin-conv-key)
'(wnn-keys2)
'(key)
(N_ "[Wnn] begin conversion")
(N_ "long description will be here"))
(define-custom 'wnn-commit-key '(generic-commit-key)
'(wnn-keys2)
'(key)
(N_ "[Wnn] commit")
(N_ "long description will be here"))
(define-custom 'wnn-cancel-key '(generic-cancel-key)
'(wnn-keys2)
'(key)
(N_ "[Wnn] cancel")
(N_ "long description will be here"))
(define-custom 'wnn-next-candidate-key '(generic-next-candidate-key)
'(wnn-keys2)
'(key)
(N_ "[Wnn] next candidate")
(N_ "long description will be here"))
(define-custom 'wnn-prev-candidate-key '(generic-prev-candidate-key)
'(wnn-keys2)
'(key)
(N_ "[Wnn] previous candidate")
(N_ "long description will be here"))
(define-custom 'wnn-next-page-key '(generic-next-page-key)
'(wnn-keys2)
'(key)
(N_ "[Wnn] next page of candidate window")
(N_ "long description will be here"))
(define-custom 'wnn-prev-page-key '(generic-prev-page-key)
'(wnn-keys2)
'(key)
(N_ "[Wnn] previous page of candidate window")
(N_ "long description will be here"))
(define-custom 'wnn-beginning-of-preedit-key '(generic-beginning-of-preedit-key)
'(wnn-keys3)
'(key)
(N_ "[Wnn] beginning of preedit")
(N_ "long description will be here"))
(define-custom 'wnn-end-of-preedit-key '(generic-end-of-preedit-key)
'(wnn-keys3)
'(key)
(N_ "[Wnn] end of preedit")
(N_ "long description will be here"))
(define-custom 'wnn-kill-key '(generic-kill-key)
'(wnn-keys3)
'(key)
(N_ "[Wnn] erase after cursor")
(N_ "long description will be here"))
(define-custom 'wnn-kill-backward-key '(generic-kill-backward-key)
'(wnn-keys3)
'(key)
(N_ "[Wnn] erase before cursor")
(N_ "long description will be here"))
(define-custom 'wnn-backspace-key '(generic-backspace-key)
'(wnn-keys3)
'(key)
(N_ "[Wnn] backspace")
(N_ "long description will be here"))
(define-custom 'wnn-delete-key '(generic-delete-key)
'(wnn-keys3)
'(key)
(N_ "[Wnn] delete")
(N_ "long description will be here"))
(define-custom 'wnn-go-left-key '(generic-go-left-key)
'(wnn-keys3)
'(key)
(N_ "[Wnn] go left")
(N_ "long description will be here"))
(define-custom 'wnn-go-right-key '(generic-go-right-key)
'(wnn-keys3)
'(key)
(N_ "[Wnn] go right")
(N_ "long description will be here"))
(define-custom 'wnn-vi-escape-key '("escape" "<Control>[")
'(wnn-keys3)
'(key)
(N_ "[Wnn] ESC keys on vi-cooperative mode")
(N_ "long description will be here"))
(define-custom 'wnn-hiragana-key '("<Shift>F6")
'(wnn-keys4 mode-transition)
'(key)
(N_ "[Wnn] hiragana mode")
(N_ "long description will be here"))
(define-custom 'wnn-katakana-key '("<Shift>F7")
'(wnn-keys4 mode-transition)
'(key)
(N_ "[Wnn] katakana mode")
(N_ "long description will be here"))
(define-custom 'wnn-halfkana-key '("<Shift>F8")
'(wnn-keys4 mode-transition)
'(key)
(N_ "[Wnn] halfwidth katakana mode")
(N_ "long description will be here"))
(define-custom 'wnn-halfwidth-alnum-key '("<Shift>F10")
'(wnn-keys4 mode-transition)
'(key)
(N_ "[Wnn] halfwidth alphanumeric mode")
(N_ "long description will be here"))
(define-custom 'wnn-fullwidth-alnum-key '("<Shift>F9")
'(wnn-keys4 mode-transition)
'(key)
(N_ "[Wnn] fullwidth alphanumeric mode")
(N_ "long description will be here"))
(define-custom 'wnn-kana-toggle-key '()
'(wnn-keys4 advanced)
'(key)
(N_ "[Wnn] toggle hiragana/katakana mode")
(N_ "long description will be here"))
(define-custom 'wnn-alkana-toggle-key '()
'(wnn-keys4 advanced)
'(key)
(N_ "[Wnn] toggle kana/alphanumeric mode")
(N_ "long description will be here"))
(define-custom 'wnn-next-prediction-key '("tab" "down" "<IgnoreCase><Control>n" "<IgnoreCase><Control>i")
'(wnn-keys4 wnn-prediction)
'(key)
(N_ "[Wnn] Next prediction candidate")
(N_ "long description will be here"))
(define-custom 'wnn-prev-prediction-key '(generic-prev-candidate-key)
'(wnn-keys4 wnn-prediction)
'(key)
(N_ "[Wnn] Previous prediction candidate")
(N_ "long description will be here"))
|
2c2dccfc97be9e63cfba46c216f0c6bc24b633d60f7ca519b6932c4be97e71ec | bozsahin/ccglab | g.ccg.lisp | (DEFPARAMETER *CCG-GRAMMAR*
'(((KEY 1) (PHON I) (MORPH N) (SYN ((BCAT NP) (FEATS ((AGR 1S))))) (SEM "I")
(PARAM 1.0))
((KEY 2) (PHON THINK) (MORPH EN)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR 1S)))))
(DIR FS) (MODAL HARMONIC) ((BCAT S) (FEATS NIL))))
(SEM (LAM P (LAM X (("THINK" P) X)))) (PARAM 1.0))
((KEY 3) (PHON JOHN) (MORPH N) (SYN ((BCAT NP) (FEATS ((AGR 3S)))))
(SEM "JOHN") (PARAM 1.0))
((KEY 4) (PHON LIKES) (MORPH EN)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR 3S)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("LIKE" X) Y)))) (PARAM 1.0))
((KEY 5) (PHON AND) (MORPH CO)
(SYN
((((BCAT @X) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT @X) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT @X) (FEATS NIL))))
(SEM (LAM P (LAM Q (LAM X (("AND" (P X)) (Q X)))))) (PARAM 1.0))
((KEY 6) (PHON YOU) (MORPH N) (SYN ((BCAT NP) (FEATS ((AGR 2S)))))
(SEM "YOU") (PARAM 1.0))
((KEY 7) (PHON BELIEVE) (MORPH EN)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR 2S)))))
(DIR FS) (MODAL HARMONIC) ((BCAT S) (FEATS NIL))))
(SEM (LAM P (LAM X (("BELIEVE" P) X)))) (PARAM 1.0))
((KEY 8) (PHON MARY) (MORPH N) (SYN ((BCAT NP) (FEATS ((AGR 3S)))))
(SEM "MARY") (PARAM 1.0))
((KEY 9) (PHON HATES) (MORPH EN)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR 3S)))))
(DIR FS) (MODAL HARMONIC) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("HATE" X) Y)))) (PARAM 1.0))
((KEY 10) (PHON CATS) (MORPH N) (SYN ((BCAT NP) (FEATS ((AGR 3P)))))
(SEM "CATS") (PARAM 1.0))
((KEY 11) (PHON THE) (MORPH D)
(SYN
(((BCAT NP) (FEATS ((HEAD ?H)))) (DIR FS) (MODAL HARMONIC)
((BCAT N) (FEATS ((HEAD ?H))))))
(SEM (LAM X ("DEF" X))) (PARAM 1.0))
((KEY 12) (PHON BOOK) (MORPH N) (SYN ((BCAT N) (FEATS NIL))) (SEM "BOOK")
(PARAM 1.0))
((KEY 13) (PHON "this book") (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((TOP P)))))))
(SEM (LAM P (("AND" (P "BOOK")) ("TOPIC" "BOOK")))) (PARAM 1.0))
((KEY 14) (PHON LIKE) (MORPH EN)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR 1S)))))
(DIR FS) (MODAL HARMONIC) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("LIKE" X) Y)))) (PARAM 1.0))
((KEY 15) (PHON PICKED) (MORPH EN)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT (up)) (BCONST T) (FEATS NIL)))
(DIR FS) (MODAL HARMONIC) ((BCAT NP) (FEATS ((HEAVY M))))))
(SEM
(LAM Y
(LAM X
(LAM Z (("CAUSE" ("INIT" (((("HOLD" _) ("REACH" X)) Y) Z))) Z)))))
(PARAM 1.0))
((KEY 16) (PHON PICKED) (MORPH EN)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL HARMONIC) ((BCAT NP) (FEATS ((LEXC P)))))
(DIR FS) (MODAL ALL) ((BCAT (up)) (BCONST T) (FEATS NIL))))
(SEM (LAM X (LAM Y (LAM Z (((("PICK" _) X) Y) Z))))) (PARAM 1.0))
((KEY 17) (PHON THINKS) (MORPH EN)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR 3S)))))
(DIR FS) (MODAL HARMONIC) ((BCAT SP) (FEATS NIL))))
(SEM (LAM P (LAM X (("THINK" P) X)))) (PARAM 1.0))
((KEY 18) (PHON SHE) (MORPH N) (SYN ((BCAT NP) (FEATS ((AGR 3S)))))
(SEM "SHE") (PARAM 1.0))
((KEY 19) (PHON HARRY) (MORPH NP) (SYN ((BCAT NP) (FEATS ((AGR 3S)))))
(SEM "HARRY") (PARAM 1.0))
((KEY 20) (PHON BARRY) (MORPH NP) (SYN ((BCAT NP) (FEATS ((AGR 3S)))))
(SEM "BARRY") (PARAM 1.0))
((KEY 21) (PHON MARY) (MORPH NP) (SYN ((BCAT NP) (FEATS ((AGR 3S)))))
(SEM "MARY") (PARAM 1.0))
((KEY 22) (PHON UP) (MORPH P)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM P ("UP" (P X))))) (PARAM 1.0))
((KEY 23) (PHON BEANS) (MORPH N) (SYN ((BCAT N) (FEATS ((HEAD BEANS)))))
(SEM "BEANS") (PARAM 1.0))
((KEY 24) (PHON THAT) (MORPH REL)
(SYN
((((BCAT N) (FEATS ((HEAD ?H)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((HEAD ?H)))))
(DIR FS) (MODAL ALL)
(((BCAT S) (FEATS ((HEAD ?H)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((HEAD ?H)))))))
(SEM (LAM P (LAM Q (LAM X (("AND" (P X)) (Q X)))))) (PARAM 1.0))
((KEY 25) (PHON SPILLED) (MORPH EN)
(SYN
((((BCAT S) (FEATS ((HEAD BEANS)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL HARMONIC) ((BCAT NP) (FEATS ((HEAD BEANS))))))
(SEM (LAM X (LAM Y (((("DIVULGE" _) ("PUBLIC" X)) "SECRET") Y))))
(PARAM 1.0))
((KEY 26) (PHON CAUSED) (MORPH EN)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL HARMONIC) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("CAUSE" X) Y)))) (PARAM 1.0))
((KEY 27) (PHON "quite a stir") (MORPH N) (SYN ((BCAT NP) (FEATS NIL)))
(SEM "STIR") (PARAM 1.0))
((KEY 28) (PHON TAROO-WA) (MORPH N) (SYN ((BCAT NP) (FEATS ((TOP P)))))
(SEM "TAROO") (PARAM 1.0))
((KEY 29) (PHON HANAKO-NI) (MORPH N)
(SYN
(((BCAT PREDP) (FEATS ((CASE DAT)))) (DIR FS) (MODAL ALL)
((((BCAT CING) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (LAM X ((P X) "HANAKO")))) (PARAM 1.0))
((KEY 30) (PHON HANAKO-NI) (MORPH N) (SYN ((BCAT NP) (FEATS ((CASE DAT)))))
(SEM "HANAKO") (PARAM 1.0))
((KEY 31) (PHON HUKU-O) (MORPH N)
(SYN
(((BCAT PREDP) (FEATS ((CASE ACC)))) (DIR BS) (MODAL ALL)
((((BCAT CING) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "CLOTHES"))) (PARAM 1.0))
((KEY 32) (PHON HUKU-O) (MORPH N) (SYN ((BCAT NP) (FEATS ((CASE ACC)))))
(SEM "CLOTHES") (PARAM 1.0))
((KEY 33) (PHON KITEIRU) (MORPH JP)
(SYN
((((BCAT CING) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("WEARING" X) Y)))) (PARAM 1.0))
((KEY 34) (PHON KITEIRU) (MORPH JP)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("WEAR" X) Y)))) (PARAM 1.0))
((KEY 35) (PHON YOGOS-ARE-TA) (MORPH JP)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE TOP)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE DAT)))))
(DIR BS) (MODAL ALL) ((BCAT PREDP) (FEATS ((CASE ACC))))))
(SEM (LAM X (LAM Y (LAM Z ((("LET" (("DIRTY" (X Z)) Y)) Y) Z)))))
(PARAM 1.0))
((KEY 36) (PHON YOGOS-ARE-TA) (MORPH JP)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE TOP)))))
(DIR BS) (MODAL ALL) ((BCAT PREDP) (FEATS ((CASE DAT)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ACC))))))
(SEM (LAM X (LAM Y (LAM Z ((("LET" (("DIRTY" (X Y)) Y)) Y) Z)))))
(PARAM 1.0))
((KEY 37) (PHON ZHANGSAN) (MORPH N) (SYN ((BCAT NP) (FEATS NIL))) (SEM "Z")
(PARAM 1.0))
((KEY 38) (PHON XIHUAN) (MORPH CH)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("LIKE" X) Y)))) (PARAM 1.0))
((KEY 39) (PHON XIHUAN) (MORPH CH)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (("LIKE" X) "TOP"))) (PARAM 1.0))
((KEY 40) (PHON DANSHI) (MORPH CO)
(SYN
((((BCAT @X) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT @X) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT @X) (FEATS NIL))))
(SEM (LAM P (LAM Q (LAM X (("BUT" (P X)) (Q X)))))) (PARAM 1.0))
((KEY 41) (PHON E2R) (MORPH CO)
(SYN
((((BCAT @X) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT @X) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT @X) (FEATS NIL))))
(SEM (LAM P (LAM Q (LAM X (("AND" (P X)) (Q X)))))) (PARAM 1.0))
((KEY 42) (PHON LISI) (MORPH N) (SYN ((BCAT NP) (FEATS NIL))) (SEM "LISI")
(PARAM 1.0))
((KEY 43) (PHON BU) (MORPH NEG)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (LAM X ("NEG" (P X))))) (PARAM 1.0))
((KEY 44) (PHON "zhe-ben shu") (MORPH N) (SYN ((BCAT NP) (FEATS NIL)))
(SEM ("DEF" "BOOK")) (PARAM 1.0))
((KEY 45) (PHON TA) (MORPH N) (SYN ((BCAT NP) (FEATS NIL))) (SEM "HESHE")
(PARAM 1.0))
((KEY 46) (PHON DIGEI) (MORPH CH)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (LAM Z ((("GIVE" X) Y) Z))))) (PARAM 1.0))
((KEY 47) (PHON GEGE) (MORPH N) (SYN ((BCAT NP) (FEATS NIL)))
(SEM "BROTHER") (PARAM 1.0))
((KEY 48) (PHON "yi-hu jiu") (MORPH N) (SYN ((BCAT NP) (FEATS NIL)))
(SEM ("ONE" "WINE")) (PARAM 1.0))
((KEY 49) (PHON JIEJIE) (MORPH N) (SYN ((BCAT NP) (FEATS NIL)))
(SEM "SISTER") (PARAM 1.0))
((KEY 50) (PHON "yi-pan cai") (MORPH N) (SYN ((BCAT NP) (FEATS NIL)))
(SEM ("ONE" "DISH")) (PARAM 1.0))
((KEY 51) (PHON ZHANGSAN) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((TOP P) (PRO P) (PERS 3S)))))))
(SEM (LAM P (("AND" (P Z)) ("TOPIC" Z)))) (PARAM 1.0))
((KEY 52) (PHON WO) (MORPH N) (SYN ((BCAT NP) (FEATS ((PERS 1S)))))
(SEM "I") (PARAM 1.0))
((KEY 53) (PHON QIDAI) (MORPH CH)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM P (LAM Y (("FORESEE" (P X)) Y))))) (PARAM 1.0))
((KEY 54) (PHON QUAN) (MORPH CH)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM P (LAM Y ((("PERSUADE" (P X)) X) Y))))) (PARAM 1.0))
((KEY 55) (PHON DAYING) (MORPH CH)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM P (LAM Y ((("PROMISE" (P Y)) X) Y))))) (PARAM 1.0))
((KEY 56) (PHON TA) (MORPH PRO)
(SYN
((((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((PRO P) (PERS 3S)))))
(DIR BS) (MODAL ALL)
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P ("RES" P))) (PARAM 1.0))
((KEY 57) (PHON "yao lai") (MORPH CH) (SYN ((BCAT VP) (FEATS NIL)))
(SEM (LAM X ("WILLCOME" X))) (PARAM 1.0))
((KEY 58) (PHON BEN-IM) (MORPH N)
(SYN
(((BCAT S) (FEATS ((AGR 1S)))) (DIR FS) (MODAL ALL)
((BCAT IV) (FEATS ((AGR 1S))))))
(SEM (LAM P (P "I"))) (PARAM 1.0))
((KEY 59) (PHON ADAM-IN) (MORPH N) (SYN ((BCAT NP) (FEATS ((AGR 3S)))))
(SEM "MAN") (PARAM 1.0))
((KEY 60) (PHON OKU) (MORPH TR)
(SYN
(((BCAT IV) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ACC))))))
(SEM (LAM X (LAM Y (("READ" X) Y)))) (PARAM 1.0))
((KEY 61) (PHON OKUDU) (MORPH TR)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM) (AGR 3S)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ACC))))))
(SEM (LAM X (LAM Y (("READ" X) Y)))) (PARAM 1.0))
((KEY 62) (PHON -DUGU) (MORPH COMP)
(SYN
((((BCAT S) (FEATS ((AGR ?A)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR ?A)))))
(DIR BS) (MODAL HARMONIC) ((BCAT IV) (FEATS ((AGR ?A))))))
(SEM (LAM P (LAM X (P X)))) (PARAM 1.0))
((KEY 63) (PHON -NU) (MORPH CASE)
(SYN
(((BCAT S) (FEATS ((CASE ACC)))) (DIR BS) (MODAL HARMONIC)
((BCAT S) (FEATS ((AGR 3S))))))
(SEM (LAM P P)) (PARAM 1.0))
((KEY 64) (PHON BIL) (MORPH TR)
(SYN
(((BCAT IV) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT S) (FEATS ((CASE ACC))))))
(SEM (LAM P (LAM X (("KNOW" P) X)))) (PARAM 1.0))
((KEY 65) (PHON -DIGIM) (MORPH REL)
(SYN
((((BCAT NP) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL HARMONIC)
(((BCAT S) (FEATS ((AGR 1S)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (LAM Q (LAM X (("AND" (P X)) (Q X)))))) (PARAM 1.0))
((KEY 66) (PHON KITAP) (MORPH N)
(SYN
(((BCAT NP) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT NP) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "BOOK"))) (PARAM 1.0))
((KEY 67) (PHON "O Paulo") (MORPH N) (SYN ((BCAT NP) (FEATS ((AGR 3S)))))
(SEM "PAUL") (PARAM 1.0))
((KEY 68) (PHON NAO) (MORPH NEG)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR ?A)))))
(DIR FS) (MODAL ALL)
(((BCAT S) (FEATS ((FOP P)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR ?A)))))))
(SEM (LAM P (LAM X ("NEG" (P X))))) (PARAM 1.0))
((KEY 69) (PHON OS) (MORPH PRO)
(SYN
((((BCAT S) (FEATS ((FOP P)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR ?A)))))
(DIR FS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR ?A)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((TYP PRO) (KIND PLU)))))))
(SEM (LAM P (P "THEM"))) (PARAM 1.0))
((KEY 70) (PHON VIU) (MORPH PT)
(SYN
((((BCAT S) (FEATS ((TENSE PAST)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR 3S)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("SEE" X) Y)))) (PARAM 1.0))
((KEY 71) (PHON HANKWUK-EY) (MORPH N) (SYN ((BCAT NP) (FEATS NIL)))
(SEM "KOREA") (PARAM 1.0))
((KEY 72) (PHON SEWUL-I) (MORPH N)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ?C))))))
(DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ?C))))))))
(SEM (LAM P ("SEUL" P))) (PARAM 1.0))
((KEY 73) (PHON NAMTAYMUN-SICANG-I) (MORPH N)
(SYN ((BCAT NP) (FEATS ((CASE NOM))))) (SEM "MARKET") (PARAM 1.0))
((KEY 74) (PHON PUL-I) (MORPH N) (SYN ((BCAT NP) (FEATS ((CASE NOM)))))
(SEM "FIRE") (PARAM 1.0))
((KEY 75) (PHON NA-ASS-TA) (MORPH KO)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ?C1)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ?C2)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NOM))))))
(SEM
(LAM X
(LAM Y (LAM Z (("AND" ((("BREAKOUT" Z) X) "ONE")) (("AT" Y) Z))))))
(PARAM 1.0))
((KEY 76) (PHON "bayi yara") (MORPH N)
(SYN ((BCAT NP) (FEATS ((CASE ABS))))) (SEM "MAN") (PARAM 1.0))
((KEY 77) (PHON NUMA-NGU) (MORPH N) (SYN ((BCAT NP) (FEATS ((ACSE ERG)))))
(SEM "FATHER") (PARAM 1.0))
((KEY 78) (PHON GIGA-N) (MORPH DY)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ERG)))))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS NIL))))
(SEM (LAM P (LAM Y (LAM X ((("TELL" (P X)) X) Y))))) (PARAM 1.0))
((KEY 79) (PHON GUBI-NGU) (MORPH N) (SYN ((BCAT NP) (FEATS ((CASE ERG)))))
(SEM "GUBI") (PARAM 1.0))
((KEY 80) (PHON MAWA-LI) (MORPH DY)
(SYN
(((BCAT VP) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG))))))
(SEM (LAM X (LAM Y (("EXAMINE" Y) X)))) (PARAM 1.0))
((KEY 81) (PHON BANAGA-NYU) (MORPH DY) (SYN ((BCAT VP) (FEATS NIL)))
(SEM (LAM X ("RETURN" X))) (PARAM 1.0))
((KEY 82) (PHON BAGUL) (MORPH CL)
(SYN
(((BCAT NP) (FEATS ((CASE DAT)))) (DIR FS) (MODAL ALL)
((BCAT N) (FEATS ((CASE DAT))))))
(SEM (LAM X ("CLASS1" X))) (PARAM 1.0))
((KEY 83) (PHON WANAL-GU) (MORPH N) (SYN ((BCAT N) (FEATS ((CASE DAT)))))
(SEM "BOOMERANG") (PARAM 1.0))
((KEY 84) (PHON BANUL-DIN-GU) (MORPH N)
(SYN
((((BCAT NP) (FEATS ((POSS GEN) (CASE DAT)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((POSS GEN) (CASE DAT)))))
(DIR FS) (MODAL ALL) ((BCAT N) (FEATS ((POSS GEN) (CASE DAT))))))
(SEM (LAM X (LAM Y (("OF" X) Y)))) (PARAM 1.0))
((KEY 85) (PHON YARA-NU-N-DIN-GU) (MORPH N)
(SYN ((BCAT N) (FEATS ((POSS GEN) (CASE DAT))))) (SEM "MAN") (PARAM 1.0))
((KEY 86) (PHON "bagul wanal-gu") (MORPH DY)
(SYN
(((BCAT NP) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE DAT))))))
(SEM (LAM X ("BOOMERANG" X))) (PARAM 1.0))
((KEY 87) (PHON M33KA55) (MORPH N) (SYN ((BCAT NP) (FEATS NIL)))
(SEM "MUGA") (PARAM 1.0))
((KEY 88) (PHON M33KO44) (MORPH N) (SYN ((BCAT NP) (FEATS NIL)))
(SEM "MUGO") (PARAM 1.0))
((KEY 89) (PHON NDU21) (MORPH NU)
(SYN
((((BCAT S) (FEATS ((TYP E)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("BEAT" Y) X)))) (PARAM 1.0))
((KEY 90) (PHON NDU21) (MORPH NU)
(SYN
((((BCAT S) (FEATS ((TYP A)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("BEAT" X) Y)))) (PARAM 1.0))
((KEY 91) (PHON NATEX-KAN-KE) (MORPH SH)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG) (AGR PLU)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ABS))))))
(SEM (LAM X (LAM Y (("BITE" X) Y)))) (PARAM 1.0))
((KEY 92) (PHON NATEX) (MORPH SH)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG) (AGR SING)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ABS))))))
(SEM (LAM X (LAM Y (("BITE" X) Y)))) (PARAM 1.0))
((KEY 93) (PHON MAWA-KAN-KE) (MORPH SH)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR PLU))))))
(SEM (LAM X ("DIE" X))) (PARAM 1.0))
((KEY 94) (PHON OCHITI-BAON-RA) (MORPH N)
(SYN ((BCAT NP) (FEATS ((CASE ERG) (AGR PLU) (MOD PRT))))) (SEM "DOGS")
(PARAM 1.0))
((KEY 95) (PHON BAKE) (MORPH N)
(SYN ((BCAT NP) (FEATS ((CASE ABS) (NUM SING))))) (SEM "CHILD")
(PARAM 1.0))
((KEY 96) (PHON JONI-BO-RA) (MORPH N)
(SYN ((BCAT NP) (FEATS ((CASE ABS) (AGR PLU) (MOD PRT))))) (SEM "PERSONS")
(PARAM 1.0))
((KEY 97) (PHON BAKE-BO) (MORPH N)
(SYN ((BCAT NP) (FEATS ((CASE ABS) (NUM PLU))))) (SEM "CHILDREN")
(PARAM 1.0))
((KEY 98) (PHON OCHITI-NIN-RA) (MORPH N)
(SYN ((BCAT NP) (FEATS ((CASE ERG) (AGR SING) (MOD PRT))))) (SEM "DOG")
(PARAM 1.0))
((KEY 99) (PHON "Dass sie kommt") (MORPH C)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT S) (FEATS ((TOP P)))))))
(SEM (LAM P (P ("COMES" "SHE")))) (PARAM 1.0))
((KEY 100) (PHON GLAUBT) (MORPH DE)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT S) (FEATS NIL))))
(SEM (LAM P (LAM X (("BELIEVE" P) X)))) (PARAM 1.0))
((KEY 101) (PHON ER) (MORPH PRO)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "HE"))) (PARAM 1.0))
((KEY 102) (PHON NICHT) (MORPH F)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL HARMONIC)
((BCAT S) (FEATS NIL))))
(SEM (LAM P ("NEG" P))) (PARAM 1.0))
((KEY 103) (PHON "Die Diplomarbeit") (MORPH N)
(SYN ((BCAT NP) (FEATS NIL))) (SEM "THE-MA") (PARAM 1.0))
((KEY 104) (PHON ZU) (MORPH C)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P P)) (PARAM 1.0))
((KEY 105) (PHON SCHREIBEN) (MORPH DE)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("WRITE" X) Y)))) (PARAM 1.0))
((KEY 106) (PHON HAT) (MORPH F)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P P)) (PARAM 1.0))
((KEY 107) (PHON "die Studentin") (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "STUDENT"))) (PARAM 1.0))
((KEY 108) (PHON GELANWEILT) (MORPH DE)
(SYN (((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT S) (FEATS NIL))))
(SEM (LAM P ("BORE" P))) (PARAM 1.0))
((KEY 109) (PHON JANOS) (MORPH N) (SYN ((BCAT NP) (FEATS ((AGR 3S)))))
(SEM "JOHN") (PARAM 1.0))
((KEY 110) (PHON LAT-T-A) (MORPH HU)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR 3S)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR 3S))))))
(SEM (LAM X (LAM Y (("SEE" X) Y)))) (PARAM 1.0))
((KEY 111) (PHON OT) (MORPH N)
(SYN ((BCAT NP) (FEATS ((AGR 3S) (TYP PRO))))) (SEM "HIM") (PARAM 1.0))
((KEY 112) (PHON LAT-OTT) (MORPH HU)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR 3S)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR 1S))))))
(SEM (LAM X (LAM Y (("SEE" X) Y)))) (PARAM 1.0))
((KEY 113) (PHON LAT-OTT) (MORPH HU)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR 3S)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR 2S))))))
(SEM (LAM X (LAM Y (("SEE" X) Y)))) (PARAM 1.0))
((KEY 114) (PHON ENGEM) (MORPH N) (SYN ((BCAT NP) (FEATS ((AGR 1S)))))
(SEM "ME") (PARAM 1.0)))) | null | https://raw.githubusercontent.com/bozsahin/ccglab/15def13c76e562a053ff92d61353549818d2a7e3/examples/type-raising-with-workflow/g.ccg.lisp | lisp | (DEFPARAMETER *CCG-GRAMMAR*
'(((KEY 1) (PHON I) (MORPH N) (SYN ((BCAT NP) (FEATS ((AGR 1S))))) (SEM "I")
(PARAM 1.0))
((KEY 2) (PHON THINK) (MORPH EN)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR 1S)))))
(DIR FS) (MODAL HARMONIC) ((BCAT S) (FEATS NIL))))
(SEM (LAM P (LAM X (("THINK" P) X)))) (PARAM 1.0))
((KEY 3) (PHON JOHN) (MORPH N) (SYN ((BCAT NP) (FEATS ((AGR 3S)))))
(SEM "JOHN") (PARAM 1.0))
((KEY 4) (PHON LIKES) (MORPH EN)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR 3S)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("LIKE" X) Y)))) (PARAM 1.0))
((KEY 5) (PHON AND) (MORPH CO)
(SYN
((((BCAT @X) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT @X) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT @X) (FEATS NIL))))
(SEM (LAM P (LAM Q (LAM X (("AND" (P X)) (Q X)))))) (PARAM 1.0))
((KEY 6) (PHON YOU) (MORPH N) (SYN ((BCAT NP) (FEATS ((AGR 2S)))))
(SEM "YOU") (PARAM 1.0))
((KEY 7) (PHON BELIEVE) (MORPH EN)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR 2S)))))
(DIR FS) (MODAL HARMONIC) ((BCAT S) (FEATS NIL))))
(SEM (LAM P (LAM X (("BELIEVE" P) X)))) (PARAM 1.0))
((KEY 8) (PHON MARY) (MORPH N) (SYN ((BCAT NP) (FEATS ((AGR 3S)))))
(SEM "MARY") (PARAM 1.0))
((KEY 9) (PHON HATES) (MORPH EN)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR 3S)))))
(DIR FS) (MODAL HARMONIC) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("HATE" X) Y)))) (PARAM 1.0))
((KEY 10) (PHON CATS) (MORPH N) (SYN ((BCAT NP) (FEATS ((AGR 3P)))))
(SEM "CATS") (PARAM 1.0))
((KEY 11) (PHON THE) (MORPH D)
(SYN
(((BCAT NP) (FEATS ((HEAD ?H)))) (DIR FS) (MODAL HARMONIC)
((BCAT N) (FEATS ((HEAD ?H))))))
(SEM (LAM X ("DEF" X))) (PARAM 1.0))
((KEY 12) (PHON BOOK) (MORPH N) (SYN ((BCAT N) (FEATS NIL))) (SEM "BOOK")
(PARAM 1.0))
((KEY 13) (PHON "this book") (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((TOP P)))))))
(SEM (LAM P (("AND" (P "BOOK")) ("TOPIC" "BOOK")))) (PARAM 1.0))
((KEY 14) (PHON LIKE) (MORPH EN)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR 1S)))))
(DIR FS) (MODAL HARMONIC) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("LIKE" X) Y)))) (PARAM 1.0))
((KEY 15) (PHON PICKED) (MORPH EN)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT (up)) (BCONST T) (FEATS NIL)))
(DIR FS) (MODAL HARMONIC) ((BCAT NP) (FEATS ((HEAVY M))))))
(SEM
(LAM Y
(LAM X
(LAM Z (("CAUSE" ("INIT" (((("HOLD" _) ("REACH" X)) Y) Z))) Z)))))
(PARAM 1.0))
((KEY 16) (PHON PICKED) (MORPH EN)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL HARMONIC) ((BCAT NP) (FEATS ((LEXC P)))))
(DIR FS) (MODAL ALL) ((BCAT (up)) (BCONST T) (FEATS NIL))))
(SEM (LAM X (LAM Y (LAM Z (((("PICK" _) X) Y) Z))))) (PARAM 1.0))
((KEY 17) (PHON THINKS) (MORPH EN)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR 3S)))))
(DIR FS) (MODAL HARMONIC) ((BCAT SP) (FEATS NIL))))
(SEM (LAM P (LAM X (("THINK" P) X)))) (PARAM 1.0))
((KEY 18) (PHON SHE) (MORPH N) (SYN ((BCAT NP) (FEATS ((AGR 3S)))))
(SEM "SHE") (PARAM 1.0))
((KEY 19) (PHON HARRY) (MORPH NP) (SYN ((BCAT NP) (FEATS ((AGR 3S)))))
(SEM "HARRY") (PARAM 1.0))
((KEY 20) (PHON BARRY) (MORPH NP) (SYN ((BCAT NP) (FEATS ((AGR 3S)))))
(SEM "BARRY") (PARAM 1.0))
((KEY 21) (PHON MARY) (MORPH NP) (SYN ((BCAT NP) (FEATS ((AGR 3S)))))
(SEM "MARY") (PARAM 1.0))
((KEY 22) (PHON UP) (MORPH P)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM P ("UP" (P X))))) (PARAM 1.0))
((KEY 23) (PHON BEANS) (MORPH N) (SYN ((BCAT N) (FEATS ((HEAD BEANS)))))
(SEM "BEANS") (PARAM 1.0))
((KEY 24) (PHON THAT) (MORPH REL)
(SYN
((((BCAT N) (FEATS ((HEAD ?H)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((HEAD ?H)))))
(DIR FS) (MODAL ALL)
(((BCAT S) (FEATS ((HEAD ?H)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((HEAD ?H)))))))
(SEM (LAM P (LAM Q (LAM X (("AND" (P X)) (Q X)))))) (PARAM 1.0))
((KEY 25) (PHON SPILLED) (MORPH EN)
(SYN
((((BCAT S) (FEATS ((HEAD BEANS)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL HARMONIC) ((BCAT NP) (FEATS ((HEAD BEANS))))))
(SEM (LAM X (LAM Y (((("DIVULGE" _) ("PUBLIC" X)) "SECRET") Y))))
(PARAM 1.0))
((KEY 26) (PHON CAUSED) (MORPH EN)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL HARMONIC) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("CAUSE" X) Y)))) (PARAM 1.0))
((KEY 27) (PHON "quite a stir") (MORPH N) (SYN ((BCAT NP) (FEATS NIL)))
(SEM "STIR") (PARAM 1.0))
((KEY 28) (PHON TAROO-WA) (MORPH N) (SYN ((BCAT NP) (FEATS ((TOP P)))))
(SEM "TAROO") (PARAM 1.0))
((KEY 29) (PHON HANAKO-NI) (MORPH N)
(SYN
(((BCAT PREDP) (FEATS ((CASE DAT)))) (DIR FS) (MODAL ALL)
((((BCAT CING) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (LAM X ((P X) "HANAKO")))) (PARAM 1.0))
((KEY 30) (PHON HANAKO-NI) (MORPH N) (SYN ((BCAT NP) (FEATS ((CASE DAT)))))
(SEM "HANAKO") (PARAM 1.0))
((KEY 31) (PHON HUKU-O) (MORPH N)
(SYN
(((BCAT PREDP) (FEATS ((CASE ACC)))) (DIR BS) (MODAL ALL)
((((BCAT CING) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "CLOTHES"))) (PARAM 1.0))
((KEY 32) (PHON HUKU-O) (MORPH N) (SYN ((BCAT NP) (FEATS ((CASE ACC)))))
(SEM "CLOTHES") (PARAM 1.0))
((KEY 33) (PHON KITEIRU) (MORPH JP)
(SYN
((((BCAT CING) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("WEARING" X) Y)))) (PARAM 1.0))
((KEY 34) (PHON KITEIRU) (MORPH JP)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("WEAR" X) Y)))) (PARAM 1.0))
((KEY 35) (PHON YOGOS-ARE-TA) (MORPH JP)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE TOP)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE DAT)))))
(DIR BS) (MODAL ALL) ((BCAT PREDP) (FEATS ((CASE ACC))))))
(SEM (LAM X (LAM Y (LAM Z ((("LET" (("DIRTY" (X Z)) Y)) Y) Z)))))
(PARAM 1.0))
((KEY 36) (PHON YOGOS-ARE-TA) (MORPH JP)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE TOP)))))
(DIR BS) (MODAL ALL) ((BCAT PREDP) (FEATS ((CASE DAT)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ACC))))))
(SEM (LAM X (LAM Y (LAM Z ((("LET" (("DIRTY" (X Y)) Y)) Y) Z)))))
(PARAM 1.0))
((KEY 37) (PHON ZHANGSAN) (MORPH N) (SYN ((BCAT NP) (FEATS NIL))) (SEM "Z")
(PARAM 1.0))
((KEY 38) (PHON XIHUAN) (MORPH CH)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("LIKE" X) Y)))) (PARAM 1.0))
((KEY 39) (PHON XIHUAN) (MORPH CH)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (("LIKE" X) "TOP"))) (PARAM 1.0))
((KEY 40) (PHON DANSHI) (MORPH CO)
(SYN
((((BCAT @X) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT @X) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT @X) (FEATS NIL))))
(SEM (LAM P (LAM Q (LAM X (("BUT" (P X)) (Q X)))))) (PARAM 1.0))
((KEY 41) (PHON E2R) (MORPH CO)
(SYN
((((BCAT @X) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT @X) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT @X) (FEATS NIL))))
(SEM (LAM P (LAM Q (LAM X (("AND" (P X)) (Q X)))))) (PARAM 1.0))
((KEY 42) (PHON LISI) (MORPH N) (SYN ((BCAT NP) (FEATS NIL))) (SEM "LISI")
(PARAM 1.0))
((KEY 43) (PHON BU) (MORPH NEG)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (LAM X ("NEG" (P X))))) (PARAM 1.0))
((KEY 44) (PHON "zhe-ben shu") (MORPH N) (SYN ((BCAT NP) (FEATS NIL)))
(SEM ("DEF" "BOOK")) (PARAM 1.0))
((KEY 45) (PHON TA) (MORPH N) (SYN ((BCAT NP) (FEATS NIL))) (SEM "HESHE")
(PARAM 1.0))
((KEY 46) (PHON DIGEI) (MORPH CH)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (LAM Z ((("GIVE" X) Y) Z))))) (PARAM 1.0))
((KEY 47) (PHON GEGE) (MORPH N) (SYN ((BCAT NP) (FEATS NIL)))
(SEM "BROTHER") (PARAM 1.0))
((KEY 48) (PHON "yi-hu jiu") (MORPH N) (SYN ((BCAT NP) (FEATS NIL)))
(SEM ("ONE" "WINE")) (PARAM 1.0))
((KEY 49) (PHON JIEJIE) (MORPH N) (SYN ((BCAT NP) (FEATS NIL)))
(SEM "SISTER") (PARAM 1.0))
((KEY 50) (PHON "yi-pan cai") (MORPH N) (SYN ((BCAT NP) (FEATS NIL)))
(SEM ("ONE" "DISH")) (PARAM 1.0))
((KEY 51) (PHON ZHANGSAN) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((TOP P) (PRO P) (PERS 3S)))))))
(SEM (LAM P (("AND" (P Z)) ("TOPIC" Z)))) (PARAM 1.0))
((KEY 52) (PHON WO) (MORPH N) (SYN ((BCAT NP) (FEATS ((PERS 1S)))))
(SEM "I") (PARAM 1.0))
((KEY 53) (PHON QIDAI) (MORPH CH)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM P (LAM Y (("FORESEE" (P X)) Y))))) (PARAM 1.0))
((KEY 54) (PHON QUAN) (MORPH CH)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM P (LAM Y ((("PERSUADE" (P X)) X) Y))))) (PARAM 1.0))
((KEY 55) (PHON DAYING) (MORPH CH)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM P (LAM Y ((("PROMISE" (P Y)) X) Y))))) (PARAM 1.0))
((KEY 56) (PHON TA) (MORPH PRO)
(SYN
((((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((PRO P) (PERS 3S)))))
(DIR BS) (MODAL ALL)
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P ("RES" P))) (PARAM 1.0))
((KEY 57) (PHON "yao lai") (MORPH CH) (SYN ((BCAT VP) (FEATS NIL)))
(SEM (LAM X ("WILLCOME" X))) (PARAM 1.0))
((KEY 58) (PHON BEN-IM) (MORPH N)
(SYN
(((BCAT S) (FEATS ((AGR 1S)))) (DIR FS) (MODAL ALL)
((BCAT IV) (FEATS ((AGR 1S))))))
(SEM (LAM P (P "I"))) (PARAM 1.0))
((KEY 59) (PHON ADAM-IN) (MORPH N) (SYN ((BCAT NP) (FEATS ((AGR 3S)))))
(SEM "MAN") (PARAM 1.0))
((KEY 60) (PHON OKU) (MORPH TR)
(SYN
(((BCAT IV) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ACC))))))
(SEM (LAM X (LAM Y (("READ" X) Y)))) (PARAM 1.0))
((KEY 61) (PHON OKUDU) (MORPH TR)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM) (AGR 3S)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ACC))))))
(SEM (LAM X (LAM Y (("READ" X) Y)))) (PARAM 1.0))
((KEY 62) (PHON -DUGU) (MORPH COMP)
(SYN
((((BCAT S) (FEATS ((AGR ?A)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR ?A)))))
(DIR BS) (MODAL HARMONIC) ((BCAT IV) (FEATS ((AGR ?A))))))
(SEM (LAM P (LAM X (P X)))) (PARAM 1.0))
((KEY 63) (PHON -NU) (MORPH CASE)
(SYN
(((BCAT S) (FEATS ((CASE ACC)))) (DIR BS) (MODAL HARMONIC)
((BCAT S) (FEATS ((AGR 3S))))))
(SEM (LAM P P)) (PARAM 1.0))
((KEY 64) (PHON BIL) (MORPH TR)
(SYN
(((BCAT IV) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT S) (FEATS ((CASE ACC))))))
(SEM (LAM P (LAM X (("KNOW" P) X)))) (PARAM 1.0))
((KEY 65) (PHON -DIGIM) (MORPH REL)
(SYN
((((BCAT NP) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL HARMONIC)
(((BCAT S) (FEATS ((AGR 1S)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (LAM Q (LAM X (("AND" (P X)) (Q X)))))) (PARAM 1.0))
((KEY 66) (PHON KITAP) (MORPH N)
(SYN
(((BCAT NP) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT NP) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "BOOK"))) (PARAM 1.0))
((KEY 67) (PHON "O Paulo") (MORPH N) (SYN ((BCAT NP) (FEATS ((AGR 3S)))))
(SEM "PAUL") (PARAM 1.0))
((KEY 68) (PHON NAO) (MORPH NEG)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR ?A)))))
(DIR FS) (MODAL ALL)
(((BCAT S) (FEATS ((FOP P)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR ?A)))))))
(SEM (LAM P (LAM X ("NEG" (P X))))) (PARAM 1.0))
((KEY 69) (PHON OS) (MORPH PRO)
(SYN
((((BCAT S) (FEATS ((FOP P)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR ?A)))))
(DIR FS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR ?A)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((TYP PRO) (KIND PLU)))))))
(SEM (LAM P (P "THEM"))) (PARAM 1.0))
((KEY 70) (PHON VIU) (MORPH PT)
(SYN
((((BCAT S) (FEATS ((TENSE PAST)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR 3S)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("SEE" X) Y)))) (PARAM 1.0))
((KEY 71) (PHON HANKWUK-EY) (MORPH N) (SYN ((BCAT NP) (FEATS NIL)))
(SEM "KOREA") (PARAM 1.0))
((KEY 72) (PHON SEWUL-I) (MORPH N)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ?C))))))
(DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ?C))))))))
(SEM (LAM P ("SEUL" P))) (PARAM 1.0))
((KEY 73) (PHON NAMTAYMUN-SICANG-I) (MORPH N)
(SYN ((BCAT NP) (FEATS ((CASE NOM))))) (SEM "MARKET") (PARAM 1.0))
((KEY 74) (PHON PUL-I) (MORPH N) (SYN ((BCAT NP) (FEATS ((CASE NOM)))))
(SEM "FIRE") (PARAM 1.0))
((KEY 75) (PHON NA-ASS-TA) (MORPH KO)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ?C1)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ?C2)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NOM))))))
(SEM
(LAM X
(LAM Y (LAM Z (("AND" ((("BREAKOUT" Z) X) "ONE")) (("AT" Y) Z))))))
(PARAM 1.0))
((KEY 76) (PHON "bayi yara") (MORPH N)
(SYN ((BCAT NP) (FEATS ((CASE ABS))))) (SEM "MAN") (PARAM 1.0))
((KEY 77) (PHON NUMA-NGU) (MORPH N) (SYN ((BCAT NP) (FEATS ((ACSE ERG)))))
(SEM "FATHER") (PARAM 1.0))
((KEY 78) (PHON GIGA-N) (MORPH DY)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ERG)))))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS NIL))))
(SEM (LAM P (LAM Y (LAM X ((("TELL" (P X)) X) Y))))) (PARAM 1.0))
((KEY 79) (PHON GUBI-NGU) (MORPH N) (SYN ((BCAT NP) (FEATS ((CASE ERG)))))
(SEM "GUBI") (PARAM 1.0))
((KEY 80) (PHON MAWA-LI) (MORPH DY)
(SYN
(((BCAT VP) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG))))))
(SEM (LAM X (LAM Y (("EXAMINE" Y) X)))) (PARAM 1.0))
((KEY 81) (PHON BANAGA-NYU) (MORPH DY) (SYN ((BCAT VP) (FEATS NIL)))
(SEM (LAM X ("RETURN" X))) (PARAM 1.0))
((KEY 82) (PHON BAGUL) (MORPH CL)
(SYN
(((BCAT NP) (FEATS ((CASE DAT)))) (DIR FS) (MODAL ALL)
((BCAT N) (FEATS ((CASE DAT))))))
(SEM (LAM X ("CLASS1" X))) (PARAM 1.0))
((KEY 83) (PHON WANAL-GU) (MORPH N) (SYN ((BCAT N) (FEATS ((CASE DAT)))))
(SEM "BOOMERANG") (PARAM 1.0))
((KEY 84) (PHON BANUL-DIN-GU) (MORPH N)
(SYN
((((BCAT NP) (FEATS ((POSS GEN) (CASE DAT)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((POSS GEN) (CASE DAT)))))
(DIR FS) (MODAL ALL) ((BCAT N) (FEATS ((POSS GEN) (CASE DAT))))))
(SEM (LAM X (LAM Y (("OF" X) Y)))) (PARAM 1.0))
((KEY 85) (PHON YARA-NU-N-DIN-GU) (MORPH N)
(SYN ((BCAT N) (FEATS ((POSS GEN) (CASE DAT))))) (SEM "MAN") (PARAM 1.0))
((KEY 86) (PHON "bagul wanal-gu") (MORPH DY)
(SYN
(((BCAT NP) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE DAT))))))
(SEM (LAM X ("BOOMERANG" X))) (PARAM 1.0))
((KEY 87) (PHON M33KA55) (MORPH N) (SYN ((BCAT NP) (FEATS NIL)))
(SEM "MUGA") (PARAM 1.0))
((KEY 88) (PHON M33KO44) (MORPH N) (SYN ((BCAT NP) (FEATS NIL)))
(SEM "MUGO") (PARAM 1.0))
((KEY 89) (PHON NDU21) (MORPH NU)
(SYN
((((BCAT S) (FEATS ((TYP E)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("BEAT" Y) X)))) (PARAM 1.0))
((KEY 90) (PHON NDU21) (MORPH NU)
(SYN
((((BCAT S) (FEATS ((TYP A)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("BEAT" X) Y)))) (PARAM 1.0))
((KEY 91) (PHON NATEX-KAN-KE) (MORPH SH)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG) (AGR PLU)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ABS))))))
(SEM (LAM X (LAM Y (("BITE" X) Y)))) (PARAM 1.0))
((KEY 92) (PHON NATEX) (MORPH SH)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG) (AGR SING)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ABS))))))
(SEM (LAM X (LAM Y (("BITE" X) Y)))) (PARAM 1.0))
((KEY 93) (PHON MAWA-KAN-KE) (MORPH SH)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR PLU))))))
(SEM (LAM X ("DIE" X))) (PARAM 1.0))
((KEY 94) (PHON OCHITI-BAON-RA) (MORPH N)
(SYN ((BCAT NP) (FEATS ((CASE ERG) (AGR PLU) (MOD PRT))))) (SEM "DOGS")
(PARAM 1.0))
((KEY 95) (PHON BAKE) (MORPH N)
(SYN ((BCAT NP) (FEATS ((CASE ABS) (NUM SING))))) (SEM "CHILD")
(PARAM 1.0))
((KEY 96) (PHON JONI-BO-RA) (MORPH N)
(SYN ((BCAT NP) (FEATS ((CASE ABS) (AGR PLU) (MOD PRT))))) (SEM "PERSONS")
(PARAM 1.0))
((KEY 97) (PHON BAKE-BO) (MORPH N)
(SYN ((BCAT NP) (FEATS ((CASE ABS) (NUM PLU))))) (SEM "CHILDREN")
(PARAM 1.0))
((KEY 98) (PHON OCHITI-NIN-RA) (MORPH N)
(SYN ((BCAT NP) (FEATS ((CASE ERG) (AGR SING) (MOD PRT))))) (SEM "DOG")
(PARAM 1.0))
((KEY 99) (PHON "Dass sie kommt") (MORPH C)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT S) (FEATS ((TOP P)))))))
(SEM (LAM P (P ("COMES" "SHE")))) (PARAM 1.0))
((KEY 100) (PHON GLAUBT) (MORPH DE)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT S) (FEATS NIL))))
(SEM (LAM P (LAM X (("BELIEVE" P) X)))) (PARAM 1.0))
((KEY 101) (PHON ER) (MORPH PRO)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "HE"))) (PARAM 1.0))
((KEY 102) (PHON NICHT) (MORPH F)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL HARMONIC)
((BCAT S) (FEATS NIL))))
(SEM (LAM P ("NEG" P))) (PARAM 1.0))
((KEY 103) (PHON "Die Diplomarbeit") (MORPH N)
(SYN ((BCAT NP) (FEATS NIL))) (SEM "THE-MA") (PARAM 1.0))
((KEY 104) (PHON ZU) (MORPH C)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P P)) (PARAM 1.0))
((KEY 105) (PHON SCHREIBEN) (MORPH DE)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("WRITE" X) Y)))) (PARAM 1.0))
((KEY 106) (PHON HAT) (MORPH F)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P P)) (PARAM 1.0))
((KEY 107) (PHON "die Studentin") (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "STUDENT"))) (PARAM 1.0))
((KEY 108) (PHON GELANWEILT) (MORPH DE)
(SYN (((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT S) (FEATS NIL))))
(SEM (LAM P ("BORE" P))) (PARAM 1.0))
((KEY 109) (PHON JANOS) (MORPH N) (SYN ((BCAT NP) (FEATS ((AGR 3S)))))
(SEM "JOHN") (PARAM 1.0))
((KEY 110) (PHON LAT-T-A) (MORPH HU)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR 3S)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR 3S))))))
(SEM (LAM X (LAM Y (("SEE" X) Y)))) (PARAM 1.0))
((KEY 111) (PHON OT) (MORPH N)
(SYN ((BCAT NP) (FEATS ((AGR 3S) (TYP PRO))))) (SEM "HIM") (PARAM 1.0))
((KEY 112) (PHON LAT-OTT) (MORPH HU)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR 3S)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR 1S))))))
(SEM (LAM X (LAM Y (("SEE" X) Y)))) (PARAM 1.0))
((KEY 113) (PHON LAT-OTT) (MORPH HU)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR 3S)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR 2S))))))
(SEM (LAM X (LAM Y (("SEE" X) Y)))) (PARAM 1.0))
((KEY 114) (PHON ENGEM) (MORPH N) (SYN ((BCAT NP) (FEATS ((AGR 1S)))))
(SEM "ME") (PARAM 1.0)))) | |
d7c3ff3bb7ae181daecc1ef851cbfed08c91e4f18c19423b24982f7d6f478ae6 | armedbear/abcl | digest.lisp | Cryptographic message digest calculation with ABCL with different implementations .
;;;;
< >
;;;;
(in-package :cl-user)
;;; API
(defgeneric digest (url algorithim &optional (digest 'sha-256))
(:documentation "Digest byte based resource at URL with ALGORITHIM."))
(defun digest-path (path) (ascii-digest (digest path 'nio 'sha-256)))
(defvar *digest-types*
'((sha-1 . "SHA-1")
(sha-256 . "SHA-256")
(sha-512 . "SHA-512"))
"Normalization of cryptographic digest naming.")
;;; Implementation
(defconstant +byte-buffer-rewind+
(jmethod "java.nio.ByteBuffer" "rewind"))
(defconstant +byte-buffer-get+
(jmethod "java.nio.ByteBuffer" "get" "[B" "int" "int"))
(defconstant +digest-update+
(jmethod "java.security.MessageDigest" "update" "[B" "int" "int"))
(defmethod digest ((url t) (algorithim (eql 'nio)) &optional (digest 'sha-256))
"Calculate digest with default of :SHA-256 pathname specified by URL.
Returns an array of JVM primitive signed 8-bit bytes.
*DIGEST-TYPES* controls the allowable digest types."
(let* ((digest-type (cdr (assoc digest *digest-types*)))
(digest (jstatic "getInstance" "java.security.MessageDigest" digest-type))
(namestring (if (pathnamep url) (namestring url) url))
(file-input-stream (jnew "java.io.FileInputStream" namestring))
(channel (jcall "getChannel" file-input-stream))
(length 8192)
(buffer (jstatic "allocateDirect" "java.nio.ByteBuffer" length))
(array (jnew-array "byte" length)))
(do ((read (jcall "read" channel buffer)
(jcall "read" channel buffer)))
((not (> read 0)))
(jcall +byte-buffer-rewind+ buffer)
(jcall +byte-buffer-get+ buffer array 0 read)
(jcall +byte-buffer-rewind+ buffer)
(jcall +digest-update+ digest array 0 read))
(jcall "digest" digest)))
(defmethod digest ((url pathname) (algorithim (eql 'lisp)) &optional (digest 'sha-256))
"Compute digest of URL in Lisp where possible.
Currently much slower that using 'nio.
Needs ABCL svn > r13328."
(let* ((digest-type (cdr (assoc digest *digest-types*)))
(digest (jstatic "getInstance" "java.security.MessageDigest" digest-type))
(buffer (make-array 8192 :element-type '(unsigned-byte 8))))
(with-open-file (input url :element-type '(unsigned-byte 8))
(loop
:for
bytes = (read-sequence buffer input)
:while
(plusp bytes)
:do
(jcall-raw "update" digest
(jnew-array-from-array "byte" buffer) 0 bytes))
(jcall "digest" digest))))
(defun ascii-digest (digest)
(format nil "~{~X~}"
(mapcar (lambda (b) (if (< b 0) (+ 256 b) b))
(java::list-from-jarray digest))))
(defun benchmark (directory)
"For a given DIRECTORY containing a wildcard of files, run the benchmark tests."
(let (results)
(flet ((benchmark (task)
(let (start end result)
(psetf start (get-internal-run-time)
result (push (funcall task) result)
end (get-internal-run-time))
(nconc result (list start (- end start))))))
(dolist (entry (directory directory))
(let ((result
(list
(list 'nio (benchmark (lambda () (digest entry 'nio))))
(list 'lisp (benchmark (lambda () (digest entry 'lisp)))))))
(format t "~&~{~A~&~A~}" result)
(push result results))))))
;;; Deprecated
(setf (symbol-function 'digest-file-1) #'digest)
;;; Test
#|
(benchmark "/usr/local/bin/*") ;; unix
(benchmark "c:/*") ;; win32
|#
| null | https://raw.githubusercontent.com/armedbear/abcl/36a4b5994227d768882ff6458b3df9f79caac664/tools/digest.lisp | lisp |
API
Implementation
Deprecated
Test
(benchmark "/usr/local/bin/*") ;; unix
(benchmark "c:/*") ;; win32
| Cryptographic message digest calculation with ABCL with different implementations .
< >
(in-package :cl-user)
(defgeneric digest (url algorithim &optional (digest 'sha-256))
(:documentation "Digest byte based resource at URL with ALGORITHIM."))
(defun digest-path (path) (ascii-digest (digest path 'nio 'sha-256)))
(defvar *digest-types*
'((sha-1 . "SHA-1")
(sha-256 . "SHA-256")
(sha-512 . "SHA-512"))
"Normalization of cryptographic digest naming.")
(defconstant +byte-buffer-rewind+
(jmethod "java.nio.ByteBuffer" "rewind"))
(defconstant +byte-buffer-get+
(jmethod "java.nio.ByteBuffer" "get" "[B" "int" "int"))
(defconstant +digest-update+
(jmethod "java.security.MessageDigest" "update" "[B" "int" "int"))
(defmethod digest ((url t) (algorithim (eql 'nio)) &optional (digest 'sha-256))
"Calculate digest with default of :SHA-256 pathname specified by URL.
Returns an array of JVM primitive signed 8-bit bytes.
*DIGEST-TYPES* controls the allowable digest types."
(let* ((digest-type (cdr (assoc digest *digest-types*)))
(digest (jstatic "getInstance" "java.security.MessageDigest" digest-type))
(namestring (if (pathnamep url) (namestring url) url))
(file-input-stream (jnew "java.io.FileInputStream" namestring))
(channel (jcall "getChannel" file-input-stream))
(length 8192)
(buffer (jstatic "allocateDirect" "java.nio.ByteBuffer" length))
(array (jnew-array "byte" length)))
(do ((read (jcall "read" channel buffer)
(jcall "read" channel buffer)))
((not (> read 0)))
(jcall +byte-buffer-rewind+ buffer)
(jcall +byte-buffer-get+ buffer array 0 read)
(jcall +byte-buffer-rewind+ buffer)
(jcall +digest-update+ digest array 0 read))
(jcall "digest" digest)))
(defmethod digest ((url pathname) (algorithim (eql 'lisp)) &optional (digest 'sha-256))
"Compute digest of URL in Lisp where possible.
Currently much slower that using 'nio.
Needs ABCL svn > r13328."
(let* ((digest-type (cdr (assoc digest *digest-types*)))
(digest (jstatic "getInstance" "java.security.MessageDigest" digest-type))
(buffer (make-array 8192 :element-type '(unsigned-byte 8))))
(with-open-file (input url :element-type '(unsigned-byte 8))
(loop
:for
bytes = (read-sequence buffer input)
:while
(plusp bytes)
:do
(jcall-raw "update" digest
(jnew-array-from-array "byte" buffer) 0 bytes))
(jcall "digest" digest))))
(defun ascii-digest (digest)
(format nil "~{~X~}"
(mapcar (lambda (b) (if (< b 0) (+ 256 b) b))
(java::list-from-jarray digest))))
(defun benchmark (directory)
"For a given DIRECTORY containing a wildcard of files, run the benchmark tests."
(let (results)
(flet ((benchmark (task)
(let (start end result)
(psetf start (get-internal-run-time)
result (push (funcall task) result)
end (get-internal-run-time))
(nconc result (list start (- end start))))))
(dolist (entry (directory directory))
(let ((result
(list
(list 'nio (benchmark (lambda () (digest entry 'nio))))
(list 'lisp (benchmark (lambda () (digest entry 'lisp)))))))
(format t "~&~{~A~&~A~}" result)
(push result results))))))
(setf (symbol-function 'digest-file-1) #'digest)
|
7adf3df1737d52f35ae42c7b16419993da768e9b1cb33fdfbe4afedb89f6780e | inria-parkas/sundialsml | ark_reaction_diffusion_mri.ml | ------------------------------------------------------------------
* Programmer(s ): @ LLNL
* ------------------------------------------------------------------
* OCaml port : , , Aug 2020 .
* ------------------------------------------------------------------
* Based an example program by Rujeko Chinomona @ SMU .
* ------------------------------------------------------------------
* SUNDIALS Copyright Start
* Copyright ( c ) 2002 - 2019 , National Security
* and Southern Methodist University .
* All rights reserved .
*
* See the top - level LICENSE and NOTICE files for details .
*
* SPDX - License - Identifier : BSD-3 - Clause
* SUNDIALS Copyright End
* ------------------------------------------------------------------
* Example problem :
*
* The following test simulates a simple 1D reaction - diffusion
* equation ,
*
* y_t = k * y_xx + y^2 * ( 1 - y )
*
* for t in [ 0 , 3 ] , x in [ 0 , L ] with boundary conditions ,
*
* y_x(0,t ) = y_x(L , t ) = 0
*
* and initial condition ,
*
* y(x,0 ) = ( 1 + exp(lambda*(x-1))^(-1 ) ,
*
* with parameter k = 1e-4 / ep , lambda = 0.5*sqrt(2*ep*1e4 ) ,
* ep = 1e-2 , and L = 5 .
*
* The spatial derivatives are computed using second - order
* centered differences , with the data distributed over N points
* on a uniform spatial grid .
*
* This program solves the problem with the MRI stepper . Outputs are
* printed at equal intervals of 0.1 and run statistics are printed
* at the end .
* ----------------------------------------------------------------
* Programmer(s): David J. Gardner @ LLNL
* ------------------------------------------------------------------
* OCaml port: Timothy Bourke, Inria, Aug 2020.
* ------------------------------------------------------------------
* Based an example program by Rujeko Chinomona @ SMU.
* ------------------------------------------------------------------
* SUNDIALS Copyright Start
* Copyright (c) 2002-2019, Lawrence Livermore National Security
* and Southern Methodist University.
* All rights reserved.
*
* See the top-level LICENSE and NOTICE files for details.
*
* SPDX-License-Identifier: BSD-3-Clause
* SUNDIALS Copyright End
* ------------------------------------------------------------------
* Example problem:
*
* The following test simulates a simple 1D reaction-diffusion
* equation,
*
* y_t = k * y_xx + y^2 * (1-y)
*
* for t in [0, 3], x in [0, L] with boundary conditions,
*
* y_x(0,t) = y_x(L,t) = 0
*
* and initial condition,
*
* y(x,0) = (1 + exp(lambda*(x-1))^(-1),
*
* with parameter k = 1e-4/ep, lambda = 0.5*sqrt(2*ep*1e4),
* ep = 1e-2, and L = 5.
*
* The spatial derivatives are computed using second-order
* centered differences, with the data distributed over N points
* on a uniform spatial grid.
*
* This program solves the problem with the MRI stepper. Outputs are
* printed at equal intervals of 0.1 and run statistics are printed
* at the end.
* ----------------------------------------------------------------*)
open Sundials
module ARKStep = Arkode.ARKStep
module MRIStep = Arkode.MRIStep
let printf = Printf.printf
let fprintf = Printf.fprintf
(* ------------------------------
* Functions called by the solver
* ------------------------------*)
type userdata = {
n : int; (* number of intervals *)
k : float; (* diffusion coefficient *)
dx : float; (* mesh spacing *)
lam : float;
}
(* ff routine to compute the fast portion of the ODE RHS. *)
let ff { n } _ (y : RealArray.t) (ydot : RealArray.t) =
(* iterate over domain, computing reaction term *)
for i = 0 to n - 1 do
ydot.{i} <- y.{i} *. y.{i} *. (1.0 -. y.{i})
done
(* fs routine to compute the slow portion of the ODE RHS. *)
let fs { n; k; dx } _ (y : RealArray.t) (ydot : RealArray.t) =
(* iterate over domain, computing diffusion term *)
let c1 = k/.dx/.dx in
let c2 = 2.0*.k/.dx/.dx in
(* left boundary condition *)
ydot.{0} <- c2*.(y.{1} -. y.{0});
(* interior points *)
for i=1 to n-2 do
ydot.{i} <- c1*.y.{i-1} -. c2*.y.{i} +. c1*.y.{i+1}
done;
(* right boundary condition *)
ydot.{n-1} <- c2*.(y.{n-2} -. y.{n-1})
(* -----------------------------------------
* Private function to set initial condition
* -----------------------------------------*)
let set_initial_condition { n; dx; lam } y =
let y = Nvector_serial.unwrap y in
(* set initial condition *)
for i = 0 to n-1 do
y.{i} <- 1.0/.(1. +. exp(lam*.((float i)*.dx-.1.0)))
done
Main Program
let main () =
(* general problem parameters *)
let t0 = 0.0 in (* initial time *)
let tf = 3.0 in (* final time *)
let dTout = 0.1 in (* time between outputs *)
let nt = int_of_float(ceil(tf/.dTout)) in (* number of output times *)
let hs = 0.001 in (* slow step size *)
let hf = 0.00002 in (* fast step size *)
let l = 5.0 in (* domain length *)
let n = 1001 in (* number of mesh points *)
let ep = 1e-2 in
(*
* Initialization
*)
(* allocate and fill user data structure *)
let udata = {
n;
dx = l /. (float n -. 1.0);
k = 1e-4/.ep;
lam = 0.5*.sqrt(2.0 *. ep *. 1e4)
} in
(* Initial problem output *)
printf "\n1D reaction-diffusion PDE test problem:\n";
printf " N = %d\n" udata.n;
printf " diffusion coefficient: k = %g\n" udata.k;
(* Create and initialize serial vector for the solution *)
let y = Nvector_serial.make n 0. in (* Create serial vector for solution *)
set_initial_condition udata y;
Initialize the fast integrator . Specify the fast right - hand side
function in y'=fs(t , y)+ff(t , y ) , the inital time T0 , and the
initial dependent variable vector y.
function in y'=fs(t,y)+ff(t,y), the inital time T0, and the
initial dependent variable vector y. *)
let inner_arkode_mem = ARKStep.(init (explicit (ff udata)) default_tolerances t0 y) in
ARKStep.set_erk_table_num inner_arkode_mem
Arkode.ButcherTable.Knoth_Wolke_3_3;
ARKStep.set_fixed_step inner_arkode_mem (Some hf);
(* Call MRIStepCreate to initialize the MRI timestepper module and
specify the right-hand side function in y'=f(t,y), the inital time
T0, and the initial dependent variable vector y. Note: since this
problem is fully implicit, we set f_E to NULL and f_I to f. *)
Pass udata to user functions
(* Specify slow and fast step sizes *)
let arkode_mem = MRIStep.(init
(explicit (fs udata))
default_tolerances
InnerStepper.(from_arkstep inner_arkode_mem)
~slowstep:hs t0 y)
in
(* Increase max num steps *)
MRIStep.set_max_num_steps arkode_mem 10000;
(*
* Integrate ODE
*)
(* output mesh to disk *)
let fid = open_out "heat_mesh.txt" in
for i=0 to n-1 do
fprintf fid " %.16e\n" (udata.dx*.float i)
done;
(* Open output stream for results, access data array *)
let ufid = open_out "heat1D.txt" in
let data = Nvector_serial.unwrap y in
(* output initial condition to disk *)
for i=0 to n-1 do
fprintf ufid " %.16e" data.{i}
done;
fprintf ufid "\n";
(* Main time-stepping loop: calls MRIStepEvolve to perform the integration, then
prints results. Stops when the final time has been reached *)
printf " t ||u||_rms\n";
printf " -------------------------\n";
printf " %10.6f %10.6f\n" t0
(sqrt((Nvector_serial.Ops.dotprod y y)/.float n));
let dTout = (tf-.t0)/.(float nt) in
let rec loop iout tout =
if iout = nt then ()
else begin
(* call integrator *)
let t, _ = MRIStep.evolve_normal arkode_mem tout y in
(* print solution stats and output results to disk *)
printf " %10.6f %10.6f\n" t
(sqrt((Nvector_serial.Ops.dotprod y y)/.float n));
for i=0 to n-1 do
fprintf ufid " %.16e" data.{i}
done;
fprintf ufid "\n";
(* successful solve: update output time *)
loop (iout+1) (min (tout+.dTout) tf)
end
in
loop 0 (t0+.dTout);
printf " -------------------------\n";
(* Print some final statistics *)
let nsts = MRIStep.get_num_steps arkode_mem in
let nfse, _ = MRIStep.get_num_rhs_evals arkode_mem in
let nstf = ARKStep.get_num_steps inner_arkode_mem in
let nff, _ = ARKStep.get_num_rhs_evals inner_arkode_mem in
printf "\nFinal Solver Statistics:\n";
printf " Steps: nsts = %d, nstf = %d\n" nsts nstf;
printf " Total RHS evals: Fs = %d, Ff = %d\n" nfse nff
(* Check environment variables for extra arguments. *)
let reps =
try int_of_string (Unix.getenv "NUM_REPS")
with Not_found | Failure _ -> 1
let gc_at_end =
try int_of_string (Unix.getenv "GC_AT_END") <> 0
with Not_found | Failure _ -> false
let gc_each_rep =
try int_of_string (Unix.getenv "GC_EACH_REP") <> 0
with Not_found | Failure _ -> false
(* Entry point *)
let _ =
for _ = 1 to reps do
main ();
if gc_each_rep then Gc.compact ()
done;
if gc_at_end then Gc.compact ()
| null | https://raw.githubusercontent.com/inria-parkas/sundialsml/a72ebfc84b55470ed97fbb0b45d700deebfc1664/examples/arkode/C_serial/ark_reaction_diffusion_mri.ml | ocaml | ------------------------------
* Functions called by the solver
* ------------------------------
number of intervals
diffusion coefficient
mesh spacing
ff routine to compute the fast portion of the ODE RHS.
iterate over domain, computing reaction term
fs routine to compute the slow portion of the ODE RHS.
iterate over domain, computing diffusion term
left boundary condition
interior points
right boundary condition
-----------------------------------------
* Private function to set initial condition
* -----------------------------------------
set initial condition
general problem parameters
initial time
final time
time between outputs
number of output times
slow step size
fast step size
domain length
number of mesh points
* Initialization
allocate and fill user data structure
Initial problem output
Create and initialize serial vector for the solution
Create serial vector for solution
Call MRIStepCreate to initialize the MRI timestepper module and
specify the right-hand side function in y'=f(t,y), the inital time
T0, and the initial dependent variable vector y. Note: since this
problem is fully implicit, we set f_E to NULL and f_I to f.
Specify slow and fast step sizes
Increase max num steps
* Integrate ODE
output mesh to disk
Open output stream for results, access data array
output initial condition to disk
Main time-stepping loop: calls MRIStepEvolve to perform the integration, then
prints results. Stops when the final time has been reached
call integrator
print solution stats and output results to disk
successful solve: update output time
Print some final statistics
Check environment variables for extra arguments.
Entry point | ------------------------------------------------------------------
* Programmer(s ): @ LLNL
* ------------------------------------------------------------------
* OCaml port : , , Aug 2020 .
* ------------------------------------------------------------------
* Based an example program by Rujeko Chinomona @ SMU .
* ------------------------------------------------------------------
* SUNDIALS Copyright Start
* Copyright ( c ) 2002 - 2019 , National Security
* and Southern Methodist University .
* All rights reserved .
*
* See the top - level LICENSE and NOTICE files for details .
*
* SPDX - License - Identifier : BSD-3 - Clause
* SUNDIALS Copyright End
* ------------------------------------------------------------------
* Example problem :
*
* The following test simulates a simple 1D reaction - diffusion
* equation ,
*
* y_t = k * y_xx + y^2 * ( 1 - y )
*
* for t in [ 0 , 3 ] , x in [ 0 , L ] with boundary conditions ,
*
* y_x(0,t ) = y_x(L , t ) = 0
*
* and initial condition ,
*
* y(x,0 ) = ( 1 + exp(lambda*(x-1))^(-1 ) ,
*
* with parameter k = 1e-4 / ep , lambda = 0.5*sqrt(2*ep*1e4 ) ,
* ep = 1e-2 , and L = 5 .
*
* The spatial derivatives are computed using second - order
* centered differences , with the data distributed over N points
* on a uniform spatial grid .
*
* This program solves the problem with the MRI stepper . Outputs are
* printed at equal intervals of 0.1 and run statistics are printed
* at the end .
* ----------------------------------------------------------------
* Programmer(s): David J. Gardner @ LLNL
* ------------------------------------------------------------------
* OCaml port: Timothy Bourke, Inria, Aug 2020.
* ------------------------------------------------------------------
* Based an example program by Rujeko Chinomona @ SMU.
* ------------------------------------------------------------------
* SUNDIALS Copyright Start
* Copyright (c) 2002-2019, Lawrence Livermore National Security
* and Southern Methodist University.
* All rights reserved.
*
* See the top-level LICENSE and NOTICE files for details.
*
* SPDX-License-Identifier: BSD-3-Clause
* SUNDIALS Copyright End
* ------------------------------------------------------------------
* Example problem:
*
* The following test simulates a simple 1D reaction-diffusion
* equation,
*
* y_t = k * y_xx + y^2 * (1-y)
*
* for t in [0, 3], x in [0, L] with boundary conditions,
*
* y_x(0,t) = y_x(L,t) = 0
*
* and initial condition,
*
* y(x,0) = (1 + exp(lambda*(x-1))^(-1),
*
* with parameter k = 1e-4/ep, lambda = 0.5*sqrt(2*ep*1e4),
* ep = 1e-2, and L = 5.
*
* The spatial derivatives are computed using second-order
* centered differences, with the data distributed over N points
* on a uniform spatial grid.
*
* This program solves the problem with the MRI stepper. Outputs are
* printed at equal intervals of 0.1 and run statistics are printed
* at the end.
* ----------------------------------------------------------------*)
open Sundials
module ARKStep = Arkode.ARKStep
module MRIStep = Arkode.MRIStep
let printf = Printf.printf
let fprintf = Printf.fprintf
type userdata = {
lam : float;
}
let ff { n } _ (y : RealArray.t) (ydot : RealArray.t) =
for i = 0 to n - 1 do
ydot.{i} <- y.{i} *. y.{i} *. (1.0 -. y.{i})
done
let fs { n; k; dx } _ (y : RealArray.t) (ydot : RealArray.t) =
let c1 = k/.dx/.dx in
let c2 = 2.0*.k/.dx/.dx in
ydot.{0} <- c2*.(y.{1} -. y.{0});
for i=1 to n-2 do
ydot.{i} <- c1*.y.{i-1} -. c2*.y.{i} +. c1*.y.{i+1}
done;
ydot.{n-1} <- c2*.(y.{n-2} -. y.{n-1})
let set_initial_condition { n; dx; lam } y =
let y = Nvector_serial.unwrap y in
for i = 0 to n-1 do
y.{i} <- 1.0/.(1. +. exp(lam*.((float i)*.dx-.1.0)))
done
Main Program
let main () =
let ep = 1e-2 in
let udata = {
n;
dx = l /. (float n -. 1.0);
k = 1e-4/.ep;
lam = 0.5*.sqrt(2.0 *. ep *. 1e4)
} in
printf "\n1D reaction-diffusion PDE test problem:\n";
printf " N = %d\n" udata.n;
printf " diffusion coefficient: k = %g\n" udata.k;
set_initial_condition udata y;
Initialize the fast integrator . Specify the fast right - hand side
function in y'=fs(t , y)+ff(t , y ) , the inital time T0 , and the
initial dependent variable vector y.
function in y'=fs(t,y)+ff(t,y), the inital time T0, and the
initial dependent variable vector y. *)
let inner_arkode_mem = ARKStep.(init (explicit (ff udata)) default_tolerances t0 y) in
ARKStep.set_erk_table_num inner_arkode_mem
Arkode.ButcherTable.Knoth_Wolke_3_3;
ARKStep.set_fixed_step inner_arkode_mem (Some hf);
Pass udata to user functions
let arkode_mem = MRIStep.(init
(explicit (fs udata))
default_tolerances
InnerStepper.(from_arkstep inner_arkode_mem)
~slowstep:hs t0 y)
in
MRIStep.set_max_num_steps arkode_mem 10000;
let fid = open_out "heat_mesh.txt" in
for i=0 to n-1 do
fprintf fid " %.16e\n" (udata.dx*.float i)
done;
let ufid = open_out "heat1D.txt" in
let data = Nvector_serial.unwrap y in
for i=0 to n-1 do
fprintf ufid " %.16e" data.{i}
done;
fprintf ufid "\n";
printf " t ||u||_rms\n";
printf " -------------------------\n";
printf " %10.6f %10.6f\n" t0
(sqrt((Nvector_serial.Ops.dotprod y y)/.float n));
let dTout = (tf-.t0)/.(float nt) in
let rec loop iout tout =
if iout = nt then ()
else begin
let t, _ = MRIStep.evolve_normal arkode_mem tout y in
printf " %10.6f %10.6f\n" t
(sqrt((Nvector_serial.Ops.dotprod y y)/.float n));
for i=0 to n-1 do
fprintf ufid " %.16e" data.{i}
done;
fprintf ufid "\n";
loop (iout+1) (min (tout+.dTout) tf)
end
in
loop 0 (t0+.dTout);
printf " -------------------------\n";
let nsts = MRIStep.get_num_steps arkode_mem in
let nfse, _ = MRIStep.get_num_rhs_evals arkode_mem in
let nstf = ARKStep.get_num_steps inner_arkode_mem in
let nff, _ = ARKStep.get_num_rhs_evals inner_arkode_mem in
printf "\nFinal Solver Statistics:\n";
printf " Steps: nsts = %d, nstf = %d\n" nsts nstf;
printf " Total RHS evals: Fs = %d, Ff = %d\n" nfse nff
let reps =
try int_of_string (Unix.getenv "NUM_REPS")
with Not_found | Failure _ -> 1
let gc_at_end =
try int_of_string (Unix.getenv "GC_AT_END") <> 0
with Not_found | Failure _ -> false
let gc_each_rep =
try int_of_string (Unix.getenv "GC_EACH_REP") <> 0
with Not_found | Failure _ -> false
let _ =
for _ = 1 to reps do
main ();
if gc_each_rep then Gc.compact ()
done;
if gc_at_end then Gc.compact ()
|
c5e58bb64c6aa8df49d02e775e1b5ad324e985c2bbe23fbf2cfed90e5f3312c3 | scymtym/trivial-with-current-source-form | unsupported.lisp | ;;;; unsupported.lisp --- Compatibility for unsupported implementations.
;;;;
Copyright ( C ) 2020 Jan Moringen
;;;;
Author : < >
(cl:in-package #:trivial-with-current-source-form)
(defun expand (forms body)
(declare (ignore forms))
`(progn ,@body))
| null | https://raw.githubusercontent.com/scymtym/trivial-with-current-source-form/198fdc9193c6c8bc43fad2ad7562603d11194c6d/code/unsupported.lisp | lisp | unsupported.lisp --- Compatibility for unsupported implementations.
| Copyright ( C ) 2020 Jan Moringen
Author : < >
(cl:in-package #:trivial-with-current-source-form)
(defun expand (forms body)
(declare (ignore forms))
`(progn ,@body))
|
b04ab4f7aa0b492705dfbe2820ea72f106350a6536346127ad0da375ddd76880 | gilith/hol-light | inferpsign_thms.ml | let EVEN_DIV_LEM = prove_by_refinement(
`!set p q c d a n.
(!x. a pow n * p x = c x * q x + d x) ==>
a <> &0 ==>
EVEN n ==>
((interpsign set q Zero) ==>
(interpsign set d Neg) ==>
(interpsign set p Neg)) /\
((interpsign set q Zero) ==>
(interpsign set d Pos) ==>
(interpsign set p Pos)) /\
((interpsign set q Zero) ==>
(interpsign set d Zero) ==>
(interpsign set p Zero))`,
(* {{{ Proof *)
[
REWRITE_TAC[interpsign];
REPEAT STRIP_TAC;
RULE_ASSUM_TAC (fun y -> try ISPEC `x:real` y with _ -> y);
POP_ASSUM (fun x -> REWRITE_ASSUMS[x]);
POP_ASSUM MP_TAC;
POP_ASSUM (fun x -> REWRITE_ASSUMS[x;REAL_MUL_RZERO;REAL_ADD_LID;]);
STRIP_TAC;
CLAIM `&0 < a pow n`;
ASM_MESON_TAC[EVEN_ODD_POW;real_gt];
STRIP_TAC;
CLAIM `a pow n * p x < &0`;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
REWRITE_TAC[REAL_MUL_LT];
REPEAT STRIP_TAC;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
RULE_ASSUM_TAC (fun y -> try ISPEC `x:real` y with _ -> y);
POP_ASSUM (fun x -> REWRITE_ASSUMS[x]);
POP_ASSUM MP_TAC;
POP_ASSUM (fun x -> REWRITE_ASSUMS[x;REAL_MUL_RZERO;REAL_ADD_LID;]);
STRIP_TAC;
CLAIM `&0 < a pow n`;
ASM_MESON_TAC[EVEN_ODD_POW;real_gt];
STRIP_TAC;
CLAIM `a pow n * p x > &0`;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
REWRITE_TAC[REAL_MUL_LT;REAL_MUL_GT;real_gt];
REPEAT STRIP_TAC;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
RULE_ASSUM_TAC (fun y -> try ISPEC `x:real` y with _ -> y);
POP_ASSUM (fun x -> REWRITE_ASSUMS[x]);
POP_ASSUM MP_TAC;
POP_ASSUM (fun x -> REWRITE_ASSUMS[x;REAL_MUL_RZERO;REAL_ADD_LID;]);
STRIP_TAC;
CLAIM `&0 < a pow n`;
ASM_MESON_TAC[EVEN_ODD_POW;real_gt];
STRIP_TAC;
CLAIM `a pow n * p x = &0`;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
REWRITE_TAC[REAL_MUL_LT;REAL_MUL_GT;real_gt];
REPEAT STRIP_TAC;
ASM_MESON_TAC[REAL_ENTIRE;REAL_LT_IMP_NZ];
]);;
(* }}} *)
let GT_DIV_LEM = prove_by_refinement(
`!set p q c d a n.
(!x. a pow n * p x = c x * q x + d x) ==>
a > &0 ==>
((interpsign set q Zero) ==>
(interpsign set d Neg) ==>
(interpsign set p Neg)) /\
((interpsign set q Zero) ==>
(interpsign set d Pos) ==>
(interpsign set p Pos)) /\
((interpsign set q Zero) ==>
(interpsign set d Zero) ==>
(interpsign set p Zero))`,
(* {{{ Proof *)
[
REWRITE_TAC[interpsign];
REPEAT_N 9 STRIP_TAC;
CLAIM `a pow n > &0`;
ASM_MESON_TAC[REAL_POW_LT;real_gt;];
STRIP_TAC;
REPEAT STRIP_TAC;
RULE_ASSUM_TAC (fun y -> try ISPEC `x:real` y with _ -> y);
POP_ASSUM (fun x -> REWRITE_ASSUMS[x]);
POP_ASSUM MP_TAC;
POP_ASSUM (fun x -> REWRITE_ASSUMS[x;REAL_MUL_RZERO;REAL_ADD_LID;]);
STRIP_TAC;
CLAIM `a pow n * p x < &0`;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
REWRITE_TAC[REAL_MUL_LT];
REPEAT STRIP_TAC;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
(* save *)
RULE_ASSUM_TAC (fun y -> try ISPEC `x:real` y with _ -> y);
POP_ASSUM (fun x -> REWRITE_ASSUMS[x]);
POP_ASSUM MP_TAC;
POP_ASSUM (fun x -> REWRITE_ASSUMS[x;REAL_MUL_RZERO;REAL_ADD_LID;]);
STRIP_TAC;
CLAIM `a pow n * p x > &0`;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
REWRITE_TAC[REAL_MUL_GT;real_gt];
REPEAT STRIP_TAC;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
RULE_ASSUM_TAC (fun y -> try ISPEC `x:real` y with _ -> y);
POP_ASSUM (fun x -> REWRITE_ASSUMS[x]);
POP_ASSUM MP_TAC;
POP_ASSUM (fun x -> REWRITE_ASSUMS[x;REAL_MUL_RZERO;REAL_ADD_LID;]);
STRIP_TAC;
CLAIM `a pow n * p x = &0`;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
ASM_MESON_TAC[REAL_ENTIRE;REAL_NOT_EQ;real_gt];
]);;
(* }}} *)
let NEG_ODD_LEM = prove_by_refinement(
`!set p q c d a n.
(!x. a pow n * p x = c x * q x + d x) ==>
a < &0 ==>
ODD n ==>
((interpsign set q Zero) ==>
(interpsign set (\x. -- d x) Neg) ==>
(interpsign set p Neg)) /\
((interpsign set q Zero) ==>
(interpsign set (\x. -- d x) Pos) ==>
(interpsign set p Pos)) /\
((interpsign set q Zero) ==>
(interpsign set (\x. -- d x) Zero) ==>
(interpsign set p Zero))`,
(* {{{ Proof *)
[
REWRITE_TAC[interpsign;POLY_NEG];
REPEAT_N 10 STRIP_TAC;
CLAIM `a pow n < &0`;
ASM_MESON_TAC[PARITY_POW_LT;real_gt;];
STRIP_TAC;
REAL_SIMP_TAC;
REPEAT STRIP_TAC;
RULE_ASSUM_TAC (fun y -> try ISPEC `x:real` y with _ -> y);
POP_ASSUM (fun x -> REWRITE_ASSUMS[x]);
POP_ASSUM MP_TAC;
POP_ASSUM (fun x -> REWRITE_ASSUMS[x;REAL_MUL_RZERO;REAL_ADD_LID;]);
STRIP_TAC;
CLAIM `a pow n * p x > &0`;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
REWRITE_TAC[REAL_MUL_LT;REAL_MUL_GT;real_gt];
REPEAT STRIP_TAC;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
(* save *)
RULE_ASSUM_TAC (fun y -> try ISPEC `x:real` y with _ -> y);
POP_ASSUM (fun x -> REWRITE_ASSUMS[x]);
POP_ASSUM MP_TAC;
POP_ASSUM (fun x -> REWRITE_ASSUMS[x;REAL_MUL_RZERO;REAL_ADD_LID;]);
STRIP_TAC;
CLAIM `a pow n * p x < &0`;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
REWRITE_TAC[REAL_MUL_LT;REAL_MUL_GT;real_gt];
REPEAT STRIP_TAC;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
RULE_ASSUM_TAC (fun y -> try ISPEC `x:real` y with _ -> y);
POP_ASSUM (fun x -> REWRITE_ASSUMS[x]);
POP_ASSUM MP_TAC;
POP_ASSUM (fun x -> REWRITE_ASSUMS[x;REAL_MUL_RZERO;REAL_ADD_LID;]);
STRIP_TAC;
CLAIM `a pow n * p x = &0`;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
ASM_MESON_TAC[REAL_ENTIRE;REAL_NOT_EQ;real_gt];
]);;
(* }}} *)
let NEQ_ODD_LEM = prove_by_refinement(
`!set p q c d a n.
(!x. a pow n * p x = c x * q x + d x) ==>
a <> &0 ==>
ODD n ==>
((interpsign set q Zero) ==>
(interpsign set (\x. a * d x) Neg) ==>
(interpsign set p Neg)) /\
((interpsign set q Zero) ==>
(interpsign set (\x. a * d x) Pos) ==>
(interpsign set p Pos)) /\
((interpsign set q Zero) ==>
(interpsign set (\x. a * d x) Zero) ==>
(interpsign set p Zero))`,
(* {{{ Proof *)
[
REWRITE_TAC[interpsign;POLY_CMUL];
REPEAT_N 10 STRIP_TAC;
CLAIM `a < &0 \/ a > &0 \/ (a = &0)`;
REAL_ARITH_TAC;
REWRITE_ASSUMS[NEQ];
ASM_REWRITE_TAC[];
LABEL_ALL_TAC;
STRIP_TAC;
(* save *)
CLAIM `a pow n < &0`;
ASM_MESON_TAC[PARITY_POW_LT];
STRIP_TAC;
REPEAT STRIP_TAC;
RULE_ASSUM_TAC (fun y -> try ISPEC `x:real` y with _ -> y);
POP_ASSUM (fun x -> REWRITE_ASSUMS[x]);
POP_ASSUM MP_TAC;
POP_ASSUM (fun x -> REWRITE_ASSUMS[x;REAL_MUL_RZERO;REAL_ADD_LID;]);
STRIP_TAC;
CLAIM `d x > &0`;
POP_ASSUM MP_TAC;
ASM_REWRITE_TAC[real_gt;REAL_MUL_LT];
REPEAT STRIP_TAC;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
REWRITE_TAC[REAL_MUL_LT;REAL_MUL_GT;real_gt];
REPEAT STRIP_TAC;
POP_ASSUM MP_TAC;
POP_ASSUM MP_TAC;
REWRITE_TAC[REAL_MUL_LT];
REPEAT STRIP_TAC;
CLAIM `&0 < a pow n * p x`;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
REWRITE_TAC[REAL_MUL_GT];
REPEAT STRIP_TAC;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
(* save *)
RULE_ASSUM_TAC (fun y -> try ISPEC `x:real` y with _ -> y);
POP_ASSUM (fun x -> REWRITE_ASSUMS[x]);
POP_ASSUM MP_TAC;
POP_ASSUM (fun x -> REWRITE_ASSUMS[x;REAL_MUL_RZERO;REAL_ADD_LID;]);
STRIP_TAC;
CLAIM `d x < &0`;
POP_ASSUM MP_TAC;
REWRITE_TAC[REAL_MUL_GT;real_gt];
REPEAT STRIP_TAC;
CLAIM `a pow n * p x < &0`;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
REWRITE_TAC[REAL_MUL_LT;REAL_MUL_GT;real_gt];
REPEAT STRIP_TAC;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
STRIP_TAC;
CLAIM `a pow n * p x < &0`;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
REWRITE_TAC[REAL_MUL_LT;REAL_MUL_GT;real_gt];
REPEAT STRIP_TAC;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
RULE_ASSUM_TAC (fun y -> try ISPEC `x:real` y with _ -> y);
POP_ASSUM (fun x -> REWRITE_ASSUMS[x]);
POP_ASSUM MP_TAC;
POP_ASSUM (fun x -> REWRITE_ASSUMS[x;REAL_MUL_RZERO;REAL_ADD_LID;]);
STRIP_TAC;
CLAIM `d x = &0`;
ASM_MESON_TAC[REAL_ENTIRE;REAL_NOT_EQ;real_gt];
STRIP_TAC;
CLAIM `a pow n * p x = &0`;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
ASM_MESON_TAC[REAL_ENTIRE;REAL_NOT_EQ;real_gt];
(* save *)
CLAIM `a pow n > &0`;
ASM_MESON_TAC[EVEN_ODD_POW;NEQ;real_gt];
STRIP_TAC;
REPEAT STRIP_TAC;
RULE_ASSUM_TAC (fun y -> try ISPEC `x:real` y with _ -> y);
POP_ASSUM (fun x -> REWRITE_ASSUMS[x]);
POP_ASSUM MP_TAC;
POP_ASSUM (fun x -> REWRITE_ASSUMS[x;REAL_MUL_RZERO;REAL_ADD_LID;]);
STRIP_TAC;
CLAIM `d x < &0`;
POP_ASSUM MP_TAC;
ASM_REWRITE_TAC[real_gt;REAL_MUL_LT];
REPEAT STRIP_TAC;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
REWRITE_TAC[REAL_MUL_LT;REAL_MUL_GT;real_gt];
REPEAT STRIP_TAC;
POP_ASSUM MP_TAC;
POP_ASSUM MP_TAC;
REWRITE_TAC[REAL_MUL_LT];
REPEAT STRIP_TAC;
CLAIM `a pow n * p x < &0`;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
REWRITE_TAC[REAL_MUL_LT;REAL_MUL_GT;real_gt];
REPEAT STRIP_TAC;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
CLAIM `a pow n * p x < &0`;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
REWRITE_TAC[REAL_MUL_LT;REAL_MUL_GT;real_gt];
REPEAT STRIP_TAC;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
(* save *)
RULE_ASSUM_TAC (fun y -> try ISPEC `x:real` y with _ -> y);
POP_ASSUM (fun x -> REWRITE_ASSUMS[x]);
POP_ASSUM MP_TAC;
POP_ASSUM (fun x -> REWRITE_ASSUMS[x;REAL_MUL_RZERO;REAL_ADD_LID;]);
STRIP_TAC;
CLAIM `d x > &0`;
POP_ASSUM MP_TAC;
REWRITE_TAC[REAL_MUL_GT;real_gt];
REPEAT STRIP_TAC;
CLAIM `a pow n * p x < &0`;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
REWRITE_TAC[REAL_MUL_LT;REAL_MUL_GT;real_gt];
REPEAT STRIP_TAC;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
STRIP_TAC;
CLAIM `a pow n * p x > &0`;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
REWRITE_TAC[REAL_MUL_LT;REAL_MUL_GT;real_gt];
REPEAT STRIP_TAC;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
RULE_ASSUM_TAC (fun y -> try ISPEC `x:real` y with _ -> y);
POP_ASSUM (fun x -> REWRITE_ASSUMS[x]);
POP_ASSUM MP_TAC;
POP_ASSUM (fun x -> REWRITE_ASSUMS[x;REAL_MUL_RZERO;REAL_ADD_LID;]);
STRIP_TAC;
CLAIM `d x = &0`;
ASM_MESON_TAC[REAL_ENTIRE;REAL_NOT_EQ;real_gt];
STRIP_TAC;
CLAIM `a pow n * p x = &0`;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
ASM_MESON_TAC[REAL_ENTIRE;REAL_NOT_EQ;real_gt];
]);;
(* }}} *)
let NEQ_MULT_LT_LEM = prove_by_refinement(
`!a q d d' set.
a < &0 ==>
((interpsign set d Neg) ==>
(interpsign set (\x. a * d x) Pos)) /\
((interpsign set d Pos) ==>
(interpsign set (\x. a * d x) Neg)) /\
((interpsign set d Zero) ==>
(interpsign set (\x. a * d x) Zero))`,
(* {{{ Proof *)
[
REWRITE_TAC[interpsign;POLY_NEG];
REPEAT STRIP_TAC;
ASM_MESON_TAC[REAL_MUL_GT;real_gt];
ASM_MESON_TAC[REAL_MUL_LT;real_gt];
ASM_MESON_TAC[REAL_ENTIRE;REAL_NOT_EQ;real_gt];
]);;
(* }}} *)
let NEQ_MULT_GT_LEM = prove_by_refinement(
`!a q d d' set.
a > &0 ==>
((interpsign set d Neg) ==>
(interpsign set (\x. a * d x) Neg)) /\
((interpsign set d Pos) ==>
(interpsign set (\x. a * d x) Pos)) /\
((interpsign set d Zero) ==>
(interpsign set (\x. a * d x) Zero))`,
(* {{{ Proof *)
[
REWRITE_TAC[interpsign;POLY_NEG] THEN
MESON_TAC[REAL_MUL_LT;REAL_ENTIRE;REAL_NOT_EQ;REAL_MUL_GT;real_gt];
]);;
(* }}} *)
let unknown_thm = prove(
`!set p. (interpsign set p Unknown)`,
MESON_TAC[interpsign]);;
let ips_gt_nz_thm = prove_by_refinement(
`!x. x > &0 ==> x <> &0`,
(* {{{ Proof *)
[
REWRITE_TAC[NEQ];
REAL_ARITH_TAC;
]);;
(* }}} *)
let ips_lt_nz_thm = prove_by_refinement(
`!x. x < &0 ==> x <> &0`,
(* {{{ Proof *)
[
REWRITE_TAC[NEQ];
REAL_ARITH_TAC;
]);;
(* }}} *)
| null | https://raw.githubusercontent.com/gilith/hol-light/f3f131963f2298b4d65ee5fead6e986a4a14237a/Rqe/inferpsign_thms.ml | ocaml | {{{ Proof
}}}
{{{ Proof
save
}}}
{{{ Proof
save
}}}
{{{ Proof
save
save
save
save
}}}
{{{ Proof
}}}
{{{ Proof
}}}
{{{ Proof
}}}
{{{ Proof
}}} | let EVEN_DIV_LEM = prove_by_refinement(
`!set p q c d a n.
(!x. a pow n * p x = c x * q x + d x) ==>
a <> &0 ==>
EVEN n ==>
((interpsign set q Zero) ==>
(interpsign set d Neg) ==>
(interpsign set p Neg)) /\
((interpsign set q Zero) ==>
(interpsign set d Pos) ==>
(interpsign set p Pos)) /\
((interpsign set q Zero) ==>
(interpsign set d Zero) ==>
(interpsign set p Zero))`,
[
REWRITE_TAC[interpsign];
REPEAT STRIP_TAC;
RULE_ASSUM_TAC (fun y -> try ISPEC `x:real` y with _ -> y);
POP_ASSUM (fun x -> REWRITE_ASSUMS[x]);
POP_ASSUM MP_TAC;
POP_ASSUM (fun x -> REWRITE_ASSUMS[x;REAL_MUL_RZERO;REAL_ADD_LID;]);
STRIP_TAC;
CLAIM `&0 < a pow n`;
ASM_MESON_TAC[EVEN_ODD_POW;real_gt];
STRIP_TAC;
CLAIM `a pow n * p x < &0`;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
REWRITE_TAC[REAL_MUL_LT];
REPEAT STRIP_TAC;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
RULE_ASSUM_TAC (fun y -> try ISPEC `x:real` y with _ -> y);
POP_ASSUM (fun x -> REWRITE_ASSUMS[x]);
POP_ASSUM MP_TAC;
POP_ASSUM (fun x -> REWRITE_ASSUMS[x;REAL_MUL_RZERO;REAL_ADD_LID;]);
STRIP_TAC;
CLAIM `&0 < a pow n`;
ASM_MESON_TAC[EVEN_ODD_POW;real_gt];
STRIP_TAC;
CLAIM `a pow n * p x > &0`;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
REWRITE_TAC[REAL_MUL_LT;REAL_MUL_GT;real_gt];
REPEAT STRIP_TAC;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
RULE_ASSUM_TAC (fun y -> try ISPEC `x:real` y with _ -> y);
POP_ASSUM (fun x -> REWRITE_ASSUMS[x]);
POP_ASSUM MP_TAC;
POP_ASSUM (fun x -> REWRITE_ASSUMS[x;REAL_MUL_RZERO;REAL_ADD_LID;]);
STRIP_TAC;
CLAIM `&0 < a pow n`;
ASM_MESON_TAC[EVEN_ODD_POW;real_gt];
STRIP_TAC;
CLAIM `a pow n * p x = &0`;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
REWRITE_TAC[REAL_MUL_LT;REAL_MUL_GT;real_gt];
REPEAT STRIP_TAC;
ASM_MESON_TAC[REAL_ENTIRE;REAL_LT_IMP_NZ];
]);;
let GT_DIV_LEM = prove_by_refinement(
`!set p q c d a n.
(!x. a pow n * p x = c x * q x + d x) ==>
a > &0 ==>
((interpsign set q Zero) ==>
(interpsign set d Neg) ==>
(interpsign set p Neg)) /\
((interpsign set q Zero) ==>
(interpsign set d Pos) ==>
(interpsign set p Pos)) /\
((interpsign set q Zero) ==>
(interpsign set d Zero) ==>
(interpsign set p Zero))`,
[
REWRITE_TAC[interpsign];
REPEAT_N 9 STRIP_TAC;
CLAIM `a pow n > &0`;
ASM_MESON_TAC[REAL_POW_LT;real_gt;];
STRIP_TAC;
REPEAT STRIP_TAC;
RULE_ASSUM_TAC (fun y -> try ISPEC `x:real` y with _ -> y);
POP_ASSUM (fun x -> REWRITE_ASSUMS[x]);
POP_ASSUM MP_TAC;
POP_ASSUM (fun x -> REWRITE_ASSUMS[x;REAL_MUL_RZERO;REAL_ADD_LID;]);
STRIP_TAC;
CLAIM `a pow n * p x < &0`;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
REWRITE_TAC[REAL_MUL_LT];
REPEAT STRIP_TAC;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
RULE_ASSUM_TAC (fun y -> try ISPEC `x:real` y with _ -> y);
POP_ASSUM (fun x -> REWRITE_ASSUMS[x]);
POP_ASSUM MP_TAC;
POP_ASSUM (fun x -> REWRITE_ASSUMS[x;REAL_MUL_RZERO;REAL_ADD_LID;]);
STRIP_TAC;
CLAIM `a pow n * p x > &0`;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
REWRITE_TAC[REAL_MUL_GT;real_gt];
REPEAT STRIP_TAC;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
RULE_ASSUM_TAC (fun y -> try ISPEC `x:real` y with _ -> y);
POP_ASSUM (fun x -> REWRITE_ASSUMS[x]);
POP_ASSUM MP_TAC;
POP_ASSUM (fun x -> REWRITE_ASSUMS[x;REAL_MUL_RZERO;REAL_ADD_LID;]);
STRIP_TAC;
CLAIM `a pow n * p x = &0`;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
ASM_MESON_TAC[REAL_ENTIRE;REAL_NOT_EQ;real_gt];
]);;
let NEG_ODD_LEM = prove_by_refinement(
`!set p q c d a n.
(!x. a pow n * p x = c x * q x + d x) ==>
a < &0 ==>
ODD n ==>
((interpsign set q Zero) ==>
(interpsign set (\x. -- d x) Neg) ==>
(interpsign set p Neg)) /\
((interpsign set q Zero) ==>
(interpsign set (\x. -- d x) Pos) ==>
(interpsign set p Pos)) /\
((interpsign set q Zero) ==>
(interpsign set (\x. -- d x) Zero) ==>
(interpsign set p Zero))`,
[
REWRITE_TAC[interpsign;POLY_NEG];
REPEAT_N 10 STRIP_TAC;
CLAIM `a pow n < &0`;
ASM_MESON_TAC[PARITY_POW_LT;real_gt;];
STRIP_TAC;
REAL_SIMP_TAC;
REPEAT STRIP_TAC;
RULE_ASSUM_TAC (fun y -> try ISPEC `x:real` y with _ -> y);
POP_ASSUM (fun x -> REWRITE_ASSUMS[x]);
POP_ASSUM MP_TAC;
POP_ASSUM (fun x -> REWRITE_ASSUMS[x;REAL_MUL_RZERO;REAL_ADD_LID;]);
STRIP_TAC;
CLAIM `a pow n * p x > &0`;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
REWRITE_TAC[REAL_MUL_LT;REAL_MUL_GT;real_gt];
REPEAT STRIP_TAC;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
RULE_ASSUM_TAC (fun y -> try ISPEC `x:real` y with _ -> y);
POP_ASSUM (fun x -> REWRITE_ASSUMS[x]);
POP_ASSUM MP_TAC;
POP_ASSUM (fun x -> REWRITE_ASSUMS[x;REAL_MUL_RZERO;REAL_ADD_LID;]);
STRIP_TAC;
CLAIM `a pow n * p x < &0`;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
REWRITE_TAC[REAL_MUL_LT;REAL_MUL_GT;real_gt];
REPEAT STRIP_TAC;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
RULE_ASSUM_TAC (fun y -> try ISPEC `x:real` y with _ -> y);
POP_ASSUM (fun x -> REWRITE_ASSUMS[x]);
POP_ASSUM MP_TAC;
POP_ASSUM (fun x -> REWRITE_ASSUMS[x;REAL_MUL_RZERO;REAL_ADD_LID;]);
STRIP_TAC;
CLAIM `a pow n * p x = &0`;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
ASM_MESON_TAC[REAL_ENTIRE;REAL_NOT_EQ;real_gt];
]);;
let NEQ_ODD_LEM = prove_by_refinement(
`!set p q c d a n.
(!x. a pow n * p x = c x * q x + d x) ==>
a <> &0 ==>
ODD n ==>
((interpsign set q Zero) ==>
(interpsign set (\x. a * d x) Neg) ==>
(interpsign set p Neg)) /\
((interpsign set q Zero) ==>
(interpsign set (\x. a * d x) Pos) ==>
(interpsign set p Pos)) /\
((interpsign set q Zero) ==>
(interpsign set (\x. a * d x) Zero) ==>
(interpsign set p Zero))`,
[
REWRITE_TAC[interpsign;POLY_CMUL];
REPEAT_N 10 STRIP_TAC;
CLAIM `a < &0 \/ a > &0 \/ (a = &0)`;
REAL_ARITH_TAC;
REWRITE_ASSUMS[NEQ];
ASM_REWRITE_TAC[];
LABEL_ALL_TAC;
STRIP_TAC;
CLAIM `a pow n < &0`;
ASM_MESON_TAC[PARITY_POW_LT];
STRIP_TAC;
REPEAT STRIP_TAC;
RULE_ASSUM_TAC (fun y -> try ISPEC `x:real` y with _ -> y);
POP_ASSUM (fun x -> REWRITE_ASSUMS[x]);
POP_ASSUM MP_TAC;
POP_ASSUM (fun x -> REWRITE_ASSUMS[x;REAL_MUL_RZERO;REAL_ADD_LID;]);
STRIP_TAC;
CLAIM `d x > &0`;
POP_ASSUM MP_TAC;
ASM_REWRITE_TAC[real_gt;REAL_MUL_LT];
REPEAT STRIP_TAC;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
REWRITE_TAC[REAL_MUL_LT;REAL_MUL_GT;real_gt];
REPEAT STRIP_TAC;
POP_ASSUM MP_TAC;
POP_ASSUM MP_TAC;
REWRITE_TAC[REAL_MUL_LT];
REPEAT STRIP_TAC;
CLAIM `&0 < a pow n * p x`;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
REWRITE_TAC[REAL_MUL_GT];
REPEAT STRIP_TAC;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
RULE_ASSUM_TAC (fun y -> try ISPEC `x:real` y with _ -> y);
POP_ASSUM (fun x -> REWRITE_ASSUMS[x]);
POP_ASSUM MP_TAC;
POP_ASSUM (fun x -> REWRITE_ASSUMS[x;REAL_MUL_RZERO;REAL_ADD_LID;]);
STRIP_TAC;
CLAIM `d x < &0`;
POP_ASSUM MP_TAC;
REWRITE_TAC[REAL_MUL_GT;real_gt];
REPEAT STRIP_TAC;
CLAIM `a pow n * p x < &0`;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
REWRITE_TAC[REAL_MUL_LT;REAL_MUL_GT;real_gt];
REPEAT STRIP_TAC;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
STRIP_TAC;
CLAIM `a pow n * p x < &0`;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
REWRITE_TAC[REAL_MUL_LT;REAL_MUL_GT;real_gt];
REPEAT STRIP_TAC;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
RULE_ASSUM_TAC (fun y -> try ISPEC `x:real` y with _ -> y);
POP_ASSUM (fun x -> REWRITE_ASSUMS[x]);
POP_ASSUM MP_TAC;
POP_ASSUM (fun x -> REWRITE_ASSUMS[x;REAL_MUL_RZERO;REAL_ADD_LID;]);
STRIP_TAC;
CLAIM `d x = &0`;
ASM_MESON_TAC[REAL_ENTIRE;REAL_NOT_EQ;real_gt];
STRIP_TAC;
CLAIM `a pow n * p x = &0`;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
ASM_MESON_TAC[REAL_ENTIRE;REAL_NOT_EQ;real_gt];
CLAIM `a pow n > &0`;
ASM_MESON_TAC[EVEN_ODD_POW;NEQ;real_gt];
STRIP_TAC;
REPEAT STRIP_TAC;
RULE_ASSUM_TAC (fun y -> try ISPEC `x:real` y with _ -> y);
POP_ASSUM (fun x -> REWRITE_ASSUMS[x]);
POP_ASSUM MP_TAC;
POP_ASSUM (fun x -> REWRITE_ASSUMS[x;REAL_MUL_RZERO;REAL_ADD_LID;]);
STRIP_TAC;
CLAIM `d x < &0`;
POP_ASSUM MP_TAC;
ASM_REWRITE_TAC[real_gt;REAL_MUL_LT];
REPEAT STRIP_TAC;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
REWRITE_TAC[REAL_MUL_LT;REAL_MUL_GT;real_gt];
REPEAT STRIP_TAC;
POP_ASSUM MP_TAC;
POP_ASSUM MP_TAC;
REWRITE_TAC[REAL_MUL_LT];
REPEAT STRIP_TAC;
CLAIM `a pow n * p x < &0`;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
REWRITE_TAC[REAL_MUL_LT;REAL_MUL_GT;real_gt];
REPEAT STRIP_TAC;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
CLAIM `a pow n * p x < &0`;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
REWRITE_TAC[REAL_MUL_LT;REAL_MUL_GT;real_gt];
REPEAT STRIP_TAC;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
RULE_ASSUM_TAC (fun y -> try ISPEC `x:real` y with _ -> y);
POP_ASSUM (fun x -> REWRITE_ASSUMS[x]);
POP_ASSUM MP_TAC;
POP_ASSUM (fun x -> REWRITE_ASSUMS[x;REAL_MUL_RZERO;REAL_ADD_LID;]);
STRIP_TAC;
CLAIM `d x > &0`;
POP_ASSUM MP_TAC;
REWRITE_TAC[REAL_MUL_GT;real_gt];
REPEAT STRIP_TAC;
CLAIM `a pow n * p x < &0`;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
REWRITE_TAC[REAL_MUL_LT;REAL_MUL_GT;real_gt];
REPEAT STRIP_TAC;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
STRIP_TAC;
CLAIM `a pow n * p x > &0`;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
REWRITE_TAC[REAL_MUL_LT;REAL_MUL_GT;real_gt];
REPEAT STRIP_TAC;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
RULE_ASSUM_TAC (fun y -> try ISPEC `x:real` y with _ -> y);
POP_ASSUM (fun x -> REWRITE_ASSUMS[x]);
POP_ASSUM MP_TAC;
POP_ASSUM (fun x -> REWRITE_ASSUMS[x;REAL_MUL_RZERO;REAL_ADD_LID;]);
STRIP_TAC;
CLAIM `d x = &0`;
ASM_MESON_TAC[REAL_ENTIRE;REAL_NOT_EQ;real_gt];
STRIP_TAC;
CLAIM `a pow n * p x = &0`;
EVERY_ASSUM MP_TAC THEN REAL_ARITH_TAC;
ASM_MESON_TAC[REAL_ENTIRE;REAL_NOT_EQ;real_gt];
]);;
let NEQ_MULT_LT_LEM = prove_by_refinement(
`!a q d d' set.
a < &0 ==>
((interpsign set d Neg) ==>
(interpsign set (\x. a * d x) Pos)) /\
((interpsign set d Pos) ==>
(interpsign set (\x. a * d x) Neg)) /\
((interpsign set d Zero) ==>
(interpsign set (\x. a * d x) Zero))`,
[
REWRITE_TAC[interpsign;POLY_NEG];
REPEAT STRIP_TAC;
ASM_MESON_TAC[REAL_MUL_GT;real_gt];
ASM_MESON_TAC[REAL_MUL_LT;real_gt];
ASM_MESON_TAC[REAL_ENTIRE;REAL_NOT_EQ;real_gt];
]);;
let NEQ_MULT_GT_LEM = prove_by_refinement(
`!a q d d' set.
a > &0 ==>
((interpsign set d Neg) ==>
(interpsign set (\x. a * d x) Neg)) /\
((interpsign set d Pos) ==>
(interpsign set (\x. a * d x) Pos)) /\
((interpsign set d Zero) ==>
(interpsign set (\x. a * d x) Zero))`,
[
REWRITE_TAC[interpsign;POLY_NEG] THEN
MESON_TAC[REAL_MUL_LT;REAL_ENTIRE;REAL_NOT_EQ;REAL_MUL_GT;real_gt];
]);;
let unknown_thm = prove(
`!set p. (interpsign set p Unknown)`,
MESON_TAC[interpsign]);;
let ips_gt_nz_thm = prove_by_refinement(
`!x. x > &0 ==> x <> &0`,
[
REWRITE_TAC[NEQ];
REAL_ARITH_TAC;
]);;
let ips_lt_nz_thm = prove_by_refinement(
`!x. x < &0 ==> x <> &0`,
[
REWRITE_TAC[NEQ];
REAL_ARITH_TAC;
]);;
|
f67250205e27c391dc1f787e1142efb2bc30d59531d2848f2e9249c8b2ea0918 | elastic/eui-cljs | warn_once.cljs | (ns eui.services.warn-once
(:require ["@elastic/eui/lib/services/console/warn_once.js" :as eui]))
(def warnOnce eui/warnOnce)
| null | https://raw.githubusercontent.com/elastic/eui-cljs/ad60b57470a2eb8db9bca050e02f52dd964d9f8e/src/eui/services/warn_once.cljs | clojure | (ns eui.services.warn-once
(:require ["@elastic/eui/lib/services/console/warn_once.js" :as eui]))
(def warnOnce eui/warnOnce)
| |
0adbce6c9106253462bcd4d630648c6c8a0c0d91ffbca48120bfe64893bea11e | ijvcms/chuanqi_dev | player_monster_merge_cache.erl | %%%-------------------------------------------------------------------
@author apple
( C ) 2015 , < COMPANY >
%%% @doc
%%%
%%% @end
Created : 30 . 2015 19:19
%%%-------------------------------------------------------------------
-module(player_monster_merge_cache).
-include("common.hrl").
-include("cache.hrl").
-export([
select_row/2,
select_all/0,
insert/1,
delete/2,
update/2
]).
select_row(PlayerId, MonsterId) ->
db_cache_lib:select_row(?DB_PLAYER_MONSTER_MERGE, {MonsterId, PlayerId}).
select_all() ->
db_cache_lib:select_all(?DB_PLAYER_MONSTER_MERGE, {'_', '_'}).
insert(PlayerMonsterInfo) ->
MonsterId = PlayerMonsterInfo#db_player_monster_merge.monster_id,
PlayerId = PlayerMonsterInfo#db_player_monster_merge.player_id,
db_cache_lib:insert(?DB_PLAYER_MONSTER_MERGE, {MonsterId, PlayerId}, PlayerMonsterInfo).
update({PlayerId, MonsterId}, PlayerMonsterInfo) ->
db_cache_lib:update(?DB_PLAYER_MONSTER_MERGE, {MonsterId, PlayerId}, PlayerMonsterInfo).
delete(PlayerId, MonsterId) ->
db_cache_lib:delete(?DB_PLAYER_MONSTER_MERGE, {MonsterId, PlayerId}).
%% API
| null | https://raw.githubusercontent.com/ijvcms/chuanqi_dev/7742184bded15f25be761c4f2d78834249d78097/server/trunk/server/src/business/active_merge/player_monster_merge_cache.erl | erlang | -------------------------------------------------------------------
@doc
@end
-------------------------------------------------------------------
API | @author apple
( C ) 2015 , < COMPANY >
Created : 30 . 2015 19:19
-module(player_monster_merge_cache).
-include("common.hrl").
-include("cache.hrl").
-export([
select_row/2,
select_all/0,
insert/1,
delete/2,
update/2
]).
select_row(PlayerId, MonsterId) ->
db_cache_lib:select_row(?DB_PLAYER_MONSTER_MERGE, {MonsterId, PlayerId}).
select_all() ->
db_cache_lib:select_all(?DB_PLAYER_MONSTER_MERGE, {'_', '_'}).
insert(PlayerMonsterInfo) ->
MonsterId = PlayerMonsterInfo#db_player_monster_merge.monster_id,
PlayerId = PlayerMonsterInfo#db_player_monster_merge.player_id,
db_cache_lib:insert(?DB_PLAYER_MONSTER_MERGE, {MonsterId, PlayerId}, PlayerMonsterInfo).
update({PlayerId, MonsterId}, PlayerMonsterInfo) ->
db_cache_lib:update(?DB_PLAYER_MONSTER_MERGE, {MonsterId, PlayerId}, PlayerMonsterInfo).
delete(PlayerId, MonsterId) ->
db_cache_lib:delete(?DB_PLAYER_MONSTER_MERGE, {MonsterId, PlayerId}).
|
85a4f091dc7ad7d353d9c46bcf4937ac7adc9040a472835bc1b8b29c694a1349 | cljfx/cljfx | project.clj | (defproject splash "0.1.0-SNAPSHOT"
:description "Example splash screen for cljfx"
:java-source-paths ["java-src"]
:dependencies [[cljfx/cljfx "1.7.13"]]
:repl-options {:init-ns splash}
:profiles {:uberjar {:aot :all
:jvm-opts ["-Dcljfx.skip-javafx-initialization=true"]}}
;; entrypoint for splash screen
:main splash.Main)
| null | https://raw.githubusercontent.com/cljfx/cljfx/d41e4ec2456cf227ec44c60f1ab76ccef7be194e/example-projects/splash/project.clj | clojure | entrypoint for splash screen | (defproject splash "0.1.0-SNAPSHOT"
:description "Example splash screen for cljfx"
:java-source-paths ["java-src"]
:dependencies [[cljfx/cljfx "1.7.13"]]
:repl-options {:init-ns splash}
:profiles {:uberjar {:aot :all
:jvm-opts ["-Dcljfx.skip-javafx-initialization=true"]}}
:main splash.Main)
|
b96ef617b42e7de5922f7748638ebac0d1331fbf2928fd26606289fba9b28e7f | ygmpkk/house | Preprocess.hs | --------------------------------------------------------------------------------
--
Program : Preprocess
Copyright : ( c ) 2003
-- License : BSD-style (see the file libraries/OpenGL/LICENSE)
--
-- Maintainer :
-- Stability : provisional
-- Portability : portable
--
The .spec files from the SI are normally processed by / AWK scripts and
-- have therefore a rather ugly line-oriented syntax. To make things more
-- amenable to "real" parsing, some lexical preprocessing is useful. Note that
-- the following algorithm doesn't remove or insert lines, which is important
-- for good error messages later. After this preprocessing, whitespace is not
-- significant anymore, apart from its common use as a token separator.
--
-- For every line do:
--
1 ) Remove comments : Remove everything starting at the first ' # ' .
--
-- 2) Ignore passthru-hack: Consider lines starting with 'passthru:' as empty.
--
-- 3) Remove trailing whitespace.
--
4 ) Mangle property declarations : Append ' ; ' to a line where the first ' : '
is only preceded by non - TAB and non - SPC characters . Additionally , move
-- that ':' to the beginning of the line.
--
5 ) Separate definitions : Append ' , ' to a line starting with TAB and
followed ( ignoring empty lines ) by a line starting with TAB .
--
6 ) Terminate definitions : Append ' ; ' to a line starting with TAB and not
followed ( ignoring empty lines ) by a line starting with TAB .
--
--------------------------------------------------------------------------------
module Main ( main ) where
import Control.Monad ( liftM )
import Data.Char ( isSpace )
import Data.List ( isPrefixOf, tails )
import System.Environment ( getArgs )
--------------------------------------------------------------------------------
-- Preprocessing of spec files, making it more amenable to "real" parsing
--------------------------------------------------------------------------------
preprocess :: String -> String
preprocess = unlines .
addSeparators . mangleColonLines .
removeTrailingWhitespace . removePassthru . removeComments .
lines
where removeComments = map $ takeWhile (/= '#')
removePassthru = map $ \l -> if "passthru:" `isPrefixOf` l then "" else l
removeTrailingWhitespace = map $ reverse . dropWhile isSpace . reverse
mangleColonLines = map $ \l ->
case break (== ':') l of
(xs, ':':ys) | noSpaceIn xs -> ":" ++ xs ++ " " ++ ys ++ ";"
_ -> l
noSpaceIn = not . any (`elem` ['\t',' '])
addSeparators = map addSeparator . tails
addSeparator [] = []
addSeparator xs@(l:ls) | startsWithTabbedLine xs = l ++ separatorFor ls
| otherwise = l
separatorFor ls | startsWithTabbedLine (dropEmpty ls) = ","
| otherwise = ";"
dropEmpty = dropWhile ((== 0) . length)
startsWithTabbedLine (('\t':_):_) = True
startsWithTabbedLine _ = False
--------------------------------------------------------------------------------
-- The driver
--------------------------------------------------------------------------------
-- behave like 'cat'
mainWithArgs :: [String] -> IO ()
mainWithArgs fileNames = putStr . preprocess =<< input
where input | null fileNames = getContents
| otherwise = liftM concat (mapM readFile fileNames)
main :: IO ()
main = getArgs >>= mainWithArgs
| null | https://raw.githubusercontent.com/ygmpkk/house/1ed0eed82139869e85e3c5532f2b579cf2566fa2/ghc-6.2/libraries/OpenGL/specs/preprocess/Preprocess.hs | haskell | ------------------------------------------------------------------------------
License : BSD-style (see the file libraries/OpenGL/LICENSE)
Maintainer :
Stability : provisional
Portability : portable
have therefore a rather ugly line-oriented syntax. To make things more
amenable to "real" parsing, some lexical preprocessing is useful. Note that
the following algorithm doesn't remove or insert lines, which is important
for good error messages later. After this preprocessing, whitespace is not
significant anymore, apart from its common use as a token separator.
For every line do:
2) Ignore passthru-hack: Consider lines starting with 'passthru:' as empty.
3) Remove trailing whitespace.
that ':' to the beginning of the line.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Preprocessing of spec files, making it more amenable to "real" parsing
------------------------------------------------------------------------------
------------------------------------------------------------------------------
The driver
------------------------------------------------------------------------------
behave like 'cat' | Program : Preprocess
Copyright : ( c ) 2003
The .spec files from the SI are normally processed by / AWK scripts and
1 ) Remove comments : Remove everything starting at the first ' # ' .
4 ) Mangle property declarations : Append ' ; ' to a line where the first ' : '
is only preceded by non - TAB and non - SPC characters . Additionally , move
5 ) Separate definitions : Append ' , ' to a line starting with TAB and
followed ( ignoring empty lines ) by a line starting with TAB .
6 ) Terminate definitions : Append ' ; ' to a line starting with TAB and not
followed ( ignoring empty lines ) by a line starting with TAB .
module Main ( main ) where
import Control.Monad ( liftM )
import Data.Char ( isSpace )
import Data.List ( isPrefixOf, tails )
import System.Environment ( getArgs )
preprocess :: String -> String
preprocess = unlines .
addSeparators . mangleColonLines .
removeTrailingWhitespace . removePassthru . removeComments .
lines
where removeComments = map $ takeWhile (/= '#')
removePassthru = map $ \l -> if "passthru:" `isPrefixOf` l then "" else l
removeTrailingWhitespace = map $ reverse . dropWhile isSpace . reverse
mangleColonLines = map $ \l ->
case break (== ':') l of
(xs, ':':ys) | noSpaceIn xs -> ":" ++ xs ++ " " ++ ys ++ ";"
_ -> l
noSpaceIn = not . any (`elem` ['\t',' '])
addSeparators = map addSeparator . tails
addSeparator [] = []
addSeparator xs@(l:ls) | startsWithTabbedLine xs = l ++ separatorFor ls
| otherwise = l
separatorFor ls | startsWithTabbedLine (dropEmpty ls) = ","
| otherwise = ";"
dropEmpty = dropWhile ((== 0) . length)
startsWithTabbedLine (('\t':_):_) = True
startsWithTabbedLine _ = False
mainWithArgs :: [String] -> IO ()
mainWithArgs fileNames = putStr . preprocess =<< input
where input | null fileNames = getContents
| otherwise = liftM concat (mapM readFile fileNames)
main :: IO ()
main = getArgs >>= mainWithArgs
|
825ff411d6d55161a6183cfb87e92fb7545776f9e3a7d89a50c6103bf5913171 | dalong0514/ITstudy | endplot.lsp | (prompt " \nLoad Only....Do NOT Run...")
(vl-load-com)
;*******************************************************
(vlr-command-reactor
"Backup After Plot" '((:vlr-commandEnded . endPlot)))
;*******************************************************
(defun endPlot (calling-reactor endcommandInfo /
thecommandend drgName newname)
(setq thecommandend (nth 0 endcommandInfo))
(if (= thecommandend "PLOT")
(progn
(setq acadDocument (vla-get-activedocument
(vlax-get-acad-object)))
(setq drgName (vla-get-name acadDocument))
(setq newname (strcat "c:\\backup\\" drgName))
(vla-save acadDocument)
(vla-saveas acadDocument newname)
progn
);if
(princ)
defun
;*********************************************************
(princ) | null | https://raw.githubusercontent.com/dalong0514/ITstudy/dbfe59151a416b7ebfd4a3881c1fa234bda5ad22/001%E7%A2%8E%E7%89%87%E7%9F%A5%E8%AF%86/2022%E7%A2%8E%E7%89%87%E7%9F%A5%E8%AF%86/%E9%99%84%E4%BB%B6/20220308AutoLisp-Reactors/endplot.lsp | lisp | *******************************************************
*******************************************************
if
*********************************************************
| (prompt " \nLoad Only....Do NOT Run...")
(vl-load-com)
(vlr-command-reactor
"Backup After Plot" '((:vlr-commandEnded . endPlot)))
(defun endPlot (calling-reactor endcommandInfo /
thecommandend drgName newname)
(setq thecommandend (nth 0 endcommandInfo))
(if (= thecommandend "PLOT")
(progn
(setq acadDocument (vla-get-activedocument
(vlax-get-acad-object)))
(setq drgName (vla-get-name acadDocument))
(setq newname (strcat "c:\\backup\\" drgName))
(vla-save acadDocument)
(vla-saveas acadDocument newname)
progn
(princ)
defun
(princ) |
bed01313f67aa1ec091921cef877ebb597fed0e7a57df47c074e06db45bd7d2c | phantomics/april | demo.lisp | -*- Mode : Lisp ; Syntax : ANSI - Common - Lisp ; Coding : utf-8 ; Package : AprilDemo . Cnn -*-
;;;; demo.lisp
(in-package #:april-demo.cnn)
(defparameter *package-symbol* (intern (package-name *package*) "KEYWORD"))
;; binary format for .idx files
(defbinary idx-file (:byte-order :big-endian)
(empty 0 :type 16)
(type 0 :type 8)
(rank 0 :type 8)
(dimensions #() :type (simple-array (unsigned-byte 32) (rank)))
(data #() :type (eval (case type (#x08 `(simple-array (unsigned-byte 8) (,(reduce #'* dimensions))))
(#x09 `(simple-array (signed-byte 8) (,(reduce #'* dimensions))))
(#x0b `(simple-array (signed-byte 16) (,(reduce #'* dimensions))))
(#x0c `(simple-array (signed-byte 32) (,(reduce #'* dimensions))))
(#x0d `(simple-array single-float (,(reduce #'* dimensions))))
(#x0e `(simple-array double-float (,(reduce #'* dimensions))))))))
(defun idx-file-to-array (file-path)
"Load the contents of an .idx file into an array."
(with-open-binary-file (in-raw file-path :direction :input)
(with-wrapped-in-bit-stream (in in-raw :byte-order :big-endian)
(let ((idx-input (read-binary 'idx-file in)))
(if (= 1 (slot-value idx-input 'rank))
(slot-value idx-input 'data)
(make-array (loop :for d :across (slot-value idx-input 'dimensions) :collect d)
:element-type (array-element-type (slot-value idx-input 'data))
:displaced-to (slot-value idx-input 'data)))))))
(april-load (with (:space cnn-demo-space))
(asdf:system-relative-pathname (intern (package-name *package*) "KEYWORD") "cnn.apl"))
(let ((training-data) (training-labels) (test-data) (test-labels))
(defun load-idx-files ()
"Load data from .idx files in input/ directory into four variables."
(setf training-data (idx-file-to-array (asdf:system-relative-pathname
*package-symbol* "input/train-images.idx3-ubyte"))
training-labels (idx-file-to-array (asdf:system-relative-pathname
*package-symbol* "input/train-labels.idx1-ubyte"))
test-data (idx-file-to-array (asdf:system-relative-pathname
*package-symbol* "input/t10k-images.idx3-ubyte"))
test-labels (idx-file-to-array (asdf:system-relative-pathname
*package-symbol* "input/t10k-labels.idx1-ubyte")))
"Data loaded.")
;; these functions fetch the input data
(defun get-training-data () training-data)
(defun get-training-labels () training-labels)
(defun get-test-data () test-data)
(defun get-test-labels () test-labels))
(defun train ()
"Train a convolutional neural network with a set of training data and test it against another dataset."
(april (with (:space cnn-demo-space)
(:state :in ((trimgs (get-training-data)) (trlabs (get-training-labels)))))
"
epochs ← 10
batchSize ← 1
trainings ← 100 ⍝ 1000
rate ← 0.05
k1 ← 6 5 5⍴÷25.0
b1 ← 6⍴÷6.0
k2 ← 12 6 5 5⍴÷150.0
b2 ← 12⍴÷12.0
fc ← 10 12 1 4 4⍴÷192.0
b ← 10⍴÷10.0
index ← 1
startTime ← ⍬
⎕ ← 'Training Zhang with ',(⍕epochs),' epochs, batch size ',⍕batchSize,','
⎕ ← (⍕trainings),' training images and a rate of ',(⍕rate),'.'
⎕ ← ' '⍪'--',[.5]' '
(k1 b1 k2 b2 fc b) ← {
t ← timeFactors⊥¯4↑⎕ts
⍝ ⎕ ← 'SET' ⋄ ⎕ ← ' ' ⋄ ⎕←⊃⍵ ⋄ ⎕ ← ' ' ⋄ ⎕ ← ' '
⍝ ⎕←'A1' ⋄ ⎕←10↑,0⊃⍵ ⋄ ⎕←' ' ⋄ ⎕←10↑,2⊃⍵
⍝ ⎕←'A1' ⋄ ⎕←1⊃⍵ ⋄ ⎕←' ' ⋄ ⎕←3⊃⍵
⍝ ⎕←'A1' ⋄ ⎕←5↑,4⊃⍵ ⋄ ⎕←' ' ⋄ ⎕←5↑5⊃⍵
e k1 b1 k2 b2 fc b ← train (0 0), ⍵, rate trimgs trlabs trainings
⎕ ← 'Training epoch ',({⍵,⍨'0'⍴⍨(⍴⍕epochs)-⍴⍵}⍕index),' completed in ',formatElapsed t
⎕ ← 'Average error after training: ',⍕e ⋄ ⎕ ← ' '
index+←1
⍝ ⎕←'A2' ⋄ ⎕←10↑,k1 ⋄ ⎕←' ' ⋄ ⎕←10↑,k2
⍝ ⎕←'A2' ⋄ ⎕←b1 ⋄ ⎕←' ' ⋄ ⎕←b2
⍝ ⎕←'A2' ⋄ ⎕←5↑,fc ⋄ ⎕←' ' ⋄ ⎕←5↑b
k1 b1 k2 b2 fc b
}⍣epochs⊢k1 b1 k2 b2 fc b
")
"Neural network training complete.")
(defun test ()
"Train a convolutional neural network with a set of training data and test it against another dataset."
(april (with (:space cnn-demo-space)
(:state :in ((teimgs (get-test-data)) (telabs (get-test-labels)))))
"
tests ← 100 ⍝ 10000
⎕ ← 'Testing Zhang with ',(⍕tests),' tests.'
⎕ ← ' '⍪'--',[.5]' '
t ← timeFactors⊥¯4↑⎕ts
correct ← +/(tests↑[0]telabs) = (tests↑[0]teimgs) testZhang⍤2⊢k1 b1 k2 b2 fc b
⎕ ← 'Recognition testing completed in ',formatElapsed t
⎕ ← (⍕correct),' images out of ',(⍕tests),' recognized correctly.'
")
"Neural network test complete.")
(defun train-and-test ()
(april (with (:space cnn-demo-space)) "startTime ← timeFactors⊥¯4↑⎕ts")
(train)
(format t "~%Training complete, now running tests...~%~%")
(test)
(april (with (:space cnn-demo-space)) "⎕ ← ' ' ⋄ ⎕ ← 'Total time: ',formatElapsed startTime ⋄ ⎕ ← ' '"))
| null | https://raw.githubusercontent.com/phantomics/april/9e5fac321e8ef666226467724e65e0f89c51f5c5/demos/cnn/demo.lisp | lisp | Syntax : ANSI - Common - Lisp ; Coding : utf-8 ; Package : AprilDemo . Cnn -*-
demo.lisp
binary format for .idx files
these functions fetch the input data |
(in-package #:april-demo.cnn)
(defparameter *package-symbol* (intern (package-name *package*) "KEYWORD"))
(defbinary idx-file (:byte-order :big-endian)
(empty 0 :type 16)
(type 0 :type 8)
(rank 0 :type 8)
(dimensions #() :type (simple-array (unsigned-byte 32) (rank)))
(data #() :type (eval (case type (#x08 `(simple-array (unsigned-byte 8) (,(reduce #'* dimensions))))
(#x09 `(simple-array (signed-byte 8) (,(reduce #'* dimensions))))
(#x0b `(simple-array (signed-byte 16) (,(reduce #'* dimensions))))
(#x0c `(simple-array (signed-byte 32) (,(reduce #'* dimensions))))
(#x0d `(simple-array single-float (,(reduce #'* dimensions))))
(#x0e `(simple-array double-float (,(reduce #'* dimensions))))))))
(defun idx-file-to-array (file-path)
"Load the contents of an .idx file into an array."
(with-open-binary-file (in-raw file-path :direction :input)
(with-wrapped-in-bit-stream (in in-raw :byte-order :big-endian)
(let ((idx-input (read-binary 'idx-file in)))
(if (= 1 (slot-value idx-input 'rank))
(slot-value idx-input 'data)
(make-array (loop :for d :across (slot-value idx-input 'dimensions) :collect d)
:element-type (array-element-type (slot-value idx-input 'data))
:displaced-to (slot-value idx-input 'data)))))))
(april-load (with (:space cnn-demo-space))
(asdf:system-relative-pathname (intern (package-name *package*) "KEYWORD") "cnn.apl"))
(let ((training-data) (training-labels) (test-data) (test-labels))
(defun load-idx-files ()
"Load data from .idx files in input/ directory into four variables."
(setf training-data (idx-file-to-array (asdf:system-relative-pathname
*package-symbol* "input/train-images.idx3-ubyte"))
training-labels (idx-file-to-array (asdf:system-relative-pathname
*package-symbol* "input/train-labels.idx1-ubyte"))
test-data (idx-file-to-array (asdf:system-relative-pathname
*package-symbol* "input/t10k-images.idx3-ubyte"))
test-labels (idx-file-to-array (asdf:system-relative-pathname
*package-symbol* "input/t10k-labels.idx1-ubyte")))
"Data loaded.")
(defun get-training-data () training-data)
(defun get-training-labels () training-labels)
(defun get-test-data () test-data)
(defun get-test-labels () test-labels))
(defun train ()
"Train a convolutional neural network with a set of training data and test it against another dataset."
(april (with (:space cnn-demo-space)
(:state :in ((trimgs (get-training-data)) (trlabs (get-training-labels)))))
"
epochs ← 10
batchSize ← 1
trainings ← 100 ⍝ 1000
rate ← 0.05
k1 ← 6 5 5⍴÷25.0
b1 ← 6⍴÷6.0
k2 ← 12 6 5 5⍴÷150.0
b2 ← 12⍴÷12.0
fc ← 10 12 1 4 4⍴÷192.0
b ← 10⍴÷10.0
index ← 1
startTime ← ⍬
⎕ ← 'Training Zhang with ',(⍕epochs),' epochs, batch size ',⍕batchSize,','
⎕ ← (⍕trainings),' training images and a rate of ',(⍕rate),'.'
⎕ ← ' '⍪'--',[.5]' '
(k1 b1 k2 b2 fc b) ← {
t ← timeFactors⊥¯4↑⎕ts
⍝ ⎕ ← 'SET' ⋄ ⎕ ← ' ' ⋄ ⎕←⊃⍵ ⋄ ⎕ ← ' ' ⋄ ⎕ ← ' '
⍝ ⎕←'A1' ⋄ ⎕←10↑,0⊃⍵ ⋄ ⎕←' ' ⋄ ⎕←10↑,2⊃⍵
⍝ ⎕←'A1' ⋄ ⎕←1⊃⍵ ⋄ ⎕←' ' ⋄ ⎕←3⊃⍵
⍝ ⎕←'A1' ⋄ ⎕←5↑,4⊃⍵ ⋄ ⎕←' ' ⋄ ⎕←5↑5⊃⍵
e k1 b1 k2 b2 fc b ← train (0 0), ⍵, rate trimgs trlabs trainings
⎕ ← 'Training epoch ',({⍵,⍨'0'⍴⍨(⍴⍕epochs)-⍴⍵}⍕index),' completed in ',formatElapsed t
⎕ ← 'Average error after training: ',⍕e ⋄ ⎕ ← ' '
index+←1
⍝ ⎕←'A2' ⋄ ⎕←10↑,k1 ⋄ ⎕←' ' ⋄ ⎕←10↑,k2
⍝ ⎕←'A2' ⋄ ⎕←b1 ⋄ ⎕←' ' ⋄ ⎕←b2
⍝ ⎕←'A2' ⋄ ⎕←5↑,fc ⋄ ⎕←' ' ⋄ ⎕←5↑b
k1 b1 k2 b2 fc b
}⍣epochs⊢k1 b1 k2 b2 fc b
")
"Neural network training complete.")
(defun test ()
"Train a convolutional neural network with a set of training data and test it against another dataset."
(april (with (:space cnn-demo-space)
(:state :in ((teimgs (get-test-data)) (telabs (get-test-labels)))))
"
tests ← 100 ⍝ 10000
⎕ ← 'Testing Zhang with ',(⍕tests),' tests.'
⎕ ← ' '⍪'--',[.5]' '
t ← timeFactors⊥¯4↑⎕ts
correct ← +/(tests↑[0]telabs) = (tests↑[0]teimgs) testZhang⍤2⊢k1 b1 k2 b2 fc b
⎕ ← 'Recognition testing completed in ',formatElapsed t
⎕ ← (⍕correct),' images out of ',(⍕tests),' recognized correctly.'
")
"Neural network test complete.")
(defun train-and-test ()
(april (with (:space cnn-demo-space)) "startTime ← timeFactors⊥¯4↑⎕ts")
(train)
(format t "~%Training complete, now running tests...~%~%")
(test)
(april (with (:space cnn-demo-space)) "⎕ ← ' ' ⋄ ⎕ ← 'Total time: ',formatElapsed startTime ⋄ ⎕ ← ' '"))
|
5beea08d91b43166bd5cd432b1d93f24123e0f4d6be151ae6c26bc0996bcedab | phylogeography/spread | math_utils.cljc | (ns shared.math-utils)
(def sqrt #?(:clj #(Math/sqrt %)
:cljs #(js/Math.sqrt %)))
(def log #?(:clj #(Math/log %)
:cljs #(js/Math.log %)))
(def pow #?(:clj #(Math/pow %1 %2)
:cljs #(js/Math.pow %1 %2)))
(def parse-int #?(:clj #(Integer/parseInt %1 %2)
:cljs #(js/parseInt %1 %2)))
(def min-int #?(:clj Integer/MIN_VALUE
:cljs js/Number.MIN_SAFE_INTEGER))
(def max-int #?(:clj Integer/MAX_VALUE
:cljs js/Number.MAX_SAFE_INTEGER))
(defn quad-curve-length
"Calculates the length of a quadratic curve given three points using the algorithm in
:80/blog/quadratic-bezier-curve-length/
p0x p0y - Quadratic curve starting point
p1x p1y - Quadratic curve focus point
p2x p2y - Quadratic curve stop point"
[p0x p0y p1x p1y p2x p2y]
(let [ax (+ (- p0x (* 2 p1x)) p2x)
ay (+ (- p0y (* 2 p1y)) p2y)
bx (- (* 2 p1x) (* 2 p0x))
by (- (* 2 p1y) (* 2 p0y))
A (* 4 (+ (* ax ax) (* ay ay)))
B (* 4 (+ (* ax bx) (* ay by)))
C (+ (* bx bx) (* by by))
Sabc (* 2 (sqrt (+ A B C)))
A_2 (sqrt A)
A_32 (* 2 A A_2)
C_2 (* 2 (sqrt C))
BA (/ B A_2)]
(/ (+ (* A_32 Sabc)
(* A_2 B (- Sabc C_2))
(* (- (* 4 C A) (* B B)) (log (/ (+ (* 2 A_2) BA Sabc)
(+ BA C_2)))))
(* 4 A_32))))
(defn quad-curve-focuses
"Calculates nice focuses (positive and negative) for a quadratic curve given its starting and end points"
[x1 y1 x2 y2 curvature]
(let [line-m (/ (- y1 y2)
(- x1 x2))
the line that goes from [ ] to [ x2,y2 ]
line (fn [x] (- (+ (* line-m x) y1) (* x1 line-m)))
perp-m (/ (- x1 x2)
(- y1 y2)
-1)
cx (+ x1 (/ (- x2 x1) 2))
cy (line cx)
;; a line perp to `line` that pass thru its center
center-perp (fn [x] (- (+ (* perp-m x) cy) (* cx perp-m)))
length ( sqrt ( + ( pow ( - x2 x1 ) 2 ) ( pow ( - y2 y1 ) 2 ) ) )
;; calculates focus x, a point that belongs to `center-perp` line and is at distance `k`
;; from `cx`,`cy`
;; `sol-fn` can be `+` or `-` to get the fx below and avobe the line
fx-fn (fn [sol-fn]
This was solved with wolframalfa using the next formula where
f = fx , e = fy , m = perp - m , c = cx , d = cy
It will yield two solutions ( one for each focus )
;; Solve[mx+d-mc-y=0 && (x-c)^2+(y-d)^2=k^2, {x,y}]
;; calculates focus-x, which is the point x that belongs to the perpendicular line
;; that goes thru the center, and also is at distance k from cx,cy
(/ (sol-fn (+ (* cx (pow perp-m 2)) cx) (sqrt (* (pow curvature 2) (+ (pow perp-m 2) 1))))
(+ (pow perp-m 2) 1)))
f1x (fx-fn +)
f2x (fx-fn -)
f1y (center-perp f1x)
f2y (center-perp f2x)]
{:f1 [f1x f1y]
:f2 [f2x f2y]}))
(defn outscribing-rectangle
"Calculates x,y,w,h of the rectangle outscribing a circle of
center-x,center-y and radius."
[[center-x center-y] radius]
{:x (- center-x radius)
:y (- center-y radius)
:w (* 2 radius)
:h (* 2 radius)})
(defn map-coord->proj-coord
"Convert from:
- map-coord: [lat,lon] coordinates in map lat,long coords, -180 <= lon <= 180, -90 <= lat <= 90
into
- proj-coord: [x,y] coordinates in map projection coords, 0 <= x <= 360, 0 <= y <= 180
"
[[long lat]]
[(+ long 180)
(+ (* -1 lat) 90)])
(defn map-box->proj-box [{:keys [min-x min-y max-x max-y]}]
(let [[x1 y1] (map-coord->proj-coord [min-x min-y])
[x2 y2] (map-coord->proj-coord [max-x max-y])]
{:min-x (min x1 x2)
:min-y (min y1 y2)
:max-x (max x1 x2)
:max-y (max y1 y2)}))
(defn screen-coord->proj-coord
"Convert from:
- screen-coord: [x,y] coordinates in screen pixels, 0 <= x <= map-width, 0 <= y <= map-height
into
- proj-coord: [x,y] coordinates in map projection coords, 0 <= x <= 360, 0 <= y <= 180
`translate`: current map translation
`scale`: current map scale
`proj-scale`: the scale between the screen area and the map projection.
"
[translate scale proj-scale [screen-x screen-y]]
(let [[tx ty] translate]
[(/ (- screen-x tx) (* proj-scale scale))
(/ (- screen-y ty) (* proj-scale scale))]))
(defn calc-zoom-for-view-box
"Calculates a scale and a translation to fit the rectangle
defined by `x1`,`y1` `x2`,`y2` fully zoomed.
All parameter coordinates are in map proj-coord.
`proj-scale`: is the scale between the screen area and the map projection.
Assumes working with a map projection of 360x180."
[x1 y1 x2 y2 proj-scale]
(let [map-proj-width 360
map-proj-height 180
scale-x (/ map-proj-width (- x2 x1))
scale-y (/ map-proj-height (- y2 y1))
scale (min scale-x scale-y)
tx (* -1 scale proj-scale x1)
ty (* -1 scale proj-scale y1)]
{:translate [tx ty]
:scale scale}))
(defn normalize-color-str [color-str]
(let [[_ r g b] (re-find #"#(..)(..)(..)" color-str)
norm (fn [hex-str] (/ (parse-int hex-str 16) 255))]
[(norm r) (norm g) (norm b)]))
(defn to-hex [n]
(let [s (.toString n 16)]
(if (= 1 (count s))
(str "0" s)
s)))
(defn denormalize-color [[r g b]]
(str "#"
(to-hex (int (* 255 r)))
(to-hex (int (* 255 g)))
(to-hex (int (* 255 b)))))
(defn calculate-color [start end perc]
(let [[rs gs bs] (normalize-color-str start)
[re ge be] (normalize-color-str end)
color (denormalize-color [(+ (* perc rs) (* (- 1 perc) re))
(+ (* perc gs) (* (- 1 perc) ge))
(+ (* perc bs) (* (- 1 perc) be))])]
color))
(defn calc-perc [from to x]
(/ (- x from) (- to from)))
(defn build-scaler
"Builds a function that given a number in [orig-from...orig-to] range will
yield a proportional number in the [dest-from...dest-to] range."
[orig-from orig-to dest-from dest-to]
(fn [x]
(let [p (calc-perc orig-from orig-to x)]
(+ (* p (- dest-to dest-from)) dest-from))))
(defn bounding-box [coords]
(reduce (fn [r [x y]]
(-> r
(update :min-x #(min % x))
(update :min-y #(min % y))
(update :max-x #(max % x))
(update :max-y #(max % y))))
{:min-x max-int
:min-y max-int
:max-x min-int
:max-y min-int}
coords))
(defn box-overlap? [box-1 box-2]
(let [overlap-1d? (fn [a1 a2 b1 b2]
(and (>= a2 b1)
(>= b2 a1)))]
(and (overlap-1d? (:min-x box-1) (:max-x box-1) (:min-x box-2) (:max-x box-2))
(overlap-1d? (:min-y box-1) (:max-y box-1) (:min-y box-2) (:max-y box-2)))))
(defn distance [[x1 y1] [x2 y2]]
(sqrt
(+ (pow (- x2 x1) 2)
(pow (- y2 y1) 2))))
| null | https://raw.githubusercontent.com/phylogeography/spread/56f3500e6d83e0ebd50041dc336ffa0697d7baf8/src/cljc/shared/math_utils.cljc | clojure | a line perp to `line` that pass thru its center
calculates focus x, a point that belongs to `center-perp` line and is at distance `k`
from `cx`,`cy`
`sol-fn` can be `+` or `-` to get the fx below and avobe the line
Solve[mx+d-mc-y=0 && (x-c)^2+(y-d)^2=k^2, {x,y}]
calculates focus-x, which is the point x that belongs to the perpendicular line
that goes thru the center, and also is at distance k from cx,cy | (ns shared.math-utils)
(def sqrt #?(:clj #(Math/sqrt %)
:cljs #(js/Math.sqrt %)))
(def log #?(:clj #(Math/log %)
:cljs #(js/Math.log %)))
(def pow #?(:clj #(Math/pow %1 %2)
:cljs #(js/Math.pow %1 %2)))
(def parse-int #?(:clj #(Integer/parseInt %1 %2)
:cljs #(js/parseInt %1 %2)))
(def min-int #?(:clj Integer/MIN_VALUE
:cljs js/Number.MIN_SAFE_INTEGER))
(def max-int #?(:clj Integer/MAX_VALUE
:cljs js/Number.MAX_SAFE_INTEGER))
(defn quad-curve-length
"Calculates the length of a quadratic curve given three points using the algorithm in
:80/blog/quadratic-bezier-curve-length/
p0x p0y - Quadratic curve starting point
p1x p1y - Quadratic curve focus point
p2x p2y - Quadratic curve stop point"
[p0x p0y p1x p1y p2x p2y]
(let [ax (+ (- p0x (* 2 p1x)) p2x)
ay (+ (- p0y (* 2 p1y)) p2y)
bx (- (* 2 p1x) (* 2 p0x))
by (- (* 2 p1y) (* 2 p0y))
A (* 4 (+ (* ax ax) (* ay ay)))
B (* 4 (+ (* ax bx) (* ay by)))
C (+ (* bx bx) (* by by))
Sabc (* 2 (sqrt (+ A B C)))
A_2 (sqrt A)
A_32 (* 2 A A_2)
C_2 (* 2 (sqrt C))
BA (/ B A_2)]
(/ (+ (* A_32 Sabc)
(* A_2 B (- Sabc C_2))
(* (- (* 4 C A) (* B B)) (log (/ (+ (* 2 A_2) BA Sabc)
(+ BA C_2)))))
(* 4 A_32))))
(defn quad-curve-focuses
"Calculates nice focuses (positive and negative) for a quadratic curve given its starting and end points"
[x1 y1 x2 y2 curvature]
(let [line-m (/ (- y1 y2)
(- x1 x2))
the line that goes from [ ] to [ x2,y2 ]
line (fn [x] (- (+ (* line-m x) y1) (* x1 line-m)))
perp-m (/ (- x1 x2)
(- y1 y2)
-1)
cx (+ x1 (/ (- x2 x1) 2))
cy (line cx)
center-perp (fn [x] (- (+ (* perp-m x) cy) (* cx perp-m)))
length ( sqrt ( + ( pow ( - x2 x1 ) 2 ) ( pow ( - y2 y1 ) 2 ) ) )
fx-fn (fn [sol-fn]
This was solved with wolframalfa using the next formula where
f = fx , e = fy , m = perp - m , c = cx , d = cy
It will yield two solutions ( one for each focus )
(/ (sol-fn (+ (* cx (pow perp-m 2)) cx) (sqrt (* (pow curvature 2) (+ (pow perp-m 2) 1))))
(+ (pow perp-m 2) 1)))
f1x (fx-fn +)
f2x (fx-fn -)
f1y (center-perp f1x)
f2y (center-perp f2x)]
{:f1 [f1x f1y]
:f2 [f2x f2y]}))
(defn outscribing-rectangle
"Calculates x,y,w,h of the rectangle outscribing a circle of
center-x,center-y and radius."
[[center-x center-y] radius]
{:x (- center-x radius)
:y (- center-y radius)
:w (* 2 radius)
:h (* 2 radius)})
(defn map-coord->proj-coord
"Convert from:
- map-coord: [lat,lon] coordinates in map lat,long coords, -180 <= lon <= 180, -90 <= lat <= 90
into
- proj-coord: [x,y] coordinates in map projection coords, 0 <= x <= 360, 0 <= y <= 180
"
[[long lat]]
[(+ long 180)
(+ (* -1 lat) 90)])
(defn map-box->proj-box [{:keys [min-x min-y max-x max-y]}]
(let [[x1 y1] (map-coord->proj-coord [min-x min-y])
[x2 y2] (map-coord->proj-coord [max-x max-y])]
{:min-x (min x1 x2)
:min-y (min y1 y2)
:max-x (max x1 x2)
:max-y (max y1 y2)}))
(defn screen-coord->proj-coord
"Convert from:
- screen-coord: [x,y] coordinates in screen pixels, 0 <= x <= map-width, 0 <= y <= map-height
into
- proj-coord: [x,y] coordinates in map projection coords, 0 <= x <= 360, 0 <= y <= 180
`translate`: current map translation
`scale`: current map scale
`proj-scale`: the scale between the screen area and the map projection.
"
[translate scale proj-scale [screen-x screen-y]]
(let [[tx ty] translate]
[(/ (- screen-x tx) (* proj-scale scale))
(/ (- screen-y ty) (* proj-scale scale))]))
(defn calc-zoom-for-view-box
"Calculates a scale and a translation to fit the rectangle
defined by `x1`,`y1` `x2`,`y2` fully zoomed.
All parameter coordinates are in map proj-coord.
`proj-scale`: is the scale between the screen area and the map projection.
Assumes working with a map projection of 360x180."
[x1 y1 x2 y2 proj-scale]
(let [map-proj-width 360
map-proj-height 180
scale-x (/ map-proj-width (- x2 x1))
scale-y (/ map-proj-height (- y2 y1))
scale (min scale-x scale-y)
tx (* -1 scale proj-scale x1)
ty (* -1 scale proj-scale y1)]
{:translate [tx ty]
:scale scale}))
(defn normalize-color-str [color-str]
(let [[_ r g b] (re-find #"#(..)(..)(..)" color-str)
norm (fn [hex-str] (/ (parse-int hex-str 16) 255))]
[(norm r) (norm g) (norm b)]))
(defn to-hex [n]
(let [s (.toString n 16)]
(if (= 1 (count s))
(str "0" s)
s)))
(defn denormalize-color [[r g b]]
(str "#"
(to-hex (int (* 255 r)))
(to-hex (int (* 255 g)))
(to-hex (int (* 255 b)))))
(defn calculate-color [start end perc]
(let [[rs gs bs] (normalize-color-str start)
[re ge be] (normalize-color-str end)
color (denormalize-color [(+ (* perc rs) (* (- 1 perc) re))
(+ (* perc gs) (* (- 1 perc) ge))
(+ (* perc bs) (* (- 1 perc) be))])]
color))
(defn calc-perc [from to x]
(/ (- x from) (- to from)))
(defn build-scaler
"Builds a function that given a number in [orig-from...orig-to] range will
yield a proportional number in the [dest-from...dest-to] range."
[orig-from orig-to dest-from dest-to]
(fn [x]
(let [p (calc-perc orig-from orig-to x)]
(+ (* p (- dest-to dest-from)) dest-from))))
(defn bounding-box [coords]
(reduce (fn [r [x y]]
(-> r
(update :min-x #(min % x))
(update :min-y #(min % y))
(update :max-x #(max % x))
(update :max-y #(max % y))))
{:min-x max-int
:min-y max-int
:max-x min-int
:max-y min-int}
coords))
(defn box-overlap? [box-1 box-2]
(let [overlap-1d? (fn [a1 a2 b1 b2]
(and (>= a2 b1)
(>= b2 a1)))]
(and (overlap-1d? (:min-x box-1) (:max-x box-1) (:min-x box-2) (:max-x box-2))
(overlap-1d? (:min-y box-1) (:max-y box-1) (:min-y box-2) (:max-y box-2)))))
(defn distance [[x1 y1] [x2 y2]]
(sqrt
(+ (pow (- x2 x1) 2)
(pow (- y2 y1) 2))))
|
9abc6b563576efd5dce7fa199e79a8e7fbf158e15b629bcab7ae9e52ab740c5d | yansh/MoanaML | reteImpl.ml |
* Copyright ( c ) 2015
* 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) 2015 Yan Shvartzshnaider
*
* 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.
*)
module type Rete =
sig
type am
type bm
type t = | Empty | Node of am * bm * t | BNode of Config.tuple list
val join : am -> bm -> bm
end
* AM keeps tuples matching the pattern .
* Each AM also contains vars which is a list of paits ( position , var_string )
* position stands for the position of varibale in a pattern and var_string denotes its string value .
* This is used later when we join AM with BM
*
* Each AM also contains vars which is a list of paits (position, var_string)
* position stands for the position of varibale in a pattern and var_string denotes its string value.
* This is used later when we join AM with BM
*
*)
open Config
module InMemory =
struct
type am =
{ tuples : tuple list;
(* for convinience - direct access to tuples without going through variables. *)
pattern : tuple;
(* this is a mapping of Variables and their respective values in *)
(* each tuple *)
vars : (string * (((t element_type) * tuple) list)) list
}
BM contains ( var , value , solution for the value
type solutions = { solutions : (string * ((t element_type) * (tuple list))) list}
type bm = |InitBM | BM of solutions
type t = | Empty | Node of am * bm * t | BNode of Config.tuple list
(* type am = { pattern: tuple; tuples: tuple list; vars: (string * *)
(* ((element * tuple) list)) list } *)
let val_to_json value = let open Rete_node_t
in
match value with
| Variable x -> { t = `Variable; value_ = x; }
| Constant x -> { t = `Constant; value_ = x; }
let json_to_val jval = let open Rete_node_t
in
match jval with
| { t = `Variable; value_ = x } -> Variable x
| { t = `Constant; value_ = x } -> Constant x
let get_val value = function | Variable x -> x | Constant x -> x
let tpl_to_json tpl = let open Rete_node_t
in
let tpl_json =
{
s = val_to_json tpl.subj;
p = val_to_json tpl.pred;
o = val_to_json tpl.obj;
cxt = val_to_json tpl.ctxt;
time_smp = None;
sign = None;
}
in tpl_json
FIXME : take care of time_stp and signature and that issue with context
let json_to_tpl jtpl = let open Rete_node_t
in
match jtpl with
| {
s = subj;
p = pred;
o = obj;
cxt = ctxt;
time_smp = ts;
sign = sg } ->
{
subj = json_to_val subj;
pred = json_to_val pred;
obj = json_to_val obj;
ctxt = json_to_val ctxt;
time_stp = None;
sign = None;
}
let to_json_tpl_list tuples = List.map (fun t -> tpl_to_json t) tuples
let to_tpl_list tuples = List.map (fun t -> json_to_tpl t) tuples
let v_json vars =
List.map
(fun (var, values) ->
(var,
(List.map
(fun (value, tpl) ->
( val_to_json value , ) -- we know it 's
(* constant *)
((get_val () value), (tpl_to_json tpl)))
values)))
vars
let json_to_vars vars =
List.map
(fun (var, values) ->
(var,
(List.map
(fun (value, tpl) ->
( val_to_json value , ) -- we know it 's
(* constant *)
((Constant value), (json_to_tpl tpl)))
values)))
vars
let am_to_json am = (* convert the am/vars mapping into json *)
let open Rete_node_t
in
{
ptrn = tpl_to_json am.pattern;
tpls = to_json_tpl_list am.tuples;
vrs = v_json am.vars;
}
let json_to_am jam = let open Rete_node_t
in
{
pattern = json_to_tpl jam.ptrn;
tuples = to_tpl_list jam.tpls;
vars = json_to_vars jam.vrs;
}
let bm_to_json bm = let open Rete_node_t in
match bm with
| InitBM -> {sols = []}
| BM bm ->
{
sols =
List.map
(fun (var, values) ->
match values with
| (value, tpls) ->
(var, ((get_val () value), (to_json_tpl_list tpls))))
bm.solutions;
}
let json_to_bm jbm = let open Rete_node_t
in
match jbm with
| `InitBM -> BM {solutions = []}
| `BM jbm ->
BM {
solutions =
List.map
(fun (var, values) ->
match values with
| (value, tpls) ->
(var, ((Constant value), (to_tpl_list tpls))))
jbm;
}
let rec node_to_json node =
match node with
| Node (am, bm, next_node) -> let open Rete_node_t
in
`Node ((`AM (am_to_json am)), (`BM (bm_to_json bm)),
(node_to_json next_node))
| BNode tuples -> `BNode (to_json_tpl_list tuples)
| Empty -> `Empty
let rec json_to_node jnode = let open Rete_node_t
in
match jnode with
| `Node ((`AM jam), (`BM jbm), (`Node next_node)) ->
Node ((json_to_am jam), (json_to_bm jbm),
(json_to_node next_node))
| `BNode tuples -> BNode (to_tpl_list tuples)
| `Empty -> Empty
let node_json_to_string jnode =
Rete_node_j.string_of_node_json jnode |>
Yojson.Basic.from_string |>Yojson.Basic.pretty_to_string
(* helper to filter tuples list to form the pattern *)
let filter ptrn tuples =
let cmp p_attr t_attr =
match p_attr with
| Variable _ -> true
| Constant _ -> p_attr = t_attr
in
List.filter
(fun t ->
(cmp ptrn.subj t.subj) &&
((cmp ptrn.pred t.pred) && (cmp ptrn.obj t.obj)))
tuples
(* add value to the list of values associated with the variable *)
let sel_arg arg pos =
match (arg, pos) with
| (Constant _, _) -> None
| (Variable var, pos) -> Some (var, pos)
let mappings p tuples =
List.fold_right
(fun e acc ->
match e with
| Some (var, 1) ->
acc @ [ (var, (List.map (fun t -> ((t.subj), t)) tuples)) ]
| Some (var, 2) ->
acc @ [ (var, (List.map (fun t -> ((t.pred), t)) tuples)) ]
acc @ [ ( var , List.map ( fun t - > print_value t.pred ; t.pred ) tuples ) ]
Some (var, 3) ->
acc @ [ (var, (List.map (fun t -> ((t.obj), t)) tuples)) ]
| Some (_, _) -> acc
| None -> acc)
[ sel_arg p.subj 1; sel_arg p.pred 2; sel_arg p.obj 3 ] []
(* helper to print the mappings *)
let print_mappings am =
List.map
(fun (var, values) ->
(print_string var;
List.map
(fun value ->
match value with
| (Constant x, t) ->
(print_endline "";
print_string x;
print_endline (Helper.to_string t))
| (Variable _, _) -> print_string " ")
values))
am.vars
let create_am p tuples_ =
{
pattern = p;
tuples = filter p tuples_;
vars =
if (List.length tuples_) > 0
then mappings p (filter p tuples_)
else [];
}
helper to print BM
let print_bm bm =
match bm with
| InitBM -> print_string "Empty (init) BM"
| BM bm ->
List.iter
(fun (var, (value, tuples)) ->
(* (string * (t element_type * tuple list) ) *)
(print_endline "";
print_endline var;
Helper.print_value value;
print_string "[";
List.iter (fun t -> print_string (Helper.to_string t)) tuples))
bm.solutions
joining BM and AM to create a new BM
let gen_first_bm am=
{
solutions =
List.fold_right
(fun (var, values) acc ->
(* string * ((t element_type * tuple) list) am: (t *)
(* element_type * tuple list) *)
acc @
(List.map
(fun (value, tuple) -> (var, (value, [ tuple ])))
values))
am.vars []}
let join am bm =
match bm with
| InitBM ->
BM { solutions = List.fold_right
(fun (var, values) acc ->
(* string * ((t element_type * tuple) list) am: (t *)
(* element_type * tuple list) *)
acc @
(List.map
(fun (value, tuple) -> (var, (value, [ tuple ])))
values))
am.vars []}
| BM {solutions = solutions} ->
BM {solutions =
(* (string * (t element_type * tuple list) ) list * -- existing *)
(* solution *)
List.fold_right (* string * ((t element_type * tuple) list) *)
(* am: (t element_type * tuple) list) *)
(fun (am_var, am_values) acc ->
try
let _ = List.assoc am_var solutions in
(* filter all the solutions assoc with the variable *)
let sol_list =
List.filter (fun (bm_var, _) -> bm_var = am_var)
solutions in
let sol =
List.fold_right
(fun (_, (bm_value, sol_tuples)) acc_f ->
(* filter tuples that have matching values to *)
(* corresponding variable *)
let fltr_list =
List.filter
(fun (value, _) -> value = bm_value)
am_values
in
acc_f @
(List.map
(fun (_, tuple) ->
(am_var,
(bm_value, (tuple :: sol_tuples))))
fltr_list))
sol_list []
in sol
with
In a nutshell , when a variable from an AM is not found in BM solution set
(* we apply_ptrn to find values for other variable in *)
(* the tuple. Eg., in case we have pattern ?x type ?y *)
and ? x is not found in BM solutions the we check
the value for ? y and see if ? y appears in the BM ,
(* if does we add the *)
(* tuple to the solution *) Not_found ->
let apply_ptrn p tuple =
List.fold_right
(fun e acc ->
match e with
| Some (var, 1) ->
if var <> am_var
then acc @ [ (var, ((tuple.subj), tuple)) ]
else acc
| Some (var, 2) ->
if var <> am_var
then acc @ [ (var, ((tuple.pred), tuple)) ]
else acc
| Some (var, 3) ->
if var <> am_var
then acc @ [ (var, ((tuple.obj), tuple)) ]
else acc
| Some (_, _) -> acc
| None -> acc)
[ sel_arg p.subj 1; sel_arg p.pred 2;
sel_arg p.obj 3 ]
[]
in
acc @
(List.fold_right
(fun (am_value, tuple) acc1 ->
acc1 @
(List.fold_right
(fun (var, (value, tuple)) acc2 ->
(* filter all the solutions assoc *)
(* with the variable *)
let sol_list =
List.filter
(fun
(bm_var,
(bm_value, sol_tuples))
->
(bm_var = var) &&
(bm_value = value))
solutions
in
List.map
(fun
(bm_var,
(bm_value, sol_tuples))
->
(am_var,
(am_value,
(tuple :: sol_tuples))))
sol_list)
(apply_ptrn am.pattern tuple) []))
am_values []))
am.vars [];}
* gerenate RETE data from list of AMs *
let gen_rete ams =
let first_am = List.hd ams in
let empty_bm = { solutions = [ ] ; } in
let tail = List.tl ams in
let res_list =
List.fold_right
(fun am acc ->
let (_, prev_bm) = List.hd acc in (am, (join am prev_bm)) :: acc)
(List.rev tail) [ (first_am, (join first_am InitBM)) ]
in
List.fold_right (fun (am, bm) acc -> Node (am, bm, acc)) res_list
Empty
let compare q tpl =
let ( = ) v1 v2 =
match (v1, v2) with
| (Variable _, _) -> true
| (Constant x, Constant y) -> if x = y then true else false
| (_, Variable _) -> false in
let { subj = s; pred = p; obj = o; ctxt = c; time_stp = _; sign = _ } =
q
and
{
subj = q_s;
pred = q_p;
obj = q_o;
ctxt = q_c;
time_stp = _;
sign = _
} = tpl
in (s = q_s) && ((p = q_p) && ((o = q_o) && (c = q_c)))
(** add tuple to an existing AM **)
FIX ME : implement efficient way to create new AM from the old one
let add rete_network tuple =
let get_bm node =
match node with
| Node (_, bm, _) -> bm
| Empty -> InitBM in (*{ solutions = []; } in*)
let rec regen rete_network =
match rete_network with
| Node (current_am, bm, node) ->
if not (compare current_am.pattern tuple)
then (*-let p= print_bm bm in*)
(let next_node = regen node
in
Node (current_am, (join current_am (get_bm next_node)),
next_node))
else
(let new_am =
create_am current_am.pattern (tuple :: current_am.tuples)
in
(* in let p3 = print_mappings new_am in let p4 = print_bm *)
( get_bm node ) in let p4 = print_string " AFTER -- " in
let print_bm ( join new_am ( get_bm node ) ) in let p6 =
(* print_string " END" *)
Node (new_am, (join new_am (get_bm node)), node))
| Empty -> Empty
in regen rete_network
(* add list of tuples *)
let add_tuples rete_network tuples =
List.fold_right (fun tpl acc -> add acc tpl) tuples rete_network
(*** given rete network start activations **)
let rec execute_rete rete_network =
let get_bm node =
match node with
| Node (_, bm, _) -> bm
| Empty -> BM { solutions = []; }
in
match rete_network with
| Node (am, _, node) ->
Node (am, (join am (get_bm node)), (execute_rete node))
| Empty -> Empty
(** generate rete network from a list of query tuples *)
let to_rete_dataflow queries tuples =
let x = print_string " Initial Length : " ; print_string
( string_of_int ( queries ) ) in
let am_list = List.map (fun q -> create_am q []) queries in
let x = print_string " Length : " ; print_string ( string_of_int
( am_list ) ) in
let rn =
match am_list with
| [] -> (print_string "for some reason the AM list is empty"; Empty)
| l -> gen_rete l in
let new_rn = match tuples with | [] -> rn | tpls -> add_tuples rn tpls
in
let ( Helper.flatten_tuple_list
( get_sol_tuples new_rn ) ) in let ( _ , bm , _ ) = new_rn in
(* print_bm bm; *)
new_rn
(** function to create rete newtork from a query **)
let to_rete str tuples =
let qs = Helper.str_query_list str in
let ams = List.map (fun q -> create_am q tuples) qs in gen_rete ams
* function to return a list of values for a particular variable in the solution ( BM ) *
let get_lst_value bm var =
List.fold_right
(fun (v, (value, _)) acc2 ->
(* (string * (t element_type * tuple list) ) *)
if var = v then value :: acc2 else acc2)
bm.solutions []
* deprecated : function to return a list of values for a particular variable in the solution ( BM ) *
helper to print BM
List.fold_right
(fun var acc ->
let sols =
List.fold_right
(fun (v, (value, _)) acc2 ->
(* (string * (t element_type * tuple list) ) *)
if var = v then value :: acc2 else List.rev acc2)
bm.solutions []
in if (List.length sols) <> 0 then [ (var, sols) ] @ acc else acc)
vars []
* function to return a Map of values for a particular variable in the solution ( BM ) *
helper to print BM
List.fold_right
(fun var acc ->
let sols =
List.fold_right
(fun (v, (value, _)) acc2 ->
(* (string * (t element_type * tuple list) ) *)
if var = v then value :: acc2 else List.rev acc2)
bm.solutions []
in
if (List.length sols) <> 0
then Helper.StringMap.add var sols acc
else acc)
vars Helper.StringMap.empty
(** given rete network get the current values associated with var **)
let rec get_values rete_network (vars : string list) =
(* check whether the variable has been found, return vars that still *)
(* missing * *)
let missing_vars values_map =
List.filter (fun v -> not (Helper.StringMap.mem v values_map)) vars
in
match rete_network with
| Node (_, BM bm, node) ->
let values_map = get_values_map bm vars in
let mvars = missing_vars values_map
in
(Helper.StringMap.bindings values_map) @
(get_values node mvars)
| Empty -> []
* generates a MAP with Var , Values pairs from the results *
let get_res_map rete_network vars =
let res_map = Helper.StringMap.empty in
let result = get_values rete_network vars
in
List.fold_right
(fun (var, values) acc -> Helper.StringMap.add var values acc)
result res_map
(** helper method accepts query string and runs it over tuples,
extracts the values associated with the var **)
let exec_qry q tuples =
let network = to_rete q tuples in execute_rete network
let get_tuples network =
let tuples_set = Helper.TupleSet.empty
in
match network with
(* | Node (_, { solutions = sols }, _) ->*)
| Node (_, BM { solutions = sols }, _) ->
List.fold_right
(fun (_, var_sols) acc ->
let (_, tuples) = var_sols
in List.fold_right Helper.TupleSet.add tuples acc)
sols tuples_set
| Empty -> tuples_set
* helper method accepts query string and runs it over tuples in a given BM ,
extracts the values associated with the var *
extracts the values associated with the var **)
let exec_bm q network =
let network = to_rete q (Helper.TupleSet.elements (get_tuples network))
in execute_rete network
(* takes a list of AMs and joins them *)
let execute_am_list ams =
let empty_bm = { solutions = []; }
in List.fold_right (fun am acc -> join am acc) ams InitBM
(* returns solution tuples in a list *)
let get_sol_tuples network =
match network with
| Node (_, BM { solutions = sols }, _) ->
List.fold_right
(fun (_, var_sols) acc ->
let (_, tuples) = var_sols
Helper.print_tuples tuples ;
sols []
| Empty -> []
| BNode tuples -> [ tuples ]
end
| null | https://raw.githubusercontent.com/yansh/MoanaML/c9843c10a0624e1c06e185e3dd1e7d877270d0d7/Rete/reteImpl.ml | ocaml | for convinience - direct access to tuples without going through variables.
this is a mapping of Variables and their respective values in
each tuple
type am = { pattern: tuple; tuples: tuple list; vars: (string *
((element * tuple) list)) list }
constant
constant
convert the am/vars mapping into json
helper to filter tuples list to form the pattern
add value to the list of values associated with the variable
helper to print the mappings
(string * (t element_type * tuple list) )
string * ((t element_type * tuple) list) am: (t
element_type * tuple list)
string * ((t element_type * tuple) list) am: (t
element_type * tuple list)
(string * (t element_type * tuple list) ) list * -- existing
solution
string * ((t element_type * tuple) list)
am: (t element_type * tuple) list)
filter all the solutions assoc with the variable
filter tuples that have matching values to
corresponding variable
we apply_ptrn to find values for other variable in
the tuple. Eg., in case we have pattern ?x type ?y
if does we add the
tuple to the solution
filter all the solutions assoc
with the variable
* add tuple to an existing AM *
{ solutions = []; } in
-let p= print_bm bm in
in let p3 = print_mappings new_am in let p4 = print_bm
print_string " END"
add list of tuples
** given rete network start activations *
* generate rete network from a list of query tuples
print_bm bm;
* function to create rete newtork from a query *
(string * (t element_type * tuple list) )
(string * (t element_type * tuple list) )
(string * (t element_type * tuple list) )
* given rete network get the current values associated with var *
check whether the variable has been found, return vars that still
missing *
* helper method accepts query string and runs it over tuples,
extracts the values associated with the var *
| Node (_, { solutions = sols }, _) ->
takes a list of AMs and joins them
returns solution tuples in a list |
* Copyright ( c ) 2015
* 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) 2015 Yan Shvartzshnaider
*
* 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.
*)
module type Rete =
sig
type am
type bm
type t = | Empty | Node of am * bm * t | BNode of Config.tuple list
val join : am -> bm -> bm
end
* AM keeps tuples matching the pattern .
* Each AM also contains vars which is a list of paits ( position , var_string )
* position stands for the position of varibale in a pattern and var_string denotes its string value .
* This is used later when we join AM with BM
*
* Each AM also contains vars which is a list of paits (position, var_string)
* position stands for the position of varibale in a pattern and var_string denotes its string value.
* This is used later when we join AM with BM
*
*)
open Config
module InMemory =
struct
type am =
{ tuples : tuple list;
pattern : tuple;
vars : (string * (((t element_type) * tuple) list)) list
}
BM contains ( var , value , solution for the value
type solutions = { solutions : (string * ((t element_type) * (tuple list))) list}
type bm = |InitBM | BM of solutions
type t = | Empty | Node of am * bm * t | BNode of Config.tuple list
let val_to_json value = let open Rete_node_t
in
match value with
| Variable x -> { t = `Variable; value_ = x; }
| Constant x -> { t = `Constant; value_ = x; }
let json_to_val jval = let open Rete_node_t
in
match jval with
| { t = `Variable; value_ = x } -> Variable x
| { t = `Constant; value_ = x } -> Constant x
let get_val value = function | Variable x -> x | Constant x -> x
let tpl_to_json tpl = let open Rete_node_t
in
let tpl_json =
{
s = val_to_json tpl.subj;
p = val_to_json tpl.pred;
o = val_to_json tpl.obj;
cxt = val_to_json tpl.ctxt;
time_smp = None;
sign = None;
}
in tpl_json
FIXME : take care of time_stp and signature and that issue with context
let json_to_tpl jtpl = let open Rete_node_t
in
match jtpl with
| {
s = subj;
p = pred;
o = obj;
cxt = ctxt;
time_smp = ts;
sign = sg } ->
{
subj = json_to_val subj;
pred = json_to_val pred;
obj = json_to_val obj;
ctxt = json_to_val ctxt;
time_stp = None;
sign = None;
}
let to_json_tpl_list tuples = List.map (fun t -> tpl_to_json t) tuples
let to_tpl_list tuples = List.map (fun t -> json_to_tpl t) tuples
let v_json vars =
List.map
(fun (var, values) ->
(var,
(List.map
(fun (value, tpl) ->
( val_to_json value , ) -- we know it 's
((get_val () value), (tpl_to_json tpl)))
values)))
vars
let json_to_vars vars =
List.map
(fun (var, values) ->
(var,
(List.map
(fun (value, tpl) ->
( val_to_json value , ) -- we know it 's
((Constant value), (json_to_tpl tpl)))
values)))
vars
let open Rete_node_t
in
{
ptrn = tpl_to_json am.pattern;
tpls = to_json_tpl_list am.tuples;
vrs = v_json am.vars;
}
let json_to_am jam = let open Rete_node_t
in
{
pattern = json_to_tpl jam.ptrn;
tuples = to_tpl_list jam.tpls;
vars = json_to_vars jam.vrs;
}
let bm_to_json bm = let open Rete_node_t in
match bm with
| InitBM -> {sols = []}
| BM bm ->
{
sols =
List.map
(fun (var, values) ->
match values with
| (value, tpls) ->
(var, ((get_val () value), (to_json_tpl_list tpls))))
bm.solutions;
}
let json_to_bm jbm = let open Rete_node_t
in
match jbm with
| `InitBM -> BM {solutions = []}
| `BM jbm ->
BM {
solutions =
List.map
(fun (var, values) ->
match values with
| (value, tpls) ->
(var, ((Constant value), (to_tpl_list tpls))))
jbm;
}
let rec node_to_json node =
match node with
| Node (am, bm, next_node) -> let open Rete_node_t
in
`Node ((`AM (am_to_json am)), (`BM (bm_to_json bm)),
(node_to_json next_node))
| BNode tuples -> `BNode (to_json_tpl_list tuples)
| Empty -> `Empty
let rec json_to_node jnode = let open Rete_node_t
in
match jnode with
| `Node ((`AM jam), (`BM jbm), (`Node next_node)) ->
Node ((json_to_am jam), (json_to_bm jbm),
(json_to_node next_node))
| `BNode tuples -> BNode (to_tpl_list tuples)
| `Empty -> Empty
let node_json_to_string jnode =
Rete_node_j.string_of_node_json jnode |>
Yojson.Basic.from_string |>Yojson.Basic.pretty_to_string
let filter ptrn tuples =
let cmp p_attr t_attr =
match p_attr with
| Variable _ -> true
| Constant _ -> p_attr = t_attr
in
List.filter
(fun t ->
(cmp ptrn.subj t.subj) &&
((cmp ptrn.pred t.pred) && (cmp ptrn.obj t.obj)))
tuples
let sel_arg arg pos =
match (arg, pos) with
| (Constant _, _) -> None
| (Variable var, pos) -> Some (var, pos)
let mappings p tuples =
List.fold_right
(fun e acc ->
match e with
| Some (var, 1) ->
acc @ [ (var, (List.map (fun t -> ((t.subj), t)) tuples)) ]
| Some (var, 2) ->
acc @ [ (var, (List.map (fun t -> ((t.pred), t)) tuples)) ]
acc @ [ ( var , List.map ( fun t - > print_value t.pred ; t.pred ) tuples ) ]
Some (var, 3) ->
acc @ [ (var, (List.map (fun t -> ((t.obj), t)) tuples)) ]
| Some (_, _) -> acc
| None -> acc)
[ sel_arg p.subj 1; sel_arg p.pred 2; sel_arg p.obj 3 ] []
let print_mappings am =
List.map
(fun (var, values) ->
(print_string var;
List.map
(fun value ->
match value with
| (Constant x, t) ->
(print_endline "";
print_string x;
print_endline (Helper.to_string t))
| (Variable _, _) -> print_string " ")
values))
am.vars
let create_am p tuples_ =
{
pattern = p;
tuples = filter p tuples_;
vars =
if (List.length tuples_) > 0
then mappings p (filter p tuples_)
else [];
}
helper to print BM
let print_bm bm =
match bm with
| InitBM -> print_string "Empty (init) BM"
| BM bm ->
List.iter
(fun (var, (value, tuples)) ->
(print_endline "";
print_endline var;
Helper.print_value value;
print_string "[";
List.iter (fun t -> print_string (Helper.to_string t)) tuples))
bm.solutions
joining BM and AM to create a new BM
let gen_first_bm am=
{
solutions =
List.fold_right
(fun (var, values) acc ->
acc @
(List.map
(fun (value, tuple) -> (var, (value, [ tuple ])))
values))
am.vars []}
let join am bm =
match bm with
| InitBM ->
BM { solutions = List.fold_right
(fun (var, values) acc ->
acc @
(List.map
(fun (value, tuple) -> (var, (value, [ tuple ])))
values))
am.vars []}
| BM {solutions = solutions} ->
BM {solutions =
(fun (am_var, am_values) acc ->
try
let _ = List.assoc am_var solutions in
let sol_list =
List.filter (fun (bm_var, _) -> bm_var = am_var)
solutions in
let sol =
List.fold_right
(fun (_, (bm_value, sol_tuples)) acc_f ->
let fltr_list =
List.filter
(fun (value, _) -> value = bm_value)
am_values
in
acc_f @
(List.map
(fun (_, tuple) ->
(am_var,
(bm_value, (tuple :: sol_tuples))))
fltr_list))
sol_list []
in sol
with
In a nutshell , when a variable from an AM is not found in BM solution set
and ? x is not found in BM solutions the we check
the value for ? y and see if ? y appears in the BM ,
let apply_ptrn p tuple =
List.fold_right
(fun e acc ->
match e with
| Some (var, 1) ->
if var <> am_var
then acc @ [ (var, ((tuple.subj), tuple)) ]
else acc
| Some (var, 2) ->
if var <> am_var
then acc @ [ (var, ((tuple.pred), tuple)) ]
else acc
| Some (var, 3) ->
if var <> am_var
then acc @ [ (var, ((tuple.obj), tuple)) ]
else acc
| Some (_, _) -> acc
| None -> acc)
[ sel_arg p.subj 1; sel_arg p.pred 2;
sel_arg p.obj 3 ]
[]
in
acc @
(List.fold_right
(fun (am_value, tuple) acc1 ->
acc1 @
(List.fold_right
(fun (var, (value, tuple)) acc2 ->
let sol_list =
List.filter
(fun
(bm_var,
(bm_value, sol_tuples))
->
(bm_var = var) &&
(bm_value = value))
solutions
in
List.map
(fun
(bm_var,
(bm_value, sol_tuples))
->
(am_var,
(am_value,
(tuple :: sol_tuples))))
sol_list)
(apply_ptrn am.pattern tuple) []))
am_values []))
am.vars [];}
* gerenate RETE data from list of AMs *
let gen_rete ams =
let first_am = List.hd ams in
let empty_bm = { solutions = [ ] ; } in
let tail = List.tl ams in
let res_list =
List.fold_right
(fun am acc ->
let (_, prev_bm) = List.hd acc in (am, (join am prev_bm)) :: acc)
(List.rev tail) [ (first_am, (join first_am InitBM)) ]
in
List.fold_right (fun (am, bm) acc -> Node (am, bm, acc)) res_list
Empty
let compare q tpl =
let ( = ) v1 v2 =
match (v1, v2) with
| (Variable _, _) -> true
| (Constant x, Constant y) -> if x = y then true else false
| (_, Variable _) -> false in
let { subj = s; pred = p; obj = o; ctxt = c; time_stp = _; sign = _ } =
q
and
{
subj = q_s;
pred = q_p;
obj = q_o;
ctxt = q_c;
time_stp = _;
sign = _
} = tpl
in (s = q_s) && ((p = q_p) && ((o = q_o) && (c = q_c)))
FIX ME : implement efficient way to create new AM from the old one
let add rete_network tuple =
let get_bm node =
match node with
| Node (_, bm, _) -> bm
let rec regen rete_network =
match rete_network with
| Node (current_am, bm, node) ->
if not (compare current_am.pattern tuple)
(let next_node = regen node
in
Node (current_am, (join current_am (get_bm next_node)),
next_node))
else
(let new_am =
create_am current_am.pattern (tuple :: current_am.tuples)
in
( get_bm node ) in let p4 = print_string " AFTER -- " in
let print_bm ( join new_am ( get_bm node ) ) in let p6 =
Node (new_am, (join new_am (get_bm node)), node))
| Empty -> Empty
in regen rete_network
let add_tuples rete_network tuples =
List.fold_right (fun tpl acc -> add acc tpl) tuples rete_network
let rec execute_rete rete_network =
let get_bm node =
match node with
| Node (_, bm, _) -> bm
| Empty -> BM { solutions = []; }
in
match rete_network with
| Node (am, _, node) ->
Node (am, (join am (get_bm node)), (execute_rete node))
| Empty -> Empty
let to_rete_dataflow queries tuples =
let x = print_string " Initial Length : " ; print_string
( string_of_int ( queries ) ) in
let am_list = List.map (fun q -> create_am q []) queries in
let x = print_string " Length : " ; print_string ( string_of_int
( am_list ) ) in
let rn =
match am_list with
| [] -> (print_string "for some reason the AM list is empty"; Empty)
| l -> gen_rete l in
let new_rn = match tuples with | [] -> rn | tpls -> add_tuples rn tpls
in
let ( Helper.flatten_tuple_list
( get_sol_tuples new_rn ) ) in let ( _ , bm , _ ) = new_rn in
new_rn
let to_rete str tuples =
let qs = Helper.str_query_list str in
let ams = List.map (fun q -> create_am q tuples) qs in gen_rete ams
* function to return a list of values for a particular variable in the solution ( BM ) *
let get_lst_value bm var =
List.fold_right
(fun (v, (value, _)) acc2 ->
if var = v then value :: acc2 else acc2)
bm.solutions []
* deprecated : function to return a list of values for a particular variable in the solution ( BM ) *
helper to print BM
List.fold_right
(fun var acc ->
let sols =
List.fold_right
(fun (v, (value, _)) acc2 ->
if var = v then value :: acc2 else List.rev acc2)
bm.solutions []
in if (List.length sols) <> 0 then [ (var, sols) ] @ acc else acc)
vars []
* function to return a Map of values for a particular variable in the solution ( BM ) *
helper to print BM
List.fold_right
(fun var acc ->
let sols =
List.fold_right
(fun (v, (value, _)) acc2 ->
if var = v then value :: acc2 else List.rev acc2)
bm.solutions []
in
if (List.length sols) <> 0
then Helper.StringMap.add var sols acc
else acc)
vars Helper.StringMap.empty
let rec get_values rete_network (vars : string list) =
let missing_vars values_map =
List.filter (fun v -> not (Helper.StringMap.mem v values_map)) vars
in
match rete_network with
| Node (_, BM bm, node) ->
let values_map = get_values_map bm vars in
let mvars = missing_vars values_map
in
(Helper.StringMap.bindings values_map) @
(get_values node mvars)
| Empty -> []
* generates a MAP with Var , Values pairs from the results *
let get_res_map rete_network vars =
let res_map = Helper.StringMap.empty in
let result = get_values rete_network vars
in
List.fold_right
(fun (var, values) acc -> Helper.StringMap.add var values acc)
result res_map
let exec_qry q tuples =
let network = to_rete q tuples in execute_rete network
let get_tuples network =
let tuples_set = Helper.TupleSet.empty
in
match network with
| Node (_, BM { solutions = sols }, _) ->
List.fold_right
(fun (_, var_sols) acc ->
let (_, tuples) = var_sols
in List.fold_right Helper.TupleSet.add tuples acc)
sols tuples_set
| Empty -> tuples_set
* helper method accepts query string and runs it over tuples in a given BM ,
extracts the values associated with the var *
extracts the values associated with the var **)
let exec_bm q network =
let network = to_rete q (Helper.TupleSet.elements (get_tuples network))
in execute_rete network
let execute_am_list ams =
let empty_bm = { solutions = []; }
in List.fold_right (fun am acc -> join am acc) ams InitBM
let get_sol_tuples network =
match network with
| Node (_, BM { solutions = sols }, _) ->
List.fold_right
(fun (_, var_sols) acc ->
let (_, tuples) = var_sols
Helper.print_tuples tuples ;
sols []
| Empty -> []
| BNode tuples -> [ tuples ]
end
|
9b03c16aec76ea989255f8f11a65d2f410ee6fee65d612d7fcc974ff6f46ffe5 | kana/sicp | ex-3.61.scm | Exercise 3.61 . Let S be a power series ( exercise 3.59 ) whose constant term
is 1 . Suppose we want to find the power series 1 / S , that is , the series
X such that S · X = 1 . Write S = 1 + S_R where S_R is the part of S after
;;; the constant term. Then we can solve for X as follows:
;;;
S・X = 1
( 1+S_R)・X = 1
X + S_R・X = 1
;;; X = 1 - S_R・X
;;;
In other words , X is the power series whose constant term is 1 and whose
higher - order terms are given by the negative of S_R times X. Use this idea
to write a procedure invert - unit - series that computes 1 / S for a power
series S with constant term 1 . You will need to use mul - series from
exercise 3.60 .
(define (invert-unit-series S)
(define X (cons-stream 1
(mul-series (scale-stream (stream-cdr S) -1)
X)))
X)
| null | https://raw.githubusercontent.com/kana/sicp/912bda4276995492ffc2ec971618316701e196f6/ex-3.61.scm | scheme | the constant term. Then we can solve for X as follows:
X = 1 - S_R・X
| Exercise 3.61 . Let S be a power series ( exercise 3.59 ) whose constant term
is 1 . Suppose we want to find the power series 1 / S , that is , the series
X such that S · X = 1 . Write S = 1 + S_R where S_R is the part of S after
S・X = 1
( 1+S_R)・X = 1
X + S_R・X = 1
In other words , X is the power series whose constant term is 1 and whose
higher - order terms are given by the negative of S_R times X. Use this idea
to write a procedure invert - unit - series that computes 1 / S for a power
series S with constant term 1 . You will need to use mul - series from
exercise 3.60 .
(define (invert-unit-series S)
(define X (cons-stream 1
(mul-series (scale-stream (stream-cdr S) -1)
X)))
X)
|
c52a73ea5e29e06223b2654d2af7f0e1ad43638aabad4f9329c9cc9588d2138d | unclechu/xlib-keys-hack | Main.hs | Author :
License : -keys-hack/master/LICENSE
# LANGUAGE NoMonomorphismRestriction , FlexibleContexts , DataKinds #
{-# LANGUAGE ScopedTypeVariables, TupleSections #-}
module Main (main) where
import "base" Data.Proxy (Proxy (Proxy))
import "base" Data.Word (Word8)
import "base" Data.Maybe (fromJust)
import "base" Data.List (intercalate)
import "base" Data.Typeable (Typeable)
import "data-default" Data.Default (def)
import "qm-interpolated-string" Text.InterpolatedString.QM (qm, qms, qns)
import qualified "containers" Data.Map.Strict as Map
import "containers" Data.Map.Strict (type Map)
import "deepseq" Control.DeepSeq (deepseq, force)
import qualified "mtl" Control.Monad.State as St (get, gets, put, modify)
import "mtl" Control.Monad.State (StateT, execStateT, evalStateT)
import "base" Control.Monad.IO.Class (liftIO)
import "transformers" Control.Monad.Trans.Class (lift)
import "transformers" Control.Monad.Trans.Except (runExceptT, throwE)
import "base" Control.Monad ((>=>), when, unless, filterM, forever, forM_, void)
import "lens" Control.Lens ((.~), (^.), set, view)
import "base" Control.Concurrent ( forkIO
, forkFinally
, throwTo
, ThreadId
, threadDelay
, tryTakeMVar
)
import "base" Control.Concurrent.MVar (newMVar, modifyMVar_, readMVar)
import "base" Control.Concurrent.Chan (Chan, newChan, readChan)
import "base" Control.Exception (Exception (fromException))
import "base" Control.Arrow ((&&&))
import "extra" Control.Monad.Extra (whenJust)
import "base" System.Exit (ExitCode (ExitFailure), exitSuccess)
import "base" System.Environment (getArgs)
import "directory" System.Directory (doesFileExist)
import "unix" System.Posix.Signals ( installHandler
, Handler (Catch)
, sigINT
, sigTERM
)
import "unix" System.Posix (exitImmediately)
import qualified "base" System.IO as SysIO
import qualified "base" GHC.IO.Handle.FD as IOHandleFD
import "process" System.Process (terminateProcess, waitForProcess)
import qualified "X11" Graphics.X11.Types as XTypes
import qualified "X11" Graphics.X11.ExtraTypes as XTypes
import "X11" Graphics.X11.Xlib.Types (Display)
import "X11" Graphics.X11.Xlib.Display (closeDisplay)
import "X11" Graphics.X11.Xlib.Misc (keysymToKeycode)
import "X11" Graphics.X11.Xlib (displayString)
-- local imports
import "xlib-keys-hack" Utils.Sugar
( (&), (<&>), (.>), (|?|), (?)
, preserveF', unnoticed, apart
)
import "xlib-keys-hack" Utils (errPutStrLn, dieWith)
import "xlib-keys-hack" Bindings.Xkb ( xkbGetDescPtr
, xkbFetchControls
, xkbGetGroupsCount
, xkbGetDisplay
)
import " xlib - keys - hack " Bindings . MoreXlib ( initThreads )
import qualified "xlib-keys-hack" Options as O
import qualified "xlib-keys-hack" Actions
import qualified "xlib-keys-hack" XInput
import qualified "xlib-keys-hack" Keys
import "xlib-keys-hack" Types ( type AlternativeModeState
, type AlternativeModeLevel (..)
)
import "xlib-keys-hack" Actions (ActionType, Action, KeyAction)
import "xlib-keys-hack" IPC ( openIPC
, closeIPC
, setIndicatorState
, logView
)
import "xlib-keys-hack" Process ( initReset
, watchLeds
, handleKeyEvent
, getNextKeyboardDeviceKeyEvent
, getSoftwareDebouncer
, getSoftwareDebouncerTiming
, moveKeyThroughSoftwareDebouncer
, handleNextSoftwareDebouncerEvent
, processWindowFocus
, processKeysActions
, processKeyboardState
)
import qualified "xlib-keys-hack" Process.CrossThread as CrossThread
( toggleAlternative
, turnAlternativeMode
)
import "xlib-keys-hack" State ( CrossThreadVars ( CrossThreadVars
, stateMVar
, actionsChan
, keysActionsChan
)
, State ( isTerminating
, windowFocusProc
, alternative
, kbdLayout
)
, HasState (isTerminating', leds')
, HasLedModes (numLockLed', capsLockLed')
)
type Options = O.Options
type KeyName = Keys.KeyName
type KeyCode = XTypes.KeyCode
-- Bool indicates if it's alive or dead
type ThreadsState = [(Bool, ThreadId)]
main :: IO ()
main = flip evalStateT ([] :: ThreadsState) $ do
opts <- liftIO $ getArgs >>= parseOpts
opts `deepseq` pure ()
let noise = liftIO . O.noise opts
-- We don't need this since we use own X Display instance for every thread
noise " Enabling threads support for Xlib ... "
-- liftIO initThreads
noise "Initialization of Xkb..."
dpy <- liftIO xkbInit -- for main thread
noise "Getting additional X Display for keys actions handler thread..."
dpyForKeysActionsHanlder <- liftIO xkbInit
noise "Getting additional X Display for keyboard state handler thread..."
dpyForKeyboardStateHandler <- liftIO xkbInit
noise "Getting additional X Display for leds watcher thread..."
dpyForLedsWatcher <- liftIO xkbInit
noise "Dynamically getting media keys X key codes..."
(mediaKeysAliases :: Map KeyName KeyCode) <- liftIO $ Map.fromList <$> mapM
(\(keyName, keySym) -> (keyName,) <$> keysymToKeycode dpy keySym)
[ (Keys.MCalculatorKey, XTypes.xF86XK_Calculator)
, (Keys.MEjectKey, XTypes.xF86XK_Eject)
, (Keys.MAudioMuteKey, XTypes.xF86XK_AudioMute)
, (Keys.MAudioLowerVolumeKey, XTypes.xF86XK_AudioLowerVolume)
, (Keys.MAudioRaiseVolumeKey, XTypes.xF86XK_AudioRaiseVolume)
, (Keys.MAudioPlayKey, XTypes.xF86XK_AudioPlay)
, (Keys.MAudioStopKey, XTypes.xF86XK_AudioStop)
, (Keys.MAudioPrevKey, XTypes.xF86XK_AudioPrev)
, (Keys.MAudioNextKey, XTypes.xF86XK_AudioNext)
, (Keys.MMonBrightnessDownKey, XTypes.xF86XK_MonBrightnessDown)
, (Keys.MMonBrightnessUpKey, XTypes.xF86XK_MonBrightnessUp)
]
noise
$ "Media keys aliases:"
<> Map.foldMapWithKey (\a b -> [qm|\n {a}: {b}|]) mediaKeysAliases
keyMap <-
let failure err = liftIO $ dieWith [qm| Failed to construct KeyMap: {err} |]
in either failure pure $ Keys.getKeyMap opts mediaKeysAliases
-- Making it fail at start app time if media keys described incorrectly
keyMap `deepseq` pure ()
!capsLockKeyDef <-
let
key = Keys.CapsLockKey
failure = liftIO $ dieWith [qm| Failed to obtain {key} code |]
success = pure . (Proxy :: Proxy 'Keys.CapsLockKey,)
in
maybe failure success $ Keys.getDefaultKeyCodeByName keyMap key
when (O.shiftNumericKeys opts) $
noise "Numeric keys in numbers row are shifted"
noise "Making cross-thread variables..."
ctVars <- liftIO $ do
ctState <- newMVar $ force def
(ctActions :: Chan (ActionType Action)) <- newChan
(ctKeysActions :: Chan (ActionType KeyAction)) <- newChan
pure CrossThreadVars { stateMVar = ctState
, actionsChan = ctActions
, keysActionsChan = ctKeysActions
}
ctVars `deepseq` pure ()
ipcHandle <- preserveF' (O.xmobarIndicators opts || O.externalControl opts) $
do let for = intercalate " and "
$ (O.xmobarIndicators opts ? ["xmobar indicators"] $ mempty)
<> (O.externalControl opts ? ["external control"] $ mempty)
in noise [qm| Opening DBus connection for {for}... |]
h <- let flush = Actions.flushXmobar opts ctVars
_noise' :: [String] -> IO ()
_noise' = Actions.noise' opts ctVars
_notify' :: [Actions.XmobarFlag] -> IO ()
_notify' = Actions.notifyXmobar' opts ctVars
_toggleAlternative :: IO ()
_toggleAlternative =
modifyMVar_ (State.stateMVar ctVars) $
CrossThread.toggleAlternative _noise' _notify'
_turnAlternativeMode :: AlternativeModeState -> IO ()
_turnAlternativeMode to =
modifyMVar_ (State.stateMVar ctVars) $
flip (CrossThread.turnAlternativeMode _noise' _notify') to
altModeChange :: Either () AlternativeModeState -> IO ()
altModeChange (Left ()) = _toggleAlternative
altModeChange (Right x) = _turnAlternativeMode x
in lift $ openIPC (displayString dpy) opts flush altModeChange
h <$ noise (logView h)
noise "Initial resetting..."
liftIO $ initReset opts ipcHandle capsLockKeyDef dpy
let termHook = Actions.initTerminate ctVars
catch sig = installHandler sig (Catch termHook) Nothing
in liftIO $ mapM_ catch [sigINT, sigTERM]
let runThread :: String -> IO () -> StateT ThreadsState IO ()
runThread threadName m = go where
go = do
noise [qm| Starting {threadName} thread... |]
(ids, tIdx) <- St.gets $ id &&& length
tId <- liftIO $ forkFinally m $ handleFork tIdx
St.put $ (True, tId) : ids
handleFork idx = \case
Left e ->
case fromException e of
Just MortifyThreadException ->
Actions.threadIsDeath ctVars threadName idx
_ -> do
Actions.panicNoise ctVars
[qm| Unexpected thread #{idx} "{threadName}" exception: {e} |]
Actions.overthrow ctVars
Right _ -> do
Actions.panicNoise ctVars
[qm| Thread #{idx} "{threadName}" unexpectedly terminated |]
Actions.overthrow ctVars
runThread "keys actions handler" $
processKeysActions ctVars opts capsLockKeyDef
dpyForKeysActionsHanlder
runThread "keyboard state handler" $
processKeyboardState ctVars opts dpyForKeyboardStateHandler
when (O.resetByWindowFocusEvent opts) $
runThread "window focus handler" $ processWindowFocus ctVars opts
runThread "leds watcher" $ watchLeds ctVars opts dpyForLedsWatcher
noise "Starting device handle threads (one thread per device)..."
let keyEventHandler = handleKeyEvent ctVars opts keyMap
O.handleDeviceFd opts `forM_` \fd -> do
liftIO (getSoftwareDebouncer opts) >>= \case
Nothing ->
runThread [qm| handler for device: {fd} |] $ forever $
getNextKeyboardDeviceKeyEvent keyMap fd >>= keyEventHandler
Just softwareDebouncer -> do
let timing = round $
getSoftwareDebouncerTiming softwareDebouncer * 1000 :: Word8
runThread [qms| software debouncer (with timing: {timing}ms)
debounced events handling for device: {fd} |]
$ forever
$ handleNextSoftwareDebouncerEvent softwareDebouncer
>>= pure () `maybe` keyEventHandler
runThread [qms| handler for device
(with software debouncer timing: {timing}ms): {fd} |]
$ forever
$ getNextKeyboardDeviceKeyEvent keyMap fd
>>= moveKeyThroughSoftwareDebouncer softwareDebouncer
>>= pure () `maybe` keyEventHandler
St.modify reverse -- Threads in order they have been forked
noise "Listening for actions in main thread..."
forever $ do
(action :: ActionType Action) <- liftIO $ readChan $ actionsChan ctVars
let f :: ActionType Action -> StateT ThreadsState IO ()
f (Actions.Single a) = m a
f (Actions.Sequence []) = pure ()
f (Actions.seqHead -> (x, xs)) = m x >> f xs
m :: Action -> StateT ThreadsState IO ()
m (Actions.Noise msg) = noise msg
m (Actions.PanicNoise msg) = liftIO $ errPutStrLn msg
m (Actions.NotifyXmobar x) = whenJust ipcHandle $ \ipc ->
let flag a isOn title = do
noise [qms| Setting xmobar {title} indicator state
{isOn ? "On" $ "Off"}... |]
liftIO $ setIndicatorState ipc a
value a v title = do
noise [qm| Setting xmobar {title} indicator value to '{v}'... |]
liftIO $ setIndicatorState ipc a
flush = do
noise "Flushing all xmobar indicators..."
state <- liftIO $ readMVar $ State.stateMVar ctVars
handle $ Actions.XmobarNumLockFlag
$ state ^. State.leds' . State.numLockLed'
handle $ Actions.XmobarCapsLockFlag
$ state ^. State.leds' . State.capsLockLed'
handle $ Actions.XmobarAlternativeFlag
$ State.alternative state
handle $ Actions.XmobarXkbLayout
$ State.kbdLayout state
alternativeModeFlag a newModeState = do
let showPermament = "permanently" |?| "temporarily"
let showLevel FirstAlternativeModeLevel = "1st level"
showLevel SecondAlternativeModeLevel = "2nd level"
let showState = maybe "Off" $ \(level, isPermanent) ->
[qms| On {showPermament isPermanent}
on {showLevel level} |]
noise [qms| Setting xmobar Alternative Mode indicator state
{showState newModeState}... |]
liftIO $ setIndicatorState ipc a
handle a = case a of
Actions.XmobarFlushAll -> flush
Actions.XmobarNumLockFlag y -> flag a y "Num Lock"
Actions.XmobarCapsLockFlag y -> flag a y "Caps Lock"
Actions.XmobarAlternativeFlag y -> alternativeModeFlag a y
Actions.XmobarXkbLayout y -> value a y "Keyboard layout"
in handle x
m Actions.InitTerminate = do
liftIO handleTerminationTimeout
threads <- St.get
liftIO $ modifyMVar_ (State.stateMVar ctVars)
$ execStateT . runExceptT $ do
-- Check if termination process already initialized
St.gets (not . State.isTerminating)
>>= pure () |?| let s = [qns| Attempt to initialize application
termination process when it's
already initialized was skipped |]
in noise s >> throwE ()
St.modify $ State.isTerminating' .~ True
noise "Application termination process initialization..."
liftIO $ forM_ threads $ snd .> flip throwTo MortifyThreadException
m (Actions.ThreadIsDead threadName tIdx) = do
let markAsDead (_, []) = []
markAsDead (l, (_, x) : xs) = l <> ((False, x) : xs)
in St.modify $ splitAt tIdx .> markAsDead
(dead, total) <- St.gets $ length . filter not . map fst &&& length
noise [qms| Thread #{tIdx + 1} "{threadName}" is dead
({dead} of {total} is dead) |]
when (dead == total) $ liftIO $ Actions.overthrow ctVars
m Actions.JustDie = do
liftIO handleTerminationTimeout
noise "Application is going to die"
noise "Closing devices files descriptors..."
O.handleDeviceFd opts `forM_` \fd -> do
noise [qm| Closing device file descriptor: {fd}... |]
liftIO $ SysIO.hClose fd
let close h = noise "Closing DBus connection..." >> lift (closeIPC h)
in maybe (pure ()) close ipcHandle
noise "Closing X Display descriptors..."
liftIO $ mapM_ closeDisplay [ dpy
, dpyForKeysActionsHanlder
, dpyForKeyboardStateHandler
, dpyForLedsWatcher
]
when (O.resetByWindowFocusEvent opts) $
liftIO $ tryTakeMVar (State.stateMVar ctVars)
<&> fmap State.windowFocusProc
>>= let fm (fromJust -> Just (execFilePath, procH, outH)) = do
noise [qms| Terminating of window focus events watcher
'{execFilePath}' subprocess... |]
liftIO $ SysIO.hClose outH
liftIO $ terminateProcess procH
exitCode <- liftIO $ waitForProcess procH
noise [qms| Subprocess '{execFilePath}' terminated
with exit code: {exitCode} |]
fm _ = pure ()
in fm
noise "Enabling disabled before XInput devices back..."
liftIO $ XInput.enable opts
noise "The end"
liftIO exitSuccess
in f action
Parses arguments and returns options data structure
-- or shows usage info and exit the application
-- (by --help flag or because of error).
getOptsFromArgs :: [String] -> IO Options
getOptsFromArgs argv = case O.extractOptions argv of
Left err -> errPutStrLn O.usageInfo >> dieWith err
Right opts -> do
when (O.showHelp opts) $ do
putStrLn O.usageInfo
exitSuccess
O.handleDevicePath opts & length & (> 0) & \x -> unless x $ do
errPutStrLn O.usageInfo
dieWith "At least one device fd path must be specified!"
O.noise opts "Started in verbose mode"
pure opts
-- Filters only existing descriptors files of devices,
-- stores this list to 'availableDevices' option and
-- open these files to read and puts these descriptors to
-- 'handleDeviceFd' option or fail the application
-- if there's no available devices.
extractAvailableDevices :: Options -> IO Options
extractAvailableDevices
= execStateT
$ St.gets O.noise
>>= \noise -> St.gets (view O.handleDevicePath')
>>= lift . filterM doesFileExist
>>= ( unnoticed $ length .> \availableDevicesCount ->
unless (availableDevicesCount > 0) $ lift $ dieWith
"All specified devices to get events from is unavailable!"
)
>>= ( unnoticed $ lift . noise
. ("Devices that will be handled:" <>) . foldMap ("\n " <>)
)
>>= unnoticed (St.modify . set O.availableDevices')
>>= ( apart $ lift
$ noise "Opening devices files descriptors for reading..."
)
>>= lift . mapM (`IOHandleFD.openFile` SysIO.ReadMode)
>>= St.modify . set O.handleDeviceFd'
-- Completely parse input arguments and returns options
-- data structure based on them.
parseOpts :: [String] -> IO Options
parseOpts = go where
go
= getOptsFromArgs
>=> extractAvailableDevices
>=> XInput.getAvailable
>=> unnoticed XInput.disable
>=> logDisabled
logDisabled :: Options -> IO Options
logDisabled opts
= O.availableXInputDevices opts
& ("XInput devices ids that was disabled: " <>) . show
& (\x -> opts <$ O.noise opts x)
-- For situations when something went wrong and application
-- can't finish its stuff correctly.
handleTerminationTimeout :: IO ()
handleTerminationTimeout = void $ forkIO $ do
threadDelay $ terminationTimeout * 1000 * 1000
errPutStrLn [qms| Termination process timeout
after {terminationTimeout} seconds,
just exiting immidiately... |]
exitImmediately $ ExitFailure 1
and Xkb and checks if everything is okay
and returns Xlib Display pointer then .
xkbInit :: IO Display
xkbInit = do
(dpy :: Display) <- xkbGetDisplay >>= (`either` pure)
(\err -> dieWith [qm| Xkb open display error: {err} |])
xkbDescPtr <- xkbGetDescPtr dpy >>= (`either` pure)
(\err -> dieWith [qm| Xkb error: get keyboard data error: {err} |])
xkbFetchControls dpy xkbDescPtr
>>= (`unless` dieWith "Xkb error: fetch controls error")
(> 0) <$> xkbGetGroupsCount xkbDescPtr
>>= (`unless` dieWith "Xkb error: groups count is 0")
pure dpy
data MyThreadException = MortifyThreadException deriving (Show, Typeable)
instance Exception MyThreadException
In seconds
terminationTimeout :: Int
terminationTimeout = 5
| null | https://raw.githubusercontent.com/unclechu/xlib-keys-hack/33b49a9b1fc4bc87bdb95e2bb632a312ec2ebad0/app/XlibKeysHack/Main.hs | haskell | # LANGUAGE ScopedTypeVariables, TupleSections #
local imports
Bool indicates if it's alive or dead
We don't need this since we use own X Display instance for every thread
liftIO initThreads
for main thread
Making it fail at start app time if media keys described incorrectly
Threads in order they have been forked
Check if termination process already initialized
or shows usage info and exit the application
(by --help flag or because of error).
Filters only existing descriptors files of devices,
stores this list to 'availableDevices' option and
open these files to read and puts these descriptors to
'handleDeviceFd' option or fail the application
if there's no available devices.
Completely parse input arguments and returns options
data structure based on them.
For situations when something went wrong and application
can't finish its stuff correctly. | Author :
License : -keys-hack/master/LICENSE
# LANGUAGE NoMonomorphismRestriction , FlexibleContexts , DataKinds #
module Main (main) where
import "base" Data.Proxy (Proxy (Proxy))
import "base" Data.Word (Word8)
import "base" Data.Maybe (fromJust)
import "base" Data.List (intercalate)
import "base" Data.Typeable (Typeable)
import "data-default" Data.Default (def)
import "qm-interpolated-string" Text.InterpolatedString.QM (qm, qms, qns)
import qualified "containers" Data.Map.Strict as Map
import "containers" Data.Map.Strict (type Map)
import "deepseq" Control.DeepSeq (deepseq, force)
import qualified "mtl" Control.Monad.State as St (get, gets, put, modify)
import "mtl" Control.Monad.State (StateT, execStateT, evalStateT)
import "base" Control.Monad.IO.Class (liftIO)
import "transformers" Control.Monad.Trans.Class (lift)
import "transformers" Control.Monad.Trans.Except (runExceptT, throwE)
import "base" Control.Monad ((>=>), when, unless, filterM, forever, forM_, void)
import "lens" Control.Lens ((.~), (^.), set, view)
import "base" Control.Concurrent ( forkIO
, forkFinally
, throwTo
, ThreadId
, threadDelay
, tryTakeMVar
)
import "base" Control.Concurrent.MVar (newMVar, modifyMVar_, readMVar)
import "base" Control.Concurrent.Chan (Chan, newChan, readChan)
import "base" Control.Exception (Exception (fromException))
import "base" Control.Arrow ((&&&))
import "extra" Control.Monad.Extra (whenJust)
import "base" System.Exit (ExitCode (ExitFailure), exitSuccess)
import "base" System.Environment (getArgs)
import "directory" System.Directory (doesFileExist)
import "unix" System.Posix.Signals ( installHandler
, Handler (Catch)
, sigINT
, sigTERM
)
import "unix" System.Posix (exitImmediately)
import qualified "base" System.IO as SysIO
import qualified "base" GHC.IO.Handle.FD as IOHandleFD
import "process" System.Process (terminateProcess, waitForProcess)
import qualified "X11" Graphics.X11.Types as XTypes
import qualified "X11" Graphics.X11.ExtraTypes as XTypes
import "X11" Graphics.X11.Xlib.Types (Display)
import "X11" Graphics.X11.Xlib.Display (closeDisplay)
import "X11" Graphics.X11.Xlib.Misc (keysymToKeycode)
import "X11" Graphics.X11.Xlib (displayString)
import "xlib-keys-hack" Utils.Sugar
( (&), (<&>), (.>), (|?|), (?)
, preserveF', unnoticed, apart
)
import "xlib-keys-hack" Utils (errPutStrLn, dieWith)
import "xlib-keys-hack" Bindings.Xkb ( xkbGetDescPtr
, xkbFetchControls
, xkbGetGroupsCount
, xkbGetDisplay
)
import " xlib - keys - hack " Bindings . MoreXlib ( initThreads )
import qualified "xlib-keys-hack" Options as O
import qualified "xlib-keys-hack" Actions
import qualified "xlib-keys-hack" XInput
import qualified "xlib-keys-hack" Keys
import "xlib-keys-hack" Types ( type AlternativeModeState
, type AlternativeModeLevel (..)
)
import "xlib-keys-hack" Actions (ActionType, Action, KeyAction)
import "xlib-keys-hack" IPC ( openIPC
, closeIPC
, setIndicatorState
, logView
)
import "xlib-keys-hack" Process ( initReset
, watchLeds
, handleKeyEvent
, getNextKeyboardDeviceKeyEvent
, getSoftwareDebouncer
, getSoftwareDebouncerTiming
, moveKeyThroughSoftwareDebouncer
, handleNextSoftwareDebouncerEvent
, processWindowFocus
, processKeysActions
, processKeyboardState
)
import qualified "xlib-keys-hack" Process.CrossThread as CrossThread
( toggleAlternative
, turnAlternativeMode
)
import "xlib-keys-hack" State ( CrossThreadVars ( CrossThreadVars
, stateMVar
, actionsChan
, keysActionsChan
)
, State ( isTerminating
, windowFocusProc
, alternative
, kbdLayout
)
, HasState (isTerminating', leds')
, HasLedModes (numLockLed', capsLockLed')
)
type Options = O.Options
type KeyName = Keys.KeyName
type KeyCode = XTypes.KeyCode
type ThreadsState = [(Bool, ThreadId)]
main :: IO ()
main = flip evalStateT ([] :: ThreadsState) $ do
opts <- liftIO $ getArgs >>= parseOpts
opts `deepseq` pure ()
let noise = liftIO . O.noise opts
noise " Enabling threads support for Xlib ... "
noise "Initialization of Xkb..."
noise "Getting additional X Display for keys actions handler thread..."
dpyForKeysActionsHanlder <- liftIO xkbInit
noise "Getting additional X Display for keyboard state handler thread..."
dpyForKeyboardStateHandler <- liftIO xkbInit
noise "Getting additional X Display for leds watcher thread..."
dpyForLedsWatcher <- liftIO xkbInit
noise "Dynamically getting media keys X key codes..."
(mediaKeysAliases :: Map KeyName KeyCode) <- liftIO $ Map.fromList <$> mapM
(\(keyName, keySym) -> (keyName,) <$> keysymToKeycode dpy keySym)
[ (Keys.MCalculatorKey, XTypes.xF86XK_Calculator)
, (Keys.MEjectKey, XTypes.xF86XK_Eject)
, (Keys.MAudioMuteKey, XTypes.xF86XK_AudioMute)
, (Keys.MAudioLowerVolumeKey, XTypes.xF86XK_AudioLowerVolume)
, (Keys.MAudioRaiseVolumeKey, XTypes.xF86XK_AudioRaiseVolume)
, (Keys.MAudioPlayKey, XTypes.xF86XK_AudioPlay)
, (Keys.MAudioStopKey, XTypes.xF86XK_AudioStop)
, (Keys.MAudioPrevKey, XTypes.xF86XK_AudioPrev)
, (Keys.MAudioNextKey, XTypes.xF86XK_AudioNext)
, (Keys.MMonBrightnessDownKey, XTypes.xF86XK_MonBrightnessDown)
, (Keys.MMonBrightnessUpKey, XTypes.xF86XK_MonBrightnessUp)
]
noise
$ "Media keys aliases:"
<> Map.foldMapWithKey (\a b -> [qm|\n {a}: {b}|]) mediaKeysAliases
keyMap <-
let failure err = liftIO $ dieWith [qm| Failed to construct KeyMap: {err} |]
in either failure pure $ Keys.getKeyMap opts mediaKeysAliases
keyMap `deepseq` pure ()
!capsLockKeyDef <-
let
key = Keys.CapsLockKey
failure = liftIO $ dieWith [qm| Failed to obtain {key} code |]
success = pure . (Proxy :: Proxy 'Keys.CapsLockKey,)
in
maybe failure success $ Keys.getDefaultKeyCodeByName keyMap key
when (O.shiftNumericKeys opts) $
noise "Numeric keys in numbers row are shifted"
noise "Making cross-thread variables..."
ctVars <- liftIO $ do
ctState <- newMVar $ force def
(ctActions :: Chan (ActionType Action)) <- newChan
(ctKeysActions :: Chan (ActionType KeyAction)) <- newChan
pure CrossThreadVars { stateMVar = ctState
, actionsChan = ctActions
, keysActionsChan = ctKeysActions
}
ctVars `deepseq` pure ()
ipcHandle <- preserveF' (O.xmobarIndicators opts || O.externalControl opts) $
do let for = intercalate " and "
$ (O.xmobarIndicators opts ? ["xmobar indicators"] $ mempty)
<> (O.externalControl opts ? ["external control"] $ mempty)
in noise [qm| Opening DBus connection for {for}... |]
h <- let flush = Actions.flushXmobar opts ctVars
_noise' :: [String] -> IO ()
_noise' = Actions.noise' opts ctVars
_notify' :: [Actions.XmobarFlag] -> IO ()
_notify' = Actions.notifyXmobar' opts ctVars
_toggleAlternative :: IO ()
_toggleAlternative =
modifyMVar_ (State.stateMVar ctVars) $
CrossThread.toggleAlternative _noise' _notify'
_turnAlternativeMode :: AlternativeModeState -> IO ()
_turnAlternativeMode to =
modifyMVar_ (State.stateMVar ctVars) $
flip (CrossThread.turnAlternativeMode _noise' _notify') to
altModeChange :: Either () AlternativeModeState -> IO ()
altModeChange (Left ()) = _toggleAlternative
altModeChange (Right x) = _turnAlternativeMode x
in lift $ openIPC (displayString dpy) opts flush altModeChange
h <$ noise (logView h)
noise "Initial resetting..."
liftIO $ initReset opts ipcHandle capsLockKeyDef dpy
let termHook = Actions.initTerminate ctVars
catch sig = installHandler sig (Catch termHook) Nothing
in liftIO $ mapM_ catch [sigINT, sigTERM]
let runThread :: String -> IO () -> StateT ThreadsState IO ()
runThread threadName m = go where
go = do
noise [qm| Starting {threadName} thread... |]
(ids, tIdx) <- St.gets $ id &&& length
tId <- liftIO $ forkFinally m $ handleFork tIdx
St.put $ (True, tId) : ids
handleFork idx = \case
Left e ->
case fromException e of
Just MortifyThreadException ->
Actions.threadIsDeath ctVars threadName idx
_ -> do
Actions.panicNoise ctVars
[qm| Unexpected thread #{idx} "{threadName}" exception: {e} |]
Actions.overthrow ctVars
Right _ -> do
Actions.panicNoise ctVars
[qm| Thread #{idx} "{threadName}" unexpectedly terminated |]
Actions.overthrow ctVars
runThread "keys actions handler" $
processKeysActions ctVars opts capsLockKeyDef
dpyForKeysActionsHanlder
runThread "keyboard state handler" $
processKeyboardState ctVars opts dpyForKeyboardStateHandler
when (O.resetByWindowFocusEvent opts) $
runThread "window focus handler" $ processWindowFocus ctVars opts
runThread "leds watcher" $ watchLeds ctVars opts dpyForLedsWatcher
noise "Starting device handle threads (one thread per device)..."
let keyEventHandler = handleKeyEvent ctVars opts keyMap
O.handleDeviceFd opts `forM_` \fd -> do
liftIO (getSoftwareDebouncer opts) >>= \case
Nothing ->
runThread [qm| handler for device: {fd} |] $ forever $
getNextKeyboardDeviceKeyEvent keyMap fd >>= keyEventHandler
Just softwareDebouncer -> do
let timing = round $
getSoftwareDebouncerTiming softwareDebouncer * 1000 :: Word8
runThread [qms| software debouncer (with timing: {timing}ms)
debounced events handling for device: {fd} |]
$ forever
$ handleNextSoftwareDebouncerEvent softwareDebouncer
>>= pure () `maybe` keyEventHandler
runThread [qms| handler for device
(with software debouncer timing: {timing}ms): {fd} |]
$ forever
$ getNextKeyboardDeviceKeyEvent keyMap fd
>>= moveKeyThroughSoftwareDebouncer softwareDebouncer
>>= pure () `maybe` keyEventHandler
noise "Listening for actions in main thread..."
forever $ do
(action :: ActionType Action) <- liftIO $ readChan $ actionsChan ctVars
let f :: ActionType Action -> StateT ThreadsState IO ()
f (Actions.Single a) = m a
f (Actions.Sequence []) = pure ()
f (Actions.seqHead -> (x, xs)) = m x >> f xs
m :: Action -> StateT ThreadsState IO ()
m (Actions.Noise msg) = noise msg
m (Actions.PanicNoise msg) = liftIO $ errPutStrLn msg
m (Actions.NotifyXmobar x) = whenJust ipcHandle $ \ipc ->
let flag a isOn title = do
noise [qms| Setting xmobar {title} indicator state
{isOn ? "On" $ "Off"}... |]
liftIO $ setIndicatorState ipc a
value a v title = do
noise [qm| Setting xmobar {title} indicator value to '{v}'... |]
liftIO $ setIndicatorState ipc a
flush = do
noise "Flushing all xmobar indicators..."
state <- liftIO $ readMVar $ State.stateMVar ctVars
handle $ Actions.XmobarNumLockFlag
$ state ^. State.leds' . State.numLockLed'
handle $ Actions.XmobarCapsLockFlag
$ state ^. State.leds' . State.capsLockLed'
handle $ Actions.XmobarAlternativeFlag
$ State.alternative state
handle $ Actions.XmobarXkbLayout
$ State.kbdLayout state
alternativeModeFlag a newModeState = do
let showPermament = "permanently" |?| "temporarily"
let showLevel FirstAlternativeModeLevel = "1st level"
showLevel SecondAlternativeModeLevel = "2nd level"
let showState = maybe "Off" $ \(level, isPermanent) ->
[qms| On {showPermament isPermanent}
on {showLevel level} |]
noise [qms| Setting xmobar Alternative Mode indicator state
{showState newModeState}... |]
liftIO $ setIndicatorState ipc a
handle a = case a of
Actions.XmobarFlushAll -> flush
Actions.XmobarNumLockFlag y -> flag a y "Num Lock"
Actions.XmobarCapsLockFlag y -> flag a y "Caps Lock"
Actions.XmobarAlternativeFlag y -> alternativeModeFlag a y
Actions.XmobarXkbLayout y -> value a y "Keyboard layout"
in handle x
m Actions.InitTerminate = do
liftIO handleTerminationTimeout
threads <- St.get
liftIO $ modifyMVar_ (State.stateMVar ctVars)
$ execStateT . runExceptT $ do
St.gets (not . State.isTerminating)
>>= pure () |?| let s = [qns| Attempt to initialize application
termination process when it's
already initialized was skipped |]
in noise s >> throwE ()
St.modify $ State.isTerminating' .~ True
noise "Application termination process initialization..."
liftIO $ forM_ threads $ snd .> flip throwTo MortifyThreadException
m (Actions.ThreadIsDead threadName tIdx) = do
let markAsDead (_, []) = []
markAsDead (l, (_, x) : xs) = l <> ((False, x) : xs)
in St.modify $ splitAt tIdx .> markAsDead
(dead, total) <- St.gets $ length . filter not . map fst &&& length
noise [qms| Thread #{tIdx + 1} "{threadName}" is dead
({dead} of {total} is dead) |]
when (dead == total) $ liftIO $ Actions.overthrow ctVars
m Actions.JustDie = do
liftIO handleTerminationTimeout
noise "Application is going to die"
noise "Closing devices files descriptors..."
O.handleDeviceFd opts `forM_` \fd -> do
noise [qm| Closing device file descriptor: {fd}... |]
liftIO $ SysIO.hClose fd
let close h = noise "Closing DBus connection..." >> lift (closeIPC h)
in maybe (pure ()) close ipcHandle
noise "Closing X Display descriptors..."
liftIO $ mapM_ closeDisplay [ dpy
, dpyForKeysActionsHanlder
, dpyForKeyboardStateHandler
, dpyForLedsWatcher
]
when (O.resetByWindowFocusEvent opts) $
liftIO $ tryTakeMVar (State.stateMVar ctVars)
<&> fmap State.windowFocusProc
>>= let fm (fromJust -> Just (execFilePath, procH, outH)) = do
noise [qms| Terminating of window focus events watcher
'{execFilePath}' subprocess... |]
liftIO $ SysIO.hClose outH
liftIO $ terminateProcess procH
exitCode <- liftIO $ waitForProcess procH
noise [qms| Subprocess '{execFilePath}' terminated
with exit code: {exitCode} |]
fm _ = pure ()
in fm
noise "Enabling disabled before XInput devices back..."
liftIO $ XInput.enable opts
noise "The end"
liftIO exitSuccess
in f action
Parses arguments and returns options data structure
getOptsFromArgs :: [String] -> IO Options
getOptsFromArgs argv = case O.extractOptions argv of
Left err -> errPutStrLn O.usageInfo >> dieWith err
Right opts -> do
when (O.showHelp opts) $ do
putStrLn O.usageInfo
exitSuccess
O.handleDevicePath opts & length & (> 0) & \x -> unless x $ do
errPutStrLn O.usageInfo
dieWith "At least one device fd path must be specified!"
O.noise opts "Started in verbose mode"
pure opts
extractAvailableDevices :: Options -> IO Options
extractAvailableDevices
= execStateT
$ St.gets O.noise
>>= \noise -> St.gets (view O.handleDevicePath')
>>= lift . filterM doesFileExist
>>= ( unnoticed $ length .> \availableDevicesCount ->
unless (availableDevicesCount > 0) $ lift $ dieWith
"All specified devices to get events from is unavailable!"
)
>>= ( unnoticed $ lift . noise
. ("Devices that will be handled:" <>) . foldMap ("\n " <>)
)
>>= unnoticed (St.modify . set O.availableDevices')
>>= ( apart $ lift
$ noise "Opening devices files descriptors for reading..."
)
>>= lift . mapM (`IOHandleFD.openFile` SysIO.ReadMode)
>>= St.modify . set O.handleDeviceFd'
parseOpts :: [String] -> IO Options
parseOpts = go where
go
= getOptsFromArgs
>=> extractAvailableDevices
>=> XInput.getAvailable
>=> unnoticed XInput.disable
>=> logDisabled
logDisabled :: Options -> IO Options
logDisabled opts
= O.availableXInputDevices opts
& ("XInput devices ids that was disabled: " <>) . show
& (\x -> opts <$ O.noise opts x)
handleTerminationTimeout :: IO ()
handleTerminationTimeout = void $ forkIO $ do
threadDelay $ terminationTimeout * 1000 * 1000
errPutStrLn [qms| Termination process timeout
after {terminationTimeout} seconds,
just exiting immidiately... |]
exitImmediately $ ExitFailure 1
and Xkb and checks if everything is okay
and returns Xlib Display pointer then .
xkbInit :: IO Display
xkbInit = do
(dpy :: Display) <- xkbGetDisplay >>= (`either` pure)
(\err -> dieWith [qm| Xkb open display error: {err} |])
xkbDescPtr <- xkbGetDescPtr dpy >>= (`either` pure)
(\err -> dieWith [qm| Xkb error: get keyboard data error: {err} |])
xkbFetchControls dpy xkbDescPtr
>>= (`unless` dieWith "Xkb error: fetch controls error")
(> 0) <$> xkbGetGroupsCount xkbDescPtr
>>= (`unless` dieWith "Xkb error: groups count is 0")
pure dpy
data MyThreadException = MortifyThreadException deriving (Show, Typeable)
instance Exception MyThreadException
In seconds
terminationTimeout :: Int
terminationTimeout = 5
|
b8c44b9290106da4230d66a64d092789c7787d0306dc1b7452bc8f261fbacafc | emaphis/HtDP2e-solutions | ex008.rkt | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-beginner-reader.ss" "lang")((modname ex008) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
(require 2htdp/image)
Ex . 8
;; Add the following line to the definitions area:
;; (define cat <image>)
;; Create a conditional expression that computes whether the image is tall or wide.
;; An image should be labeled "tall" if its height is larger than or equal to its width;
;; otherwise it is "wide".
;; Replace the cat with a rectangle of your choice to ensure that you know the expected answer.
;; Now try the following modification.
;; Create an expression that computes whether a picture is "tall", "wide", or "square"
(define cat (bitmap "images/cat.png"))
(if (> (image-height cat) (image-width cat))
"tall"
(if (= (image-height cat) (image-width cat))
"square"
"wide")) ;=> "tall"
(define image-1 (rectangle 60 40 "solid" "red"))
( rectangle 60 40 " solid " " red " )
(if (> (image-height image-1) (image-width image-1))
"tall"
(if (= (image-height image-1) (image-width image-1))
"square"
"wide")) ;=> "tall" | null | https://raw.githubusercontent.com/emaphis/HtDP2e-solutions/ecb60b9a7bbf9b8999c0122b6ea152a3301f0a68/1-Fixed-Size-Data/01-Arithmetic/ex008.rkt | racket | about the language level of this file in a form that our tools can easily process.
Add the following line to the definitions area:
(define cat <image>)
Create a conditional expression that computes whether the image is tall or wide.
An image should be labeled "tall" if its height is larger than or equal to its width;
otherwise it is "wide".
Replace the cat with a rectangle of your choice to ensure that you know the expected answer.
Now try the following modification.
Create an expression that computes whether a picture is "tall", "wide", or "square"
=> "tall"
=> "tall" | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-beginner-reader.ss" "lang")((modname ex008) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
(require 2htdp/image)
Ex . 8
(define cat (bitmap "images/cat.png"))
(if (> (image-height cat) (image-width cat))
"tall"
(if (= (image-height cat) (image-width cat))
"square"
(define image-1 (rectangle 60 40 "solid" "red"))
( rectangle 60 40 " solid " " red " )
(if (> (image-height image-1) (image-width image-1))
"tall"
(if (= (image-height image-1) (image-width image-1))
"square" |
413da96351ae1d7f9921ec7c39d0922ca4ebb787b9b62ba05da554e516f95ec1 | goodmind/Infornography | infornography-macos.rkt | #!/usr/bin/env racket
#lang racket/base
(require racket/port racket/system racket/string racket/list)
(define-syntax $
(syntax-rules ()
((_ v)
(getenv (symbol->string (quote v))))))
(define (-> cmd)
(port->string (car (process cmd))))
(define (hostname)
(string-trim (-> "hostname")))
(define (filename->string file)
(call-with-input-file file port->string))
(define (get-match pattern string)
(cadr (regexp-match pattern string)))
(define (cpu)
(string-trim (-> "sysctl -n machdep.cpu.brand_string")))
(define (memory:make-pattern name)
(pregexp (string-append name ":[[:space:]]+([[:digit:]]+)")))
(define (memory:information)
(let* ((mkpattern memory:make-pattern)
(meminfo (-> "vm_stat"))
(total-pages (/ (string->number (string-trim (-> "sysctl -n hw.memsize"))) 4096))
(total (number->string total-pages))
(free (get-match (mkpattern "Pages free") meminfo))
(speculative (get-match (mkpattern "Pages speculative") meminfo)))
(map (λ (num)
(round
(/ (/ (* (string->number num) 4096) 1024) 1024)))
(list total free speculative))))
(define (memory)
(let* ((total (first (memory:information)))
(free (second (memory:information)))
(speculative (third (memory:information)))
(used (- total (+ free speculative))))
(string-join (list (number->string used) "M/"
(number->string total) "M")
"")))
(define (kernel)
(string-trim (-> "uname -s")))
(define (os)
(let* ((os-name (-> "sw_vers -productName"))
(os-version (-> "sw_vers -productVersion")))
(string-join (map string-trim (list os-name os-version)))))
(define data (list "
.......
............... " ($ USER) "@" (hostname) "
.................... Shell: " ($ SHELL) "
......................... Memory: " (memory) "
........................... Kernel: " (kernel) "
............................. OS: " (os) "
............................... Terminal: " ($ TERM) "
..............x................ CPU: " (cpu) "
............xo@................
...........xoo@xxx.............
........o@oxxoo@@@@@@x..xx.....
@@@@@@x...o\\./.
....o@@@@@@@@@@@@@@@@@@@o.\\..
.....x@@@@@@@@@@@o@@@@@@x/.\\.
......@@@@@@@@@@o@@@@@x....
.......@@@@@@@@o@@@@o......
.x@@@@@@@@@@ox.. .....
.@@@@@@@ooooxxxo. ...
...x@@@@@@@@@ooooo@... ..
........@@@@@@@....xoo........
.............@@@....................
........................................
....................x..x................
\n"))
(for-each (λ (s)
(if (string? s)
(display s)
(display "Unknown."))) data)
| null | https://raw.githubusercontent.com/goodmind/Infornography/718c3510f93c9d6aae0a1097cf2823e0cad347ef/infornography-macos.rkt | racket | #!/usr/bin/env racket
#lang racket/base
(require racket/port racket/system racket/string racket/list)
(define-syntax $
(syntax-rules ()
((_ v)
(getenv (symbol->string (quote v))))))
(define (-> cmd)
(port->string (car (process cmd))))
(define (hostname)
(string-trim (-> "hostname")))
(define (filename->string file)
(call-with-input-file file port->string))
(define (get-match pattern string)
(cadr (regexp-match pattern string)))
(define (cpu)
(string-trim (-> "sysctl -n machdep.cpu.brand_string")))
(define (memory:make-pattern name)
(pregexp (string-append name ":[[:space:]]+([[:digit:]]+)")))
(define (memory:information)
(let* ((mkpattern memory:make-pattern)
(meminfo (-> "vm_stat"))
(total-pages (/ (string->number (string-trim (-> "sysctl -n hw.memsize"))) 4096))
(total (number->string total-pages))
(free (get-match (mkpattern "Pages free") meminfo))
(speculative (get-match (mkpattern "Pages speculative") meminfo)))
(map (λ (num)
(round
(/ (/ (* (string->number num) 4096) 1024) 1024)))
(list total free speculative))))
(define (memory)
(let* ((total (first (memory:information)))
(free (second (memory:information)))
(speculative (third (memory:information)))
(used (- total (+ free speculative))))
(string-join (list (number->string used) "M/"
(number->string total) "M")
"")))
(define (kernel)
(string-trim (-> "uname -s")))
(define (os)
(let* ((os-name (-> "sw_vers -productName"))
(os-version (-> "sw_vers -productVersion")))
(string-join (map string-trim (list os-name os-version)))))
(define data (list "
.......
............... " ($ USER) "@" (hostname) "
.................... Shell: " ($ SHELL) "
......................... Memory: " (memory) "
........................... Kernel: " (kernel) "
............................. OS: " (os) "
............................... Terminal: " ($ TERM) "
..............x................ CPU: " (cpu) "
............xo@................
...........xoo@xxx.............
........o@oxxoo@@@@@@x..xx.....
@@@@@@x...o\\./.
....o@@@@@@@@@@@@@@@@@@@o.\\..
.....x@@@@@@@@@@@o@@@@@@x/.\\.
......@@@@@@@@@@o@@@@@x....
.......@@@@@@@@o@@@@o......
.x@@@@@@@@@@ox.. .....
.@@@@@@@ooooxxxo. ...
...x@@@@@@@@@ooooo@... ..
........@@@@@@@....xoo........
.............@@@....................
........................................
....................x..x................
\n"))
(for-each (λ (s)
(if (string? s)
(display s)
(display "Unknown."))) data)
| |
73eb37bb9eeefbb164034aee5747e933dad88d5a5019e058b892a255d9471112 | Viasat/halite | jadeite.clj | Copyright ( c ) 2022 Viasat , Inc.
Licensed under the MIT license
(ns com.viasat.jadeite
(:require [clojure.core.match :as match :refer [match]]
[clojure.edn :as edn]
[clojure.java.io :as io]
[clojure.string :as string]
[com.viasat.halite.base :as base]
[com.viasat.halite.lib.fixed-decimal :as fixed-decimal]
[instaparse.core :as insta]))
(set! *warn-on-reflection* true)
(def global-fns
"Set of halite operator names that are written as function calls in jadeite,
otherwise method call syntax is used."
'#{abs error expt range str rescale})
;;;;
From to Halite
(defn- flatten-variadics [h]
(if-not (and (seq? h) (seq? (second h)))
h
(let [[op2 [op1 & args1] & args2] h]
(cond
(and (contains? '#{+ - * div or and =} op2)
(= op2 op1))
(concat [op2] args1 args2)
(and (= op2 'get) (= op1 'get))
(list 'get-in (first args1) [(second args1) (first args2)])
(and (= op2 'get) (= op1 'get-in))
(list 'get-in (first args1) (conj (second args1) (first args2)))
:else h))))
(defn- unwrap-symbol [s]
(if-let [[_ weird-s] (or (re-matches #"'([^\s']+)'" s)
(re-matches #"<(\S+)>" s))]
(symbol weird-s)
(symbol s)))
(defprotocol AddMetadata
(add-source-metadata-when-possible [obj source-tree]))
(extend-protocol AddMetadata
clojure.lang.IObj
(add-source-metadata-when-possible [obj source-tree]
(let [{:instaparse.gll/keys [start-line start-column end-line end-column]} (meta source-tree)]
(if start-line
(with-meta obj (merge (meta obj) {:row start-line
:col start-column
:end-row end-line
:end-col end-column}))
obj)))
Object
;; default implementation for clojure objects that do not support metadata
(add-source-metadata-when-possible [obj source-tree]
obj))
(defn- combine-ifs [h]
(if (and (seq? h)
(#{'if 'cond} (first h)))
(let [[_ pred then else] h]
(if (and (seq? else)
(#{'if 'cond} (first else)))
(let [[_ & more] (combine-ifs else)]
(apply list (into ['cond pred then] more)))
h))
h))
(defn toh
"Translate from tree of expression objects created by instaparse (hiccup) into halite"
[tree]
(-> (match [tree]
[[:conditional op a b c]] (combine-ifs (list (if (= "if" op) 'if 'if-value) (toh a) (toh b) (toh c)))
[[:if-value-let sym m t e]] (list 'if-value-let [(toh sym) (toh m)] (toh t) (toh e))
[[:when-value-let sym m t]] (list 'when-value-let [(toh sym) (toh m)] (toh t))
[[:when-value sym t]] (list 'when-value (toh sym) (toh t))
[[:optional pred body]] (list 'when (toh pred) (toh body))
[[:valid op body]] (list (symbol op) (toh body))
[[:implication a b]] (list '=> (toh a) (toh b))
[[:or a "||" b]] (list 'or (toh a) (toh b))
[[:and a "&&" b]] (list 'and (toh a) (toh b))
[[:equality a "==" b]] (list '= (toh a) (toh b))
[[:equality a "!=" b]] (list 'not= (toh a) (toh b))
[[:relational a op b]] (list (symbol op) (toh a) (toh b))
[[:add a op b]] (let [hb (toh b)]
(match [op hb]
["+" 1] (list 'inc (toh a))
["-" 1] (list 'dec (toh a))
:else (list (symbol op) (toh a) hb)))
[[:mult a "*" b]] (list '* (toh a) (toh b))
[[:mult a "/" b]] (list 'div (toh a) (toh b))
[[:mult a "%" b]] (list 'mod (toh a) (toh b))
[[:prefix "!" a]] (list 'not (toh a))
[[:get-field a [:symbol b]]] (list 'get (toh a) (keyword (unwrap-symbol b)))
[[:get-index a b]] (list 'get (toh a) (toh b))
[[:comprehend [:symbol "sortBy"] s bind pred]] (list 'sort-by [(toh s) (toh bind)] (toh pred))
[[:comprehend [:symbol op] s bind pred]] (list (symbol op) [(toh s) (toh bind)] (toh pred))
[[:reduce acc init elem coll body]] (list 'reduce [(toh acc) (toh init)]
[(toh elem) (toh coll)] (toh body))
[[:call-fn [:symbol "equalTo"] & args]] (list* '= (map toh args))
[[:call-fn [:symbol "notEqualTo"] & args]] (list* 'not= (map toh args))
[[:call-fn op & args]] (let [s (toh op)]
(if (global-fns s)
(list* s (map toh args))
(throw (ex-info (str "No such global function: " s)
{:op s :args args}))))
[[:call-method a op & args]] (let [s (toh op)]
(if (global-fns s)
(throw (ex-info (str "No such method: " s)
{:op s :args args}))
(list* s (toh a) (map toh args))))
[[:type-method a "refineTo" & args]] (list* 'refine-to (toh a) (map toh args))
[[:type-method a "refinesTo?" & args]] (list* 'refines-to? (toh a) (map toh args))
[[:map & args]] (into {} (map toh) args)
[[:map-entry "$type" v]] [:$type (toh v)]
[[:map-entry [_ k] v]] [(keyword (unwrap-symbol k)) (toh v)]
[[:set & args]] (set (map toh args))
[[:vec & args]] (vec (map toh args))
[[:let & args]] (if (next args)
(list 'let (mapv toh (drop-last args)) (toh (last args)))
(toh (last args)))
[[:int & strs]] (parse-long (apply str strs))
[[:decimal s]] (fixed-decimal/fixed-decimal-reader (edn/read-string (second s)))
[[:symbol "true"]] true
[[:symbol "false"]] false
[[:symbol s]] (unwrap-symbol s)
[[:typename [_ s]]] (keyword (unwrap-symbol s))
[[:typename s]] (keyword s)
[[:string s]] (edn/read-string s)
;; Default to descending through intermediate grammar nodes
[[(_ :guard keyword?) (kid :guard vector?)]] (toh kid)
:else (throw (ex-info (str "Unhandled parse tree:\n" (pr-str tree))
{:tree tree})))
flatten-variadics
(add-source-metadata-when-possible tree)))
(def whitespace-or-comments
(insta/parser
"ws-or-comments = #'\\s+' | comment+
comment = #'\\s*//.*(\\n\\s*|$)'"))
(def parse
(insta/parser (io/resource "com/viasat/jadeite.bnf")
:auto-whitespace whitespace-or-comments))
(defn to-halite [jadeite-string]
(let [tree (->> jadeite-string
parse
(insta/add-line-and-column-info-to-metadata jadeite-string))]
(when (insta/failure? tree)
(throw (ex-info (pr-str tree) {:parse-failure tree})))
(toh tree)))
;;;;
From Halite to
(declare toj)
(def ^:dynamic *pprint* false)
(defn infix
([args] (infix "(" ", " ")" args))
([op args] (infix "(" op ")" args))
([pre op post args & {:keys [sort?]}]
(let [parts (map toj args)
ordered-parts (if sort? (sort parts) parts)]
(if (and *pprint*
(or (some #(re-find #"\n" %) parts)
(< 70 (reduce + (map count parts)))))
(apply str (concat [pre "\n"]
(interpose (str op "\n")
(map #(string/replace % #"\n" "\n ")
ordered-parts))
[post]))
(apply str (concat [pre] (interpose op ordered-parts) [post]))))))
(defn typename [kw]
(let [without-colon (subs (str kw) 1)]
(if (and *pprint* (re-find #"[^a-zA-Z0-9./$]" without-colon))
(str "<" without-colon ">")
without-colon)))
(defn call-method [method-name [target & args]]
(let [args-str (infix args)]
(if (re-find #"\n" args-str)
(str (toj target) "\n." method-name (string/replace args-str #"\n" "\n "))
(str (toj target) "." method-name args-str))))
(defn call-fn-or-method [op args]
(if (global-fns op)
(str op (infix ", " args))
(call-method op args)))
(defn wrap-string [s]
(if (re-find #"[^a-zA-Z0-9]" s)
(str "'" s "'")
s))
(defn toj [x]
(cond
(string? x) (pr-str x)
(base/fixed-decimal? x) (str "#d" " \"" (fixed-decimal/string-representation x) "\"")
(keyword? x) (typename x)
(symbol? x) (wrap-string (str x))
(set? x) (infix "#{" ", " "}" x :sort? true)
(map? x) (infix "{" ", " "}" x :sort? true)
(map-entry? x) (let [[k v] x]
(str (if (= :$type k)
(name k)
(wrap-string (name k)))
": "
(if (= :$type k)
(typename v)
(toj v))))
(vector? x) (infix "[" ", " "]" x)
(seq? x) (let [[op & [a0 a1 a2 :as args]] x]
(case op
(< <= > >= + - * =>) (infix (str " " op " ") args)
= (if (> (count args) 2)
(str "equalTo" (infix ", " args))
(infix " == " args))
(every? any? map filter) (str "(" op (infix " in " a0) (toj a1) ")")
sort-by (str "sortBy" (infix " in " a0) (toj a1))
reduce (let [[[acc init] [elem coll] body] args]
(str "(reduce( " (toj acc) " = " (toj init) "; " (toj elem) " in " (toj coll)
" ) { " (toj body) " })"))
and (infix " && " args)
dec (str "(" (toj a0) " - 1)")
div (infix " / " args)
get (if (keyword? a1)
(str (toj a0) '. (wrap-string (name a1)))
(str (toj a0) "[" (toj a1) "]"))
get-in (reduce (fn [target index]
(if (keyword? index)
(str target '. (wrap-string (name index)))
(str target "[" (toj index) "]")))
(toj a0)
a1)
if (str "(if(" (toj a0)
") {" (toj a1)
"} else {" (toj a2)
"})")
cond (str "(if(" (toj a0)
") {" (toj a1)
"} else {" (if (> (count args) 3)
(toj (apply list (into ['cond] (drop 2 args))))
(toj a2))
"})")
WAT
valid? (str "(valid? " (toj a0) ")")
valid (str "(valid " (toj a0) ")")
(if-value if-value-) (str "(ifValue(" (toj a0)
") {" (toj a1)
"} else {" (toj a2) "})")
when-value (str "(whenValue(" (toj a0) ") {" (toj a1) "})")
if-value-let (apply format "(ifValueLet ( %s = %s ) {%s} else {%s})"
(map toj [(first a0) (second a0) a1 a2]))
when-value-let (apply format "(whenValueLet ( %s = %s ) {%s})"
(map toj [(first a0) (second a0) a1]))
inc (str "(" (toj a0) " + 1)")
let (let [[bindings expr] args]
(str "({ "
(->> bindings
(partition 2)
(mapcat (fn [[k v]]
[(toj k) " = " (toj v) "; "]))
(apply str))
(toj expr)
" })"))
mod (infix " % " args)
not (str "!" (toj a0))
not= (if (> (count args) 2)
(str "notEqualTo" (infix ", " args))
(infix " != " args))
or (infix " || " args)
refine-to (str (toj a0) ".refineTo( " (typename a1) " )")
refines-to? (str (toj a0) ".refinesTo?( " (typename a1) " )")
select (call-method "select" (reverse args))
;; default:
(call-fn-or-method op args)))
:else (str x)))
(def to-jadeite
"Translate halite form into jadeite string"
toj)
| null | https://raw.githubusercontent.com/Viasat/halite/1145fdf49b5148acb389dd5100059b0d2ef959e1/src/com/viasat/jadeite.clj | clojure |
default implementation for clojure objects that do not support metadata
Default to descending through intermediate grammar nodes
default: | Copyright ( c ) 2022 Viasat , Inc.
Licensed under the MIT license
(ns com.viasat.jadeite
(:require [clojure.core.match :as match :refer [match]]
[clojure.edn :as edn]
[clojure.java.io :as io]
[clojure.string :as string]
[com.viasat.halite.base :as base]
[com.viasat.halite.lib.fixed-decimal :as fixed-decimal]
[instaparse.core :as insta]))
(set! *warn-on-reflection* true)
(def global-fns
"Set of halite operator names that are written as function calls in jadeite,
otherwise method call syntax is used."
'#{abs error expt range str rescale})
From to Halite
(defn- flatten-variadics [h]
(if-not (and (seq? h) (seq? (second h)))
h
(let [[op2 [op1 & args1] & args2] h]
(cond
(and (contains? '#{+ - * div or and =} op2)
(= op2 op1))
(concat [op2] args1 args2)
(and (= op2 'get) (= op1 'get))
(list 'get-in (first args1) [(second args1) (first args2)])
(and (= op2 'get) (= op1 'get-in))
(list 'get-in (first args1) (conj (second args1) (first args2)))
:else h))))
(defn- unwrap-symbol [s]
(if-let [[_ weird-s] (or (re-matches #"'([^\s']+)'" s)
(re-matches #"<(\S+)>" s))]
(symbol weird-s)
(symbol s)))
(defprotocol AddMetadata
(add-source-metadata-when-possible [obj source-tree]))
(extend-protocol AddMetadata
clojure.lang.IObj
(add-source-metadata-when-possible [obj source-tree]
(let [{:instaparse.gll/keys [start-line start-column end-line end-column]} (meta source-tree)]
(if start-line
(with-meta obj (merge (meta obj) {:row start-line
:col start-column
:end-row end-line
:end-col end-column}))
obj)))
Object
(add-source-metadata-when-possible [obj source-tree]
obj))
(defn- combine-ifs [h]
(if (and (seq? h)
(#{'if 'cond} (first h)))
(let [[_ pred then else] h]
(if (and (seq? else)
(#{'if 'cond} (first else)))
(let [[_ & more] (combine-ifs else)]
(apply list (into ['cond pred then] more)))
h))
h))
(defn toh
"Translate from tree of expression objects created by instaparse (hiccup) into halite"
[tree]
(-> (match [tree]
[[:conditional op a b c]] (combine-ifs (list (if (= "if" op) 'if 'if-value) (toh a) (toh b) (toh c)))
[[:if-value-let sym m t e]] (list 'if-value-let [(toh sym) (toh m)] (toh t) (toh e))
[[:when-value-let sym m t]] (list 'when-value-let [(toh sym) (toh m)] (toh t))
[[:when-value sym t]] (list 'when-value (toh sym) (toh t))
[[:optional pred body]] (list 'when (toh pred) (toh body))
[[:valid op body]] (list (symbol op) (toh body))
[[:implication a b]] (list '=> (toh a) (toh b))
[[:or a "||" b]] (list 'or (toh a) (toh b))
[[:and a "&&" b]] (list 'and (toh a) (toh b))
[[:equality a "==" b]] (list '= (toh a) (toh b))
[[:equality a "!=" b]] (list 'not= (toh a) (toh b))
[[:relational a op b]] (list (symbol op) (toh a) (toh b))
[[:add a op b]] (let [hb (toh b)]
(match [op hb]
["+" 1] (list 'inc (toh a))
["-" 1] (list 'dec (toh a))
:else (list (symbol op) (toh a) hb)))
[[:mult a "*" b]] (list '* (toh a) (toh b))
[[:mult a "/" b]] (list 'div (toh a) (toh b))
[[:mult a "%" b]] (list 'mod (toh a) (toh b))
[[:prefix "!" a]] (list 'not (toh a))
[[:get-field a [:symbol b]]] (list 'get (toh a) (keyword (unwrap-symbol b)))
[[:get-index a b]] (list 'get (toh a) (toh b))
[[:comprehend [:symbol "sortBy"] s bind pred]] (list 'sort-by [(toh s) (toh bind)] (toh pred))
[[:comprehend [:symbol op] s bind pred]] (list (symbol op) [(toh s) (toh bind)] (toh pred))
[[:reduce acc init elem coll body]] (list 'reduce [(toh acc) (toh init)]
[(toh elem) (toh coll)] (toh body))
[[:call-fn [:symbol "equalTo"] & args]] (list* '= (map toh args))
[[:call-fn [:symbol "notEqualTo"] & args]] (list* 'not= (map toh args))
[[:call-fn op & args]] (let [s (toh op)]
(if (global-fns s)
(list* s (map toh args))
(throw (ex-info (str "No such global function: " s)
{:op s :args args}))))
[[:call-method a op & args]] (let [s (toh op)]
(if (global-fns s)
(throw (ex-info (str "No such method: " s)
{:op s :args args}))
(list* s (toh a) (map toh args))))
[[:type-method a "refineTo" & args]] (list* 'refine-to (toh a) (map toh args))
[[:type-method a "refinesTo?" & args]] (list* 'refines-to? (toh a) (map toh args))
[[:map & args]] (into {} (map toh) args)
[[:map-entry "$type" v]] [:$type (toh v)]
[[:map-entry [_ k] v]] [(keyword (unwrap-symbol k)) (toh v)]
[[:set & args]] (set (map toh args))
[[:vec & args]] (vec (map toh args))
[[:let & args]] (if (next args)
(list 'let (mapv toh (drop-last args)) (toh (last args)))
(toh (last args)))
[[:int & strs]] (parse-long (apply str strs))
[[:decimal s]] (fixed-decimal/fixed-decimal-reader (edn/read-string (second s)))
[[:symbol "true"]] true
[[:symbol "false"]] false
[[:symbol s]] (unwrap-symbol s)
[[:typename [_ s]]] (keyword (unwrap-symbol s))
[[:typename s]] (keyword s)
[[:string s]] (edn/read-string s)
[[(_ :guard keyword?) (kid :guard vector?)]] (toh kid)
:else (throw (ex-info (str "Unhandled parse tree:\n" (pr-str tree))
{:tree tree})))
flatten-variadics
(add-source-metadata-when-possible tree)))
(def whitespace-or-comments
(insta/parser
"ws-or-comments = #'\\s+' | comment+
comment = #'\\s*//.*(\\n\\s*|$)'"))
(def parse
(insta/parser (io/resource "com/viasat/jadeite.bnf")
:auto-whitespace whitespace-or-comments))
(defn to-halite [jadeite-string]
(let [tree (->> jadeite-string
parse
(insta/add-line-and-column-info-to-metadata jadeite-string))]
(when (insta/failure? tree)
(throw (ex-info (pr-str tree) {:parse-failure tree})))
(toh tree)))
From Halite to
(declare toj)
(def ^:dynamic *pprint* false)
(defn infix
([args] (infix "(" ", " ")" args))
([op args] (infix "(" op ")" args))
([pre op post args & {:keys [sort?]}]
(let [parts (map toj args)
ordered-parts (if sort? (sort parts) parts)]
(if (and *pprint*
(or (some #(re-find #"\n" %) parts)
(< 70 (reduce + (map count parts)))))
(apply str (concat [pre "\n"]
(interpose (str op "\n")
(map #(string/replace % #"\n" "\n ")
ordered-parts))
[post]))
(apply str (concat [pre] (interpose op ordered-parts) [post]))))))
(defn typename [kw]
(let [without-colon (subs (str kw) 1)]
(if (and *pprint* (re-find #"[^a-zA-Z0-9./$]" without-colon))
(str "<" without-colon ">")
without-colon)))
(defn call-method [method-name [target & args]]
(let [args-str (infix args)]
(if (re-find #"\n" args-str)
(str (toj target) "\n." method-name (string/replace args-str #"\n" "\n "))
(str (toj target) "." method-name args-str))))
(defn call-fn-or-method [op args]
(if (global-fns op)
(str op (infix ", " args))
(call-method op args)))
(defn wrap-string [s]
(if (re-find #"[^a-zA-Z0-9]" s)
(str "'" s "'")
s))
(defn toj [x]
(cond
(string? x) (pr-str x)
(base/fixed-decimal? x) (str "#d" " \"" (fixed-decimal/string-representation x) "\"")
(keyword? x) (typename x)
(symbol? x) (wrap-string (str x))
(set? x) (infix "#{" ", " "}" x :sort? true)
(map? x) (infix "{" ", " "}" x :sort? true)
(map-entry? x) (let [[k v] x]
(str (if (= :$type k)
(name k)
(wrap-string (name k)))
": "
(if (= :$type k)
(typename v)
(toj v))))
(vector? x) (infix "[" ", " "]" x)
(seq? x) (let [[op & [a0 a1 a2 :as args]] x]
(case op
(< <= > >= + - * =>) (infix (str " " op " ") args)
= (if (> (count args) 2)
(str "equalTo" (infix ", " args))
(infix " == " args))
(every? any? map filter) (str "(" op (infix " in " a0) (toj a1) ")")
sort-by (str "sortBy" (infix " in " a0) (toj a1))
reduce (let [[[acc init] [elem coll] body] args]
(str "(reduce( " (toj acc) " = " (toj init) "; " (toj elem) " in " (toj coll)
" ) { " (toj body) " })"))
and (infix " && " args)
dec (str "(" (toj a0) " - 1)")
div (infix " / " args)
get (if (keyword? a1)
(str (toj a0) '. (wrap-string (name a1)))
(str (toj a0) "[" (toj a1) "]"))
get-in (reduce (fn [target index]
(if (keyword? index)
(str target '. (wrap-string (name index)))
(str target "[" (toj index) "]")))
(toj a0)
a1)
if (str "(if(" (toj a0)
") {" (toj a1)
"} else {" (toj a2)
"})")
cond (str "(if(" (toj a0)
") {" (toj a1)
"} else {" (if (> (count args) 3)
(toj (apply list (into ['cond] (drop 2 args))))
(toj a2))
"})")
WAT
valid? (str "(valid? " (toj a0) ")")
valid (str "(valid " (toj a0) ")")
(if-value if-value-) (str "(ifValue(" (toj a0)
") {" (toj a1)
"} else {" (toj a2) "})")
when-value (str "(whenValue(" (toj a0) ") {" (toj a1) "})")
if-value-let (apply format "(ifValueLet ( %s = %s ) {%s} else {%s})"
(map toj [(first a0) (second a0) a1 a2]))
when-value-let (apply format "(whenValueLet ( %s = %s ) {%s})"
(map toj [(first a0) (second a0) a1]))
inc (str "(" (toj a0) " + 1)")
let (let [[bindings expr] args]
(str "({ "
(->> bindings
(partition 2)
(mapcat (fn [[k v]]
[(toj k) " = " (toj v) "; "]))
(apply str))
(toj expr)
" })"))
mod (infix " % " args)
not (str "!" (toj a0))
not= (if (> (count args) 2)
(str "notEqualTo" (infix ", " args))
(infix " != " args))
or (infix " || " args)
refine-to (str (toj a0) ".refineTo( " (typename a1) " )")
refines-to? (str (toj a0) ".refinesTo?( " (typename a1) " )")
select (call-method "select" (reverse args))
(call-fn-or-method op args)))
:else (str x)))
(def to-jadeite
"Translate halite form into jadeite string"
toj)
|
22b6ba1fa30c368defa6dec6a65d6822d5b8d2bc77890642be7f7725e7584752 | zwizwa/staapl | info.rkt | #lang setup/infotab
* * * generated from / release * * *
(define name "Staapl")
(define blurb
'("A collection of abstractions for metaprogramming microcontrollers."))
(define repositories '("4.x"))
(define primary-file '("pic18.rkt" "staaplc.rkt" "live.rkt"))
(define homepage "")
(define categories '(devtools metaprogramming))
(define scribblings '(("scribblings/staapl.scrbl" ())))
(define release-notes
'(div
()
"See the "
(a ((href "-blog")) "Staapl blog")
" for release notes."))
(define version "0.5.12")
| null | https://raw.githubusercontent.com/zwizwa/staapl/e30e6ae6ac45de7141b97ad3cebf9b5a51bcda52/info.rkt | racket | #lang setup/infotab
* * * generated from / release * * *
(define name "Staapl")
(define blurb
'("A collection of abstractions for metaprogramming microcontrollers."))
(define repositories '("4.x"))
(define primary-file '("pic18.rkt" "staaplc.rkt" "live.rkt"))
(define homepage "")
(define categories '(devtools metaprogramming))
(define scribblings '(("scribblings/staapl.scrbl" ())))
(define release-notes
'(div
()
"See the "
(a ((href "-blog")) "Staapl blog")
" for release notes."))
(define version "0.5.12")
| |
8f514a7ca8de3b662ccb485d507bca4900a4966258f4b8f53c002dda347250d1 | janestreet/bonsai | tailwind_colors.mli | * The color palettes included in the Tailwind CSS library , taken from
[ -colors ] on 2022 - 11 - 21 . The larger
the number on a color , the darker it is .
This library takes the approach of * not * ascribing semantic value to
certain colors ; instead , it selects several " palettes " of colors which work
well together , and offloads the semantics of each color to the library or
application that depends on this one . Thus , this library does not aim to
provide any consistent design pattern or color conventions . However , a set
of conventions could easily be created using this set of colors .
[-colors] on 2022-11-21. The larger
the number on a color, the darker it is.
This library takes the approach of *not* ascribing semantic value to
certain colors; instead, it selects several "palettes" of colors which work
well together, and offloads the semantics of each color to the library or
application that depends on this one. Thus, this library does not aim to
provide any consistent design pattern or color conventions. However, a set
of conventions could easily be created using this set of colors. *)
type t := [ `Hex of string ]
module Hue : sig
type t =
[ `slate
| `gray
| `zinc
| `neutral
| `stone
| `red
| `orange
| `amber
| `yellow
| `lime
| `green
| `emerald
| `teal
| `cyan
| `sky
| `blue
| `indigo
| `violet
| `purple
| `fuchsia
| `pink
| `rose
]
[@@deriving enumerate]
val to_string : t -> string
end
module Brightness : sig
type t =
[ `_50
| `_100
| `_200
| `_300
| `_400
| `_500
| `_600
| `_700
| `_800
| `_900
]
[@@deriving enumerate]
end
val create : Hue.t -> Brightness.t -> t
(** The slate palette *)
val slate50 : t
val slate100 : t
val slate200 : t
val slate300 : t
val slate400 : t
val slate500 : t
val slate600 : t
val slate700 : t
val slate800 : t
val slate900 : t
(** The gray palette *)
val gray50 : t
val gray100 : t
val gray200 : t
val gray300 : t
val gray400 : t
val gray500 : t
val gray600 : t
val gray700 : t
val gray800 : t
val gray900 : t
(** The zinc palette *)
val zinc50 : t
val zinc100 : t
val zinc200 : t
val zinc300 : t
val zinc400 : t
val zinc500 : t
val zinc600 : t
val zinc700 : t
val zinc800 : t
val zinc900 : t
(** The neutral palette *)
val neutral50 : t
val neutral100 : t
val neutral200 : t
val neutral300 : t
val neutral400 : t
val neutral500 : t
val neutral600 : t
val neutral700 : t
val neutral800 : t
val neutral900 : t
(** The stone palette *)
val stone50 : t
val stone100 : t
val stone200 : t
val stone300 : t
val stone400 : t
val stone500 : t
val stone600 : t
val stone700 : t
val stone800 : t
val stone900 : t
(** The red palette *)
val red50 : t
val red100 : t
val red200 : t
val red300 : t
val red400 : t
val red500 : t
val red600 : t
val red700 : t
val red800 : t
val red900 : t
(** The orange palette *)
val orange50 : t
val orange100 : t
val orange200 : t
val orange300 : t
val orange400 : t
val orange500 : t
val orange600 : t
val orange700 : t
val orange800 : t
val orange900 : t
(** The amber palette *)
val amber50 : t
val amber100 : t
val amber200 : t
val amber300 : t
val amber400 : t
val amber500 : t
val amber600 : t
val amber700 : t
val amber800 : t
val amber900 : t
(** The yellow palette *)
val yellow50 : t
val yellow100 : t
val yellow200 : t
val yellow300 : t
val yellow400 : t
val yellow500 : t
val yellow600 : t
val yellow700 : t
val yellow800 : t
val yellow900 : t
(** The lime palette *)
val lime50 : t
val lime100 : t
val lime200 : t
val lime300 : t
val lime400 : t
val lime500 : t
val lime600 : t
val lime700 : t
val lime800 : t
val lime900 : t
(** The green palette *)
val green50 : t
val green100 : t
val green200 : t
val green300 : t
val green400 : t
val green500 : t
val green600 : t
val green700 : t
val green800 : t
val green900 : t
(** The emerald palette *)
val emerald50 : t
val emerald100 : t
val emerald200 : t
val emerald300 : t
val emerald400 : t
val emerald500 : t
val emerald600 : t
val emerald700 : t
val emerald800 : t
val emerald900 : t
(** The teal palette *)
val teal50 : t
val teal100 : t
val teal200 : t
val teal300 : t
val teal400 : t
val teal500 : t
val teal600 : t
val teal700 : t
val teal800 : t
val teal900 : t
(** The cyan palette *)
val cyan50 : t
val cyan100 : t
val cyan200 : t
val cyan300 : t
val cyan400 : t
val cyan500 : t
val cyan600 : t
val cyan700 : t
val cyan800 : t
val cyan900 : t
(** The sky palette *)
val sky50 : t
val sky100 : t
val sky200 : t
val sky300 : t
val sky400 : t
val sky500 : t
val sky600 : t
val sky700 : t
val sky800 : t
val sky900 : t
(** The blue palette *)
val blue50 : t
val blue100 : t
val blue200 : t
val blue300 : t
val blue400 : t
val blue500 : t
val blue600 : t
val blue700 : t
val blue800 : t
val blue900 : t
(** The indigo palette *)
val indigo50 : t
val indigo100 : t
val indigo200 : t
val indigo300 : t
val indigo400 : t
val indigo500 : t
val indigo600 : t
val indigo700 : t
val indigo800 : t
val indigo900 : t
(** The violet palette *)
val violet50 : t
val violet100 : t
val violet200 : t
val violet300 : t
val violet400 : t
val violet500 : t
val violet600 : t
val violet700 : t
val violet800 : t
val violet900 : t
(** The purple palette *)
val purple50 : t
val purple100 : t
val purple200 : t
val purple300 : t
val purple400 : t
val purple500 : t
val purple600 : t
val purple700 : t
val purple800 : t
val purple900 : t
(** The fuchsia palette *)
val fuchsia50 : t
val fuchsia100 : t
val fuchsia200 : t
val fuchsia300 : t
val fuchsia400 : t
val fuchsia500 : t
val fuchsia600 : t
val fuchsia700 : t
val fuchsia800 : t
val fuchsia900 : t
(** The pink palette *)
val pink50 : t
val pink100 : t
val pink200 : t
val pink300 : t
val pink400 : t
val pink500 : t
val pink600 : t
val pink700 : t
val pink800 : t
val pink900 : t
(** The rose palette *)
val rose50 : t
val rose100 : t
val rose200 : t
val rose300 : t
val rose400 : t
val rose500 : t
val rose600 : t
val rose700 : t
val rose800 : t
val rose900 : t
module Stable : sig
module Hue : sig
module V1 : sig
type t = Hue.t [@@deriving bin_io, compare, enumerate, equal, sexp, sexp_grammar]
end
end
end
| null | https://raw.githubusercontent.com/janestreet/bonsai/782fecd000a1f97b143a3f24b76efec96e36a398/web_ui/tailwind_colors/tailwind_colors.mli | ocaml | * The slate palette
* The gray palette
* The zinc palette
* The neutral palette
* The stone palette
* The red palette
* The orange palette
* The amber palette
* The yellow palette
* The lime palette
* The green palette
* The emerald palette
* The teal palette
* The cyan palette
* The sky palette
* The blue palette
* The indigo palette
* The violet palette
* The purple palette
* The fuchsia palette
* The pink palette
* The rose palette | * The color palettes included in the Tailwind CSS library , taken from
[ -colors ] on 2022 - 11 - 21 . The larger
the number on a color , the darker it is .
This library takes the approach of * not * ascribing semantic value to
certain colors ; instead , it selects several " palettes " of colors which work
well together , and offloads the semantics of each color to the library or
application that depends on this one . Thus , this library does not aim to
provide any consistent design pattern or color conventions . However , a set
of conventions could easily be created using this set of colors .
[-colors] on 2022-11-21. The larger
the number on a color, the darker it is.
This library takes the approach of *not* ascribing semantic value to
certain colors; instead, it selects several "palettes" of colors which work
well together, and offloads the semantics of each color to the library or
application that depends on this one. Thus, this library does not aim to
provide any consistent design pattern or color conventions. However, a set
of conventions could easily be created using this set of colors. *)
type t := [ `Hex of string ]
module Hue : sig
type t =
[ `slate
| `gray
| `zinc
| `neutral
| `stone
| `red
| `orange
| `amber
| `yellow
| `lime
| `green
| `emerald
| `teal
| `cyan
| `sky
| `blue
| `indigo
| `violet
| `purple
| `fuchsia
| `pink
| `rose
]
[@@deriving enumerate]
val to_string : t -> string
end
module Brightness : sig
type t =
[ `_50
| `_100
| `_200
| `_300
| `_400
| `_500
| `_600
| `_700
| `_800
| `_900
]
[@@deriving enumerate]
end
val create : Hue.t -> Brightness.t -> t
val slate50 : t
val slate100 : t
val slate200 : t
val slate300 : t
val slate400 : t
val slate500 : t
val slate600 : t
val slate700 : t
val slate800 : t
val slate900 : t
val gray50 : t
val gray100 : t
val gray200 : t
val gray300 : t
val gray400 : t
val gray500 : t
val gray600 : t
val gray700 : t
val gray800 : t
val gray900 : t
val zinc50 : t
val zinc100 : t
val zinc200 : t
val zinc300 : t
val zinc400 : t
val zinc500 : t
val zinc600 : t
val zinc700 : t
val zinc800 : t
val zinc900 : t
val neutral50 : t
val neutral100 : t
val neutral200 : t
val neutral300 : t
val neutral400 : t
val neutral500 : t
val neutral600 : t
val neutral700 : t
val neutral800 : t
val neutral900 : t
val stone50 : t
val stone100 : t
val stone200 : t
val stone300 : t
val stone400 : t
val stone500 : t
val stone600 : t
val stone700 : t
val stone800 : t
val stone900 : t
val red50 : t
val red100 : t
val red200 : t
val red300 : t
val red400 : t
val red500 : t
val red600 : t
val red700 : t
val red800 : t
val red900 : t
val orange50 : t
val orange100 : t
val orange200 : t
val orange300 : t
val orange400 : t
val orange500 : t
val orange600 : t
val orange700 : t
val orange800 : t
val orange900 : t
val amber50 : t
val amber100 : t
val amber200 : t
val amber300 : t
val amber400 : t
val amber500 : t
val amber600 : t
val amber700 : t
val amber800 : t
val amber900 : t
val yellow50 : t
val yellow100 : t
val yellow200 : t
val yellow300 : t
val yellow400 : t
val yellow500 : t
val yellow600 : t
val yellow700 : t
val yellow800 : t
val yellow900 : t
val lime50 : t
val lime100 : t
val lime200 : t
val lime300 : t
val lime400 : t
val lime500 : t
val lime600 : t
val lime700 : t
val lime800 : t
val lime900 : t
val green50 : t
val green100 : t
val green200 : t
val green300 : t
val green400 : t
val green500 : t
val green600 : t
val green700 : t
val green800 : t
val green900 : t
val emerald50 : t
val emerald100 : t
val emerald200 : t
val emerald300 : t
val emerald400 : t
val emerald500 : t
val emerald600 : t
val emerald700 : t
val emerald800 : t
val emerald900 : t
val teal50 : t
val teal100 : t
val teal200 : t
val teal300 : t
val teal400 : t
val teal500 : t
val teal600 : t
val teal700 : t
val teal800 : t
val teal900 : t
val cyan50 : t
val cyan100 : t
val cyan200 : t
val cyan300 : t
val cyan400 : t
val cyan500 : t
val cyan600 : t
val cyan700 : t
val cyan800 : t
val cyan900 : t
val sky50 : t
val sky100 : t
val sky200 : t
val sky300 : t
val sky400 : t
val sky500 : t
val sky600 : t
val sky700 : t
val sky800 : t
val sky900 : t
val blue50 : t
val blue100 : t
val blue200 : t
val blue300 : t
val blue400 : t
val blue500 : t
val blue600 : t
val blue700 : t
val blue800 : t
val blue900 : t
val indigo50 : t
val indigo100 : t
val indigo200 : t
val indigo300 : t
val indigo400 : t
val indigo500 : t
val indigo600 : t
val indigo700 : t
val indigo800 : t
val indigo900 : t
val violet50 : t
val violet100 : t
val violet200 : t
val violet300 : t
val violet400 : t
val violet500 : t
val violet600 : t
val violet700 : t
val violet800 : t
val violet900 : t
val purple50 : t
val purple100 : t
val purple200 : t
val purple300 : t
val purple400 : t
val purple500 : t
val purple600 : t
val purple700 : t
val purple800 : t
val purple900 : t
val fuchsia50 : t
val fuchsia100 : t
val fuchsia200 : t
val fuchsia300 : t
val fuchsia400 : t
val fuchsia500 : t
val fuchsia600 : t
val fuchsia700 : t
val fuchsia800 : t
val fuchsia900 : t
val pink50 : t
val pink100 : t
val pink200 : t
val pink300 : t
val pink400 : t
val pink500 : t
val pink600 : t
val pink700 : t
val pink800 : t
val pink900 : t
val rose50 : t
val rose100 : t
val rose200 : t
val rose300 : t
val rose400 : t
val rose500 : t
val rose600 : t
val rose700 : t
val rose800 : t
val rose900 : t
module Stable : sig
module Hue : sig
module V1 : sig
type t = Hue.t [@@deriving bin_io, compare, enumerate, equal, sexp, sexp_grammar]
end
end
end
|
bf62393b116c3c262b025e666be0b83fa72b02364768b463f0ea3c8c1018267b | footprintanalytics/footprint-web | exceptions.clj | (ns metabase.server.middleware.exceptions
"Ring middleware for handling Exceptions thrown in API request handler functions."
(:require [clojure.java.jdbc :as jdbc]
[clojure.string :as str]
[clojure.tools.logging :as log]
[metabase.server.middleware.security :as mw.security]
[metabase.util.i18n :refer [trs]])
(:import java.sql.SQLException
org.eclipse.jetty.io.EofException))
(defn genericize-exceptions
"Catch any exceptions thrown in the request handler body and rethrow a generic 400 exception instead. This minimizes
information available to bad actors when exceptions occur on public endpoints."
[handler]
(fn [request respond _]
(let [raise (fn [e]
(log/warn e (trs "Exception in API call"))
(respond {:status 400, :body "An error occurred."}))]
(try
(handler request respond raise)
(catch Throwable e
(raise e))))))
(defn message-only-exceptions
"Catch any exceptions thrown in the request handler body and rethrow a 400 exception that only has the message from
the original instead (i.e., don't rethrow the original stacktrace). This reduces the information available to bad
actors but still provides some information that will prove useful in debugging errors."
[handler]
(fn [request respond _]
(let [raise (fn [^Throwable e]
(respond {:status 400, :body (.getMessage e)}))]
(try
(handler request respond raise)
(catch Throwable e
(raise e))))))
(defmulti api-exception-response
"Convert an uncaught exception from an API endpoint into an appropriate format to be returned by the REST API (e.g. a
map, which eventually gets serialized to JSON, or a plain string message)."
{:arglists '([e])}
class)
(defmethod api-exception-response Throwable
[^Throwable e]
(let [{:keys [status-code], :as info} (ex-data e)
other-info (dissoc info :status-code :schema :type)
body (cond
(and status-code (empty? other-info))
;; If status code was specified but other data wasn't, it's something like a
404 . Return message as the ( plain - text ) body .
(.getMessage e)
;; if the response includes `:errors`, (e.g., it's something like a generic
;; parameter validation exception), just return the `other-info` from the
;; ex-data.
(and status-code (:errors other-info))
other-info
Otherwise return the full ` Throwable->map ` representation with Stacktrace
;; and ex-data
:else
(merge
(Throwable->map e)
{:message (.getMessage e)}
other-info))]
{:status (or status-code 500)
:headers (mw.security/security-headers)
:body body}))
(defmethod api-exception-response SQLException
[e]
(-> ((get-method api-exception-response (.getSuperclass SQLException)) e)
(assoc-in [:body :sql-exception-chain] (str/split (with-out-str (jdbc/print-sql-exception-chain e))
#"\s*\n\s*"))))
(defmethod api-exception-response EofException
[_e]
(log/info (trs "Request canceled before finishing."))
{:status-code 204, :body nil, :headers (mw.security/security-headers)})
(defn catch-api-exceptions
"Middleware that catches API Exceptions and returns them in our normal-style format rather than the Jetty 500
Stacktrace page, which is not so useful for our frontend."
[handler]
(fn [request respond _raise]
(handler
request
respond
(comp respond api-exception-response))))
(defn catch-uncaught-exceptions
"Middleware that catches any unexpected Exceptions that reroutes them thru `raise` where they can be handled
appropriately."
[handler]
(fn [request respond raise]
(try
(handler
request
for people that accidentally pass along an Exception , e.g. from qp.async , do the nice thing and route it to
;; the write place for them
(fn [response]
((if (instance? Throwable response)
raise
respond) response))
raise)
(catch Throwable e
(raise e)))))
| null | https://raw.githubusercontent.com/footprintanalytics/footprint-web/d3090d943dd9fcea493c236f79e7ef8a36ae17fc/src/metabase/server/middleware/exceptions.clj | clojure | If status code was specified but other data wasn't, it's something like a
if the response includes `:errors`, (e.g., it's something like a generic
parameter validation exception), just return the `other-info` from the
ex-data.
and ex-data
the write place for them | (ns metabase.server.middleware.exceptions
"Ring middleware for handling Exceptions thrown in API request handler functions."
(:require [clojure.java.jdbc :as jdbc]
[clojure.string :as str]
[clojure.tools.logging :as log]
[metabase.server.middleware.security :as mw.security]
[metabase.util.i18n :refer [trs]])
(:import java.sql.SQLException
org.eclipse.jetty.io.EofException))
(defn genericize-exceptions
"Catch any exceptions thrown in the request handler body and rethrow a generic 400 exception instead. This minimizes
information available to bad actors when exceptions occur on public endpoints."
[handler]
(fn [request respond _]
(let [raise (fn [e]
(log/warn e (trs "Exception in API call"))
(respond {:status 400, :body "An error occurred."}))]
(try
(handler request respond raise)
(catch Throwable e
(raise e))))))
(defn message-only-exceptions
"Catch any exceptions thrown in the request handler body and rethrow a 400 exception that only has the message from
the original instead (i.e., don't rethrow the original stacktrace). This reduces the information available to bad
actors but still provides some information that will prove useful in debugging errors."
[handler]
(fn [request respond _]
(let [raise (fn [^Throwable e]
(respond {:status 400, :body (.getMessage e)}))]
(try
(handler request respond raise)
(catch Throwable e
(raise e))))))
(defmulti api-exception-response
"Convert an uncaught exception from an API endpoint into an appropriate format to be returned by the REST API (e.g. a
map, which eventually gets serialized to JSON, or a plain string message)."
{:arglists '([e])}
class)
(defmethod api-exception-response Throwable
[^Throwable e]
(let [{:keys [status-code], :as info} (ex-data e)
other-info (dissoc info :status-code :schema :type)
body (cond
(and status-code (empty? other-info))
404 . Return message as the ( plain - text ) body .
(.getMessage e)
(and status-code (:errors other-info))
other-info
Otherwise return the full ` Throwable->map ` representation with Stacktrace
:else
(merge
(Throwable->map e)
{:message (.getMessage e)}
other-info))]
{:status (or status-code 500)
:headers (mw.security/security-headers)
:body body}))
(defmethod api-exception-response SQLException
[e]
(-> ((get-method api-exception-response (.getSuperclass SQLException)) e)
(assoc-in [:body :sql-exception-chain] (str/split (with-out-str (jdbc/print-sql-exception-chain e))
#"\s*\n\s*"))))
(defmethod api-exception-response EofException
[_e]
(log/info (trs "Request canceled before finishing."))
{:status-code 204, :body nil, :headers (mw.security/security-headers)})
(defn catch-api-exceptions
"Middleware that catches API Exceptions and returns them in our normal-style format rather than the Jetty 500
Stacktrace page, which is not so useful for our frontend."
[handler]
(fn [request respond _raise]
(handler
request
respond
(comp respond api-exception-response))))
(defn catch-uncaught-exceptions
"Middleware that catches any unexpected Exceptions that reroutes them thru `raise` where they can be handled
appropriately."
[handler]
(fn [request respond raise]
(try
(handler
request
for people that accidentally pass along an Exception , e.g. from qp.async , do the nice thing and route it to
(fn [response]
((if (instance? Throwable response)
raise
respond) response))
raise)
(catch Throwable e
(raise e)))))
|
2bffdf257b08272a2d527a9a90ccb435cc060ccc55cbe87696c4d656e1ad9165 | liqd/aula | Config.hs | {-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE DeriveGeneric #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
# OPTIONS_GHC -Werror -Wall -fno - warn - orphans #
module Config
( Config(Config)
, ListenerConfig(..)
, SmtpConfig(SmtpConfig)
, CleanUpConfig(..)
, CleanUpRule(..)
, GetConfig(..), MonadReaderConfig
, WarnMissing(DontWarnMissing, WarnMissing, CrashMissing)
, PersistenceImpl(..)
, aulaRoot
, aulaTimeLocale
, avatarPath
, cfgCsrfSecret
, checkAvatarPathExists
, checkAvatarPathExistsAndIsEmpty
, checkStaticHtmlPathExists
, cleanUp
, cleanUpDirectory
, cleanUpInterval
, cleanUpKeepnum
, cleanUpPrefix
, cleanUpRules
, dbPath
, defaultConfig
, defaultRecipient
, delegateLikes
, devMode
, exposedUrl
, getSamplesPath
, htmlStatic
, listener
, listenerInterface
, listenerPort
, logging
, logmotd
, monitoring
, persist
, persistenceImpl
, readConfig, configFilePath
, releaseVersion
, senderEmail
, senderName
, sendmailArgs
, sendmailPath
, setCurrentDirectoryToAulaRoot
, smtp
, snapshotInterval
, timeoutCheckInterval
, unsafeTimestampToLocalTime
)
where
import Control.Exception (throwIO, ErrorCall(ErrorCall))
import Control.Lens
import Control.Monad (unless)
import Control.Monad.Reader (MonadReader)
import Data.Functor.Infix ((<$$>))
import Data.List (isSuffixOf)
import Data.Maybe (fromMaybe)
import Data.Monoid ((<>))
import Data.String.Conversions (SBS, cs)
import Data.Time
import Data.Version (showVersion)
import Data.Yaml
import GHC.Generics
import System.Directory
import System.Environment
import System.FilePath ((</>))
import Text.Show.Pretty (ppShow)
import Thentos.CookieSession.CSRF (GetCsrfSecret(..), CsrfSecret(..))
import qualified System.IO.Unsafe
import qualified Data.Text as ST
import Logger
import Types hiding (logLevel)
import qualified Paths_aula as Paths
-- (if you are running ghci and Paths_aula is not available, try `-idist/build/autogen`.)
-- | FIXME: move this instance upstream and remove -fno-warn-orphans for this module.
instance ToJSON CsrfSecret where
toJSON (CsrfSecret s) = String $ cs s
-- | FIXME: move this instance upstream and remove -fno-warn-orphans for this module.
instance FromJSON CsrfSecret where
parseJSON o = CsrfSecret . (cs :: String -> SBS) <$> parseJSON o
data PersistenceImpl = AcidStateInMem | AcidStateOnDisk
deriving (Eq, Ord, Show, Generic, ToJSON, FromJSON, Enum, Bounded)
data SmtpConfig = SmtpConfig
{ _senderName :: String
, _senderEmail :: String
, _defaultRecipient :: String -- (will receive a test email on start, but also for e.g. for use in demo data.)
, _sendmailPath :: String
, _sendmailArgs :: [String]
^ Not using ' ST ' here since Network . Mail . wants ' String ' anyway .
}
deriving (Show, Generic, ToJSON, FromJSON)
makeLenses ''SmtpConfig
data PersistConfig = PersistConfig
{ _dbPath :: String
, _persistenceImpl :: PersistenceImpl
, _snapshotInterval :: Timespan
}
deriving (Show, Generic, ToJSON, FromJSON)
makeLenses ''PersistConfig
data ListenerConfig = ListenerConfig
{ _listenerInterface :: String
, _listenerPort :: Int
}
deriving (Show, Generic, ToJSON, FromJSON)
makeLenses ''ListenerConfig
data CleanUpRule = CleanUpRule
{ _cleanUpDirectory :: FilePath
, _cleanUpPrefix :: FilePath
, _cleanUpKeepnum :: Int
}
deriving (Show, Generic, ToJSON, FromJSON)
makeLenses ''CleanUpRule
data CleanUpConfig = CleanUpConfig
{ _cleanUpInterval :: Timespan
, _cleanUpRules :: [CleanUpRule]
}
deriving (Show, Generic, ToJSON, FromJSON)
makeLenses ''CleanUpConfig
data Config = Config
{ _exposedUrl :: String -- e.g. -stage.liqd.net
, _listener :: ListenerConfig
, _monitoring :: Maybe ListenerConfig
, _htmlStatic :: FilePath
, _avatarPath :: FilePath -- avatars are stored in this directory:
-- FIXME: i think this is not working. run `git grep
-- \"/avatars\"`, and you will find a few places where
-- Config should be consulted, but a string literal is used
-- instead!
, _cfgCsrfSecret :: CsrfSecret
, _logging :: LogConfig
, _persist :: PersistConfig
, _smtp :: SmtpConfig
, _delegateLikes :: Bool
, _timeoutCheckInterval :: Timespan
, _cleanUp :: CleanUpConfig
-- ^ Topics which needs to change phase due to a timeout will
-- be checked at this interval.
* once per day would be the
* 4 times a day ( every 6 hours ) would ensures that
all the topics are ready at least at 6 am .
, _devMode :: Bool
}
deriving (Show, Generic, ToJSON, FromJSON) -- FIXME: make nicer JSON field names.
makeLenses ''Config
class GetConfig r where
getConfig :: Getter r Config
viewConfig :: MonadReader r m => m Config
viewConfig = view getConfig
type MonadReaderConfig r m = (MonadReader r m, GetConfig r)
instance GetConfig Config where
getConfig = id
instance GetCsrfSecret Config where
csrfSecret = pre cfgCsrfSecret
defaultSmtpConfig :: SmtpConfig
defaultSmtpConfig = SmtpConfig
{ _senderName = "Aula Notifications"
, _senderEmail = ""
, _defaultRecipient = "postmaster@localhost"
, _sendmailPath = "/usr/sbin/sendmail"
, _sendmailArgs = ["-t"]
}
defaultPersistConfig :: PersistConfig
defaultPersistConfig = PersistConfig
{ _dbPath = "./state/AulaData"
, _persistenceImpl = AcidStateInMem
, _snapshotInterval = TimespanMins 47
}
defaultLogConfig :: LogConfig
defaultLogConfig = LogConfig
{ _logCfgLevel = DEBUG
, _logCfgPath = "./aula.log"
, _eventLogPath = "./aulaEventLog.json"
}
defaulCleanUpConfig :: CleanUpConfig
defaulCleanUpConfig = CleanUpConfig
{ _cleanUpInterval = TimespanMins 45
, _cleanUpRules =
[ CleanUpRule "./state/AulaData/Archive" "events" 0
, CleanUpRule "./state/AulaData/Archive" "checkpoints" 10
]
}
defaultConfig :: Config
defaultConfig = Config
{ _exposedUrl = ":8080"
, _listener = ListenerConfig "127.0.0.1" 8080
, _monitoring = Just (ListenerConfig "127.0.0.1" 8888)
, _htmlStatic = "./static"
, _avatarPath = "./avatars"
, _cfgCsrfSecret = CsrfSecret "please-replace-this-with-random-secret"
, _logging = defaultLogConfig
, _persist = defaultPersistConfig
, _smtp = defaultSmtpConfig
, _delegateLikes = True
, _timeoutCheckInterval = TimespanHours 6
, _cleanUp = defaulCleanUpConfig
, _devMode = False
}
sanitize :: Config -> Config
sanitize = exposedUrl %~ (\u -> if "/" `isSuffixOf` u then init u else u)
data WarnMissing = DontWarnMissing | WarnMissing | CrashMissing
deriving (Eq, Show)
| In case of @WarnMissing : : WarnMissing@ , log the warning to stderr . ( We do n't have logging
-- configured yet.)
readConfig :: WarnMissing -> IO Config
readConfig warnMissing = sanitize <$> (configFilePath >>= maybe (errr msgAulaPathNotSet >> dflt) decodeFileDflt)
where
dflt :: IO Config
dflt = pure defaultConfig
decodeFileDflt :: FilePath -> IO Config
decodeFileDflt fp = decodeFileEither fp >>= either (\emsg -> errr (msgParseError emsg) >> dflt) pure
msgAulaPathNotSet :: [String]
msgAulaPathNotSet =
[ "no config file found: $AULA_ROOT_PATH not set."
, "to fix this, write the following lines to $AULA_ROOT_PATH/aula.yaml:"
]
msgParseError :: Show a => a -> [String]
msgParseError emsg =
[ "could not read config file:"
, show emsg
, "to fix this, write the following lines to $AULA_ROOT_PATH/aula.yaml:"
]
errr :: [String] -> IO ()
errr msgH = case warnMissing of
DontWarnMissing -> pure ()
WarnMissing -> unSendLogMsg stderrLog . LogEntry ERROR $ cs msgs
CrashMissing -> throwIO . ErrorCall $ msgs
where
msgs = unlines $ [""] <> msgH <> ["", cs $ encode defaultConfig]
configFilePath :: IO (Maybe FilePath)
configFilePath = (</> "aula.yaml") <$$> aulaRoot
aulaRoot :: IO (Maybe FilePath)
aulaRoot = lookup "AULA_ROOT_PATH" <$> getEnvironment
setCurrentDirectoryToAulaRoot :: IO ()
setCurrentDirectoryToAulaRoot = aulaRoot >>= maybe (pure ()) setCurrentDirectory
getSamplesPath :: IO FilePath
getSamplesPath = fromMaybe (error msg) . lookup var <$> getEnvironment
where
var = "AULA_SAMPLES"
msg = "please set $" <> var <> " to a path (will be created if n/a)"
-- * release version
releaseVersion :: String
releaseVersion = "[v" <> showVersion Paths.version <> "]"
-- * system time, time zones
| This works as long as the running system does n't move from one time zone to the other . It
-- would be nicer to make that an extra 'Action' class, but I argue that it's not worth the time to
-- do it (and to have to handle the slightly larger code base from now on).
unsafeTimestampToLocalTime :: Timestamp -> ZonedTime
unsafeTimestampToLocalTime (Timestamp t) = System.IO.Unsafe.unsafePerformIO $ utcToLocalZonedTime t
aulaTimeLocale :: TimeLocale
aulaTimeLocale = defaultTimeLocale
{ knownTimeZones = knownTimeZones defaultTimeLocale
<> [TimeZone (1 * 60) False "CET", TimeZone (2 * 60) True "CEST"] }
checkAvatarPathExists :: Config -> IO ()
checkAvatarPathExists cfg = checkPathExists (cfg ^. avatarPath)
checkAvatarPathExistsAndIsEmpty :: Config -> IO ()
checkAvatarPathExistsAndIsEmpty cfg =
checkPathExistsAndIsEmpty (cfg ^. avatarPath)
checkStaticHtmlPathExists :: Config -> IO ()
checkStaticHtmlPathExists cfg =
checkPathExists (cfg ^. htmlStatic)
checkPathExists :: FilePath -> IO ()
checkPathExists path = do
exists <- doesDirectoryExist path
unless exists . throwIO . ErrorCall $
show path <> " does not exist or is not a directory."
checkPathExistsAndIsEmpty :: FilePath -> IO ()
checkPathExistsAndIsEmpty path = do
checkPathExists path
isempty <- null <$> getDirectoryContentsNoDots path
unless isempty . throwIO . ErrorCall $
show path <> " does not exist, is not a directory, or is not empty."
-- * motd
| Log the message ( motto ) of the day ( like /etc / motd ) .
logmotd :: Config -> FilePath -> IO ()
logmotd cfg wd = do
name <- getProgName
unSendLogMsg (aulaLog (cfg ^. logging)) . LogEntry INFO . ST.unlines $
[ "starting " <> cs name
, ""
, "\nrelease:"
, cs Config.releaseVersion
, "\nroot path:"
, cs wd
, "\nsetup:", cs $ ppShow cfg
, ""
]
| null | https://raw.githubusercontent.com/liqd/aula/f96dbf85cd80d0b445e7d198c9b2866bed9c4e3d/src/Config.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE DeriveAnyClass #
# LANGUAGE OverloadedStrings #
# LANGUAGE TemplateHaskell #
(if you are running ghci and Paths_aula is not available, try `-idist/build/autogen`.)
| FIXME: move this instance upstream and remove -fno-warn-orphans for this module.
| FIXME: move this instance upstream and remove -fno-warn-orphans for this module.
(will receive a test email on start, but also for e.g. for use in demo data.)
e.g. -stage.liqd.net
avatars are stored in this directory:
FIXME: i think this is not working. run `git grep
\"/avatars\"`, and you will find a few places where
Config should be consulted, but a string literal is used
instead!
^ Topics which needs to change phase due to a timeout will
be checked at this interval.
FIXME: make nicer JSON field names.
configured yet.)
* release version
* system time, time zones
would be nicer to make that an extra 'Action' class, but I argue that it's not worth the time to
do it (and to have to handle the slightly larger code base from now on).
* motd | # LANGUAGE DeriveGeneric #
# OPTIONS_GHC -Werror -Wall -fno - warn - orphans #
module Config
( Config(Config)
, ListenerConfig(..)
, SmtpConfig(SmtpConfig)
, CleanUpConfig(..)
, CleanUpRule(..)
, GetConfig(..), MonadReaderConfig
, WarnMissing(DontWarnMissing, WarnMissing, CrashMissing)
, PersistenceImpl(..)
, aulaRoot
, aulaTimeLocale
, avatarPath
, cfgCsrfSecret
, checkAvatarPathExists
, checkAvatarPathExistsAndIsEmpty
, checkStaticHtmlPathExists
, cleanUp
, cleanUpDirectory
, cleanUpInterval
, cleanUpKeepnum
, cleanUpPrefix
, cleanUpRules
, dbPath
, defaultConfig
, defaultRecipient
, delegateLikes
, devMode
, exposedUrl
, getSamplesPath
, htmlStatic
, listener
, listenerInterface
, listenerPort
, logging
, logmotd
, monitoring
, persist
, persistenceImpl
, readConfig, configFilePath
, releaseVersion
, senderEmail
, senderName
, sendmailArgs
, sendmailPath
, setCurrentDirectoryToAulaRoot
, smtp
, snapshotInterval
, timeoutCheckInterval
, unsafeTimestampToLocalTime
)
where
import Control.Exception (throwIO, ErrorCall(ErrorCall))
import Control.Lens
import Control.Monad (unless)
import Control.Monad.Reader (MonadReader)
import Data.Functor.Infix ((<$$>))
import Data.List (isSuffixOf)
import Data.Maybe (fromMaybe)
import Data.Monoid ((<>))
import Data.String.Conversions (SBS, cs)
import Data.Time
import Data.Version (showVersion)
import Data.Yaml
import GHC.Generics
import System.Directory
import System.Environment
import System.FilePath ((</>))
import Text.Show.Pretty (ppShow)
import Thentos.CookieSession.CSRF (GetCsrfSecret(..), CsrfSecret(..))
import qualified System.IO.Unsafe
import qualified Data.Text as ST
import Logger
import Types hiding (logLevel)
import qualified Paths_aula as Paths
instance ToJSON CsrfSecret where
toJSON (CsrfSecret s) = String $ cs s
instance FromJSON CsrfSecret where
parseJSON o = CsrfSecret . (cs :: String -> SBS) <$> parseJSON o
data PersistenceImpl = AcidStateInMem | AcidStateOnDisk
deriving (Eq, Ord, Show, Generic, ToJSON, FromJSON, Enum, Bounded)
data SmtpConfig = SmtpConfig
{ _senderName :: String
, _senderEmail :: String
, _sendmailPath :: String
, _sendmailArgs :: [String]
^ Not using ' ST ' here since Network . Mail . wants ' String ' anyway .
}
deriving (Show, Generic, ToJSON, FromJSON)
makeLenses ''SmtpConfig
data PersistConfig = PersistConfig
{ _dbPath :: String
, _persistenceImpl :: PersistenceImpl
, _snapshotInterval :: Timespan
}
deriving (Show, Generic, ToJSON, FromJSON)
makeLenses ''PersistConfig
data ListenerConfig = ListenerConfig
{ _listenerInterface :: String
, _listenerPort :: Int
}
deriving (Show, Generic, ToJSON, FromJSON)
makeLenses ''ListenerConfig
data CleanUpRule = CleanUpRule
{ _cleanUpDirectory :: FilePath
, _cleanUpPrefix :: FilePath
, _cleanUpKeepnum :: Int
}
deriving (Show, Generic, ToJSON, FromJSON)
makeLenses ''CleanUpRule
data CleanUpConfig = CleanUpConfig
{ _cleanUpInterval :: Timespan
, _cleanUpRules :: [CleanUpRule]
}
deriving (Show, Generic, ToJSON, FromJSON)
makeLenses ''CleanUpConfig
data Config = Config
, _listener :: ListenerConfig
, _monitoring :: Maybe ListenerConfig
, _htmlStatic :: FilePath
, _cfgCsrfSecret :: CsrfSecret
, _logging :: LogConfig
, _persist :: PersistConfig
, _smtp :: SmtpConfig
, _delegateLikes :: Bool
, _timeoutCheckInterval :: Timespan
, _cleanUp :: CleanUpConfig
* once per day would be the
* 4 times a day ( every 6 hours ) would ensures that
all the topics are ready at least at 6 am .
, _devMode :: Bool
}
makeLenses ''Config
class GetConfig r where
getConfig :: Getter r Config
viewConfig :: MonadReader r m => m Config
viewConfig = view getConfig
type MonadReaderConfig r m = (MonadReader r m, GetConfig r)
instance GetConfig Config where
getConfig = id
instance GetCsrfSecret Config where
csrfSecret = pre cfgCsrfSecret
defaultSmtpConfig :: SmtpConfig
defaultSmtpConfig = SmtpConfig
{ _senderName = "Aula Notifications"
, _senderEmail = ""
, _defaultRecipient = "postmaster@localhost"
, _sendmailPath = "/usr/sbin/sendmail"
, _sendmailArgs = ["-t"]
}
defaultPersistConfig :: PersistConfig
defaultPersistConfig = PersistConfig
{ _dbPath = "./state/AulaData"
, _persistenceImpl = AcidStateInMem
, _snapshotInterval = TimespanMins 47
}
defaultLogConfig :: LogConfig
defaultLogConfig = LogConfig
{ _logCfgLevel = DEBUG
, _logCfgPath = "./aula.log"
, _eventLogPath = "./aulaEventLog.json"
}
defaulCleanUpConfig :: CleanUpConfig
defaulCleanUpConfig = CleanUpConfig
{ _cleanUpInterval = TimespanMins 45
, _cleanUpRules =
[ CleanUpRule "./state/AulaData/Archive" "events" 0
, CleanUpRule "./state/AulaData/Archive" "checkpoints" 10
]
}
defaultConfig :: Config
defaultConfig = Config
{ _exposedUrl = ":8080"
, _listener = ListenerConfig "127.0.0.1" 8080
, _monitoring = Just (ListenerConfig "127.0.0.1" 8888)
, _htmlStatic = "./static"
, _avatarPath = "./avatars"
, _cfgCsrfSecret = CsrfSecret "please-replace-this-with-random-secret"
, _logging = defaultLogConfig
, _persist = defaultPersistConfig
, _smtp = defaultSmtpConfig
, _delegateLikes = True
, _timeoutCheckInterval = TimespanHours 6
, _cleanUp = defaulCleanUpConfig
, _devMode = False
}
sanitize :: Config -> Config
sanitize = exposedUrl %~ (\u -> if "/" `isSuffixOf` u then init u else u)
data WarnMissing = DontWarnMissing | WarnMissing | CrashMissing
deriving (Eq, Show)
| In case of @WarnMissing : : WarnMissing@ , log the warning to stderr . ( We do n't have logging
readConfig :: WarnMissing -> IO Config
readConfig warnMissing = sanitize <$> (configFilePath >>= maybe (errr msgAulaPathNotSet >> dflt) decodeFileDflt)
where
dflt :: IO Config
dflt = pure defaultConfig
decodeFileDflt :: FilePath -> IO Config
decodeFileDflt fp = decodeFileEither fp >>= either (\emsg -> errr (msgParseError emsg) >> dflt) pure
msgAulaPathNotSet :: [String]
msgAulaPathNotSet =
[ "no config file found: $AULA_ROOT_PATH not set."
, "to fix this, write the following lines to $AULA_ROOT_PATH/aula.yaml:"
]
msgParseError :: Show a => a -> [String]
msgParseError emsg =
[ "could not read config file:"
, show emsg
, "to fix this, write the following lines to $AULA_ROOT_PATH/aula.yaml:"
]
errr :: [String] -> IO ()
errr msgH = case warnMissing of
DontWarnMissing -> pure ()
WarnMissing -> unSendLogMsg stderrLog . LogEntry ERROR $ cs msgs
CrashMissing -> throwIO . ErrorCall $ msgs
where
msgs = unlines $ [""] <> msgH <> ["", cs $ encode defaultConfig]
configFilePath :: IO (Maybe FilePath)
configFilePath = (</> "aula.yaml") <$$> aulaRoot
aulaRoot :: IO (Maybe FilePath)
aulaRoot = lookup "AULA_ROOT_PATH" <$> getEnvironment
setCurrentDirectoryToAulaRoot :: IO ()
setCurrentDirectoryToAulaRoot = aulaRoot >>= maybe (pure ()) setCurrentDirectory
getSamplesPath :: IO FilePath
getSamplesPath = fromMaybe (error msg) . lookup var <$> getEnvironment
where
var = "AULA_SAMPLES"
msg = "please set $" <> var <> " to a path (will be created if n/a)"
releaseVersion :: String
releaseVersion = "[v" <> showVersion Paths.version <> "]"
| This works as long as the running system does n't move from one time zone to the other . It
unsafeTimestampToLocalTime :: Timestamp -> ZonedTime
unsafeTimestampToLocalTime (Timestamp t) = System.IO.Unsafe.unsafePerformIO $ utcToLocalZonedTime t
aulaTimeLocale :: TimeLocale
aulaTimeLocale = defaultTimeLocale
{ knownTimeZones = knownTimeZones defaultTimeLocale
<> [TimeZone (1 * 60) False "CET", TimeZone (2 * 60) True "CEST"] }
checkAvatarPathExists :: Config -> IO ()
checkAvatarPathExists cfg = checkPathExists (cfg ^. avatarPath)
checkAvatarPathExistsAndIsEmpty :: Config -> IO ()
checkAvatarPathExistsAndIsEmpty cfg =
checkPathExistsAndIsEmpty (cfg ^. avatarPath)
checkStaticHtmlPathExists :: Config -> IO ()
checkStaticHtmlPathExists cfg =
checkPathExists (cfg ^. htmlStatic)
checkPathExists :: FilePath -> IO ()
checkPathExists path = do
exists <- doesDirectoryExist path
unless exists . throwIO . ErrorCall $
show path <> " does not exist or is not a directory."
checkPathExistsAndIsEmpty :: FilePath -> IO ()
checkPathExistsAndIsEmpty path = do
checkPathExists path
isempty <- null <$> getDirectoryContentsNoDots path
unless isempty . throwIO . ErrorCall $
show path <> " does not exist, is not a directory, or is not empty."
| Log the message ( motto ) of the day ( like /etc / motd ) .
logmotd :: Config -> FilePath -> IO ()
logmotd cfg wd = do
name <- getProgName
unSendLogMsg (aulaLog (cfg ^. logging)) . LogEntry INFO . ST.unlines $
[ "starting " <> cs name
, ""
, "\nrelease:"
, cs Config.releaseVersion
, "\nroot path:"
, cs wd
, "\nsetup:", cs $ ppShow cfg
, ""
]
|
27670a02d70be92ca1cdf2a00adf5685afc8c4b19f3989573932894d55c99d27 | jyh/metaprl | nuprl_general.mli | extends Ma_strong__subtype__stuff
define unfold_imax__list : "imax-list"[]{'"L"} <-->
"list_accum"[]{"x", "y"."imax"[]{'"x";'"y"};"hd"[]{'"L"};"tl"[]{'"L"}}
define unfold_l_interval : "l_interval"[]{'"l";'"j";'"i"} <-->
"mklist"[]{"sub"[]{'"i";'"j"};"lambda"[]{"x"."select"[]{"add"[]{'"j";'"x"};'"l"}}}
define unfold_pairwise : "pairwise"[]{"x", "y".'"P"['"x";'"y"];'"L"} <-->
"all"[]{"int_seg"[]{"number"[0:n]{};"length"[]{'"L"}};"i"."all"[]{"int_seg"[]{"number"[0:n]{};'"i"};"j".'"P"["select"[]{'"j";'"L"};"select"[]{'"i";'"L"}]}}
define unfold_inv__rel : "inv-rel"[]{'"A";'"B";'"f";'"finv"} <-->
"and"[]{"all"[]{'"A";"a"."all"[]{'"B";"b"."implies"[]{"equal"[]{"union"[]{'"A";"unit"[]{}};('"finv" '"b");"inl"[]{'"a"}};"equal"[]{'"B";'"b";('"f" '"a")}}}};"all"[]{'"A";"a"."equal"[]{"union"[]{'"A";"unit"[]{}};('"finv" ('"f" '"a"));"inl"[]{'"a"}}}}
define unfold_dectt : "dectt"[]{'"d"} <-->
"is_inl"[]{'"d"}
define unfold_finite__type : "finite-type"[]{'"T"} <-->
"exists"[]{"nat"[]{};"n"."exists"[]{"fun"[]{"int_seg"[]{"number"[0:n]{};'"n"};"".'"T"};"f"."surject"[]{"int_seg"[]{"number"[0:n]{};'"n"};'"T";'"f"}}}
define unfold_mu : "mu"[]{'"f"} <-->
(("ycomb"[]{} "lambda"[]{"mu"."lambda"[]{"f"."ifthenelse"[]{('"f" "number"[0:n]{});"number"[0:n]{};"add"[]{('"mu" "lambda"[]{"x".('"f" "add"[]{'"x";"number"[1:n]{}})});"number"[1:n]{}}}}}) '"f")
define unfold_upto : "upto"[]{'"n"} <-->
(("ycomb"[]{} "lambda"[]{"upto"."lambda"[]{"n"."ifthenelse"[]{"beq_int"[]{'"n";"number"[0:n]{}};"nil"[]{};"append"[]{('"upto" "sub"[]{'"n";"number"[1:n]{}});"cons"[]{"sub"[]{'"n";"number"[1:n]{}};"nil"[]{}}}}}}) '"n")
define unfold_concat : "concat"[]{'"ll"} <-->
"reduce"[]{"lambda"[]{"l"."lambda"[]{"l'"."append"[]{'"l";'"l'"}}};"nil"[]{};'"ll"}
define unfold_mapl : "mapl"[]{'"f";'"l"} <-->
"map"[]{'"f";'"l"}
define unfold_CV : "CV"[]{'"F"} <-->
("ycomb"[]{} "lambda"[]{"CV"."lambda"[]{"t".(('"F" '"t") '"CV")}})
| null | https://raw.githubusercontent.com/jyh/metaprl/51ba0bbbf409ecb7f96f5abbeb91902fdec47a19/theories/mesa/nuprl_general.mli | ocaml | extends Ma_strong__subtype__stuff
define unfold_imax__list : "imax-list"[]{'"L"} <-->
"list_accum"[]{"x", "y"."imax"[]{'"x";'"y"};"hd"[]{'"L"};"tl"[]{'"L"}}
define unfold_l_interval : "l_interval"[]{'"l";'"j";'"i"} <-->
"mklist"[]{"sub"[]{'"i";'"j"};"lambda"[]{"x"."select"[]{"add"[]{'"j";'"x"};'"l"}}}
define unfold_pairwise : "pairwise"[]{"x", "y".'"P"['"x";'"y"];'"L"} <-->
"all"[]{"int_seg"[]{"number"[0:n]{};"length"[]{'"L"}};"i"."all"[]{"int_seg"[]{"number"[0:n]{};'"i"};"j".'"P"["select"[]{'"j";'"L"};"select"[]{'"i";'"L"}]}}
define unfold_inv__rel : "inv-rel"[]{'"A";'"B";'"f";'"finv"} <-->
"and"[]{"all"[]{'"A";"a"."all"[]{'"B";"b"."implies"[]{"equal"[]{"union"[]{'"A";"unit"[]{}};('"finv" '"b");"inl"[]{'"a"}};"equal"[]{'"B";'"b";('"f" '"a")}}}};"all"[]{'"A";"a"."equal"[]{"union"[]{'"A";"unit"[]{}};('"finv" ('"f" '"a"));"inl"[]{'"a"}}}}
define unfold_dectt : "dectt"[]{'"d"} <-->
"is_inl"[]{'"d"}
define unfold_finite__type : "finite-type"[]{'"T"} <-->
"exists"[]{"nat"[]{};"n"."exists"[]{"fun"[]{"int_seg"[]{"number"[0:n]{};'"n"};"".'"T"};"f"."surject"[]{"int_seg"[]{"number"[0:n]{};'"n"};'"T";'"f"}}}
define unfold_mu : "mu"[]{'"f"} <-->
(("ycomb"[]{} "lambda"[]{"mu"."lambda"[]{"f"."ifthenelse"[]{('"f" "number"[0:n]{});"number"[0:n]{};"add"[]{('"mu" "lambda"[]{"x".('"f" "add"[]{'"x";"number"[1:n]{}})});"number"[1:n]{}}}}}) '"f")
define unfold_upto : "upto"[]{'"n"} <-->
(("ycomb"[]{} "lambda"[]{"upto"."lambda"[]{"n"."ifthenelse"[]{"beq_int"[]{'"n";"number"[0:n]{}};"nil"[]{};"append"[]{('"upto" "sub"[]{'"n";"number"[1:n]{}});"cons"[]{"sub"[]{'"n";"number"[1:n]{}};"nil"[]{}}}}}}) '"n")
define unfold_concat : "concat"[]{'"ll"} <-->
"reduce"[]{"lambda"[]{"l"."lambda"[]{"l'"."append"[]{'"l";'"l'"}}};"nil"[]{};'"ll"}
define unfold_mapl : "mapl"[]{'"f";'"l"} <-->
"map"[]{'"f";'"l"}
define unfold_CV : "CV"[]{'"F"} <-->
("ycomb"[]{} "lambda"[]{"CV"."lambda"[]{"t".(('"F" '"t") '"CV")}})
| |
6173bba01e7d288a86fe4563c94b06cf31ccf1a84dc1f160cba548060f7236df | ocaml-multicore/tezos | client_baking_denunciation.mli | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < >
(* *)
(* 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. *)
(* *)
(*****************************************************************************)
val create :
#Protocol_client_context.full ->
?canceler:Lwt_canceler.t ->
preserved_levels:int ->
Client_baking_blocks.block_info tzresult Lwt_stream.t ->
unit tzresult Lwt.t
| null | https://raw.githubusercontent.com/ocaml-multicore/tezos/e4fd21a1cb02d194b3162ab42d512b7c985ee8a9/src/proto_012_Psithaca/lib_delegate/client_baking_denunciation.mli | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*************************************************************************** | Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < >
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
val create :
#Protocol_client_context.full ->
?canceler:Lwt_canceler.t ->
preserved_levels:int ->
Client_baking_blocks.block_info tzresult Lwt_stream.t ->
unit tzresult Lwt.t
|
c9200b9ad6b51c7b2ace93d6c25e8bb286c86af1bc173d5405e8689aea20b028 | troy-west/apache-kafka-number-stations-clj | serde_test.clj | (ns numbers.serde-test
(:require [clojure.test :refer :all]
[numbers.serdes :as serdes])
(:import (org.apache.kafka.common.serialization Serializer Deserializer)))
(deftest serialize
(is (= "{\"time\":1557125670789,\"type\":\"GER\",\"name\":\"85\",\"long\":-92,\"lat\":-30,\"content\":[\"eins\",\"null\",\"sechs\"]}"
(String.
(.serialize ^Serializer (serdes/json-serializer)
"radio-logs"
{:time 1557125670789
:type "GER"
:name "85"
:long -92
:lat -30
:content ["eins" "null" "sechs"]})))))
(deftest deserialize
(is (= {:time 1557125670789
:type "GER"
:name "85"
:long -92
:lat -30
:content ["eins" "null" "sechs"]}
(.deserialize ^Deserializer (serdes/json-deserializer)
"radio-logs"
(.getBytes "{\"time\":1557125670789,\"type\":\"GER\",\"name\":\"85\",\"long\":-92,\"lat\":-30,\"content\":[\"eins\",\"null\",\"sechs\"]}"))))) | null | https://raw.githubusercontent.com/troy-west/apache-kafka-number-stations-clj/d38b8ef57c38c056b41e1d24a2b8671479113300/test/numbers/serde_test.clj | clojure | (ns numbers.serde-test
(:require [clojure.test :refer :all]
[numbers.serdes :as serdes])
(:import (org.apache.kafka.common.serialization Serializer Deserializer)))
(deftest serialize
(is (= "{\"time\":1557125670789,\"type\":\"GER\",\"name\":\"85\",\"long\":-92,\"lat\":-30,\"content\":[\"eins\",\"null\",\"sechs\"]}"
(String.
(.serialize ^Serializer (serdes/json-serializer)
"radio-logs"
{:time 1557125670789
:type "GER"
:name "85"
:long -92
:lat -30
:content ["eins" "null" "sechs"]})))))
(deftest deserialize
(is (= {:time 1557125670789
:type "GER"
:name "85"
:long -92
:lat -30
:content ["eins" "null" "sechs"]}
(.deserialize ^Deserializer (serdes/json-deserializer)
"radio-logs"
(.getBytes "{\"time\":1557125670789,\"type\":\"GER\",\"name\":\"85\",\"long\":-92,\"lat\":-30,\"content\":[\"eins\",\"null\",\"sechs\"]}"))))) | |
3817e26a6039e83e7d3b2cd0b58103c932ebd3404fd9ef41b3069a269553d0a4 | jgm/pandoc-citeproc | Embedded.hs | # LANGUAGE NoImplicitPrelude #
# LANGUAGE TemplateHaskell #
module Text.CSL.Data.Embedded (localeFiles, defaultCSL, manpage, license)
where
import Prelude
import qualified Data.ByteString.Char8 as S
import Data.FileEmbed
localeFiles :: [(FilePath, S.ByteString)]
localeFiles = $(embedDir "locales")
defaultCSL :: S.ByteString
defaultCSL = $(embedFile "chicago-author-date.csl")
manpage :: S.ByteString
manpage = $(embedFile "man/man1/pandoc-citeproc.1")
license :: S.ByteString
license = $(embedFile "LICENSE")
| null | https://raw.githubusercontent.com/jgm/pandoc-citeproc/473378e588c40a6c3cb3b24330431b89cf4f81b4/src/Text/CSL/Data/Embedded.hs | haskell | # LANGUAGE NoImplicitPrelude #
# LANGUAGE TemplateHaskell #
module Text.CSL.Data.Embedded (localeFiles, defaultCSL, manpage, license)
where
import Prelude
import qualified Data.ByteString.Char8 as S
import Data.FileEmbed
localeFiles :: [(FilePath, S.ByteString)]
localeFiles = $(embedDir "locales")
defaultCSL :: S.ByteString
defaultCSL = $(embedFile "chicago-author-date.csl")
manpage :: S.ByteString
manpage = $(embedFile "man/man1/pandoc-citeproc.1")
license :: S.ByteString
license = $(embedFile "LICENSE")
| |
ca24b74116eb0c77274837149c86e0e695086ed790bcd4ccea66922bee40c7a8 | junjihashimoto/hugs-js | DefaultSetup.hs | module Main where
import Distribution.Simple
main :: IO ()
main = defaultMain
| null | https://raw.githubusercontent.com/junjihashimoto/hugs-js/5a38dbe8310b5d56746ec83c24f7a9f520fbdcd3/hugs98-Sep2006/packages/Cabal/DefaultSetup.hs | haskell | module Main where
import Distribution.Simple
main :: IO ()
main = defaultMain
| |
a987d14f98a75d7b0eb779cfdfd5e941aa5e49d7094c8f54b8ab19cba8d59fdf | larcenists/larceny | rlist.sps | (import (scheme base)
(scheme write)
(tests scheme rlist)
(tests scheme test))
(display "Running tests for (scheme rlist)\n")
(run-rlist-tests)
(report-test-results)
| null | https://raw.githubusercontent.com/larcenists/larceny/fef550c7d3923deb7a5a1ccd5a628e54cf231c75/test/R7RS/Lib/tests/scheme/run/rlist.sps | scheme | (import (scheme base)
(scheme write)
(tests scheme rlist)
(tests scheme test))
(display "Running tests for (scheme rlist)\n")
(run-rlist-tests)
(report-test-results)
| |
136e9bad29b14f6c5aa5cb408925f23176005aa26dbb54bb7dfe776fb824ce81 | biocaml/biocaml | biocaml_app_main.ml | open Core.Std
open Flow
open Biocaml_app_common
let cmd_info =
let say fmt = ksprintf (fun s -> wrap_deferred_lwt (fun () -> Lwt_io.print s)) fmt in
Command_line.(
basic
~summary:"Get information about files"
Spec.(empty +> anon (sequence ("FILES" %: string)) ++ uses_lwt ())
(fun files ->
let f s =
say "File: %S\n" s
>>= fun () ->
match Biocaml_tags.guess_from_filename s with
| Ok tags ->
say
" Inferred Tags: %s\n"
(Biocaml_tags.sexp_of_file_format tags |> Sexp.to_string_hum)
| Error e ->
say
" Cannot retrieve tags: %s\n"
(match e with
| `extension_absent -> "no extension"
| `extension_unknown s -> sprintf "unknown extension: %S" s)
in
List.fold files ~init:(return ( ) ) ~f:(fun m v - > m > > = fun ( ) - > f v ) )
while_sequential ~f files >>= (fun _ -> return ()) >>< common_error_to_string))
;;
let () =
Command_line.(
let whole_thing =
group
~summary:"Biocaml's command-line application"
[ "bed", Biocaml_app_bed_operations.command
; "transform", Biocaml_app_transform.command
; "entrez", Biocaml_app_entrez.command
; "demux", Biocaml_app_demux.command
; "random", Biocaml_app_random.command
; "alignments", Biocaml_app_count_alignments.command
; "info", cmd_info
]
in
run ~version:Biocaml_about.version whole_thing;
let m = List.fold !lwts_to_run ~init:(return ()) ~f:(fun m n -> m >>= fun () -> n) in
match Lwt_main.run m with
| Ok () -> ()
| Error s -> eprintf "ERROR: %s\n%!" s)
;;
| null | https://raw.githubusercontent.com/biocaml/biocaml/ac619539fed348747d686b8f628e80c1bb8bfc59/src/tmp/biocaml_app_main.ml | ocaml | open Core.Std
open Flow
open Biocaml_app_common
let cmd_info =
let say fmt = ksprintf (fun s -> wrap_deferred_lwt (fun () -> Lwt_io.print s)) fmt in
Command_line.(
basic
~summary:"Get information about files"
Spec.(empty +> anon (sequence ("FILES" %: string)) ++ uses_lwt ())
(fun files ->
let f s =
say "File: %S\n" s
>>= fun () ->
match Biocaml_tags.guess_from_filename s with
| Ok tags ->
say
" Inferred Tags: %s\n"
(Biocaml_tags.sexp_of_file_format tags |> Sexp.to_string_hum)
| Error e ->
say
" Cannot retrieve tags: %s\n"
(match e with
| `extension_absent -> "no extension"
| `extension_unknown s -> sprintf "unknown extension: %S" s)
in
List.fold files ~init:(return ( ) ) ~f:(fun m v - > m > > = fun ( ) - > f v ) )
while_sequential ~f files >>= (fun _ -> return ()) >>< common_error_to_string))
;;
let () =
Command_line.(
let whole_thing =
group
~summary:"Biocaml's command-line application"
[ "bed", Biocaml_app_bed_operations.command
; "transform", Biocaml_app_transform.command
; "entrez", Biocaml_app_entrez.command
; "demux", Biocaml_app_demux.command
; "random", Biocaml_app_random.command
; "alignments", Biocaml_app_count_alignments.command
; "info", cmd_info
]
in
run ~version:Biocaml_about.version whole_thing;
let m = List.fold !lwts_to_run ~init:(return ()) ~f:(fun m n -> m >>= fun () -> n) in
match Lwt_main.run m with
| Ok () -> ()
| Error s -> eprintf "ERROR: %s\n%!" s)
;;
| |
84c3bb025732dc7f1f9322e374d2b420e6bd53333b9de4fbd09c46b172b455fb | Vetd-Inc/vetd-app | repl_init.clj | (ns repl-init
(:require [com.vetd.app.core :as core]
[figwheel-sidecar.repl-api :as fw]))
#_(.setLevel ( org.slf4j.LoggerFactory/getLogger org.slf4j.Logger/ROOT_LOGGER_NAME)
ch.qos.logback.classic.Level/INFO)
(future
(core/-main))
| null | https://raw.githubusercontent.com/Vetd-Inc/vetd-app/9b33b1443b9d84d39305a63fc58119f8e014cf11/dev/clj/repl_init.clj | clojure | (ns repl-init
(:require [com.vetd.app.core :as core]
[figwheel-sidecar.repl-api :as fw]))
#_(.setLevel ( org.slf4j.LoggerFactory/getLogger org.slf4j.Logger/ROOT_LOGGER_NAME)
ch.qos.logback.classic.Level/INFO)
(future
(core/-main))
| |
709ffa51d2ec79fac5d52745ec8e02d0fbf9f16ba4af501e1ac55ecf68e595a2 | DHSProgram/DHS-Indicators-SPSS | CH_SIZE.sps | * Encoding: windows-1252.
*****************************************************************************************************
Program: CH_SIZE.sps
Purpose: Code child size variables
Data inputs: KR dataset
Data outputs: coded variables
Author: Shireen Assaf and translated to SPSS by Ivana Bjelic
Date last modified: September 01 2019 by Ivana Bjelic
*****************************************************************************************************
*----------------------------------------------------------------------------
Variables created in this file:
ch_size_birth "Size of child at birth as reported by mother"
ch_report_bw "Has a reported birth weight"
ch_below_2p5 "Birth weight less than 2.5 kg"
----------------------------------------------------------------------------.
*Child's size at birth.
recode m18 (5=1) (4=2) (1,2,3=3) (8,9=9) into ch_size_birth.
variable labels ch_size_birth "Child's size at birth".
value labels ch_size_birth 1 "Very small" 2 "Smaller than average" 3 "Average or larger" 9 "Don't know/missing".
*Child's reported birth weight.
recode m19 (0 thru 9000=1) (else=0) into ch_report_bw.
variable labels ch_report_bw "Child's reported birth weight".
value labels ch_report_bw 0 "No" 1 "Yes".
*Child before 2.5kg.
do if ch_report_bw=1.
+recode m19 (0 thru 2499=1) (else=0) into ch_below_2p5.
end if.
variable labels ch_below_2p5 "Child before 2.5kg".
value labels ch_below_2p5 0 "No" 1 "Yes".
| null | https://raw.githubusercontent.com/DHSProgram/DHS-Indicators-SPSS/578e6d40eff9edebda7cf0db0d9a0a52a537d98c/Chap10_CH/CH_SIZE.sps | scheme | * Encoding: windows-1252.
*****************************************************************************************************
Program: CH_SIZE.sps
Purpose: Code child size variables
Data inputs: KR dataset
Data outputs: coded variables
Author: Shireen Assaf and translated to SPSS by Ivana Bjelic
Date last modified: September 01 2019 by Ivana Bjelic
*****************************************************************************************************
*----------------------------------------------------------------------------
Variables created in this file:
ch_size_birth "Size of child at birth as reported by mother"
ch_report_bw "Has a reported birth weight"
ch_below_2p5 "Birth weight less than 2.5 kg"
----------------------------------------------------------------------------.
*Child's size at birth.
recode m18 (5=1) (4=2) (1,2,3=3) (8,9=9) into ch_size_birth.
variable labels ch_size_birth "Child's size at birth".
value labels ch_size_birth 1 "Very small" 2 "Smaller than average" 3 "Average or larger" 9 "Don't know/missing".
*Child's reported birth weight.
recode m19 (0 thru 9000=1) (else=0) into ch_report_bw.
variable labels ch_report_bw "Child's reported birth weight".
value labels ch_report_bw 0 "No" 1 "Yes".
*Child before 2.5kg.
do if ch_report_bw=1.
+recode m19 (0 thru 2499=1) (else=0) into ch_below_2p5.
end if.
variable labels ch_below_2p5 "Child before 2.5kg".
value labels ch_below_2p5 0 "No" 1 "Yes".
| |
d6081d6a2fed7b00a8a44abf00864e9b599c399388039c3f551309b2857cb776 | racket/deinprogramm | tool.rkt | #lang racket/base
(require racket/file racket/class racket/unit racket/contract
drracket/tool
mred framework
string-constants)
(provide tool@)
(preferences:set-default 'signatures:enable-checking? #t boolean?)
(define tool@
(unit (import drracket:tool^) (export drracket:tool-exports^)
(define (phase1) (void))
(define (phase2) (void))
(define (signatures-frame-mixin %)
(class* % ()
(inherit get-current-tab)
(inherit register-capability-menu-item get-language-menu)
(define/private (signatures-menu-init)
(let ([language-menu (get-language-menu)]
[enable-label (string-constant signature-enable-checks)]
[disable-label (string-constant signature-disable-checks)])
(make-object separator-menu-item% language-menu)
(register-capability-menu-item 'signatures:signatures-menu language-menu)
(letrec ([enable-menu-item%
(class menu:can-restore-menu-item%
(define enabled? #t)
(define/public (is-signature-checking-enabled?) enabled?)
(define/public (set-signature-checking-enabled?! e) (set! enabled? e))
(inherit set-label)
(define/public (enable-signature-checking)
(unless enabled?
(set! enabled? #t)
(set-label disable-label)
(preferences:set 'signatures:enable-checking? '#t)))
(define/public (disable-signature-checking)
(when enabled?
(set! enabled? #f)
(set-label enable-label)
(preferences:set 'signatures:enable-checking? '#f)))
(super-instantiate ()))]
[enable? (preferences:get 'signatures:enable-checking?)]
[enable-menu-item (make-object enable-menu-item%
(if enable? disable-label enable-label)
language-menu
(lambda (_1 _2)
(if (send _1 is-signature-checking-enabled?)
(send _1 disable-signature-checking)
(send _1 enable-signature-checking))) #f)])
(send enable-menu-item set-signature-checking-enabled?! enable?)
(register-capability-menu-item 'signatures:signatures-menu language-menu))))
(unless (drracket:language:capability-registered? 'signatures:signatures-menu)
(drracket:language:register-capability 'signatures:signatures-menu (flat-contract boolean?) #f))
(super-instantiate ())
(signatures-menu-init)
))
(drracket:get/extend:extend-unit-frame signatures-frame-mixin)
))
| null | https://raw.githubusercontent.com/racket/deinprogramm/e9fb68455641ae7d409ddb48f5e584c9d014ef4f/deinprogramm-signature/deinprogramm/signature/tool.rkt | racket | #lang racket/base
(require racket/file racket/class racket/unit racket/contract
drracket/tool
mred framework
string-constants)
(provide tool@)
(preferences:set-default 'signatures:enable-checking? #t boolean?)
(define tool@
(unit (import drracket:tool^) (export drracket:tool-exports^)
(define (phase1) (void))
(define (phase2) (void))
(define (signatures-frame-mixin %)
(class* % ()
(inherit get-current-tab)
(inherit register-capability-menu-item get-language-menu)
(define/private (signatures-menu-init)
(let ([language-menu (get-language-menu)]
[enable-label (string-constant signature-enable-checks)]
[disable-label (string-constant signature-disable-checks)])
(make-object separator-menu-item% language-menu)
(register-capability-menu-item 'signatures:signatures-menu language-menu)
(letrec ([enable-menu-item%
(class menu:can-restore-menu-item%
(define enabled? #t)
(define/public (is-signature-checking-enabled?) enabled?)
(define/public (set-signature-checking-enabled?! e) (set! enabled? e))
(inherit set-label)
(define/public (enable-signature-checking)
(unless enabled?
(set! enabled? #t)
(set-label disable-label)
(preferences:set 'signatures:enable-checking? '#t)))
(define/public (disable-signature-checking)
(when enabled?
(set! enabled? #f)
(set-label enable-label)
(preferences:set 'signatures:enable-checking? '#f)))
(super-instantiate ()))]
[enable? (preferences:get 'signatures:enable-checking?)]
[enable-menu-item (make-object enable-menu-item%
(if enable? disable-label enable-label)
language-menu
(lambda (_1 _2)
(if (send _1 is-signature-checking-enabled?)
(send _1 disable-signature-checking)
(send _1 enable-signature-checking))) #f)])
(send enable-menu-item set-signature-checking-enabled?! enable?)
(register-capability-menu-item 'signatures:signatures-menu language-menu))))
(unless (drracket:language:capability-registered? 'signatures:signatures-menu)
(drracket:language:register-capability 'signatures:signatures-menu (flat-contract boolean?) #f))
(super-instantiate ())
(signatures-menu-init)
))
(drracket:get/extend:extend-unit-frame signatures-frame-mixin)
))
| |
d13c5ad697c8b7ec761a1448616dd39bb28a978a9df40067aaf7b56cc4b6cf58 | facebook/pyre-check | abstractSimpleDomain.mli |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
module type ELEMENT = sig
type t
val name : string
val bottom : t
val join : t -> t -> t
val meet : t -> t -> t
val less_or_equal : left:t -> right:t -> bool
val show : t -> string
end
module Make (Element : ELEMENT) : sig
include AbstractDomainCore.S with type t = Element.t
end
| null | https://raw.githubusercontent.com/facebook/pyre-check/10c375bea52db5d10b71cb5206fac7da9549eb0c/source/domains/abstractSimpleDomain.mli | ocaml |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
module type ELEMENT = sig
type t
val name : string
val bottom : t
val join : t -> t -> t
val meet : t -> t -> t
val less_or_equal : left:t -> right:t -> bool
val show : t -> string
end
module Make (Element : ELEMENT) : sig
include AbstractDomainCore.S with type t = Element.t
end
| |
273e586749e09dbbfcbc74add1f086690e559167ec588665f34038b2521252a0 | bobzhang/fan | ast_plc.ml |
(* e.g. parent/2 *)
type pred = (string * int)
module Pred =struct
type t = pred
let compare : t -> t -> int = compare
end
module PredMap = Map.Make(Pred)
(* terms are integers, (anonymous) variables and compound (possibly atoms) *)
type term =
| Integer of int * Locf.t
| Var of string * Locf.t
| Anon of Locf.t
| Comp of string * term list * Locf.t
e.g. for sibling/2 : ( X , Y ) : - parent(Z , X ) , parent(Z , Y ) .
type rule =
(term list * term list * Locf.t)
e.g. + X or -Y
type arg_mask =
| ArgOpen of Locf.t
| ArgClosed of Locf.t
| ArgAny of Locf.t
(* e.g. for same/2: +X, ?Y *)
type mask = ( arg_mask list * Locf.t)
Complete program : map from pred to rule list + mask list
type prog = (rule list * mask list) PredMap.t
let rec statics_of_terms (acc : int Mapf.String.t) (terms : term list) : int Mapf.String.t =
List.fold_left (fun comps -> fun
| Comp (c,ts,_) ->
let comps =
let n = List.length ts in
try
let n' = Mapf.String.find c comps in
if n = n' then comps
else failwith ("Contradictory arities for " ^ c)
with Not_found -> Mapf.String.add c n comps
in
statics_of_terms comps ts
| _ -> comps ) acc terms
let rec statics_of_goal_terms acc terms =
List.fold_left (fun comps -> fun
| Comp ("is",[t;_],_loc) -> statics_of_terms comps [t]
| Comp ("eq",[_;_],_loc) | Comp ("ne",[_;_],_loc)
| Comp ("lt",[_;_],_loc) | Comp ("lte",[_;_],_loc)
| Comp ("gt",[_;_],_loc) | Comp ("gte",[_;_],_loc) -> comps
| Comp ("not",([_t] as ts),_loc) -> statics_of_goal_terms comps ts
| Comp (_c,ts,_) ->
(* same and diff, cut, true and fail, etc. will also match here *)
statics_of_terms comps ts
| _ -> comps) acc terms
let statics (prog : prog) : (int Mapf.String.t) =
PredMap.fold (fun _pred (rules,_) acc ->
List.fold_left (fun acc (terms,goals,_) ->
statics_of_goal_terms (statics_of_terms acc terms) goals) acc rules) prog Mapf.String.empty
| null | https://raw.githubusercontent.com/bobzhang/fan/7ed527d96c5a006da43d3813f32ad8a5baa31b7f/src/thirdparty/plc/ast_plc.ml | ocaml | e.g. parent/2
terms are integers, (anonymous) variables and compound (possibly atoms)
e.g. for same/2: +X, ?Y
same and diff, cut, true and fail, etc. will also match here |
type pred = (string * int)
module Pred =struct
type t = pred
let compare : t -> t -> int = compare
end
module PredMap = Map.Make(Pred)
type term =
| Integer of int * Locf.t
| Var of string * Locf.t
| Anon of Locf.t
| Comp of string * term list * Locf.t
e.g. for sibling/2 : ( X , Y ) : - parent(Z , X ) , parent(Z , Y ) .
type rule =
(term list * term list * Locf.t)
e.g. + X or -Y
type arg_mask =
| ArgOpen of Locf.t
| ArgClosed of Locf.t
| ArgAny of Locf.t
type mask = ( arg_mask list * Locf.t)
Complete program : map from pred to rule list + mask list
type prog = (rule list * mask list) PredMap.t
let rec statics_of_terms (acc : int Mapf.String.t) (terms : term list) : int Mapf.String.t =
List.fold_left (fun comps -> fun
| Comp (c,ts,_) ->
let comps =
let n = List.length ts in
try
let n' = Mapf.String.find c comps in
if n = n' then comps
else failwith ("Contradictory arities for " ^ c)
with Not_found -> Mapf.String.add c n comps
in
statics_of_terms comps ts
| _ -> comps ) acc terms
let rec statics_of_goal_terms acc terms =
List.fold_left (fun comps -> fun
| Comp ("is",[t;_],_loc) -> statics_of_terms comps [t]
| Comp ("eq",[_;_],_loc) | Comp ("ne",[_;_],_loc)
| Comp ("lt",[_;_],_loc) | Comp ("lte",[_;_],_loc)
| Comp ("gt",[_;_],_loc) | Comp ("gte",[_;_],_loc) -> comps
| Comp ("not",([_t] as ts),_loc) -> statics_of_goal_terms comps ts
| Comp (_c,ts,_) ->
statics_of_terms comps ts
| _ -> comps) acc terms
let statics (prog : prog) : (int Mapf.String.t) =
PredMap.fold (fun _pred (rules,_) acc ->
List.fold_left (fun acc (terms,goals,_) ->
statics_of_goal_terms (statics_of_terms acc terms) goals) acc rules) prog Mapf.String.empty
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.