_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
|
---|---|---|---|---|---|---|---|---|
3797dbbf4605609edd786e33399d70fe7fdb749a66e252d2461c7eec1693e78d
|
metosin/spec-tools
|
spec.cljc
|
(ns spec-tools.spec
(:refer-clojure :exclude [any? some? number? pos? neg? integer? int? pos-int? neg-int? nat-int?
float? double? boolean? string? ident? simple-ident? qualified-ident?
keyword? simple-keyword? qualified-keyword? symbol? simple-symbol?
qualified-symbol? uuid? uri? decimal? inst? seqable? indexed?
map? vector? list? seq? char? set? nil? false? true? zero?
rational? coll? empty? associative? sequential? ratio? bytes?
#?@(:cljs [Inst Keyword UUID])])
(:require [spec-tools.core :as st]))
(def any? (st/spec clojure.core/any?))
(def some? (st/spec clojure.core/some?))
(def number? (st/spec clojure.core/number?))
(def pos? (st/spec clojure.core/pos?))
(def neg? (st/spec clojure.core/neg?))
(def integer? (st/spec clojure.core/integer?))
(def int? (st/spec clojure.core/int?))
(def pos-int? (st/spec clojure.core/pos-int?))
(def neg-int? (st/spec clojure.core/neg-int?))
(def nat-int? (st/spec clojure.core/nat-int?))
(def float? (st/spec clojure.core/float?))
(def double? (st/spec clojure.core/double?))
(def boolean? (st/spec clojure.core/boolean?))
(def string? (st/spec clojure.core/string?))
(def ident? (st/spec clojure.core/ident?))
(def simple-ident? (st/spec clojure.core/simple-ident?))
(def qualified-ident? (st/spec clojure.core/qualified-ident?))
(def keyword? (st/spec clojure.core/keyword?))
(def simple-keyword? (st/spec clojure.core/simple-keyword?))
(def qualified-keyword? (st/spec clojure.core/qualified-keyword?))
(def symbol? (st/spec clojure.core/symbol?))
(def simple-symbol? (st/spec clojure.core/simple-symbol?))
(def qualified-symbol? (st/spec clojure.core/qualified-symbol?))
(def uuid? (st/spec clojure.core/uuid?))
#?(:clj (def uri? (st/spec clojure.core/uri?)))
#?(:clj (def decimal? (st/spec clojure.core/decimal?)))
(def inst? (st/spec clojure.core/inst?))
(def seqable? (st/spec clojure.core/seqable?))
(def indexed? (st/spec clojure.core/indexed?))
(def map? (st/spec clojure.core/map?))
(def vector? (st/spec clojure.core/vector?))
(def list? (st/spec clojure.core/list?))
(def seq? (st/spec clojure.core/seq?))
(def char? (st/spec clojure.core/char?))
(def set? (st/spec clojure.core/set?))
(def nil? (st/spec clojure.core/nil?))
(def false? (st/spec clojure.core/false?))
(def true? (st/spec clojure.core/true?))
(def zero? (st/spec clojure.core/zero?))
#?(:clj (def rational? (st/spec clojure.core/rational?)))
(def coll? (st/spec clojure.core/coll?))
(def empty? (st/spec clojure.core/empty?))
(def associative? (st/spec clojure.core/associative?))
(def sequential? (st/spec clojure.core/sequential?))
#?(:clj (def ratio? (st/spec clojure.core/ratio?)))
#?(:clj (def bytes? (st/spec clojure.core/bytes?)))
| null |
https://raw.githubusercontent.com/metosin/spec-tools/d05e6e3c76c3c6ff847aa3f8e66344df2705aeae/src/spec_tools/spec.cljc
|
clojure
|
(ns spec-tools.spec
(:refer-clojure :exclude [any? some? number? pos? neg? integer? int? pos-int? neg-int? nat-int?
float? double? boolean? string? ident? simple-ident? qualified-ident?
keyword? simple-keyword? qualified-keyword? symbol? simple-symbol?
qualified-symbol? uuid? uri? decimal? inst? seqable? indexed?
map? vector? list? seq? char? set? nil? false? true? zero?
rational? coll? empty? associative? sequential? ratio? bytes?
#?@(:cljs [Inst Keyword UUID])])
(:require [spec-tools.core :as st]))
(def any? (st/spec clojure.core/any?))
(def some? (st/spec clojure.core/some?))
(def number? (st/spec clojure.core/number?))
(def pos? (st/spec clojure.core/pos?))
(def neg? (st/spec clojure.core/neg?))
(def integer? (st/spec clojure.core/integer?))
(def int? (st/spec clojure.core/int?))
(def pos-int? (st/spec clojure.core/pos-int?))
(def neg-int? (st/spec clojure.core/neg-int?))
(def nat-int? (st/spec clojure.core/nat-int?))
(def float? (st/spec clojure.core/float?))
(def double? (st/spec clojure.core/double?))
(def boolean? (st/spec clojure.core/boolean?))
(def string? (st/spec clojure.core/string?))
(def ident? (st/spec clojure.core/ident?))
(def simple-ident? (st/spec clojure.core/simple-ident?))
(def qualified-ident? (st/spec clojure.core/qualified-ident?))
(def keyword? (st/spec clojure.core/keyword?))
(def simple-keyword? (st/spec clojure.core/simple-keyword?))
(def qualified-keyword? (st/spec clojure.core/qualified-keyword?))
(def symbol? (st/spec clojure.core/symbol?))
(def simple-symbol? (st/spec clojure.core/simple-symbol?))
(def qualified-symbol? (st/spec clojure.core/qualified-symbol?))
(def uuid? (st/spec clojure.core/uuid?))
#?(:clj (def uri? (st/spec clojure.core/uri?)))
#?(:clj (def decimal? (st/spec clojure.core/decimal?)))
(def inst? (st/spec clojure.core/inst?))
(def seqable? (st/spec clojure.core/seqable?))
(def indexed? (st/spec clojure.core/indexed?))
(def map? (st/spec clojure.core/map?))
(def vector? (st/spec clojure.core/vector?))
(def list? (st/spec clojure.core/list?))
(def seq? (st/spec clojure.core/seq?))
(def char? (st/spec clojure.core/char?))
(def set? (st/spec clojure.core/set?))
(def nil? (st/spec clojure.core/nil?))
(def false? (st/spec clojure.core/false?))
(def true? (st/spec clojure.core/true?))
(def zero? (st/spec clojure.core/zero?))
#?(:clj (def rational? (st/spec clojure.core/rational?)))
(def coll? (st/spec clojure.core/coll?))
(def empty? (st/spec clojure.core/empty?))
(def associative? (st/spec clojure.core/associative?))
(def sequential? (st/spec clojure.core/sequential?))
#?(:clj (def ratio? (st/spec clojure.core/ratio?)))
#?(:clj (def bytes? (st/spec clojure.core/bytes?)))
|
|
ba066e8e8d8cf8aea3bb17644ae8d573aa491e1382f7e055a63beaf381726d22
|
gsakkas/rite
|
3401.ml
|
let rec sepConcat sep sl =
match sl with
| [] -> ""
| h::t ->
let f a x = a ^ (sep ^ x) in
let base = h in let l = t in List.fold_left f base l;;
let stringOfList f l = "[" ^ (sepConcat ^ (";" ^ ((List.map f l) ^ "]")));;
fix
let rec sepConcat sep sl =
match sl with
| [ ] - > " "
| h::t - >
let f a x = a ^ ( sep ^ x ) in
let base = h in let l = t in List.fold_left f base l ; ;
let stringOfList f l = " [ " ^ ( ( sepConcat " ; " ( List.map f l ) ) ^ " ] " ) ; ;
let rec sepConcat sep sl =
match sl with
| [] -> ""
| h::t ->
let f a x = a ^ (sep ^ x) in
let base = h in let l = t in List.fold_left f base l;;
let stringOfList f l = "[" ^ ((sepConcat ";" (List.map f l)) ^ "]");;
*)
changed spans
( 9,31)-(9,40 )
sepConcat " ; " ( List.map f l )
AppG [ LitG , AppG [ EmptyG , EmptyG ] ]
( 9,43)-(9,73 )
" ] "
LitG
(9,31)-(9,40)
sepConcat ";" (List.map f l)
AppG [LitG,AppG [EmptyG,EmptyG]]
(9,43)-(9,73)
"]"
LitG
*)
type error slice
( 2,4)-(7,61 )
( 2,19)-(7,59 )
( 9,30)-(9,74 )
( 9,31)-(9,40 )
( 9,41)-(9,42 )
( 9,50)-(9,72 )
( 9,51)-(9,65 )
( 9,52)-(9,60 )
( 9,66)-(9,67 )
(2,4)-(7,61)
(2,19)-(7,59)
(9,30)-(9,74)
(9,31)-(9,40)
(9,41)-(9,42)
(9,50)-(9,72)
(9,51)-(9,65)
(9,52)-(9,60)
(9,66)-(9,67)
*)
| null |
https://raw.githubusercontent.com/gsakkas/rite/958a0ad2460e15734447bc07bd181f5d35956d3b/data/sp14/3401.ml
|
ocaml
|
let rec sepConcat sep sl =
match sl with
| [] -> ""
| h::t ->
let f a x = a ^ (sep ^ x) in
let base = h in let l = t in List.fold_left f base l;;
let stringOfList f l = "[" ^ (sepConcat ^ (";" ^ ((List.map f l) ^ "]")));;
fix
let rec sepConcat sep sl =
match sl with
| [ ] - > " "
| h::t - >
let f a x = a ^ ( sep ^ x ) in
let base = h in let l = t in List.fold_left f base l ; ;
let stringOfList f l = " [ " ^ ( ( sepConcat " ; " ( List.map f l ) ) ^ " ] " ) ; ;
let rec sepConcat sep sl =
match sl with
| [] -> ""
| h::t ->
let f a x = a ^ (sep ^ x) in
let base = h in let l = t in List.fold_left f base l;;
let stringOfList f l = "[" ^ ((sepConcat ";" (List.map f l)) ^ "]");;
*)
changed spans
( 9,31)-(9,40 )
sepConcat " ; " ( List.map f l )
AppG [ LitG , AppG [ EmptyG , EmptyG ] ]
( 9,43)-(9,73 )
" ] "
LitG
(9,31)-(9,40)
sepConcat ";" (List.map f l)
AppG [LitG,AppG [EmptyG,EmptyG]]
(9,43)-(9,73)
"]"
LitG
*)
type error slice
( 2,4)-(7,61 )
( 2,19)-(7,59 )
( 9,30)-(9,74 )
( 9,31)-(9,40 )
( 9,41)-(9,42 )
( 9,50)-(9,72 )
( 9,51)-(9,65 )
( 9,52)-(9,60 )
( 9,66)-(9,67 )
(2,4)-(7,61)
(2,19)-(7,59)
(9,30)-(9,74)
(9,31)-(9,40)
(9,41)-(9,42)
(9,50)-(9,72)
(9,51)-(9,65)
(9,52)-(9,60)
(9,66)-(9,67)
*)
|
|
6f05bd81057f68145057562bcdf2f97c847c21e5179c77d97f61a121e698b3f6
|
gedge-platform/gedge-platform
|
vhost.erl
|
This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
%%
Copyright ( c ) 2018 - 2021 VMware , Inc. or its affiliates . All rights reserved .
%%
-module(vhost).
-include_lib("rabbit_common/include/rabbit.hrl").
-include("vhost.hrl").
-export([
new/2,
new/3,
fields/0,
fields/1,
info_keys/0,
record_version_to_use/0,
upgrade/1,
upgrade_to/2,
pattern_match_all/0,
get_name/1,
get_limits/1,
get_metadata/1,
get_description/1,
get_tags/1,
set_limits/2,
set_metadata/2
]).
-define(record_version, vhost_v2).
-type(name() :: binary()).
-type(metadata_key() :: atom()).
-type(metadata() :: #{description => binary(),
tags => [atom()],
metadata_key() => any()} | undefined).
-type vhost() :: vhost_v1:vhost_v1() | vhost_v2().
-record(vhost, {
%% name as a binary
virtual_host :: name() | '_',
%% proplist of limits configured, if any
limits :: list() | '_',
metadata :: metadata() | '_'
}).
-type vhost_v2() :: #vhost{
virtual_host :: name(),
limits :: list(),
metadata :: metadata()
}.
-type vhost_pattern() :: vhost_v1:vhost_v1_pattern() |
vhost_v2_pattern().
-type vhost_v2_pattern() :: #vhost{
virtual_host :: name() | '_',
limits :: '_',
metadata :: '_'
}.
-export_type([name/0,
metadata_key/0,
metadata/0,
vhost/0,
vhost_v2/0,
vhost_pattern/0,
vhost_v2_pattern/0]).
-spec new(name(), list()) -> vhost().
new(Name, Limits) ->
case record_version_to_use() of
?record_version ->
#vhost{virtual_host = Name, limits = Limits};
_ ->
vhost_v1:new(Name, Limits)
end.
-spec new(name(), list(), map()) -> vhost().
new(Name, Limits, Metadata) ->
case record_version_to_use() of
?record_version ->
#vhost{virtual_host = Name, limits = Limits, metadata = Metadata};
_ ->
vhost_v1:new(Name, Limits)
end.
-spec record_version_to_use() -> vhost_v1 | vhost_v2.
record_version_to_use() ->
case rabbit_feature_flags:is_enabled(virtual_host_metadata) of
true -> ?record_version;
false -> vhost_v1:record_version_to_use()
end.
-spec upgrade(vhost()) -> vhost().
upgrade(#vhost{} = VHost) -> VHost;
upgrade(OldVHost) -> upgrade_to(record_version_to_use(), OldVHost).
-spec upgrade_to
(vhost_v2, vhost()) -> vhost_v2();
(vhost_v1, vhost_v1:vhost_v1()) -> vhost_v1:vhost_v1().
upgrade_to(?record_version, #vhost{} = VHost) ->
VHost;
upgrade_to(?record_version, OldVHost) ->
Fields = erlang:tuple_to_list(OldVHost) ++ [#{description => <<"">>, tags => []}],
#vhost{} = erlang:list_to_tuple(Fields);
upgrade_to(Version, OldVHost) ->
vhost_v1:upgrade_to(Version, OldVHost).
fields() ->
case record_version_to_use() of
?record_version -> fields(?record_version);
_ -> vhost_v1:fields()
end.
fields(?record_version) -> record_info(fields, vhost);
fields(Version) -> vhost_v1:fields(Version).
info_keys() ->
case record_version_to_use() of
%% note: this reports description and tags separately even though
they are stored in the metadata map . MK .
?record_version -> [name, description, tags, metadata, tracing, cluster_state];
_ -> vhost_v1:info_keys()
end.
-spec pattern_match_all() -> vhost_pattern().
pattern_match_all() ->
case record_version_to_use() of
?record_version -> #vhost{_ = '_'};
_ -> vhost_v1:pattern_match_all()
end.
-spec get_name(vhost()) -> name().
get_name(#vhost{virtual_host = Value}) -> Value;
get_name(VHost) -> vhost_v1:get_name(VHost).
-spec get_limits(vhost()) -> list().
get_limits(#vhost{limits = Value}) -> Value;
get_limits(VHost) -> vhost_v1:get_limits(VHost).
-spec get_metadata(vhost()) -> metadata().
get_metadata(#vhost{metadata = Value}) -> Value;
get_metadata(VHost) -> vhost_v1:get_metadata(VHost).
-spec get_description(vhost()) -> binary().
get_description(#vhost{} = VHost) ->
maps:get(description, get_metadata(VHost), undefined);
get_description(VHost) ->
vhost_v1:get_description(VHost).
-spec get_tags(vhost()) -> [atom()].
get_tags(#vhost{} = VHost) ->
maps:get(tags, get_metadata(VHost), undefined);
get_tags(VHost) ->
vhost_v1:get_tags(VHost).
set_limits(VHost, Value) ->
case record_version_to_use() of
?record_version ->
VHost#vhost{limits = Value};
_ ->
vhost_v1:set_limits(VHost, Value)
end.
set_metadata(VHost, Value) ->
case record_version_to_use() of
?record_version ->
VHost#vhost{metadata = Value};
_ ->
%% the field is not available, so this is a no-op
VHost
end.
| null |
https://raw.githubusercontent.com/gedge-platform/gedge-platform/97c1e87faf28ba2942a77196b6be0a952bff1c3e/gs-broker/broker-server/deps/rabbit/src/vhost.erl
|
erlang
|
name as a binary
proplist of limits configured, if any
note: this reports description and tags separately even though
the field is not available, so this is a no-op
|
This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
Copyright ( c ) 2018 - 2021 VMware , Inc. or its affiliates . All rights reserved .
-module(vhost).
-include_lib("rabbit_common/include/rabbit.hrl").
-include("vhost.hrl").
-export([
new/2,
new/3,
fields/0,
fields/1,
info_keys/0,
record_version_to_use/0,
upgrade/1,
upgrade_to/2,
pattern_match_all/0,
get_name/1,
get_limits/1,
get_metadata/1,
get_description/1,
get_tags/1,
set_limits/2,
set_metadata/2
]).
-define(record_version, vhost_v2).
-type(name() :: binary()).
-type(metadata_key() :: atom()).
-type(metadata() :: #{description => binary(),
tags => [atom()],
metadata_key() => any()} | undefined).
-type vhost() :: vhost_v1:vhost_v1() | vhost_v2().
-record(vhost, {
virtual_host :: name() | '_',
limits :: list() | '_',
metadata :: metadata() | '_'
}).
-type vhost_v2() :: #vhost{
virtual_host :: name(),
limits :: list(),
metadata :: metadata()
}.
-type vhost_pattern() :: vhost_v1:vhost_v1_pattern() |
vhost_v2_pattern().
-type vhost_v2_pattern() :: #vhost{
virtual_host :: name() | '_',
limits :: '_',
metadata :: '_'
}.
-export_type([name/0,
metadata_key/0,
metadata/0,
vhost/0,
vhost_v2/0,
vhost_pattern/0,
vhost_v2_pattern/0]).
-spec new(name(), list()) -> vhost().
new(Name, Limits) ->
case record_version_to_use() of
?record_version ->
#vhost{virtual_host = Name, limits = Limits};
_ ->
vhost_v1:new(Name, Limits)
end.
-spec new(name(), list(), map()) -> vhost().
new(Name, Limits, Metadata) ->
case record_version_to_use() of
?record_version ->
#vhost{virtual_host = Name, limits = Limits, metadata = Metadata};
_ ->
vhost_v1:new(Name, Limits)
end.
-spec record_version_to_use() -> vhost_v1 | vhost_v2.
record_version_to_use() ->
case rabbit_feature_flags:is_enabled(virtual_host_metadata) of
true -> ?record_version;
false -> vhost_v1:record_version_to_use()
end.
-spec upgrade(vhost()) -> vhost().
upgrade(#vhost{} = VHost) -> VHost;
upgrade(OldVHost) -> upgrade_to(record_version_to_use(), OldVHost).
-spec upgrade_to
(vhost_v2, vhost()) -> vhost_v2();
(vhost_v1, vhost_v1:vhost_v1()) -> vhost_v1:vhost_v1().
upgrade_to(?record_version, #vhost{} = VHost) ->
VHost;
upgrade_to(?record_version, OldVHost) ->
Fields = erlang:tuple_to_list(OldVHost) ++ [#{description => <<"">>, tags => []}],
#vhost{} = erlang:list_to_tuple(Fields);
upgrade_to(Version, OldVHost) ->
vhost_v1:upgrade_to(Version, OldVHost).
fields() ->
case record_version_to_use() of
?record_version -> fields(?record_version);
_ -> vhost_v1:fields()
end.
fields(?record_version) -> record_info(fields, vhost);
fields(Version) -> vhost_v1:fields(Version).
info_keys() ->
case record_version_to_use() of
they are stored in the metadata map . MK .
?record_version -> [name, description, tags, metadata, tracing, cluster_state];
_ -> vhost_v1:info_keys()
end.
-spec pattern_match_all() -> vhost_pattern().
pattern_match_all() ->
case record_version_to_use() of
?record_version -> #vhost{_ = '_'};
_ -> vhost_v1:pattern_match_all()
end.
-spec get_name(vhost()) -> name().
get_name(#vhost{virtual_host = Value}) -> Value;
get_name(VHost) -> vhost_v1:get_name(VHost).
-spec get_limits(vhost()) -> list().
get_limits(#vhost{limits = Value}) -> Value;
get_limits(VHost) -> vhost_v1:get_limits(VHost).
-spec get_metadata(vhost()) -> metadata().
get_metadata(#vhost{metadata = Value}) -> Value;
get_metadata(VHost) -> vhost_v1:get_metadata(VHost).
-spec get_description(vhost()) -> binary().
get_description(#vhost{} = VHost) ->
maps:get(description, get_metadata(VHost), undefined);
get_description(VHost) ->
vhost_v1:get_description(VHost).
-spec get_tags(vhost()) -> [atom()].
get_tags(#vhost{} = VHost) ->
maps:get(tags, get_metadata(VHost), undefined);
get_tags(VHost) ->
vhost_v1:get_tags(VHost).
set_limits(VHost, Value) ->
case record_version_to_use() of
?record_version ->
VHost#vhost{limits = Value};
_ ->
vhost_v1:set_limits(VHost, Value)
end.
set_metadata(VHost, Value) ->
case record_version_to_use() of
?record_version ->
VHost#vhost{metadata = Value};
_ ->
VHost
end.
|
cbe53e08e64717e0a5939ba2445f70f5388caeb342ca5454b210e12c651a962c
|
nasa/pvslib
|
patch-20210301.lisp
|
;; There was a off-by-one error in the nondestructive update macro.
(defmacro nd-rec-tup-update (rec fieldnum newval)
`(let ((val ,newval)
(newrec (copy-seq ,rec)))
no need to and rec
newrec)) ;;since fieldnum is a fixed number
(defmethod pvs2cl-update-nd-type* ((type recordtype) expr arg1 restargs
assign-expr bindings livevars)
(let* ((id (id (car arg1)))
(fields (sort-fields (fields type)))
(field-num (position id fields :test #'(lambda (x y) (eq x (id y)))))
(cl-expr-var (gentemp "E"))
(new-expr `(svref ,cl-expr-var ,field-num))
(field-type (type (find id fields :key #'id) ))
(dep-fields (sort-fields (fields type) t));;dependent sort
(new-bindings (pvs2cl-add-dep-field-bindings dep-fields fields id
cl-expr-var bindings))
(newval (pvs2cl-update-nd-type field-type new-expr
restargs assign-expr new-bindings
livevars)))
`(let ((,cl-expr-var ,expr))
(nd-rec-tup-update ,expr ,field-num ,newval))))
(defmethod pvs2cl-update-nd-type* ((type tupletype) expr arg1 restargs
assign-expr bindings livevars)
(let* ((num (number (if (consp arg1) (car arg1) arg1)))
(new-expr `(svref ,expr ,(1- num)))
(pos (1- num))
(tupsel-type (nth pos (types type)))
(newval (pvs2cl-update-nd-type tupsel-type new-expr
restargs assign-expr bindings
livevars)))
`(nd-rec-tup-update ,expr ,pos ,newval)))
| null |
https://raw.githubusercontent.com/nasa/pvslib/2be465b36f4d884c33cbd49a37939c4664db74eb/pvs-patches/patch-20210301.lisp
|
lisp
|
There was a off-by-one error in the nondestructive update macro.
since fieldnum is a fixed number
dependent sort
|
(defmacro nd-rec-tup-update (rec fieldnum newval)
`(let ((val ,newval)
(newrec (copy-seq ,rec)))
no need to and rec
(defmethod pvs2cl-update-nd-type* ((type recordtype) expr arg1 restargs
assign-expr bindings livevars)
(let* ((id (id (car arg1)))
(fields (sort-fields (fields type)))
(field-num (position id fields :test #'(lambda (x y) (eq x (id y)))))
(cl-expr-var (gentemp "E"))
(new-expr `(svref ,cl-expr-var ,field-num))
(field-type (type (find id fields :key #'id) ))
(new-bindings (pvs2cl-add-dep-field-bindings dep-fields fields id
cl-expr-var bindings))
(newval (pvs2cl-update-nd-type field-type new-expr
restargs assign-expr new-bindings
livevars)))
`(let ((,cl-expr-var ,expr))
(nd-rec-tup-update ,expr ,field-num ,newval))))
(defmethod pvs2cl-update-nd-type* ((type tupletype) expr arg1 restargs
assign-expr bindings livevars)
(let* ((num (number (if (consp arg1) (car arg1) arg1)))
(new-expr `(svref ,expr ,(1- num)))
(pos (1- num))
(tupsel-type (nth pos (types type)))
(newval (pvs2cl-update-nd-type tupsel-type new-expr
restargs assign-expr bindings
livevars)))
`(nd-rec-tup-update ,expr ,pos ,newval)))
|
8309b87b7249ee466629554fa17ed7c80eef36d42abbe5f02c75b6d6ab58dbdc
|
foretspaisibles/lemonade-sqlite
|
lemonade_Sqlite.mli
|
Lemonade_sqlite -- Monadic interface for sqlite
( -sqlite )
This file is part of Lemonade Sqlite
Copyright © 2016
This file must be used under the terms of the CeCILL - B.
This source file is licensed as described in the file COPYING , which
you should have received as part of this distribution . The terms
are also available at
-B_V1-en.txt
Lemonade Sqlite (-sqlite)
This file is part of Lemonade Sqlite
Copyright © 2016 Michael Grünewald
This file must be used under the terms of the CeCILL-B.
This source file is licensed as described in the file COPYING, which
you should have received as part of this distribution. The terms
are also available at
-B_V1-en.txt *)
* Monadic interface to SQlite3 .
This monad is a composition of a [ Success ] monad holding computations
that can fail and of a [ Reader ] monad for computations reading a
database handle and some caching information .
This monad is a composition of a [Success] monad holding computations
that can fail and of a [Reader] monad for computations reading a
database handle and some caching information. *)
* { 6 The Sqlite Monad }
include Lemonade_Type.S
* { 6 Operations in the success monad }
type error = string * string
(** The type of sqlite errors. *)
(** The outcome of computations throwing errors. *)
type (+'a) outcome =
| Success of 'a
| Error of error
val run : 'a t -> 'a outcome
(** Reveal the outcome of a computation with errors. *)
val error : error -> 'a t
(** Fail with the given error. *)
val recover : 'a t -> (error -> 'a t) -> 'a t
(** [recover m handler] is a monad containing the same value as [m]
and thrown errors are interepreted by the [handler]. *)
type handle
(** The type of database handle. *)
* { 6 The Stream Monad }
module S : Lemonade_Stream.S
with type 'a monad = 'a t
val opendb : ?init:string -> string -> handle
* Open a handle to a database .
If [ init ] is provided , this sql statement is used to initialise
the database , in case the database does not already exist .
If [init] is provided, this sql statement is used to initialise
the database, in case the database does not already exist. *)
val closedb : handle -> unit
(** Close a handle to a database. *)
val withdb : ?init:string -> string -> (handle -> 'a) -> 'a
* [ f ] safely applies [ f ] on a handle opened on
the given database .
If [ init ] is provided , this sql statement is used to initialise
the database , in case the database does not already exist .
the given database.
If [init] is provided, this sql statement is used to initialise
the database, in case the database does not already exist. *)
* { 6 Database related types }
type row = data array
(** The type of database rows returned by queries. *)
(** The type of data held by our database. *)
and data = Sqlite3.Data.t =
| NONE
| NULL
| INT of int64
| FLOAT of float
| TEXT of string
| BLOB of string
type statement
(** The abstract type of SQL statements. *)
type binding = (string * data) list
(** The type of variable binding definitions. These can be applied
to statements or used with a query. *)
val query : statement -> handle -> row S.t
(** [query statement] is the stream of rows returned by the
[statement]. *)
val one : row S.t -> row t
* [ one rows ] convert a stream of rows into one row . It will
return an [ Error ] if the input stream has not exactly one row .
return an [Error] if the input stream has not exactly one row. *)
val maybe : row S.t -> row option t
* [ maybe rows ] convert a stream of rows into one or zero rows .
It will return an [ Error ] if the input stream has more than one row .
It will return an [Error] if the input stream has more than one row. *)
val project : ('a -> 'b * 'c ) -> 'a S.t -> ('b * 'c list) S.t
* [ project p stream ] construct a stream by applying the projector
[ p ] on stream items , to extract a base and a fibre value . Consecutive
fibre values above a given [ base ] are bundled together .
[p] on stream items, to extract a base and a fibre value. Consecutive
fibre values above a given [base] are bundled together. *)
val exec : statement -> handle -> unit t
(** [exec commmand] is a monad applying the statements provided by
[command] and ignoring produced rows if any. *)
val insert : statement S.t -> handle -> unit t
(** [insert commmands] is a monad applying the statements provided by
[commands] and ignoring produced rows if any. *)
(** {6 Statements} *)
val statement : string -> statement
(** [statement sql] return the statement corresponding to [sql].
Complex statements are supported. *)
val rowid_binding : int64 ref -> ('a -> data)
(** Make a function returning the given rowid in the form of sqlite data. *)
* { 6 Bindings }
val binding_apply : ?rowid:int64 ref -> statement -> binding -> statement
* [ binding_apply stmt binding ] create a statement by
using the bindings provided by [ binding ] on [ stmt ] .
If the argument [ rowid ] is given , the statement generated by the
binding arrange so that the [ rowid ] is updated with the
[ last_insert_rowid ] value after execution of the statement .
using the bindings provided by [binding] on [stmt].
If the argument [rowid] is given, the statement generated by the
binding arrange so that the [rowid] is updated with the
[last_insert_rowid] value after execution of the statement. *)
val bindings: (string * ('a -> data)) list -> 'a S.t -> binding S.t
(** [bindings spec data] turn a binding specification and data stream into
a binding stream. The specification is made of pairs [(name, get)] which
identify which variable to bind and which data to bind it to. *)
val bindings_apply : ?rowid:int64 ref -> binding S.t -> statement -> statement S.t
(** [bindings_apply bindings stmt] create a statement stream by
repetitively using the bindings provided by [bindings] on [stmt].
If the argument [rowid] is given, the statements generated by the
binding arrange so that the [rowid] is updated with the
[last_insert_rowid] value after execution of the statement. *)
* { 6 Pretty printing }
These pretty - printers are to be used when debugging .
These pretty-printers are to be used when debugging. *)
val pp_print_data : Format.formatter -> data -> unit
(** Pretty printer for sqlite data. *)
val pp_print_row : Format.formatter -> row -> unit
(** Pretty printer for sqlite data rows. *)
val pp_print_statement : Format.formatter -> statement -> unit
(** Pretty printer for statements. *)
val pp_print_handle : Format.formatter -> handle -> unit
(** Pretty printer for database handles. *)
| null |
https://raw.githubusercontent.com/foretspaisibles/lemonade-sqlite/a1fcdf49afc3d902ddd7f0d58ef1fdc894f92965/src/lemonade_Sqlite.mli
|
ocaml
|
* The type of sqlite errors.
* The outcome of computations throwing errors.
* Reveal the outcome of a computation with errors.
* Fail with the given error.
* [recover m handler] is a monad containing the same value as [m]
and thrown errors are interepreted by the [handler].
* The type of database handle.
* Close a handle to a database.
* The type of database rows returned by queries.
* The type of data held by our database.
* The abstract type of SQL statements.
* The type of variable binding definitions. These can be applied
to statements or used with a query.
* [query statement] is the stream of rows returned by the
[statement].
* [exec commmand] is a monad applying the statements provided by
[command] and ignoring produced rows if any.
* [insert commmands] is a monad applying the statements provided by
[commands] and ignoring produced rows if any.
* {6 Statements}
* [statement sql] return the statement corresponding to [sql].
Complex statements are supported.
* Make a function returning the given rowid in the form of sqlite data.
* [bindings spec data] turn a binding specification and data stream into
a binding stream. The specification is made of pairs [(name, get)] which
identify which variable to bind and which data to bind it to.
* [bindings_apply bindings stmt] create a statement stream by
repetitively using the bindings provided by [bindings] on [stmt].
If the argument [rowid] is given, the statements generated by the
binding arrange so that the [rowid] is updated with the
[last_insert_rowid] value after execution of the statement.
* Pretty printer for sqlite data.
* Pretty printer for sqlite data rows.
* Pretty printer for statements.
* Pretty printer for database handles.
|
Lemonade_sqlite -- Monadic interface for sqlite
( -sqlite )
This file is part of Lemonade Sqlite
Copyright © 2016
This file must be used under the terms of the CeCILL - B.
This source file is licensed as described in the file COPYING , which
you should have received as part of this distribution . The terms
are also available at
-B_V1-en.txt
Lemonade Sqlite (-sqlite)
This file is part of Lemonade Sqlite
Copyright © 2016 Michael Grünewald
This file must be used under the terms of the CeCILL-B.
This source file is licensed as described in the file COPYING, which
you should have received as part of this distribution. The terms
are also available at
-B_V1-en.txt *)
* Monadic interface to SQlite3 .
This monad is a composition of a [ Success ] monad holding computations
that can fail and of a [ Reader ] monad for computations reading a
database handle and some caching information .
This monad is a composition of a [Success] monad holding computations
that can fail and of a [Reader] monad for computations reading a
database handle and some caching information. *)
* { 6 The Sqlite Monad }
include Lemonade_Type.S
* { 6 Operations in the success monad }
type error = string * string
type (+'a) outcome =
| Success of 'a
| Error of error
val run : 'a t -> 'a outcome
val error : error -> 'a t
val recover : 'a t -> (error -> 'a t) -> 'a t
type handle
* { 6 The Stream Monad }
module S : Lemonade_Stream.S
with type 'a monad = 'a t
val opendb : ?init:string -> string -> handle
* Open a handle to a database .
If [ init ] is provided , this sql statement is used to initialise
the database , in case the database does not already exist .
If [init] is provided, this sql statement is used to initialise
the database, in case the database does not already exist. *)
val closedb : handle -> unit
val withdb : ?init:string -> string -> (handle -> 'a) -> 'a
* [ f ] safely applies [ f ] on a handle opened on
the given database .
If [ init ] is provided , this sql statement is used to initialise
the database , in case the database does not already exist .
the given database.
If [init] is provided, this sql statement is used to initialise
the database, in case the database does not already exist. *)
* { 6 Database related types }
type row = data array
and data = Sqlite3.Data.t =
| NONE
| NULL
| INT of int64
| FLOAT of float
| TEXT of string
| BLOB of string
type statement
type binding = (string * data) list
val query : statement -> handle -> row S.t
val one : row S.t -> row t
* [ one rows ] convert a stream of rows into one row . It will
return an [ Error ] if the input stream has not exactly one row .
return an [Error] if the input stream has not exactly one row. *)
val maybe : row S.t -> row option t
* [ maybe rows ] convert a stream of rows into one or zero rows .
It will return an [ Error ] if the input stream has more than one row .
It will return an [Error] if the input stream has more than one row. *)
val project : ('a -> 'b * 'c ) -> 'a S.t -> ('b * 'c list) S.t
* [ project p stream ] construct a stream by applying the projector
[ p ] on stream items , to extract a base and a fibre value . Consecutive
fibre values above a given [ base ] are bundled together .
[p] on stream items, to extract a base and a fibre value. Consecutive
fibre values above a given [base] are bundled together. *)
val exec : statement -> handle -> unit t
val insert : statement S.t -> handle -> unit t
val statement : string -> statement
val rowid_binding : int64 ref -> ('a -> data)
* { 6 Bindings }
val binding_apply : ?rowid:int64 ref -> statement -> binding -> statement
* [ binding_apply stmt binding ] create a statement by
using the bindings provided by [ binding ] on [ stmt ] .
If the argument [ rowid ] is given , the statement generated by the
binding arrange so that the [ rowid ] is updated with the
[ last_insert_rowid ] value after execution of the statement .
using the bindings provided by [binding] on [stmt].
If the argument [rowid] is given, the statement generated by the
binding arrange so that the [rowid] is updated with the
[last_insert_rowid] value after execution of the statement. *)
val bindings: (string * ('a -> data)) list -> 'a S.t -> binding S.t
val bindings_apply : ?rowid:int64 ref -> binding S.t -> statement -> statement S.t
* { 6 Pretty printing }
These pretty - printers are to be used when debugging .
These pretty-printers are to be used when debugging. *)
val pp_print_data : Format.formatter -> data -> unit
val pp_print_row : Format.formatter -> row -> unit
val pp_print_statement : Format.formatter -> statement -> unit
val pp_print_handle : Format.formatter -> handle -> unit
|
e328f5d9e1c567ee7a6653018ee2e1dae378557758b5e7a2e105b66c1e3881bc
|
weiliang1503/XZZ-racket
|
help.rkt
|
#lang racket
(require "../lib.rkt")
(define (help type ids msg)
(send-msg type (car ids)
(string-append "妾身可以为您提供以下服务:\n"
"1. help 查看此列表\n"
"2. hello 跟女仆酱打声招乎\n"
"3. echo [内容] 让女仆重复你的话\n"
"4. five new 新开一局五子棋\n"
"**请在所有命令前都加上maid!**"
)))
(provide help)
| null |
https://raw.githubusercontent.com/weiliang1503/XZZ-racket/eee9dc45a4a39aefbec2dfb542fdfdb12ed2bac1/plugins/help.rkt
|
racket
|
#lang racket
(require "../lib.rkt")
(define (help type ids msg)
(send-msg type (car ids)
(string-append "妾身可以为您提供以下服务:\n"
"1. help 查看此列表\n"
"2. hello 跟女仆酱打声招乎\n"
"3. echo [内容] 让女仆重复你的话\n"
"4. five new 新开一局五子棋\n"
"**请在所有命令前都加上maid!**"
)))
(provide help)
|
|
3fd0ae460d0620984bf84aa0231daf49e81f6a4a567c2a7bb974820e35c7c7b0
|
Kakadu/fp2022
|
parser.ml
|
* Copyright 2021 - 2022 , Kakadu and contributors
* SPDX - License - Identifier : LGPL-3.0 - or - later
(* TODO: implement parser here *)
open Angstrom
open Caml.Format
open Ast
let is_whitespace = function
| '\x20' | '\x0a' | '\x0d' | '\x09' -> true
| _ -> false
;;
let is_digit = function
| '0' .. '9' -> true
| _ -> false
;;
let integer = take_while1 is_digit
module FloatNumParser = struct
let sign =
peek_char
>>= function
| Some '-' -> advance 1 >>| fun () -> "-"
| Some '+' -> advance 1 >>| fun () -> "+"
| Some c when is_digit c -> return "+"
| _ -> fail "Sign or digit expected"
;;
let number =
sign
>>= fun sign ->
take_while1 is_digit
<* char '.'
>>= fun whole ->
take_while1 is_digit >>= fun part -> return (sign ^ whole ^ "." ^ part)
;;
end
module OCamlParser = struct
open Base
let keywords_list = [ "let"; "in"; "rec"; "if"; "then"; "else"; "match"; "with" ]
let is_keyword id = List.exists ~f:(fun s -> String.equal s id) keywords_list
let token_separator = take_while is_whitespace
let is_letter = function
| 'a' .. 'z' -> true
| 'A' .. 'Z' -> true
| _ -> false
;;
let is_digit = function
| '0' .. '9' -> true
| _ -> false
;;
let space = take_while is_whitespace
let space1 = take_while1 is_whitespace
let token s = space *> string s
(* CHANGED!!!!!! *)
module Literals = struct
let int_token =
space *> take_while1 is_digit
>>= fun res -> return @@ Exp_literal (Int (int_of_string res))
;;
let float_token =
space *> FloatNumParser.number
>>= fun res -> return @@ Exp_literal (Float (float_of_string res))
;;
let string_token =
space *> char '"' *> take_while (fun c -> not (Char.equal c '"'))
<* char '"'
>>= fun res -> return @@ Exp_literal (String res)
;;
end
module BinOperators = struct
let ar_operators =
choice
[ token "+."
; token "-."
; token "*."
; token "/."
; token "+"
; token "-"
; token "/"
; token "*"
]
;;
end
let new_ident =
space *> take_while1 is_letter
>>= fun str ->
if is_keyword str then fail "Keyword in the wrong place of program" else return str
;;
let int_number = take_while1 is_digit >>= fun s -> return @@ int_of_string s
let rec link_exps e_list =
match e_list with
| e :: [] -> e
| h :: t -> Exp_seq (h, link_exps t)
| _ -> failwith "empty list"
;;
let let_binding_constructor name arg_list body =
match arg_list with
| [] -> Exp_letbinding (name, body)
| _ ->
printf "Size: %i" (List.length arg_list);
List.iter ~f:(printf "\n%s \n") arg_list;
failwith "error!!!!"
;;
let rec fun_constructor name args body =
match args with
| [ a ] -> Exp_fun (name, a, body)
| h :: t -> Exp_fun (name, h, fun_constructor name t body)
| _ -> let_binding_constructor name args body
;;
let literals =
choice [ Literals.float_token; Literals.int_token; Literals.string_token ]
;;
let arithm_parser =
let c = choice [ (new_ident >>= fun res -> return @@ Exp_ident res); literals ] in
lift3
(fun arg1 operator arg2 -> Exp_apply (operator, [ arg1; arg2 ]))
(space *> c <* space)
BinOperators.ar_operators
(space *> c <* space)
;;
let arg_of_application =
choice [ (new_ident >>= fun res -> return @@ Exp_ident res); literals ]
;;
let appl =
lift2
(fun id li -> Exp_apply (id, li))
new_ident
(many1 (space1 *> arg_of_application) <* space)
;;
let decl =
lift3
(fun name args body -> let_binding_constructor name args body)
(token "let" *> space1 *> new_ident)
(many (space1 *> new_ident))
(space *> token "=" *> space *> choice [ arithm_parser; literals; appl ]
<* space
<* token "in")
;;
let base =
choice
[ arithm_parser; decl; appl; (new_ident >>= fun res -> return @@ Exp_ident res) ]
;;
let fun_body =
many (base <* char '\n' <|> base <* space1 <|> base)
>>= fun res -> return @@ link_exps res
;;
let hl_fun_decl =
lift3
(fun a b c -> fun_constructor a b c)
(token "let" *> space1 *> new_ident)
(many1 (space1 *> new_ident))
(space *> token "=" *> space *> fun_body <* space <* string ";;" <* space)
;;
let p = choice [ arithm_parser; hl_fun_decl; appl ]
end
module Printer = struct
open Base
let print_let = function
| name, Int i -> printf "Name: %s; Val: %i\n" name i
| name, Float i -> printf "Name: %s; Val: %f\n" name i
| name, String i -> printf "Name: %s; Val: %s\n" name i
;;
let print_literal = function
| Int i -> printf "(Int: %i)" i
| Float f -> printf "(Float: %f)" f
| String s -> printf "(String: %s)" s
;;
let rec print_ast = function
| Exp_letbinding (id, value) ->
printf "(LetB: Name=%s value=" id;
print_ast value;
printf ")"
| Exp_literal l -> print_literal l
| Exp_ident i -> printf "(Ident: %s)" i
| Exp_fun (name, arg, e) ->
printf "(Fun: name=%s arg=%s" name arg;
print_ast e;
printf ")"
| Exp_seq (e1, e2) ->
printf "Seq (";
print_ast e1;
print_ast e2;
printf ")"
| Exp_apply (name, arg_list) ->
printf "(Apply: name=%s Args:" name;
List.iter ~f:print_ast arg_list;
printf ")"
| _ -> printf "Unrecognised Ast Node"
;;
end
let parse_exp code =
let result = Angstrom.parse_string OCamlParser.p ~consume:Angstrom.Consume.All code in
result
;;
let print_result = function
| Result.Ok res -> Printer.print_ast res
| Result.Error s -> printf "SOMETHING WENT WRONG: %s\n" s
;;
(*
let () =
parse_exp "let c s = concat s \"asdf\";;" |> print_result
;;*)
let p2 = parse_exp "1 + 2"
let%test _ =
p2 = Result.Ok (Exp_apply ("+", [ Exp_literal (Int 1); Exp_literal (Int 2) ]))
;;
let p2 = parse_exp "a + 2"
let%test _ = p2 = Result.Ok (Exp_apply ("+", [ Exp_ident "a"; Exp_literal (Int 2) ]))
let p2 = parse_exp "abc - asdf "
let%test _ = p2 = Result.Ok (Exp_apply ("-", [ Exp_ident "abc"; Exp_ident "asdf" ]))
let p2 = parse_exp "1.5 +. 2.3"
let%test _ =
p2 = Result.Ok (Exp_apply ("+.", [ Exp_literal (Float 1.5); Exp_literal (Float 2.3) ]))
;;
let p2 = parse_exp "let incr x = x + 1;;"
let%test _ =
p2
= Result.Ok
(Exp_fun ("incr", "x", Exp_apply ("+", [ Exp_ident "x"; Exp_literal (Int 1) ])))
;;
let p2 = parse_exp "let c s = concat s \"ml\";;"
let%test _ =
p2
= Result.Ok
(Exp_fun
("c", "s", Exp_apply ("concat", [ Exp_ident "s"; Exp_literal (String "ml") ])))
;;
let p2 = parse_exp "c \"asdf\""
let%test _ = p2 = Result.Ok (Exp_apply ("c", [ Exp_literal (String "asdf") ]))
let p2 = parse_exp "let f q w = let res = w + q in res;;"
let%test _ =
p2
= Result.Ok
(Exp_fun
( "f"
, "q"
, Exp_fun
( "f"
, "w"
, Exp_seq
( Exp_letbinding
("res", Exp_apply ("+", [ Exp_ident "w"; Exp_ident "q" ]))
, Exp_ident "res" ) ) ))
;;
let p2 = parse_exp ""
let%test _ = true
| null |
https://raw.githubusercontent.com/Kakadu/fp2022/58d6ba7a63f656e7f753219102108aac7a147a25/OCaml-with-variants/lib/parser.ml
|
ocaml
|
TODO: implement parser here
CHANGED!!!!!!
let () =
parse_exp "let c s = concat s \"asdf\";;" |> print_result
;;
|
* Copyright 2021 - 2022 , Kakadu and contributors
* SPDX - License - Identifier : LGPL-3.0 - or - later
open Angstrom
open Caml.Format
open Ast
let is_whitespace = function
| '\x20' | '\x0a' | '\x0d' | '\x09' -> true
| _ -> false
;;
let is_digit = function
| '0' .. '9' -> true
| _ -> false
;;
let integer = take_while1 is_digit
module FloatNumParser = struct
let sign =
peek_char
>>= function
| Some '-' -> advance 1 >>| fun () -> "-"
| Some '+' -> advance 1 >>| fun () -> "+"
| Some c when is_digit c -> return "+"
| _ -> fail "Sign or digit expected"
;;
let number =
sign
>>= fun sign ->
take_while1 is_digit
<* char '.'
>>= fun whole ->
take_while1 is_digit >>= fun part -> return (sign ^ whole ^ "." ^ part)
;;
end
module OCamlParser = struct
open Base
let keywords_list = [ "let"; "in"; "rec"; "if"; "then"; "else"; "match"; "with" ]
let is_keyword id = List.exists ~f:(fun s -> String.equal s id) keywords_list
let token_separator = take_while is_whitespace
let is_letter = function
| 'a' .. 'z' -> true
| 'A' .. 'Z' -> true
| _ -> false
;;
let is_digit = function
| '0' .. '9' -> true
| _ -> false
;;
let space = take_while is_whitespace
let space1 = take_while1 is_whitespace
let token s = space *> string s
module Literals = struct
let int_token =
space *> take_while1 is_digit
>>= fun res -> return @@ Exp_literal (Int (int_of_string res))
;;
let float_token =
space *> FloatNumParser.number
>>= fun res -> return @@ Exp_literal (Float (float_of_string res))
;;
let string_token =
space *> char '"' *> take_while (fun c -> not (Char.equal c '"'))
<* char '"'
>>= fun res -> return @@ Exp_literal (String res)
;;
end
module BinOperators = struct
let ar_operators =
choice
[ token "+."
; token "-."
; token "*."
; token "/."
; token "+"
; token "-"
; token "/"
; token "*"
]
;;
end
let new_ident =
space *> take_while1 is_letter
>>= fun str ->
if is_keyword str then fail "Keyword in the wrong place of program" else return str
;;
let int_number = take_while1 is_digit >>= fun s -> return @@ int_of_string s
let rec link_exps e_list =
match e_list with
| e :: [] -> e
| h :: t -> Exp_seq (h, link_exps t)
| _ -> failwith "empty list"
;;
let let_binding_constructor name arg_list body =
match arg_list with
| [] -> Exp_letbinding (name, body)
| _ ->
printf "Size: %i" (List.length arg_list);
List.iter ~f:(printf "\n%s \n") arg_list;
failwith "error!!!!"
;;
let rec fun_constructor name args body =
match args with
| [ a ] -> Exp_fun (name, a, body)
| h :: t -> Exp_fun (name, h, fun_constructor name t body)
| _ -> let_binding_constructor name args body
;;
let literals =
choice [ Literals.float_token; Literals.int_token; Literals.string_token ]
;;
let arithm_parser =
let c = choice [ (new_ident >>= fun res -> return @@ Exp_ident res); literals ] in
lift3
(fun arg1 operator arg2 -> Exp_apply (operator, [ arg1; arg2 ]))
(space *> c <* space)
BinOperators.ar_operators
(space *> c <* space)
;;
let arg_of_application =
choice [ (new_ident >>= fun res -> return @@ Exp_ident res); literals ]
;;
let appl =
lift2
(fun id li -> Exp_apply (id, li))
new_ident
(many1 (space1 *> arg_of_application) <* space)
;;
let decl =
lift3
(fun name args body -> let_binding_constructor name args body)
(token "let" *> space1 *> new_ident)
(many (space1 *> new_ident))
(space *> token "=" *> space *> choice [ arithm_parser; literals; appl ]
<* space
<* token "in")
;;
let base =
choice
[ arithm_parser; decl; appl; (new_ident >>= fun res -> return @@ Exp_ident res) ]
;;
let fun_body =
many (base <* char '\n' <|> base <* space1 <|> base)
>>= fun res -> return @@ link_exps res
;;
let hl_fun_decl =
lift3
(fun a b c -> fun_constructor a b c)
(token "let" *> space1 *> new_ident)
(many1 (space1 *> new_ident))
(space *> token "=" *> space *> fun_body <* space <* string ";;" <* space)
;;
let p = choice [ arithm_parser; hl_fun_decl; appl ]
end
module Printer = struct
open Base
let print_let = function
| name, Int i -> printf "Name: %s; Val: %i\n" name i
| name, Float i -> printf "Name: %s; Val: %f\n" name i
| name, String i -> printf "Name: %s; Val: %s\n" name i
;;
let print_literal = function
| Int i -> printf "(Int: %i)" i
| Float f -> printf "(Float: %f)" f
| String s -> printf "(String: %s)" s
;;
let rec print_ast = function
| Exp_letbinding (id, value) ->
printf "(LetB: Name=%s value=" id;
print_ast value;
printf ")"
| Exp_literal l -> print_literal l
| Exp_ident i -> printf "(Ident: %s)" i
| Exp_fun (name, arg, e) ->
printf "(Fun: name=%s arg=%s" name arg;
print_ast e;
printf ")"
| Exp_seq (e1, e2) ->
printf "Seq (";
print_ast e1;
print_ast e2;
printf ")"
| Exp_apply (name, arg_list) ->
printf "(Apply: name=%s Args:" name;
List.iter ~f:print_ast arg_list;
printf ")"
| _ -> printf "Unrecognised Ast Node"
;;
end
let parse_exp code =
let result = Angstrom.parse_string OCamlParser.p ~consume:Angstrom.Consume.All code in
result
;;
let print_result = function
| Result.Ok res -> Printer.print_ast res
| Result.Error s -> printf "SOMETHING WENT WRONG: %s\n" s
;;
let p2 = parse_exp "1 + 2"
let%test _ =
p2 = Result.Ok (Exp_apply ("+", [ Exp_literal (Int 1); Exp_literal (Int 2) ]))
;;
let p2 = parse_exp "a + 2"
let%test _ = p2 = Result.Ok (Exp_apply ("+", [ Exp_ident "a"; Exp_literal (Int 2) ]))
let p2 = parse_exp "abc - asdf "
let%test _ = p2 = Result.Ok (Exp_apply ("-", [ Exp_ident "abc"; Exp_ident "asdf" ]))
let p2 = parse_exp "1.5 +. 2.3"
let%test _ =
p2 = Result.Ok (Exp_apply ("+.", [ Exp_literal (Float 1.5); Exp_literal (Float 2.3) ]))
;;
let p2 = parse_exp "let incr x = x + 1;;"
let%test _ =
p2
= Result.Ok
(Exp_fun ("incr", "x", Exp_apply ("+", [ Exp_ident "x"; Exp_literal (Int 1) ])))
;;
let p2 = parse_exp "let c s = concat s \"ml\";;"
let%test _ =
p2
= Result.Ok
(Exp_fun
("c", "s", Exp_apply ("concat", [ Exp_ident "s"; Exp_literal (String "ml") ])))
;;
let p2 = parse_exp "c \"asdf\""
let%test _ = p2 = Result.Ok (Exp_apply ("c", [ Exp_literal (String "asdf") ]))
let p2 = parse_exp "let f q w = let res = w + q in res;;"
let%test _ =
p2
= Result.Ok
(Exp_fun
( "f"
, "q"
, Exp_fun
( "f"
, "w"
, Exp_seq
( Exp_letbinding
("res", Exp_apply ("+", [ Exp_ident "w"; Exp_ident "q" ]))
, Exp_ident "res" ) ) ))
;;
let p2 = parse_exp ""
let%test _ = true
|
35987b9a99461c4de138f261fa8f87bed2c80636a8c61fc0717adf8cbe109276
|
mfikes/fifth-postulate
|
ns314.cljs
|
(ns fifth-postulate.ns314)
(defn solve-for01 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for02 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for03 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for04 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for05 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for06 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for07 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for08 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for09 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for10 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for11 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for12 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for13 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for14 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for15 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for16 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for17 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for18 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for19 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
| null |
https://raw.githubusercontent.com/mfikes/fifth-postulate/22cfd5f8c2b4a2dead1c15a96295bfeb4dba235e/src/fifth_postulate/ns314.cljs
|
clojure
|
(ns fifth-postulate.ns314)
(defn solve-for01 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for02 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for03 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for04 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for05 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for06 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for07 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for08 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for09 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for10 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for11 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for12 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for13 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for14 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for15 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for16 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for17 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for18 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for19 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
|
|
6ecda3137a9d462a8990b00ba6ecb1f6ae04a649a4ccb1d08bbf8acdadb4c689
|
kupl/FixML
|
sub6.ml
|
type formula=
|True
|False
|Not of formula
|AndAlso of formula*formula
|OrElse of formula*formula
|Imply of formula*formula
|Equal of exp*exp
and exp=
|Num of int
|Plus of exp*exp
|Minus of exp*exp
let rec trans:exp->exp
=fun e1-> match e1 with
|Plus(Num(a),Num(b))->Num(a+b)
|Plus(Num(a),e3)->Plus(Num(a),trans(e3))
|Plus(e2,Num(b))->Plus(trans(e2),Num(b))
|Plus(e2,e3)->Plus(trans(e2),trans(e3))
|Minus(Num(a),Num(b))->Num(a-b)
|Minus(Num(a),e3)->Minus(Num(a),trans(e3))
|Minus(e2,Num(b))->Minus(trans(e2),Num(b))
|Minus(e2,e3)->Minus(trans(e2),trans(e3))
|Num a->Num a
let rec eval:formula->bool
=fun f->match f with
|True->true
|False->false
|Not f1->if f1=True then false else true
|AndAlso (f1,f2)->if (f1=True && f2=True) then true else false
|OrElse (f1,f2)->if (f1=False && f2=False) then false else true
|Imply (f1,f2)->if (f1=True && f2=False) then false else true
|Equal (e1,e2)-> if (trans(e1)=trans(e2)) then true else false;;
| null |
https://raw.githubusercontent.com/kupl/FixML/0a032a733d68cd8ccc8b1034d2908cd43b241fce/benchmarks/formula/formula1/submissions/sub6.ml
|
ocaml
|
type formula=
|True
|False
|Not of formula
|AndAlso of formula*formula
|OrElse of formula*formula
|Imply of formula*formula
|Equal of exp*exp
and exp=
|Num of int
|Plus of exp*exp
|Minus of exp*exp
let rec trans:exp->exp
=fun e1-> match e1 with
|Plus(Num(a),Num(b))->Num(a+b)
|Plus(Num(a),e3)->Plus(Num(a),trans(e3))
|Plus(e2,Num(b))->Plus(trans(e2),Num(b))
|Plus(e2,e3)->Plus(trans(e2),trans(e3))
|Minus(Num(a),Num(b))->Num(a-b)
|Minus(Num(a),e3)->Minus(Num(a),trans(e3))
|Minus(e2,Num(b))->Minus(trans(e2),Num(b))
|Minus(e2,e3)->Minus(trans(e2),trans(e3))
|Num a->Num a
let rec eval:formula->bool
=fun f->match f with
|True->true
|False->false
|Not f1->if f1=True then false else true
|AndAlso (f1,f2)->if (f1=True && f2=True) then true else false
|OrElse (f1,f2)->if (f1=False && f2=False) then false else true
|Imply (f1,f2)->if (f1=True && f2=False) then false else true
|Equal (e1,e2)-> if (trans(e1)=trans(e2)) then true else false;;
|
|
6e9a3e797ab3b0ee38e306a3b085204b91198c88d97fa1b860898071e18f20a0
|
Relph1119/sicp-solutions-manual
|
p1-32-iter-accumulate.scm
|
(define (accumulate combiner null-value term a next b)
(define (iter a result)
(if (> a b)
result
(iter (next a)
(combiner result (term a)))))
(iter a null-value))
| null |
https://raw.githubusercontent.com/Relph1119/sicp-solutions-manual/f2ff309a6c898376209c198030c70d6adfac1fc1/src/practices/ch01/p1-32-iter-accumulate.scm
|
scheme
|
(define (accumulate combiner null-value term a next b)
(define (iter a result)
(if (> a b)
result
(iter (next a)
(combiner result (term a)))))
(iter a null-value))
|
|
596a4ef3104cadb4270206bf7af3b8ff2837c83dd898daefa04584666803f0e1
|
carld/compiler-tutorial
|
tests-1.1-req.scm
|
(add-tests-with-string-output "integers"
[0 => "0\n"]
[1 => "1\n"]
[-1 => "-1\n"]
[10 => "10\n"]
[-10 => "-10\n"]
[2736 => "2736\n"]
[-2736 => "-2736\n"]
[536870911 => "536870911\n"]
[-536870912 => "-536870912\n"]
)
| null |
https://raw.githubusercontent.com/carld/compiler-tutorial/4b5d275336cadcccd8e4d4752c0646d655402b1f/tests-1.1-req.scm
|
scheme
|
(add-tests-with-string-output "integers"
[0 => "0\n"]
[1 => "1\n"]
[-1 => "-1\n"]
[10 => "10\n"]
[-10 => "-10\n"]
[2736 => "2736\n"]
[-2736 => "-2736\n"]
[536870911 => "536870911\n"]
[-536870912 => "-536870912\n"]
)
|
|
de2bef0d8697db431530df5d76fb47ef97418af16111c3993e6c4e2b36683116
|
malcolmreynolds/GSLL
|
ode.lisp
|
Regression test ODE for GSLL , automatically generated
(in-package :gsl)
(LISP-UNIT:DEFINE-TEST ODE
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 495 1.0d0 -1.4568657425802234d0 -11.547345633897558d0)
(MULTIPLE-VALUE-LIST (INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-RK2+ NIL)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 40 1.0d0 -1.4568569264026898d0 -11.547449151779395d0)
(MULTIPLE-VALUE-LIST (INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-RK4+ NIL)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 35 1.0d0 -1.456874342553472d0 -11.547250693698407d0)
(MULTIPLE-VALUE-LIST
(INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-RKF45+ NIL)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 27 1.0d0 -1.4568588825970334d0 -11.547432342449643d0)
(MULTIPLE-VALUE-LIST
(INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-RKCK+ NIL)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 16 1.0d0 -1.4568622636249005d0 -11.547385179410822d0)
(MULTIPLE-VALUE-LIST
(INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-RK8PD+ NIL)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 359 1.0d0 -1.4569507371916566d0 -11.546406519788615d0)
(MULTIPLE-VALUE-LIST
(INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-RK2IMP+ NIL)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 40 1.0d0 -1.4568644436344684d0 -11.547361181933427d0)
(MULTIPLE-VALUE-LIST
(INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-RK4IMP+ NIL)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 9 1.0d0 -1.4568620806209944d0 -11.547387321938151d0)
(MULTIPLE-VALUE-LIST
(INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-BSIMP+ NIL)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 11176 1.0d0 -1.459959741392502d0 -11.510866371379606d0)
(MULTIPLE-VALUE-LIST
(LET ((*MAX-ITER* 12000))
(INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-GEAR1+ NIL))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 52 1.0d0 -1.4568645170220367d0 -11.54736019525012d0)
(MULTIPLE-VALUE-LIST
(INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-GEAR2+ NIL))))
| null |
https://raw.githubusercontent.com/malcolmreynolds/GSLL/2f722f12f1d08e1b9550a46e2a22adba8e1e52c4/tests/ode.lisp
|
lisp
|
Regression test ODE for GSLL , automatically generated
(in-package :gsl)
(LISP-UNIT:DEFINE-TEST ODE
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 495 1.0d0 -1.4568657425802234d0 -11.547345633897558d0)
(MULTIPLE-VALUE-LIST (INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-RK2+ NIL)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 40 1.0d0 -1.4568569264026898d0 -11.547449151779395d0)
(MULTIPLE-VALUE-LIST (INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-RK4+ NIL)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 35 1.0d0 -1.456874342553472d0 -11.547250693698407d0)
(MULTIPLE-VALUE-LIST
(INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-RKF45+ NIL)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 27 1.0d0 -1.4568588825970334d0 -11.547432342449643d0)
(MULTIPLE-VALUE-LIST
(INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-RKCK+ NIL)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 16 1.0d0 -1.4568622636249005d0 -11.547385179410822d0)
(MULTIPLE-VALUE-LIST
(INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-RK8PD+ NIL)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 359 1.0d0 -1.4569507371916566d0 -11.546406519788615d0)
(MULTIPLE-VALUE-LIST
(INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-RK2IMP+ NIL)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 40 1.0d0 -1.4568644436344684d0 -11.547361181933427d0)
(MULTIPLE-VALUE-LIST
(INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-RK4IMP+ NIL)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 9 1.0d0 -1.4568620806209944d0 -11.547387321938151d0)
(MULTIPLE-VALUE-LIST
(INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-BSIMP+ NIL)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 11176 1.0d0 -1.459959741392502d0 -11.510866371379606d0)
(MULTIPLE-VALUE-LIST
(LET ((*MAX-ITER* 12000))
(INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-GEAR1+ NIL))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 52 1.0d0 -1.4568645170220367d0 -11.54736019525012d0)
(MULTIPLE-VALUE-LIST
(INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-GEAR2+ NIL))))
|
|
e324806ada1b97fdd1a5d4320caeeb0c78635f22f62bb06b104671a059c07e52
|
threatgrid/naga-store
|
store_structs.cljc
|
(ns naga.schema.store-structs
#?(:cljs (:refer-clojure :exclude [Var]))
(:require #?(:clj [schema.core :as s]
:cljs [schema.core :as s :include-macros true])))
;; single element in a rule
(def EntityPropertyElt
(s/cond-pre s/Keyword s/Symbol #?(:clj Long :cljs s/Num)))
;; simple pattern containing a single element. e.g. [?v]
(def EntityPattern [(s/one s/Symbol "entity")])
two or three element pattern .
;; e.g. [?s :property]
;; [:my/id ?property ?value]
(def EntityPropertyPattern
[(s/one EntityPropertyElt "entity")
(s/one EntityPropertyElt "property")
(s/optional s/Any "value")])
The full pattern definition , with 1 , 2 or 3 elements
(def EPVPattern
(s/if #(= 1 (count %))
EntityPattern
EntityPropertyPattern))
Less restrictive than EPVPattern , because this is called at runtime
(s/defn epv-pattern? :- s/Bool
[pattern :- [s/Any]]
(and (vector? pattern)
(let [f (first pattern)]
(and (boolean f) (not (seq? f))))))
(def Var (s/constrained s/Symbol (comp #{\? \%} first name)))
(s/defn vartest? :- s/Bool
[x]
(and (symbol? x) (boolean (#{\? \%} (first (name x))))))
(s/defn vars :- [s/Symbol]
"Return a seq of all variables in a pattern"
[pattern :- EPVPattern]
(filter vartest? pattern))
(defn list-like? [x] (and (sequential? x) (not (vector? x))))
(s/defn filter-pattern? :- s/Bool
[pattern :- [s/Any]]
(and (vector? pattern) (list-like? (first pattern)) (nil? (second pattern))))
(defn eval-pattern?
"eval bindings take the form of [expression var] where the
expression is a list-based s-expression. It binds the var
to the result of the expression."
[p]
(and (vector? p) (= 2 (count p))
(let [[e v] p]
(and (vartest? v) (sequential? e) (not (vector? e))))))
(def operators ['and 'AND 'or 'not 'OR 'NOT])
(s/defn op-pattern? :- s/Bool
[[op :as pattern] :- [s/Any]]
(and (list-like? pattern) (boolean (some (partial = op) operators))))
(def Operators (apply s/enum operators))
(defn unnested-list?
[[fl :as l]]
(and (vector? l) (list-like? fl) (not-any? list-like? fl)))
;; filters are a vector with an executable list destined for eval
(def FilterPattern (s/constrained [(s/one [s/Any] "Predicate")]
unnested-list?))
(def EvalPattern (s/constrained [(s/one [s/Any] "Expression")
(s/one Var "Binding var")]
unnested-list?))
(declare Pattern)
(def OpPattern (s/constrained [(s/one Operators "operator")
(s/one (s/recursive #'Pattern) "first pattern")
(s/recursive #'Pattern)]
list-like?))
(def Pattern (s/if list-like? OpPattern
(s/if (comp list-like? first)
(s/if (comp nil? second) FilterPattern EvalPattern)
EPVPattern)))
(def Value (s/pred (complement symbol?) "Value"))
(def Results [[Value]])
(def EntityPropAxiomElt
(s/cond-pre s/Keyword #?(:clj Long :cljs s/Num)))
(def EntityPropValAxiomElt
(s/conditional (complement symbol?) s/Any))
(def Triple
[(s/one s/Any "entity")
(s/one s/Any "property")
(s/one s/Any "value")])
(def Axiom
[(s/one EntityPropAxiomElt "entity")
(s/one EntityPropAxiomElt "property")
(s/one EntityPropValAxiomElt "value")])
| null |
https://raw.githubusercontent.com/threatgrid/naga-store/73ceae3692bff1124d0dddaa3bbf6da7b2ab62e4/src/naga/schema/store_structs.cljc
|
clojure
|
single element in a rule
simple pattern containing a single element. e.g. [?v]
e.g. [?s :property]
[:my/id ?property ?value]
filters are a vector with an executable list destined for eval
|
(ns naga.schema.store-structs
#?(:cljs (:refer-clojure :exclude [Var]))
(:require #?(:clj [schema.core :as s]
:cljs [schema.core :as s :include-macros true])))
(def EntityPropertyElt
(s/cond-pre s/Keyword s/Symbol #?(:clj Long :cljs s/Num)))
(def EntityPattern [(s/one s/Symbol "entity")])
two or three element pattern .
(def EntityPropertyPattern
[(s/one EntityPropertyElt "entity")
(s/one EntityPropertyElt "property")
(s/optional s/Any "value")])
The full pattern definition , with 1 , 2 or 3 elements
(def EPVPattern
(s/if #(= 1 (count %))
EntityPattern
EntityPropertyPattern))
Less restrictive than EPVPattern , because this is called at runtime
(s/defn epv-pattern? :- s/Bool
[pattern :- [s/Any]]
(and (vector? pattern)
(let [f (first pattern)]
(and (boolean f) (not (seq? f))))))
(def Var (s/constrained s/Symbol (comp #{\? \%} first name)))
(s/defn vartest? :- s/Bool
[x]
(and (symbol? x) (boolean (#{\? \%} (first (name x))))))
(s/defn vars :- [s/Symbol]
"Return a seq of all variables in a pattern"
[pattern :- EPVPattern]
(filter vartest? pattern))
(defn list-like? [x] (and (sequential? x) (not (vector? x))))
(s/defn filter-pattern? :- s/Bool
[pattern :- [s/Any]]
(and (vector? pattern) (list-like? (first pattern)) (nil? (second pattern))))
(defn eval-pattern?
"eval bindings take the form of [expression var] where the
expression is a list-based s-expression. It binds the var
to the result of the expression."
[p]
(and (vector? p) (= 2 (count p))
(let [[e v] p]
(and (vartest? v) (sequential? e) (not (vector? e))))))
(def operators ['and 'AND 'or 'not 'OR 'NOT])
(s/defn op-pattern? :- s/Bool
[[op :as pattern] :- [s/Any]]
(and (list-like? pattern) (boolean (some (partial = op) operators))))
(def Operators (apply s/enum operators))
(defn unnested-list?
[[fl :as l]]
(and (vector? l) (list-like? fl) (not-any? list-like? fl)))
(def FilterPattern (s/constrained [(s/one [s/Any] "Predicate")]
unnested-list?))
(def EvalPattern (s/constrained [(s/one [s/Any] "Expression")
(s/one Var "Binding var")]
unnested-list?))
(declare Pattern)
(def OpPattern (s/constrained [(s/one Operators "operator")
(s/one (s/recursive #'Pattern) "first pattern")
(s/recursive #'Pattern)]
list-like?))
(def Pattern (s/if list-like? OpPattern
(s/if (comp list-like? first)
(s/if (comp nil? second) FilterPattern EvalPattern)
EPVPattern)))
(def Value (s/pred (complement symbol?) "Value"))
(def Results [[Value]])
(def EntityPropAxiomElt
(s/cond-pre s/Keyword #?(:clj Long :cljs s/Num)))
(def EntityPropValAxiomElt
(s/conditional (complement symbol?) s/Any))
(def Triple
[(s/one s/Any "entity")
(s/one s/Any "property")
(s/one s/Any "value")])
(def Axiom
[(s/one EntityPropAxiomElt "entity")
(s/one EntityPropAxiomElt "property")
(s/one EntityPropValAxiomElt "value")])
|
538eec61179b17b341279313df3b2fb72e1d5ddb248aeb9124f585b2380d71ae
|
pmundkur/flowcaml
|
avl_graphviz.mli
|
(**************************************************************************)
(* *)
(* Averell *)
(* *)
, Projet Cristal , INRIA Rocquencourt
(* *)
Copyright 2002 , 2003 Institut National de Recherche en Informatique
(* et en Automatique. All rights reserved. This file is distributed *)
under the terms of the GNU Library General Public License , with the
(* special exception on linking described in file LICENSE. *)
(* *)
(* Author contact: *)
(* Software page: /~simonet/soft/ *)
(* *)
(**************************************************************************)
$ I d : avl_graphviz.mli , v 1.4 2003/06/26 13:32:45 simonet Exp $
* Interface with { i GraphViz }
This module provides a basic interface with dot and neato ,
two programs of the GraphViz toolbox .
These tools are available at the following URLs :
{ v / v }
{ v / v }
This module provides a basic interface with dot and neato,
two programs of the GraphViz toolbox.
These tools are available at the following URLs:
{v / v}
{v / v}
*)
open Format
(***************************************************************************)
* { 2 Common stuff }
* Because the neato and dot engines present a lot of common points -
in particular in the graph description language , large parts of
the code is shared . First , the [ ! CommonAttributes ] module defines
attributes of graphs , nodes and edges that are understood by the
two engines . Second , given a module ( of type [ ! ENGINE ] )
describing an engine the [ ! MakeEngine ] functor provides suitable
interface function for it .
in particular in the graph description language, large parts of
the code is shared. First, the [!CommonAttributes] module defines
attributes of graphs, nodes and edges that are understood by the
two engines. Second, given a module (of type [!ENGINE])
describing an engine the [!MakeEngine] functor provides suitable
interface function for it. *)
(*-------------------------------------------------------------------------*)
* { 3 Common attributes }
type color = int
type arrow_style =
[ `None | `Normal | `Inv | `Dot | `Odot | `Invdot | `Invodot ]
* The [ CommonAttributes ] module defines attributes for graphs , nodes and edges
that are available in the two engines , dot and neato .
that are available in the two engines, dot and neato.
*)
module CommonAttributes : sig
(** Attributes of graphs.
*)
type graph =
[ `Center of bool
(** Centers the drawing on the page. Default value is [false]. *)
| `Fontcolor of color
(** Sets the font color. Default value is [black]. *)
| `Fontname of string
(** Sets the font family name. Default value is ["Times-Roman"]. *)
| `Fontsize of int
* Sets the type size ( in points ) . Default value is [ 14 ] .
| `Label of string
(** Caption for graph drawing. *)
| `Orientation of [ `Portrait | `Landscape ]
(** Sets the page orientation. Default value is [`Portrait]. *)
| `Page of float * float
* Sets the PostScript pagination unit , e.g [ 8.5 , 11.0 ] .
| `Pagedir of [ `TopToBottom | `LeftToRight ]
* Traversal order of pages . Default value is [ ` TopToBottom ] .
| `Size of float * float
(** Sets the bounding box of drawing (in inches). *)
]
(** Attributes of nodes.
*)
type node =
[ `Color of color
(** Sets the color of the border of the node. Default value is [black]
*)
| `Fontcolor of color
(** Sets the label font color. Default value is [black]. *)
| `Fontname of string
(** Sets the label font family name. Default value is
["Times-Roman"]. *)
| `Fontsize of int
* Sets the label type size ( in points ) . Default value is [ 14 ] .
*)
| `Height of float
* Sets the minimum height . Default value is [ 0.5 ] .
| `Label of string
* Sets the label printed in the node . The string may include escaped
newlines \n , \l , or \r for center , left , and right justified lines .
Record labels may contain recursive box lists delimited by { | } .
newlines \n, \l, or \r for center, left, and right justified lines.
Record labels may contain recursive box lists delimited by { | }. *)
| `Orientation of float
* Node rotation angle , in degrees . Default value is [ 0.0 ] .
| `Peripheries of int
(** Sets the number of periphery lines drawn around the polygon. *)
| `Regular of bool
* If [ true ] , then the polygon is made regular , i.e. symmetric about
the x and y axis , otherwise the polygon takes on the aspect
ratio of the label . Default value is [ false ] .
the x and y axis, otherwise the polygon takes on the aspect
ratio of the label. Default value is [false]. *)
| `Shape of
[`Ellipse | `Box | `Circle | `Doublecircle | `Diamond
| `Plaintext | `Record | `Polygon of int * float]
* Sets the shape of the node . Default value is [ ` Ellipse ] .
[ ` Polygon ( i , f ) ] draws a polygon with [ n ] sides and a skewing
of [ f ] .
[`Polygon (i, f)] draws a polygon with [n] sides and a skewing
of [f]. *)
| `Style of [ `Filled | `Solid | `Dashed | `Dotted | `Bold | `Invis ]
(** Sets the layout style of the node. Several styles may be combined
simultaneously. *)
| `Width of float
* Sets the minimum width . Default value is [ 0.75 ] .
]
(** Attributes of edges.
*)
type edge =
[ `Color of color
(** Sets the edge stroke color. Default value is [black]. *)
| `Decorate of bool
(** If [true], draws a line connecting labels with their edges. *)
| `Dir of [ `Forward | `Back | `Both | `None ]
(** Sets arrow direction. Default value is [`Forward]. *)
| `Fontcolor of color
(** Sets the label font color. Default value is [black]. *)
| `Fontname of string
(** Sets the label font family name. Default value is
["Times-Roman"]. *)
| `Fontsize of int
* Sets the label type size ( in points ) . Default value is [ 14 ] .
| `Label of string
* Sets the label to be attached to the edge . The string may include
escaped newlines \n , \l , or \r for centered , left , or right
justified lines .
escaped newlines \n, \l, or \r for centered, left, or right
justified lines. *)
| `Labelfontcolor of color
(** Sets the font color for head and tail labels. Default value is
[black]. *)
| `Labelfontname of string
(** Sets the font family name for head and tail labels. Default
value is ["Times-Roman"]. *)
| `Labelfontsize of int
* Sets the font size for head and tail labels ( in points ) .
Default value is [ 14 ] .
Default value is [14]. *)
| `Style of [ `Solid | `Dashed | `Dotted | `Bold | `Invis ]
(** Sets the layout style of the edge. Several styles may be combined
simultaneously. *)
]
end
(***************************************************************************)
(** {2 Interface with the dot engine} *)
module Dot : sig
(** Several functions provided by this module run the external program
{i dot}. By default, this command is supposed to be in the default
path and is invoked by {i dot}. The function
[set_command] allows to set an alternative path at run time.
*)
val set_command: string -> unit
module Attributes : sig
* Attributes of graphs . They include all common graph attributes and
several specific ones . All attributes described in the " dot User 's
Manual , February 4 , 2002 " are handled , excepted : clusterank , color ,
compound , labeljust , labelloc , ordering , rank , remincross , rotate ,
searchsize and style .
several specific ones. All attributes described in the "dot User's
Manual, February 4, 2002" are handled, excepted: clusterank, color,
compound, labeljust, labelloc, ordering, rank, remincross, rotate,
searchsize and style.
*)
type graph =
[ CommonAttributes.graph
| `Bgcolor of color
(** Sets the background color and the inital fill color. *)
| `Comment of string
(** Comment string. *)
| `Concentrate of bool
(** If [true], enables edge concentrators. Default value is [false]. *)
| `Fontpath of string
(** List of directories for fonts. *)
| `Layers of string list
(** List of layers. *)
| `Margin of float
* Sets the page margin ( included in the page size ) . Default value is
[ 0.5 ] .
[0.5]. *)
| `Mclimit of float
* Scale factor for mincross iterations . Default value is [ 1.0 ] .
| `Nodesep of float
* Sets the minimum separation between nodes , in inches . Default
value is [ 0.25 ] .
value is [0.25]. *)
| `Nslimit of int
(** If set of [f], bounds network simplex iterations by [f *
<number of nodes>] when ranking nodes. *)
| `Nslimit1 of int
(** If set of [f], bounds network simplex iterations by [f *
<number of nodes>] when setting x-coordinates. *)
| `Ranksep of float
(** Sets the minimum separation between ranks. *)
| `Quantum of float
* If not [ 0.0 ] , node label dimensions will be rounded to integral
multiples of it . Default value is [ 0.0 ] .
multiples of it. Default value is [0.0]. *)
| `Rankdir of [ `TopToBottom | `LeftToRight ]
* Direction of rank ordering . Default value is [ ` TopToBottom ] .
| `Ratio of [ `Float of float | `Fill | `Compress| `Auto ]
(** Sets the aspect ratio. *)
| `Samplepoints of int
* Number of points used to represent ellipses and circles on output .
Default value is [ 8 ] .
Default value is [8]. *)
| `Url of string
(** URL associated with graph (format-dependent). *)
]
* Attributes of nodes . They include all common node attributes and
several specific ones . All attributes described in the " dot User 's
Manual , February 4 , 2002 " are handled , excepted : bottomlabel , group ,
shapefile and toplabel .
several specific ones. All attributes described in the "dot User's
Manual, February 4, 2002" are handled, excepted: bottomlabel, group,
shapefile and toplabel.
*)
type node =
[ CommonAttributes.node
| `Comment of string
(** Comment string. *)
| `Distortion of float
(* TEMPORARY *)
| `Fillcolor of color
(** Sets the fill color (used when `Style filled). Default value
is [lightgrey]. *)
| `Fixedsize of bool
(** If [true], forces the given dimensions to be the actual ones.
Default value is [false]. *)
| `Layer of string
(** Overlay. *)
| `Url of string
* The default url for image map files ; in PostScript files ,
the base URL for all relative URLs , as recognized by Acrobat
Distiller 3.0 and up .
the base URL for all relative URLs, as recognized by Acrobat
Distiller 3.0 and up. *)
| `Z of float
* z coordinate for VRML output .
]
* Attributes of edges . They include all common edge attributes and
several specific ones . All attributes described in the " dot User 's
Manual , February 4 , 2002 " are handled , excepted : and .
several specific ones. All attributes described in the "dot User's
Manual, February 4, 2002" are handled, excepted: lhead and ltail.
*)
type edge =
[ CommonAttributes.edge
| `Arrowhead of arrow_style
(** Sets the style of the head arrow. Default value is [`Normal]. *)
| `Arrowsize of float
* Sets the scaling factor of arrowheads . Default value is [ 1.0 ] .
| `Arrowtail of arrow_style
(** Sets the style of the tail arrow. Default value is [`Normal]. *)
| `Comment of string
(** Comment string. *)
| `Constraints of bool
(** If [false], causes an edge to be ignored for rank assignment.
Default value is [true]. *)
| `Headlabel of string
(** Sets the label attached to the head arrow. *)
| `Headport of [ `N | `NE | `E | `SE | `S | `SW | `W | `NW ]
(* TEMPORARY *)
| `Headurl of string
(** Url attached to head label if output format is ismap. *)
| `Labelangle of float
(** Angle in degrees which head or tail label is rotated off edge.
Default value is [-25.0]. *)
| `Labeldistance of float
* Scaling factor for distance of head or tail label from node .
Default value is [ 1.0 ] .
Default value is [1.0]. *)
| `Labelfloat of bool
(** If [true], lessen constraints on edge label placement.
Default value is [false]. *)
| `Layer of string
(** Overlay. *)
| `Minlen of int
* Minimum rank distance between head an tail . Default value is [ 1 ] .
| `Samehead of string
(** Tag for head node; edge heads with the same tag are merged onto the
same port. *)
| `Sametail of string
(** Tag for tail node; edge tails with the same tag are merged onto the
same port. *)
| `Taillabel of string
(** Sets the label attached to the tail arrow. *)
| `Tailport of [ `N | `NE | `E | `SE | `S | `SW | `W | `NW ]
(* TEMPORARY *)
| `Tailurl of string
(** Url attached to tail label if output format is ismap. *)
| `Weight of int
* Sets the integer cost of stretching the edge . Default value is
[ 1 ] .
[1]. *)
]
end
module type INPUT = sig
type graph
type node
type edge
val iter_nodes: (node -> unit) -> graph -> unit
val iter_edges: (edge -> unit) -> graph -> unit
val graph_attributes: graph -> Attributes.graph list
val default_node_attributes: graph -> Attributes.node list
val default_edge_attributes: graph -> Attributes.edge list
val node_name: node -> string
val node_attributes: node -> Attributes.node list
val edge_head: edge -> node
val edge_tail: edge -> node
val edge_attributes: edge -> Attributes.edge list
end
module Make (X: INPUT) : sig
exception Error of string
val handle_error: ('a -> 'b) -> 'a -> 'b
(** [fprint_graph ppf graph] pretty prints the graph [graph] in
the CGL language on the formatter [ppf].
*)
val fprint_graph: formatter -> X.graph -> unit
(** [output_graph oc graph] pretty prints the graph [graph] in the dot
language on the channel [oc].
*)
val output_graph: out_channel -> X.graph -> unit
(** [run_graph output_mode f graph] runs the engine on the graph
[graph]. The function [f] is applied with the input channel where
the engine writes its output as argument.
This function must not close the channel.
The format of the output is specified
by the [output_mode] argument which may be one of the following
[ `PostScript | `Mif | `HpGl | `Gif | `Imap | `Ismap | `Plain ].
*)
val run_graph:
[ `PostScript | `Mif | `HpGl | `Gif | `Imap | `Ismap | `Plain ] ->
(in_channel -> 'a) -> X.graph -> 'a
end
end
(***************************************************************************)
* { 2 The neato engine }
module Neato : sig
(** Several functions provided by this module run the external program
{i neato}. By default, this command is supposed to be in the default
path and is invoked by {i neato}. The function
[set_command] allows to set an alternative path at run time.
*)
val set_command: string -> unit
module Attributes : sig
* Attributes of graphs . They include all common graph attributes and
several specific ones . All attributes described in the " Neato User 's
manual , April 10 , 2002 " are handled .
several specific ones. All attributes described in the "Neato User's
manual, April 10, 2002" are handled.
*)
type graph =
[ CommonAttributes.graph
| `Margin of float * float
* Sets the page margin ( included in the page size ) . Default value is
[ 0.5 , 0.5 ] .
[0.5, 0.5]. *)
| `Start of int
(** Seed for random number generator. *)
| `Overlap of bool
(** Default value is [true]. *)
| `Spline of bool
(** [true] makes edge splines if nodes don't overlap.
Default value is [false]. *)
| `Sep of float
* Edge spline separation factor from nodes . Default value
is [ 0.0 ] .
is [0.0]. *)
]
* Attributes of nodes . They include all common node attributes and
several specific ones . All attributes described in the " Neato User 's
manual , April 10 , 2002 " are handled .
several specific ones. All attributes described in the "Neato User's
manual, April 10, 2002" are handled.
*)
type node =
[ CommonAttributes.node
| `Pos of float * float
(** Initial coordinates of the node. *)
]
* Attributes of edges . They include all common edge attributes and
several specific ones . All attributes described in the " Neato User 's
manual , April 10 , 2002 " are handled .
several specific ones. All attributes described in the "Neato User's
manual, April 10, 2002" are handled.
*)
type edge =
[ CommonAttributes.edge
| `Id of string
(** Optional value to distinguish multiple edges. *)
| `Len of float
* Preferred length of edge . Default value is [ 1.0 ] .
| `Weight of float
* Strength of edge spring . Default value is [ 1.0 ] .
]
end
module type INPUT = sig
type graph
type node
type edge
val iter_nodes: (node -> unit) -> graph -> unit
val iter_edges: (edge -> unit) -> graph -> unit
val graph_attributes: graph -> Attributes.graph list
val default_node_attributes: graph -> Attributes.node list
val default_edge_attributes: graph -> Attributes.edge list
val node_name: node -> string
val node_attributes: node -> Attributes.node list
val edge_head: edge -> node
val edge_tail: edge -> node
val edge_attributes: edge -> Attributes.edge list
end
module Make (X: INPUT) : sig
exception Error of string
val handle_error: ('a -> 'b) -> 'a -> 'b
(** [fprint_graph ppf graph] pretty prints the graph [graph] in
the CGL language on the formatter [ppf].
*)
val fprint_graph: formatter -> X.graph -> unit
(** [output_graph oc graph] pretty prints the graph [graph] in the dot
language on the channel [oc].
*)
val output_graph: out_channel -> X.graph -> unit
(** [run_graph output_mode f graph] runs the engine on the graph
[graph]. The function [f] is applied with the input channel where
the engine writes its output as argument.
This function must not close the channel.
The format of the output is specified
by the [output_mode] argument which may be one of the following
[ `PostScript | `Mif | `HpGl | `Gif | `Imap | `Ismap | `Plain ].
*)
val run_graph:
[ `PostScript | `Mif | `HpGl | `Gif | `Imap | `Ismap | `Plain ] ->
(in_channel -> 'a) -> X.graph -> 'a
end
end
| null |
https://raw.githubusercontent.com/pmundkur/flowcaml/ddfa8a37e1cb60f42650bed8030036ac313e048a/src-averell/avl_graphviz.mli
|
ocaml
|
************************************************************************
Averell
et en Automatique. All rights reserved. This file is distributed
special exception on linking described in file LICENSE.
Author contact:
Software page: /~simonet/soft/
************************************************************************
*************************************************************************
-------------------------------------------------------------------------
* Attributes of graphs.
* Centers the drawing on the page. Default value is [false].
* Sets the font color. Default value is [black].
* Sets the font family name. Default value is ["Times-Roman"].
* Caption for graph drawing.
* Sets the page orientation. Default value is [`Portrait].
* Sets the bounding box of drawing (in inches).
* Attributes of nodes.
* Sets the color of the border of the node. Default value is [black]
* Sets the label font color. Default value is [black].
* Sets the label font family name. Default value is
["Times-Roman"].
* Sets the number of periphery lines drawn around the polygon.
* Sets the layout style of the node. Several styles may be combined
simultaneously.
* Attributes of edges.
* Sets the edge stroke color. Default value is [black].
* If [true], draws a line connecting labels with their edges.
* Sets arrow direction. Default value is [`Forward].
* Sets the label font color. Default value is [black].
* Sets the label font family name. Default value is
["Times-Roman"].
* Sets the font color for head and tail labels. Default value is
[black].
* Sets the font family name for head and tail labels. Default
value is ["Times-Roman"].
* Sets the layout style of the edge. Several styles may be combined
simultaneously.
*************************************************************************
* {2 Interface with the dot engine}
* Several functions provided by this module run the external program
{i dot}. By default, this command is supposed to be in the default
path and is invoked by {i dot}. The function
[set_command] allows to set an alternative path at run time.
* Sets the background color and the inital fill color.
* Comment string.
* If [true], enables edge concentrators. Default value is [false].
* List of directories for fonts.
* List of layers.
* If set of [f], bounds network simplex iterations by [f *
<number of nodes>] when ranking nodes.
* If set of [f], bounds network simplex iterations by [f *
<number of nodes>] when setting x-coordinates.
* Sets the minimum separation between ranks.
* Sets the aspect ratio.
* URL associated with graph (format-dependent).
* Comment string.
TEMPORARY
* Sets the fill color (used when `Style filled). Default value
is [lightgrey].
* If [true], forces the given dimensions to be the actual ones.
Default value is [false].
* Overlay.
* Sets the style of the head arrow. Default value is [`Normal].
* Sets the style of the tail arrow. Default value is [`Normal].
* Comment string.
* If [false], causes an edge to be ignored for rank assignment.
Default value is [true].
* Sets the label attached to the head arrow.
TEMPORARY
* Url attached to head label if output format is ismap.
* Angle in degrees which head or tail label is rotated off edge.
Default value is [-25.0].
* If [true], lessen constraints on edge label placement.
Default value is [false].
* Overlay.
* Tag for head node; edge heads with the same tag are merged onto the
same port.
* Tag for tail node; edge tails with the same tag are merged onto the
same port.
* Sets the label attached to the tail arrow.
TEMPORARY
* Url attached to tail label if output format is ismap.
* [fprint_graph ppf graph] pretty prints the graph [graph] in
the CGL language on the formatter [ppf].
* [output_graph oc graph] pretty prints the graph [graph] in the dot
language on the channel [oc].
* [run_graph output_mode f graph] runs the engine on the graph
[graph]. The function [f] is applied with the input channel where
the engine writes its output as argument.
This function must not close the channel.
The format of the output is specified
by the [output_mode] argument which may be one of the following
[ `PostScript | `Mif | `HpGl | `Gif | `Imap | `Ismap | `Plain ].
*************************************************************************
* Several functions provided by this module run the external program
{i neato}. By default, this command is supposed to be in the default
path and is invoked by {i neato}. The function
[set_command] allows to set an alternative path at run time.
* Seed for random number generator.
* Default value is [true].
* [true] makes edge splines if nodes don't overlap.
Default value is [false].
* Initial coordinates of the node.
* Optional value to distinguish multiple edges.
* [fprint_graph ppf graph] pretty prints the graph [graph] in
the CGL language on the formatter [ppf].
* [output_graph oc graph] pretty prints the graph [graph] in the dot
language on the channel [oc].
* [run_graph output_mode f graph] runs the engine on the graph
[graph]. The function [f] is applied with the input channel where
the engine writes its output as argument.
This function must not close the channel.
The format of the output is specified
by the [output_mode] argument which may be one of the following
[ `PostScript | `Mif | `HpGl | `Gif | `Imap | `Ismap | `Plain ].
|
, Projet Cristal , INRIA Rocquencourt
Copyright 2002 , 2003 Institut National de Recherche en Informatique
under the terms of the GNU Library General Public License , with the
$ I d : avl_graphviz.mli , v 1.4 2003/06/26 13:32:45 simonet Exp $
* Interface with { i GraphViz }
This module provides a basic interface with dot and neato ,
two programs of the GraphViz toolbox .
These tools are available at the following URLs :
{ v / v }
{ v / v }
This module provides a basic interface with dot and neato,
two programs of the GraphViz toolbox.
These tools are available at the following URLs:
{v / v}
{v / v}
*)
open Format
* { 2 Common stuff }
* Because the neato and dot engines present a lot of common points -
in particular in the graph description language , large parts of
the code is shared . First , the [ ! CommonAttributes ] module defines
attributes of graphs , nodes and edges that are understood by the
two engines . Second , given a module ( of type [ ! ENGINE ] )
describing an engine the [ ! MakeEngine ] functor provides suitable
interface function for it .
in particular in the graph description language, large parts of
the code is shared. First, the [!CommonAttributes] module defines
attributes of graphs, nodes and edges that are understood by the
two engines. Second, given a module (of type [!ENGINE])
describing an engine the [!MakeEngine] functor provides suitable
interface function for it. *)
* { 3 Common attributes }
type color = int
type arrow_style =
[ `None | `Normal | `Inv | `Dot | `Odot | `Invdot | `Invodot ]
* The [ CommonAttributes ] module defines attributes for graphs , nodes and edges
that are available in the two engines , dot and neato .
that are available in the two engines, dot and neato.
*)
module CommonAttributes : sig
type graph =
[ `Center of bool
| `Fontcolor of color
| `Fontname of string
| `Fontsize of int
* Sets the type size ( in points ) . Default value is [ 14 ] .
| `Label of string
| `Orientation of [ `Portrait | `Landscape ]
| `Page of float * float
* Sets the PostScript pagination unit , e.g [ 8.5 , 11.0 ] .
| `Pagedir of [ `TopToBottom | `LeftToRight ]
* Traversal order of pages . Default value is [ ` TopToBottom ] .
| `Size of float * float
]
type node =
[ `Color of color
| `Fontcolor of color
| `Fontname of string
| `Fontsize of int
* Sets the label type size ( in points ) . Default value is [ 14 ] .
*)
| `Height of float
* Sets the minimum height . Default value is [ 0.5 ] .
| `Label of string
* Sets the label printed in the node . The string may include escaped
newlines \n , \l , or \r for center , left , and right justified lines .
Record labels may contain recursive box lists delimited by { | } .
newlines \n, \l, or \r for center, left, and right justified lines.
Record labels may contain recursive box lists delimited by { | }. *)
| `Orientation of float
* Node rotation angle , in degrees . Default value is [ 0.0 ] .
| `Peripheries of int
| `Regular of bool
* If [ true ] , then the polygon is made regular , i.e. symmetric about
the x and y axis , otherwise the polygon takes on the aspect
ratio of the label . Default value is [ false ] .
the x and y axis, otherwise the polygon takes on the aspect
ratio of the label. Default value is [false]. *)
| `Shape of
[`Ellipse | `Box | `Circle | `Doublecircle | `Diamond
| `Plaintext | `Record | `Polygon of int * float]
* Sets the shape of the node . Default value is [ ` Ellipse ] .
[ ` Polygon ( i , f ) ] draws a polygon with [ n ] sides and a skewing
of [ f ] .
[`Polygon (i, f)] draws a polygon with [n] sides and a skewing
of [f]. *)
| `Style of [ `Filled | `Solid | `Dashed | `Dotted | `Bold | `Invis ]
| `Width of float
* Sets the minimum width . Default value is [ 0.75 ] .
]
type edge =
[ `Color of color
| `Decorate of bool
| `Dir of [ `Forward | `Back | `Both | `None ]
| `Fontcolor of color
| `Fontname of string
| `Fontsize of int
* Sets the label type size ( in points ) . Default value is [ 14 ] .
| `Label of string
* Sets the label to be attached to the edge . The string may include
escaped newlines \n , \l , or \r for centered , left , or right
justified lines .
escaped newlines \n, \l, or \r for centered, left, or right
justified lines. *)
| `Labelfontcolor of color
| `Labelfontname of string
| `Labelfontsize of int
* Sets the font size for head and tail labels ( in points ) .
Default value is [ 14 ] .
Default value is [14]. *)
| `Style of [ `Solid | `Dashed | `Dotted | `Bold | `Invis ]
]
end
module Dot : sig
val set_command: string -> unit
module Attributes : sig
* Attributes of graphs . They include all common graph attributes and
several specific ones . All attributes described in the " dot User 's
Manual , February 4 , 2002 " are handled , excepted : clusterank , color ,
compound , labeljust , labelloc , ordering , rank , remincross , rotate ,
searchsize and style .
several specific ones. All attributes described in the "dot User's
Manual, February 4, 2002" are handled, excepted: clusterank, color,
compound, labeljust, labelloc, ordering, rank, remincross, rotate,
searchsize and style.
*)
type graph =
[ CommonAttributes.graph
| `Bgcolor of color
| `Comment of string
| `Concentrate of bool
| `Fontpath of string
| `Layers of string list
| `Margin of float
* Sets the page margin ( included in the page size ) . Default value is
[ 0.5 ] .
[0.5]. *)
| `Mclimit of float
* Scale factor for mincross iterations . Default value is [ 1.0 ] .
| `Nodesep of float
* Sets the minimum separation between nodes , in inches . Default
value is [ 0.25 ] .
value is [0.25]. *)
| `Nslimit of int
| `Nslimit1 of int
| `Ranksep of float
| `Quantum of float
* If not [ 0.0 ] , node label dimensions will be rounded to integral
multiples of it . Default value is [ 0.0 ] .
multiples of it. Default value is [0.0]. *)
| `Rankdir of [ `TopToBottom | `LeftToRight ]
* Direction of rank ordering . Default value is [ ` TopToBottom ] .
| `Ratio of [ `Float of float | `Fill | `Compress| `Auto ]
| `Samplepoints of int
* Number of points used to represent ellipses and circles on output .
Default value is [ 8 ] .
Default value is [8]. *)
| `Url of string
]
* Attributes of nodes . They include all common node attributes and
several specific ones . All attributes described in the " dot User 's
Manual , February 4 , 2002 " are handled , excepted : bottomlabel , group ,
shapefile and toplabel .
several specific ones. All attributes described in the "dot User's
Manual, February 4, 2002" are handled, excepted: bottomlabel, group,
shapefile and toplabel.
*)
type node =
[ CommonAttributes.node
| `Comment of string
| `Distortion of float
| `Fillcolor of color
| `Fixedsize of bool
| `Layer of string
| `Url of string
* The default url for image map files ; in PostScript files ,
the base URL for all relative URLs , as recognized by Acrobat
Distiller 3.0 and up .
the base URL for all relative URLs, as recognized by Acrobat
Distiller 3.0 and up. *)
| `Z of float
* z coordinate for VRML output .
]
* Attributes of edges . They include all common edge attributes and
several specific ones . All attributes described in the " dot User 's
Manual , February 4 , 2002 " are handled , excepted : and .
several specific ones. All attributes described in the "dot User's
Manual, February 4, 2002" are handled, excepted: lhead and ltail.
*)
type edge =
[ CommonAttributes.edge
| `Arrowhead of arrow_style
| `Arrowsize of float
* Sets the scaling factor of arrowheads . Default value is [ 1.0 ] .
| `Arrowtail of arrow_style
| `Comment of string
| `Constraints of bool
| `Headlabel of string
| `Headport of [ `N | `NE | `E | `SE | `S | `SW | `W | `NW ]
| `Headurl of string
| `Labelangle of float
| `Labeldistance of float
* Scaling factor for distance of head or tail label from node .
Default value is [ 1.0 ] .
Default value is [1.0]. *)
| `Labelfloat of bool
| `Layer of string
| `Minlen of int
* Minimum rank distance between head an tail . Default value is [ 1 ] .
| `Samehead of string
| `Sametail of string
| `Taillabel of string
| `Tailport of [ `N | `NE | `E | `SE | `S | `SW | `W | `NW ]
| `Tailurl of string
| `Weight of int
* Sets the integer cost of stretching the edge . Default value is
[ 1 ] .
[1]. *)
]
end
module type INPUT = sig
type graph
type node
type edge
val iter_nodes: (node -> unit) -> graph -> unit
val iter_edges: (edge -> unit) -> graph -> unit
val graph_attributes: graph -> Attributes.graph list
val default_node_attributes: graph -> Attributes.node list
val default_edge_attributes: graph -> Attributes.edge list
val node_name: node -> string
val node_attributes: node -> Attributes.node list
val edge_head: edge -> node
val edge_tail: edge -> node
val edge_attributes: edge -> Attributes.edge list
end
module Make (X: INPUT) : sig
exception Error of string
val handle_error: ('a -> 'b) -> 'a -> 'b
val fprint_graph: formatter -> X.graph -> unit
val output_graph: out_channel -> X.graph -> unit
val run_graph:
[ `PostScript | `Mif | `HpGl | `Gif | `Imap | `Ismap | `Plain ] ->
(in_channel -> 'a) -> X.graph -> 'a
end
end
* { 2 The neato engine }
module Neato : sig
val set_command: string -> unit
module Attributes : sig
* Attributes of graphs . They include all common graph attributes and
several specific ones . All attributes described in the " Neato User 's
manual , April 10 , 2002 " are handled .
several specific ones. All attributes described in the "Neato User's
manual, April 10, 2002" are handled.
*)
type graph =
[ CommonAttributes.graph
| `Margin of float * float
* Sets the page margin ( included in the page size ) . Default value is
[ 0.5 , 0.5 ] .
[0.5, 0.5]. *)
| `Start of int
| `Overlap of bool
| `Spline of bool
| `Sep of float
* Edge spline separation factor from nodes . Default value
is [ 0.0 ] .
is [0.0]. *)
]
* Attributes of nodes . They include all common node attributes and
several specific ones . All attributes described in the " Neato User 's
manual , April 10 , 2002 " are handled .
several specific ones. All attributes described in the "Neato User's
manual, April 10, 2002" are handled.
*)
type node =
[ CommonAttributes.node
| `Pos of float * float
]
* Attributes of edges . They include all common edge attributes and
several specific ones . All attributes described in the " Neato User 's
manual , April 10 , 2002 " are handled .
several specific ones. All attributes described in the "Neato User's
manual, April 10, 2002" are handled.
*)
type edge =
[ CommonAttributes.edge
| `Id of string
| `Len of float
* Preferred length of edge . Default value is [ 1.0 ] .
| `Weight of float
* Strength of edge spring . Default value is [ 1.0 ] .
]
end
module type INPUT = sig
type graph
type node
type edge
val iter_nodes: (node -> unit) -> graph -> unit
val iter_edges: (edge -> unit) -> graph -> unit
val graph_attributes: graph -> Attributes.graph list
val default_node_attributes: graph -> Attributes.node list
val default_edge_attributes: graph -> Attributes.edge list
val node_name: node -> string
val node_attributes: node -> Attributes.node list
val edge_head: edge -> node
val edge_tail: edge -> node
val edge_attributes: edge -> Attributes.edge list
end
module Make (X: INPUT) : sig
exception Error of string
val handle_error: ('a -> 'b) -> 'a -> 'b
val fprint_graph: formatter -> X.graph -> unit
val output_graph: out_channel -> X.graph -> unit
val run_graph:
[ `PostScript | `Mif | `HpGl | `Gif | `Imap | `Ismap | `Plain ] ->
(in_channel -> 'a) -> X.graph -> 'a
end
end
|
23db1578dfc73d588aa85acc1b958ec1f4a2b2d67a4b7393d06005248771b552
|
threatgrid/ctia
|
migrate_es_stores_test.clj
|
(ns ctia.task.migration.migrate-es-stores-test
(:require [clj-momo.lib.clj-time.coerce :as time-coerce]
[clj-momo.test-helpers.core :as mth]
[clojure.data :refer [diff]]
[clojure.java.io :as io]
[clojure.set :as set]
[clojure.string :as str]
[clojure.test :refer [deftest is join-fixtures testing use-fixtures]]
[clojure.walk :refer [keywordize-keys]]
[ctia.entity.relationship.schemas :refer [StoredRelationship]]
[ctia.stores.es.store :refer [store->map]]
[ctia.task.migration.migrate-es-stores :as sut]
[ctia.task.migration.store
:refer
[fetch-batch get-migration init-migration prefixed-index setup!]]
[ctia.task.rollover :refer [rollover-stores]]
[ctia.test-helpers.auth :refer [all-capabilities]]
[ctia.test-helpers.core
:as
helpers
:refer
[GET DELETE POST-bulk PUT with-atom-logger]]
[ctia.test-helpers.es :as es-helpers]
[ctia.test-helpers.fake-whoami-service :as whoami-helpers]
[ctia.test-helpers.fixtures :as fixt]
[ctia.test-helpers.migration :refer [app->MigrationStoreServices]]
[ctim.domain.id :refer [long-id->id]]
[ductile.conn :refer [connect]]
[ductile.document :as ductile.doc]
[ductile.index :as es-index]
[ductile.query :as es-query]
[schema.core :as s])
(:import clojure.lang.ExceptionInfo
java.lang.AssertionError
java.text.SimpleDateFormat
[java.util Date UUID]))
(defn fixture-setup! [f]
(let [app (helpers/get-current-app)
services (app->MigrationStoreServices app)]
(setup! services)
(f)))
(use-fixtures :once
(join-fixtures [mth/fixture-schema-validation
whoami-helpers/fixture-server
es-helpers/fixture-properties:es-store]))
(defn es-props [get-in-config]
(get-in-config [:ctia :store :es]))
(defn es-conn [get-in-config]
(connect (:default (es-props get-in-config))))
(defn migration-index [get-in-config]
(get-in-config [:ctia :migration :store :es :migration :indexname]))
(defn fixture-clean-migration [t]
(let [app (helpers/get-current-app)
{:keys [get-in-config]} (helpers/get-service-map app :ConfigService)]
(try
(t)
(finally
(doto (es-conn get-in-config)
(es-index/delete! "v0.0.0*")
(es-index/delete! (str (migration-index get-in-config) "*")))))))
(s/defn with-each-fixtures*
"Wrap this function around each deftest instead of use-fixtures
so the TK config can be transformed before helpers/fixture-ctia
starts the app."
[config-transformer body-fn :- (s/=> s/Any (s/=> s/Any (s/named s/Any 'app)))]
(let [fixtures (join-fixtures [helpers/fixture-ctia
fixture-setup! ;; Note: goes _after_ fixture-ctia
es-helpers/fixture-delete-store-indexes
fixture-clean-migration])]
(helpers/with-config-transformer*
config-transformer
#(fixtures
(fn []
(body-fn (helpers/get-current-app)))))))
(defmacro with-each-fixtures
"Primarily for check-migration-params-test. Binds `app` to current TK app."
[config-transformer app & body]
(assert (simple-symbol? app) (pr-str app))
`(with-each-fixtures* ~config-transformer
(fn [~app]
(do ~@body))))
(defn index-exists?
[store prefix]
(let [{:keys [conn indexname]} (store->map store {})]
(es-index/index-exists? conn
(prefixed-index indexname prefix))))
(def fixtures-nb 100)
(def updates-nb 50)
(def minimal-examples (fixt/bundle fixtures-nb false))
(def example-types
(->> (vals minimal-examples)
(map #(-> % first :type keyword))
set))
(defn update-entity
[app
{entity-type :type
entity-id :short-id}]
(let [entity-path (format "ctia/%s/%s" (str entity-type) entity-id)
previous (-> (GET app
entity-path
:headers {"Authorization" "45c1f5e3f05d0"})
:parsed-body)]
(PUT app
entity-path
:body (assoc previous :description "UPDATED")
:headers {"Authorization" "45c1f5e3f05d0"})))
(defn random-updates
"select nb random entities of the bulk and update them"
[app bulk-result nb]
(let [random-ids (->> (select-keys bulk-result
[:malwares
:sightings
:indicators
:vulnerabilities])
vals
(apply concat)
shuffle
(take nb)
(map long-id->id))]
(doseq [entity random-ids]
(update-entity app entity))))
(defn rollover-post-bulk
"post data in 2 parts with rollover, randomly update son entities"
[app all-stores]
(let [bulk-res-1 (POST-bulk app (fixt/bundle (/ fixtures-nb 2) false))
_ (rollover-stores (all-stores))
bulk-res-2 (POST-bulk app (fixt/bundle (/ fixtures-nb 2) false))
_ (rollover-stores (all-stores))]
(random-updates app bulk-res-1 (/ updates-nb 2))
(random-updates app bulk-res-2 (/ updates-nb 2))))
(deftest check-migration-params-test
(let [migration-params {:migration-id "id"
:prefix "1.2.0"
:migrations [:identity]
:store-keys [:incident :investigation :malware]
:batch-size 100
:buffer-size 3
:confirm? true
:restart? false}]
(testing "misconfigured migration"
(let [investigation-indexname (str "v1.2.0_ctia_investigation" (UUID/randomUUID))
malware-indexname (str "v1.2.0_ctia_malware" (UUID/randomUUID))]
(with-each-fixtures #(-> %
(assoc-in [:ctia :store :es :investigation :indexname]
investigation-indexname)
(assoc-in [:malware 0 :state :props :indexname]
malware-indexname))
app
(let [{:keys [get-in-config]} (helpers/get-service-map app :ConfigService)]
(let [v (get-in-config [:ctia :store :es :investigation :indexname])]
(assert (= v investigation-indexname)
[v investigation-indexname]))
(let [v (get-in-config [:malware 0 :state :props :indexname])]
(assert (= v malware-indexname)
[v malware-indexname]))
(is (thrown? AssertionError
(sut/check-migration-params migration-params
get-in-config))
"source and target store must be different")))
(with-each-fixtures identity app
(let [{:keys [get-in-config]} (helpers/get-service-map app :ConfigService)]
(is (thrown? ExceptionInfo
(sut/check-migration-params (update migration-params
:migrations
conj
:bad-migration-id)
get-in-config))))))
(testing "properly configured migration"
(with-each-fixtures identity app
(let [{:keys [get-in-config]} (helpers/get-service-map app :ConfigService)]
(is (sut/check-migration-params migration-params
get-in-config))))))))
(deftest prepare-params-test
(let [migration-props {:buffer-size 3,
:batch-size 100,
:migration-id "migration-test",
:restart? false,
:store-keys "malware, tool,sighting ",
:migrations "identity",
:confirm? false,
:prefix "v1.2.0"}
prepared (sut/prepare-params migration-props)]
(testing "prepare params should properly format migration properties"
(is (= (dissoc prepared :store-keys :migrations)
(dissoc migration-props :store-keys :migrations)))
(is (= (:store-keys prepared)
[:malware :tool :sighting]))
(is (= (:migrations prepared)
[:identity])))))
(deftest migration-with-rollover
(with-each-fixtures identity app
(testing "migration with rollover and multiple indices for source stores"
(let [{:keys [get-in-config]} (helpers/get-service-map app :ConfigService)
{:keys [all-stores]} (helpers/get-service-map app :StoreService)
services (app->MigrationStoreServices app)
conn (es-conn get-in-config)
store-types [:malware :tool :incident]]
(helpers/set-capabilities! app
"foouser"
["foogroup"]
"user"
all-capabilities)
(whoami-helpers/set-whoami-response app
"45c1f5e3f05d0"
"foouser"
"foogroup"
"user")
(rollover-post-bulk app all-stores)
;; insert malformed documents
(doseq [store-type store-types]
(es-index/get conn
(str (get-in (es-props get-in-config) [store-type :indexname]) "*")))
(sut/migrate-store-indexes {:migration-id "test-3"
:prefix "0.0.0"
:migrations [:__test]
:store-keys store-types
:batch-size 10
:buffer-size 3
:confirm? true
:restart? false}
services)
(let [migration-state (ductile.doc/get-doc conn
(migration-index get-in-config)
"migration"
"test-3"
{})]
(doseq [store-type store-types]
(is (= (count (es-index/get conn
(str "v0.0.0_" (get-in (es-props get-in-config) [store-type :indexname]) "*")))
3)
"target index should be rolled over during migration")
(es-index/get conn
(str "v0.0.0_" (get-in (es-props get-in-config) [store-type :indexname]) "*"))
(let [migrated-store (get-in migration-state [:stores store-type])
{:keys [source target]} migrated-store]
(is (= fixtures-nb (:total source)))
(is (= fixtures-nb (:migrated target))))))))))
(def date-str->epoch-millis
(comp time-coerce/to-long time-coerce/to-date-time))
(deftest read-source-batch-test
(with-each-fixtures identity app
(with-open [rdr (io/reader "./test/data/indices/sample-relationships-1000.json")]
(let [{:keys [get-in-config]} (helpers/get-service-map app :ConfigService)
conn (es-conn get-in-config)
storemap {:conn conn
:indexname (es-helpers/get-indexname app :relationship)
:mapping "relationship"
:props {:write-index (es-helpers/get-indexname app :relationship)}
:type "relationship"
:settings {}
:config {}}
docs (map (partial es-helpers/prepare-bulk-ops app)
(line-seq rdr))
_ (es-helpers/load-bulk conn docs)
no-meta-docs (map #(dissoc % :_index :_type :_id)
docs)
docs-no-modified (filter #(nil? (:modified %))
no-meta-docs)
docs-100 (take 100 no-meta-docs)
missing-query {:bool {:must_not {:exists {:field :modified}}}}
ids-100-query {:ids {:values (map :id docs-100)}}
match-all-query {:match_all {}}
nb-skipped-ids 10
[last-skipped & expected-ids-docs] (->> (sort-by (juxt :modified :created :id)
docs-100)
(drop (dec nb-skipped-ids)))
{after-modified :modified
after-created :created
after-id :id} last-skipped
search_after [(date-str->epoch-millis after-modified)
(date-str->epoch-millis after-created)
after-id]
read-params-1 {:source-store storemap
:batch-size 1000
:query missing-query}
read-params-2 {:source-store storemap
:batch-size 100
:search_after search_after
:query ids-100-query}
read-params-3 {:source-store storemap
:batch-size 400
:query match-all-query}
missing-res (sut/read-source-batch read-params-1)
ids-res (sut/read-source-batch read-params-2)
match-all-res (rest (iterate sut/read-source-batch read-params-3))]
(testing "queries should be used to select data"
(is (= (set docs-no-modified)
(set (:documents missing-res)))))
(testing "search_after should be properly taken into account"
(is (= (set expected-ids-docs)
(set (:documents ids-res))))
(is (= (- 100 nb-skipped-ids)
(count (:documents ids-res)))))
(testing "read source should return parameters for next call"
(is (= read-params-1
(dissoc missing-res :search_after :documents)))
(is (= (dissoc read-params-2 :search_after)
(dissoc ids-res :search_after :documents))))
(testing "read-source-batch shoould return nil when parameters map is nil or the query result is empty"
(is (= nil
(sut/read-source-batch nil)
(sut/read-source-batch (assoc read-params-1
:batch-size
0)))))
(testing "read-source-batch result should be usable to call read-source-batch again for scrolling given query"
(is (= '(400 400 200 0)
(->> (take 4 match-all-res)
(map #(-> % :documents count)))))
(is (= (set no-meta-docs)
(->> (take 4 match-all-res)
(map :documents)
(apply concat)
set))))))))
(deftest read-source-test
(with-each-fixtures identity app
(testing "read-source should produce a lazy seq from recursive read-source-batch calls"
(let [counter (atom 0)]
(with-redefs [sut/read-source-batch (fn [batch-params]
(when (< @counter 5)
(swap! counter inc)
(update batch-params :migrated-count inc)))]
(let [batches (map :migrated-count
(sut/read-source {:migrated-count 0}))]
(is (= '(1 2) (take 2 batches)))
(is (= 2 @counter))
(is (= '(1 2 3 4 5) (take 10 batches)))
(is (= 5 @counter))))))))
(deftest write-target-test
(with-each-fixtures identity app
(with-open [rdr (io/reader "./test/data/indices/sample-relationships-1000.json")]
(let [{:keys [get-in-config]} (helpers/get-service-map app :ConfigService)
services (app->MigrationStoreServices app)
prefix "0.0.1"
indexname (str "v0.0.1_" (es-helpers/get-indexname app :relationship))
conn (es-conn get-in-config)
storemap {:conn conn
:indexname indexname
:mapping "relationship"
:props {:write-index indexname}
:type "relationship"
:settings {}
:config {}}
list-coerce (sut/list-coerce-fn StoredRelationship)
migration-id "migration-1"
docs (map (comp :_source es-helpers/str->doc)
(line-seq rdr))
base-params {:target-store storemap
:entity-type :relationship
:list-coerce list-coerce
:migration-id migration-id
:migrations (sut/compose-migrations [:__test])
:batch-size 1000
:migration-es-conn conn
:confirm? true}
test-fn (fn [total
migrated-count
msg
{:keys [confirm?]
:as override-params}]
(init-migration {:migration-id migration-id
:prefix prefix
:store-keys [:relationship]
:confirm? true
:migrations [:__test]
:batch-size 1000
:buffer-size 3
:restart? false}
services)
(let [test-docs (take total docs)
search_after [(rand-int total)]
batch-params (-> (into base-params
override-params)
(assoc :documents test-docs
:search_after search_after))
nb-migrated (sut/write-target migrated-count
batch-params
services)
{target-state :target
source-state :source} (-> (get-migration migration-id
conn
services)
:stores
:relationship)
_ (es-index/refresh! conn)
migrated-docs (:data (ductile.doc/query conn
indexname
{:match_all {}}
{:limit total}))]
(testing msg
(when-not confirm?
(is (= (+ total migrated-count)
nb-migrated))
(is (= (count migrated-docs)
(:migrated target-state))))
(when confirm?
(is (= (+ total migrated-count)
(+ (count migrated-docs) migrated-count)
nb-migrated
(:migrated target-state)))
(is (= (set (map #(dissoc % :groups)
migrated-docs))
(set (map #(dissoc % :groups)
test-docs)))
"write-target should only perform attended modifications")
(is (every? #(= (:groups %)
["migration-test"])
migrated-docs)
"write-target should perform attended modifications on migrated documents")
(is (= search_after
(:search_after source-state))
"write-target should store last search_after in migration state")))))]
(test-fn 100
0
"write-target should properly modify documents, and write them in target index"
{:confirm? true})
(test-fn 100
10
"write-target should properly accumulate migration count"
{:confirm? true})
(test-fn 100
0
"write-target should not write anything while properly simulating migration when `confirm?` is set to false"
{:confirm? false})))))
(deftest sliced-migration-test
(with-each-fixtures identity app
(with-open [rdr (io/reader "./test/data/indices/sample-relationships-1000.json")]
(let [{:keys [get-in-config]} (helpers/get-service-map app :ConfigService)
services (app->MigrationStoreServices app)
conn (es-conn get-in-config)
{wo-modified true
w-modified false} (->> (line-seq rdr)
(map (partial es-helpers/prepare-bulk-ops app))
(group-by #(nil? (:modified %))))
sorted-w-modified (sort-by :modified w-modified)
bulk-1 (concat wo-modified (take 500 sorted-w-modified))
bulk-2 (drop 500 sorted-w-modified)
logger-1 (atom [])
_ (es-helpers/load-bulk conn bulk-1)
_ (with-atom-logger logger-1
(sut/migrate-store-indexes {:migration-id "migration-test-4"
:prefix "0.0.0"
:migrations [:__test]
:store-keys [:relationship]
:batch-size 100
:buffer-size 3
:confirm? true
:restart? false}
services))
migration-state-1 (ductile.doc/get-doc conn
(migration-index get-in-config)
"migration"
"migration-test-4"
{})
target-count-1 (ductile.doc/count-docs conn
(str "v0.0.0_"
(es-helpers/get-indexname app :relationship))
nil)
_ (es-helpers/load-bulk conn bulk-2)
_ (with-atom-logger logger-1
(sut/migrate-store-indexes {:migration-id "migration-test-4"
:prefix "0.0.0"
:migrations [:__test]
:store-keys [:relationship]
:batch-size 100
:buffer-size 3
:confirm? true
:restart? true}
services))
target-count-2 (ductile.doc/count-docs conn
(str "v0.0.0_"
(es-helpers/get-indexname app :relationship))
nil)
migration-state-2 (ductile.doc/get-doc conn
(migration-index get-in-config)
"migration"
"migration-test-4"
{})]
(is (= (+ 500 (count wo-modified))
target-count-1
(get-in migration-state-1 [:stores :relationship :target :migrated])
(get-in migration-state-1 [:stores :relationship :source :total]))
"migration process should start with documents missing field used for bucketizing")
(is (= 1000
target-count-2
(get-in migration-state-2 [:stores :relationship :source :total]))
"migration process should complete the migration after restart")))))
(deftest migration-with-malformed-docs
(with-each-fixtures identity app
(testing "migration with malformed documents in store"
(let [{:keys [get-in-config]} (helpers/get-service-map app :ConfigService)
{:keys [all-stores]} (helpers/get-service-map app :StoreService)
services (app->MigrationStoreServices app)
conn (es-conn get-in-config)
store-types [:malware :tool :incident]
logger (atom [])
bad-doc {:id 1
:hey "I"
:am "a"
:bad "document"}]
(helpers/set-capabilities! app
"foouser"
["foogroup"]
"user"
all-capabilities)
(whoami-helpers/set-whoami-response app
"45c1f5e3f05d0"
"foouser"
"foogroup"
"user")
;; insert proper documents
(rollover-post-bulk app all-stores)
;; insert malformed documents
(doseq [store-type store-types]
(ductile.doc/create-doc conn
(str (get-in (es-props get-in-config) [store-type :indexname]) "-write")
(name store-type)
bad-doc
{:refresh "true"}))
(with-atom-logger logger
(sut/migrate-store-indexes {:migration-id "test-3"
:prefix "0.0.0"
:migrations [:__test]
:store-keys store-types
:batch-size 10
:buffer-size 3
:confirm? true
:restart? false}
services))
(let [messages (set @logger)
migration-state (ductile.doc/get-doc conn
(migration-index get-in-config)
"migration"
"test-3"
{})]
(doseq [store-type store-types]
(let [migrated-store (get-in migration-state [:stores store-type])
{:keys [source target]} migrated-store]
(is (= (inc fixtures-nb) (:total source)))
(is (= fixtures-nb (:migrated target))))
(is (some #(str/starts-with? % (format "%s - Cannot migrate entity: {"
(name store-type)))
messages)
(format "malformed %s was not logged" store-type))))))))
(deftest test-migrate-store-indexes
(with-each-fixtures identity app
TODO clean data
(let [{:keys [get-in-config]} (helpers/get-service-map app :ConfigService)
{:keys [all-stores]} (helpers/get-service-map app :StoreService)
services (app->MigrationStoreServices app)
conn (es-conn get-in-config)]
(helpers/set-capabilities! app
"foouser"
["foogroup"]
"user"
all-capabilities)
(whoami-helpers/set-whoami-response app
"45c1f5e3f05d0"
"foouser"
"foogroup"
"user")
;; insert proper documents
(rollover-post-bulk app all-stores)
(testing "migrate ES Stores test setup"
(testing "simulate migrate es indexes shall not create any document"
(sut/migrate-store-indexes {:migration-id "test-1"
:prefix "0.0.0"
:migrations [:0.4.16]
:store-keys (keys (all-stores))
:batch-size 10
:buffer-size 3
:confirm? false
:restart? false}
services)
(doseq [store (vals (all-stores))]
(is (not (index-exists? store "0.0.0"))))
(is (nil? (seq (ductile.doc/get-doc conn
(migration-index get-in-config)
"migration"
"test-1"
{})))))))
(testing "migrate es indexes"
(let [{:keys [get-in-config]} (helpers/get-service-map app :ConfigService)
{:keys [all-stores]} (helpers/get-service-map app :StoreService)
services (app->MigrationStoreServices app)
conn (es-conn get-in-config)
logger (atom [])]
(with-atom-logger logger
(sut/migrate-store-indexes {:migration-id "test-2"
:prefix "0.0.0"
:migrations [:__test]
:store-keys (keys (all-stores))
:batch-size 10
:buffer-size 3
:confirm? true
:restart? false}
services))
(testing "shall generate a proper migration state"
(let [migration-state (ductile.doc/get-doc conn
(migration-index get-in-config)
"migration"
"test-2"
{})]
(is (= (set (keys (all-stores)))
(set (keys (:stores migration-state)))))
(doseq [[entity-type migrated-store] (:stores migration-state)]
(let [{:keys [source target started completed]} migrated-store
source-size
(cond
(= :identity entity-type) 1
(= :event entity-type) (+ updates-nb
(* fixtures-nb
(count minimal-examples)))
(contains? example-types (keyword entity-type)) fixtures-nb
:else 0)]
(is (= source-size (:total source))
(str "source size match for " (:index source)))
(is (not (nil? started)))
(is (not (nil? completed)))
(is (<= (:migrated target) (:total source)))
(is (int? (:total source)))
(is (= (:index target)
(prefixed-index (:index source) "0.0.0")))))))
(testing "shall produce valid logs"
(let [messages (set @logger)]
(is (contains? messages "set batch size: 10"))
(is (set/subset?
#{"campaign - finished migrating 100 documents"
"indicator - finished migrating 100 documents"
(format "event - finished migrating %s documents"
(+ 2000 updates-nb))
"actor - finished migrating 100 documents"
"asset - finished migrating 100 documents"
"relationship - finished migrating 100 documents"
"incident - finished migrating 100 documents"
"investigation - finished migrating 100 documents"
"coa - finished migrating 100 documents"
"identity - finished migrating 0 documents"
"judgement - finished migrating 100 documents"
"note - finished migrating 100 documents"
"data-table - finished migrating 0 documents"
"feedback - finished migrating 0 documents"
"casebook - finished migrating 100 documents"
"sighting - finished migrating 100 documents"
"identity-assertion - finished migrating 0 documents"
"attack-pattern - finished migrating 100 documents"
"malware - finished migrating 100 documents"
"target-record - finished migrating 100 documents"
"tool - finished migrating 100 documents"
"vulnerability - finished migrating 100 documents"
"weakness - finished migrating 100 documents" }
messages))))
(testing "shall produce new indices with enough documents and the right transforms"
(let [{:keys [default
asset
target-record
relationship
judgement
investigation
coa
tool
attack-pattern
malware
incident
indicator
campaign
sighting
casebook
actor
vulnerability
weakness]}
(get-in-config [:ctia :store :es])
date (Date.)
index-date (.format (SimpleDateFormat. "yyyy.MM.dd") date)
expected-event-indices {(format "v0.0.0_%s-%s-000001"
(es-helpers/get-indexname app :event)
index-date)
1000
(format "v0.0.0_%s-%s-000002"
(es-helpers/get-indexname app :event)
index-date)
(+ 950 updates-nb)}
expected-indices
(->> #{relationship
target-record
judgement
coa
attack-pattern
malware
tool
incident
indicator
investigation
campaign
casebook
sighting
actor
vulnerability
weakness}
(map (fn [k]
{(format "v0.0.0_%s-%s-000001" (:indexname k) index-date) 50
(format "v0.0.0_%s-%s-000002" (:indexname k) index-date) 50
(format "v0.0.0_%s-%s-000003" (:indexname k) index-date) 0}))
(into expected-event-indices)
keywordize-keys)
_ (es-index/refresh! conn)
formatted-cat-indices (es-helpers/get-cat-indices conn)
result-indices (select-keys formatted-cat-indices
(keys expected-indices))]
(is (= expected-indices result-indices)
(let [[only-expected only-result _]
(diff expected-indices result-indices)]
(format "only in expected ==> %s\nonly in result ==> %s"
only-expected
only-result)))
(doseq [[index _]
expected-indices]
(let [docs (->> (ductile.doc/search-docs conn (name index) nil nil {})
:data
(map :groups))]
(is (every? #(= ["migration-test"] %)
docs))))))
(testing "restart migration shall properly handle inserts, updates and deletes"
retrieve the first 2 source indices for sighting store
[sighting-index-1 sighting-index-2 :as sighting-indices]
(->> (es-helpers/get-cat-indices conn)
keys
(map name)
(filter #(.contains ^String % "sighting"))
sort
(take 2))
_ (assert (= 2 (count sighting-indices)) sighting-indices)
retrieve source entity to update , in first position of first index
es-sighting0 (-> (ductile.doc/query conn
sighting-index-1
{:match_all {}}
{:sort_by "timestamp:asc"
:size 1})
:data
first)
retrieve source entity to update , in first position of second index
es-sighting1 (-> (ductile.doc/query conn
sighting-index-2
{:match_all {}}
{:sort_by "timestamp:asc"
:size 1})
:data
first)
;; prepare new malwares
new-malwares {:malwares (->> (fixt/n-examples :malware 3 false)
(map #(assoc % :description "INSERTED")))}
retrieve 5 source entities to delete , in last positions of first index
es-sightings-1 (-> (ductile.doc/query conn
sighting-index-1
{:match_all {}}
{:sort_by "timestamp:desc"
:limit 5})
:data)
retrieve 5 source entities to delete , in last positions of second index
es-sightings-2 (-> (ductile.doc/query conn
sighting-index-2
{:match_all {}}
{:sort_by "timestamp:desc"
:limit 5})
:data)
sightings (concat es-sightings-1 es-sightings-2)
sighting0-id (:id es-sighting0)
sighting1-id (:id es-sighting1)
sighting-ids (map :id sightings)
updated-sighting-body (-> (:sightings minimal-examples)
first
(dissoc :id)
(assoc :description "UPDATED"))]
;; insert new entities in source store
(POST-bulk app new-malwares)
modify entities in first and second source indices
(let [response (PUT app
(format "ctia/sighting/%s" sighting0-id)
:body updated-sighting-body
:headers {"Authorization" "45c1f5e3f05d0"})]
(is (= 200 (:status response))
response))
(let [response (PUT app
(format "ctia/sighting/%s" sighting1-id)
:body updated-sighting-body
:headers {"Authorization" "45c1f5e3f05d0"})]
(is (= 200 (:status response))
response))
delete entities from first and second source indices
(doseq [sighting-id sighting-ids]
(let [response (DELETE app
(format "ctia/sighting/%s" sighting-id)
:headers {"Authorization" "45c1f5e3f05d0"})]
(is (= 204 (:status response))
response)))
(sut/migrate-store-indexes {:migration-id "test-2"
:prefix "0.0.0"
:migrations [:__test]
:store-keys (keys (all-stores))
;; small batch to check proper delete paging
:batch-size 2
:buffer-size 1
:confirm? true
:restart? true}
services)
(let [migration-state (get-migration "test-2" conn services)
malware-migration (get-in migration-state [:stores :malware])
sighting-migration (get-in migration-state [:stores :sighting])
malware-target-store (get-in malware-migration [:target :store])
{last-target-malwares :data} (fetch-batch malware-target-store 3 0 "desc" nil)
{:keys [conn indexname mapping]} (get-in sighting-migration [:target :store])
updated-sightings (-> (ductile.doc/query conn
indexname
(es-query/ids [sighting0-id sighting1-id])
{})
:data)
get-deleted-sightings (-> (ductile.doc/query conn
indexname
(es-query/ids sighting-ids)
{})
:data)]
(is (= (repeat 3 "INSERTED") (map :description last-target-malwares))
"inserted malwares must be found in target malware store")
(is (= (repeat 2 "UPDATED") (map :description updated-sightings))
"updated document must be updated in target stores")
(is (empty? get-deleted-sightings)
"deleted document must not be in target stores"))))))))
(defn load-test-fn
[app maximal?]
insert 20000 docs per entity - type
(try
(doseq [bundle (repeatedly 20 #(fixt/bundle 1000 maximal?))]
(POST-bulk app bundle))
(doseq [batch-size [1000 3000 6000 10000]
:let [{:keys [get-in-config]} (helpers/get-service-map app :ConfigService)
services (app->MigrationStoreServices app)
conn (es-conn get-in-config)
migration-id (format "test-load-%s" batch-size)
prefix (format "test_load_%s" batch-size)]]
(try
(let [total-docs (* (count @example-types) 20000)
_ (println (format "===== migrating %s documents with batch size %s"
total-docs
batch-size))
start (System/currentTimeMillis)
_ (sut/migrate-store-indexes {:migration-id migration-id
:prefix prefix
:migrations [:__test]
:store-keys (into [] example-types)
:batch-size batch-size
:buffer-size 3
:confirm? true
:restart? false}
services)
end (System/currentTimeMillis)
total (/ (- end start) 1000)
doc-per-sec (/ total-docs total)
migration-state (ductile.doc/get-doc conn
(migration-index get-in-config)
"migration"
migration-id
{})]
(println "total: " (float total))
(println "documents per seconds: " (float doc-per-sec))
(doseq [[_ state] (:stores migration-state)]
(is (= 20000
(get-in state [:source :total])
(get-in state [:target :migrated])))))
(finally
(es-index/delete! conn (format "v%s*" prefix))
(ductile.doc/delete-doc conn "migration" migration-id {:refresh "true"}))))
(finally
(es-index/delete! (es-conn (helpers/current-get-in-config-fn app)) "ctia_*"))))
;;(deftest ^:integration minimal-load-test
;; (with-each-fixtures identity app
;; (testing "load testing with minimal entities"
;; (println "load testing with minimal entities")
;; (load-test-fn app false))))
;;(deftest ^:integration maximal-load-test
;; (with-each-fixtures identity app
;; (testing "load testing with maximal entities"
;; (println "load testing with maximal entities")
;; (load-test-fn app true))))
| null |
https://raw.githubusercontent.com/threatgrid/ctia/8e306e63428d620d101ff9ce6e2eaf6ebf97b41b/test/ctia/task/migration/migrate_es_stores_test.clj
|
clojure
|
Note: goes _after_ fixture-ctia
insert malformed documents
insert proper documents
insert malformed documents
insert proper documents
prepare new malwares
insert new entities in source store
small batch to check proper delete paging
(deftest ^:integration minimal-load-test
(with-each-fixtures identity app
(testing "load testing with minimal entities"
(println "load testing with minimal entities")
(load-test-fn app false))))
(deftest ^:integration maximal-load-test
(with-each-fixtures identity app
(testing "load testing with maximal entities"
(println "load testing with maximal entities")
(load-test-fn app true))))
|
(ns ctia.task.migration.migrate-es-stores-test
(:require [clj-momo.lib.clj-time.coerce :as time-coerce]
[clj-momo.test-helpers.core :as mth]
[clojure.data :refer [diff]]
[clojure.java.io :as io]
[clojure.set :as set]
[clojure.string :as str]
[clojure.test :refer [deftest is join-fixtures testing use-fixtures]]
[clojure.walk :refer [keywordize-keys]]
[ctia.entity.relationship.schemas :refer [StoredRelationship]]
[ctia.stores.es.store :refer [store->map]]
[ctia.task.migration.migrate-es-stores :as sut]
[ctia.task.migration.store
:refer
[fetch-batch get-migration init-migration prefixed-index setup!]]
[ctia.task.rollover :refer [rollover-stores]]
[ctia.test-helpers.auth :refer [all-capabilities]]
[ctia.test-helpers.core
:as
helpers
:refer
[GET DELETE POST-bulk PUT with-atom-logger]]
[ctia.test-helpers.es :as es-helpers]
[ctia.test-helpers.fake-whoami-service :as whoami-helpers]
[ctia.test-helpers.fixtures :as fixt]
[ctia.test-helpers.migration :refer [app->MigrationStoreServices]]
[ctim.domain.id :refer [long-id->id]]
[ductile.conn :refer [connect]]
[ductile.document :as ductile.doc]
[ductile.index :as es-index]
[ductile.query :as es-query]
[schema.core :as s])
(:import clojure.lang.ExceptionInfo
java.lang.AssertionError
java.text.SimpleDateFormat
[java.util Date UUID]))
(defn fixture-setup! [f]
(let [app (helpers/get-current-app)
services (app->MigrationStoreServices app)]
(setup! services)
(f)))
(use-fixtures :once
(join-fixtures [mth/fixture-schema-validation
whoami-helpers/fixture-server
es-helpers/fixture-properties:es-store]))
(defn es-props [get-in-config]
(get-in-config [:ctia :store :es]))
(defn es-conn [get-in-config]
(connect (:default (es-props get-in-config))))
(defn migration-index [get-in-config]
(get-in-config [:ctia :migration :store :es :migration :indexname]))
(defn fixture-clean-migration [t]
(let [app (helpers/get-current-app)
{:keys [get-in-config]} (helpers/get-service-map app :ConfigService)]
(try
(t)
(finally
(doto (es-conn get-in-config)
(es-index/delete! "v0.0.0*")
(es-index/delete! (str (migration-index get-in-config) "*")))))))
(s/defn with-each-fixtures*
"Wrap this function around each deftest instead of use-fixtures
so the TK config can be transformed before helpers/fixture-ctia
starts the app."
[config-transformer body-fn :- (s/=> s/Any (s/=> s/Any (s/named s/Any 'app)))]
(let [fixtures (join-fixtures [helpers/fixture-ctia
es-helpers/fixture-delete-store-indexes
fixture-clean-migration])]
(helpers/with-config-transformer*
config-transformer
#(fixtures
(fn []
(body-fn (helpers/get-current-app)))))))
(defmacro with-each-fixtures
"Primarily for check-migration-params-test. Binds `app` to current TK app."
[config-transformer app & body]
(assert (simple-symbol? app) (pr-str app))
`(with-each-fixtures* ~config-transformer
(fn [~app]
(do ~@body))))
(defn index-exists?
[store prefix]
(let [{:keys [conn indexname]} (store->map store {})]
(es-index/index-exists? conn
(prefixed-index indexname prefix))))
(def fixtures-nb 100)
(def updates-nb 50)
(def minimal-examples (fixt/bundle fixtures-nb false))
(def example-types
(->> (vals minimal-examples)
(map #(-> % first :type keyword))
set))
(defn update-entity
[app
{entity-type :type
entity-id :short-id}]
(let [entity-path (format "ctia/%s/%s" (str entity-type) entity-id)
previous (-> (GET app
entity-path
:headers {"Authorization" "45c1f5e3f05d0"})
:parsed-body)]
(PUT app
entity-path
:body (assoc previous :description "UPDATED")
:headers {"Authorization" "45c1f5e3f05d0"})))
(defn random-updates
"select nb random entities of the bulk and update them"
[app bulk-result nb]
(let [random-ids (->> (select-keys bulk-result
[:malwares
:sightings
:indicators
:vulnerabilities])
vals
(apply concat)
shuffle
(take nb)
(map long-id->id))]
(doseq [entity random-ids]
(update-entity app entity))))
(defn rollover-post-bulk
"post data in 2 parts with rollover, randomly update son entities"
[app all-stores]
(let [bulk-res-1 (POST-bulk app (fixt/bundle (/ fixtures-nb 2) false))
_ (rollover-stores (all-stores))
bulk-res-2 (POST-bulk app (fixt/bundle (/ fixtures-nb 2) false))
_ (rollover-stores (all-stores))]
(random-updates app bulk-res-1 (/ updates-nb 2))
(random-updates app bulk-res-2 (/ updates-nb 2))))
(deftest check-migration-params-test
(let [migration-params {:migration-id "id"
:prefix "1.2.0"
:migrations [:identity]
:store-keys [:incident :investigation :malware]
:batch-size 100
:buffer-size 3
:confirm? true
:restart? false}]
(testing "misconfigured migration"
(let [investigation-indexname (str "v1.2.0_ctia_investigation" (UUID/randomUUID))
malware-indexname (str "v1.2.0_ctia_malware" (UUID/randomUUID))]
(with-each-fixtures #(-> %
(assoc-in [:ctia :store :es :investigation :indexname]
investigation-indexname)
(assoc-in [:malware 0 :state :props :indexname]
malware-indexname))
app
(let [{:keys [get-in-config]} (helpers/get-service-map app :ConfigService)]
(let [v (get-in-config [:ctia :store :es :investigation :indexname])]
(assert (= v investigation-indexname)
[v investigation-indexname]))
(let [v (get-in-config [:malware 0 :state :props :indexname])]
(assert (= v malware-indexname)
[v malware-indexname]))
(is (thrown? AssertionError
(sut/check-migration-params migration-params
get-in-config))
"source and target store must be different")))
(with-each-fixtures identity app
(let [{:keys [get-in-config]} (helpers/get-service-map app :ConfigService)]
(is (thrown? ExceptionInfo
(sut/check-migration-params (update migration-params
:migrations
conj
:bad-migration-id)
get-in-config))))))
(testing "properly configured migration"
(with-each-fixtures identity app
(let [{:keys [get-in-config]} (helpers/get-service-map app :ConfigService)]
(is (sut/check-migration-params migration-params
get-in-config))))))))
(deftest prepare-params-test
(let [migration-props {:buffer-size 3,
:batch-size 100,
:migration-id "migration-test",
:restart? false,
:store-keys "malware, tool,sighting ",
:migrations "identity",
:confirm? false,
:prefix "v1.2.0"}
prepared (sut/prepare-params migration-props)]
(testing "prepare params should properly format migration properties"
(is (= (dissoc prepared :store-keys :migrations)
(dissoc migration-props :store-keys :migrations)))
(is (= (:store-keys prepared)
[:malware :tool :sighting]))
(is (= (:migrations prepared)
[:identity])))))
(deftest migration-with-rollover
(with-each-fixtures identity app
(testing "migration with rollover and multiple indices for source stores"
(let [{:keys [get-in-config]} (helpers/get-service-map app :ConfigService)
{:keys [all-stores]} (helpers/get-service-map app :StoreService)
services (app->MigrationStoreServices app)
conn (es-conn get-in-config)
store-types [:malware :tool :incident]]
(helpers/set-capabilities! app
"foouser"
["foogroup"]
"user"
all-capabilities)
(whoami-helpers/set-whoami-response app
"45c1f5e3f05d0"
"foouser"
"foogroup"
"user")
(rollover-post-bulk app all-stores)
(doseq [store-type store-types]
(es-index/get conn
(str (get-in (es-props get-in-config) [store-type :indexname]) "*")))
(sut/migrate-store-indexes {:migration-id "test-3"
:prefix "0.0.0"
:migrations [:__test]
:store-keys store-types
:batch-size 10
:buffer-size 3
:confirm? true
:restart? false}
services)
(let [migration-state (ductile.doc/get-doc conn
(migration-index get-in-config)
"migration"
"test-3"
{})]
(doseq [store-type store-types]
(is (= (count (es-index/get conn
(str "v0.0.0_" (get-in (es-props get-in-config) [store-type :indexname]) "*")))
3)
"target index should be rolled over during migration")
(es-index/get conn
(str "v0.0.0_" (get-in (es-props get-in-config) [store-type :indexname]) "*"))
(let [migrated-store (get-in migration-state [:stores store-type])
{:keys [source target]} migrated-store]
(is (= fixtures-nb (:total source)))
(is (= fixtures-nb (:migrated target))))))))))
(def date-str->epoch-millis
(comp time-coerce/to-long time-coerce/to-date-time))
(deftest read-source-batch-test
(with-each-fixtures identity app
(with-open [rdr (io/reader "./test/data/indices/sample-relationships-1000.json")]
(let [{:keys [get-in-config]} (helpers/get-service-map app :ConfigService)
conn (es-conn get-in-config)
storemap {:conn conn
:indexname (es-helpers/get-indexname app :relationship)
:mapping "relationship"
:props {:write-index (es-helpers/get-indexname app :relationship)}
:type "relationship"
:settings {}
:config {}}
docs (map (partial es-helpers/prepare-bulk-ops app)
(line-seq rdr))
_ (es-helpers/load-bulk conn docs)
no-meta-docs (map #(dissoc % :_index :_type :_id)
docs)
docs-no-modified (filter #(nil? (:modified %))
no-meta-docs)
docs-100 (take 100 no-meta-docs)
missing-query {:bool {:must_not {:exists {:field :modified}}}}
ids-100-query {:ids {:values (map :id docs-100)}}
match-all-query {:match_all {}}
nb-skipped-ids 10
[last-skipped & expected-ids-docs] (->> (sort-by (juxt :modified :created :id)
docs-100)
(drop (dec nb-skipped-ids)))
{after-modified :modified
after-created :created
after-id :id} last-skipped
search_after [(date-str->epoch-millis after-modified)
(date-str->epoch-millis after-created)
after-id]
read-params-1 {:source-store storemap
:batch-size 1000
:query missing-query}
read-params-2 {:source-store storemap
:batch-size 100
:search_after search_after
:query ids-100-query}
read-params-3 {:source-store storemap
:batch-size 400
:query match-all-query}
missing-res (sut/read-source-batch read-params-1)
ids-res (sut/read-source-batch read-params-2)
match-all-res (rest (iterate sut/read-source-batch read-params-3))]
(testing "queries should be used to select data"
(is (= (set docs-no-modified)
(set (:documents missing-res)))))
(testing "search_after should be properly taken into account"
(is (= (set expected-ids-docs)
(set (:documents ids-res))))
(is (= (- 100 nb-skipped-ids)
(count (:documents ids-res)))))
(testing "read source should return parameters for next call"
(is (= read-params-1
(dissoc missing-res :search_after :documents)))
(is (= (dissoc read-params-2 :search_after)
(dissoc ids-res :search_after :documents))))
(testing "read-source-batch shoould return nil when parameters map is nil or the query result is empty"
(is (= nil
(sut/read-source-batch nil)
(sut/read-source-batch (assoc read-params-1
:batch-size
0)))))
(testing "read-source-batch result should be usable to call read-source-batch again for scrolling given query"
(is (= '(400 400 200 0)
(->> (take 4 match-all-res)
(map #(-> % :documents count)))))
(is (= (set no-meta-docs)
(->> (take 4 match-all-res)
(map :documents)
(apply concat)
set))))))))
(deftest read-source-test
(with-each-fixtures identity app
(testing "read-source should produce a lazy seq from recursive read-source-batch calls"
(let [counter (atom 0)]
(with-redefs [sut/read-source-batch (fn [batch-params]
(when (< @counter 5)
(swap! counter inc)
(update batch-params :migrated-count inc)))]
(let [batches (map :migrated-count
(sut/read-source {:migrated-count 0}))]
(is (= '(1 2) (take 2 batches)))
(is (= 2 @counter))
(is (= '(1 2 3 4 5) (take 10 batches)))
(is (= 5 @counter))))))))
(deftest write-target-test
(with-each-fixtures identity app
(with-open [rdr (io/reader "./test/data/indices/sample-relationships-1000.json")]
(let [{:keys [get-in-config]} (helpers/get-service-map app :ConfigService)
services (app->MigrationStoreServices app)
prefix "0.0.1"
indexname (str "v0.0.1_" (es-helpers/get-indexname app :relationship))
conn (es-conn get-in-config)
storemap {:conn conn
:indexname indexname
:mapping "relationship"
:props {:write-index indexname}
:type "relationship"
:settings {}
:config {}}
list-coerce (sut/list-coerce-fn StoredRelationship)
migration-id "migration-1"
docs (map (comp :_source es-helpers/str->doc)
(line-seq rdr))
base-params {:target-store storemap
:entity-type :relationship
:list-coerce list-coerce
:migration-id migration-id
:migrations (sut/compose-migrations [:__test])
:batch-size 1000
:migration-es-conn conn
:confirm? true}
test-fn (fn [total
migrated-count
msg
{:keys [confirm?]
:as override-params}]
(init-migration {:migration-id migration-id
:prefix prefix
:store-keys [:relationship]
:confirm? true
:migrations [:__test]
:batch-size 1000
:buffer-size 3
:restart? false}
services)
(let [test-docs (take total docs)
search_after [(rand-int total)]
batch-params (-> (into base-params
override-params)
(assoc :documents test-docs
:search_after search_after))
nb-migrated (sut/write-target migrated-count
batch-params
services)
{target-state :target
source-state :source} (-> (get-migration migration-id
conn
services)
:stores
:relationship)
_ (es-index/refresh! conn)
migrated-docs (:data (ductile.doc/query conn
indexname
{:match_all {}}
{:limit total}))]
(testing msg
(when-not confirm?
(is (= (+ total migrated-count)
nb-migrated))
(is (= (count migrated-docs)
(:migrated target-state))))
(when confirm?
(is (= (+ total migrated-count)
(+ (count migrated-docs) migrated-count)
nb-migrated
(:migrated target-state)))
(is (= (set (map #(dissoc % :groups)
migrated-docs))
(set (map #(dissoc % :groups)
test-docs)))
"write-target should only perform attended modifications")
(is (every? #(= (:groups %)
["migration-test"])
migrated-docs)
"write-target should perform attended modifications on migrated documents")
(is (= search_after
(:search_after source-state))
"write-target should store last search_after in migration state")))))]
(test-fn 100
0
"write-target should properly modify documents, and write them in target index"
{:confirm? true})
(test-fn 100
10
"write-target should properly accumulate migration count"
{:confirm? true})
(test-fn 100
0
"write-target should not write anything while properly simulating migration when `confirm?` is set to false"
{:confirm? false})))))
(deftest sliced-migration-test
(with-each-fixtures identity app
(with-open [rdr (io/reader "./test/data/indices/sample-relationships-1000.json")]
(let [{:keys [get-in-config]} (helpers/get-service-map app :ConfigService)
services (app->MigrationStoreServices app)
conn (es-conn get-in-config)
{wo-modified true
w-modified false} (->> (line-seq rdr)
(map (partial es-helpers/prepare-bulk-ops app))
(group-by #(nil? (:modified %))))
sorted-w-modified (sort-by :modified w-modified)
bulk-1 (concat wo-modified (take 500 sorted-w-modified))
bulk-2 (drop 500 sorted-w-modified)
logger-1 (atom [])
_ (es-helpers/load-bulk conn bulk-1)
_ (with-atom-logger logger-1
(sut/migrate-store-indexes {:migration-id "migration-test-4"
:prefix "0.0.0"
:migrations [:__test]
:store-keys [:relationship]
:batch-size 100
:buffer-size 3
:confirm? true
:restart? false}
services))
migration-state-1 (ductile.doc/get-doc conn
(migration-index get-in-config)
"migration"
"migration-test-4"
{})
target-count-1 (ductile.doc/count-docs conn
(str "v0.0.0_"
(es-helpers/get-indexname app :relationship))
nil)
_ (es-helpers/load-bulk conn bulk-2)
_ (with-atom-logger logger-1
(sut/migrate-store-indexes {:migration-id "migration-test-4"
:prefix "0.0.0"
:migrations [:__test]
:store-keys [:relationship]
:batch-size 100
:buffer-size 3
:confirm? true
:restart? true}
services))
target-count-2 (ductile.doc/count-docs conn
(str "v0.0.0_"
(es-helpers/get-indexname app :relationship))
nil)
migration-state-2 (ductile.doc/get-doc conn
(migration-index get-in-config)
"migration"
"migration-test-4"
{})]
(is (= (+ 500 (count wo-modified))
target-count-1
(get-in migration-state-1 [:stores :relationship :target :migrated])
(get-in migration-state-1 [:stores :relationship :source :total]))
"migration process should start with documents missing field used for bucketizing")
(is (= 1000
target-count-2
(get-in migration-state-2 [:stores :relationship :source :total]))
"migration process should complete the migration after restart")))))
(deftest migration-with-malformed-docs
(with-each-fixtures identity app
(testing "migration with malformed documents in store"
(let [{:keys [get-in-config]} (helpers/get-service-map app :ConfigService)
{:keys [all-stores]} (helpers/get-service-map app :StoreService)
services (app->MigrationStoreServices app)
conn (es-conn get-in-config)
store-types [:malware :tool :incident]
logger (atom [])
bad-doc {:id 1
:hey "I"
:am "a"
:bad "document"}]
(helpers/set-capabilities! app
"foouser"
["foogroup"]
"user"
all-capabilities)
(whoami-helpers/set-whoami-response app
"45c1f5e3f05d0"
"foouser"
"foogroup"
"user")
(rollover-post-bulk app all-stores)
(doseq [store-type store-types]
(ductile.doc/create-doc conn
(str (get-in (es-props get-in-config) [store-type :indexname]) "-write")
(name store-type)
bad-doc
{:refresh "true"}))
(with-atom-logger logger
(sut/migrate-store-indexes {:migration-id "test-3"
:prefix "0.0.0"
:migrations [:__test]
:store-keys store-types
:batch-size 10
:buffer-size 3
:confirm? true
:restart? false}
services))
(let [messages (set @logger)
migration-state (ductile.doc/get-doc conn
(migration-index get-in-config)
"migration"
"test-3"
{})]
(doseq [store-type store-types]
(let [migrated-store (get-in migration-state [:stores store-type])
{:keys [source target]} migrated-store]
(is (= (inc fixtures-nb) (:total source)))
(is (= fixtures-nb (:migrated target))))
(is (some #(str/starts-with? % (format "%s - Cannot migrate entity: {"
(name store-type)))
messages)
(format "malformed %s was not logged" store-type))))))))
(deftest test-migrate-store-indexes
(with-each-fixtures identity app
TODO clean data
(let [{:keys [get-in-config]} (helpers/get-service-map app :ConfigService)
{:keys [all-stores]} (helpers/get-service-map app :StoreService)
services (app->MigrationStoreServices app)
conn (es-conn get-in-config)]
(helpers/set-capabilities! app
"foouser"
["foogroup"]
"user"
all-capabilities)
(whoami-helpers/set-whoami-response app
"45c1f5e3f05d0"
"foouser"
"foogroup"
"user")
(rollover-post-bulk app all-stores)
(testing "migrate ES Stores test setup"
(testing "simulate migrate es indexes shall not create any document"
(sut/migrate-store-indexes {:migration-id "test-1"
:prefix "0.0.0"
:migrations [:0.4.16]
:store-keys (keys (all-stores))
:batch-size 10
:buffer-size 3
:confirm? false
:restart? false}
services)
(doseq [store (vals (all-stores))]
(is (not (index-exists? store "0.0.0"))))
(is (nil? (seq (ductile.doc/get-doc conn
(migration-index get-in-config)
"migration"
"test-1"
{})))))))
(testing "migrate es indexes"
(let [{:keys [get-in-config]} (helpers/get-service-map app :ConfigService)
{:keys [all-stores]} (helpers/get-service-map app :StoreService)
services (app->MigrationStoreServices app)
conn (es-conn get-in-config)
logger (atom [])]
(with-atom-logger logger
(sut/migrate-store-indexes {:migration-id "test-2"
:prefix "0.0.0"
:migrations [:__test]
:store-keys (keys (all-stores))
:batch-size 10
:buffer-size 3
:confirm? true
:restart? false}
services))
(testing "shall generate a proper migration state"
(let [migration-state (ductile.doc/get-doc conn
(migration-index get-in-config)
"migration"
"test-2"
{})]
(is (= (set (keys (all-stores)))
(set (keys (:stores migration-state)))))
(doseq [[entity-type migrated-store] (:stores migration-state)]
(let [{:keys [source target started completed]} migrated-store
source-size
(cond
(= :identity entity-type) 1
(= :event entity-type) (+ updates-nb
(* fixtures-nb
(count minimal-examples)))
(contains? example-types (keyword entity-type)) fixtures-nb
:else 0)]
(is (= source-size (:total source))
(str "source size match for " (:index source)))
(is (not (nil? started)))
(is (not (nil? completed)))
(is (<= (:migrated target) (:total source)))
(is (int? (:total source)))
(is (= (:index target)
(prefixed-index (:index source) "0.0.0")))))))
(testing "shall produce valid logs"
(let [messages (set @logger)]
(is (contains? messages "set batch size: 10"))
(is (set/subset?
#{"campaign - finished migrating 100 documents"
"indicator - finished migrating 100 documents"
(format "event - finished migrating %s documents"
(+ 2000 updates-nb))
"actor - finished migrating 100 documents"
"asset - finished migrating 100 documents"
"relationship - finished migrating 100 documents"
"incident - finished migrating 100 documents"
"investigation - finished migrating 100 documents"
"coa - finished migrating 100 documents"
"identity - finished migrating 0 documents"
"judgement - finished migrating 100 documents"
"note - finished migrating 100 documents"
"data-table - finished migrating 0 documents"
"feedback - finished migrating 0 documents"
"casebook - finished migrating 100 documents"
"sighting - finished migrating 100 documents"
"identity-assertion - finished migrating 0 documents"
"attack-pattern - finished migrating 100 documents"
"malware - finished migrating 100 documents"
"target-record - finished migrating 100 documents"
"tool - finished migrating 100 documents"
"vulnerability - finished migrating 100 documents"
"weakness - finished migrating 100 documents" }
messages))))
(testing "shall produce new indices with enough documents and the right transforms"
(let [{:keys [default
asset
target-record
relationship
judgement
investigation
coa
tool
attack-pattern
malware
incident
indicator
campaign
sighting
casebook
actor
vulnerability
weakness]}
(get-in-config [:ctia :store :es])
date (Date.)
index-date (.format (SimpleDateFormat. "yyyy.MM.dd") date)
expected-event-indices {(format "v0.0.0_%s-%s-000001"
(es-helpers/get-indexname app :event)
index-date)
1000
(format "v0.0.0_%s-%s-000002"
(es-helpers/get-indexname app :event)
index-date)
(+ 950 updates-nb)}
expected-indices
(->> #{relationship
target-record
judgement
coa
attack-pattern
malware
tool
incident
indicator
investigation
campaign
casebook
sighting
actor
vulnerability
weakness}
(map (fn [k]
{(format "v0.0.0_%s-%s-000001" (:indexname k) index-date) 50
(format "v0.0.0_%s-%s-000002" (:indexname k) index-date) 50
(format "v0.0.0_%s-%s-000003" (:indexname k) index-date) 0}))
(into expected-event-indices)
keywordize-keys)
_ (es-index/refresh! conn)
formatted-cat-indices (es-helpers/get-cat-indices conn)
result-indices (select-keys formatted-cat-indices
(keys expected-indices))]
(is (= expected-indices result-indices)
(let [[only-expected only-result _]
(diff expected-indices result-indices)]
(format "only in expected ==> %s\nonly in result ==> %s"
only-expected
only-result)))
(doseq [[index _]
expected-indices]
(let [docs (->> (ductile.doc/search-docs conn (name index) nil nil {})
:data
(map :groups))]
(is (every? #(= ["migration-test"] %)
docs))))))
(testing "restart migration shall properly handle inserts, updates and deletes"
retrieve the first 2 source indices for sighting store
[sighting-index-1 sighting-index-2 :as sighting-indices]
(->> (es-helpers/get-cat-indices conn)
keys
(map name)
(filter #(.contains ^String % "sighting"))
sort
(take 2))
_ (assert (= 2 (count sighting-indices)) sighting-indices)
retrieve source entity to update , in first position of first index
es-sighting0 (-> (ductile.doc/query conn
sighting-index-1
{:match_all {}}
{:sort_by "timestamp:asc"
:size 1})
:data
first)
retrieve source entity to update , in first position of second index
es-sighting1 (-> (ductile.doc/query conn
sighting-index-2
{:match_all {}}
{:sort_by "timestamp:asc"
:size 1})
:data
first)
new-malwares {:malwares (->> (fixt/n-examples :malware 3 false)
(map #(assoc % :description "INSERTED")))}
retrieve 5 source entities to delete , in last positions of first index
es-sightings-1 (-> (ductile.doc/query conn
sighting-index-1
{:match_all {}}
{:sort_by "timestamp:desc"
:limit 5})
:data)
retrieve 5 source entities to delete , in last positions of second index
es-sightings-2 (-> (ductile.doc/query conn
sighting-index-2
{:match_all {}}
{:sort_by "timestamp:desc"
:limit 5})
:data)
sightings (concat es-sightings-1 es-sightings-2)
sighting0-id (:id es-sighting0)
sighting1-id (:id es-sighting1)
sighting-ids (map :id sightings)
updated-sighting-body (-> (:sightings minimal-examples)
first
(dissoc :id)
(assoc :description "UPDATED"))]
(POST-bulk app new-malwares)
modify entities in first and second source indices
(let [response (PUT app
(format "ctia/sighting/%s" sighting0-id)
:body updated-sighting-body
:headers {"Authorization" "45c1f5e3f05d0"})]
(is (= 200 (:status response))
response))
(let [response (PUT app
(format "ctia/sighting/%s" sighting1-id)
:body updated-sighting-body
:headers {"Authorization" "45c1f5e3f05d0"})]
(is (= 200 (:status response))
response))
delete entities from first and second source indices
(doseq [sighting-id sighting-ids]
(let [response (DELETE app
(format "ctia/sighting/%s" sighting-id)
:headers {"Authorization" "45c1f5e3f05d0"})]
(is (= 204 (:status response))
response)))
(sut/migrate-store-indexes {:migration-id "test-2"
:prefix "0.0.0"
:migrations [:__test]
:store-keys (keys (all-stores))
:batch-size 2
:buffer-size 1
:confirm? true
:restart? true}
services)
(let [migration-state (get-migration "test-2" conn services)
malware-migration (get-in migration-state [:stores :malware])
sighting-migration (get-in migration-state [:stores :sighting])
malware-target-store (get-in malware-migration [:target :store])
{last-target-malwares :data} (fetch-batch malware-target-store 3 0 "desc" nil)
{:keys [conn indexname mapping]} (get-in sighting-migration [:target :store])
updated-sightings (-> (ductile.doc/query conn
indexname
(es-query/ids [sighting0-id sighting1-id])
{})
:data)
get-deleted-sightings (-> (ductile.doc/query conn
indexname
(es-query/ids sighting-ids)
{})
:data)]
(is (= (repeat 3 "INSERTED") (map :description last-target-malwares))
"inserted malwares must be found in target malware store")
(is (= (repeat 2 "UPDATED") (map :description updated-sightings))
"updated document must be updated in target stores")
(is (empty? get-deleted-sightings)
"deleted document must not be in target stores"))))))))
(defn load-test-fn
[app maximal?]
insert 20000 docs per entity - type
(try
(doseq [bundle (repeatedly 20 #(fixt/bundle 1000 maximal?))]
(POST-bulk app bundle))
(doseq [batch-size [1000 3000 6000 10000]
:let [{:keys [get-in-config]} (helpers/get-service-map app :ConfigService)
services (app->MigrationStoreServices app)
conn (es-conn get-in-config)
migration-id (format "test-load-%s" batch-size)
prefix (format "test_load_%s" batch-size)]]
(try
(let [total-docs (* (count @example-types) 20000)
_ (println (format "===== migrating %s documents with batch size %s"
total-docs
batch-size))
start (System/currentTimeMillis)
_ (sut/migrate-store-indexes {:migration-id migration-id
:prefix prefix
:migrations [:__test]
:store-keys (into [] example-types)
:batch-size batch-size
:buffer-size 3
:confirm? true
:restart? false}
services)
end (System/currentTimeMillis)
total (/ (- end start) 1000)
doc-per-sec (/ total-docs total)
migration-state (ductile.doc/get-doc conn
(migration-index get-in-config)
"migration"
migration-id
{})]
(println "total: " (float total))
(println "documents per seconds: " (float doc-per-sec))
(doseq [[_ state] (:stores migration-state)]
(is (= 20000
(get-in state [:source :total])
(get-in state [:target :migrated])))))
(finally
(es-index/delete! conn (format "v%s*" prefix))
(ductile.doc/delete-doc conn "migration" migration-id {:refresh "true"}))))
(finally
(es-index/delete! (es-conn (helpers/current-get-in-config-fn app)) "ctia_*"))))
|
0b5466c6912a78b623249d87002e37afe3f14937fa3292a55448d8d0eaeff212
|
Jell/euroclojure-2016
|
localization.cljs
|
(ns euroclojure.localization)
(defn slide [{:keys [speaker]}]
[:div.slide.left
[:h1.centered "Localization"]])
| null |
https://raw.githubusercontent.com/Jell/euroclojure-2016/a8ca883e8480a4616ede19995aaacd4a495608af/src/euroclojure/localization.cljs
|
clojure
|
(ns euroclojure.localization)
(defn slide [{:keys [speaker]}]
[:div.slide.left
[:h1.centered "Localization"]])
|
|
14dd6f869e9250e706a1bb1bb15966e91c115092c2a129db20b9fd3e0f05e50c
|
racketscript/racketscript
|
require-provide.rkt
|
#lang racket/base
(provide add sub)
(require racket/string)
(require racket/list racket/base)
(define (add a b)
(+ a b))
(define (sub a b)
(- a b))
require protected i d , see
(require "protect-out.rkt")
(displayln (f 10))
| null |
https://raw.githubusercontent.com/racketscript/racketscript/8505512292f268e03c6e33e82978e3333d7c5b22/tests/basic/require-provide.rkt
|
racket
|
#lang racket/base
(provide add sub)
(require racket/string)
(require racket/list racket/base)
(define (add a b)
(+ a b))
(define (sub a b)
(- a b))
require protected i d , see
(require "protect-out.rkt")
(displayln (f 10))
|
|
39fe95c2596aabd6080f7fc093566d064fb41c01fce27d064b506a18eaba8d74
|
rescript-association/genType
|
GenTypeCommon.ml
|
module StringMap = Map.Make (String)
module StringSet = Set.Make (String)
module Config = Config_
include Config
let logNotImplemented x =
if !Debug.notImplemented then Log_.item "Not Implemented: %s\n" x
type optional = Mandatory | Optional
type mutable_ = Immutable | Mutable
type labelJS =
| BoolLabel of bool
| FloatLabel of string
| IntLabel of string
| StringLabel of string
type case = {label : string; labelJS : labelJS}
let isJSSafePropertyName name =
let jsSafeRegex = {|^[A-z][A-z0-9]*$|} |> Str.regexp in
Str.string_match jsSafeRegex name 0
let labelJSToString ?(alwaysQuotes = false) case =
let addQuotes x =
match alwaysQuotes with true -> x |> EmitText.quotes | false -> x
in
let isNumber s =
let len = String.length s in
len > 0
&& (match len > 1 with true -> s.[0] > '0' | false -> true)
&&
let res = ref true in
for i = 0 to len - 1 do
match s.[i] with '0' .. '9' -> () | _ -> res := false
done;
res.contents
in
match case.labelJS with
| BoolLabel b -> b |> string_of_bool |> addQuotes
| FloatLabel s -> s |> addQuotes
| IntLabel i -> i |> addQuotes
| StringLabel s ->
if s = case.label && isNumber s then s |> addQuotes
else s |> EmitText.quotes
type closedFlag = Open | Closed
type type_ =
| Array of type_ * mutable_
| Function of function_
| GroupOfLabeledArgs of fields
| Ident of ident
| Null of type_
| Nullable of type_
| Object of closedFlag * fields
| Option of type_
| Promise of type_
| Record of fields
| Tuple of type_ list
| TypeVar of string
| Variant of variant
and fields = field list
and argType = {aName : string; aType : type_}
and field = {
mutable_ : mutable_;
nameJS : string;
nameRE : string;
optional : optional;
type_ : type_;
}
and function_ = {
argTypes : argType list;
componentName : string option;
retType : type_;
typeVars : string list;
uncurried : bool;
}
and ident = {builtin : bool; name : string; typeArgs : type_ list}
and variant = {
bsStringOrInt : bool;
hash : int;
inherits : type_ list;
noPayloads : case list;
payloads : payload list;
polymorphic : bool;
unboxed : bool;
}
and payload = {case : case; inlineRecord : bool; numArgs : int; t : type_}
let typeIsObject type_ =
match type_ with
| Array _ -> true
| Function _ -> false
| GroupOfLabeledArgs _ -> false
| Ident _ -> false
| Null _ -> false
| Nullable _ -> false
| Object _ -> true
| Option _ -> false
| Promise _ -> true
| Record _ -> true
| Tuple _ -> true
| TypeVar _ -> false
| Variant _ -> false
type label = Nolabel | Label of string | OptLabel of string
type dep =
| External of string
| Internal of ResolvedName.t
| Dot of dep * string
module ScopedPackage = (* Taken from ext_namespace.ml in bukclescript *)
struct
let namespace_of_package_name (s : string) : string =
let len = String.length s in
let buf = Buffer.create len in
let add capital ch =
Buffer.add_char buf (if capital then Char.uppercase_ascii ch else ch)
in
let rec aux capital off len =
if off >= len then ()
else
let ch = String.unsafe_get s off in
match ch with
| 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' ->
add capital ch;
aux false (off + 1) len
| '/' | '-' -> aux true (off + 1) len
| _ -> aux capital (off + 1) len
in
aux true 0 len;
Buffer.contents buf
(** @demo/some-library -> DemoSomelibrary *)
let packageNameToGeneratedModuleName packageName =
if String.contains packageName '/' then
Some (packageName |> namespace_of_package_name)
else None
let isGeneratedModule id ~config =
config.bsDependencies
|> List.exists (fun packageName ->
packageName |> packageNameToGeneratedModuleName
= Some (id |> Ident.name))
* ( Common , DemoSomelibrary ) - > Common - DemoSomelibrary
let addGeneratedModule s ~generatedModule =
s ^ "-" ^ Ident.name generatedModule
(** Common-DemoSomelibrary -> Common *)
let removeGeneratedModule s =
match s |> String.split_on_char '-' with [name; _scope] -> name | _ -> s
end
let rec depToString dep =
match dep with
| External name -> name |> ScopedPackage.removeGeneratedModule
| Internal resolvedName -> resolvedName |> ResolvedName.toString
| Dot (d, s) -> depToString d ^ "_" ^ s
let rec depToResolvedName (dep : dep) =
match dep with
| External name -> name |> ResolvedName.fromString
| Internal resolvedName -> resolvedName
| Dot (p, s) -> ResolvedName.dot s (p |> depToResolvedName)
let createVariant ~bsStringOrInt ~inherits ~noPayloads ~payloads ~polymorphic =
let hash =
noPayloads
|> List.map (fun case -> (case.label, case.labelJS))
|> Array.of_list |> Hashtbl.hash
in
let unboxed = payloads = [] in
Variant
{bsStringOrInt; hash; inherits; noPayloads; payloads; polymorphic; unboxed}
let variantTable hash ~toJS =
(match toJS with true -> "$$toJS" | false -> "$$toRE") ^ string_of_int hash
let ident ?(builtin = true) ?(typeArgs = []) name =
Ident {builtin; name; typeArgs}
let sanitizeTypeName name = name |> Str.global_replace (Str.regexp "'") "_"
let mixedOrUnknown ~config =
ident
(match config.language with
| Flow -> "mixed"
| TypeScript | Untyped -> "unknown")
let booleanT = ident "boolean"
let dateT = ident "Date"
let numberT = ident "number"
let stringT = ident "string"
let unitT = ident "void"
let int64T = Tuple [numberT; numberT]
module NodeFilename = struct
include Filename
(* Force "/" separator. *)
let dirSep = "/"
module Path : sig
type t
val normalize : string -> t
val concat : t -> string -> t
val toString : t -> string
end = struct
type t = string
let normalize path : t =
match Sys.os_type with
| "Win32" -> path |> Str.split (Str.regexp "\\") |> String.concat dirSep
| _ -> path
let toString path = path
let length path = String.length path
let concat dirname filename =
let isDirSep s i =
let c = s.[i] in
c = '/' || c = '\\' || c = ':'
in
let l = length dirname in
if l = 0 || isDirSep dirname (l - 1) then dirname ^ filename
else dirname ^ dirSep ^ filename
end
let concat (dirname : string) filename =
let open Path in
Path.concat (normalize dirname) filename |> toString
end
| null |
https://raw.githubusercontent.com/rescript-association/genType/c19a86c13f0f05c983cce5794540a7c30a0c02a1/src/GenTypeCommon.ml
|
ocaml
|
Taken from ext_namespace.ml in bukclescript
* @demo/some-library -> DemoSomelibrary
* Common-DemoSomelibrary -> Common
Force "/" separator.
|
module StringMap = Map.Make (String)
module StringSet = Set.Make (String)
module Config = Config_
include Config
let logNotImplemented x =
if !Debug.notImplemented then Log_.item "Not Implemented: %s\n" x
type optional = Mandatory | Optional
type mutable_ = Immutable | Mutable
type labelJS =
| BoolLabel of bool
| FloatLabel of string
| IntLabel of string
| StringLabel of string
type case = {label : string; labelJS : labelJS}
let isJSSafePropertyName name =
let jsSafeRegex = {|^[A-z][A-z0-9]*$|} |> Str.regexp in
Str.string_match jsSafeRegex name 0
let labelJSToString ?(alwaysQuotes = false) case =
let addQuotes x =
match alwaysQuotes with true -> x |> EmitText.quotes | false -> x
in
let isNumber s =
let len = String.length s in
len > 0
&& (match len > 1 with true -> s.[0] > '0' | false -> true)
&&
let res = ref true in
for i = 0 to len - 1 do
match s.[i] with '0' .. '9' -> () | _ -> res := false
done;
res.contents
in
match case.labelJS with
| BoolLabel b -> b |> string_of_bool |> addQuotes
| FloatLabel s -> s |> addQuotes
| IntLabel i -> i |> addQuotes
| StringLabel s ->
if s = case.label && isNumber s then s |> addQuotes
else s |> EmitText.quotes
type closedFlag = Open | Closed
type type_ =
| Array of type_ * mutable_
| Function of function_
| GroupOfLabeledArgs of fields
| Ident of ident
| Null of type_
| Nullable of type_
| Object of closedFlag * fields
| Option of type_
| Promise of type_
| Record of fields
| Tuple of type_ list
| TypeVar of string
| Variant of variant
and fields = field list
and argType = {aName : string; aType : type_}
and field = {
mutable_ : mutable_;
nameJS : string;
nameRE : string;
optional : optional;
type_ : type_;
}
and function_ = {
argTypes : argType list;
componentName : string option;
retType : type_;
typeVars : string list;
uncurried : bool;
}
and ident = {builtin : bool; name : string; typeArgs : type_ list}
and variant = {
bsStringOrInt : bool;
hash : int;
inherits : type_ list;
noPayloads : case list;
payloads : payload list;
polymorphic : bool;
unboxed : bool;
}
and payload = {case : case; inlineRecord : bool; numArgs : int; t : type_}
let typeIsObject type_ =
match type_ with
| Array _ -> true
| Function _ -> false
| GroupOfLabeledArgs _ -> false
| Ident _ -> false
| Null _ -> false
| Nullable _ -> false
| Object _ -> true
| Option _ -> false
| Promise _ -> true
| Record _ -> true
| Tuple _ -> true
| TypeVar _ -> false
| Variant _ -> false
type label = Nolabel | Label of string | OptLabel of string
type dep =
| External of string
| Internal of ResolvedName.t
| Dot of dep * string
struct
let namespace_of_package_name (s : string) : string =
let len = String.length s in
let buf = Buffer.create len in
let add capital ch =
Buffer.add_char buf (if capital then Char.uppercase_ascii ch else ch)
in
let rec aux capital off len =
if off >= len then ()
else
let ch = String.unsafe_get s off in
match ch with
| 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' ->
add capital ch;
aux false (off + 1) len
| '/' | '-' -> aux true (off + 1) len
| _ -> aux capital (off + 1) len
in
aux true 0 len;
Buffer.contents buf
let packageNameToGeneratedModuleName packageName =
if String.contains packageName '/' then
Some (packageName |> namespace_of_package_name)
else None
let isGeneratedModule id ~config =
config.bsDependencies
|> List.exists (fun packageName ->
packageName |> packageNameToGeneratedModuleName
= Some (id |> Ident.name))
* ( Common , DemoSomelibrary ) - > Common - DemoSomelibrary
let addGeneratedModule s ~generatedModule =
s ^ "-" ^ Ident.name generatedModule
let removeGeneratedModule s =
match s |> String.split_on_char '-' with [name; _scope] -> name | _ -> s
end
let rec depToString dep =
match dep with
| External name -> name |> ScopedPackage.removeGeneratedModule
| Internal resolvedName -> resolvedName |> ResolvedName.toString
| Dot (d, s) -> depToString d ^ "_" ^ s
let rec depToResolvedName (dep : dep) =
match dep with
| External name -> name |> ResolvedName.fromString
| Internal resolvedName -> resolvedName
| Dot (p, s) -> ResolvedName.dot s (p |> depToResolvedName)
let createVariant ~bsStringOrInt ~inherits ~noPayloads ~payloads ~polymorphic =
let hash =
noPayloads
|> List.map (fun case -> (case.label, case.labelJS))
|> Array.of_list |> Hashtbl.hash
in
let unboxed = payloads = [] in
Variant
{bsStringOrInt; hash; inherits; noPayloads; payloads; polymorphic; unboxed}
let variantTable hash ~toJS =
(match toJS with true -> "$$toJS" | false -> "$$toRE") ^ string_of_int hash
let ident ?(builtin = true) ?(typeArgs = []) name =
Ident {builtin; name; typeArgs}
let sanitizeTypeName name = name |> Str.global_replace (Str.regexp "'") "_"
let mixedOrUnknown ~config =
ident
(match config.language with
| Flow -> "mixed"
| TypeScript | Untyped -> "unknown")
let booleanT = ident "boolean"
let dateT = ident "Date"
let numberT = ident "number"
let stringT = ident "string"
let unitT = ident "void"
let int64T = Tuple [numberT; numberT]
module NodeFilename = struct
include Filename
let dirSep = "/"
module Path : sig
type t
val normalize : string -> t
val concat : t -> string -> t
val toString : t -> string
end = struct
type t = string
let normalize path : t =
match Sys.os_type with
| "Win32" -> path |> Str.split (Str.regexp "\\") |> String.concat dirSep
| _ -> path
let toString path = path
let length path = String.length path
let concat dirname filename =
let isDirSep s i =
let c = s.[i] in
c = '/' || c = '\\' || c = ':'
in
let l = length dirname in
if l = 0 || isDirSep dirname (l - 1) then dirname ^ filename
else dirname ^ dirSep ^ filename
end
let concat (dirname : string) filename =
let open Path in
Path.concat (normalize dirname) filename |> toString
end
|
e51cff04efdbbe2da33f361532a17e9c7094dbe24d618fa3f95373db3aeac688
|
binsec/haunted
|
nonrelational.ml
|
(**************************************************************************)
This file is part of BINSEC .
(* *)
Copyright ( C ) 2016 - 2019
CEA ( Commissariat à l'énergie atomique et aux énergies
(* alternatives) *)
(* *)
(* you can redistribute it and/or modify it under the terms of the GNU *)
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
(* *)
(* It is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU Lesser General Public License for more details. *)
(* *)
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(* *)
(**************************************************************************)
open Dba_utils
open! Basic_types
open High_level_predicate
open Format
open Static_types (* Env *)
open Ai_options
exception RecursiveCall of Dba.address
module Malloc_status = Dba_types.Region.Map
module MemInterval = struct
type t = {
base : Bigint.t;
size : Size.Byte.t;
}
let create base n =
assert (n >= 0);
{ base; size = Size.Byte.create n; }
let size_of m = Size.Byte.to_int m.size
let base_of m = m.base
let upper_bound m =
Bigint.(pred_big_int (add_int_big_int (Size.Byte.to_int m.size) m.base))
let compare m1 m2 =
if Bigint.lt_big_int (upper_bound m1) m2.base then -1
else if Bigint.lt_big_int (upper_bound m2) m1.base then 1
compare
let _overlap m1 m2 =
not (Bigint.lt_big_int (upper_bound m1) m2.base &&
Bigint.lt_big_int (upper_bound m2) m1.base)
let same_base m1 m2 = m1.base = m2.base
let equal m1 m2 = same_base m1 m2 && m1.size = m2.size
let empty = create Bigint.zero_big_int 1
(* Beware of this function if you have integers bigger than max_int *)
let pp ppf t =
Format.fprintf ppf "@[0x%x+%a@]"
(Bigint.int_of_big_int t.base)
Size.Byte.pp_hex t.size
end
module MemMap = Map.Make(MemInterval)
exception Emptyset
exception Unknown
type update_type = Strong | Weak
module Make(Val: Ai_sigs.Domain) =
struct
module Eq = Union_find.Make (Val)
type env = (MemInterval.t * Machine.endianness * Val.t) MemMap.t Env.t
type t = env option
type equalities = Eq.t
type thresholds = int array * int array * int array * int array
type elementsRecord = Region_bitvector.t list Dba_types.AddressStack.Map.t
type naturalPredicatesRecord = (Dba.Expr.t * Dba.Expr.t) Dba_types.Caddress.Map.t
let default_address =
Dba_types.Caddress.block_start @@ Virtual_address.create 0, [], 0
X86 : : Default size to 32
let current_address = ref default_address
let top = Some Env.empty, High_level_predicate.empty, Eq.create ()
let bottom = None, High_level_predicate.bottom, Eq.bottom
let is_empty s =
match s with
| None -> true
| Some _ -> false
let s_init : (env option) ref = ref (Some Env.empty)
let pp ppf t =
match t with
| None -> fprintf ppf "{}"
| Some env ->
let pp key subenv =
match key with
| Static_types.Var (name, _) ->
fprintf ppf "@[<v 0>";
MemMap.iter
(fun _ (_, _, value) ->
fprintf ppf "%s = %a@ " name Val.pp value) subenv;
fprintf ppf "@]"
| Static_types.Array region ->
fprintf ppf "@[<v 0>Region %a@ {@[<hov 0>"
Dba_printer.Ascii.pp_region region;
MemMap.iter
(fun mloc (_, _, value) ->
fprintf ppf "%a -> %a;@ " MemInterval.pp mloc Val.pp value)
subenv;
fprintf ppf "@]}@]@ ";
in
fprintf ppf "@[<v 1>{";
Env.iter pp env;
fprintf ppf "}@]"
let pp_equalities ppf equalities = Eq.pp ppf equalities
let to_string (s, equalities) =
fprintf str_formatter "@[<v 0>";
if not (is_empty s) then
Format.fprintf Format.str_formatter "Env:@ %a@ " pp s;
fprintf str_formatter "Equalities@ %a@ " pp_equalities equalities;
fprintf str_formatter "@]";
Format.flush_str_formatter ()
let regs_in_expr_to_string expr ppf (s, _, _) =
let contains_expr_var expr var =
let s1 = asprintf "%a" Dba_printer.Ascii.pp_bl_term expr in
let re = Str.regexp_string var in
try ignore (Str.search_forward re s1 0); true
with Not_found -> false
in
match s with
| None -> fprintf ppf "{}"
| Some s ->
fprintf ppf "@[<hov 0>";
Env.iter (
fun key sub_m ->
match key with
| Static_types.Var (vname, _) ->
if contains_expr_var expr vname
then
MemMap.iter (fun _ (_, _, v) ->
fprintf ppf ".%s: %s; "
vname (Val.to_string v))
sub_m
| Static_types.Array _ -> ()
) s;
fprintf ppf "@]"
let read key subkey s =
try let _, _, v = (MemMap.find subkey (Env.find key s)) in v
with Not_found -> Val.universe
let leq s1 s2 =
match (s1, s2) with
| _, None -> false
| None, _ -> true
| Some s1, Some s2 ->
(* for each constraint in s1 there
should be a stricter constraint in s2 *)
let has_constraint key subkey (_, _, v2) =
let v1 = read key subkey s1 in Val.contains v2 v1
in Env.for_all (fun k v -> MemMap.for_all (has_constraint k) v) s2
let rec collect loc id size sub_m =
if id > size then raise Not_found
else
try MemMap.find (MemInterval.create loc id) sub_m
with Not_found -> collect loc (id + 1) size sub_m
let join (s1, flgs1, equalities1) (s2, flgs2, equalities2) =
match (s1, s2) with
| (None, s) -> (s, flgs2, equalities2)
| (s, None) -> (s, flgs1, equalities1)
| (Some s1, Some s2) ->
let rec join_values sub_s2 _ (mloc1, en1, v1) acc =
let size1 = MemInterval.size_of mloc1 in
let base1 = MemInterval.base_of mloc1 in
try
let mloc2, en2, v2 = collect base1 1 size1 sub_s2 in
let size2 = MemInterval.size_of mloc2 in
let base2 = MemInterval.base_of mloc2 in
if MemInterval.equal mloc1 mloc2 && (en1 = en2)
then MemMap.add mloc1 (mloc1, en1, Val.join v1 v2) acc
else
if MemInterval.same_base mloc1 mloc2 && en1 = en2 && en1 = Machine.LittleEndian
then
if size1 < size2
then
let v2' = Val.restrict v2 0 ((size1 * 8) - 1) in
MemMap.add mloc1 (mloc1, en1, Val.join v1 v2') acc
else (
let v1' = Val.restrict v1 0 ((size2 * 8) - 1) in
let v = Val.join v1' v2 in
let loc = MemInterval.create base1 size2 in
let acc = MemMap.add loc (loc, en1, v) acc in
let v1'' = Val.restrict v1 (size2 * 8) (size1 * 8 - 1) in
let sz = Bigint.big_int_of_int size2 in
let base1 = Bigint.add_big_int base1 sz in
let sz = size1 - size2 in
let loc = MemInterval.create base1 sz in
join_values sub_s2 loc (loc, en1, v1'') acc
)
else
if en1 = en2 && en1 = Machine.LittleEndian
then
if Bigint.lt_big_int base1 base2
then
let sz = Bigint.sub_big_int base2 base1 in
let sz = Bigint.int_of_big_int sz in
let sz1 = size1 - sz in
let loc = MemInterval.create base2 sz1 in
let v1' = Val.restrict v1 (sz * 8) (size1 * 8 - 1) in
join_values sub_s2 loc (loc, en1, v1') acc
else
let sz = Bigint.sub_big_int base1 base2 in
let sz = Bigint.int_of_big_int sz in
let sz2 = size2 - sz in
let v2' = Val.restrict v2 (sz * 8) (size2 * 8 - 1) in
if size1 = sz2 then
let loc = MemInterval.create base1 size1 in
MemMap.add loc (loc, en1, Val.join v1 v2') acc
else if size1 < sz2
then
let v2' = Val.restrict v2' 0 ((size1 * 8) - 1) in
MemMap.add mloc1 (mloc1, en1, Val.join v1 v2') acc
else (
let v1' = Val.restrict v1 0 ((sz2 * 8) - 1) in
let v = Val.join v1' v2 in
let loc = MemInterval.create base1 sz in
let acc = MemMap.add loc (loc, en1, v) acc in
let v1'' = Val.restrict v1 (sz2 * 8) (size1 * 8 - 1) in
let sz = Bigint.big_int_of_int sz2 in
let base1 = Bigint.add_big_int base1 sz in
let sz = size1 - sz2 in
let loc = MemInterval.create base1 sz in
join_values sub_s2 loc (loc, en1, v1'') acc
)
else failwith "unrelState.ml: fail3"
with Not_found -> acc
in
let sub_join array_var sub_s1 =
try let sub_s2 = Env.find array_var s2 in
MemMap.fold (join_values sub_s2) sub_s1 MemMap.empty
with Not_found -> MemMap.empty
in
let s = Some (Env.mapi sub_join s1) in
let flgs = High_level_predicate.join flgs1 flgs2 in
let t0 = Unix.gettimeofday () in
let equalities = Eq.join equalities1 equalities2 in
Ai_options.time_equalities := Unix.gettimeofday () -. t0 +. !Ai_options.time_equalities;
(s, flgs, equalities)
let widen (s1, flgs1, equalities1) (s2, flgs2, equalities2) thresholds =
match (s1, s2) with
| (None, s) -> (s, flgs2, equalities2)
| (s, None) -> (s, flgs1, equalities1)
| (Some s1, Some s2) ->
let rec widen_values sub_s2 _ (base1,en1,v1) acc =
let size1 = MemInterval.size_of base1 in
let base1 = MemInterval.base_of base1 in
try
let (base2, en2, v2) = collect base1 1 size1 sub_s2 in
let size2 = MemInterval.size_of base2 in
let base2 = MemInterval.base_of base2 in
if (Bigint.eq_big_int base1 base2) && (size1 = size2) && (en1 = en2)
then
let loc = MemInterval.create base1 size1 in
MemMap.add loc (loc, en1, Val.widen v1 v2 thresholds) acc
else
if (Bigint.eq_big_int base1 base2) && (en1 = en2) && (en1 = Machine.LittleEndian)
then
if size1 < size2
then
let v2' = Val.restrict v2 0 ((size1 * 8) - 1) in
let loc = MemInterval.create base1 size1 in
MemMap.add loc (loc, en1, Val.widen v1 v2' thresholds) acc
else (
let v1' = Val.restrict v1 0 ((size2 * 8) - 1) in
let v = Val.widen v1' v2 thresholds in
let loc = MemInterval.create base1 size2 in
let acc = MemMap.add loc (loc, en1, v) acc in
let v1'' = Val.restrict v1 (size2 * 8) (size1 * 8 - 1) in
let sz = Bigint.big_int_of_int size2 in
let base1 = Bigint.add_big_int base1 sz in
let sz = size1 - size2 in
let loc = MemInterval.create base1 sz in
widen_values sub_s2 loc (loc, en1, v1'') acc
)
else
if (en1 = en2) && (en1 = Machine.LittleEndian)
then
if (Bigint.lt_big_int base1 base2)
then
let sz = Bigint.sub_big_int base2 base1 in
let sz = Bigint.int_of_big_int sz in
let sz1 = size1 - sz in
let loc = MemInterval.create base2 sz1 in
let v1' = Val.restrict v1 (sz * 8) (size1 * 8 - 1) in
widen_values sub_s2 loc (loc, en1, v1') acc
else
let sz = Bigint.sub_big_int base1 base2 in
let sz = Bigint.int_of_big_int sz in
let sz2 = size2 - sz in
let v2' = Val.restrict v2 (sz * 8) (size2 * 8 - 1) in
if size1 = sz2 then
let loc = MemInterval.create base1 size1 in
MemMap.add loc (loc, en1, Val.widen v1 v2' thresholds) acc
else if size1 < sz2
then
let v2' = Val.restrict v2' 0 ((size1 * 8) - 1) in
let loc = MemInterval.create base1 size1 in
MemMap.add loc (loc, en1, Val.widen v1 v2' thresholds) acc
else (
let v1' = Val.restrict v1 0 ((sz2 * 8) - 1) in
let v = Val.widen v1' v2 thresholds in
let loc = MemInterval.create base1 sz in
let acc = MemMap.add loc (loc, en1, v) acc in
let v1'' = Val.restrict v1 (sz2 * 8) (size1 * 8 - 1) in
let sz = Bigint.big_int_of_int sz2 in
let base1 = Bigint.add_big_int base1 sz in
let sz = size1 - sz2 in
let loc = MemInterval.create base1 sz in
widen_values sub_s2 loc (loc, en1, v1'') acc
)
else failwith "unrelState.ml: fail3"
with Not_found -> acc
in
let sub_widen array_var sub_s1 =
try let sub_s2 = Env.find array_var s2 in
MemMap.fold (widen_values sub_s2) sub_s1 MemMap.empty
with Not_found -> MemMap.empty
in
let s = Some (Env.mapi sub_widen s1) in
let flgs = High_level_predicate.join flgs1 flgs2 in
let l0 = Unix.gettimeofday () in
let equalities = Eq.widen equalities1 equalities2 thresholds in
Ai_options.time_equalities := Unix.gettimeofday () -. l0 +. !Ai_options.time_equalities;
(s, flgs, equalities)
let meet s1 s2 =
match s1, s2 with
| (None, _) | (_, None) -> None
| (Some s1, Some s2) ->
let res = ref Env.empty in
let meet_info key subkey (i, en, v1) =
let v2 = read key subkey s2 in
let v = Val.meet v1 v2 in
res := match key with
| Static_types.Var _ ->
let loc = subkey in
let sub_s = MemMap.add loc (loc, en, v) MemMap.empty in
(Env.add key sub_s !res)
| Static_types.Array r ->
let sub_s =
try Env.find (Static_types.Array r) !res
with Not_found -> MemMap.empty in
let sub_s = MemMap.add subkey (i, en, v) sub_s in
(Env.add (Static_types.Array r) sub_s !res)
in
Env.iter (fun key v -> MemMap.iter (meet_info key) v) s1;
Some !res
let add_addr_macro (s : t) elem =
let bv = Region_bitvector.bitvector_of elem in
let v = Val.singleton (`Value (`Constant, bv)) in
let loc = MemInterval.create Bigint.zero_big_int 1 in
let en = Machine.LittleEndian in
let sub_s = MemMap.add loc (loc, en, v) MemMap.empty in
let v_addr = Var ("\\addr", Kernel_options.Machine.word_size ()) in
let s =
match s with
| None -> Some (Env.add v_addr sub_s Env.empty)
| Some s -> Some (Env.add v_addr sub_s s)
in s
let rec is_mul expr =
match expr with
| Dba.Expr.Cst _
| Dba.Expr.Var _ -> ()
| Dba.Expr.Load (_, _, expr)
| Dba.Expr.Unary (_, expr) -> is_mul expr
| Dba.Expr.Binary (Dba.Binary_op.Mult, _expr1, _expr2) -> raise Errors.Enumerate_Top
| Dba.Expr.Ite (_, expr1, expr2)
| Dba.Expr.Binary (_, expr1, expr2) -> is_mul expr1; is_mul expr2
let rec eval_expr expr s assumes globals elements equalities =
let eval_without_equalities () =
match expr with
| Dba.Expr.Var { Dba.name = st; Dba.size; _} ->
let v =
let loc = (Bigint.zero_big_int, 1, Machine.LittleEndian) in
try load (Static_types.Var (st, size)) loc s assumes globals elements equalities
with Not_found | Errors.Empty_env ->
try load (Static_types.Var (st, size)) loc !s_init assumes globals elements equalities
with Not_found -> Val.universe
in v, assumes
| Dba.Expr.Load (size, en, e) -> (
try
let v_exp, assumes = eval_expr e s assumes globals elements equalities in
let indexes =
try let _ = is_mul e in
Val.elements v_exp
with Errors.Enumerate_Top ->
if List.length elements = 0
then raise Errors.Enumerate_Top
else elements
in
List.fold_right (fun elem acc ->
let region = Region_bitvector.region_of elem in
let i = Region_bitvector.value_of elem in
let s = add_addr_macro s elem in
let arr = Array region in
let ret = load arr (i, size, en) s assumes globals elements equalities in
Val.join ret acc
) indexes Val.empty, assumes
with Val.Elements_of_top -> Val.universe, assumes
)
| Dba.Expr.Cst (r, v) -> Val.singleton (`Value (r, v)), assumes
| Dba.Expr.Unary (uop, expr) ->
let e, assumes = eval_expr expr s assumes globals elements equalities in
let f =
match uop with
| Dba.Unary_op.UMinus -> Val.neg
| Dba.Unary_op.Not -> Val.lognot
| Dba.Unary_op.Uext n -> fun e -> Val.extension e n
| Dba.Unary_op.Sext n -> fun e -> Val.signed_extension e n
| Dba.Unary_op.Restrict {Interval.lo; Interval.hi} ->
fun e -> Val.restrict e lo hi
in f e, assumes
| Dba.Expr.Binary (bop, expr1, expr2) ->
let op1, assumes = eval_expr expr1 s assumes globals elements equalities in
let op2, assumes = eval_expr expr2 s assumes globals elements equalities in
let build_bop =
match bop with
| Dba.Binary_op.Plus -> Val.add
| Dba.Binary_op.Minus -> Val.sub
| Dba.Binary_op.Mult -> Val.mul
| Dba.Binary_op.DivU -> Val.udiv
| Dba.Binary_op.DivS -> Val.sdiv
| Dba.Binary_op.ModU -> Val.umod
| Dba.Binary_op.ModS -> Val.smod
| Dba.Binary_op.Or -> Val.logor
| Dba.Binary_op.And -> Val.logand
| Dba.Binary_op.Xor -> Val.logxor
| Dba.Binary_op.Concat -> Val.concat
| Dba.Binary_op.LShift -> Val.lshift
| Dba.Binary_op.RShiftU -> Val.rshiftU
| Dba.Binary_op.RShiftS -> Val.rshiftS
| Dba.Binary_op.LeftRotate -> Val.rotate_left
| Dba.Binary_op.RightRotate -> Val.rotate_right
| Dba.Binary_op.Eq -> Val.eq
| Dba.Binary_op.Diff -> Val.diff
| Dba.Binary_op.LeqU -> Val.leqU
| Dba.Binary_op.LtU -> Val.ltU
| Dba.Binary_op.GeqU -> Val.geqU
| Dba.Binary_op.GtU -> Val.gtU
| Dba.Binary_op.LeqS -> Val.leqS
| Dba.Binary_op.LtS -> Val.ltS
| Dba.Binary_op.GeqS -> Val.geqS
| Dba.Binary_op.GtS -> Val.gtS
in build_bop op1 op2, assumes
| Dba.Expr.Ite (cond, expr1, expr2) ->
let cond, assumes = eval_cond cond s assumes globals elements equalities in
begin match cond with
| Ternary.True ->
eval_expr expr1 s assumes globals elements equalities
| Ternary.False ->
eval_expr expr2 s assumes globals elements equalities
| Ternary.Unknown ->
let op1 =
eval_expr expr1 s assumes globals elements equalities |> fst
and op2 =
eval_expr expr2 s assumes globals elements equalities |> fst
in Val.join op1 op2, assumes
end
in
(* Redefinition for stat purposes *)
let eval_without_equalities () =
Display.save_evaluation_counts ();
let _time, v = Utils.time (eval_without_equalities) in
(* add_time_without_equalities time; *)
Display.restore_evaluation_counts ();
v
in
Display.increase_evaluation_count ();
match Dba.LValue.of_expr expr with
| lhs_e ->
Display.increase_lhs_evaluation_count ();
let t0 = Unix.gettimeofday () in
let equal_lhs_e, equal_v_e = Eq.find equalities lhs_e in
Ai_options.time_equalities := Unix.gettimeofday () -. t0
+. !Ai_options.time_equalities;
begin
match equal_lhs_e, equal_v_e with
| _, None | None, _ -> eval_without_equalities ()
| Some lhs_eq, Some v ->
Display.increase_lhseq_evaluation_count ();
if not (Dba.LValue.equal lhs_e lhs_eq) then
Display.equality_use !current_address lhs_eq lhs_e;
let v_without_equalities, _ = eval_without_equalities () in
if Val.contains v_without_equalities v &&
not (Val.contains v v_without_equalities)
then incr Ai_options.nb_equalities_refinement;
v, assumes
end
| exception Failure _ -> eval_without_equalities ()
and eval_cond expr s assumes globals elements equalities =
try
let op,assumes = eval_expr expr s assumes globals elements equalities in
Val.is_true op assumes globals, assumes
with Smt_bitvectors.Assume_condition smb ->
let assumes = smb :: assumes in
eval_cond expr s assumes globals elements equalities
and get_elem i r m =
let en = Machine.LittleEndian in
try MemMap.find (MemInterval.create i 1) (Env.find (Static_types.Array r) m)
with Not_found ->
match !s_init with
| None -> raise Errors.Empty_env
| Some s ->
try MemMap.find (MemInterval.create i 1) (Env.find (Static_types.Array r) s)
with Not_found ->
if Region_bitvector.region_equal r `Constant
then begin
let value =
try Val.singleton (Region_bitvector.get_byte_region_at i)
with _ -> Val.universe
in
Display.add_call i;
MemInterval.create i 1, en, value
end
else MemInterval.create i 1, en, Val.universe
and retrieve_value_little i r m =
let size = MemInterval.size_of i in
let i = MemInterval.base_of i in
let a, en, value = get_elem i r m in
let sz = MemInterval.size_of a in
let a = MemInterval.base_of a in
match en with
| Machine.LittleEndian ->
if Bigint.eq_big_int a i && sz = size
then value
else if Bigint.eq_big_int a i
then
if size < sz
then Val.restrict value 0 ((size * 8) - 1)
else
let sz' = Bigint.big_int_of_int sz in
let i = Bigint.add_big_int i sz' in
let v = retrieve_value_little (MemInterval.create i (size - sz)) r m in
Val.concat v value
else
let sz_minus1 = Bigint.big_int_of_int (sz - 1) in
let size_minus1 = Bigint.big_int_of_int (size - 1) in
let upper_a = (Bigint.add_big_int a sz_minus1) in
let upper_i = (Bigint.add_big_int i size_minus1) in
if Bigint.lt_big_int a i then
if Bigint.ge_big_int upper_a upper_i
then
let delta = Bigint.sub_big_int i a in
let off1 = (Bigint.int_of_big_int delta) * 8 in
let off2 = off1 + size * 8 - 1 in
Val.restrict value off1 off2
else
let delta = Bigint.sub_big_int i a in
let off1 = (Bigint.int_of_big_int delta) * 8 in
let off2 = (sz * 8) - 1 in
let v1 = Val.restrict value off1 off2 in
let i = Bigint.succ_big_int upper_a in
let size = Bigint.sub_big_int upper_i upper_a in
let size = Bigint.int_of_big_int size in
let v2 = retrieve_value_little (MemInterval.create i size) r m in
Val.concat v2 v1
else failwith "unrelSate.ml: load_little_e"
| Machine.BigEndian ->
let rec invert value off1 off2 acc sz =
if sz < 1
then acc
else let v = Val.restrict value off1 off2 in
let acc = Val.concat acc v in
invert value (off1 + 8) (off2 + 8) acc (sz - 1)
in
if (Bigint.eq_big_int a i) && (sz=size)
then
let v = Val.restrict value 0 7 in
invert value 8 15 v (sz - 1)
else if (Bigint.eq_big_int a i)
then
if size < sz
then
let off1 = (sz - size) * 8 in
let off2 = off1 + 7 in
let v = Val.restrict value off1 off2 in
invert value off1 off2 v (size - 1)
else
let v = Val.restrict value 0 7 in
let v1 = invert value 8 15 v (sz - 1) in
let sz' = Bigint.big_int_of_int sz in
let i = Bigint.add_big_int i sz' in
let v2 = retrieve_value_little (MemInterval.create i (size - sz)) r m in
Val.concat v2 v1
else failwith "unrelSate.ml: impossible case in load_big_e"
and retrieve_value_big i r m =
let size = MemInterval.size_of i in
let i = MemInterval.base_of i in
let en = Machine.LittleEndian in
let a, _en, value =
try MemMap.find (MemInterval.create i 1) (Env.find (Static_types.Array r) m)
with Not_found ->
match !s_init with
| None -> raise Errors.Empty_env
| Some s ->
try MemMap.find (MemInterval.create i 1) (Env.find (Static_types.Array r) s)
with Not_found ->
let v =
try Val.singleton (Region_bitvector.get_byte_region_at i)
with Errors.Invalid_address _ -> Val.universe
in MemInterval.create i 1, en, v
in
let sz = MemInterval.size_of a in
let a = MemInterval.base_of a in
if Bigint.eq_big_int a i && sz = size
then value
else if Bigint.eq_big_int a i
then
if size < sz
then Val.restrict value 0 (size - 1)
else
let i = Bigint.add_big_int i (Bigint.big_int_of_int sz) in
let v = retrieve_value_big (MemInterval.create i (size - sz)) r m in
Val.concat v value
else
let sz_minus1 = Bigint.big_int_of_int (sz - 1) in
let size_minus1 = Bigint.big_int_of_int (size - 1) in
let upper_a = (Bigint.add_big_int a sz_minus1) in
let upper_i = (Bigint.add_big_int i size_minus1) in
if Bigint.lt_big_int a i then
if Bigint.ge_big_int upper_a upper_i
then
let delta = Bigint.sub_big_int upper_a upper_i in
let off1 = Bigint.int_of_big_int delta in
let off2 = sz - 1 in
Val.restrict value off1 off2
else
let off1 = 0 in
let delta = Bigint.sub_big_int upper_a i in
let off2 = Bigint.int_of_big_int delta in
let v1 = Val.restrict value off1 off2 in
let i = Bigint.succ_big_int upper_a in
let size = off2 - off1 + 1 in
let v2 = retrieve_value_big (MemInterval.create i size) r m in
Val.concat v2 v1
else failwith "unrelSate.ml: impossible case in load_big"
(* Checking read of memory permissions here *)
and load x (i, size, en) m assumes globals elements equalities =
match m with
| None -> raise Errors.Empty_env
| Some m ->
match x with
| Static_types.Var _ ->
let loc = MemInterval.create Bigint.zero_big_int 1 in
let _, _, av = MemMap.find loc (Env.find x m) in av
| Static_types.Array r ->
let c =
try Dba_types.Rights.find_read_right r !Concrete_eval.permis
with Not_found -> Dba.Expr.one in
let b, _assumes = eval_cond c (Some m) assumes globals elements equalities in
match b with
| Ternary.True ->
begin
match en with
| Machine.LittleEndian ->
retrieve_value_little (MemInterval.create i size) r m
| Machine.BigEndian ->
retrieve_value_big (MemInterval.create i size) r m
end
| Ternary.False -> raise Errors.Read_permission_denied
| Ternary.Unknown -> failwith "read permission unknown"
and update base en old_value new_value sub_m =
let size = MemInterval.size_of base in
let base = MemInterval.base_of base in
let loc = MemInterval.create base size in
let v = Val.join old_value new_value in
MemMap.add loc (loc, en, v) sub_m
and clear_at_beginning old_info new_info sub_m _sw =
Logger.debug "Clear beginning";
let (old_loc, old_size, old_en, old_value) = old_info in
let (_new_loc, new_size, _new_en, _new_value) = new_info in
let off1 = new_size * 8 in
let off2 = old_size * 8 - 1 in
assert (off1 <= off2);
let v = Val.restrict old_value off1 off2 in
let sz = Bigint.big_int_of_int new_size in
let base = Bigint.add_big_int old_loc sz in
let loc = MemInterval.create base (old_size - new_size) in
let sub_m = MemMap.add loc (loc, old_en, v) sub_m in
sub_m
and update_at_beginning old_info new_info sub_m sw =
let (old_loc, old_size, old_en, old_value) = old_info in
let (new_loc, new_size, new_en, new_value) = new_info in
if sw = Strong
then
clear_at_beginning old_info new_info sub_m sw
else
let off1 = 0 in
let off2 = 8 * new_size - 1 in
assert (off1 <= off2);
let v = Val.restrict old_value off1 off2 in
let loc = MemInterval.create new_loc new_size in
let sub_m = update loc new_en v new_value sub_m in
let off1 = new_size * 8 in
let off2 = old_size * 8 - 1 in
assert (off1 <= off2);
let v = Val.restrict old_value off1 off2 in
let sz = Bigint.big_int_of_int new_size in
let base = Bigint.add_big_int old_loc sz in
let loc = MemInterval.create base (old_size - new_size) in
let sub_m = MemMap.add loc (loc, old_en, v) sub_m in
sub_m
and clear_at_beginning_and_beyond addrStack old_info new_info sub_m sw =
Logger.debug "Clear beginning & beyond called";
let old_loc, old_size, _, _ = old_info in
let (_new_loc, new_size, new_en, new_value) = new_info in
let off1 = old_size * 8 in
let off2 = new_size * 8 - 1 in
assert (off1 <= off2);
let v = Val.restrict new_value off1 off2 in
let sz = Bigint.big_int_of_int old_size in
let base = Bigint.add_big_int old_loc sz in
split_regions addrStack sub_m v (base, new_size - old_size) new_en sw
and update_at_beginning_and_beyond addrStack old_info new_info sub_m sw =
let (old_loc, old_size, old_en, old_value) = old_info in
let (new_loc, new_size, new_en, new_value) = new_info in
let off1 = 0 in
let off2 = 8 * old_size - 1 in
assert (off1 <= off2);
let v = Val.restrict new_value off1 off2 in
let loc = MemInterval.create new_loc old_size in
let sub_m = update loc new_en v old_value sub_m in
let off1 = old_size * 8 in
let off2 = new_size * 8 - 1 in
assert (off1 <= off2);
let v = Val.restrict new_value off1 off2 in
let sz = Bigint.big_int_of_int old_size in
let base = Bigint.add_big_int old_loc sz in
let sub_m = MemMap.add (MemInterval.create old_loc old_size)
(MemInterval.create old_loc old_size, old_en, old_value) sub_m in
split_regions addrStack sub_m v (base, new_size - old_size) new_en sw
and clear_inside_and_beyond addrStack old_info new_info sub_m sw =
Logger.debug "Clear inside & beyond called";
let (old_loc, old_size, old_en, old_value) = old_info in
let (new_loc, new_size, new_en, new_value) = new_info in
let delta = Bigint.sub_big_int new_loc old_loc in
let delta = Bigint.int_of_big_int delta in
let off1 = 0 in
let off2 = delta * 8 - 1 in
assert (off1 <= off2);
let v = Val.restrict old_value off1 off2 in
let loc = MemInterval.create old_loc delta in
let sub_m = MemMap.add loc (loc, old_en, v) sub_m in
let off1 = delta * 8 in
let off2 = old_size * 8 - 1 in
let off2' = off2 - off1 in
let off1 = off2' + 1 in
let off2 = new_size * 8 - 1 in
if (off1 > off2) then
sub_m
else
let v = Val.restrict new_value off1 off2 in
let sz = Bigint.big_int_of_int ((off2' + 1) / 8) in
let base = Bigint.add_big_int new_loc sz in
split_regions addrStack sub_m v (base, (off2 - off1) / 8 + 1) new_en sw
and update_inside_and_beyond addrStack old_info new_info sub_m sw =
let (old_loc, old_size, old_en, old_value) = old_info in
let (new_loc, new_size, new_en, new_value) = new_info in
let delta = Bigint.sub_big_int new_loc old_loc in
let delta = Bigint.int_of_big_int delta in
let off1 = 0 in
let off2 = delta * 8 - 1 in
assert (off1 <= off2);
let v = Val.restrict old_value off1 off2 in
let loc = MemInterval.create old_loc delta in
let sub_m = MemMap.add loc (loc, old_en, v) sub_m in
let off1 = delta * 8 in
let off2 = old_size * 8 - 1 in
assert (off1 <= off2);
let v1 = Val.restrict old_value off1 off2 in
let off1' = 0 in
let off2' = off2 - off1 in
assert (off1' <= off2');
let v2 = Val.restrict new_value off1' off2' in
let v = Val.join v1 v2 in
let loc = MemInterval.create new_loc (off2' / 8 + 1) in
let sub_m = MemMap.add loc (loc, new_en, v) sub_m in
let off1 = off2' + 1 in
let off2 = new_size * 8 - 1 in
if (off1 > off2) then
sub_m
else
let v = Val.restrict new_value off1 off2 in
let sz = Bigint.big_int_of_int off2' in
let base = Bigint.add_big_int new_loc sz in
let sub_m = MemMap.add (MemInterval.create old_loc old_size)
((MemInterval.create old_loc old_size), old_en, old_value) sub_m in
split_regions addrStack sub_m v (base, ((off2 - off1) / 8 + 1)) new_en sw
and clear_inside addrStack old_info new_info sub_m sw =
Logger.debug "Clear inside called";
let (old_loc, old_size, old_en, old_value) = old_info in
let (new_loc, new_size, new_en, _new_value) = new_info in
let delta = Bigint.sub_big_int new_loc old_loc in
let delta = Bigint.int_of_big_int delta in
let off1 = 0 in
let off2 = delta * 8 - 1 in
assert (off1 <= off2);
let v = Val.restrict old_value off1 off2 in
let loc = MemInterval.create old_loc delta in
let sub_m = MemMap.add loc (loc, old_en, v) sub_m in
let off2 = (new_size + delta) * 8 - 1 in
let sz = Bigint.big_int_of_int off2 in
let off1 = off2 + 1 in
let off2 = old_size * 8 - 1 in
assert (off1 <= off2);
let v = Val.restrict old_value off1 off2 in
let base = Bigint.add_big_int new_loc sz in
let sub_m = MemMap.add (MemInterval.create old_loc old_size)
((MemInterval.create old_loc old_size), old_en, old_value) sub_m in
let sub_m = split_regions addrStack sub_m v (base, ((off2 - off1) / 8 + 1)) new_en sw in
sub_m
and update_inside addrStack old_info new_info sub_m sw =
let (old_loc, old_size, old_en, old_value) = old_info in
let (new_loc, new_size, new_en, new_value) = new_info in
let delta = Bigint.sub_big_int new_loc old_loc in
let delta = Bigint.int_of_big_int delta in
let off1 = 0 in
let off2 = delta * 8 - 1 in
assert (off1 <= off2);
let v = Val.restrict old_value off1 off2 in
let loc = MemInterval.create old_loc delta in
let sub_m = MemMap.add loc (loc, old_en, v) sub_m in
let off1 = delta * 8 in
let off2 = (new_size + delta) * 8 - 1 in
assert (off1 <= off2);
let v1 = Val.restrict old_value off1 off2 in
let off1' = 0 in
let off2' = off2 - off1 in
assert (off1' <= off2');
let v2 = Val.restrict new_value off1' off2' in
let v = Val.join v1 v2 in
let loc = MemInterval.create new_loc (off2' / 8 + 1) in
let sub_m = MemMap.add loc (loc, new_en, v) sub_m in
let sz = Bigint.big_int_of_int off2 in
let off1 = off2 + 1 in
let off2 = old_size * 8 - 1 in
assert (off1 <= off2);
let v = Val.restrict old_value off1 off2 in
let base = Bigint.add_big_int new_loc sz in
let sub_m = MemMap.add (MemInterval.create old_loc old_size)
((MemInterval.create old_loc old_size), old_en, old_value) sub_m in
let sub_m = split_regions addrStack sub_m v
(base, succ (off2 - off1) / (Constants.bytesize:>int)) new_en sw in
sub_m
and clear_before_and_beyond addrStack old_info new_info sub_m sw =
Logger.debug "Clear before & beyond";
let (old_loc, old_size, old_en, old_value) = old_info in
let (new_loc, new_size, new_en, new_value) = new_info in
let delta = Bigint.sub_big_int old_loc new_loc in
let delta = Bigint.int_of_big_int delta in
let off1 = delta * 8 in
let off2 = new_size * 8 - 1 in
Logger.debug "OFF1:%d OFF2:%d" off1 off2;
assert (off1 <= off2);
let v = Val.restrict new_value off1 off2 in
let sub_m = MemMap.add (MemInterval.create old_loc old_size)
((MemInterval.create old_loc old_size), old_en, old_value) sub_m in
let sub_m = split_regions addrStack sub_m v (old_loc, new_size - delta) new_en sw in
sub_m
and update_before_and_beyond addrStack old_info new_info sub_m sw =
let (old_loc, old_size, old_en, old_value) = old_info in
let (new_loc, new_size, new_en, new_value) = new_info in
let delta = Bigint.sub_big_int old_loc new_loc in
let delta = Bigint.int_of_big_int delta in
let sub_m =
if (sw = Strong) then
let off1 = 0 in
let off2 = delta * 8 - 1 in
assert (off1 <= off2);
let v = Val.restrict new_value off1 off2 in
let loc = MemInterval.create new_loc delta in
MemMap.add loc (loc, new_en, v) sub_m
else sub_m
in
let off1 = delta * 8 in
let off2 = new_size * 8 - 1 in
assert (off1 <= off2);
let v = Val.restrict new_value off1 off2 in
let sub_m = MemMap.add (MemInterval.create old_loc old_size)
(MemInterval.create old_loc old_size, old_en, old_value) sub_m in
let sub_m = split_regions addrStack sub_m v (old_loc, new_size - delta) new_en sw in
sub_m
and split_regions addrStack sub_m new_value (address, nbytes) new_en sw =
let new_loc = address
and new_size = nbytes in
let (_, _, loop) = addrStack in
try
let old_loc, old_en, old_value = collect new_loc 1 new_size sub_m in
let old_size = MemInterval.size_of old_loc in
let old_loc = MemInterval.base_of old_loc in
if loop > 1 then
Logger.warning "Potential buffer overflow at %a"
Dba_types.AddressStack.pp addrStack;
let loc = MemInterval.create old_loc old_size in
let sub_m = MemMap.remove loc sub_m in
let old_info = (old_loc, old_size, old_en, old_value) in
let new_info = (new_loc, new_size, new_en, new_value) in
match old_en, new_en with
| Machine.LittleEndian, Machine.LittleEndian -> (
match sw with
| Strong ->
if (Bigint.eq_big_int old_loc new_loc) && (new_size = old_size)
then sub_m
else if Bigint.eq_big_int old_loc new_loc
then
let f =
if new_size < old_size
then clear_at_beginning
else clear_at_beginning_and_beyond addrStack
in f old_info new_info sub_m sw
else
let old_size_1 = Bigint.big_int_of_int (old_size - 1) in
let new_size_1 = Bigint.big_int_of_int (new_size - 1) in
let upper_old = Bigint.add_big_int old_loc old_size_1 in
let upper_new = Bigint.add_big_int new_loc new_size_1 in
if Bigint.lt_big_int old_loc new_loc then
if Bigint.ge_big_int upper_new upper_old
then clear_inside_and_beyond addrStack old_info new_info sub_m sw
else clear_inside addrStack old_info new_info sub_m sw
else clear_before_and_beyond addrStack old_info new_info sub_m sw
| Weak ->
if (Bigint.eq_big_int old_loc new_loc) && (new_size = old_size)
then update (MemInterval.create new_loc new_size) new_en old_value new_value sub_m
else (
if (Bigint.eq_big_int old_loc new_loc)
then
if new_size < old_size
then update_at_beginning old_info new_info sub_m sw
else update_at_beginning_and_beyond addrStack old_info new_info sub_m sw
else
let old_size_1 = Bigint.big_int_of_int (old_size - 1) in
let new_size_1 = Bigint.big_int_of_int (new_size - 1) in
let upper_old = Bigint.add_big_int old_loc old_size_1 in
let upper_new = Bigint.add_big_int new_loc new_size_1 in
if Bigint.lt_big_int old_loc new_loc then
if Bigint.ge_big_int upper_new upper_old
then update_inside_and_beyond addrStack old_info new_info sub_m sw
else update_inside addrStack old_info new_info sub_m sw
else update_before_and_beyond addrStack old_info new_info sub_m sw
)
)
| Machine.BigEndian, Machine.LittleEndian
| Machine.LittleEndian, Machine.BigEndian
| Machine.BigEndian, Machine.BigEndian -> failwith "split_regions:big_endian"
with Not_found ->
if sw = Strong
then
let loc = MemInterval.create new_loc new_size in
Logger.debug "SPLITREG STORE: %a" MemInterval.pp loc;
MemMap.add loc (loc, new_en, new_value) sub_m
else sub_m
(* Checking write to memory permissions here *)
and store addrStack x (i, nbytes) en value m assumes globals sw elements equalities =
let m = match m with
| None -> Env.empty
| Some m -> m
in
match x with
| Static_types.Var _ ->
let loc = MemInterval.create Bigint.zero_big_int 1 in
let sub_m = MemMap.singleton loc (loc, en, value) in
Some (Env.add x sub_m m)
| Static_types.Array r ->
let c =
try Dba_types.Rights.find_write_right r !Concrete_eval.permis
with Not_found -> Dba.Expr.one
in
let b, _assumes = eval_cond c (Some m) assumes globals elements equalities in
match b with
| Ternary.True ->
let sub_m =
try Env.find (Static_types.Array r) m with Not_found -> MemMap.empty
in
let sub_m = split_regions addrStack sub_m value (i, nbytes) en sw in
let sub_m =
if sw = Strong then begin
let loc = MemInterval.create i nbytes in
Logger.debug "LOCSTORE: %a" MemInterval.pp loc;
MemMap.add loc (loc, en, value) sub_m
end
else sub_m
in Some (Env.add (Static_types.Array r) sub_m m)
| Ternary.False -> raise Errors.Write_permission_denied
| Ternary.Unknown -> failwith "write permission unknown"
and check_region_size region i sz =
if sz < 1 then
raise (Errors.Bad_bound ("store, case1: store size = " ^ (string_of_int sz)))
else
match region with
| `Constant | `Stack -> ()
| `Malloc ((id, _), malloc_size) ->
let open Bigint in
if gt_big_int (add_big_int i (big_int_of_int (sz - 1))) malloc_size
then
let message = Format.asprintf "store, case2: store at 𝑴 %d[@%s, size = %d bytes] but size(𝑴 %d) = %s bytes!"
id (Bigint.string_of_big_int i) sz id (Bigint.string_of_big_int malloc_size) in
raise (Errors.Bad_bound message)
else ()
let store endianness addrStack sz v e env assumes globals recordMap elements
equalities =
let v_index, assumes = eval_expr e env assumes globals elements equalities
in
Logger.debug "VAL: %a" Val.pp v_index;
let en = endianness in
let indexes =
try Val.elements v_index
with
| Val.Elements_of_top ->
if Ai_options.FailSoftMode.get () then
try Dba_types.AddressStack.Map.find addrStack recordMap
with Not_found -> []
else
if List.length elements = 0
then raise Errors.Enumerate_Top
else elements
in
let apply update elem env =
let region = Region_bitvector.region_of elem in
let i = Region_bitvector.value_of elem in
Logger.debug "RBVVAL: %s" (Bigint.string_of_big_int i);
check_region_size region i sz;
let r = Static_types.Array region in
store addrStack r (i, sz) en v env assumes globals update elements equalities
in
let env =
match indexes with
| [] -> env
| [elem] -> apply Strong elem env
| elems -> List.fold_right (apply Weak) elems env
in
env, assumes, Dba_types.AddressStack.Map.add addrStack indexes recordMap
let store_little_end = store Machine.LittleEndian
let store_big_end = store Machine.BigEndian
let assign addrStack lhs e s assumes globals recordMap elements equalities =
current_address := addrStack;
let v, assumes = eval_expr e s assumes globals elements equalities in
match lhs with
| Dba.(LValue.Var { name = st; size; _}) ->
let v_string = Val.to_string v in
Display.display (Display.Assign (st, e, v_string));
let loc = MemInterval.create Bigint.zero_big_int 1 in
let sub_s = MemMap.add loc (loc, Machine.LittleEndian, v) MemMap.empty in
let s = match s with None -> Env.empty | Some s -> s in
let s = Some (Env.add (Static_types.Var (st, size)) sub_s s) in
s, assumes, recordMap, v
| Dba.LValue.Restrict ({ Dba.name = st; Dba.size; _}, {Interval.lo=of1; Interval.hi=of2}) ->
let s =
match s with
None -> Env.empty
| Some s -> s
in
let loc = MemInterval.create Bigint.zero_big_int 1 in
let en, x =
try let _, en, av = (MemMap.find loc (Env.find (Var (st, size)) s))
in en, av
with Not_found -> Machine.LittleEndian,Val.universe
in
let temp1 =
if (of1 = 0) then v
else (Val.concat v (Val.restrict x 0 (of1 - 1)))
in
let temp2 = Val.restrict x (of2 + 1) (size - 1) in
let loc = MemInterval.create Bigint.zero_big_int 1 in
let v = Val.concat temp2 temp1 in
let sub_s = MemMap.add loc (loc, en, v) MemMap.empty in
let s = Some (Env.add (Static_types.Var (st, size)) sub_s s) in
s, assumes, recordMap, v
| Dba.LValue.Store (sz, endianness, e) ->
let op, assumes, recordMap =
store endianness addrStack sz v e s assumes globals recordMap elements equalities in
op, assumes, recordMap, v
let rec guard addr cond s assumes glbs rcd elements equalities =
match s with
| None -> None, assumes, rcd, equalities
| Some m ->
match cond with
| Dba.Expr.Cst (_, v) ->
let s' = if Bitvector.is_zero v then None else s in
s', assumes, rcd, equalities
| Dba.Expr.Binary (bop, exp1, exp2) -> (
match bop with
| Dba.Binary_op.Eq | Dba.Binary_op.Diff | Dba.Binary_op.LeqU | Dba.Binary_op.LtU
| Dba.Binary_op.GeqU | Dba.Binary_op.GtU | Dba.Binary_op.LeqS | Dba.Binary_op.LtS
| Dba.Binary_op.GeqS | Dba.Binary_op.GtS ->
let v_1, v_2 =
let op1, assumes = eval_expr exp1 s assumes glbs elements equalities in
let op2, _assumes = eval_expr exp2 s assumes glbs elements equalities in
Val.guard bop op1 op2 in
let loc = MemInterval.empty in
(match exp1, exp2 with
| Dba.Expr.Var { Dba.name = v1; Dba.size; _}, Dba.Expr.Cst _ ->
let en = Machine.LittleEndian in
let sub_m = MemMap.add loc (loc, en, v_1) MemMap.empty in
let s = Some (Env.add (Static_types.Var (v1, size)) sub_m m) in
let equalities = Eq.refine exp1 v_1 equalities in
s, assumes, rcd, equalities
| Dba.Expr.Unary (Dba.Unary_op.Restrict
{Interval.lo = o1; Interval.hi = o2;},
Dba.Expr.Var { Dba.name = v1; Dba.size; _}), Dba.Expr.Cst _ ->
let en, x =
try
let _, en, av = MemMap.find loc (Env.find (Var (v1, size)) m)
in en, av
with Not_found -> Machine.LittleEndian, Val.universe
in
let temp1 =
if o1 = 0 then v_1
else Val.concat v_1 (Val.restrict x 0 (o1 - 1)) in
let temp2 = Val.restrict x (o2 + 1) (size - 1) in
let v = Val.concat temp2 temp1 in
let sub_m = MemMap.add loc (loc, en, v) MemMap.empty in
let s = Some (Env.add (Static_types.Var (v1, size)) sub_m m) in
let equalities = Eq.refine exp1 v_1 equalities in
s, assumes, rcd, equalities
| Dba.Expr.Load (sz, Machine.LittleEndian, e), Dba.Expr.Cst _ ->
let s, assumes, rcd = store_little_end addr sz v_1 e s assumes glbs rcd elements equalities in
let equalities = Eq.refine exp1 v_1 equalities in
s, assumes, rcd, equalities
| Dba.Expr.Cst _, Dba.Expr.Load (sz, Machine.LittleEndian, e) ->
let s, assumes, rcd =
store_little_end addr sz v_2 e s assumes glbs rcd elements equalities in
let equalities = Eq.refine exp2 v_2 equalities in
s, assumes, rcd, equalities
| Dba.Expr.Cst _, Dba.Expr.Var { Dba.name = v2; Dba.size; _} ->
let en = Machine.LittleEndian in
let sub_m = MemMap.add loc (loc, en, v_2) MemMap.empty in
let s = Some (Env.add (Static_types.Var (v2, size)) sub_m m) in
let equalities = Eq.refine exp2 v_2 equalities in
s, assumes, rcd, equalities
| Dba.Expr.Var { Dba.name = v1; _},
Dba.Expr.Var {Dba.name = v2; Dba.size; _} ->
let en = Machine.LittleEndian in
let sub_m = MemMap.add loc (loc, en, v_1) MemMap.empty in
let m = Env.add (Static_types.Var (v1, size)) sub_m m in
let sub_m = MemMap.add loc (loc, en, v_2) MemMap.empty in
let s = Some (Env.add (Static_types.Var (v2, size)) sub_m m) in
let equalities = Eq.refine exp1 v_1 equalities in
let equalities = Eq.refine exp2 v_2 equalities in
s, assumes, rcd, equalities
| Dba.Expr.Var {Dba.name = v1; Dba.size = size2; _}, Dba.Expr.Load (size, Machine.BigEndian, e) ->
let en = Machine.LittleEndian in
let sub_m = MemMap.add loc (loc, en, v_1) MemMap.empty in
let m = Some (Env.add (Static_types.Var (v1, size2)) sub_m m) in
let s, assumes, rcd = store_big_end addr size v_2 e m assumes glbs rcd elements equalities in
let equalities = Eq.refine exp1 v_1 equalities in
let equalities = Eq.refine exp2 v_2 equalities in
s, assumes, rcd, equalities
| Dba.Expr.Load (size, Machine.BigEndian, e), Dba.Expr.Var {Dba.name = v2; Dba.size = size2; _} ->
let en = Machine.LittleEndian in (* FIXME ? *)
let sub_m = MemMap.singleton loc (loc, en, v_2) in
let m = Some (Env.add (Static_types.Var (v2, size2)) sub_m m) in
let s, assumes, rcd = store_big_end addr size v_1 e m assumes glbs rcd elements equalities in
let equalities = Eq.refine exp1 v_1 equalities in
let equalities = Eq.refine exp2 v_2 equalities in
s, assumes, rcd, equalities
| Dba.Expr.Var {Dba.name = v1; Dba.size = size1; _}, Dba.Expr.Load (sz, Machine.LittleEndian, e) ->
let en = Machine.LittleEndian in
let sub_m = MemMap.add loc (loc, en, v_1) MemMap.empty in
let m = Some (Env.add (Static_types.Var (v1, size1)) sub_m m) in
let s, assumes, rcd = store_little_end addr sz v_2 e m assumes glbs rcd elements equalities in
let equalities = Eq.refine exp1 v_1 equalities in
let equalities = Eq.refine exp2 v_2 equalities in
s, assumes, rcd, equalities
| Dba.Expr.Load (sz, Machine.LittleEndian, e), Dba.Expr.Var {Dba.name = v2; Dba.size = size2; _} ->
let en = Machine.LittleEndian in
let sub_m = MemMap.add loc (loc, en, v_2) MemMap.empty in
let m = Some (Env.add (Static_types.Var (v2, size2)) sub_m m) in
let s, assumes, rcd = store_little_end addr sz v_1 e m assumes glbs rcd elements equalities in
let equalities = Eq.refine exp1 v_1 equalities in
let equalities = Eq.refine exp2 v_2 equalities in
s, assumes, rcd, equalities
| Dba.Expr.Load (size1, endianness1, e1),
Dba.Expr.Load (size2, endianness2, e2) ->
let m, assumes, rcd = store endianness1
addr size1 v_1 e1 s assumes glbs rcd elements equalities in
let s, assumes, rcd = store endianness2
addr size2 v_2 e2 m assumes glbs rcd elements equalities in
let equalities = Eq.refine exp1 v_1 equalities in
let equalities = Eq.refine exp2 v_2 equalities in
s, assumes, rcd, equalities
| _, _ -> s, assumes, rcd, equalities
)
| _ -> s, assumes, rcd, equalities
)
| Dba.Expr.Unary (uop, expr) ->
( match uop with
| Dba.Unary_op.Not ->
(match expr with
| Dba.Expr.Binary (bop, e1, e2) ->
let k c =
guard addr c s assumes glbs rcd elements equalities in
begin
match bop with
| Dba.Binary_op.Eq -> Dba.Expr.diff e1 e2 |> k
| Dba.Binary_op.Diff -> Dba.Expr.equal e1 e2 |> k
| Dba.Binary_op.LeqU -> Dba.Expr.ugt e1 e2 |> k
| Dba.Binary_op.LtU -> Dba.Expr.uge e1 e2 |> k
| Dba.Binary_op.GeqU -> Dba.Expr.ult e1 e2 |> k
| Dba.Binary_op.GtU -> Dba.Expr.ule e1 e2 |> k
| Dba.Binary_op.LeqS -> Dba.Expr.sgt e1 e2 |> k
| Dba.Binary_op.LtS -> Dba.Expr.sge e1 e2 |> k
| Dba.Binary_op.GeqS -> Dba.Expr.slt e1 e2 |> k
| Dba.Binary_op.GtS -> Dba.Expr.sle e1 e2 |> k
| Dba.Binary_op.Or -> Dba.Expr.(logand (lognot e1) (lognot e2)) |> k
| Dba.Binary_op.And -> Dba.Expr.(logor (lognot e1) (lognot e2)) |> k
| _ -> s, assumes, rcd, equalities
end
| _ -> s, assumes, rcd, equalities)
| _ -> s, assumes, rcd, equalities)
| _ -> s, assumes, rcd, equalities
let string_of_args args m assumes globals elements equalities =
let b = Buffer.create 1024 in
let rec aux assumes args =
match args with
| [] -> ()
| Dba.Str s :: tl ->
Buffer.add_string b (Scanf.unescaped s);
aux assumes tl
| Dba.Exp e :: tl ->
let op, assumes = eval_expr e m assumes globals elements equalities in
let temp = Val.to_string op in
Buffer.add_string b temp;
aux assumes tl
in aux assumes args;
Buffer.contents b
let check_exec_permission addr s assumes globals elements equalities =
let m = match s with None -> Env.empty | Some m -> m in
let bv = Bitvector.create (Virtual_address.to_bigint addr.Dba.base) 32 in
let v = Val.singleton (`Value (`Constant, bv)) in
let loc = MemInterval.create Bigint.zero_big_int 1 in
let sub_m =
MemMap.add loc (loc, Machine.LittleEndian, v) MemMap.empty in
let s = Some (Env.add (Var ("\\addr", Kernel_options.Machine.word_size ())) sub_m m) in
let c =
try Dba_types.Rights.find_exec_right `Constant !Concrete_eval.permis
with Not_found -> Dba.Expr.one in
let b, _assumes = (eval_cond c s assumes globals elements equalities) in
match b with
| Ternary.True -> addr
| Ternary.False -> raise Errors.Exec_permission_denied
| Ternary.Unknown -> failwith "exec permission unknown"
let free expr s assumes globals elements equalities =
let v, _assumes = eval_expr expr s assumes globals elements equalities in
let l =
try Val.elements v
with Val.Elements_of_top -> raise Errors.Enumerate_Top
in
List.iter (fun elem ->
match elem with
| `Value (`Malloc _ as v, bv) ->
let st =
try Malloc_status.find v !Simulate.mallocs
with Not_found -> failwith "Unbound free region"
in
let open Dba in
begin match st with
| Freeable when Bitvector.is_zero bv ->
Simulate.mallocs :=
Malloc_status.add v Freed !Simulate.mallocs
| Freed -> raise Errors.Freed_variable_access
| Freeable -> raise Errors.Invalid_free_address
end
| _ -> raise Errors.Invalid_free_region
) l;
s
let rec is_visited (a_ret, a_callee) callstack nb =
match callstack with
| [] -> false
| (_, callee) :: tl ->
if Dba_types.Caddress.equal callee a_callee
then nb = 0 || is_visited (a_ret, a_callee) tl (nb - 1)
else is_visited (a_ret, a_callee) tl nb
let resolve_jump addr expr s flgs equalities recordMap assumes globals djumps_map tag elements =
let _, cstack, loop = addr in
let v, _assumes = eval_expr expr s assumes globals elements equalities in
let l =
if Ai_options.FailSoftMode.get () then
try Val.elements v
with Val.Elements_of_top ->
try Dba_types.AddressStack.Map.find addr recordMap
with Not_found -> []
else
try Val.elements v
with Val.Elements_of_top ->
if List.length elements = 0
then raise Errors.Enumerate_Top
else elements
in
let locations, djumps_map =
List.fold_right (fun elem (acc1, acc2) ->
if Region_bitvector.region_of elem = `Constant then
if Region_bitvector.size_of elem =
Kernel_options.Machine.word_size () then
begin
let a =
Dba_types.Caddress.block_start @@
Virtual_address.of_bitvector @@
Region_bitvector.bitvector_of elem in
let addrStack =
let open Dba in
match tag, cstack with
| Some Call addr_ret, cstack ->
Display.increase_function_count ();
let calling_callee_addr = addr_ret, a in
if is_visited calling_callee_addr cstack 20
then raise (RecursiveCall a)
else (
Display.display (Display.Call(a, addr_ret));
let cstack = calling_callee_addr :: cstack in
(a, cstack, loop)
)
| Some Return, (old_ret, old_start) :: cstack ->
let cstack =
if Dba_types.Caddress.equal old_ret a then cstack
else (old_ret, old_start) :: cstack in
a, cstack, loop
| Some Return, [] -> a, cstack, loop
| None, cstack -> a, cstack, loop
in
let t1 = (addrStack, s, flgs, equalities) :: acc1 in
let t2 =
let s =
try Dba_types.AddressStack.Map.find addr acc2
with Not_found -> Dba_types.Caddress.Set.empty
in
Dba_types.AddressStack.Map.add addr (Dba_types.Caddress.Set.add a s) acc2 in
t1, t2
end
else
raise Errors.Bad_address_size
else
raise (Errors.Bad_region "Dynamic jump")
) l ([], djumps_map) in
locations, (Dba_types.AddressStack.Map.add addr l recordMap), djumps_map
let resolve_if cond s flgs (m1, eq1) (m2, eq2) addr_suiv1 addr_suiv2 assumes globals elements equalities =
match eval_cond cond s assumes globals elements equalities with
| Ternary.True, _ -> [addr_suiv1, m1, flgs, eq1]
| Ternary.False, _ -> [addr_suiv2, m2, flgs, eq2]
| Ternary.Unknown, _ ->
[ addr_suiv1, m1, flgs, eq1;
addr_suiv2, m2, flgs, eq2; ]
let resolve_assume addr cond s flgs equalities addr_suiv assumes glbs rcd elements =
match eval_cond cond s assumes glbs elements equalities with
| Ternary.Unknown, _ -> [addr_suiv, s, flgs, equalities]
| _, assumes ->
let s, _assumes, _rcd, equalities =
guard addr cond s assumes glbs rcd elements equalities in
[addr_suiv, s, flgs, equalities]
let resolve_assert cond s flgs equalities addr_suiv addrStack instr assumes glbs rcd elements =
let addr, _cstack, _loop = addrStack in
let condi, assumes = (eval_cond cond s assumes glbs elements equalities) in
let continue = Ternary.to_bool condi in
if continue then
let s, _assumes, _rcd, equalities = guard addrStack cond s assumes glbs rcd elements equalities in
[addr_suiv, s, flgs, equalities]
else Errors.assert_failure addr instr
let resolve_nondet_assume addr lhslist cond s flgs equalities addr_suiv assumes glbs rcd elements =
let rec update_memory_nondet lhslist s assumes glbs rcd =
match lhslist with
| [] -> s, assumes, rcd
| (Dba.LValue.Var {Dba.name = st; Dba.size; _}) :: tl ->
let l = MemInterval.create Bigint.zero_big_int 1 in
let en = Machine.LittleEndian in
let sub_s = MemMap.add l (l, en, Val.universe) MemMap.empty in
let s = match s with None -> Env.empty | Some s -> s in
let m' = Some (Env.add (Static_types.Var (st, size)) sub_s s) in
update_memory_nondet tl m' assumes glbs rcd
| Dba.LValue.Restrict _ :: _ ->
failwith "UnrelState.ml: restrict case not handled2"
| Dba.LValue.Store (sz, endianness, e) :: tl ->
let m', assumes, rcd = store endianness addr sz Val.universe e s assumes
glbs rcd elements equalities in
update_memory_nondet tl m' assumes glbs rcd
in
let rec iterate cond iter assumes glbs rcd equalities =
if iter mod 100000 = 0
then Logger.debug "NONDET iterartion num %d" iter;
let m', assumes, rcd = update_memory_nondet lhslist s assumes glbs rcd in
let condi, assumes = eval_cond cond m' assumes glbs elements equalities in
match condi with
| Ternary.True -> m', assumes, rcd, equalities
| Ternary.False ->
iterate cond (iter + 1) assumes glbs rcd equalities
| Ternary.Unknown ->
guard addr cond m' assumes glbs rcd elements equalities
(* TODO : apply a guard here *)
in
let op, assumes, rcd, equalities = iterate cond 0 assumes glbs rcd equalities in
[addr_suiv, op, flgs, equalities], assumes, rcd
let resolve_nondet addr lhs region s flgs equalities addr_suiv assumes glbs rcd elements =
let _region = region in
let m = match lhs with
Dba.LValue.Var { Dba.name = st; Dba.size; _} ->
let loc = MemInterval.create Bigint.zero_big_int 1 in
let en = Machine.LittleEndian in
let sub_s = MemMap.add loc (loc, en, Val.universe) MemMap.empty in
let s = match s with None -> Env.empty | Some s -> s in
Some (Env.add (Static_types.Var (st, size)) sub_s s)
| Dba.LValue.Restrict _ ->
failwith "unrelState.ml: restrict case not handled"
| Dba.LValue.Store (size, Machine.BigEndian, expr) ->
let op, _assumes, _rcd = store_big_end addr size Val.universe expr s assumes glbs rcd elements equalities in
op
| Dba.LValue.Store (size, Machine.LittleEndian, expr) ->
let op, _assumes, _rcd = store_little_end addr size Val.universe expr s assumes glbs rcd elements equalities in
op
in
[addr_suiv, m, flgs, equalities]
let resolve_undef addr lhs s flgs equalities addr_suiv assumes glbs rcd elements =
TODO : Kset can contain an undef value or
it is to Top in this case
it is trqnsformed to Top in this case *)
let m = match lhs with
Dba.LValue.Var { Dba.name = st; Dba.size; _} ->
let loc = MemInterval.create Bigint.zero_big_int 1 in
let v =Val.singleton
(`Undef (computesize_dbalhs lhs)) in
let en = Machine.LittleEndian in
let sub_s = MemMap.add loc (loc, en, v) MemMap.empty in
let s = match s with None -> Env.empty | Some s -> s in
Some (Env.add (Static_types.Var (st, size)) sub_s s)
| Dba.LValue.Restrict _ ->
failwith "unrelState.ml: restrict case not handled3"
| Dba.LValue.Store (size, Machine.BigEndian, expr) ->
let v = Val.singleton
(`Undef (computesize_dbalhs lhs)) in
let op, _assumes, _rcd =
store_big_end addr size v expr s assumes glbs rcd elements equalities in
op
| Dba.LValue.Store (size, Machine.LittleEndian, expr) ->
let v = Val.singleton
(`Undef (computesize_dbalhs lhs)) in
let op, _assumes, _rcd =
store_little_end addr size v expr s assumes glbs rcd elements equalities in
op
in
[addr_suiv, m, flgs, equalities]
let resolve_print args s flgs equalities addr_suiv assumes glbs elements =
Logger.debug "%s" (string_of_args args s assumes glbs elements equalities);
[addr_suiv, s, flgs, equalities]
let remove_memory_overlaps equalities lhs1 m assumes glbs elements =
let open Dba in
match lhs1 with
| LValue.Store (sz1, _en1, e1) ->
let equals = Eq.copy_equalities equalities in
let lhs_list = Eq.get_elements equalities in
let zero = Region_bitvector.zeros 32 in
let sz1 = Region_bitvector.create_constant (Bigint.big_int_of_int sz1) 32 in
let v_sz1 = Val.of_bounds (zero, sz1) in
let v1, _ = eval_expr e1 m assumes glbs elements equals in
let v1 = Val.add v1 v_sz1 in
let remove_memory_overlap acc lhs2 =
match lhs2 with
| LValue.Store (sz2, _en2, e2) ->
let sz2 = Region_bitvector.create_constant (Bigint.big_int_of_int sz2) 32 in
let v_sz2 = Val.of_bounds (zero, sz2) in
let v2, _ = eval_expr e2 m assumes glbs elements equals in
let v2 = Val.add v2 v_sz2 in
if Val.is_empty (Val.meet v1 v2) then acc
else Eq.remove acc lhs2
| _ -> acc
in
List.fold_left remove_memory_overlap equalities lhs_list
| _ -> equalities
let update_equalities lhs e equalities v m assumes glbs elements =
match Dba.LValue.of_expr e with
| lhs_expr ->
if Eq.is_same_class equalities lhs lhs_expr
then equalities
else (
let equalities = Eq.remove_syntax_overlaps equalities lhs in
let equalities = remove_memory_overlaps equalities lhs m assumes glbs elements in
Display.display (Display.RemoveEqualities (lhs, Eq.to_string equalities));
Eq.union equalities lhs lhs_expr v
)
| exception Failure _ ->
let equalities = Eq.remove_syntax_overlaps equalities lhs in
Display.display (Display.RemoveEqualities (lhs, Eq.to_string equalities));
Eq.union equalities lhs lhs v
let post abs_vals addrStack instr cache assumes glbs djumps_map unrolled_loops elements =
let addr, cstack, loop = addrStack in
let rcd, rcd_conds = cache in
let m, flags, equalities = abs_vals in
let equalities = Eq.copy_equalities equalities in
let open Dba in
match instr with
| Dba.Instr.Stop (Some KO) ->
Errors.assert_failure addr instr
| Dba.Instr.Stop (Some (Undefined s)) ->
raise (Errors.Stop_Unsupported s)
| Dba.Instr.Stop (Some (Unsupported s)) ->
raise (Errors.Stop_Unsupported s)
| Dba.Instr.Stop _tag ->
[], cache, assumes, djumps_map
| Dba.Instr.Assign (lhs, expr, id_suiv) ->
let m', assumes', rcd, v = assign addrStack lhs expr m assumes glbs rcd elements equalities in
let flags = update_flags lhs expr flags in
let t0 = Unix.gettimeofday () in
let equalities = update_equalities lhs expr equalities v m assumes glbs elements in
Ai_options.time_equalities :=
Unix.gettimeofday () -. t0 +. !Ai_options.time_equalities;
Ai_options.nb_equalities_names :=
max (Eq.get_nb_names equalities) !Ai_options.nb_equalities_names;
Ai_options.nb_equalities_classes :=
max (Eq.get_nb_classes equalities) !Ai_options.nb_equalities_classes;
let cache = rcd, rcd_conds in
[ (Dba_types.Caddress.reid addr id_suiv, cstack, loop), m', flags, equalities],
cache, assumes', djumps_map
| Dba.Instr.Malloc (lhs, expr, id_suiv) ->
let v, assumes = eval_expr expr m assumes glbs elements equalities in
incr Dba_types.malloc_id;
let size =
let sz = Val.elements v in
match sz with
| (`Value (`Constant, size)) :: [] -> Bitvector.value_of size
| _ -> failwith "unrelstate.ml: malloc size"
in
let region = `Malloc ((!Dba_types.malloc_id, addr), size) in
let bv = Bitvector.zeros (Kernel_options.Machine.word_size ()) in
Simulate.mallocs := Malloc_status.add region Freeable !Simulate.mallocs;
let v = Dba.Expr.constant ~region bv in
let op,assumes,rcd,_ = assign addrStack lhs v m assumes glbs rcd elements equalities in
let cache = (rcd, rcd_conds) in
[ (Dba_types.Caddress.reid addr id_suiv, cstack, loop), op, flags, equalities], cache, assumes, djumps_map
| Dba.Instr.Free (expr, id_suiv) ->
let addr = Dba_types.Caddress.reid addr id_suiv in
let a = check_exec_permission addr m assumes glbs elements equalities in
let m = free expr m assumes glbs elements equalities in
let addrStack = (a, cstack, loop) in
[addrStack, m, flags, equalities], cache, assumes, djumps_map
| Dba.Instr.SJump (JInner id_suiv, _call_return_tag) ->
let a = Dba_types.Caddress.reid addr id_suiv in
let addrStack = a, cstack, loop in
[addrStack, m, flags, equalities], cache, assumes, djumps_map
| Dba.Instr.SJump (JOuter addr_suiv, Some Dba.Call addr_ret) ->
let calling_callee_addr = addr_ret, addr_suiv in
if is_visited calling_callee_addr cstack 20
then
raise (RecursiveCall addr_suiv)
else (
Display.display (Display.Call(addr_suiv, addr_ret));
let cstack = calling_callee_addr :: cstack in
let addrStack = addr_suiv, cstack, loop in
[addrStack, m, flags, equalities], cache, assumes, djumps_map
)
| Dba.Instr.SJump (JOuter addr_suiv, Some Return) ->
Display.increase_function_count ();
let cstack =
match cstack with
| (old_ret, _) :: cstack' ->
if Dba_types.Caddress.equal old_ret addr_suiv then cstack'
else cstack
| [] -> []
in
let addrStack = addr_suiv, cstack, loop in
[addrStack, m, flags, equalities], cache, assumes, djumps_map
| Dba.Instr.SJump (JOuter addr_suiv, _call_return_tag) ->
let addrStack = addr_suiv, cstack, loop in
[addrStack, m, flags, equalities], cache, assumes, djumps_map
(* *********************************************************** *)
| Dba.Instr.DJump (expr, call_return_tag) ->
let a, rcd, djumps_map =
resolve_jump addrStack expr m flags equalities rcd assumes glbs djumps_map call_return_tag elements in
let cache = rcd, rcd_conds in
a, cache, assumes, djumps_map
(* *********************************************************** *)
| Dba.Instr.If (condition, JOuter addr_suiv1, id_suiv2) ->
(* let loop, loop_a = loop in *)
let cond, rcd_conds = retrieve_comparison ~condition flags addr rcd_conds in
let eq1 = Eq.copy_equalities equalities in
let eq2 = Eq.copy_equalities equalities in
let m1, assumes, rcd, eq1 = guard addrStack cond m assumes glbs rcd elements eq1 in
let n_cond = Dba.Expr.lognot cond in
let m2, assumes, rcd, eq2 = guard addrStack n_cond m assumes glbs rcd elements eq2 in
let a1 = addr_suiv1 in
let a2 = Dba_types.Caddress.reid addr id_suiv2 in
let loops =
try Dba_types.Caddress.Map.find addr unrolled_loops
with Not_found -> Dba_types.Caddress.Set.empty
in
0 , 0
if Dba_types.Caddress.Set.cardinal loops = 1
then
if Dba_types.Caddress.Set.mem a1 loops
then min (loop + 1) 50, 0
else 0, min (loop + 1) 50
else loop, loop
in
let addr_suiv1 = (a1, cstack, loop1) in
let addr = (a2, cstack, loop2) in
let l = resolve_if cond m flags (m1, eq1) (m2, eq2) addr_suiv1 addr assumes glbs elements equalities in
let cache = (rcd, rcd_conds) in
l, cache, assumes, djumps_map
| Dba.Instr.If (condition, JInner id_suiv1, id_suiv2) ->
(* let loop, loop_a = loop in *)
let cond, rcd_conds = retrieve_comparison ~condition flags addr rcd_conds in
let eq1 = Eq.copy_equalities equalities in
let eq2 = Eq.copy_equalities equalities in
let m1, assumes, rcd, eq1 =
guard addrStack cond m assumes glbs rcd elements eq1 in
let ncond = Dba.Expr.lognot cond in
let m2, assumes, rcd, eq2 =
guard addrStack ncond m assumes glbs rcd elements eq2 in
let loops =
try Dba_types.Caddress.Map.find addr unrolled_loops
with Not_found -> Dba_types.Caddress.Set.empty
in
let a1 = Dba_types.Caddress.reid addr id_suiv1 in
let a2 = Dba_types.Caddress.reid addr id_suiv2 in
0 , 0
if Dba_types.Caddress.Set.cardinal loops = 1
then
if Dba_types.Caddress.Set.mem a1 loops
then min (loop + 1) 50, 0
else 0, min (loop + 1) 50
else loop, loop
in
let a1 = (a1, cstack, loop1) in
let a2 = (a2, cstack, loop2) in
let l = resolve_if cond m flags (m1, eq1) (m2, eq2) a1 a2 assumes glbs elements equalities in
let cache = (rcd, rcd_conds) in
l, cache, assumes, djumps_map
| Dba.Instr.Assert (condition, id_suiv) ->
let cond, rcd_conds = retrieve_comparison ~condition flags addr rcd_conds in
let a = (Dba_types.Caddress.reid addr id_suiv, cstack, loop) in
let l = resolve_assert cond m flags equalities a addrStack instr assumes glbs rcd elements in
let cache = (rcd, rcd_conds) in
l, cache, assumes, djumps_map
| Dba.Instr.Assume (condition, id_suiv) ->
let cond, rcd_conds = retrieve_comparison ~condition flags addr rcd_conds in
let a = (Dba_types.Caddress.reid addr id_suiv, cstack, loop) in
let l = resolve_assume addrStack cond m flags equalities a assumes glbs rcd elements in
let cache = (rcd, rcd_conds) in
l, cache, assumes, djumps_map
| Dba.Instr.NondetAssume (lhslst, condition, id_suiv) ->
let cnd, rcd_conds = retrieve_comparison ~condition flags addr rcd_conds in
let a = (Dba_types.Caddress.reid addr id_suiv, cstack, loop) in
let op, assumes, rcd =
resolve_nondet_assume addrStack lhslst cnd m flags equalities a assumes glbs rcd elements in
let cache = (rcd, rcd_conds) in
op, cache, assumes, djumps_map
| Dba.Instr.Nondet (lhs, region, id_suiv) ->
let a = (Dba_types.Caddress.reid addr id_suiv, cstack, loop) in
let op = resolve_nondet addrStack lhs region m flags equalities a assumes glbs rcd elements in
op, cache, assumes, djumps_map
| Dba.Instr.Undef (lhs, id_suiv) ->
let a = (Dba_types.Caddress.reid addr id_suiv, cstack, loop) in
let l = resolve_undef addrStack lhs m flags equalities a assumes glbs rcd elements in
l, cache, assumes, djumps_map
| Dba.Instr.Print (args, id_suiv) ->
let a = (Dba_types.Caddress.reid addr id_suiv, cstack, loop) in
let l = resolve_print args m flags equalities a assumes glbs elements in
l, cache, assumes, djumps_map
let get_initial_state inits =
let addr = Dba_types.Caddress.block_start @@ Virtual_address.create 0 in
let cstack = [] in
let loop = 0 in
let addrStack = (addr, cstack, loop) in
let rcd = Dba_types.AddressStack.Map.empty in
let equalities = Eq.create () in
let conds = [] in
let glbs = Dba_types.Caddress.Set.empty in
let djmps = Dba_types.AddressStack.Map.empty in
let flags = High_level_predicate.empty in
let rcd_conds = Dba_types.Caddress.Map.empty in
let unrolled_loops = Dba_types.Caddress.Map.empty in
let cache = rcd, rcd_conds in
let init_state m instr =
let abs_vals = m, flags, equalities in
post abs_vals addrStack instr cache conds glbs djmps unrolled_loops []
in
let f m instr =
match init_state m instr with
| (_, res, _, _) :: _, _, _, _ -> res
| [], _, _, _ -> assert false
in
let m_top = Some Env.empty in
List.fold_left f m_top inits
let _projection _s _p = failwith "Not implemented"
let env_to_smt_list m varIndexes inputs =
let env, inputs =
match m with
| None -> [], inputs
| Some m ->
Env.fold (
fun key sub_m (acc, inputs) ->
match key with
| Static_types.Var (n, size) ->
MemMap.fold (fun _bv (_, _, v) (acc, inputs) ->
let id =
try String.Map.find n varIndexes
with Not_found -> 0
in
let name = n^(string_of_int id) in
let var = Formula.bv_var name size in
let var1 = Formula.BvVar var in
let var2 = Formula.mk_bv_var var in
if Formula.VarSet.mem var1 inputs then
(Val.to_smt v var2) @ acc, inputs
else
let inputs = Formula.VarSet.add var1 inputs in
(Val.to_smt v var2) @ acc, inputs) sub_m (acc, inputs)
| Static_types.Array region ->
MemMap.fold (fun bv (_, en, v) (acc, inputs) ->
let i = MemInterval.base_of bv in
let size = MemInterval.size_of bv in
let expr = Dba.Expr.constant ~region (Bitvector.create i 32) in
let var, inputs =
Normalize_instructions.load_to_smt expr size en inputs varIndexes in
(Val.to_smt v var) @ acc, inputs) sub_m (acc, inputs)
) m ([], inputs)
in
match !s_init with
| None -> env, inputs
| Some s ->
Env.fold (fun key sub_m (acc, inputs) ->
match key with
| Static_types.Array `Constant ->
MemMap.fold (fun bv (_, en, v) (acc, inputs) ->
let i = MemInterval.base_of bv in
let size = MemInterval.size_of bv in
let c =
match m with
None -> true
| Some m ->
try let _ = MemMap.find bv (Env.find (Static_types.Array `Constant) m) in
false
with Not_found -> true
in
if c then
let expr = Dba.Expr.constant (Bitvector.create i 32) in
let var, inputs = Normalize_instructions.load_to_smt expr size en inputs varIndexes in
Val.to_smt v var @ acc, inputs
else acc, inputs) sub_m (acc, inputs)
| Static_types.Array `Stack
| Static_types.Array `Malloc ((_, _), _)
| Static_types.Var (_, _) -> acc, inputs
) s (env, inputs)
let refine_state m smt_env =
match m with
| None -> m
| Some m ->
let new_m = Env.fold (
fun key sub_m acc ->
match key with
| Static_types.Var (n, _size) ->
if n = "eax" || n = "ecx" || n = "ebx" || n = "edx" then
let name = n ^ "0" in
let new_sub_m =
MemMap.fold
(fun bv (a, en, v) acc ->
let new_v = Val.smt_refine v smt_env name in
Logger.debug "Refining %s: %a -> %a" name Val.pp v Val.pp new_v;
MemMap.add bv (a, en, new_v) acc)
sub_m sub_m
in Env.add key new_sub_m acc
else acc
| Static_types.Array `Constant -> acc
| Static_types.Array `Stack ->
let new_sub_m =
MemMap.fold
(fun bv (a, en, v) acc ->
match MemInterval.size_of bv with
| 4 ->
let i = MemInterval.base_of bv in
let addr =
Formula_pp.print_bv_term
(Formula.mk_bv_cst (Bitvector.create i 32)) in
let name = Format.asprintf "(load32_at memory0 %s)" addr in
let v' = Val.smt_refine v smt_env name in
Logger.debug "Refining %s: %a -> %a" name Val.pp v Val.pp v';
MemMap.add bv (a, en, v') acc
| _ -> acc)
sub_m sub_m
in Env.add key new_sub_m acc
| Static_types.Array ((`Malloc ((_id, _), _))) -> acc
) m m in
Some new_m
end
| null |
https://raw.githubusercontent.com/binsec/haunted/7ffc5f4072950fe138f53fe953ace98fff181c73/src/static/ai/nonrelational.ml
|
ocaml
|
************************************************************************
alternatives)
you can redistribute it and/or modify it under the terms of the GNU
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
************************************************************************
Env
Beware of this function if you have integers bigger than max_int
for each constraint in s1 there
should be a stricter constraint in s2
Redefinition for stat purposes
add_time_without_equalities time;
Checking read of memory permissions here
Checking write to memory permissions here
FIXME ?
TODO : apply a guard here
***********************************************************
***********************************************************
let loop, loop_a = loop in
let loop, loop_a = loop in
|
This file is part of BINSEC .
Copyright ( C ) 2016 - 2019
CEA ( Commissariat à l'énergie atomique et aux énergies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
open Dba_utils
open! Basic_types
open High_level_predicate
open Format
open Ai_options
exception RecursiveCall of Dba.address
module Malloc_status = Dba_types.Region.Map
module MemInterval = struct
type t = {
base : Bigint.t;
size : Size.Byte.t;
}
let create base n =
assert (n >= 0);
{ base; size = Size.Byte.create n; }
let size_of m = Size.Byte.to_int m.size
let base_of m = m.base
let upper_bound m =
Bigint.(pred_big_int (add_int_big_int (Size.Byte.to_int m.size) m.base))
let compare m1 m2 =
if Bigint.lt_big_int (upper_bound m1) m2.base then -1
else if Bigint.lt_big_int (upper_bound m2) m1.base then 1
compare
let _overlap m1 m2 =
not (Bigint.lt_big_int (upper_bound m1) m2.base &&
Bigint.lt_big_int (upper_bound m2) m1.base)
let same_base m1 m2 = m1.base = m2.base
let equal m1 m2 = same_base m1 m2 && m1.size = m2.size
let empty = create Bigint.zero_big_int 1
let pp ppf t =
Format.fprintf ppf "@[0x%x+%a@]"
(Bigint.int_of_big_int t.base)
Size.Byte.pp_hex t.size
end
module MemMap = Map.Make(MemInterval)
exception Emptyset
exception Unknown
type update_type = Strong | Weak
module Make(Val: Ai_sigs.Domain) =
struct
module Eq = Union_find.Make (Val)
type env = (MemInterval.t * Machine.endianness * Val.t) MemMap.t Env.t
type t = env option
type equalities = Eq.t
type thresholds = int array * int array * int array * int array
type elementsRecord = Region_bitvector.t list Dba_types.AddressStack.Map.t
type naturalPredicatesRecord = (Dba.Expr.t * Dba.Expr.t) Dba_types.Caddress.Map.t
let default_address =
Dba_types.Caddress.block_start @@ Virtual_address.create 0, [], 0
X86 : : Default size to 32
let current_address = ref default_address
let top = Some Env.empty, High_level_predicate.empty, Eq.create ()
let bottom = None, High_level_predicate.bottom, Eq.bottom
let is_empty s =
match s with
| None -> true
| Some _ -> false
let s_init : (env option) ref = ref (Some Env.empty)
let pp ppf t =
match t with
| None -> fprintf ppf "{}"
| Some env ->
let pp key subenv =
match key with
| Static_types.Var (name, _) ->
fprintf ppf "@[<v 0>";
MemMap.iter
(fun _ (_, _, value) ->
fprintf ppf "%s = %a@ " name Val.pp value) subenv;
fprintf ppf "@]"
| Static_types.Array region ->
fprintf ppf "@[<v 0>Region %a@ {@[<hov 0>"
Dba_printer.Ascii.pp_region region;
MemMap.iter
(fun mloc (_, _, value) ->
fprintf ppf "%a -> %a;@ " MemInterval.pp mloc Val.pp value)
subenv;
fprintf ppf "@]}@]@ ";
in
fprintf ppf "@[<v 1>{";
Env.iter pp env;
fprintf ppf "}@]"
let pp_equalities ppf equalities = Eq.pp ppf equalities
let to_string (s, equalities) =
fprintf str_formatter "@[<v 0>";
if not (is_empty s) then
Format.fprintf Format.str_formatter "Env:@ %a@ " pp s;
fprintf str_formatter "Equalities@ %a@ " pp_equalities equalities;
fprintf str_formatter "@]";
Format.flush_str_formatter ()
let regs_in_expr_to_string expr ppf (s, _, _) =
let contains_expr_var expr var =
let s1 = asprintf "%a" Dba_printer.Ascii.pp_bl_term expr in
let re = Str.regexp_string var in
try ignore (Str.search_forward re s1 0); true
with Not_found -> false
in
match s with
| None -> fprintf ppf "{}"
| Some s ->
fprintf ppf "@[<hov 0>";
Env.iter (
fun key sub_m ->
match key with
| Static_types.Var (vname, _) ->
if contains_expr_var expr vname
then
MemMap.iter (fun _ (_, _, v) ->
fprintf ppf ".%s: %s; "
vname (Val.to_string v))
sub_m
| Static_types.Array _ -> ()
) s;
fprintf ppf "@]"
let read key subkey s =
try let _, _, v = (MemMap.find subkey (Env.find key s)) in v
with Not_found -> Val.universe
let leq s1 s2 =
match (s1, s2) with
| _, None -> false
| None, _ -> true
| Some s1, Some s2 ->
let has_constraint key subkey (_, _, v2) =
let v1 = read key subkey s1 in Val.contains v2 v1
in Env.for_all (fun k v -> MemMap.for_all (has_constraint k) v) s2
let rec collect loc id size sub_m =
if id > size then raise Not_found
else
try MemMap.find (MemInterval.create loc id) sub_m
with Not_found -> collect loc (id + 1) size sub_m
let join (s1, flgs1, equalities1) (s2, flgs2, equalities2) =
match (s1, s2) with
| (None, s) -> (s, flgs2, equalities2)
| (s, None) -> (s, flgs1, equalities1)
| (Some s1, Some s2) ->
let rec join_values sub_s2 _ (mloc1, en1, v1) acc =
let size1 = MemInterval.size_of mloc1 in
let base1 = MemInterval.base_of mloc1 in
try
let mloc2, en2, v2 = collect base1 1 size1 sub_s2 in
let size2 = MemInterval.size_of mloc2 in
let base2 = MemInterval.base_of mloc2 in
if MemInterval.equal mloc1 mloc2 && (en1 = en2)
then MemMap.add mloc1 (mloc1, en1, Val.join v1 v2) acc
else
if MemInterval.same_base mloc1 mloc2 && en1 = en2 && en1 = Machine.LittleEndian
then
if size1 < size2
then
let v2' = Val.restrict v2 0 ((size1 * 8) - 1) in
MemMap.add mloc1 (mloc1, en1, Val.join v1 v2') acc
else (
let v1' = Val.restrict v1 0 ((size2 * 8) - 1) in
let v = Val.join v1' v2 in
let loc = MemInterval.create base1 size2 in
let acc = MemMap.add loc (loc, en1, v) acc in
let v1'' = Val.restrict v1 (size2 * 8) (size1 * 8 - 1) in
let sz = Bigint.big_int_of_int size2 in
let base1 = Bigint.add_big_int base1 sz in
let sz = size1 - size2 in
let loc = MemInterval.create base1 sz in
join_values sub_s2 loc (loc, en1, v1'') acc
)
else
if en1 = en2 && en1 = Machine.LittleEndian
then
if Bigint.lt_big_int base1 base2
then
let sz = Bigint.sub_big_int base2 base1 in
let sz = Bigint.int_of_big_int sz in
let sz1 = size1 - sz in
let loc = MemInterval.create base2 sz1 in
let v1' = Val.restrict v1 (sz * 8) (size1 * 8 - 1) in
join_values sub_s2 loc (loc, en1, v1') acc
else
let sz = Bigint.sub_big_int base1 base2 in
let sz = Bigint.int_of_big_int sz in
let sz2 = size2 - sz in
let v2' = Val.restrict v2 (sz * 8) (size2 * 8 - 1) in
if size1 = sz2 then
let loc = MemInterval.create base1 size1 in
MemMap.add loc (loc, en1, Val.join v1 v2') acc
else if size1 < sz2
then
let v2' = Val.restrict v2' 0 ((size1 * 8) - 1) in
MemMap.add mloc1 (mloc1, en1, Val.join v1 v2') acc
else (
let v1' = Val.restrict v1 0 ((sz2 * 8) - 1) in
let v = Val.join v1' v2 in
let loc = MemInterval.create base1 sz in
let acc = MemMap.add loc (loc, en1, v) acc in
let v1'' = Val.restrict v1 (sz2 * 8) (size1 * 8 - 1) in
let sz = Bigint.big_int_of_int sz2 in
let base1 = Bigint.add_big_int base1 sz in
let sz = size1 - sz2 in
let loc = MemInterval.create base1 sz in
join_values sub_s2 loc (loc, en1, v1'') acc
)
else failwith "unrelState.ml: fail3"
with Not_found -> acc
in
let sub_join array_var sub_s1 =
try let sub_s2 = Env.find array_var s2 in
MemMap.fold (join_values sub_s2) sub_s1 MemMap.empty
with Not_found -> MemMap.empty
in
let s = Some (Env.mapi sub_join s1) in
let flgs = High_level_predicate.join flgs1 flgs2 in
let t0 = Unix.gettimeofday () in
let equalities = Eq.join equalities1 equalities2 in
Ai_options.time_equalities := Unix.gettimeofday () -. t0 +. !Ai_options.time_equalities;
(s, flgs, equalities)
let widen (s1, flgs1, equalities1) (s2, flgs2, equalities2) thresholds =
match (s1, s2) with
| (None, s) -> (s, flgs2, equalities2)
| (s, None) -> (s, flgs1, equalities1)
| (Some s1, Some s2) ->
let rec widen_values sub_s2 _ (base1,en1,v1) acc =
let size1 = MemInterval.size_of base1 in
let base1 = MemInterval.base_of base1 in
try
let (base2, en2, v2) = collect base1 1 size1 sub_s2 in
let size2 = MemInterval.size_of base2 in
let base2 = MemInterval.base_of base2 in
if (Bigint.eq_big_int base1 base2) && (size1 = size2) && (en1 = en2)
then
let loc = MemInterval.create base1 size1 in
MemMap.add loc (loc, en1, Val.widen v1 v2 thresholds) acc
else
if (Bigint.eq_big_int base1 base2) && (en1 = en2) && (en1 = Machine.LittleEndian)
then
if size1 < size2
then
let v2' = Val.restrict v2 0 ((size1 * 8) - 1) in
let loc = MemInterval.create base1 size1 in
MemMap.add loc (loc, en1, Val.widen v1 v2' thresholds) acc
else (
let v1' = Val.restrict v1 0 ((size2 * 8) - 1) in
let v = Val.widen v1' v2 thresholds in
let loc = MemInterval.create base1 size2 in
let acc = MemMap.add loc (loc, en1, v) acc in
let v1'' = Val.restrict v1 (size2 * 8) (size1 * 8 - 1) in
let sz = Bigint.big_int_of_int size2 in
let base1 = Bigint.add_big_int base1 sz in
let sz = size1 - size2 in
let loc = MemInterval.create base1 sz in
widen_values sub_s2 loc (loc, en1, v1'') acc
)
else
if (en1 = en2) && (en1 = Machine.LittleEndian)
then
if (Bigint.lt_big_int base1 base2)
then
let sz = Bigint.sub_big_int base2 base1 in
let sz = Bigint.int_of_big_int sz in
let sz1 = size1 - sz in
let loc = MemInterval.create base2 sz1 in
let v1' = Val.restrict v1 (sz * 8) (size1 * 8 - 1) in
widen_values sub_s2 loc (loc, en1, v1') acc
else
let sz = Bigint.sub_big_int base1 base2 in
let sz = Bigint.int_of_big_int sz in
let sz2 = size2 - sz in
let v2' = Val.restrict v2 (sz * 8) (size2 * 8 - 1) in
if size1 = sz2 then
let loc = MemInterval.create base1 size1 in
MemMap.add loc (loc, en1, Val.widen v1 v2' thresholds) acc
else if size1 < sz2
then
let v2' = Val.restrict v2' 0 ((size1 * 8) - 1) in
let loc = MemInterval.create base1 size1 in
MemMap.add loc (loc, en1, Val.widen v1 v2' thresholds) acc
else (
let v1' = Val.restrict v1 0 ((sz2 * 8) - 1) in
let v = Val.widen v1' v2 thresholds in
let loc = MemInterval.create base1 sz in
let acc = MemMap.add loc (loc, en1, v) acc in
let v1'' = Val.restrict v1 (sz2 * 8) (size1 * 8 - 1) in
let sz = Bigint.big_int_of_int sz2 in
let base1 = Bigint.add_big_int base1 sz in
let sz = size1 - sz2 in
let loc = MemInterval.create base1 sz in
widen_values sub_s2 loc (loc, en1, v1'') acc
)
else failwith "unrelState.ml: fail3"
with Not_found -> acc
in
let sub_widen array_var sub_s1 =
try let sub_s2 = Env.find array_var s2 in
MemMap.fold (widen_values sub_s2) sub_s1 MemMap.empty
with Not_found -> MemMap.empty
in
let s = Some (Env.mapi sub_widen s1) in
let flgs = High_level_predicate.join flgs1 flgs2 in
let l0 = Unix.gettimeofday () in
let equalities = Eq.widen equalities1 equalities2 thresholds in
Ai_options.time_equalities := Unix.gettimeofday () -. l0 +. !Ai_options.time_equalities;
(s, flgs, equalities)
let meet s1 s2 =
match s1, s2 with
| (None, _) | (_, None) -> None
| (Some s1, Some s2) ->
let res = ref Env.empty in
let meet_info key subkey (i, en, v1) =
let v2 = read key subkey s2 in
let v = Val.meet v1 v2 in
res := match key with
| Static_types.Var _ ->
let loc = subkey in
let sub_s = MemMap.add loc (loc, en, v) MemMap.empty in
(Env.add key sub_s !res)
| Static_types.Array r ->
let sub_s =
try Env.find (Static_types.Array r) !res
with Not_found -> MemMap.empty in
let sub_s = MemMap.add subkey (i, en, v) sub_s in
(Env.add (Static_types.Array r) sub_s !res)
in
Env.iter (fun key v -> MemMap.iter (meet_info key) v) s1;
Some !res
let add_addr_macro (s : t) elem =
let bv = Region_bitvector.bitvector_of elem in
let v = Val.singleton (`Value (`Constant, bv)) in
let loc = MemInterval.create Bigint.zero_big_int 1 in
let en = Machine.LittleEndian in
let sub_s = MemMap.add loc (loc, en, v) MemMap.empty in
let v_addr = Var ("\\addr", Kernel_options.Machine.word_size ()) in
let s =
match s with
| None -> Some (Env.add v_addr sub_s Env.empty)
| Some s -> Some (Env.add v_addr sub_s s)
in s
let rec is_mul expr =
match expr with
| Dba.Expr.Cst _
| Dba.Expr.Var _ -> ()
| Dba.Expr.Load (_, _, expr)
| Dba.Expr.Unary (_, expr) -> is_mul expr
| Dba.Expr.Binary (Dba.Binary_op.Mult, _expr1, _expr2) -> raise Errors.Enumerate_Top
| Dba.Expr.Ite (_, expr1, expr2)
| Dba.Expr.Binary (_, expr1, expr2) -> is_mul expr1; is_mul expr2
let rec eval_expr expr s assumes globals elements equalities =
let eval_without_equalities () =
match expr with
| Dba.Expr.Var { Dba.name = st; Dba.size; _} ->
let v =
let loc = (Bigint.zero_big_int, 1, Machine.LittleEndian) in
try load (Static_types.Var (st, size)) loc s assumes globals elements equalities
with Not_found | Errors.Empty_env ->
try load (Static_types.Var (st, size)) loc !s_init assumes globals elements equalities
with Not_found -> Val.universe
in v, assumes
| Dba.Expr.Load (size, en, e) -> (
try
let v_exp, assumes = eval_expr e s assumes globals elements equalities in
let indexes =
try let _ = is_mul e in
Val.elements v_exp
with Errors.Enumerate_Top ->
if List.length elements = 0
then raise Errors.Enumerate_Top
else elements
in
List.fold_right (fun elem acc ->
let region = Region_bitvector.region_of elem in
let i = Region_bitvector.value_of elem in
let s = add_addr_macro s elem in
let arr = Array region in
let ret = load arr (i, size, en) s assumes globals elements equalities in
Val.join ret acc
) indexes Val.empty, assumes
with Val.Elements_of_top -> Val.universe, assumes
)
| Dba.Expr.Cst (r, v) -> Val.singleton (`Value (r, v)), assumes
| Dba.Expr.Unary (uop, expr) ->
let e, assumes = eval_expr expr s assumes globals elements equalities in
let f =
match uop with
| Dba.Unary_op.UMinus -> Val.neg
| Dba.Unary_op.Not -> Val.lognot
| Dba.Unary_op.Uext n -> fun e -> Val.extension e n
| Dba.Unary_op.Sext n -> fun e -> Val.signed_extension e n
| Dba.Unary_op.Restrict {Interval.lo; Interval.hi} ->
fun e -> Val.restrict e lo hi
in f e, assumes
| Dba.Expr.Binary (bop, expr1, expr2) ->
let op1, assumes = eval_expr expr1 s assumes globals elements equalities in
let op2, assumes = eval_expr expr2 s assumes globals elements equalities in
let build_bop =
match bop with
| Dba.Binary_op.Plus -> Val.add
| Dba.Binary_op.Minus -> Val.sub
| Dba.Binary_op.Mult -> Val.mul
| Dba.Binary_op.DivU -> Val.udiv
| Dba.Binary_op.DivS -> Val.sdiv
| Dba.Binary_op.ModU -> Val.umod
| Dba.Binary_op.ModS -> Val.smod
| Dba.Binary_op.Or -> Val.logor
| Dba.Binary_op.And -> Val.logand
| Dba.Binary_op.Xor -> Val.logxor
| Dba.Binary_op.Concat -> Val.concat
| Dba.Binary_op.LShift -> Val.lshift
| Dba.Binary_op.RShiftU -> Val.rshiftU
| Dba.Binary_op.RShiftS -> Val.rshiftS
| Dba.Binary_op.LeftRotate -> Val.rotate_left
| Dba.Binary_op.RightRotate -> Val.rotate_right
| Dba.Binary_op.Eq -> Val.eq
| Dba.Binary_op.Diff -> Val.diff
| Dba.Binary_op.LeqU -> Val.leqU
| Dba.Binary_op.LtU -> Val.ltU
| Dba.Binary_op.GeqU -> Val.geqU
| Dba.Binary_op.GtU -> Val.gtU
| Dba.Binary_op.LeqS -> Val.leqS
| Dba.Binary_op.LtS -> Val.ltS
| Dba.Binary_op.GeqS -> Val.geqS
| Dba.Binary_op.GtS -> Val.gtS
in build_bop op1 op2, assumes
| Dba.Expr.Ite (cond, expr1, expr2) ->
let cond, assumes = eval_cond cond s assumes globals elements equalities in
begin match cond with
| Ternary.True ->
eval_expr expr1 s assumes globals elements equalities
| Ternary.False ->
eval_expr expr2 s assumes globals elements equalities
| Ternary.Unknown ->
let op1 =
eval_expr expr1 s assumes globals elements equalities |> fst
and op2 =
eval_expr expr2 s assumes globals elements equalities |> fst
in Val.join op1 op2, assumes
end
in
let eval_without_equalities () =
Display.save_evaluation_counts ();
let _time, v = Utils.time (eval_without_equalities) in
Display.restore_evaluation_counts ();
v
in
Display.increase_evaluation_count ();
match Dba.LValue.of_expr expr with
| lhs_e ->
Display.increase_lhs_evaluation_count ();
let t0 = Unix.gettimeofday () in
let equal_lhs_e, equal_v_e = Eq.find equalities lhs_e in
Ai_options.time_equalities := Unix.gettimeofday () -. t0
+. !Ai_options.time_equalities;
begin
match equal_lhs_e, equal_v_e with
| _, None | None, _ -> eval_without_equalities ()
| Some lhs_eq, Some v ->
Display.increase_lhseq_evaluation_count ();
if not (Dba.LValue.equal lhs_e lhs_eq) then
Display.equality_use !current_address lhs_eq lhs_e;
let v_without_equalities, _ = eval_without_equalities () in
if Val.contains v_without_equalities v &&
not (Val.contains v v_without_equalities)
then incr Ai_options.nb_equalities_refinement;
v, assumes
end
| exception Failure _ -> eval_without_equalities ()
and eval_cond expr s assumes globals elements equalities =
try
let op,assumes = eval_expr expr s assumes globals elements equalities in
Val.is_true op assumes globals, assumes
with Smt_bitvectors.Assume_condition smb ->
let assumes = smb :: assumes in
eval_cond expr s assumes globals elements equalities
and get_elem i r m =
let en = Machine.LittleEndian in
try MemMap.find (MemInterval.create i 1) (Env.find (Static_types.Array r) m)
with Not_found ->
match !s_init with
| None -> raise Errors.Empty_env
| Some s ->
try MemMap.find (MemInterval.create i 1) (Env.find (Static_types.Array r) s)
with Not_found ->
if Region_bitvector.region_equal r `Constant
then begin
let value =
try Val.singleton (Region_bitvector.get_byte_region_at i)
with _ -> Val.universe
in
Display.add_call i;
MemInterval.create i 1, en, value
end
else MemInterval.create i 1, en, Val.universe
and retrieve_value_little i r m =
let size = MemInterval.size_of i in
let i = MemInterval.base_of i in
let a, en, value = get_elem i r m in
let sz = MemInterval.size_of a in
let a = MemInterval.base_of a in
match en with
| Machine.LittleEndian ->
if Bigint.eq_big_int a i && sz = size
then value
else if Bigint.eq_big_int a i
then
if size < sz
then Val.restrict value 0 ((size * 8) - 1)
else
let sz' = Bigint.big_int_of_int sz in
let i = Bigint.add_big_int i sz' in
let v = retrieve_value_little (MemInterval.create i (size - sz)) r m in
Val.concat v value
else
let sz_minus1 = Bigint.big_int_of_int (sz - 1) in
let size_minus1 = Bigint.big_int_of_int (size - 1) in
let upper_a = (Bigint.add_big_int a sz_minus1) in
let upper_i = (Bigint.add_big_int i size_minus1) in
if Bigint.lt_big_int a i then
if Bigint.ge_big_int upper_a upper_i
then
let delta = Bigint.sub_big_int i a in
let off1 = (Bigint.int_of_big_int delta) * 8 in
let off2 = off1 + size * 8 - 1 in
Val.restrict value off1 off2
else
let delta = Bigint.sub_big_int i a in
let off1 = (Bigint.int_of_big_int delta) * 8 in
let off2 = (sz * 8) - 1 in
let v1 = Val.restrict value off1 off2 in
let i = Bigint.succ_big_int upper_a in
let size = Bigint.sub_big_int upper_i upper_a in
let size = Bigint.int_of_big_int size in
let v2 = retrieve_value_little (MemInterval.create i size) r m in
Val.concat v2 v1
else failwith "unrelSate.ml: load_little_e"
| Machine.BigEndian ->
let rec invert value off1 off2 acc sz =
if sz < 1
then acc
else let v = Val.restrict value off1 off2 in
let acc = Val.concat acc v in
invert value (off1 + 8) (off2 + 8) acc (sz - 1)
in
if (Bigint.eq_big_int a i) && (sz=size)
then
let v = Val.restrict value 0 7 in
invert value 8 15 v (sz - 1)
else if (Bigint.eq_big_int a i)
then
if size < sz
then
let off1 = (sz - size) * 8 in
let off2 = off1 + 7 in
let v = Val.restrict value off1 off2 in
invert value off1 off2 v (size - 1)
else
let v = Val.restrict value 0 7 in
let v1 = invert value 8 15 v (sz - 1) in
let sz' = Bigint.big_int_of_int sz in
let i = Bigint.add_big_int i sz' in
let v2 = retrieve_value_little (MemInterval.create i (size - sz)) r m in
Val.concat v2 v1
else failwith "unrelSate.ml: impossible case in load_big_e"
and retrieve_value_big i r m =
let size = MemInterval.size_of i in
let i = MemInterval.base_of i in
let en = Machine.LittleEndian in
let a, _en, value =
try MemMap.find (MemInterval.create i 1) (Env.find (Static_types.Array r) m)
with Not_found ->
match !s_init with
| None -> raise Errors.Empty_env
| Some s ->
try MemMap.find (MemInterval.create i 1) (Env.find (Static_types.Array r) s)
with Not_found ->
let v =
try Val.singleton (Region_bitvector.get_byte_region_at i)
with Errors.Invalid_address _ -> Val.universe
in MemInterval.create i 1, en, v
in
let sz = MemInterval.size_of a in
let a = MemInterval.base_of a in
if Bigint.eq_big_int a i && sz = size
then value
else if Bigint.eq_big_int a i
then
if size < sz
then Val.restrict value 0 (size - 1)
else
let i = Bigint.add_big_int i (Bigint.big_int_of_int sz) in
let v = retrieve_value_big (MemInterval.create i (size - sz)) r m in
Val.concat v value
else
let sz_minus1 = Bigint.big_int_of_int (sz - 1) in
let size_minus1 = Bigint.big_int_of_int (size - 1) in
let upper_a = (Bigint.add_big_int a sz_minus1) in
let upper_i = (Bigint.add_big_int i size_minus1) in
if Bigint.lt_big_int a i then
if Bigint.ge_big_int upper_a upper_i
then
let delta = Bigint.sub_big_int upper_a upper_i in
let off1 = Bigint.int_of_big_int delta in
let off2 = sz - 1 in
Val.restrict value off1 off2
else
let off1 = 0 in
let delta = Bigint.sub_big_int upper_a i in
let off2 = Bigint.int_of_big_int delta in
let v1 = Val.restrict value off1 off2 in
let i = Bigint.succ_big_int upper_a in
let size = off2 - off1 + 1 in
let v2 = retrieve_value_big (MemInterval.create i size) r m in
Val.concat v2 v1
else failwith "unrelSate.ml: impossible case in load_big"
and load x (i, size, en) m assumes globals elements equalities =
match m with
| None -> raise Errors.Empty_env
| Some m ->
match x with
| Static_types.Var _ ->
let loc = MemInterval.create Bigint.zero_big_int 1 in
let _, _, av = MemMap.find loc (Env.find x m) in av
| Static_types.Array r ->
let c =
try Dba_types.Rights.find_read_right r !Concrete_eval.permis
with Not_found -> Dba.Expr.one in
let b, _assumes = eval_cond c (Some m) assumes globals elements equalities in
match b with
| Ternary.True ->
begin
match en with
| Machine.LittleEndian ->
retrieve_value_little (MemInterval.create i size) r m
| Machine.BigEndian ->
retrieve_value_big (MemInterval.create i size) r m
end
| Ternary.False -> raise Errors.Read_permission_denied
| Ternary.Unknown -> failwith "read permission unknown"
and update base en old_value new_value sub_m =
let size = MemInterval.size_of base in
let base = MemInterval.base_of base in
let loc = MemInterval.create base size in
let v = Val.join old_value new_value in
MemMap.add loc (loc, en, v) sub_m
and clear_at_beginning old_info new_info sub_m _sw =
Logger.debug "Clear beginning";
let (old_loc, old_size, old_en, old_value) = old_info in
let (_new_loc, new_size, _new_en, _new_value) = new_info in
let off1 = new_size * 8 in
let off2 = old_size * 8 - 1 in
assert (off1 <= off2);
let v = Val.restrict old_value off1 off2 in
let sz = Bigint.big_int_of_int new_size in
let base = Bigint.add_big_int old_loc sz in
let loc = MemInterval.create base (old_size - new_size) in
let sub_m = MemMap.add loc (loc, old_en, v) sub_m in
sub_m
and update_at_beginning old_info new_info sub_m sw =
let (old_loc, old_size, old_en, old_value) = old_info in
let (new_loc, new_size, new_en, new_value) = new_info in
if sw = Strong
then
clear_at_beginning old_info new_info sub_m sw
else
let off1 = 0 in
let off2 = 8 * new_size - 1 in
assert (off1 <= off2);
let v = Val.restrict old_value off1 off2 in
let loc = MemInterval.create new_loc new_size in
let sub_m = update loc new_en v new_value sub_m in
let off1 = new_size * 8 in
let off2 = old_size * 8 - 1 in
assert (off1 <= off2);
let v = Val.restrict old_value off1 off2 in
let sz = Bigint.big_int_of_int new_size in
let base = Bigint.add_big_int old_loc sz in
let loc = MemInterval.create base (old_size - new_size) in
let sub_m = MemMap.add loc (loc, old_en, v) sub_m in
sub_m
and clear_at_beginning_and_beyond addrStack old_info new_info sub_m sw =
Logger.debug "Clear beginning & beyond called";
let old_loc, old_size, _, _ = old_info in
let (_new_loc, new_size, new_en, new_value) = new_info in
let off1 = old_size * 8 in
let off2 = new_size * 8 - 1 in
assert (off1 <= off2);
let v = Val.restrict new_value off1 off2 in
let sz = Bigint.big_int_of_int old_size in
let base = Bigint.add_big_int old_loc sz in
split_regions addrStack sub_m v (base, new_size - old_size) new_en sw
and update_at_beginning_and_beyond addrStack old_info new_info sub_m sw =
let (old_loc, old_size, old_en, old_value) = old_info in
let (new_loc, new_size, new_en, new_value) = new_info in
let off1 = 0 in
let off2 = 8 * old_size - 1 in
assert (off1 <= off2);
let v = Val.restrict new_value off1 off2 in
let loc = MemInterval.create new_loc old_size in
let sub_m = update loc new_en v old_value sub_m in
let off1 = old_size * 8 in
let off2 = new_size * 8 - 1 in
assert (off1 <= off2);
let v = Val.restrict new_value off1 off2 in
let sz = Bigint.big_int_of_int old_size in
let base = Bigint.add_big_int old_loc sz in
let sub_m = MemMap.add (MemInterval.create old_loc old_size)
(MemInterval.create old_loc old_size, old_en, old_value) sub_m in
split_regions addrStack sub_m v (base, new_size - old_size) new_en sw
and clear_inside_and_beyond addrStack old_info new_info sub_m sw =
Logger.debug "Clear inside & beyond called";
let (old_loc, old_size, old_en, old_value) = old_info in
let (new_loc, new_size, new_en, new_value) = new_info in
let delta = Bigint.sub_big_int new_loc old_loc in
let delta = Bigint.int_of_big_int delta in
let off1 = 0 in
let off2 = delta * 8 - 1 in
assert (off1 <= off2);
let v = Val.restrict old_value off1 off2 in
let loc = MemInterval.create old_loc delta in
let sub_m = MemMap.add loc (loc, old_en, v) sub_m in
let off1 = delta * 8 in
let off2 = old_size * 8 - 1 in
let off2' = off2 - off1 in
let off1 = off2' + 1 in
let off2 = new_size * 8 - 1 in
if (off1 > off2) then
sub_m
else
let v = Val.restrict new_value off1 off2 in
let sz = Bigint.big_int_of_int ((off2' + 1) / 8) in
let base = Bigint.add_big_int new_loc sz in
split_regions addrStack sub_m v (base, (off2 - off1) / 8 + 1) new_en sw
and update_inside_and_beyond addrStack old_info new_info sub_m sw =
let (old_loc, old_size, old_en, old_value) = old_info in
let (new_loc, new_size, new_en, new_value) = new_info in
let delta = Bigint.sub_big_int new_loc old_loc in
let delta = Bigint.int_of_big_int delta in
let off1 = 0 in
let off2 = delta * 8 - 1 in
assert (off1 <= off2);
let v = Val.restrict old_value off1 off2 in
let loc = MemInterval.create old_loc delta in
let sub_m = MemMap.add loc (loc, old_en, v) sub_m in
let off1 = delta * 8 in
let off2 = old_size * 8 - 1 in
assert (off1 <= off2);
let v1 = Val.restrict old_value off1 off2 in
let off1' = 0 in
let off2' = off2 - off1 in
assert (off1' <= off2');
let v2 = Val.restrict new_value off1' off2' in
let v = Val.join v1 v2 in
let loc = MemInterval.create new_loc (off2' / 8 + 1) in
let sub_m = MemMap.add loc (loc, new_en, v) sub_m in
let off1 = off2' + 1 in
let off2 = new_size * 8 - 1 in
if (off1 > off2) then
sub_m
else
let v = Val.restrict new_value off1 off2 in
let sz = Bigint.big_int_of_int off2' in
let base = Bigint.add_big_int new_loc sz in
let sub_m = MemMap.add (MemInterval.create old_loc old_size)
((MemInterval.create old_loc old_size), old_en, old_value) sub_m in
split_regions addrStack sub_m v (base, ((off2 - off1) / 8 + 1)) new_en sw
and clear_inside addrStack old_info new_info sub_m sw =
Logger.debug "Clear inside called";
let (old_loc, old_size, old_en, old_value) = old_info in
let (new_loc, new_size, new_en, _new_value) = new_info in
let delta = Bigint.sub_big_int new_loc old_loc in
let delta = Bigint.int_of_big_int delta in
let off1 = 0 in
let off2 = delta * 8 - 1 in
assert (off1 <= off2);
let v = Val.restrict old_value off1 off2 in
let loc = MemInterval.create old_loc delta in
let sub_m = MemMap.add loc (loc, old_en, v) sub_m in
let off2 = (new_size + delta) * 8 - 1 in
let sz = Bigint.big_int_of_int off2 in
let off1 = off2 + 1 in
let off2 = old_size * 8 - 1 in
assert (off1 <= off2);
let v = Val.restrict old_value off1 off2 in
let base = Bigint.add_big_int new_loc sz in
let sub_m = MemMap.add (MemInterval.create old_loc old_size)
((MemInterval.create old_loc old_size), old_en, old_value) sub_m in
let sub_m = split_regions addrStack sub_m v (base, ((off2 - off1) / 8 + 1)) new_en sw in
sub_m
and update_inside addrStack old_info new_info sub_m sw =
let (old_loc, old_size, old_en, old_value) = old_info in
let (new_loc, new_size, new_en, new_value) = new_info in
let delta = Bigint.sub_big_int new_loc old_loc in
let delta = Bigint.int_of_big_int delta in
let off1 = 0 in
let off2 = delta * 8 - 1 in
assert (off1 <= off2);
let v = Val.restrict old_value off1 off2 in
let loc = MemInterval.create old_loc delta in
let sub_m = MemMap.add loc (loc, old_en, v) sub_m in
let off1 = delta * 8 in
let off2 = (new_size + delta) * 8 - 1 in
assert (off1 <= off2);
let v1 = Val.restrict old_value off1 off2 in
let off1' = 0 in
let off2' = off2 - off1 in
assert (off1' <= off2');
let v2 = Val.restrict new_value off1' off2' in
let v = Val.join v1 v2 in
let loc = MemInterval.create new_loc (off2' / 8 + 1) in
let sub_m = MemMap.add loc (loc, new_en, v) sub_m in
let sz = Bigint.big_int_of_int off2 in
let off1 = off2 + 1 in
let off2 = old_size * 8 - 1 in
assert (off1 <= off2);
let v = Val.restrict old_value off1 off2 in
let base = Bigint.add_big_int new_loc sz in
let sub_m = MemMap.add (MemInterval.create old_loc old_size)
((MemInterval.create old_loc old_size), old_en, old_value) sub_m in
let sub_m = split_regions addrStack sub_m v
(base, succ (off2 - off1) / (Constants.bytesize:>int)) new_en sw in
sub_m
and clear_before_and_beyond addrStack old_info new_info sub_m sw =
Logger.debug "Clear before & beyond";
let (old_loc, old_size, old_en, old_value) = old_info in
let (new_loc, new_size, new_en, new_value) = new_info in
let delta = Bigint.sub_big_int old_loc new_loc in
let delta = Bigint.int_of_big_int delta in
let off1 = delta * 8 in
let off2 = new_size * 8 - 1 in
Logger.debug "OFF1:%d OFF2:%d" off1 off2;
assert (off1 <= off2);
let v = Val.restrict new_value off1 off2 in
let sub_m = MemMap.add (MemInterval.create old_loc old_size)
((MemInterval.create old_loc old_size), old_en, old_value) sub_m in
let sub_m = split_regions addrStack sub_m v (old_loc, new_size - delta) new_en sw in
sub_m
and update_before_and_beyond addrStack old_info new_info sub_m sw =
let (old_loc, old_size, old_en, old_value) = old_info in
let (new_loc, new_size, new_en, new_value) = new_info in
let delta = Bigint.sub_big_int old_loc new_loc in
let delta = Bigint.int_of_big_int delta in
let sub_m =
if (sw = Strong) then
let off1 = 0 in
let off2 = delta * 8 - 1 in
assert (off1 <= off2);
let v = Val.restrict new_value off1 off2 in
let loc = MemInterval.create new_loc delta in
MemMap.add loc (loc, new_en, v) sub_m
else sub_m
in
let off1 = delta * 8 in
let off2 = new_size * 8 - 1 in
assert (off1 <= off2);
let v = Val.restrict new_value off1 off2 in
let sub_m = MemMap.add (MemInterval.create old_loc old_size)
(MemInterval.create old_loc old_size, old_en, old_value) sub_m in
let sub_m = split_regions addrStack sub_m v (old_loc, new_size - delta) new_en sw in
sub_m
and split_regions addrStack sub_m new_value (address, nbytes) new_en sw =
let new_loc = address
and new_size = nbytes in
let (_, _, loop) = addrStack in
try
let old_loc, old_en, old_value = collect new_loc 1 new_size sub_m in
let old_size = MemInterval.size_of old_loc in
let old_loc = MemInterval.base_of old_loc in
if loop > 1 then
Logger.warning "Potential buffer overflow at %a"
Dba_types.AddressStack.pp addrStack;
let loc = MemInterval.create old_loc old_size in
let sub_m = MemMap.remove loc sub_m in
let old_info = (old_loc, old_size, old_en, old_value) in
let new_info = (new_loc, new_size, new_en, new_value) in
match old_en, new_en with
| Machine.LittleEndian, Machine.LittleEndian -> (
match sw with
| Strong ->
if (Bigint.eq_big_int old_loc new_loc) && (new_size = old_size)
then sub_m
else if Bigint.eq_big_int old_loc new_loc
then
let f =
if new_size < old_size
then clear_at_beginning
else clear_at_beginning_and_beyond addrStack
in f old_info new_info sub_m sw
else
let old_size_1 = Bigint.big_int_of_int (old_size - 1) in
let new_size_1 = Bigint.big_int_of_int (new_size - 1) in
let upper_old = Bigint.add_big_int old_loc old_size_1 in
let upper_new = Bigint.add_big_int new_loc new_size_1 in
if Bigint.lt_big_int old_loc new_loc then
if Bigint.ge_big_int upper_new upper_old
then clear_inside_and_beyond addrStack old_info new_info sub_m sw
else clear_inside addrStack old_info new_info sub_m sw
else clear_before_and_beyond addrStack old_info new_info sub_m sw
| Weak ->
if (Bigint.eq_big_int old_loc new_loc) && (new_size = old_size)
then update (MemInterval.create new_loc new_size) new_en old_value new_value sub_m
else (
if (Bigint.eq_big_int old_loc new_loc)
then
if new_size < old_size
then update_at_beginning old_info new_info sub_m sw
else update_at_beginning_and_beyond addrStack old_info new_info sub_m sw
else
let old_size_1 = Bigint.big_int_of_int (old_size - 1) in
let new_size_1 = Bigint.big_int_of_int (new_size - 1) in
let upper_old = Bigint.add_big_int old_loc old_size_1 in
let upper_new = Bigint.add_big_int new_loc new_size_1 in
if Bigint.lt_big_int old_loc new_loc then
if Bigint.ge_big_int upper_new upper_old
then update_inside_and_beyond addrStack old_info new_info sub_m sw
else update_inside addrStack old_info new_info sub_m sw
else update_before_and_beyond addrStack old_info new_info sub_m sw
)
)
| Machine.BigEndian, Machine.LittleEndian
| Machine.LittleEndian, Machine.BigEndian
| Machine.BigEndian, Machine.BigEndian -> failwith "split_regions:big_endian"
with Not_found ->
if sw = Strong
then
let loc = MemInterval.create new_loc new_size in
Logger.debug "SPLITREG STORE: %a" MemInterval.pp loc;
MemMap.add loc (loc, new_en, new_value) sub_m
else sub_m
and store addrStack x (i, nbytes) en value m assumes globals sw elements equalities =
let m = match m with
| None -> Env.empty
| Some m -> m
in
match x with
| Static_types.Var _ ->
let loc = MemInterval.create Bigint.zero_big_int 1 in
let sub_m = MemMap.singleton loc (loc, en, value) in
Some (Env.add x sub_m m)
| Static_types.Array r ->
let c =
try Dba_types.Rights.find_write_right r !Concrete_eval.permis
with Not_found -> Dba.Expr.one
in
let b, _assumes = eval_cond c (Some m) assumes globals elements equalities in
match b with
| Ternary.True ->
let sub_m =
try Env.find (Static_types.Array r) m with Not_found -> MemMap.empty
in
let sub_m = split_regions addrStack sub_m value (i, nbytes) en sw in
let sub_m =
if sw = Strong then begin
let loc = MemInterval.create i nbytes in
Logger.debug "LOCSTORE: %a" MemInterval.pp loc;
MemMap.add loc (loc, en, value) sub_m
end
else sub_m
in Some (Env.add (Static_types.Array r) sub_m m)
| Ternary.False -> raise Errors.Write_permission_denied
| Ternary.Unknown -> failwith "write permission unknown"
and check_region_size region i sz =
if sz < 1 then
raise (Errors.Bad_bound ("store, case1: store size = " ^ (string_of_int sz)))
else
match region with
| `Constant | `Stack -> ()
| `Malloc ((id, _), malloc_size) ->
let open Bigint in
if gt_big_int (add_big_int i (big_int_of_int (sz - 1))) malloc_size
then
let message = Format.asprintf "store, case2: store at 𝑴 %d[@%s, size = %d bytes] but size(𝑴 %d) = %s bytes!"
id (Bigint.string_of_big_int i) sz id (Bigint.string_of_big_int malloc_size) in
raise (Errors.Bad_bound message)
else ()
let store endianness addrStack sz v e env assumes globals recordMap elements
equalities =
let v_index, assumes = eval_expr e env assumes globals elements equalities
in
Logger.debug "VAL: %a" Val.pp v_index;
let en = endianness in
let indexes =
try Val.elements v_index
with
| Val.Elements_of_top ->
if Ai_options.FailSoftMode.get () then
try Dba_types.AddressStack.Map.find addrStack recordMap
with Not_found -> []
else
if List.length elements = 0
then raise Errors.Enumerate_Top
else elements
in
let apply update elem env =
let region = Region_bitvector.region_of elem in
let i = Region_bitvector.value_of elem in
Logger.debug "RBVVAL: %s" (Bigint.string_of_big_int i);
check_region_size region i sz;
let r = Static_types.Array region in
store addrStack r (i, sz) en v env assumes globals update elements equalities
in
let env =
match indexes with
| [] -> env
| [elem] -> apply Strong elem env
| elems -> List.fold_right (apply Weak) elems env
in
env, assumes, Dba_types.AddressStack.Map.add addrStack indexes recordMap
let store_little_end = store Machine.LittleEndian
let store_big_end = store Machine.BigEndian
let assign addrStack lhs e s assumes globals recordMap elements equalities =
current_address := addrStack;
let v, assumes = eval_expr e s assumes globals elements equalities in
match lhs with
| Dba.(LValue.Var { name = st; size; _}) ->
let v_string = Val.to_string v in
Display.display (Display.Assign (st, e, v_string));
let loc = MemInterval.create Bigint.zero_big_int 1 in
let sub_s = MemMap.add loc (loc, Machine.LittleEndian, v) MemMap.empty in
let s = match s with None -> Env.empty | Some s -> s in
let s = Some (Env.add (Static_types.Var (st, size)) sub_s s) in
s, assumes, recordMap, v
| Dba.LValue.Restrict ({ Dba.name = st; Dba.size; _}, {Interval.lo=of1; Interval.hi=of2}) ->
let s =
match s with
None -> Env.empty
| Some s -> s
in
let loc = MemInterval.create Bigint.zero_big_int 1 in
let en, x =
try let _, en, av = (MemMap.find loc (Env.find (Var (st, size)) s))
in en, av
with Not_found -> Machine.LittleEndian,Val.universe
in
let temp1 =
if (of1 = 0) then v
else (Val.concat v (Val.restrict x 0 (of1 - 1)))
in
let temp2 = Val.restrict x (of2 + 1) (size - 1) in
let loc = MemInterval.create Bigint.zero_big_int 1 in
let v = Val.concat temp2 temp1 in
let sub_s = MemMap.add loc (loc, en, v) MemMap.empty in
let s = Some (Env.add (Static_types.Var (st, size)) sub_s s) in
s, assumes, recordMap, v
| Dba.LValue.Store (sz, endianness, e) ->
let op, assumes, recordMap =
store endianness addrStack sz v e s assumes globals recordMap elements equalities in
op, assumes, recordMap, v
let rec guard addr cond s assumes glbs rcd elements equalities =
match s with
| None -> None, assumes, rcd, equalities
| Some m ->
match cond with
| Dba.Expr.Cst (_, v) ->
let s' = if Bitvector.is_zero v then None else s in
s', assumes, rcd, equalities
| Dba.Expr.Binary (bop, exp1, exp2) -> (
match bop with
| Dba.Binary_op.Eq | Dba.Binary_op.Diff | Dba.Binary_op.LeqU | Dba.Binary_op.LtU
| Dba.Binary_op.GeqU | Dba.Binary_op.GtU | Dba.Binary_op.LeqS | Dba.Binary_op.LtS
| Dba.Binary_op.GeqS | Dba.Binary_op.GtS ->
let v_1, v_2 =
let op1, assumes = eval_expr exp1 s assumes glbs elements equalities in
let op2, _assumes = eval_expr exp2 s assumes glbs elements equalities in
Val.guard bop op1 op2 in
let loc = MemInterval.empty in
(match exp1, exp2 with
| Dba.Expr.Var { Dba.name = v1; Dba.size; _}, Dba.Expr.Cst _ ->
let en = Machine.LittleEndian in
let sub_m = MemMap.add loc (loc, en, v_1) MemMap.empty in
let s = Some (Env.add (Static_types.Var (v1, size)) sub_m m) in
let equalities = Eq.refine exp1 v_1 equalities in
s, assumes, rcd, equalities
| Dba.Expr.Unary (Dba.Unary_op.Restrict
{Interval.lo = o1; Interval.hi = o2;},
Dba.Expr.Var { Dba.name = v1; Dba.size; _}), Dba.Expr.Cst _ ->
let en, x =
try
let _, en, av = MemMap.find loc (Env.find (Var (v1, size)) m)
in en, av
with Not_found -> Machine.LittleEndian, Val.universe
in
let temp1 =
if o1 = 0 then v_1
else Val.concat v_1 (Val.restrict x 0 (o1 - 1)) in
let temp2 = Val.restrict x (o2 + 1) (size - 1) in
let v = Val.concat temp2 temp1 in
let sub_m = MemMap.add loc (loc, en, v) MemMap.empty in
let s = Some (Env.add (Static_types.Var (v1, size)) sub_m m) in
let equalities = Eq.refine exp1 v_1 equalities in
s, assumes, rcd, equalities
| Dba.Expr.Load (sz, Machine.LittleEndian, e), Dba.Expr.Cst _ ->
let s, assumes, rcd = store_little_end addr sz v_1 e s assumes glbs rcd elements equalities in
let equalities = Eq.refine exp1 v_1 equalities in
s, assumes, rcd, equalities
| Dba.Expr.Cst _, Dba.Expr.Load (sz, Machine.LittleEndian, e) ->
let s, assumes, rcd =
store_little_end addr sz v_2 e s assumes glbs rcd elements equalities in
let equalities = Eq.refine exp2 v_2 equalities in
s, assumes, rcd, equalities
| Dba.Expr.Cst _, Dba.Expr.Var { Dba.name = v2; Dba.size; _} ->
let en = Machine.LittleEndian in
let sub_m = MemMap.add loc (loc, en, v_2) MemMap.empty in
let s = Some (Env.add (Static_types.Var (v2, size)) sub_m m) in
let equalities = Eq.refine exp2 v_2 equalities in
s, assumes, rcd, equalities
| Dba.Expr.Var { Dba.name = v1; _},
Dba.Expr.Var {Dba.name = v2; Dba.size; _} ->
let en = Machine.LittleEndian in
let sub_m = MemMap.add loc (loc, en, v_1) MemMap.empty in
let m = Env.add (Static_types.Var (v1, size)) sub_m m in
let sub_m = MemMap.add loc (loc, en, v_2) MemMap.empty in
let s = Some (Env.add (Static_types.Var (v2, size)) sub_m m) in
let equalities = Eq.refine exp1 v_1 equalities in
let equalities = Eq.refine exp2 v_2 equalities in
s, assumes, rcd, equalities
| Dba.Expr.Var {Dba.name = v1; Dba.size = size2; _}, Dba.Expr.Load (size, Machine.BigEndian, e) ->
let en = Machine.LittleEndian in
let sub_m = MemMap.add loc (loc, en, v_1) MemMap.empty in
let m = Some (Env.add (Static_types.Var (v1, size2)) sub_m m) in
let s, assumes, rcd = store_big_end addr size v_2 e m assumes glbs rcd elements equalities in
let equalities = Eq.refine exp1 v_1 equalities in
let equalities = Eq.refine exp2 v_2 equalities in
s, assumes, rcd, equalities
| Dba.Expr.Load (size, Machine.BigEndian, e), Dba.Expr.Var {Dba.name = v2; Dba.size = size2; _} ->
let sub_m = MemMap.singleton loc (loc, en, v_2) in
let m = Some (Env.add (Static_types.Var (v2, size2)) sub_m m) in
let s, assumes, rcd = store_big_end addr size v_1 e m assumes glbs rcd elements equalities in
let equalities = Eq.refine exp1 v_1 equalities in
let equalities = Eq.refine exp2 v_2 equalities in
s, assumes, rcd, equalities
| Dba.Expr.Var {Dba.name = v1; Dba.size = size1; _}, Dba.Expr.Load (sz, Machine.LittleEndian, e) ->
let en = Machine.LittleEndian in
let sub_m = MemMap.add loc (loc, en, v_1) MemMap.empty in
let m = Some (Env.add (Static_types.Var (v1, size1)) sub_m m) in
let s, assumes, rcd = store_little_end addr sz v_2 e m assumes glbs rcd elements equalities in
let equalities = Eq.refine exp1 v_1 equalities in
let equalities = Eq.refine exp2 v_2 equalities in
s, assumes, rcd, equalities
| Dba.Expr.Load (sz, Machine.LittleEndian, e), Dba.Expr.Var {Dba.name = v2; Dba.size = size2; _} ->
let en = Machine.LittleEndian in
let sub_m = MemMap.add loc (loc, en, v_2) MemMap.empty in
let m = Some (Env.add (Static_types.Var (v2, size2)) sub_m m) in
let s, assumes, rcd = store_little_end addr sz v_1 e m assumes glbs rcd elements equalities in
let equalities = Eq.refine exp1 v_1 equalities in
let equalities = Eq.refine exp2 v_2 equalities in
s, assumes, rcd, equalities
| Dba.Expr.Load (size1, endianness1, e1),
Dba.Expr.Load (size2, endianness2, e2) ->
let m, assumes, rcd = store endianness1
addr size1 v_1 e1 s assumes glbs rcd elements equalities in
let s, assumes, rcd = store endianness2
addr size2 v_2 e2 m assumes glbs rcd elements equalities in
let equalities = Eq.refine exp1 v_1 equalities in
let equalities = Eq.refine exp2 v_2 equalities in
s, assumes, rcd, equalities
| _, _ -> s, assumes, rcd, equalities
)
| _ -> s, assumes, rcd, equalities
)
| Dba.Expr.Unary (uop, expr) ->
( match uop with
| Dba.Unary_op.Not ->
(match expr with
| Dba.Expr.Binary (bop, e1, e2) ->
let k c =
guard addr c s assumes glbs rcd elements equalities in
begin
match bop with
| Dba.Binary_op.Eq -> Dba.Expr.diff e1 e2 |> k
| Dba.Binary_op.Diff -> Dba.Expr.equal e1 e2 |> k
| Dba.Binary_op.LeqU -> Dba.Expr.ugt e1 e2 |> k
| Dba.Binary_op.LtU -> Dba.Expr.uge e1 e2 |> k
| Dba.Binary_op.GeqU -> Dba.Expr.ult e1 e2 |> k
| Dba.Binary_op.GtU -> Dba.Expr.ule e1 e2 |> k
| Dba.Binary_op.LeqS -> Dba.Expr.sgt e1 e2 |> k
| Dba.Binary_op.LtS -> Dba.Expr.sge e1 e2 |> k
| Dba.Binary_op.GeqS -> Dba.Expr.slt e1 e2 |> k
| Dba.Binary_op.GtS -> Dba.Expr.sle e1 e2 |> k
| Dba.Binary_op.Or -> Dba.Expr.(logand (lognot e1) (lognot e2)) |> k
| Dba.Binary_op.And -> Dba.Expr.(logor (lognot e1) (lognot e2)) |> k
| _ -> s, assumes, rcd, equalities
end
| _ -> s, assumes, rcd, equalities)
| _ -> s, assumes, rcd, equalities)
| _ -> s, assumes, rcd, equalities
let string_of_args args m assumes globals elements equalities =
let b = Buffer.create 1024 in
let rec aux assumes args =
match args with
| [] -> ()
| Dba.Str s :: tl ->
Buffer.add_string b (Scanf.unescaped s);
aux assumes tl
| Dba.Exp e :: tl ->
let op, assumes = eval_expr e m assumes globals elements equalities in
let temp = Val.to_string op in
Buffer.add_string b temp;
aux assumes tl
in aux assumes args;
Buffer.contents b
let check_exec_permission addr s assumes globals elements equalities =
let m = match s with None -> Env.empty | Some m -> m in
let bv = Bitvector.create (Virtual_address.to_bigint addr.Dba.base) 32 in
let v = Val.singleton (`Value (`Constant, bv)) in
let loc = MemInterval.create Bigint.zero_big_int 1 in
let sub_m =
MemMap.add loc (loc, Machine.LittleEndian, v) MemMap.empty in
let s = Some (Env.add (Var ("\\addr", Kernel_options.Machine.word_size ())) sub_m m) in
let c =
try Dba_types.Rights.find_exec_right `Constant !Concrete_eval.permis
with Not_found -> Dba.Expr.one in
let b, _assumes = (eval_cond c s assumes globals elements equalities) in
match b with
| Ternary.True -> addr
| Ternary.False -> raise Errors.Exec_permission_denied
| Ternary.Unknown -> failwith "exec permission unknown"
let free expr s assumes globals elements equalities =
let v, _assumes = eval_expr expr s assumes globals elements equalities in
let l =
try Val.elements v
with Val.Elements_of_top -> raise Errors.Enumerate_Top
in
List.iter (fun elem ->
match elem with
| `Value (`Malloc _ as v, bv) ->
let st =
try Malloc_status.find v !Simulate.mallocs
with Not_found -> failwith "Unbound free region"
in
let open Dba in
begin match st with
| Freeable when Bitvector.is_zero bv ->
Simulate.mallocs :=
Malloc_status.add v Freed !Simulate.mallocs
| Freed -> raise Errors.Freed_variable_access
| Freeable -> raise Errors.Invalid_free_address
end
| _ -> raise Errors.Invalid_free_region
) l;
s
let rec is_visited (a_ret, a_callee) callstack nb =
match callstack with
| [] -> false
| (_, callee) :: tl ->
if Dba_types.Caddress.equal callee a_callee
then nb = 0 || is_visited (a_ret, a_callee) tl (nb - 1)
else is_visited (a_ret, a_callee) tl nb
let resolve_jump addr expr s flgs equalities recordMap assumes globals djumps_map tag elements =
let _, cstack, loop = addr in
let v, _assumes = eval_expr expr s assumes globals elements equalities in
let l =
if Ai_options.FailSoftMode.get () then
try Val.elements v
with Val.Elements_of_top ->
try Dba_types.AddressStack.Map.find addr recordMap
with Not_found -> []
else
try Val.elements v
with Val.Elements_of_top ->
if List.length elements = 0
then raise Errors.Enumerate_Top
else elements
in
let locations, djumps_map =
List.fold_right (fun elem (acc1, acc2) ->
if Region_bitvector.region_of elem = `Constant then
if Region_bitvector.size_of elem =
Kernel_options.Machine.word_size () then
begin
let a =
Dba_types.Caddress.block_start @@
Virtual_address.of_bitvector @@
Region_bitvector.bitvector_of elem in
let addrStack =
let open Dba in
match tag, cstack with
| Some Call addr_ret, cstack ->
Display.increase_function_count ();
let calling_callee_addr = addr_ret, a in
if is_visited calling_callee_addr cstack 20
then raise (RecursiveCall a)
else (
Display.display (Display.Call(a, addr_ret));
let cstack = calling_callee_addr :: cstack in
(a, cstack, loop)
)
| Some Return, (old_ret, old_start) :: cstack ->
let cstack =
if Dba_types.Caddress.equal old_ret a then cstack
else (old_ret, old_start) :: cstack in
a, cstack, loop
| Some Return, [] -> a, cstack, loop
| None, cstack -> a, cstack, loop
in
let t1 = (addrStack, s, flgs, equalities) :: acc1 in
let t2 =
let s =
try Dba_types.AddressStack.Map.find addr acc2
with Not_found -> Dba_types.Caddress.Set.empty
in
Dba_types.AddressStack.Map.add addr (Dba_types.Caddress.Set.add a s) acc2 in
t1, t2
end
else
raise Errors.Bad_address_size
else
raise (Errors.Bad_region "Dynamic jump")
) l ([], djumps_map) in
locations, (Dba_types.AddressStack.Map.add addr l recordMap), djumps_map
let resolve_if cond s flgs (m1, eq1) (m2, eq2) addr_suiv1 addr_suiv2 assumes globals elements equalities =
match eval_cond cond s assumes globals elements equalities with
| Ternary.True, _ -> [addr_suiv1, m1, flgs, eq1]
| Ternary.False, _ -> [addr_suiv2, m2, flgs, eq2]
| Ternary.Unknown, _ ->
[ addr_suiv1, m1, flgs, eq1;
addr_suiv2, m2, flgs, eq2; ]
let resolve_assume addr cond s flgs equalities addr_suiv assumes glbs rcd elements =
match eval_cond cond s assumes glbs elements equalities with
| Ternary.Unknown, _ -> [addr_suiv, s, flgs, equalities]
| _, assumes ->
let s, _assumes, _rcd, equalities =
guard addr cond s assumes glbs rcd elements equalities in
[addr_suiv, s, flgs, equalities]
let resolve_assert cond s flgs equalities addr_suiv addrStack instr assumes glbs rcd elements =
let addr, _cstack, _loop = addrStack in
let condi, assumes = (eval_cond cond s assumes glbs elements equalities) in
let continue = Ternary.to_bool condi in
if continue then
let s, _assumes, _rcd, equalities = guard addrStack cond s assumes glbs rcd elements equalities in
[addr_suiv, s, flgs, equalities]
else Errors.assert_failure addr instr
let resolve_nondet_assume addr lhslist cond s flgs equalities addr_suiv assumes glbs rcd elements =
let rec update_memory_nondet lhslist s assumes glbs rcd =
match lhslist with
| [] -> s, assumes, rcd
| (Dba.LValue.Var {Dba.name = st; Dba.size; _}) :: tl ->
let l = MemInterval.create Bigint.zero_big_int 1 in
let en = Machine.LittleEndian in
let sub_s = MemMap.add l (l, en, Val.universe) MemMap.empty in
let s = match s with None -> Env.empty | Some s -> s in
let m' = Some (Env.add (Static_types.Var (st, size)) sub_s s) in
update_memory_nondet tl m' assumes glbs rcd
| Dba.LValue.Restrict _ :: _ ->
failwith "UnrelState.ml: restrict case not handled2"
| Dba.LValue.Store (sz, endianness, e) :: tl ->
let m', assumes, rcd = store endianness addr sz Val.universe e s assumes
glbs rcd elements equalities in
update_memory_nondet tl m' assumes glbs rcd
in
let rec iterate cond iter assumes glbs rcd equalities =
if iter mod 100000 = 0
then Logger.debug "NONDET iterartion num %d" iter;
let m', assumes, rcd = update_memory_nondet lhslist s assumes glbs rcd in
let condi, assumes = eval_cond cond m' assumes glbs elements equalities in
match condi with
| Ternary.True -> m', assumes, rcd, equalities
| Ternary.False ->
iterate cond (iter + 1) assumes glbs rcd equalities
| Ternary.Unknown ->
guard addr cond m' assumes glbs rcd elements equalities
in
let op, assumes, rcd, equalities = iterate cond 0 assumes glbs rcd equalities in
[addr_suiv, op, flgs, equalities], assumes, rcd
let resolve_nondet addr lhs region s flgs equalities addr_suiv assumes glbs rcd elements =
let _region = region in
let m = match lhs with
Dba.LValue.Var { Dba.name = st; Dba.size; _} ->
let loc = MemInterval.create Bigint.zero_big_int 1 in
let en = Machine.LittleEndian in
let sub_s = MemMap.add loc (loc, en, Val.universe) MemMap.empty in
let s = match s with None -> Env.empty | Some s -> s in
Some (Env.add (Static_types.Var (st, size)) sub_s s)
| Dba.LValue.Restrict _ ->
failwith "unrelState.ml: restrict case not handled"
| Dba.LValue.Store (size, Machine.BigEndian, expr) ->
let op, _assumes, _rcd = store_big_end addr size Val.universe expr s assumes glbs rcd elements equalities in
op
| Dba.LValue.Store (size, Machine.LittleEndian, expr) ->
let op, _assumes, _rcd = store_little_end addr size Val.universe expr s assumes glbs rcd elements equalities in
op
in
[addr_suiv, m, flgs, equalities]
let resolve_undef addr lhs s flgs equalities addr_suiv assumes glbs rcd elements =
TODO : Kset can contain an undef value or
it is to Top in this case
it is trqnsformed to Top in this case *)
let m = match lhs with
Dba.LValue.Var { Dba.name = st; Dba.size; _} ->
let loc = MemInterval.create Bigint.zero_big_int 1 in
let v =Val.singleton
(`Undef (computesize_dbalhs lhs)) in
let en = Machine.LittleEndian in
let sub_s = MemMap.add loc (loc, en, v) MemMap.empty in
let s = match s with None -> Env.empty | Some s -> s in
Some (Env.add (Static_types.Var (st, size)) sub_s s)
| Dba.LValue.Restrict _ ->
failwith "unrelState.ml: restrict case not handled3"
| Dba.LValue.Store (size, Machine.BigEndian, expr) ->
let v = Val.singleton
(`Undef (computesize_dbalhs lhs)) in
let op, _assumes, _rcd =
store_big_end addr size v expr s assumes glbs rcd elements equalities in
op
| Dba.LValue.Store (size, Machine.LittleEndian, expr) ->
let v = Val.singleton
(`Undef (computesize_dbalhs lhs)) in
let op, _assumes, _rcd =
store_little_end addr size v expr s assumes glbs rcd elements equalities in
op
in
[addr_suiv, m, flgs, equalities]
let resolve_print args s flgs equalities addr_suiv assumes glbs elements =
Logger.debug "%s" (string_of_args args s assumes glbs elements equalities);
[addr_suiv, s, flgs, equalities]
let remove_memory_overlaps equalities lhs1 m assumes glbs elements =
let open Dba in
match lhs1 with
| LValue.Store (sz1, _en1, e1) ->
let equals = Eq.copy_equalities equalities in
let lhs_list = Eq.get_elements equalities in
let zero = Region_bitvector.zeros 32 in
let sz1 = Region_bitvector.create_constant (Bigint.big_int_of_int sz1) 32 in
let v_sz1 = Val.of_bounds (zero, sz1) in
let v1, _ = eval_expr e1 m assumes glbs elements equals in
let v1 = Val.add v1 v_sz1 in
let remove_memory_overlap acc lhs2 =
match lhs2 with
| LValue.Store (sz2, _en2, e2) ->
let sz2 = Region_bitvector.create_constant (Bigint.big_int_of_int sz2) 32 in
let v_sz2 = Val.of_bounds (zero, sz2) in
let v2, _ = eval_expr e2 m assumes glbs elements equals in
let v2 = Val.add v2 v_sz2 in
if Val.is_empty (Val.meet v1 v2) then acc
else Eq.remove acc lhs2
| _ -> acc
in
List.fold_left remove_memory_overlap equalities lhs_list
| _ -> equalities
let update_equalities lhs e equalities v m assumes glbs elements =
match Dba.LValue.of_expr e with
| lhs_expr ->
if Eq.is_same_class equalities lhs lhs_expr
then equalities
else (
let equalities = Eq.remove_syntax_overlaps equalities lhs in
let equalities = remove_memory_overlaps equalities lhs m assumes glbs elements in
Display.display (Display.RemoveEqualities (lhs, Eq.to_string equalities));
Eq.union equalities lhs lhs_expr v
)
| exception Failure _ ->
let equalities = Eq.remove_syntax_overlaps equalities lhs in
Display.display (Display.RemoveEqualities (lhs, Eq.to_string equalities));
Eq.union equalities lhs lhs v
let post abs_vals addrStack instr cache assumes glbs djumps_map unrolled_loops elements =
let addr, cstack, loop = addrStack in
let rcd, rcd_conds = cache in
let m, flags, equalities = abs_vals in
let equalities = Eq.copy_equalities equalities in
let open Dba in
match instr with
| Dba.Instr.Stop (Some KO) ->
Errors.assert_failure addr instr
| Dba.Instr.Stop (Some (Undefined s)) ->
raise (Errors.Stop_Unsupported s)
| Dba.Instr.Stop (Some (Unsupported s)) ->
raise (Errors.Stop_Unsupported s)
| Dba.Instr.Stop _tag ->
[], cache, assumes, djumps_map
| Dba.Instr.Assign (lhs, expr, id_suiv) ->
let m', assumes', rcd, v = assign addrStack lhs expr m assumes glbs rcd elements equalities in
let flags = update_flags lhs expr flags in
let t0 = Unix.gettimeofday () in
let equalities = update_equalities lhs expr equalities v m assumes glbs elements in
Ai_options.time_equalities :=
Unix.gettimeofday () -. t0 +. !Ai_options.time_equalities;
Ai_options.nb_equalities_names :=
max (Eq.get_nb_names equalities) !Ai_options.nb_equalities_names;
Ai_options.nb_equalities_classes :=
max (Eq.get_nb_classes equalities) !Ai_options.nb_equalities_classes;
let cache = rcd, rcd_conds in
[ (Dba_types.Caddress.reid addr id_suiv, cstack, loop), m', flags, equalities],
cache, assumes', djumps_map
| Dba.Instr.Malloc (lhs, expr, id_suiv) ->
let v, assumes = eval_expr expr m assumes glbs elements equalities in
incr Dba_types.malloc_id;
let size =
let sz = Val.elements v in
match sz with
| (`Value (`Constant, size)) :: [] -> Bitvector.value_of size
| _ -> failwith "unrelstate.ml: malloc size"
in
let region = `Malloc ((!Dba_types.malloc_id, addr), size) in
let bv = Bitvector.zeros (Kernel_options.Machine.word_size ()) in
Simulate.mallocs := Malloc_status.add region Freeable !Simulate.mallocs;
let v = Dba.Expr.constant ~region bv in
let op,assumes,rcd,_ = assign addrStack lhs v m assumes glbs rcd elements equalities in
let cache = (rcd, rcd_conds) in
[ (Dba_types.Caddress.reid addr id_suiv, cstack, loop), op, flags, equalities], cache, assumes, djumps_map
| Dba.Instr.Free (expr, id_suiv) ->
let addr = Dba_types.Caddress.reid addr id_suiv in
let a = check_exec_permission addr m assumes glbs elements equalities in
let m = free expr m assumes glbs elements equalities in
let addrStack = (a, cstack, loop) in
[addrStack, m, flags, equalities], cache, assumes, djumps_map
| Dba.Instr.SJump (JInner id_suiv, _call_return_tag) ->
let a = Dba_types.Caddress.reid addr id_suiv in
let addrStack = a, cstack, loop in
[addrStack, m, flags, equalities], cache, assumes, djumps_map
| Dba.Instr.SJump (JOuter addr_suiv, Some Dba.Call addr_ret) ->
let calling_callee_addr = addr_ret, addr_suiv in
if is_visited calling_callee_addr cstack 20
then
raise (RecursiveCall addr_suiv)
else (
Display.display (Display.Call(addr_suiv, addr_ret));
let cstack = calling_callee_addr :: cstack in
let addrStack = addr_suiv, cstack, loop in
[addrStack, m, flags, equalities], cache, assumes, djumps_map
)
| Dba.Instr.SJump (JOuter addr_suiv, Some Return) ->
Display.increase_function_count ();
let cstack =
match cstack with
| (old_ret, _) :: cstack' ->
if Dba_types.Caddress.equal old_ret addr_suiv then cstack'
else cstack
| [] -> []
in
let addrStack = addr_suiv, cstack, loop in
[addrStack, m, flags, equalities], cache, assumes, djumps_map
| Dba.Instr.SJump (JOuter addr_suiv, _call_return_tag) ->
let addrStack = addr_suiv, cstack, loop in
[addrStack, m, flags, equalities], cache, assumes, djumps_map
| Dba.Instr.DJump (expr, call_return_tag) ->
let a, rcd, djumps_map =
resolve_jump addrStack expr m flags equalities rcd assumes glbs djumps_map call_return_tag elements in
let cache = rcd, rcd_conds in
a, cache, assumes, djumps_map
| Dba.Instr.If (condition, JOuter addr_suiv1, id_suiv2) ->
let cond, rcd_conds = retrieve_comparison ~condition flags addr rcd_conds in
let eq1 = Eq.copy_equalities equalities in
let eq2 = Eq.copy_equalities equalities in
let m1, assumes, rcd, eq1 = guard addrStack cond m assumes glbs rcd elements eq1 in
let n_cond = Dba.Expr.lognot cond in
let m2, assumes, rcd, eq2 = guard addrStack n_cond m assumes glbs rcd elements eq2 in
let a1 = addr_suiv1 in
let a2 = Dba_types.Caddress.reid addr id_suiv2 in
let loops =
try Dba_types.Caddress.Map.find addr unrolled_loops
with Not_found -> Dba_types.Caddress.Set.empty
in
0 , 0
if Dba_types.Caddress.Set.cardinal loops = 1
then
if Dba_types.Caddress.Set.mem a1 loops
then min (loop + 1) 50, 0
else 0, min (loop + 1) 50
else loop, loop
in
let addr_suiv1 = (a1, cstack, loop1) in
let addr = (a2, cstack, loop2) in
let l = resolve_if cond m flags (m1, eq1) (m2, eq2) addr_suiv1 addr assumes glbs elements equalities in
let cache = (rcd, rcd_conds) in
l, cache, assumes, djumps_map
| Dba.Instr.If (condition, JInner id_suiv1, id_suiv2) ->
let cond, rcd_conds = retrieve_comparison ~condition flags addr rcd_conds in
let eq1 = Eq.copy_equalities equalities in
let eq2 = Eq.copy_equalities equalities in
let m1, assumes, rcd, eq1 =
guard addrStack cond m assumes glbs rcd elements eq1 in
let ncond = Dba.Expr.lognot cond in
let m2, assumes, rcd, eq2 =
guard addrStack ncond m assumes glbs rcd elements eq2 in
let loops =
try Dba_types.Caddress.Map.find addr unrolled_loops
with Not_found -> Dba_types.Caddress.Set.empty
in
let a1 = Dba_types.Caddress.reid addr id_suiv1 in
let a2 = Dba_types.Caddress.reid addr id_suiv2 in
0 , 0
if Dba_types.Caddress.Set.cardinal loops = 1
then
if Dba_types.Caddress.Set.mem a1 loops
then min (loop + 1) 50, 0
else 0, min (loop + 1) 50
else loop, loop
in
let a1 = (a1, cstack, loop1) in
let a2 = (a2, cstack, loop2) in
let l = resolve_if cond m flags (m1, eq1) (m2, eq2) a1 a2 assumes glbs elements equalities in
let cache = (rcd, rcd_conds) in
l, cache, assumes, djumps_map
| Dba.Instr.Assert (condition, id_suiv) ->
let cond, rcd_conds = retrieve_comparison ~condition flags addr rcd_conds in
let a = (Dba_types.Caddress.reid addr id_suiv, cstack, loop) in
let l = resolve_assert cond m flags equalities a addrStack instr assumes glbs rcd elements in
let cache = (rcd, rcd_conds) in
l, cache, assumes, djumps_map
| Dba.Instr.Assume (condition, id_suiv) ->
let cond, rcd_conds = retrieve_comparison ~condition flags addr rcd_conds in
let a = (Dba_types.Caddress.reid addr id_suiv, cstack, loop) in
let l = resolve_assume addrStack cond m flags equalities a assumes glbs rcd elements in
let cache = (rcd, rcd_conds) in
l, cache, assumes, djumps_map
| Dba.Instr.NondetAssume (lhslst, condition, id_suiv) ->
let cnd, rcd_conds = retrieve_comparison ~condition flags addr rcd_conds in
let a = (Dba_types.Caddress.reid addr id_suiv, cstack, loop) in
let op, assumes, rcd =
resolve_nondet_assume addrStack lhslst cnd m flags equalities a assumes glbs rcd elements in
let cache = (rcd, rcd_conds) in
op, cache, assumes, djumps_map
| Dba.Instr.Nondet (lhs, region, id_suiv) ->
let a = (Dba_types.Caddress.reid addr id_suiv, cstack, loop) in
let op = resolve_nondet addrStack lhs region m flags equalities a assumes glbs rcd elements in
op, cache, assumes, djumps_map
| Dba.Instr.Undef (lhs, id_suiv) ->
let a = (Dba_types.Caddress.reid addr id_suiv, cstack, loop) in
let l = resolve_undef addrStack lhs m flags equalities a assumes glbs rcd elements in
l, cache, assumes, djumps_map
| Dba.Instr.Print (args, id_suiv) ->
let a = (Dba_types.Caddress.reid addr id_suiv, cstack, loop) in
let l = resolve_print args m flags equalities a assumes glbs elements in
l, cache, assumes, djumps_map
let get_initial_state inits =
let addr = Dba_types.Caddress.block_start @@ Virtual_address.create 0 in
let cstack = [] in
let loop = 0 in
let addrStack = (addr, cstack, loop) in
let rcd = Dba_types.AddressStack.Map.empty in
let equalities = Eq.create () in
let conds = [] in
let glbs = Dba_types.Caddress.Set.empty in
let djmps = Dba_types.AddressStack.Map.empty in
let flags = High_level_predicate.empty in
let rcd_conds = Dba_types.Caddress.Map.empty in
let unrolled_loops = Dba_types.Caddress.Map.empty in
let cache = rcd, rcd_conds in
let init_state m instr =
let abs_vals = m, flags, equalities in
post abs_vals addrStack instr cache conds glbs djmps unrolled_loops []
in
let f m instr =
match init_state m instr with
| (_, res, _, _) :: _, _, _, _ -> res
| [], _, _, _ -> assert false
in
let m_top = Some Env.empty in
List.fold_left f m_top inits
let _projection _s _p = failwith "Not implemented"
let env_to_smt_list m varIndexes inputs =
let env, inputs =
match m with
| None -> [], inputs
| Some m ->
Env.fold (
fun key sub_m (acc, inputs) ->
match key with
| Static_types.Var (n, size) ->
MemMap.fold (fun _bv (_, _, v) (acc, inputs) ->
let id =
try String.Map.find n varIndexes
with Not_found -> 0
in
let name = n^(string_of_int id) in
let var = Formula.bv_var name size in
let var1 = Formula.BvVar var in
let var2 = Formula.mk_bv_var var in
if Formula.VarSet.mem var1 inputs then
(Val.to_smt v var2) @ acc, inputs
else
let inputs = Formula.VarSet.add var1 inputs in
(Val.to_smt v var2) @ acc, inputs) sub_m (acc, inputs)
| Static_types.Array region ->
MemMap.fold (fun bv (_, en, v) (acc, inputs) ->
let i = MemInterval.base_of bv in
let size = MemInterval.size_of bv in
let expr = Dba.Expr.constant ~region (Bitvector.create i 32) in
let var, inputs =
Normalize_instructions.load_to_smt expr size en inputs varIndexes in
(Val.to_smt v var) @ acc, inputs) sub_m (acc, inputs)
) m ([], inputs)
in
match !s_init with
| None -> env, inputs
| Some s ->
Env.fold (fun key sub_m (acc, inputs) ->
match key with
| Static_types.Array `Constant ->
MemMap.fold (fun bv (_, en, v) (acc, inputs) ->
let i = MemInterval.base_of bv in
let size = MemInterval.size_of bv in
let c =
match m with
None -> true
| Some m ->
try let _ = MemMap.find bv (Env.find (Static_types.Array `Constant) m) in
false
with Not_found -> true
in
if c then
let expr = Dba.Expr.constant (Bitvector.create i 32) in
let var, inputs = Normalize_instructions.load_to_smt expr size en inputs varIndexes in
Val.to_smt v var @ acc, inputs
else acc, inputs) sub_m (acc, inputs)
| Static_types.Array `Stack
| Static_types.Array `Malloc ((_, _), _)
| Static_types.Var (_, _) -> acc, inputs
) s (env, inputs)
let refine_state m smt_env =
match m with
| None -> m
| Some m ->
let new_m = Env.fold (
fun key sub_m acc ->
match key with
| Static_types.Var (n, _size) ->
if n = "eax" || n = "ecx" || n = "ebx" || n = "edx" then
let name = n ^ "0" in
let new_sub_m =
MemMap.fold
(fun bv (a, en, v) acc ->
let new_v = Val.smt_refine v smt_env name in
Logger.debug "Refining %s: %a -> %a" name Val.pp v Val.pp new_v;
MemMap.add bv (a, en, new_v) acc)
sub_m sub_m
in Env.add key new_sub_m acc
else acc
| Static_types.Array `Constant -> acc
| Static_types.Array `Stack ->
let new_sub_m =
MemMap.fold
(fun bv (a, en, v) acc ->
match MemInterval.size_of bv with
| 4 ->
let i = MemInterval.base_of bv in
let addr =
Formula_pp.print_bv_term
(Formula.mk_bv_cst (Bitvector.create i 32)) in
let name = Format.asprintf "(load32_at memory0 %s)" addr in
let v' = Val.smt_refine v smt_env name in
Logger.debug "Refining %s: %a -> %a" name Val.pp v Val.pp v';
MemMap.add bv (a, en, v') acc
| _ -> acc)
sub_m sub_m
in Env.add key new_sub_m acc
| Static_types.Array ((`Malloc ((_id, _), _))) -> acc
) m m in
Some new_m
end
|
011d5066445cd1d2485af7041e4b59897cc8c3467993a7d5c2fd9db8992b1812
|
janestreet/base
|
test_exn_reraise.ml
|
open! Import
(* These methods miss part of the backtrace. *)
let clobber_most_recent_backtrace () =
try failwith "clobbering" with
| _ -> ()
;;
let _Base_Exn_reraise exn = Exn.reraise exn "reraised"
let _Base_Exn_reraise_after_clobbering_most_recent_backtrace exn =
clobber_most_recent_backtrace ();
Exn.reraise exn "reraised"
;;
external reraiser_raw : exn -> 'a = "%reraise"
let external_reraise_unequal exn = reraiser_raw (Exn.Reraised ("reraised", exn))
let vanilla_raise_unequal exn = raise (Exn.Reraised ("reraised", exn))
(* These methods produce the full, desired backtrace. *)
let vanilla_raise exn = raise exn
let raise_with_original_backtrace exn =
let backtrace = Backtrace.Exn.most_recent () in
Exn.raise_with_original_backtrace (Exn.Reraised ("reraised", exn)) backtrace
;;
(* This ref causes [check_value] to appear in the backtrace, because the [raise_s] call is
no longer in tail position. *)
let setter = ref 0
let check_value x =
if x < 0 then raise_s [%message "bad value" (x : int)];
setter := x
;;
This function duplicates the functionality of [ Exn.reraise_uncaught ] with a custom
[ reraiser ]
[reraiser] *)
let reraise_uncaught reraiser f =
try f () with
| exn -> reraiser exn
;;
let callstacker ~reraise_uncaught =
let rec loop reraise_uncaught x =
reraise_uncaught (fun () -> check_value x);
loop reraise_uncaught (x - 1);
reraise_uncaught (fun () -> check_value x)
in
loop reraise_uncaught 1
;;
let with_backtraces_enabled f =
Backtrace.Exn.with_recording true ~f:(fun () ->
Ref.set_temporarily Backtrace.elide false ~f)
;;
let test_reraise_uncaught ~reraise_uncaught =
with_backtraces_enabled (fun () ->
Exn.handle_uncaught ~exit:false (fun () -> callstacker ~reraise_uncaught))
;;
let test_reraiser reraiser =
test_reraise_uncaught ~reraise_uncaught:(reraise_uncaught reraiser)
;;
(* If you want to see what the underlying backtraces look like, set this to true.
Otherwise, these tests extract small snippets from the backtraces so that they are
robust to compiler changes. *)
let just_print = false
let really_show_backtrace s =
if just_print
then print_endline s
else
printf
"Before re-raise: %b\nAfter re-raise: %b"
(String.is_substring s ~substring:"check_value")
(String.is_substring s ~substring:"handle_uncaught")
;;
let%test_module ("Show native backtraces" [@tags "no-js"]) =
(module struct
(* good *)
let%expect_test "Base.Exn.reraise" =
test_reraiser _Base_Exn_reraise;
really_show_backtrace [%expect.output];
[%expect {|
Before re-raise: true
After re-raise: true |}]
;;
(* bad, because the backtrace was clobbered *)
let%expect_test "Base.Exn.reraise" =
test_reraiser _Base_Exn_reraise_after_clobbering_most_recent_backtrace;
really_show_backtrace [%expect.output];
[%expect {|
Before re-raise: false
After re-raise: true |}]
;;
(* bad, missing the backtrace before the reraise *)
let%expect_test "%reraise unequal" =
test_reraiser external_reraise_unequal;
really_show_backtrace [%expect.output];
[%expect {|
Before re-raise: false
After re-raise: true |}]
;;
(* bad, missing the backtrace before the reraise *)
let%expect_test "raise unequal" =
test_reraiser vanilla_raise_unequal;
really_show_backtrace [%expect.output];
[%expect {|
Before re-raise: false
After re-raise: true |}]
;;
(* good, but no additional info attached *)
let%expect_test "raise equal" =
test_reraiser vanilla_raise;
really_show_backtrace [%expect.output];
[%expect {|
Before re-raise: true
After re-raise: true |}]
;;
(* good *)
let%expect_test "Caml.Printexc.raise_with_backtrace" =
test_reraiser raise_with_original_backtrace;
really_show_backtrace [%expect.output];
[%expect {|
Before re-raise: true
After re-raise: true |}]
;;
(* good *)
let%expect_test "Exn.reraise_uncaught" =
test_reraise_uncaught ~reraise_uncaught:(Exn.reraise_uncaught "reraised");
really_show_backtrace [%expect.output];
[%expect {|
Before re-raise: true
After re-raise: true |}]
;;
end)
;;
An example bad backtrace :
{ v
Uncaught exception :
( exn.ml . Reraised reraised ( " bad value " ( x -1 ) ) )
Raised at Base_test__Test_exn_reraise.vanilla_raise_unequal in file " test_exn_reraise.ml " ( inlined ) , line 10 , characters 32 - 70
Called from Base_test__Test_exn_reraise.reraise_uncaught in file " test_exn_reraise.ml " ( inlined ) , line 34 , characters 11 - 23
Called from Base_test__Test_exn_reraise.callstacker.loop in file " test_exn_reraise.ml " , line 39 , characters 4 - 55
Called from Base_test__Test_exn_reraise.callstacker.loop in file " test_exn_reraise.ml " ( inlined ) , line 38 , characters 15 - 167
Called from Base_test__Test_exn_reraise.callstacker.loop in file " test_exn_reraise.ml " ( inlined ) , line 40 , characters 4 - 25
Called from Base_test__Test_exn_reraise.callstacker.loop in file " test_exn_reraise.ml " ( inlined ) , line 38 , characters 15 - 167
Called from Base_test__Test_exn_reraise.callstacker.loop in file " test_exn_reraise.ml " ( inlined ) , line 40 , characters 4 - 25
Called from Base_test__Test_exn_reraise.callstacker in file " test_exn_reraise.ml " ( inlined ) , line 43 , characters 2 - 17
Called from Base__Exn.handle_uncaught_aux in file " exn.ml " ( inlined ) , line 113 , characters 6 - 10
Called from Base__Exn.handle_uncaught in file " exn.ml " ( inlined ) , line 139 , characters 2 - 88
Called from Base_test__Test_exn_reraise.test.(fun ) in file " test_exn_reraise.ml " , line 53 , characters 4 - 68
v }
{v
Uncaught exception:
(exn.ml.Reraised reraised ("bad value" (x -1)))
Raised at Base_test__Test_exn_reraise.vanilla_raise_unequal in file "test_exn_reraise.ml" (inlined), line 10, characters 32-70
Called from Base_test__Test_exn_reraise.reraise_uncaught in file "test_exn_reraise.ml" (inlined), line 34, characters 11-23
Called from Base_test__Test_exn_reraise.callstacker.loop in file "test_exn_reraise.ml", line 39, characters 4-55
Called from Base_test__Test_exn_reraise.callstacker.loop in file "test_exn_reraise.ml" (inlined), line 38, characters 15-167
Called from Base_test__Test_exn_reraise.callstacker.loop in file "test_exn_reraise.ml" (inlined), line 40, characters 4-25
Called from Base_test__Test_exn_reraise.callstacker.loop in file "test_exn_reraise.ml" (inlined), line 38, characters 15-167
Called from Base_test__Test_exn_reraise.callstacker.loop in file "test_exn_reraise.ml" (inlined), line 40, characters 4-25
Called from Base_test__Test_exn_reraise.callstacker in file "test_exn_reraise.ml" (inlined), line 43, characters 2-17
Called from Base__Exn.handle_uncaught_aux in file "exn.ml" (inlined), line 113, characters 6-10
Called from Base__Exn.handle_uncaught in file "exn.ml" (inlined), line 139, characters 2-88
Called from Base_test__Test_exn_reraise.test.(fun) in file "test_exn_reraise.ml", line 53, characters 4-68
v}
*)
An example good backtrace :
{ v
Uncaught exception :
( exn.ml . Reraised reraised ( " bad value " ( x -1 ) ) )
Raised at Base__Error.raise in file " error.ml " ( inlined ) , line 9 , characters 14 - 30
Called from Base__Error.raise_s in file " error.ml " ( inlined ) , line 10 , characters 19 - 40
Called from Base_test__Test_exn_reraise.check_value in file " test_exn_reraise.ml " , line 26 , characters 16 - 56
Called from Base_test__Test_exn_reraise.callstacker.loop.(fun ) in file " test_exn_reraise.ml " ( inlined ) , line 39 , characters 41 - 54
Called from Base_test__Test_exn_reraise.reraise_uncaught in file " test_exn_reraise.ml " ( inlined ) , line 33 , characters 6 - 10
Called from Base_test__Test_exn_reraise.callstacker.loop in file " test_exn_reraise.ml " , line 39 , characters 4 - 55
Re - raised at Base_test__Test_exn_reraise._Caml_Printexc_raise_with_backtrace in file " test_exn_reraise.ml " , line 18 , characters 2 - 79
Called from Base_test__Test_exn_reraise.reraise_uncaught in file " test_exn_reraise.ml " ( inlined ) , line 34 , characters 11 - 23
Called from Base_test__Test_exn_reraise.callstacker.loop in file " test_exn_reraise.ml " , line 39 , characters 4 - 55
Called from Base_test__Test_exn_reraise.callstacker.loop in file " test_exn_reraise.ml " ( inlined ) , line 40 , characters 4 - 25
Called from Base_test__Test_exn_reraise.callstacker.loop in file " test_exn_reraise.ml " ( inlined ) , line 40 , characters 4 - 25
Called from Base_test__Test_exn_reraise.callstacker in file " test_exn_reraise.ml " ( inlined ) , line 43 , characters 2 - 17
Called from Base__Exn.handle_uncaught_aux in file " exn.ml " ( inlined ) , line 113 , characters 6 - 10
Called from Base__Exn.handle_uncaught in file " exn.ml " ( inlined ) , line 139 , characters 2 - 88
Called from Base_test__Test_exn_reraise.test.(fun ) in file " test_exn_reraise.ml " , line 53 , characters 4 - 68
v }
{v
Uncaught exception:
(exn.ml.Reraised reraised ("bad value" (x -1)))
Raised at Base__Error.raise in file "error.ml" (inlined), line 9, characters 14-30
Called from Base__Error.raise_s in file "error.ml" (inlined), line 10, characters 19-40
Called from Base_test__Test_exn_reraise.check_value in file "test_exn_reraise.ml", line 26, characters 16-56
Called from Base_test__Test_exn_reraise.callstacker.loop.(fun) in file "test_exn_reraise.ml" (inlined), line 39, characters 41-54
Called from Base_test__Test_exn_reraise.reraise_uncaught in file "test_exn_reraise.ml" (inlined), line 33, characters 6-10
Called from Base_test__Test_exn_reraise.callstacker.loop in file "test_exn_reraise.ml", line 39, characters 4-55
Re-raised at Base_test__Test_exn_reraise._Caml_Printexc_raise_with_backtrace in file "test_exn_reraise.ml", line 18, characters 2-79
Called from Base_test__Test_exn_reraise.reraise_uncaught in file "test_exn_reraise.ml" (inlined), line 34, characters 11-23
Called from Base_test__Test_exn_reraise.callstacker.loop in file "test_exn_reraise.ml", line 39, characters 4-55
Called from Base_test__Test_exn_reraise.callstacker.loop in file "test_exn_reraise.ml" (inlined), line 40, characters 4-25
Called from Base_test__Test_exn_reraise.callstacker.loop in file "test_exn_reraise.ml" (inlined), line 40, characters 4-25
Called from Base_test__Test_exn_reraise.callstacker in file "test_exn_reraise.ml" (inlined), line 43, characters 2-17
Called from Base__Exn.handle_uncaught_aux in file "exn.ml" (inlined), line 113, characters 6-10
Called from Base__Exn.handle_uncaught in file "exn.ml" (inlined), line 139, characters 2-88
Called from Base_test__Test_exn_reraise.test.(fun) in file "test_exn_reraise.ml", line 53, characters 4-68
v}*)
| null |
https://raw.githubusercontent.com/janestreet/base/8ea6adb415ebc27fec97e1ae34b9a3d5483eb3f0/test/test_exn_reraise.ml
|
ocaml
|
These methods miss part of the backtrace.
These methods produce the full, desired backtrace.
This ref causes [check_value] to appear in the backtrace, because the [raise_s] call is
no longer in tail position.
If you want to see what the underlying backtraces look like, set this to true.
Otherwise, these tests extract small snippets from the backtraces so that they are
robust to compiler changes.
good
bad, because the backtrace was clobbered
bad, missing the backtrace before the reraise
bad, missing the backtrace before the reraise
good, but no additional info attached
good
good
|
open! Import
let clobber_most_recent_backtrace () =
try failwith "clobbering" with
| _ -> ()
;;
let _Base_Exn_reraise exn = Exn.reraise exn "reraised"
let _Base_Exn_reraise_after_clobbering_most_recent_backtrace exn =
clobber_most_recent_backtrace ();
Exn.reraise exn "reraised"
;;
external reraiser_raw : exn -> 'a = "%reraise"
let external_reraise_unequal exn = reraiser_raw (Exn.Reraised ("reraised", exn))
let vanilla_raise_unequal exn = raise (Exn.Reraised ("reraised", exn))
let vanilla_raise exn = raise exn
let raise_with_original_backtrace exn =
let backtrace = Backtrace.Exn.most_recent () in
Exn.raise_with_original_backtrace (Exn.Reraised ("reraised", exn)) backtrace
;;
let setter = ref 0
let check_value x =
if x < 0 then raise_s [%message "bad value" (x : int)];
setter := x
;;
This function duplicates the functionality of [ Exn.reraise_uncaught ] with a custom
[ reraiser ]
[reraiser] *)
let reraise_uncaught reraiser f =
try f () with
| exn -> reraiser exn
;;
let callstacker ~reraise_uncaught =
let rec loop reraise_uncaught x =
reraise_uncaught (fun () -> check_value x);
loop reraise_uncaught (x - 1);
reraise_uncaught (fun () -> check_value x)
in
loop reraise_uncaught 1
;;
let with_backtraces_enabled f =
Backtrace.Exn.with_recording true ~f:(fun () ->
Ref.set_temporarily Backtrace.elide false ~f)
;;
let test_reraise_uncaught ~reraise_uncaught =
with_backtraces_enabled (fun () ->
Exn.handle_uncaught ~exit:false (fun () -> callstacker ~reraise_uncaught))
;;
let test_reraiser reraiser =
test_reraise_uncaught ~reraise_uncaught:(reraise_uncaught reraiser)
;;
let just_print = false
let really_show_backtrace s =
if just_print
then print_endline s
else
printf
"Before re-raise: %b\nAfter re-raise: %b"
(String.is_substring s ~substring:"check_value")
(String.is_substring s ~substring:"handle_uncaught")
;;
let%test_module ("Show native backtraces" [@tags "no-js"]) =
(module struct
let%expect_test "Base.Exn.reraise" =
test_reraiser _Base_Exn_reraise;
really_show_backtrace [%expect.output];
[%expect {|
Before re-raise: true
After re-raise: true |}]
;;
let%expect_test "Base.Exn.reraise" =
test_reraiser _Base_Exn_reraise_after_clobbering_most_recent_backtrace;
really_show_backtrace [%expect.output];
[%expect {|
Before re-raise: false
After re-raise: true |}]
;;
let%expect_test "%reraise unequal" =
test_reraiser external_reraise_unequal;
really_show_backtrace [%expect.output];
[%expect {|
Before re-raise: false
After re-raise: true |}]
;;
let%expect_test "raise unequal" =
test_reraiser vanilla_raise_unequal;
really_show_backtrace [%expect.output];
[%expect {|
Before re-raise: false
After re-raise: true |}]
;;
let%expect_test "raise equal" =
test_reraiser vanilla_raise;
really_show_backtrace [%expect.output];
[%expect {|
Before re-raise: true
After re-raise: true |}]
;;
let%expect_test "Caml.Printexc.raise_with_backtrace" =
test_reraiser raise_with_original_backtrace;
really_show_backtrace [%expect.output];
[%expect {|
Before re-raise: true
After re-raise: true |}]
;;
let%expect_test "Exn.reraise_uncaught" =
test_reraise_uncaught ~reraise_uncaught:(Exn.reraise_uncaught "reraised");
really_show_backtrace [%expect.output];
[%expect {|
Before re-raise: true
After re-raise: true |}]
;;
end)
;;
An example bad backtrace :
{ v
Uncaught exception :
( exn.ml . Reraised reraised ( " bad value " ( x -1 ) ) )
Raised at Base_test__Test_exn_reraise.vanilla_raise_unequal in file " test_exn_reraise.ml " ( inlined ) , line 10 , characters 32 - 70
Called from Base_test__Test_exn_reraise.reraise_uncaught in file " test_exn_reraise.ml " ( inlined ) , line 34 , characters 11 - 23
Called from Base_test__Test_exn_reraise.callstacker.loop in file " test_exn_reraise.ml " , line 39 , characters 4 - 55
Called from Base_test__Test_exn_reraise.callstacker.loop in file " test_exn_reraise.ml " ( inlined ) , line 38 , characters 15 - 167
Called from Base_test__Test_exn_reraise.callstacker.loop in file " test_exn_reraise.ml " ( inlined ) , line 40 , characters 4 - 25
Called from Base_test__Test_exn_reraise.callstacker.loop in file " test_exn_reraise.ml " ( inlined ) , line 38 , characters 15 - 167
Called from Base_test__Test_exn_reraise.callstacker.loop in file " test_exn_reraise.ml " ( inlined ) , line 40 , characters 4 - 25
Called from Base_test__Test_exn_reraise.callstacker in file " test_exn_reraise.ml " ( inlined ) , line 43 , characters 2 - 17
Called from Base__Exn.handle_uncaught_aux in file " exn.ml " ( inlined ) , line 113 , characters 6 - 10
Called from Base__Exn.handle_uncaught in file " exn.ml " ( inlined ) , line 139 , characters 2 - 88
Called from Base_test__Test_exn_reraise.test.(fun ) in file " test_exn_reraise.ml " , line 53 , characters 4 - 68
v }
{v
Uncaught exception:
(exn.ml.Reraised reraised ("bad value" (x -1)))
Raised at Base_test__Test_exn_reraise.vanilla_raise_unequal in file "test_exn_reraise.ml" (inlined), line 10, characters 32-70
Called from Base_test__Test_exn_reraise.reraise_uncaught in file "test_exn_reraise.ml" (inlined), line 34, characters 11-23
Called from Base_test__Test_exn_reraise.callstacker.loop in file "test_exn_reraise.ml", line 39, characters 4-55
Called from Base_test__Test_exn_reraise.callstacker.loop in file "test_exn_reraise.ml" (inlined), line 38, characters 15-167
Called from Base_test__Test_exn_reraise.callstacker.loop in file "test_exn_reraise.ml" (inlined), line 40, characters 4-25
Called from Base_test__Test_exn_reraise.callstacker.loop in file "test_exn_reraise.ml" (inlined), line 38, characters 15-167
Called from Base_test__Test_exn_reraise.callstacker.loop in file "test_exn_reraise.ml" (inlined), line 40, characters 4-25
Called from Base_test__Test_exn_reraise.callstacker in file "test_exn_reraise.ml" (inlined), line 43, characters 2-17
Called from Base__Exn.handle_uncaught_aux in file "exn.ml" (inlined), line 113, characters 6-10
Called from Base__Exn.handle_uncaught in file "exn.ml" (inlined), line 139, characters 2-88
Called from Base_test__Test_exn_reraise.test.(fun) in file "test_exn_reraise.ml", line 53, characters 4-68
v}
*)
An example good backtrace :
{ v
Uncaught exception :
( exn.ml . Reraised reraised ( " bad value " ( x -1 ) ) )
Raised at Base__Error.raise in file " error.ml " ( inlined ) , line 9 , characters 14 - 30
Called from Base__Error.raise_s in file " error.ml " ( inlined ) , line 10 , characters 19 - 40
Called from Base_test__Test_exn_reraise.check_value in file " test_exn_reraise.ml " , line 26 , characters 16 - 56
Called from Base_test__Test_exn_reraise.callstacker.loop.(fun ) in file " test_exn_reraise.ml " ( inlined ) , line 39 , characters 41 - 54
Called from Base_test__Test_exn_reraise.reraise_uncaught in file " test_exn_reraise.ml " ( inlined ) , line 33 , characters 6 - 10
Called from Base_test__Test_exn_reraise.callstacker.loop in file " test_exn_reraise.ml " , line 39 , characters 4 - 55
Re - raised at Base_test__Test_exn_reraise._Caml_Printexc_raise_with_backtrace in file " test_exn_reraise.ml " , line 18 , characters 2 - 79
Called from Base_test__Test_exn_reraise.reraise_uncaught in file " test_exn_reraise.ml " ( inlined ) , line 34 , characters 11 - 23
Called from Base_test__Test_exn_reraise.callstacker.loop in file " test_exn_reraise.ml " , line 39 , characters 4 - 55
Called from Base_test__Test_exn_reraise.callstacker.loop in file " test_exn_reraise.ml " ( inlined ) , line 40 , characters 4 - 25
Called from Base_test__Test_exn_reraise.callstacker.loop in file " test_exn_reraise.ml " ( inlined ) , line 40 , characters 4 - 25
Called from Base_test__Test_exn_reraise.callstacker in file " test_exn_reraise.ml " ( inlined ) , line 43 , characters 2 - 17
Called from Base__Exn.handle_uncaught_aux in file " exn.ml " ( inlined ) , line 113 , characters 6 - 10
Called from Base__Exn.handle_uncaught in file " exn.ml " ( inlined ) , line 139 , characters 2 - 88
Called from Base_test__Test_exn_reraise.test.(fun ) in file " test_exn_reraise.ml " , line 53 , characters 4 - 68
v }
{v
Uncaught exception:
(exn.ml.Reraised reraised ("bad value" (x -1)))
Raised at Base__Error.raise in file "error.ml" (inlined), line 9, characters 14-30
Called from Base__Error.raise_s in file "error.ml" (inlined), line 10, characters 19-40
Called from Base_test__Test_exn_reraise.check_value in file "test_exn_reraise.ml", line 26, characters 16-56
Called from Base_test__Test_exn_reraise.callstacker.loop.(fun) in file "test_exn_reraise.ml" (inlined), line 39, characters 41-54
Called from Base_test__Test_exn_reraise.reraise_uncaught in file "test_exn_reraise.ml" (inlined), line 33, characters 6-10
Called from Base_test__Test_exn_reraise.callstacker.loop in file "test_exn_reraise.ml", line 39, characters 4-55
Re-raised at Base_test__Test_exn_reraise._Caml_Printexc_raise_with_backtrace in file "test_exn_reraise.ml", line 18, characters 2-79
Called from Base_test__Test_exn_reraise.reraise_uncaught in file "test_exn_reraise.ml" (inlined), line 34, characters 11-23
Called from Base_test__Test_exn_reraise.callstacker.loop in file "test_exn_reraise.ml", line 39, characters 4-55
Called from Base_test__Test_exn_reraise.callstacker.loop in file "test_exn_reraise.ml" (inlined), line 40, characters 4-25
Called from Base_test__Test_exn_reraise.callstacker.loop in file "test_exn_reraise.ml" (inlined), line 40, characters 4-25
Called from Base_test__Test_exn_reraise.callstacker in file "test_exn_reraise.ml" (inlined), line 43, characters 2-17
Called from Base__Exn.handle_uncaught_aux in file "exn.ml" (inlined), line 113, characters 6-10
Called from Base__Exn.handle_uncaught in file "exn.ml" (inlined), line 139, characters 2-88
Called from Base_test__Test_exn_reraise.test.(fun) in file "test_exn_reraise.ml", line 53, characters 4-68
v}*)
|
1d9c9f61d34a0def6825a6bb75ae7aaf3c21aefafcdacba92e82caee203b4794
|
xh4/web-toolkit
|
fsbv.lisp
|
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; fsbv.lisp --- Tests of foreign structure by value calls.
;;;
Copyright ( C ) 2011 ,
;;;
;;; 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.
;;;
(in-package #:cffi-tests)
;; Requires struct.lisp
(defcfun "sumpair" :int
(p (:struct struct-pair)))
(defcfun "makepair" (:struct struct-pair)
(condition :bool))
(defcfun "doublepair" (:struct struct-pair)
(p (:struct struct-pair)))
(defcfun "prodsumpair" :double
(p (:struct struct-pair+double)))
(defcfun "doublepairdouble" (:struct struct-pair+double)
(p (:struct struct-pair+double)))
;;; Call struct by value
(deftest fsbv.1
(sumpair '(1 . 2))
3)
;;; See lp#1528719
(deftest (fsbv.wfo :expected-to-fail t)
(with-foreign-object (arg '(:struct struct-pair))
(convert-into-foreign-memory '(40 . 2) '(:struct struct-pair) arg)
(sumpair arg))
42)
;;; Call and return struct by value
(deftest fsbv.2
(doublepair '(1 . 2))
(2 . 4))
;;; return struct by value
(deftest (fsbv.makepair.1 :expected-to-fail t)
(makepair nil)
(-127 . 43))
(deftest (fsbv.makepair.2 :expected-to-fail t)
(makepair t)
(-127 . 42))
;;; Call recursive structure by value
(deftest fsbv.3
(prodsumpair '(pr (a 4 b 5) dbl 2.5d0))
22.5d0)
;;; Call and return recursive structure by value
(deftest fsbv.4
(let ((ans (doublepairdouble '(pr (a 4 b 5) dbl 2.5d0))))
(values (getf (getf ans 'pr) 'a)
(getf (getf ans 'pr) 'b)
(getf ans 'dbl)))
8
10
5.0d0)
(defcstruct (struct-with-array :size 6)
(s1 (:array :char 6)))
(defcfun "zork" :void
(p (:struct struct-with-array)))
Typedef fsbv test
(defcfun ("sumpair" sumpair2) :int
(p struct-pair-typedef1))
(deftest fsbv.5
(sumpair2 '(1 . 2))
3)
(defcfun "returnpairpointer" (:pointer (:struct struct-pair))
(ignored (:struct struct-pair)))
(deftest fsbv.return-a-pointer
(let ((ptr (returnpairpointer '(1 . 2))))
(+ (foreign-slot-value ptr '(:struct struct-pair) 'a)
(foreign-slot-value ptr '(:struct struct-pair) 'b)))
42)
;;; Test ulonglong on no-long-long implementations.
(defcfun "ullsum" :unsigned-long-long
(a :unsigned-long-long) (b :unsigned-long-long))
(deftest fsbv.6
(ullsum #x10DEADBEEF #x2300000000)
#x33DEADBEEF)
;;; Combine structures by value with a string argument
(defcfun "stringlenpair" (:struct struct-pair)
(s :string)
(p (:struct struct-pair)))
(deftest fsbv.7
(stringlenpair "abc" '(1 . 2))
(3 . 6))
;;; Combine structures by value with an enum argument
(defcfun "enumpair" (:int)
(e numeros)
(p (:struct struct-pair)))
(deftest fsbv.8
(enumpair :two '(1 . 2))
5)
returning struct with bitfield member ( bug # 1474631 )
(defbitfield (struct-bitfield :unsigned-int)
(:a 1)
(:b 2))
(defcstruct bitfield-struct
(b struct-bitfield))
(defcfun "structbitfield" (:struct bitfield-struct)
(x :unsigned-int))
(defctype struct-bitfield-typedef struct-bitfield)
(defcstruct bitfield-struct.2
(b struct-bitfield-typedef))
(defcfun ("structbitfield" structbitfield.2) (:struct bitfield-struct.2)
(x :unsigned-int))
;; these would get stuck in an infinite loop previously
(deftest fsbv.struct-bitfield.0
(structbitfield 0)
(b nil))
(deftest fsbv.struct-bitfield.1
(structbitfield 1)
(b (:a)))
(deftest fsbv.struct-bitfield.2
(structbitfield 2)
(b (:b)))
(deftest fsbv.struct-bitfield.3
(structbitfield.2 2)
(b (:b)))
;;; Test for a discrepancy between normal and fsbv return values
(cffi:define-foreign-type int-return-code (cffi::foreign-type-alias)
()
(:default-initargs :actual-type (cffi::parse-type :int))
(:simple-parser int-return-code))
(defmethod cffi:expand-from-foreign (value (type int-return-code))
;; NOTE: strictly speaking it should be
;; (cffi:convert-from-foreign ,value :int), but it's irrelevant in this case
`(let ((return-code ,value))
(check-type return-code integer)
return-code))
(defcfun (noargs-with-typedef "noargs") int-return-code)
for reference , not an call
(noargs-with-typedef)
42)
(defcfun (sumpair-with-typedef "sumpair") int-return-code
(p (:struct struct-pair)))
(deftest (fsbv.return-value-typedef)
(sumpair-with-typedef '(40 . 2))
42)
| null |
https://raw.githubusercontent.com/xh4/web-toolkit/e510d44a25b36ca8acd66734ed1ee9f5fe6ecd09/vendor/cffi_0.20.1/tests/fsbv.lisp
|
lisp
|
-*- Mode: lisp; indent-tabs-mode: nil -*-
fsbv.lisp --- Tests of foreign structure by value calls.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
Requires struct.lisp
Call struct by value
See lp#1528719
Call and return struct by value
return struct by value
Call recursive structure by value
Call and return recursive structure by value
Test ulonglong on no-long-long implementations.
Combine structures by value with a string argument
Combine structures by value with an enum argument
these would get stuck in an infinite loop previously
Test for a discrepancy between normal and fsbv return values
NOTE: strictly speaking it should be
(cffi:convert-from-foreign ,value :int), but it's irrelevant in this case
|
Copyright ( C ) 2011 ,
files ( the " Software " ) , to deal in the Software without
of the Software , and to permit persons to whom the Software is
included in all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
(in-package #:cffi-tests)
(defcfun "sumpair" :int
(p (:struct struct-pair)))
(defcfun "makepair" (:struct struct-pair)
(condition :bool))
(defcfun "doublepair" (:struct struct-pair)
(p (:struct struct-pair)))
(defcfun "prodsumpair" :double
(p (:struct struct-pair+double)))
(defcfun "doublepairdouble" (:struct struct-pair+double)
(p (:struct struct-pair+double)))
(deftest fsbv.1
(sumpair '(1 . 2))
3)
(deftest (fsbv.wfo :expected-to-fail t)
(with-foreign-object (arg '(:struct struct-pair))
(convert-into-foreign-memory '(40 . 2) '(:struct struct-pair) arg)
(sumpair arg))
42)
(deftest fsbv.2
(doublepair '(1 . 2))
(2 . 4))
(deftest (fsbv.makepair.1 :expected-to-fail t)
(makepair nil)
(-127 . 43))
(deftest (fsbv.makepair.2 :expected-to-fail t)
(makepair t)
(-127 . 42))
(deftest fsbv.3
(prodsumpair '(pr (a 4 b 5) dbl 2.5d0))
22.5d0)
(deftest fsbv.4
(let ((ans (doublepairdouble '(pr (a 4 b 5) dbl 2.5d0))))
(values (getf (getf ans 'pr) 'a)
(getf (getf ans 'pr) 'b)
(getf ans 'dbl)))
8
10
5.0d0)
(defcstruct (struct-with-array :size 6)
(s1 (:array :char 6)))
(defcfun "zork" :void
(p (:struct struct-with-array)))
Typedef fsbv test
(defcfun ("sumpair" sumpair2) :int
(p struct-pair-typedef1))
(deftest fsbv.5
(sumpair2 '(1 . 2))
3)
(defcfun "returnpairpointer" (:pointer (:struct struct-pair))
(ignored (:struct struct-pair)))
(deftest fsbv.return-a-pointer
(let ((ptr (returnpairpointer '(1 . 2))))
(+ (foreign-slot-value ptr '(:struct struct-pair) 'a)
(foreign-slot-value ptr '(:struct struct-pair) 'b)))
42)
(defcfun "ullsum" :unsigned-long-long
(a :unsigned-long-long) (b :unsigned-long-long))
(deftest fsbv.6
(ullsum #x10DEADBEEF #x2300000000)
#x33DEADBEEF)
(defcfun "stringlenpair" (:struct struct-pair)
(s :string)
(p (:struct struct-pair)))
(deftest fsbv.7
(stringlenpair "abc" '(1 . 2))
(3 . 6))
(defcfun "enumpair" (:int)
(e numeros)
(p (:struct struct-pair)))
(deftest fsbv.8
(enumpair :two '(1 . 2))
5)
returning struct with bitfield member ( bug # 1474631 )
(defbitfield (struct-bitfield :unsigned-int)
(:a 1)
(:b 2))
(defcstruct bitfield-struct
(b struct-bitfield))
(defcfun "structbitfield" (:struct bitfield-struct)
(x :unsigned-int))
(defctype struct-bitfield-typedef struct-bitfield)
(defcstruct bitfield-struct.2
(b struct-bitfield-typedef))
(defcfun ("structbitfield" structbitfield.2) (:struct bitfield-struct.2)
(x :unsigned-int))
(deftest fsbv.struct-bitfield.0
(structbitfield 0)
(b nil))
(deftest fsbv.struct-bitfield.1
(structbitfield 1)
(b (:a)))
(deftest fsbv.struct-bitfield.2
(structbitfield 2)
(b (:b)))
(deftest fsbv.struct-bitfield.3
(structbitfield.2 2)
(b (:b)))
(cffi:define-foreign-type int-return-code (cffi::foreign-type-alias)
()
(:default-initargs :actual-type (cffi::parse-type :int))
(:simple-parser int-return-code))
(defmethod cffi:expand-from-foreign (value (type int-return-code))
`(let ((return-code ,value))
(check-type return-code integer)
return-code))
(defcfun (noargs-with-typedef "noargs") int-return-code)
for reference , not an call
(noargs-with-typedef)
42)
(defcfun (sumpair-with-typedef "sumpair") int-return-code
(p (:struct struct-pair)))
(deftest (fsbv.return-value-typedef)
(sumpair-with-typedef '(40 . 2))
42)
|
be3d88be172022871c12b0ab4780a68bb5b4b378dc7d9156a7e9dfeff1016741
|
haskell/haskell-language-server
|
DestructAllGADTEvidence.hs
|
{-# LANGUAGE DataKinds #-}
# LANGUAGE GADTs #
# LANGUAGE KindSignatures #
{-# LANGUAGE TypeOperators #-}
import Data.Kind
data Nat = Z | S Nat
data HList (ls :: [Type]) where
HNil :: HList '[]
HCons :: t -> HList ts -> HList (t ': ts)
data ElemAt (n :: Nat) t (ts :: [Type]) where
AtZ :: ElemAt 'Z t (t ': ts)
AtS :: ElemAt k t ts -> ElemAt ('S k) t (u ': ts)
lookMeUp :: ElemAt i ty tys -> HList tys -> ty
lookMeUp ea hl = _
| null |
https://raw.githubusercontent.com/haskell/haskell-language-server/f3ad27ba1634871b2240b8cd7de9f31b91a2e502/plugins/hls-tactics-plugin/new/test/golden/DestructAllGADTEvidence.hs
|
haskell
|
# LANGUAGE DataKinds #
# LANGUAGE TypeOperators #
|
# LANGUAGE GADTs #
# LANGUAGE KindSignatures #
import Data.Kind
data Nat = Z | S Nat
data HList (ls :: [Type]) where
HNil :: HList '[]
HCons :: t -> HList ts -> HList (t ': ts)
data ElemAt (n :: Nat) t (ts :: [Type]) where
AtZ :: ElemAt 'Z t (t ': ts)
AtS :: ElemAt k t ts -> ElemAt ('S k) t (u ': ts)
lookMeUp :: ElemAt i ty tys -> HList tys -> ty
lookMeUp ea hl = _
|
32776c522050a825b818b48e37425fe0b98ff523dd6e0bc1271eba2f5f2c6fd7
|
inaka/sumo_db
|
sumo_basic_test_helper.erl
|
-module(sumo_basic_test_helper).
%% Common Test Cases
-export([
create_schema/1,
find/1,
find_all/1,
find_by/1,
delete_all/1,
delete/1,
check_proper_dates/1,
count/1,
count_by/1,
persist_using_changeset/1
]).
%% Shared Helpers
-export([init_store/1]).
-type config() :: [{atom(), term()}].
%%%=============================================================================
%%% Test Cases - Helpers
%%%=============================================================================
-spec create_schema(config()) -> ok.
create_schema(Config) ->
ok = sumo:create_schema(),
Tables = mnesia:system_info(tables),
{_, Name} = lists:keyfind(name, 1, Config),
true = lists:member(Name, Tables),
ok.
-spec find(config()) -> ok.
find(Config) ->
{_, Name} = lists:keyfind(name, 1, Config),
Module = sumo_config:get_prop_value(Name, module),
[First, Second | _] = sumo:find_all(Name),
First = sumo:find_one(Name, [{id, Module:id(First)}]),
Second = sumo:fetch(Name, Module:id(Second)),
notfound = sumo:fetch(Name, 0),
notfound = sumo:find_one(Name, [{id, 0}]),
ok.
-spec find_all(config()) -> ok.
find_all(Config) ->
{_, Name} = lists:keyfind(name, 1, Config),
[_, _, _, _, _, _, _, _] = sumo:find_all(Name),
ok.
-spec find_by(config()) -> ok.
find_by(Config) ->
{_, Name} = lists:keyfind(name, 1, Config),
Module = sumo_config:get_prop_value(Name, module),
Results = sumo:find_by(Name, [{last_name, <<"D">>}]),
[_, _] = Results,
SortFun = fun(A, B) -> Module:name(A) < Module:name(B) end,
[First, Second | _] = lists:sort(SortFun, Results),
{Today, _} = calendar:universal_time(),
<<"B">> = Module:name(First),
<<"D">> = Module:name(Second),
3 = Module:age(First),
4 = Module:age(Second),
<<"D">> = Module:last_name(First),
undefined = Module:address(First),
Today = Module:birthdate(First),
undefined = Module:height(First),
undefined = Module:description(First),
{Today, _} = Module:created_at(First),
false = Module:is_blocked(First),
true = Module:weird_field1(First),
undefined = Module:weird_field2(First),
undefined = Module:weird_field3(First),
% Check that it returns what we have inserted
[LastPerson | _NothingElse] = sumo:find_by(Name, [
{last_name, <<"LastName">>}
]),
<<"Name">> = Module:name(LastPerson),
<<"LastName">> = Module:last_name(LastPerson),
3 = Module:age(LastPerson),
undefined = Module:address(LastPerson),
{Date, _} = calendar:universal_time(),
Date = Module:birthdate(LastPerson),
1.75 = Module:height(LastPerson),
<<"description">> = Module:description(LastPerson),
<<"profile_image">> = Module:profile_image(LastPerson),
true = Module:is_blocked(LastPerson),
{mytuple, false, 1, "2", <<"3">>} = Module:weird_field1(LastPerson),
[1, true, <<"hi">>, 1.1] = Module:weird_field2(LastPerson),
#{a := 1,
b := [1, "2", <<"3">>],
<<"c">> := false
} = Module:weird_field3(LastPerson),
{Today, _} = Module:created_at(LastPerson),
%% Check find_by ID
FirstId = Module:id(First),
[First1] = sumo:find_by(Name, [{id, FirstId}]),
[First1] = sumo:find_by(Name, [{last_name, <<"D">>}, {id, FirstId}]),
[] = sumo:find_by(Name, [{name, <<"NotB">>}, {id, FirstId}]),
First1 = First,
%% Check pagination
Results1 = sumo:find_by(Name, [], 3, 1),
[_, _, _] = Results1,
[_, _, _, _, _, _, _] = sumo:find_by(Name, [], 1000, 1),
[] = sumo:find_by(Name, [], 1, 1000),
This test is # 177 github issue related
[_, _, _, _, _, _, _, _] = sumo:find_by(Name, []),
Robot = sumo:find_by(Name, [{name, <<"Model T-2000">>}]),
[_] = Robot,
ok.
-spec delete_all(config()) -> ok.
delete_all(Config) ->
{_, Name} = lists:keyfind(name, 1, Config),
sumo:delete_all(Name),
{EventId, Name, pre_delete_all, []} = pick_up_event(),
{EventId, Name, deleted_all, []} = pick_up_event(),
[] = sumo:find_all(Name),
ok.
-spec delete(config()) -> ok.
delete(Config) ->
{_, Name} = lists:keyfind(name, 1, Config),
Module = sumo_config:get_prop_value(Name, module),
delete_by
Conditions = [{last_name, <<"D">>}],
2 = sumo:delete_by(Name, Conditions),
{EventId, Name, pre_deleted_total, [Conditions]} = pick_up_event(),
{EventId, Name, deleted_total, [2, Conditions]} = pick_up_event(),
Results = sumo:find_by(Name, Conditions),
[] = Results,
%% delete
[First | _ ] = All = sumo:find_all(Name),
Id = Module:id(First),
sumo:delete(Name, Id),
% sumo:delete/2 uses internally sumo:delete_by/2, we handle those events too
IdField = sumo_internal:id_field_name(Name),
{EventId2, Name, pre_deleted, [Id]} = pick_up_event(),
{EventId4, Name, pre_deleted_total, [[{IdField, Id}]]} = pick_up_event(),
{EventId4, Name, deleted_total, [1, [{IdField, Id}]]} = pick_up_event(),
{EventId2, Name, deleted, [Id]} = pick_up_event(),
NewAll = sumo:find_all(Name),
[_] = All -- NewAll,
ok.
-spec check_proper_dates(config()) -> ok.
check_proper_dates(Config) ->
{_, Name} = lists:keyfind(name, 1, Config),
Module = sumo_config:get_prop_value(Name, module),
[P0] = sumo:find_by(Name, [{name, <<"A">>}]),
P1 = sumo:fetch(Name, Module:id(P0)),
[P2 | _] = sumo:find_all(Name),
{Date, _} = calendar:universal_time(),
Date = Module:birthdate(P0),
{Date, {_, _, _}} = Module:created_at(P0),
Date = Module:birthdate(P1),
{Date, {_, _, _}} = Module:created_at(P1),
Date = Module:birthdate(P2),
{Date, {_, _, _}} = Module:created_at(P2),
Person = create(Name, Module:new(<<"X">>, <<"Z">>, 6)),
Date = Module:birthdate(Person),
ok.
-spec count(config()) -> ok.
count(Config) ->
{_, Name} = lists:keyfind(name, 1, Config),
8 = length(sumo:find_all(Name)),
8 = sumo:count(Name),
_ = try sumo:count(wrong)
catch
_:no_workers -> ok
end,
Conditions = [{last_name, <<"D">>}],
2 = sumo:delete_by(Name, Conditions),
6 = sumo:count(Name),
ok.
-spec count_by(config()) -> ok.
count_by(Config) ->
{_, Name} = lists:keyfind(name, 1, Config),
6 = sumo:count_by(Name, [{age, '>', 2}]),
4 = sumo:count_by(Name, [{age, '>', 2}, {age, '=<', 5}]),
2 = sumo:count_by(Name, [{age, '>', 5}]),
0 = sumo:count_by(Name, [{age, '>', 7}]),
8 = sumo:count_by(Name, []),
ok.
-spec persist_using_changeset(config()) -> ok.
persist_using_changeset(Config) ->
{_, Name} = lists:keyfind(name, 1, Config),
Module = sumo_config:get_prop_value(Name, module),
[] = sumo:find_by(Name, [{name, <<"John">>}]),
[P1] = sumo:find_by(Name, [{name, <<"A">>}]),
Schema = Module:sumo_schema(),
Allowed = [sumo_internal:field_name(F) || F <- sumo_internal:schema_fields(Schema)],
CS1 = sumo_changeset:cast(people, P1, #{name => <<"John">>, age => 34}, Allowed),
_ = sumo:persist(CS1),
[P2] = sumo:find_by(Name, [{name, <<"John">>}]),
<<"John">> = Module:name(P2),
34 = Module:age(P2),
CS2 = sumo_changeset:validate_number(CS1, age, [{less_than_or_equal_to, 33}]),
{error, CS2} = sumo:persist(CS2),
ok.
%%%=============================================================================
%%% Helpers
%%%=============================================================================
-spec init_store(atom()) -> ok.
init_store(Name) ->
sumo:create_schema(Name),
Module = sumo_config:get_prop_value(Name, module),
sumo:delete_all(Name),
DT = {Date, _} = calendar:universal_time(),
create(Name, Module:new(<<"A">>, <<"E">>, 6)),
create(Name, Module:from_map(#{
name => <<"B">>,
last_name => <<"D">>,
age => 3,
birthdate => Date,
created_at => DT,
weird_field1 => true
})),
create(Name, Module:new(<<"C">>, <<"C">>, 5)),
create(Name, Module:new(<<"D">>, <<"D">>, 4)),
create(Name, Module:new(<<"E">>, <<"A">>, 2)),
create(Name, Module:new(<<"F">>, <<"E">>, 1)),
create(Name, Module:new(<<"Model T-2000">>, <<"undefined">>, 7)),
create(Name, Module:from_map(#{
name => <<"Name">>,
last_name => <<"LastName">>,
age => 3,
birthdate => Date,
created_at => DT,
height => 1.75,
description => <<"description">>,
profile_image => <<"profile_image">>,
is_blocked => true,
weird_field1 => {mytuple, false, 1, "2", <<"3">>},
weird_field2 => [1, true, <<"hi">>, 1.1],
weird_field3 => #{a => 1, b => [1, "2", <<"3">>], <<"c">> => false}
})),
clean_events(),
ok.
%%%=============================================================================
Internal functions
%%%=============================================================================
pick_up_event() ->
sumo_test_people_events_manager:pick_up_event().
clean_events() ->
sumo_test_people_events_manager:clean_events().
create(Name, Args) ->
clean_events(),
Res = sumo:persist(Name, Args),
{EventId, Name, pre_persisted, [Args]} = pick_up_event(),
{EventId, Name, persisted, [Res]} = pick_up_event(),
Res.
| null |
https://raw.githubusercontent.com/inaka/sumo_db/331ea718c13a01748a7739ad4078b0032f4d32e5/src/adapter_test_helpers/sumo_basic_test_helper.erl
|
erlang
|
Common Test Cases
Shared Helpers
=============================================================================
Test Cases - Helpers
=============================================================================
Check that it returns what we have inserted
Check find_by ID
Check pagination
delete
sumo:delete/2 uses internally sumo:delete_by/2, we handle those events too
=============================================================================
Helpers
=============================================================================
=============================================================================
=============================================================================
|
-module(sumo_basic_test_helper).
-export([
create_schema/1,
find/1,
find_all/1,
find_by/1,
delete_all/1,
delete/1,
check_proper_dates/1,
count/1,
count_by/1,
persist_using_changeset/1
]).
-export([init_store/1]).
-type config() :: [{atom(), term()}].
-spec create_schema(config()) -> ok.
create_schema(Config) ->
ok = sumo:create_schema(),
Tables = mnesia:system_info(tables),
{_, Name} = lists:keyfind(name, 1, Config),
true = lists:member(Name, Tables),
ok.
-spec find(config()) -> ok.
find(Config) ->
{_, Name} = lists:keyfind(name, 1, Config),
Module = sumo_config:get_prop_value(Name, module),
[First, Second | _] = sumo:find_all(Name),
First = sumo:find_one(Name, [{id, Module:id(First)}]),
Second = sumo:fetch(Name, Module:id(Second)),
notfound = sumo:fetch(Name, 0),
notfound = sumo:find_one(Name, [{id, 0}]),
ok.
-spec find_all(config()) -> ok.
find_all(Config) ->
{_, Name} = lists:keyfind(name, 1, Config),
[_, _, _, _, _, _, _, _] = sumo:find_all(Name),
ok.
-spec find_by(config()) -> ok.
find_by(Config) ->
{_, Name} = lists:keyfind(name, 1, Config),
Module = sumo_config:get_prop_value(Name, module),
Results = sumo:find_by(Name, [{last_name, <<"D">>}]),
[_, _] = Results,
SortFun = fun(A, B) -> Module:name(A) < Module:name(B) end,
[First, Second | _] = lists:sort(SortFun, Results),
{Today, _} = calendar:universal_time(),
<<"B">> = Module:name(First),
<<"D">> = Module:name(Second),
3 = Module:age(First),
4 = Module:age(Second),
<<"D">> = Module:last_name(First),
undefined = Module:address(First),
Today = Module:birthdate(First),
undefined = Module:height(First),
undefined = Module:description(First),
{Today, _} = Module:created_at(First),
false = Module:is_blocked(First),
true = Module:weird_field1(First),
undefined = Module:weird_field2(First),
undefined = Module:weird_field3(First),
[LastPerson | _NothingElse] = sumo:find_by(Name, [
{last_name, <<"LastName">>}
]),
<<"Name">> = Module:name(LastPerson),
<<"LastName">> = Module:last_name(LastPerson),
3 = Module:age(LastPerson),
undefined = Module:address(LastPerson),
{Date, _} = calendar:universal_time(),
Date = Module:birthdate(LastPerson),
1.75 = Module:height(LastPerson),
<<"description">> = Module:description(LastPerson),
<<"profile_image">> = Module:profile_image(LastPerson),
true = Module:is_blocked(LastPerson),
{mytuple, false, 1, "2", <<"3">>} = Module:weird_field1(LastPerson),
[1, true, <<"hi">>, 1.1] = Module:weird_field2(LastPerson),
#{a := 1,
b := [1, "2", <<"3">>],
<<"c">> := false
} = Module:weird_field3(LastPerson),
{Today, _} = Module:created_at(LastPerson),
FirstId = Module:id(First),
[First1] = sumo:find_by(Name, [{id, FirstId}]),
[First1] = sumo:find_by(Name, [{last_name, <<"D">>}, {id, FirstId}]),
[] = sumo:find_by(Name, [{name, <<"NotB">>}, {id, FirstId}]),
First1 = First,
Results1 = sumo:find_by(Name, [], 3, 1),
[_, _, _] = Results1,
[_, _, _, _, _, _, _] = sumo:find_by(Name, [], 1000, 1),
[] = sumo:find_by(Name, [], 1, 1000),
This test is # 177 github issue related
[_, _, _, _, _, _, _, _] = sumo:find_by(Name, []),
Robot = sumo:find_by(Name, [{name, <<"Model T-2000">>}]),
[_] = Robot,
ok.
-spec delete_all(config()) -> ok.
delete_all(Config) ->
{_, Name} = lists:keyfind(name, 1, Config),
sumo:delete_all(Name),
{EventId, Name, pre_delete_all, []} = pick_up_event(),
{EventId, Name, deleted_all, []} = pick_up_event(),
[] = sumo:find_all(Name),
ok.
-spec delete(config()) -> ok.
delete(Config) ->
{_, Name} = lists:keyfind(name, 1, Config),
Module = sumo_config:get_prop_value(Name, module),
delete_by
Conditions = [{last_name, <<"D">>}],
2 = sumo:delete_by(Name, Conditions),
{EventId, Name, pre_deleted_total, [Conditions]} = pick_up_event(),
{EventId, Name, deleted_total, [2, Conditions]} = pick_up_event(),
Results = sumo:find_by(Name, Conditions),
[] = Results,
[First | _ ] = All = sumo:find_all(Name),
Id = Module:id(First),
sumo:delete(Name, Id),
IdField = sumo_internal:id_field_name(Name),
{EventId2, Name, pre_deleted, [Id]} = pick_up_event(),
{EventId4, Name, pre_deleted_total, [[{IdField, Id}]]} = pick_up_event(),
{EventId4, Name, deleted_total, [1, [{IdField, Id}]]} = pick_up_event(),
{EventId2, Name, deleted, [Id]} = pick_up_event(),
NewAll = sumo:find_all(Name),
[_] = All -- NewAll,
ok.
-spec check_proper_dates(config()) -> ok.
check_proper_dates(Config) ->
{_, Name} = lists:keyfind(name, 1, Config),
Module = sumo_config:get_prop_value(Name, module),
[P0] = sumo:find_by(Name, [{name, <<"A">>}]),
P1 = sumo:fetch(Name, Module:id(P0)),
[P2 | _] = sumo:find_all(Name),
{Date, _} = calendar:universal_time(),
Date = Module:birthdate(P0),
{Date, {_, _, _}} = Module:created_at(P0),
Date = Module:birthdate(P1),
{Date, {_, _, _}} = Module:created_at(P1),
Date = Module:birthdate(P2),
{Date, {_, _, _}} = Module:created_at(P2),
Person = create(Name, Module:new(<<"X">>, <<"Z">>, 6)),
Date = Module:birthdate(Person),
ok.
-spec count(config()) -> ok.
count(Config) ->
{_, Name} = lists:keyfind(name, 1, Config),
8 = length(sumo:find_all(Name)),
8 = sumo:count(Name),
_ = try sumo:count(wrong)
catch
_:no_workers -> ok
end,
Conditions = [{last_name, <<"D">>}],
2 = sumo:delete_by(Name, Conditions),
6 = sumo:count(Name),
ok.
-spec count_by(config()) -> ok.
count_by(Config) ->
{_, Name} = lists:keyfind(name, 1, Config),
6 = sumo:count_by(Name, [{age, '>', 2}]),
4 = sumo:count_by(Name, [{age, '>', 2}, {age, '=<', 5}]),
2 = sumo:count_by(Name, [{age, '>', 5}]),
0 = sumo:count_by(Name, [{age, '>', 7}]),
8 = sumo:count_by(Name, []),
ok.
-spec persist_using_changeset(config()) -> ok.
persist_using_changeset(Config) ->
{_, Name} = lists:keyfind(name, 1, Config),
Module = sumo_config:get_prop_value(Name, module),
[] = sumo:find_by(Name, [{name, <<"John">>}]),
[P1] = sumo:find_by(Name, [{name, <<"A">>}]),
Schema = Module:sumo_schema(),
Allowed = [sumo_internal:field_name(F) || F <- sumo_internal:schema_fields(Schema)],
CS1 = sumo_changeset:cast(people, P1, #{name => <<"John">>, age => 34}, Allowed),
_ = sumo:persist(CS1),
[P2] = sumo:find_by(Name, [{name, <<"John">>}]),
<<"John">> = Module:name(P2),
34 = Module:age(P2),
CS2 = sumo_changeset:validate_number(CS1, age, [{less_than_or_equal_to, 33}]),
{error, CS2} = sumo:persist(CS2),
ok.
-spec init_store(atom()) -> ok.
init_store(Name) ->
sumo:create_schema(Name),
Module = sumo_config:get_prop_value(Name, module),
sumo:delete_all(Name),
DT = {Date, _} = calendar:universal_time(),
create(Name, Module:new(<<"A">>, <<"E">>, 6)),
create(Name, Module:from_map(#{
name => <<"B">>,
last_name => <<"D">>,
age => 3,
birthdate => Date,
created_at => DT,
weird_field1 => true
})),
create(Name, Module:new(<<"C">>, <<"C">>, 5)),
create(Name, Module:new(<<"D">>, <<"D">>, 4)),
create(Name, Module:new(<<"E">>, <<"A">>, 2)),
create(Name, Module:new(<<"F">>, <<"E">>, 1)),
create(Name, Module:new(<<"Model T-2000">>, <<"undefined">>, 7)),
create(Name, Module:from_map(#{
name => <<"Name">>,
last_name => <<"LastName">>,
age => 3,
birthdate => Date,
created_at => DT,
height => 1.75,
description => <<"description">>,
profile_image => <<"profile_image">>,
is_blocked => true,
weird_field1 => {mytuple, false, 1, "2", <<"3">>},
weird_field2 => [1, true, <<"hi">>, 1.1],
weird_field3 => #{a => 1, b => [1, "2", <<"3">>], <<"c">> => false}
})),
clean_events(),
ok.
Internal functions
pick_up_event() ->
sumo_test_people_events_manager:pick_up_event().
clean_events() ->
sumo_test_people_events_manager:clean_events().
create(Name, Args) ->
clean_events(),
Res = sumo:persist(Name, Args),
{EventId, Name, pre_persisted, [Args]} = pick_up_event(),
{EventId, Name, persisted, [Res]} = pick_up_event(),
Res.
|
c8183c571b30ff567f768c0b273236f4bb6a421b734bacf67bfbc0f1a3192ef6
|
tweag/pirouette
|
FromTerm.hs
|
{-# LANGUAGE ConstraintKinds #-}
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE NamedFieldPuns #
# LANGUAGE PatternSynonyms #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}
{-# HLINT ignore "Replace case with maybe" #-}
| Translation of Pirouette syntactical categories into
-- smtlib through our copy of the PureSMT library.
module Pirouette.SMT.FromTerm where
import Control.Monad.Except
import Control.Monad.Writer (Any (..), WriterT (..), mapWriterT, tell)
import qualified Data.Set as S
-- import Debug.Trace (trace)
import Pirouette.Monad
import Pirouette.SMT.Base
import Pirouette.Term.Syntax
import qualified Pirouette.Term.Syntax.SystemF as Raw
import qualified PureSMT
-- useful during debugging
traceMe :: String -> a -> a
traceMe _ = id
-- traceMe = trace
-- | Synonym which takes into account whether
-- the translation used any uninterpreted functions.
type UsedAnyUFs = Any
pattern UsedSomeUFs, NotUsedAnyUFs :: UsedAnyUFs
pattern UsedSomeUFs = Any True
pattern NotUsedAnyUFs = Any False
{-# COMPLETE UsedSomeUFs, NotUsedAnyUFs #-}
-- | Monad stack used for translation.
type TranslatorT m = WriterT UsedAnyUFs (ExceptT String m)
runTranslator :: TranslatorT m a -> m (Either String (a, UsedAnyUFs))
runTranslator = runExceptT . runWriterT
pattern TranslatorT :: m (Either e (a, w)) -> WriterT w (ExceptT e m) a
pattern TranslatorT x = WriterT (ExceptT x)
-- * Translating Terms and Types to SMTLIB
translateTypeBase ::
forall lang m.
(LanguageSMT lang, Monad m) =>
TypeBase lang ->
m PureSMT.SExpr
translateTypeBase (TyBuiltin pirType) = return $ translateBuiltinType @lang pirType
translateTypeBase (TySig name) = return $ PureSMT.symbol (toSmtName name)
translateType ::
(LanguageSMT lang, ToSMT meta, Monad m) =>
TypeMeta lang meta ->
TranslatorT m PureSMT.SExpr
translateType (Raw.TyApp (Raw.Free ty) args) =
PureSMT.app <$> translateTypeBase ty <*> mapM translateType args
translateType (Raw.TyApp (Raw.Bound (Raw.Ann ann) _index) args) =
PureSMT.app (PureSMT.symbol (toSmtName ann)) <$> mapM translateType args
translateType x =
throwError $ "Translate type to smtlib: cannot handle " <> show x
-- TODO: The translation of term is still to be worked on,
-- since it does not allow to use lang or defined functions,
-- and it contains application of term to types,
A frequent situation in system F , but not allowed in the logic of SMT solvers .
translateTerm ::
forall lang meta m.
(LanguageSMT lang, ToSMT meta, PirouetteReadDefs lang m) =>
S.Set Name ->
TermMeta lang meta ->
TranslatorT m PureSMT.SExpr
translateTerm _ (Raw.Lam _ann _ty _term) =
throwError "Translate term to smtlib: Lambda abstraction in term"
translateTerm _ (Raw.Abs _ann _kind _term) =
throwError "Translate term to smtlib: Type abstraction in term"
translateTerm knownNames (Raw.App var args) = case var of
-- error cases
Raw.Bound (Raw.Ann _name) _ ->
throwError "translateApp: Bound variable; did you forget to apply something?"
Raw.Free Bottom ->
throwError "translateApp: Bottom; unclear how to translate that. WIP"
-- meta go to ToSMT
Raw.Meta h -> PureSMT.app (translate h) <$> mapM (translateArg knownNames) args
-- constants and builtins go to LanguageSMT
Raw.Free (Constant c) ->
if null args
then return $ translateConstant @lang c
else throwError "translateApp: Constant applied to arguments"
Raw.Free (Builtin b) -> do
translatedArgs <- mapM (translateArg knownNames) args
case translateBuiltinTerm @lang b translatedArgs of
Nothing -> throwError "translateApp: Built-in term applied to wrong # of args"
Just t -> return t
Raw.Free (TermSig name) -> do
_ <- traceMe ("translateApp: " ++ show name) (return ())
defn <- lift $ lift $ prtDefOf TermNamespace name
case defn of
DConstructor ix tname
| name `S.notMember` knownNames ->
throwError $ "translateApp: Unknown constructor '" <> show name <> "'"
| otherwise -> do
-- bring in the type information
Datatype {constructors} <- lift $ lift $ prtTypeDefOf tname
-- we assume that if everything is well-typed
-- the constructor actually exists, hence the use of (!!)
let cstrTy = snd (constructors !! ix)
-- now we split the arguments as required for the constructor
(tyArgs, restArgs) = splitAt (Raw.tyPolyArity cstrTy) args
-- and instantiate the type
instTy = Raw.tyInstantiateN (typeToMeta cstrTy) (map (\(Raw.TyArg ty) -> ty) tyArgs)
(argTys, resultTy) = Raw.tyFunArgs instTy
-- there must be exactly as many arguments as required
guard (length argTys == length restArgs)
-- finally build the term
PureSMT.app
<$> (PureSMT.as (PureSMT.symbol (toSmtName name)) <$> translateType resultTy)
<*> mapM (translateArg knownNames) restArgs
PureSMT.app ( PureSMT.symbol ( toSmtName name ) ) < $ > mapM ( translateArg knownNames ) restArgs
DFunDef _
| name `S.notMember` knownNames ->
throwError $ "translateApp: Unknown function '" <> show name <> "'"
| otherwise -> do
tell UsedSomeUFs
PureSMT.app (PureSMT.symbol (toSmtName name)) <$> mapM (translateArg knownNames) args
DTypeDef _ ->
throwError "translateApp: Type name in function name"
-- DO NEVER TRY TO TRANSLATE THESE!!
even though SMT contains a match primitive ,
-- this should be taken care of at the level
-- or symbolic evaluation instead
DDestructor _ ->
throwError $ "translateApp: Cannot handle '" <> show name <> "' yet"
translateArg ::
(LanguageSMT lang, ToSMT meta, PirouetteReadDefs lang m) =>
S.Set Name ->
ArgMeta lang meta ->
TranslatorT m PureSMT.SExpr
translateArg knownNames (Raw.TermArg term) = translateTerm knownNames term
TODO : This case is known to create invalid SMT terms ,
since in SMT solver , application of a term to a type is not allowed .
translateArg _ (Raw.TyArg ty) = translateType ty
| The definition of constructors in SMTlib follows a fixed layout . This
-- function translates constructor types in PlutusIR to this layout and
-- provides required names for the fields of product types.
constructorFromPIR ::
forall builtins meta typeVariable m.
(LanguageSMT builtins, ToSMT meta, Monad m) =>
[typeVariable] ->
(Name, TypeMeta builtins meta) ->
TranslatorT m (String, [(String, PureSMT.SExpr)])
constructorFromPIR tyVars (name, constructorType) = handleError $ do
Fields of product types must be named : we append ids to the constructor name
let fieldNames = map (((toSmtName name ++ "_") ++) . show) [1 :: Int ..]
(_, unwrapped) = Raw.tyUnwrapBinders (length tyVars) constructorType
(args, _) = Raw.tyFunArgs unwrapped
cstrs <- zip fieldNames <$> mapM translateType args
return (toSmtName name, cstrs)
where
handleError :: TranslatorT m a -> TranslatorT m a
handleError = mapWriterT (withExceptT (("At " ++ show name ++ ":") ++))
| null |
https://raw.githubusercontent.com/tweag/pirouette/ae4562c83dbfa2b2426166d11a218f9742ac9874/src/Pirouette/SMT/FromTerm.hs
|
haskell
|
# LANGUAGE ConstraintKinds #
# OPTIONS_GHC -Wno-unrecognised-pragmas #
# HLINT ignore "Replace case with maybe" #
smtlib through our copy of the PureSMT library.
import Debug.Trace (trace)
useful during debugging
traceMe = trace
| Synonym which takes into account whether
the translation used any uninterpreted functions.
# COMPLETE UsedSomeUFs, NotUsedAnyUFs #
| Monad stack used for translation.
* Translating Terms and Types to SMTLIB
TODO: The translation of term is still to be worked on,
since it does not allow to use lang or defined functions,
and it contains application of term to types,
error cases
meta go to ToSMT
constants and builtins go to LanguageSMT
bring in the type information
we assume that if everything is well-typed
the constructor actually exists, hence the use of (!!)
now we split the arguments as required for the constructor
and instantiate the type
there must be exactly as many arguments as required
finally build the term
DO NEVER TRY TO TRANSLATE THESE!!
this should be taken care of at the level
or symbolic evaluation instead
function translates constructor types in PlutusIR to this layout and
provides required names for the fields of product types.
|
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE NamedFieldPuns #
# LANGUAGE PatternSynonyms #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
| Translation of Pirouette syntactical categories into
module Pirouette.SMT.FromTerm where
import Control.Monad.Except
import Control.Monad.Writer (Any (..), WriterT (..), mapWriterT, tell)
import qualified Data.Set as S
import Pirouette.Monad
import Pirouette.SMT.Base
import Pirouette.Term.Syntax
import qualified Pirouette.Term.Syntax.SystemF as Raw
import qualified PureSMT
traceMe :: String -> a -> a
traceMe _ = id
type UsedAnyUFs = Any
pattern UsedSomeUFs, NotUsedAnyUFs :: UsedAnyUFs
pattern UsedSomeUFs = Any True
pattern NotUsedAnyUFs = Any False
type TranslatorT m = WriterT UsedAnyUFs (ExceptT String m)
runTranslator :: TranslatorT m a -> m (Either String (a, UsedAnyUFs))
runTranslator = runExceptT . runWriterT
pattern TranslatorT :: m (Either e (a, w)) -> WriterT w (ExceptT e m) a
pattern TranslatorT x = WriterT (ExceptT x)
translateTypeBase ::
forall lang m.
(LanguageSMT lang, Monad m) =>
TypeBase lang ->
m PureSMT.SExpr
translateTypeBase (TyBuiltin pirType) = return $ translateBuiltinType @lang pirType
translateTypeBase (TySig name) = return $ PureSMT.symbol (toSmtName name)
translateType ::
(LanguageSMT lang, ToSMT meta, Monad m) =>
TypeMeta lang meta ->
TranslatorT m PureSMT.SExpr
translateType (Raw.TyApp (Raw.Free ty) args) =
PureSMT.app <$> translateTypeBase ty <*> mapM translateType args
translateType (Raw.TyApp (Raw.Bound (Raw.Ann ann) _index) args) =
PureSMT.app (PureSMT.symbol (toSmtName ann)) <$> mapM translateType args
translateType x =
throwError $ "Translate type to smtlib: cannot handle " <> show x
A frequent situation in system F , but not allowed in the logic of SMT solvers .
translateTerm ::
forall lang meta m.
(LanguageSMT lang, ToSMT meta, PirouetteReadDefs lang m) =>
S.Set Name ->
TermMeta lang meta ->
TranslatorT m PureSMT.SExpr
translateTerm _ (Raw.Lam _ann _ty _term) =
throwError "Translate term to smtlib: Lambda abstraction in term"
translateTerm _ (Raw.Abs _ann _kind _term) =
throwError "Translate term to smtlib: Type abstraction in term"
translateTerm knownNames (Raw.App var args) = case var of
Raw.Bound (Raw.Ann _name) _ ->
throwError "translateApp: Bound variable; did you forget to apply something?"
Raw.Free Bottom ->
throwError "translateApp: Bottom; unclear how to translate that. WIP"
Raw.Meta h -> PureSMT.app (translate h) <$> mapM (translateArg knownNames) args
Raw.Free (Constant c) ->
if null args
then return $ translateConstant @lang c
else throwError "translateApp: Constant applied to arguments"
Raw.Free (Builtin b) -> do
translatedArgs <- mapM (translateArg knownNames) args
case translateBuiltinTerm @lang b translatedArgs of
Nothing -> throwError "translateApp: Built-in term applied to wrong # of args"
Just t -> return t
Raw.Free (TermSig name) -> do
_ <- traceMe ("translateApp: " ++ show name) (return ())
defn <- lift $ lift $ prtDefOf TermNamespace name
case defn of
DConstructor ix tname
| name `S.notMember` knownNames ->
throwError $ "translateApp: Unknown constructor '" <> show name <> "'"
| otherwise -> do
Datatype {constructors} <- lift $ lift $ prtTypeDefOf tname
let cstrTy = snd (constructors !! ix)
(tyArgs, restArgs) = splitAt (Raw.tyPolyArity cstrTy) args
instTy = Raw.tyInstantiateN (typeToMeta cstrTy) (map (\(Raw.TyArg ty) -> ty) tyArgs)
(argTys, resultTy) = Raw.tyFunArgs instTy
guard (length argTys == length restArgs)
PureSMT.app
<$> (PureSMT.as (PureSMT.symbol (toSmtName name)) <$> translateType resultTy)
<*> mapM (translateArg knownNames) restArgs
PureSMT.app ( PureSMT.symbol ( toSmtName name ) ) < $ > mapM ( translateArg knownNames ) restArgs
DFunDef _
| name `S.notMember` knownNames ->
throwError $ "translateApp: Unknown function '" <> show name <> "'"
| otherwise -> do
tell UsedSomeUFs
PureSMT.app (PureSMT.symbol (toSmtName name)) <$> mapM (translateArg knownNames) args
DTypeDef _ ->
throwError "translateApp: Type name in function name"
even though SMT contains a match primitive ,
DDestructor _ ->
throwError $ "translateApp: Cannot handle '" <> show name <> "' yet"
translateArg ::
(LanguageSMT lang, ToSMT meta, PirouetteReadDefs lang m) =>
S.Set Name ->
ArgMeta lang meta ->
TranslatorT m PureSMT.SExpr
translateArg knownNames (Raw.TermArg term) = translateTerm knownNames term
TODO : This case is known to create invalid SMT terms ,
since in SMT solver , application of a term to a type is not allowed .
translateArg _ (Raw.TyArg ty) = translateType ty
| The definition of constructors in SMTlib follows a fixed layout . This
constructorFromPIR ::
forall builtins meta typeVariable m.
(LanguageSMT builtins, ToSMT meta, Monad m) =>
[typeVariable] ->
(Name, TypeMeta builtins meta) ->
TranslatorT m (String, [(String, PureSMT.SExpr)])
constructorFromPIR tyVars (name, constructorType) = handleError $ do
Fields of product types must be named : we append ids to the constructor name
let fieldNames = map (((toSmtName name ++ "_") ++) . show) [1 :: Int ..]
(_, unwrapped) = Raw.tyUnwrapBinders (length tyVars) constructorType
(args, _) = Raw.tyFunArgs unwrapped
cstrs <- zip fieldNames <$> mapM translateType args
return (toSmtName name, cstrs)
where
handleError :: TranslatorT m a -> TranslatorT m a
handleError = mapWriterT (withExceptT (("At " ++ show name ++ ":") ++))
|
c8416e90a7e8b0f94d9f3368bd3b0a25e92008d6b0bf27a94f03af0020ddd2e8
|
RyanGlScott/eliminators
|
TH.hs
|
# LANGUAGE CPP #
# LANGUAGE DataKinds #
{-# LANGUAGE TemplateHaskellQuotes #-}
# LANGUAGE Unsafe #
|
Module : Data . Eliminator . TH
Copyright : ( C ) 2017
License : BSD - style ( see the file LICENSE )
Maintainer :
Stability : Experimental
Portability : GHC
Generate dependently typed elimination functions using Template Haskell .
Module: Data.Eliminator.TH
Copyright: (C) 2017 Ryan Scott
License: BSD-style (see the file LICENSE)
Maintainer: Ryan Scott
Stability: Experimental
Portability: GHC
Generate dependently typed elimination functions using Template Haskell.
-}
module Data.Eliminator.TH (
-- * Eliminator generation
-- ** Term-level eliminators
-- $term-conventions
deriveElim
, deriveElimNamed
-- ** Type-level eliminators
-- $type-conventions
, deriveTypeElim
, deriveTypeElimNamed
) where
import Control.Applicative
import Control.Monad
import Data.Char (isLetter, isUpper, toUpper)
import Data.Foldable
import qualified Data.Kind as Kind (Type)
import Data.Maybe
import Data.Proxy
import Data.Singletons.TH.Options
import Language.Haskell.TH
import Language.Haskell.TH.Datatype as Datatype
import Language.Haskell.TH.Datatype.TyVarBndr
import Language.Haskell.TH.Desugar hiding (NewOrData(..))
import Prelude.Singletons
$ term - conventions
' deriveElim ' and ' deriveElimNamed ' provide a way to automate the creation of
eliminator functions , which are mostly boilerplate . Here is a complete example
showing how one might use ' deriveElim ' :
@
$ ( ' singletons ' [ d| data MyList a = MyNil | MyCons a ( MyList a ) | ] )
$ ( ' deriveElim ' ' ' MyList )
@
This will produce an eliminator function that looks roughly like the following :
@
elimMyList : : forall ( a : : ' Type ' ) ( p : : MyList a ' ~ > ' ' Type ' ) ( l : : MyList a ) .
' Sing ' l
- > ' Apply '
- > ( forall ( x : : a ) . ' Sing ' x
- > forall ( xs : : MyList a ) . ' Sing ' xs - > ' Apply ' p xs
- > ' Apply ' p ( MyCons x xs ) )
- > ' Apply ' p l
elimMyList SMyNil pMyNil _ = pMyNil
elimMyList ( SMyCons ( x ' : : ' Sing ' x ) ( xs ' : : ' Sing ' xs ) ) pMyNil pMyCons
= pMyCons x ' xs ' ( elimMyList \@a \@xs pMyNil pMyCons )
@
There are some important things to note here :
* Because these eliminators use ' Sing ' under the hood , in order for
' deriveElim ' to work , the ' Sing ' instance for the data type given as an
argument must be in scope . Moreover , ' deriveElim ' assumes the naming
conventions for singled constructors used by the @singletons@ library .
( This is why the ' singletons ' function is used in the example above ) .
* There is a convention for the order in which the arguments appear .
The quantified type variables appear in this order :
1 . First , the type variables of the data type itself ( @a@ , in the above example ) .
2 . Second , a predicate type variable of kind @\<Datatype\ > ' ~ > ' ' Type'@
( @p@ , in the above example ) .
3 . Finally , a type variable of kind @\<Datatype\>@ ( @l@ , in the above example ) .
The function arguments appear in this order :
1 . First , a ' Sing ' argument ( @'Sing ' l@ , in the above example ) .
2 . Next , there are arguments that correspond to each constructor . More on this
in a second .
The return type is the predicate type variable applied to the data type
( @'Apply ' p ( MyCons x xs)@ , the above example ) .
The type of each constructor argument also follows certain conventions :
1 . For each field , there will be a rank-2 type variable whose kind matches
the type of the field , followed by a matching ' Sing ' type . For instance ,
in the above example , @forall ( x : : a ) . ' Sing ' corresponds to the
first field of @MyCons@.
2 . In addition , if the field is a recursive occurrence of the data type ,
an additional argument will follow the ' Sing ' type . This is best
explained using the above example . In the @MyCons@ constructor , the second
field ( of type @MyCons a@ ) is a recursive occurrence of @MyCons@ , so
that corresponds to the type
@forall ( xs : : MyList a ) . ' Sing ' xs - > ' Apply ' , where @'Apply '
is only present due to the recursion .
3 . Finally , the return type will be the predicate type variable applied
to a saturated occurrence of the data constructor
( @'Apply ' p ( MyCons x xs)@ , in the above example ) .
* You 'll need to enable lots of GHC extensions in order for the code generated
by ' deriveElim ' to . You 'll need at least the following :
* @AllowAmbiguousTypes@
* @DataKinds@
* @GADTs@
* @PolyKinds@
* @RankNTypes@
* @ScopedTypeVariables@
* @TemplateHaskell@
* @TypeApplications@
* ' deriveElim ' does n't support every possible data type at the moment .
It is known not to work for the following :
* Data types defined using @GADTs@ or @ExistentialQuantification@
* Data family instances
* Data types which use polymorphic recursion
( e.g. , @data Foo a = Foo ( Foo a)@ )
'deriveElim' and 'deriveElimNamed' provide a way to automate the creation of
eliminator functions, which are mostly boilerplate. Here is a complete example
showing how one might use 'deriveElim':
@
$('singletons' [d| data MyList a = MyNil | MyCons a (MyList a) |])
$('deriveElim' ''MyList)
@
This will produce an eliminator function that looks roughly like the following:
@
elimMyList :: forall (a :: 'Type') (p :: MyList a '~>' 'Type') (l :: MyList a).
'Sing' l
-> 'Apply' p MyNil
-> (forall (x :: a). 'Sing' x
-> forall (xs :: MyList a). 'Sing' xs -> 'Apply' p xs
-> 'Apply' p (MyCons x xs))
-> 'Apply' p l
elimMyList SMyNil pMyNil _ = pMyNil
elimMyList (SMyCons (x' :: 'Sing' x) (xs' :: 'Sing' xs)) pMyNil pMyCons
= pMyCons x' xs' (elimMyList \@a \@p \@xs pMyNil pMyCons)
@
There are some important things to note here:
* Because these eliminators use 'Sing' under the hood, in order for
'deriveElim' to work, the 'Sing' instance for the data type given as an
argument must be in scope. Moreover, 'deriveElim' assumes the naming
conventions for singled constructors used by the @singletons@ library.
(This is why the 'singletons' function is used in the example above).
* There is a convention for the order in which the arguments appear.
The quantified type variables appear in this order:
1. First, the type variables of the data type itself (@a@, in the above example).
2. Second, a predicate type variable of kind @\<Datatype\> '~>' 'Type'@
(@p@, in the above example).
3. Finally, a type variable of kind @\<Datatype\>@ (@l@, in the above example).
The function arguments appear in this order:
1. First, a 'Sing' argument (@'Sing' l@, in the above example).
2. Next, there are arguments that correspond to each constructor. More on this
in a second.
The return type is the predicate type variable applied to the data type
(@'Apply' p (MyCons x xs)@, the above example).
The type of each constructor argument also follows certain conventions:
1. For each field, there will be a rank-2 type variable whose kind matches
the type of the field, followed by a matching 'Sing' type. For instance,
in the above example, @forall (x :: a). 'Sing' x@ corresponds to the
first field of @MyCons@.
2. In addition, if the field is a recursive occurrence of the data type,
an additional argument will follow the 'Sing' type. This is best
explained using the above example. In the @MyCons@ constructor, the second
field (of type @MyCons a@) is a recursive occurrence of @MyCons@, so
that corresponds to the type
@forall (xs :: MyList a). 'Sing' xs -> 'Apply' p xs@, where @'Apply' p xs@
is only present due to the recursion.
3. Finally, the return type will be the predicate type variable applied
to a saturated occurrence of the data constructor
(@'Apply' p (MyCons x xs)@, in the above example).
* You'll need to enable lots of GHC extensions in order for the code generated
by 'deriveElim' to typecheck. You'll need at least the following:
* @AllowAmbiguousTypes@
* @DataKinds@
* @GADTs@
* @PolyKinds@
* @RankNTypes@
* @ScopedTypeVariables@
* @TemplateHaskell@
* @TypeApplications@
* 'deriveElim' doesn't support every possible data type at the moment.
It is known not to work for the following:
* Data types defined using @GADTs@ or @ExistentialQuantification@
* Data family instances
* Data types which use polymorphic recursion
(e.g., @data Foo a = Foo (Foo a)@)
-}
-- | @'deriveElim' dataName@ generates a top-level elimination function for the
-- datatype @dataName@. The eliminator will follow these naming conventions:
--
-- * If the datatype has an alphanumeric name, its eliminator will have that name
-- with @elim@ prepended.
--
-- * If the datatype has a symbolic name, its eliminator will have that name
-- with @~>@ prepended.
deriveElim :: Name -> Q [Dec]
deriveElim dataName = deriveElimNamed (eliminatorName dataName) dataName
-- | @'deriveElimNamed' funName dataName@ generates a top-level elimination
-- function named @funName@ for the datatype @dataName@.
deriveElimNamed :: String -> Name -> Q [Dec]
deriveElimNamed = deriveElimNamed' (Proxy @IsTerm)
$ type - conventions
' deriveTypeElim ' and ' deriveTypeElimNamed ' are like ' deriveElim ' and
' deriveElimNamed ' except that they create /type/-level eliminators instead of
term - level ones . Here is an example showing how one might use
' deriveTypeElim ' :
@
data MyList a = MyNil | MyCons a ( MyList a )
$ ( ' deriveTypeElim ' ' ' MyList )
@
This will produce an eliminator function that looks roughly like the following :
@
type ElimMyList : : forall ( a : : ' Type ' ) .
forall ( p : : MyList a ' ~ > ' ' Type ' ) ( l : : MyList a )
- > ' Apply ' p MyNil
- > ( forall ( x : : a ) ( xs : : MyList a )
- > ' Apply ' p xs ' ~ > ' ' Apply ' p ( MyCons x xs ) )
- > ' Apply ' p l
type family ElimMyList p l pMyNil pMyCons where
forall ( a : : ' Type ' )
( p : : MyList a ~ > ' Type ' )
( pMyNil : : ' Apply ' )
( pMyCons : : forall ( x : : a ) ( xs : : MyList a )
- > ' Apply ' p xs ' ~ > ' ' Apply ' p ( MyCons x xs ) ) .
ElimMyList @a p MyNil pMyNil pMyCons =
pMyNil
forall ( a : : ' Type ' )
( p : : MyList a ~ > ' Type ' )
( _ pMyNil : : ' Apply ' )
( pMyCons : : forall ( x : : a ) ( xs : : MyList a )
- > ' Apply ' p xs ' ~ > ' ' Apply ' p ( MyCons x xs ) )
x ' xs ' .
ElimMyList @a p ( MyCons x ' xs ' ) pMyNil pMyCons =
' Apply ' ( pMyCons x ' xs ' ) ( ElimMyList @a p xs ' pMyNil pMyCons )
@
Note the following differences from a term - level eliminator that ' deriveElim '
would generate :
* Type - level eliminators do not use ' Sing ' . Instead , they use visible dependent
quantification . That is , instead of generating
@forall ( x : : a ) . Sing x - > ... @ ( as a term - level eliminator would do ) , a
type - level eliminator would use @forall ( x : : a ) - > ... @.
* Term - level eliminators quantify @p@ with an invisible @forall@ , whereas
type - level eliminators quantify @p@ with a visible @forall@. ( Really , ought to be quantified visibly in both forms of eliminator , but GHC does not
yet support visible dependent quantification at the term level . )
* Type - level eliminators use ( ' ~ > ' ) in certain places where ( @->@ ) would appear
in term - level eliminators . For instance , note the use of
@'Apply ' p xs ' ~ > ' ' Apply ' p ( MyCons x xs)@ in @ElimMyList@ above . This is
done to make it easier to use type - level eliminators with defunctionalization
symbols ( which are n't necessary for term - level eliminators ) .
This comes with a notable drawback : type - level eliminators can not support
data constructors where recursive occurrences of the data type appear in a
position other than the last field of a constructor . In other words ,
' deriveTypeElim ' works on the @MyList@ example above , but not this variant :
@
data SnocList a = SnocNil | SnocCons ( SnocList a ) a
@
This is because @$('deriveTypeElim ' ' ' SnocList)@ would generate an eliminator
with the following kind :
@
type ElimSnocList : : forall ( a : : ' Type ' ) .
forall ( p : : SnocList a ' ~ > ' ' Type ' ) ( l : : SnocList a )
- > ' Apply '
- > ( forall ( xs : : SnocList a ) - > ' Apply ' p xs
' ~ > ' ( forall ( x : : a ) - > ' Apply ' p ( SnocCons x xs ) ) )
- > ' Apply ' p l
@
Unfortunately , the kind
@'Apply ' p xs ' ~ > ' ( forall ( x : : a ) - > ' Apply ' p ( SnocCons x xs))@ is
impredicative .
* In addition to the language extensions that ' deriveElim ' requires , you 'll need
to enable these extensions in order to use ' deriveTypeElim ' :
* @StandaloneKindSignatures@
* @UndecidableInstances@
'deriveTypeElim' and 'deriveTypeElimNamed' are like 'deriveElim' and
'deriveElimNamed' except that they create /type/-level eliminators instead of
term-level ones. Here is an example showing how one might use
'deriveTypeElim':
@
data MyList a = MyNil | MyCons a (MyList a)
$('deriveTypeElim' ''MyList)
@
This will produce an eliminator function that looks roughly like the following:
@
type ElimMyList :: forall (a :: 'Type').
forall (p :: MyList a '~>' 'Type') (l :: MyList a)
-> 'Apply' p MyNil
-> (forall (x :: a) (xs :: MyList a)
-> 'Apply' p xs '~>' 'Apply' p (MyCons x xs))
-> 'Apply' p l
type family ElimMyList p l pMyNil pMyCons where
forall (a :: 'Type')
(p :: MyList a ~> 'Type')
(pMyNil :: 'Apply' p MyNil)
(pMyCons :: forall (x :: a) (xs :: MyList a)
-> 'Apply' p xs '~>' 'Apply' p (MyCons x xs)).
ElimMyList @a p MyNil pMyNil pMyCons =
pMyNil
forall (a :: 'Type')
(p :: MyList a ~> 'Type')
(_pMyNil :: 'Apply' p MyNil)
(pMyCons :: forall (x :: a) (xs :: MyList a)
-> 'Apply' p xs '~>' 'Apply' p (MyCons x xs))
x' xs'.
ElimMyList @a p (MyCons x' xs') pMyNil pMyCons =
'Apply' (pMyCons x' xs') (ElimMyList @a p xs' pMyNil pMyCons)
@
Note the following differences from a term-level eliminator that 'deriveElim'
would generate:
* Type-level eliminators do not use 'Sing'. Instead, they use visible dependent
quantification. That is, instead of generating
@forall (x :: a). Sing x -> ...@ (as a term-level eliminator would do), a
type-level eliminator would use @forall (x :: a) -> ...@.
* Term-level eliminators quantify @p@ with an invisible @forall@, whereas
type-level eliminators quantify @p@ with a visible @forall@. (Really, @p@
ought to be quantified visibly in both forms of eliminator, but GHC does not
yet support visible dependent quantification at the term level.)
* Type-level eliminators use ('~>') in certain places where (@->@) would appear
in term-level eliminators. For instance, note the use of
@'Apply' p xs '~>' 'Apply' p (MyCons x xs)@ in @ElimMyList@ above. This is
done to make it easier to use type-level eliminators with defunctionalization
symbols (which aren't necessary for term-level eliminators).
This comes with a notable drawback: type-level eliminators cannot support
data constructors where recursive occurrences of the data type appear in a
position other than the last field of a constructor. In other words,
'deriveTypeElim' works on the @MyList@ example above, but not this variant:
@
data SnocList a = SnocNil | SnocCons (SnocList a) a
@
This is because @$('deriveTypeElim' ''SnocList)@ would generate an eliminator
with the following kind:
@
type ElimSnocList :: forall (a :: 'Type').
forall (p :: SnocList a '~>' 'Type') (l :: SnocList a)
-> 'Apply' p SnocNil
-> (forall (xs :: SnocList a) -> 'Apply' p xs
'~>' (forall (x :: a) -> 'Apply' p (SnocCons x xs)))
-> 'Apply' p l
@
Unfortunately, the kind
@'Apply' p xs '~>' (forall (x :: a) -> 'Apply' p (SnocCons x xs))@ is
impredicative.
* In addition to the language extensions that 'deriveElim' requires, you'll need
to enable these extensions in order to use 'deriveTypeElim':
* @StandaloneKindSignatures@
* @UndecidableInstances@
-}
-- | @'deriveTypeElim' dataName@ generates a type-level eliminator for the
-- datatype @dataName@. The eliminator will follow these naming conventions:
--
-- * If the datatype has an alphanumeric name, its eliminator will have that name
-- with @Elim@ prepended.
--
-- * If the datatype has a symbolic name, its eliminator will have that name
-- with @~>@ prepended.
deriveTypeElim :: Name -> Q [Dec]
deriveTypeElim dataName = deriveTypeElimNamed (upcase (eliminatorName dataName)) dataName
-- | @'deriveTypeElimNamed' funName dataName@ generates a type-level eliminator
-- named @funName@ for the datatype @dataName@.
deriveTypeElimNamed :: String -> Name -> Q [Dec]
deriveTypeElimNamed = deriveElimNamed' (Proxy @IsType)
-- The workhorse for deriveElim(Named). This generates either a term- or
-- type-level eliminator, depending on which Eliminator instance is used.
deriveElimNamed' ::
Eliminator t
=> proxy t
-> String -- The name of the eliminator function
-> Name -- The name of the data type
-> Q [Dec] -- The eliminator's type signature and body
deriveElimNamed' prox funName dataName = do
info@(DatatypeInfo { datatypeVars = dataVarBndrs
, datatypeInstTypes = instTys
, datatypeVariant = variant
, datatypeCons = cons
}) <- reifyDatatype dataName
let noDataFamilies =
fail "Eliminators for data family instances are currently not supported"
case variant of
DataInstance -> noDataFamilies
NewtypeInstance -> noDataFamilies
Datatype -> pure ()
Newtype -> pure ()
#if MIN_VERSION_th_abstraction(0,5,0)
Datatype.TypeData -> pure ()
#endif
predVar <- newName "p"
singVar <- newName "s"
let elimName = mkName funName
promDataKind = datatypeType info
predVarBndr = kindedTV predVar (InfixT promDataKind ''(~>) (ConT ''Kind.Type))
singVarBndr = kindedTV singVar promDataKind
caseTypes <- traverse (caseType prox dataName predVar) cons
unless (length (findParams info) == length instTys) $
fail "Eliminators for polymorphically recursive data types are currently not supported"
let returnType = predType predVar (VarT singVar)
elimType = elimTypeSig prox dataVarBndrs predVarBndr singVarBndr
caseTypes returnType
elimEqns <- qElimEqns prox (mkName funName) dataName
dataVarBndrs predVarBndr singVarBndr
caseTypes cons
pure [elimSigD prox elimName elimType, elimEqns]
-- Generate the type for a "case alternative" in an eliminator function's type
-- signature, which is done on a constructor-by-constructor basis.
caseType ::
Eliminator t
=> proxy t
-> Name -- The name of the data type
-> Name -- The predicate type variable
-> ConstructorInfo -- The data constructor
-> Q Type -- The full case type
caseType prox dataName predVar
(ConstructorInfo { constructorName = conName
, constructorVars = conVars
, constructorContext = conContext
, constructorFields = fieldTypes })
= do unless (null conVars && null conContext) $
fail $ unlines
[ "Eliminators for GADTs or datatypes with existentially quantified"
, "data constructors currently not supported"
]
vars <- newNameList "f" $ length fieldTypes
let returnType = predType predVar
(foldl' AppT (ConT conName) (map VarT vars))
pure $ foldr' (\(var, varType) t ->
prependElimCaseTypeVar prox dataName predVar var varType t)
returnType
(zip vars fieldTypes)
Generate a single clause for a term - level eliminator 's @go@ function .
goCaseClause ::
The name of the @go@ function
-> Name -- The name of the data type
-> Name -- The name of the "case alternative" to apply on the right-hand side
-> ConstructorInfo -- The data constructor
-> Q Clause -- The generated function clause
goCaseClause goName dataName usedCaseVar
(ConstructorInfo { constructorName = conName
, constructorFields = fieldTypes })
= do let numFields = length fieldTypes
singVars <- newNameList "s" numFields
singVarSigs <- newNameList "sTy" numFields
let singConName = singledDataConName defaultOptions conName
mkSingVarPat var varSig = SigP (VarP var) (singType varSig)
singVarPats = zipWith mkSingVarPat singVars singVarSigs
mbInductiveArg singVar singVarSig varType =
let inductiveArg = VarE goName `AppTypeE` VarT singVarSig
`AppE` VarE singVar
in mbInductiveCase dataName varType $ const inductiveArg
mkArg f (singVar, singVarSig, varType) =
foldAppE f $ VarE singVar
: maybeToList (mbInductiveArg singVar singVarSig varType)
rhs = foldl' mkArg (VarE usedCaseVar) $
zip3 singVars singVarSigs fieldTypes
pure $ Clause [ConP singConName [] singVarPats]
(NormalB rhs)
[]
-- Generate a single equation for a type-level eliminator.
--
-- This code is fairly similar in structure to caseClause, but different
-- enough in subtle ways that I did not attempt to de-duplicate this code as
-- a method of the Eliminator class.
caseTySynEqn ::
Name -- The name of the eliminator function
-> Name -- The name of the data type
-> [TyVarBndrUnit] -- The type variables bound by the data type
-> TyVarBndrUnit -- The predicate type variable
-> Int -- The index of this constructor (0-indexed)
-> [Type] -- The types of each "case alternative" in the eliminator
-- function's type signature
-> ConstructorInfo -- The data constructor
-> Q TySynEqn -- The generated type family equation
caseTySynEqn elimName dataName dataVarBndrs predVarBndr conIndex caseTypes
(ConstructorInfo { constructorName = conName
, constructorFields = fieldTypes })
= do let dataVarNames = map tvName dataVarBndrs
predVarName = tvName predVarBndr
numFields = length fieldTypes
singVars <- newNameList "s" numFields
usedCaseVar <- newName "useThis"
caseVarBndrs <- flip itraverse caseTypes $ \i caseTy ->
let mkVarName
| i == conIndex = pure usedCaseVar
| otherwise = newName ("_p" ++ show i)
in liftA2 kindedTV mkVarName (pure caseTy)
let caseVarNames = map tvName caseVarBndrs
prefix = foldAppKindT (ConT elimName) $ map VarT dataVarNames
mbInductiveArg singVar varType =
let inductiveArg = foldAppT prefix $ VarT predVarName
: VarT singVar
: map VarT caseVarNames
in mbInductiveCase dataName varType $ const inductiveArg
mkArg f (singVar, varType) =
foldAppDefunT (f `AppT` VarT singVar)
$ maybeToList (mbInductiveArg singVar varType)
bndrs = dataVarBndrs ++ predVarBndr : caseVarBndrs ++ map plainTV singVars
lhs = foldAppT prefix $ VarT predVarName
: foldAppT (ConT conName) (map VarT singVars)
: map VarT caseVarNames
rhs = foldl' mkArg (VarT usedCaseVar) $ zip singVars fieldTypes
pure $ TySynEqn (Just bndrs) lhs rhs
-- Are we dealing with a term or a type?
data TermOrType
= IsTerm
| IsType
-- A class that abstracts out certain common operations that one must perform
-- for both term- and type-level eliminators.
class Eliminator (t :: TermOrType) where
-- Create the Dec for an eliminator function's type signature.
elimSigD ::
proxy t
-> Name -- The name of the eliminator function
-> Type -- The type of the eliminator function
The type signature Dec ( SigD or KiSigD )
-- Create an eliminator function's type.
elimTypeSig ::
proxy t
-> [TyVarBndrUnit] -- The type variables bound by the data type
-> TyVarBndrUnit -- The predicate type variable
-> TyVarBndrUnit -- The type variable whose kind is that of the data type itself
-> [Type] -- The types of each "case alternative" in the eliminator
-- function's type signature
-> Type -- The eliminator function's return type
-> Type -- The full type
-- Take a data constructor's field type and prepend it to a "case
-- alternative" in an eliminator function's type signature.
prependElimCaseTypeVar ::
proxy t
-> Name -- The name of the data type
-> Name -- The predicate type variable
-> Name -- A fresh type variable name
-> Kind -- The field type
-> Type -- The rest of the "case alternative" type
-> Type -- The "case alternative" type after prepending
-- Generate the clauses/equations for the body of the eliminator function.
qElimEqns ::
proxy t
-> Name -- The name of the eliminator function
-> Name -- The name of the data type
-> [TyVarBndrUnit] -- The type variables bound by the data type
-> TyVarBndrUnit -- The predicate type variable
-> TyVarBndrUnit -- The type variable whose kind is that of the data type itself
-> [Type] -- The types of each "case alternative" in the eliminator
-- function's type signature
-> [ConstructorInfo] -- The data constructors
-> Q Dec -- The Dec containing the clauses/equations
instance Eliminator IsTerm where
elimSigD _ = SigD
elimTypeSig _ dataVarBndrs predVarBndr singVarBndr caseTypes returnType =
ForallT (changeTVFlags SpecifiedSpec $
dataVarBndrs ++ [predVarBndr, singVarBndr]) [] $
ravel (singType (tvName singVarBndr):caseTypes) returnType
prependElimCaseTypeVar _ dataName predVar var varType t =
ForallT [kindedTVSpecified var varType] [] $
ravel (singType var:maybeToList (mbInductiveType dataName predVar var varType)) t
-- A unique characteristic of term-level eliminators is that we manually
-- apply the static argument transformation, e.g.,
--
-- elimT :: forall a (p :: T a ~> Type) (t :: T a).
-- Sing t
-- -> (forall (x :: a) (xs :: T a).
-- Sing x -> Sing xs -> Apply p xs -> Apply p (MkT x xs))
-- -> Apply p t
elimT st k = go @s k
-- where
-- go :: forall (t' :: T a).
-- Sing t' -> Apply p t'
go ( SMkT ( sx : : Sing x ) ( sxs : : Sing xs ) ) =
( go @xs )
--
This reduces the likelihood of recursive calls falling afoul of GHC 's
-- ambiguity check.
qElimEqns _ elimName dataName _dataVarBndrs predVarBndr singVarBndr _caseTypes cons = do
singTermVar <- newName "s"
caseVars <- newNameList "p" $ length cons
goName <- newName "go"
let singTypeVar = tvName singVarBndr
goSingTypeVar <- newName $ nameBase singTypeVar
let elimRHS = VarE goName `AppTypeE` VarT singTypeVar `AppE` VarE singTermVar
goSingVarBndr = mapTVName (const goSingTypeVar) singVarBndr
goReturnType = predType (tvName predVarBndr) (VarT goSingTypeVar)
goType = ForallT (changeTVFlags SpecifiedSpec [goSingVarBndr]) [] $
ArrowT `AppT` singType goSingTypeVar `AppT` goReturnType
goClauses
<- if null cons
then pure [Clause [VarP singTermVar] (NormalB (CaseE (VarE singTermVar) [])) []]
else zipWithM (goCaseClause goName dataName) caseVars cons
pure $ FunD elimName [ Clause (map VarP (singTermVar:caseVars)) (NormalB elimRHS)
[SigD goName goType, FunD goName goClauses] ]
instance Eliminator IsType where
elimSigD _ = KiSigD
elimTypeSig _ dataVarBndrs predVarBndr singVarBndr caseTypes returnType =
ForallT (changeTVFlags SpecifiedSpec dataVarBndrs) [] $
ForallVisT [predVarBndr, singVarBndr] $
ravel caseTypes returnType
prependElimCaseTypeVar _ dataName predVar var varType t =
ForallVisT [kindedTV var varType] $
ravelDefun (maybeToList (mbInductiveType dataName predVar var varType)) t
qElimEqns _ elimName dataName dataVarBndrs predVarBndr singVarBndr caseTypes cons = do
caseVarBndrs <- replicateM (length caseTypes) (plainTV <$> newName "p")
let predVar = tvName predVarBndr
singVar = tvName singVarBndr
tyFamHead = TypeFamilyHead elimName
(plainTV predVar:plainTV singVar:caseVarBndrs)
NoSig Nothing
caseEqns <- itraverse (\i -> caseTySynEqn elimName dataName
dataVarBndrs predVarBndr i caseTypes) cons
pure $ ClosedTypeFamilyD tyFamHead caseEqns
mbInductiveType :: Name -> Name -> Name -> Kind -> Maybe Type
mbInductiveType dataName predVar var varType =
mbInductiveCase dataName varType $ const $ predType predVar $ VarT var
mbInductiveCase :: Name -> Type -> ([TypeArg] -> a) -> Maybe a
mbInductiveCase dataName varType inductiveArg
= case unfoldType varType of
(headTy, argTys)
-- Annoying special case for lists
| ListT <- headTy
, dataName == ''[]
-> Just $ inductiveArg argTys
| ConT n <- headTy
, dataName == n
-> Just $ inductiveArg argTys
| otherwise
-> Nothing
| Construct a type of the form @'Sing ' given @x@.
singType :: Name -> Type
singType x = ConT ''Sing `AppT` VarT x
| Construct a type of the form @'Apply ' p ty@ given @p@ and @ty@.
predType :: Name -> Type -> Type
predType p ty = ConT ''Apply `AppT` VarT p `AppT` ty
-- | Generate a list of fresh names with a common prefix, and numbered suffixes.
newNameList :: String -> Int -> Q [Name]
newNameList prefix n = ireplicateA n $ newName . (prefix ++) . show
-- Compute an eliminator function's name from the data type name.
eliminatorName :: Name -> String
eliminatorName n
| first:_ <- nStr
, isUpper first
= "elim" ++ nStr
| otherwise
= "~>" ++ nStr
where
nStr = nameBase n
Construct a function type , separating the arguments with - >
ravel :: [Type] -> Type -> Type
ravel args res = go args
where
go [] = res
go (h:t) = AppT (AppT ArrowT h) (go t)
Construct a function type , separating the arguments with ~ >
ravelDefun :: [Type] -> Type -> Type
ravelDefun args res = go args
where
go [] = res
go (h:t) = AppT (AppT (ConT ''(~>)) h) (go t)
-- Apply an expression to a list of expressions using ordinary function applications.
foldAppE :: Exp -> [Exp] -> Exp
foldAppE = foldl' AppE
-- Apply a type to a list of types using ordinary function applications.
foldAppT :: Type -> [Type] -> Type
foldAppT = foldl' AppT
-- Apply a type to a list of types using defunctionalized applications
-- (i.e., using Apply from singletons).
foldAppDefunT :: Type -> [Type] -> Type
foldAppDefunT = foldl' (\x y -> ConT ''Apply `AppT` x `AppT` y)
-- Apply a type to a list of types using visible kind applications.
foldAppKindT :: Type -> [Type] -> Type
foldAppKindT = foldl' AppKindT
itraverse :: Applicative f => (Int -> a -> f b) -> [a] -> f [b]
itraverse f xs0 = go xs0 0 where
go [] _ = pure []
go (x:xs) n = (:) <$> f n x <*> (go xs $! (n + 1))
ireplicateA :: Applicative f => Int -> (Int -> f a) -> f [a]
ireplicateA cnt0 f =
loop cnt0 0
where
loop cnt n
| cnt <= 0 = pure []
| otherwise = liftA2 (:) (f n) (loop (cnt - 1) $! (n + 1))
-- | Find the data type constructor arguments that are parameters.
--
-- Parameters are names which are unchanged across the structure.
-- They appear at least once in every constructor type, always appear
-- in the same argument position(s), and nothing else ever appears in those
-- argument positions.
--
This was adapted from a similar algorithm used in
( -lang/Idris-dev/blob/a13caeb4e50d0c096d34506f2ebf6b9d140a07aa/src/Idris/Elab/Utils.hs#L401-L468 ) ,
-- licensed under the BSD-3-Clause license.
findParams :: DatatypeInfo -> [Int]
findParams (DatatypeInfo { datatypeName = dataName
, datatypeInstTypes = instTys
, datatypeCons = cons
}) =
let allapps = map getDataApp cons
-- do each constructor separately, then merge the results (names
-- may change between constructors)
conParams = map paramPos allapps
in inAll conParams
where
inAll :: Eq pos => [[pos]] -> [pos]
inAll [] = []
inAll (x : xs) = filter (\p -> all (\ps -> p `elem` ps) xs) x
paramPos :: Eq name => [[Maybe name]] -> [Int]
paramPos [] = []
paramPos (args : rest)
= dropNothing $ keepSame (zip [0..] args) rest
dropNothing :: [(pos, Maybe name)] -> [pos]
dropNothing [] = []
dropNothing ((_, Nothing) : ts) = dropNothing ts
dropNothing ((x, _) : ts) = x : dropNothing ts
keepSame :: Eq name =>
[(pos, Maybe name)] -> [[Maybe name]] ->
[(pos, Maybe name)]
keepSame as [] = as
keepSame as (args : rest) = keepSame (update as args) rest
update :: Eq name => [(pos, Maybe name)] -> [Maybe name] -> [(pos, Maybe name)]
update [] _ = []
update _ [] = []
update ((n, Just x) : as) (Just x' : args)
| x == x' = (n, Just x) : update as args
update ((n, _) : as) (_ : args) = (n, Nothing) : update as args
getDataApp :: ConstructorInfo -> [[Maybe Name]]
getDataApp (ConstructorInfo { constructorFields = fields }) =
concatMap getThem $
fields ++ [ applyType (ConT dataName) $ map TANormal
$ map unSigType instTys
]
where
getThem :: Type -> [[Maybe Name]]
getThem ty = maybeToList $ mbInductiveCase dataName ty inductiveArg
inductiveArg :: [TypeArg] -> [Maybe Name]
inductiveArg argTys =
let visArgTys = filterTANormals argTys
in mParam visArgTys visArgTys
-- keep the arguments which are single names, which appear
in the return type , counting only the first time they appear in
-- the return type as the parameter position
mParam :: [Type] -> [Type] -> [Maybe Name]
mParam _ [] = []
mParam args (VarT n:rest)
| paramIn False n args
= Just n : mParam (filter (noN n) args) rest
mParam args (_:rest) = Nothing : mParam args rest
paramIn :: Bool -> Name -> [Type] -> Bool
paramIn ok _ [] = ok
paramIn ok n (VarT t:ts) = paramIn (ok || n == t) n ts
paramIn ok n (t:ts)
| n `elem` freeVariables t = False -- not a single name
| otherwise = paramIn ok n ts
-- If the name appears again later, don't count that appearance
-- as a parameter position
noN :: Name -> Type -> Bool
noN n (VarT t) = n /= t
noN _ _ = False
-----
-- Taken directly from th-desugar
-----
-- | Remove all of the explicit kind signatures from a 'Type'.
unSigType :: Type -> Type
unSigType (SigT t _) = t
unSigType (AppT f x) = AppT (unSigType f) (unSigType x)
unSigType (ForallT tvbs ctxt t) = ForallT tvbs (map unSigType ctxt) (unSigType t)
unSigType (InfixT t1 n t2) = InfixT (unSigType t1) n (unSigType t2)
unSigType (UInfixT t1 n t2) = UInfixT (unSigType t1) n (unSigType t2)
unSigType (ParensT t) = ParensT (unSigType t)
unSigType (AppKindT t k) = AppKindT (unSigType t) (unSigType k)
unSigType (ImplicitParamT n t) = ImplicitParamT n (unSigType t)
unSigType t = t
-----
-- Taken directly from singletons
-----
-- Make an identifier uppercase. If the identifier is infix, this acts as the
-- identity function.
upcase :: String -> String
upcase str
| isHsLetter first
= toUpper first : tail str
| otherwise
= str
where
first = head str
-- is it a letter or underscore?
isHsLetter :: Char -> Bool
isHsLetter c = isLetter c || c == '_'
| null |
https://raw.githubusercontent.com/RyanGlScott/eliminators/79e7a83d5565d6a4a807ad521a71cf88755f64da/src/Data/Eliminator/TH.hs
|
haskell
|
# LANGUAGE TemplateHaskellQuotes #
* Eliminator generation
** Term-level eliminators
$term-conventions
** Type-level eliminators
$type-conventions
| @'deriveElim' dataName@ generates a top-level elimination function for the
datatype @dataName@. The eliminator will follow these naming conventions:
* If the datatype has an alphanumeric name, its eliminator will have that name
with @elim@ prepended.
* If the datatype has a symbolic name, its eliminator will have that name
with @~>@ prepended.
| @'deriveElimNamed' funName dataName@ generates a top-level elimination
function named @funName@ for the datatype @dataName@.
| @'deriveTypeElim' dataName@ generates a type-level eliminator for the
datatype @dataName@. The eliminator will follow these naming conventions:
* If the datatype has an alphanumeric name, its eliminator will have that name
with @Elim@ prepended.
* If the datatype has a symbolic name, its eliminator will have that name
with @~>@ prepended.
| @'deriveTypeElimNamed' funName dataName@ generates a type-level eliminator
named @funName@ for the datatype @dataName@.
The workhorse for deriveElim(Named). This generates either a term- or
type-level eliminator, depending on which Eliminator instance is used.
The name of the eliminator function
The name of the data type
The eliminator's type signature and body
Generate the type for a "case alternative" in an eliminator function's type
signature, which is done on a constructor-by-constructor basis.
The name of the data type
The predicate type variable
The data constructor
The full case type
The name of the data type
The name of the "case alternative" to apply on the right-hand side
The data constructor
The generated function clause
Generate a single equation for a type-level eliminator.
This code is fairly similar in structure to caseClause, but different
enough in subtle ways that I did not attempt to de-duplicate this code as
a method of the Eliminator class.
The name of the eliminator function
The name of the data type
The type variables bound by the data type
The predicate type variable
The index of this constructor (0-indexed)
The types of each "case alternative" in the eliminator
function's type signature
The data constructor
The generated type family equation
Are we dealing with a term or a type?
A class that abstracts out certain common operations that one must perform
for both term- and type-level eliminators.
Create the Dec for an eliminator function's type signature.
The name of the eliminator function
The type of the eliminator function
Create an eliminator function's type.
The type variables bound by the data type
The predicate type variable
The type variable whose kind is that of the data type itself
The types of each "case alternative" in the eliminator
function's type signature
The eliminator function's return type
The full type
Take a data constructor's field type and prepend it to a "case
alternative" in an eliminator function's type signature.
The name of the data type
The predicate type variable
A fresh type variable name
The field type
The rest of the "case alternative" type
The "case alternative" type after prepending
Generate the clauses/equations for the body of the eliminator function.
The name of the eliminator function
The name of the data type
The type variables bound by the data type
The predicate type variable
The type variable whose kind is that of the data type itself
The types of each "case alternative" in the eliminator
function's type signature
The data constructors
The Dec containing the clauses/equations
A unique characteristic of term-level eliminators is that we manually
apply the static argument transformation, e.g.,
elimT :: forall a (p :: T a ~> Type) (t :: T a).
Sing t
-> (forall (x :: a) (xs :: T a).
Sing x -> Sing xs -> Apply p xs -> Apply p (MkT x xs))
-> Apply p t
where
go :: forall (t' :: T a).
Sing t' -> Apply p t'
ambiguity check.
Annoying special case for lists
| Generate a list of fresh names with a common prefix, and numbered suffixes.
Compute an eliminator function's name from the data type name.
Apply an expression to a list of expressions using ordinary function applications.
Apply a type to a list of types using ordinary function applications.
Apply a type to a list of types using defunctionalized applications
(i.e., using Apply from singletons).
Apply a type to a list of types using visible kind applications.
| Find the data type constructor arguments that are parameters.
Parameters are names which are unchanged across the structure.
They appear at least once in every constructor type, always appear
in the same argument position(s), and nothing else ever appears in those
argument positions.
licensed under the BSD-3-Clause license.
do each constructor separately, then merge the results (names
may change between constructors)
keep the arguments which are single names, which appear
the return type as the parameter position
not a single name
If the name appears again later, don't count that appearance
as a parameter position
---
Taken directly from th-desugar
---
| Remove all of the explicit kind signatures from a 'Type'.
---
Taken directly from singletons
---
Make an identifier uppercase. If the identifier is infix, this acts as the
identity function.
is it a letter or underscore?
|
# LANGUAGE CPP #
# LANGUAGE DataKinds #
# LANGUAGE Unsafe #
|
Module : Data . Eliminator . TH
Copyright : ( C ) 2017
License : BSD - style ( see the file LICENSE )
Maintainer :
Stability : Experimental
Portability : GHC
Generate dependently typed elimination functions using Template Haskell .
Module: Data.Eliminator.TH
Copyright: (C) 2017 Ryan Scott
License: BSD-style (see the file LICENSE)
Maintainer: Ryan Scott
Stability: Experimental
Portability: GHC
Generate dependently typed elimination functions using Template Haskell.
-}
module Data.Eliminator.TH (
deriveElim
, deriveElimNamed
, deriveTypeElim
, deriveTypeElimNamed
) where
import Control.Applicative
import Control.Monad
import Data.Char (isLetter, isUpper, toUpper)
import Data.Foldable
import qualified Data.Kind as Kind (Type)
import Data.Maybe
import Data.Proxy
import Data.Singletons.TH.Options
import Language.Haskell.TH
import Language.Haskell.TH.Datatype as Datatype
import Language.Haskell.TH.Datatype.TyVarBndr
import Language.Haskell.TH.Desugar hiding (NewOrData(..))
import Prelude.Singletons
$ term - conventions
' deriveElim ' and ' deriveElimNamed ' provide a way to automate the creation of
eliminator functions , which are mostly boilerplate . Here is a complete example
showing how one might use ' deriveElim ' :
@
$ ( ' singletons ' [ d| data MyList a = MyNil | MyCons a ( MyList a ) | ] )
$ ( ' deriveElim ' ' ' MyList )
@
This will produce an eliminator function that looks roughly like the following :
@
elimMyList : : forall ( a : : ' Type ' ) ( p : : MyList a ' ~ > ' ' Type ' ) ( l : : MyList a ) .
' Sing ' l
- > ' Apply '
- > ( forall ( x : : a ) . ' Sing ' x
- > forall ( xs : : MyList a ) . ' Sing ' xs - > ' Apply ' p xs
- > ' Apply ' p ( MyCons x xs ) )
- > ' Apply ' p l
elimMyList SMyNil pMyNil _ = pMyNil
elimMyList ( SMyCons ( x ' : : ' Sing ' x ) ( xs ' : : ' Sing ' xs ) ) pMyNil pMyCons
= pMyCons x ' xs ' ( elimMyList \@a \@xs pMyNil pMyCons )
@
There are some important things to note here :
* Because these eliminators use ' Sing ' under the hood , in order for
' deriveElim ' to work , the ' Sing ' instance for the data type given as an
argument must be in scope . Moreover , ' deriveElim ' assumes the naming
conventions for singled constructors used by the @singletons@ library .
( This is why the ' singletons ' function is used in the example above ) .
* There is a convention for the order in which the arguments appear .
The quantified type variables appear in this order :
1 . First , the type variables of the data type itself ( @a@ , in the above example ) .
2 . Second , a predicate type variable of kind @\<Datatype\ > ' ~ > ' ' Type'@
( @p@ , in the above example ) .
3 . Finally , a type variable of kind @\<Datatype\>@ ( @l@ , in the above example ) .
The function arguments appear in this order :
1 . First , a ' Sing ' argument ( @'Sing ' l@ , in the above example ) .
2 . Next , there are arguments that correspond to each constructor . More on this
in a second .
The return type is the predicate type variable applied to the data type
( @'Apply ' p ( MyCons x xs)@ , the above example ) .
The type of each constructor argument also follows certain conventions :
1 . For each field , there will be a rank-2 type variable whose kind matches
the type of the field , followed by a matching ' Sing ' type . For instance ,
in the above example , @forall ( x : : a ) . ' Sing ' corresponds to the
first field of @MyCons@.
2 . In addition , if the field is a recursive occurrence of the data type ,
an additional argument will follow the ' Sing ' type . This is best
explained using the above example . In the @MyCons@ constructor , the second
field ( of type @MyCons a@ ) is a recursive occurrence of @MyCons@ , so
that corresponds to the type
@forall ( xs : : MyList a ) . ' Sing ' xs - > ' Apply ' , where @'Apply '
is only present due to the recursion .
3 . Finally , the return type will be the predicate type variable applied
to a saturated occurrence of the data constructor
( @'Apply ' p ( MyCons x xs)@ , in the above example ) .
* You 'll need to enable lots of GHC extensions in order for the code generated
by ' deriveElim ' to . You 'll need at least the following :
* @AllowAmbiguousTypes@
* @DataKinds@
* @GADTs@
* @PolyKinds@
* @RankNTypes@
* @ScopedTypeVariables@
* @TemplateHaskell@
* @TypeApplications@
* ' deriveElim ' does n't support every possible data type at the moment .
It is known not to work for the following :
* Data types defined using @GADTs@ or @ExistentialQuantification@
* Data family instances
* Data types which use polymorphic recursion
( e.g. , @data Foo a = Foo ( Foo a)@ )
'deriveElim' and 'deriveElimNamed' provide a way to automate the creation of
eliminator functions, which are mostly boilerplate. Here is a complete example
showing how one might use 'deriveElim':
@
$('singletons' [d| data MyList a = MyNil | MyCons a (MyList a) |])
$('deriveElim' ''MyList)
@
This will produce an eliminator function that looks roughly like the following:
@
elimMyList :: forall (a :: 'Type') (p :: MyList a '~>' 'Type') (l :: MyList a).
'Sing' l
-> 'Apply' p MyNil
-> (forall (x :: a). 'Sing' x
-> forall (xs :: MyList a). 'Sing' xs -> 'Apply' p xs
-> 'Apply' p (MyCons x xs))
-> 'Apply' p l
elimMyList SMyNil pMyNil _ = pMyNil
elimMyList (SMyCons (x' :: 'Sing' x) (xs' :: 'Sing' xs)) pMyNil pMyCons
= pMyCons x' xs' (elimMyList \@a \@p \@xs pMyNil pMyCons)
@
There are some important things to note here:
* Because these eliminators use 'Sing' under the hood, in order for
'deriveElim' to work, the 'Sing' instance for the data type given as an
argument must be in scope. Moreover, 'deriveElim' assumes the naming
conventions for singled constructors used by the @singletons@ library.
(This is why the 'singletons' function is used in the example above).
* There is a convention for the order in which the arguments appear.
The quantified type variables appear in this order:
1. First, the type variables of the data type itself (@a@, in the above example).
2. Second, a predicate type variable of kind @\<Datatype\> '~>' 'Type'@
(@p@, in the above example).
3. Finally, a type variable of kind @\<Datatype\>@ (@l@, in the above example).
The function arguments appear in this order:
1. First, a 'Sing' argument (@'Sing' l@, in the above example).
2. Next, there are arguments that correspond to each constructor. More on this
in a second.
The return type is the predicate type variable applied to the data type
(@'Apply' p (MyCons x xs)@, the above example).
The type of each constructor argument also follows certain conventions:
1. For each field, there will be a rank-2 type variable whose kind matches
the type of the field, followed by a matching 'Sing' type. For instance,
in the above example, @forall (x :: a). 'Sing' x@ corresponds to the
first field of @MyCons@.
2. In addition, if the field is a recursive occurrence of the data type,
an additional argument will follow the 'Sing' type. This is best
explained using the above example. In the @MyCons@ constructor, the second
field (of type @MyCons a@) is a recursive occurrence of @MyCons@, so
that corresponds to the type
@forall (xs :: MyList a). 'Sing' xs -> 'Apply' p xs@, where @'Apply' p xs@
is only present due to the recursion.
3. Finally, the return type will be the predicate type variable applied
to a saturated occurrence of the data constructor
(@'Apply' p (MyCons x xs)@, in the above example).
* You'll need to enable lots of GHC extensions in order for the code generated
by 'deriveElim' to typecheck. You'll need at least the following:
* @AllowAmbiguousTypes@
* @DataKinds@
* @GADTs@
* @PolyKinds@
* @RankNTypes@
* @ScopedTypeVariables@
* @TemplateHaskell@
* @TypeApplications@
* 'deriveElim' doesn't support every possible data type at the moment.
It is known not to work for the following:
* Data types defined using @GADTs@ or @ExistentialQuantification@
* Data family instances
* Data types which use polymorphic recursion
(e.g., @data Foo a = Foo (Foo a)@)
-}
deriveElim :: Name -> Q [Dec]
deriveElim dataName = deriveElimNamed (eliminatorName dataName) dataName
deriveElimNamed :: String -> Name -> Q [Dec]
deriveElimNamed = deriveElimNamed' (Proxy @IsTerm)
$ type - conventions
' deriveTypeElim ' and ' deriveTypeElimNamed ' are like ' deriveElim ' and
' deriveElimNamed ' except that they create /type/-level eliminators instead of
term - level ones . Here is an example showing how one might use
' deriveTypeElim ' :
@
data MyList a = MyNil | MyCons a ( MyList a )
$ ( ' deriveTypeElim ' ' ' MyList )
@
This will produce an eliminator function that looks roughly like the following :
@
type ElimMyList : : forall ( a : : ' Type ' ) .
forall ( p : : MyList a ' ~ > ' ' Type ' ) ( l : : MyList a )
- > ' Apply ' p MyNil
- > ( forall ( x : : a ) ( xs : : MyList a )
- > ' Apply ' p xs ' ~ > ' ' Apply ' p ( MyCons x xs ) )
- > ' Apply ' p l
type family ElimMyList p l pMyNil pMyCons where
forall ( a : : ' Type ' )
( p : : MyList a ~ > ' Type ' )
( pMyNil : : ' Apply ' )
( pMyCons : : forall ( x : : a ) ( xs : : MyList a )
- > ' Apply ' p xs ' ~ > ' ' Apply ' p ( MyCons x xs ) ) .
ElimMyList @a p MyNil pMyNil pMyCons =
pMyNil
forall ( a : : ' Type ' )
( p : : MyList a ~ > ' Type ' )
( _ pMyNil : : ' Apply ' )
( pMyCons : : forall ( x : : a ) ( xs : : MyList a )
- > ' Apply ' p xs ' ~ > ' ' Apply ' p ( MyCons x xs ) )
x ' xs ' .
ElimMyList @a p ( MyCons x ' xs ' ) pMyNil pMyCons =
' Apply ' ( pMyCons x ' xs ' ) ( ElimMyList @a p xs ' pMyNil pMyCons )
@
Note the following differences from a term - level eliminator that ' deriveElim '
would generate :
* Type - level eliminators do not use ' Sing ' . Instead , they use visible dependent
quantification . That is , instead of generating
@forall ( x : : a ) . Sing x - > ... @ ( as a term - level eliminator would do ) , a
type - level eliminator would use @forall ( x : : a ) - > ... @.
* Term - level eliminators quantify @p@ with an invisible @forall@ , whereas
type - level eliminators quantify @p@ with a visible @forall@. ( Really , ought to be quantified visibly in both forms of eliminator , but GHC does not
yet support visible dependent quantification at the term level . )
* Type - level eliminators use ( ' ~ > ' ) in certain places where ( @->@ ) would appear
in term - level eliminators . For instance , note the use of
@'Apply ' p xs ' ~ > ' ' Apply ' p ( MyCons x xs)@ in @ElimMyList@ above . This is
done to make it easier to use type - level eliminators with defunctionalization
symbols ( which are n't necessary for term - level eliminators ) .
This comes with a notable drawback : type - level eliminators can not support
data constructors where recursive occurrences of the data type appear in a
position other than the last field of a constructor . In other words ,
' deriveTypeElim ' works on the @MyList@ example above , but not this variant :
@
data SnocList a = SnocNil | SnocCons ( SnocList a ) a
@
This is because @$('deriveTypeElim ' ' ' SnocList)@ would generate an eliminator
with the following kind :
@
type ElimSnocList : : forall ( a : : ' Type ' ) .
forall ( p : : SnocList a ' ~ > ' ' Type ' ) ( l : : SnocList a )
- > ' Apply '
- > ( forall ( xs : : SnocList a ) - > ' Apply ' p xs
' ~ > ' ( forall ( x : : a ) - > ' Apply ' p ( SnocCons x xs ) ) )
- > ' Apply ' p l
@
Unfortunately , the kind
@'Apply ' p xs ' ~ > ' ( forall ( x : : a ) - > ' Apply ' p ( SnocCons x xs))@ is
impredicative .
* In addition to the language extensions that ' deriveElim ' requires , you 'll need
to enable these extensions in order to use ' deriveTypeElim ' :
* @StandaloneKindSignatures@
* @UndecidableInstances@
'deriveTypeElim' and 'deriveTypeElimNamed' are like 'deriveElim' and
'deriveElimNamed' except that they create /type/-level eliminators instead of
term-level ones. Here is an example showing how one might use
'deriveTypeElim':
@
data MyList a = MyNil | MyCons a (MyList a)
$('deriveTypeElim' ''MyList)
@
This will produce an eliminator function that looks roughly like the following:
@
type ElimMyList :: forall (a :: 'Type').
forall (p :: MyList a '~>' 'Type') (l :: MyList a)
-> 'Apply' p MyNil
-> (forall (x :: a) (xs :: MyList a)
-> 'Apply' p xs '~>' 'Apply' p (MyCons x xs))
-> 'Apply' p l
type family ElimMyList p l pMyNil pMyCons where
forall (a :: 'Type')
(p :: MyList a ~> 'Type')
(pMyNil :: 'Apply' p MyNil)
(pMyCons :: forall (x :: a) (xs :: MyList a)
-> 'Apply' p xs '~>' 'Apply' p (MyCons x xs)).
ElimMyList @a p MyNil pMyNil pMyCons =
pMyNil
forall (a :: 'Type')
(p :: MyList a ~> 'Type')
(_pMyNil :: 'Apply' p MyNil)
(pMyCons :: forall (x :: a) (xs :: MyList a)
-> 'Apply' p xs '~>' 'Apply' p (MyCons x xs))
x' xs'.
ElimMyList @a p (MyCons x' xs') pMyNil pMyCons =
'Apply' (pMyCons x' xs') (ElimMyList @a p xs' pMyNil pMyCons)
@
Note the following differences from a term-level eliminator that 'deriveElim'
would generate:
* Type-level eliminators do not use 'Sing'. Instead, they use visible dependent
quantification. That is, instead of generating
@forall (x :: a). Sing x -> ...@ (as a term-level eliminator would do), a
type-level eliminator would use @forall (x :: a) -> ...@.
* Term-level eliminators quantify @p@ with an invisible @forall@, whereas
type-level eliminators quantify @p@ with a visible @forall@. (Really, @p@
ought to be quantified visibly in both forms of eliminator, but GHC does not
yet support visible dependent quantification at the term level.)
* Type-level eliminators use ('~>') in certain places where (@->@) would appear
in term-level eliminators. For instance, note the use of
@'Apply' p xs '~>' 'Apply' p (MyCons x xs)@ in @ElimMyList@ above. This is
done to make it easier to use type-level eliminators with defunctionalization
symbols (which aren't necessary for term-level eliminators).
This comes with a notable drawback: type-level eliminators cannot support
data constructors where recursive occurrences of the data type appear in a
position other than the last field of a constructor. In other words,
'deriveTypeElim' works on the @MyList@ example above, but not this variant:
@
data SnocList a = SnocNil | SnocCons (SnocList a) a
@
This is because @$('deriveTypeElim' ''SnocList)@ would generate an eliminator
with the following kind:
@
type ElimSnocList :: forall (a :: 'Type').
forall (p :: SnocList a '~>' 'Type') (l :: SnocList a)
-> 'Apply' p SnocNil
-> (forall (xs :: SnocList a) -> 'Apply' p xs
'~>' (forall (x :: a) -> 'Apply' p (SnocCons x xs)))
-> 'Apply' p l
@
Unfortunately, the kind
@'Apply' p xs '~>' (forall (x :: a) -> 'Apply' p (SnocCons x xs))@ is
impredicative.
* In addition to the language extensions that 'deriveElim' requires, you'll need
to enable these extensions in order to use 'deriveTypeElim':
* @StandaloneKindSignatures@
* @UndecidableInstances@
-}
deriveTypeElim :: Name -> Q [Dec]
deriveTypeElim dataName = deriveTypeElimNamed (upcase (eliminatorName dataName)) dataName
deriveTypeElimNamed :: String -> Name -> Q [Dec]
deriveTypeElimNamed = deriveElimNamed' (Proxy @IsType)
deriveElimNamed' ::
Eliminator t
=> proxy t
deriveElimNamed' prox funName dataName = do
info@(DatatypeInfo { datatypeVars = dataVarBndrs
, datatypeInstTypes = instTys
, datatypeVariant = variant
, datatypeCons = cons
}) <- reifyDatatype dataName
let noDataFamilies =
fail "Eliminators for data family instances are currently not supported"
case variant of
DataInstance -> noDataFamilies
NewtypeInstance -> noDataFamilies
Datatype -> pure ()
Newtype -> pure ()
#if MIN_VERSION_th_abstraction(0,5,0)
Datatype.TypeData -> pure ()
#endif
predVar <- newName "p"
singVar <- newName "s"
let elimName = mkName funName
promDataKind = datatypeType info
predVarBndr = kindedTV predVar (InfixT promDataKind ''(~>) (ConT ''Kind.Type))
singVarBndr = kindedTV singVar promDataKind
caseTypes <- traverse (caseType prox dataName predVar) cons
unless (length (findParams info) == length instTys) $
fail "Eliminators for polymorphically recursive data types are currently not supported"
let returnType = predType predVar (VarT singVar)
elimType = elimTypeSig prox dataVarBndrs predVarBndr singVarBndr
caseTypes returnType
elimEqns <- qElimEqns prox (mkName funName) dataName
dataVarBndrs predVarBndr singVarBndr
caseTypes cons
pure [elimSigD prox elimName elimType, elimEqns]
caseType ::
Eliminator t
=> proxy t
caseType prox dataName predVar
(ConstructorInfo { constructorName = conName
, constructorVars = conVars
, constructorContext = conContext
, constructorFields = fieldTypes })
= do unless (null conVars && null conContext) $
fail $ unlines
[ "Eliminators for GADTs or datatypes with existentially quantified"
, "data constructors currently not supported"
]
vars <- newNameList "f" $ length fieldTypes
let returnType = predType predVar
(foldl' AppT (ConT conName) (map VarT vars))
pure $ foldr' (\(var, varType) t ->
prependElimCaseTypeVar prox dataName predVar var varType t)
returnType
(zip vars fieldTypes)
Generate a single clause for a term - level eliminator 's @go@ function .
goCaseClause ::
The name of the @go@ function
goCaseClause goName dataName usedCaseVar
(ConstructorInfo { constructorName = conName
, constructorFields = fieldTypes })
= do let numFields = length fieldTypes
singVars <- newNameList "s" numFields
singVarSigs <- newNameList "sTy" numFields
let singConName = singledDataConName defaultOptions conName
mkSingVarPat var varSig = SigP (VarP var) (singType varSig)
singVarPats = zipWith mkSingVarPat singVars singVarSigs
mbInductiveArg singVar singVarSig varType =
let inductiveArg = VarE goName `AppTypeE` VarT singVarSig
`AppE` VarE singVar
in mbInductiveCase dataName varType $ const inductiveArg
mkArg f (singVar, singVarSig, varType) =
foldAppE f $ VarE singVar
: maybeToList (mbInductiveArg singVar singVarSig varType)
rhs = foldl' mkArg (VarE usedCaseVar) $
zip3 singVars singVarSigs fieldTypes
pure $ Clause [ConP singConName [] singVarPats]
(NormalB rhs)
[]
caseTySynEqn ::
caseTySynEqn elimName dataName dataVarBndrs predVarBndr conIndex caseTypes
(ConstructorInfo { constructorName = conName
, constructorFields = fieldTypes })
= do let dataVarNames = map tvName dataVarBndrs
predVarName = tvName predVarBndr
numFields = length fieldTypes
singVars <- newNameList "s" numFields
usedCaseVar <- newName "useThis"
caseVarBndrs <- flip itraverse caseTypes $ \i caseTy ->
let mkVarName
| i == conIndex = pure usedCaseVar
| otherwise = newName ("_p" ++ show i)
in liftA2 kindedTV mkVarName (pure caseTy)
let caseVarNames = map tvName caseVarBndrs
prefix = foldAppKindT (ConT elimName) $ map VarT dataVarNames
mbInductiveArg singVar varType =
let inductiveArg = foldAppT prefix $ VarT predVarName
: VarT singVar
: map VarT caseVarNames
in mbInductiveCase dataName varType $ const inductiveArg
mkArg f (singVar, varType) =
foldAppDefunT (f `AppT` VarT singVar)
$ maybeToList (mbInductiveArg singVar varType)
bndrs = dataVarBndrs ++ predVarBndr : caseVarBndrs ++ map plainTV singVars
lhs = foldAppT prefix $ VarT predVarName
: foldAppT (ConT conName) (map VarT singVars)
: map VarT caseVarNames
rhs = foldl' mkArg (VarT usedCaseVar) $ zip singVars fieldTypes
pure $ TySynEqn (Just bndrs) lhs rhs
data TermOrType
= IsTerm
| IsType
class Eliminator (t :: TermOrType) where
elimSigD ::
proxy t
The type signature Dec ( SigD or KiSigD )
elimTypeSig ::
proxy t
prependElimCaseTypeVar ::
proxy t
qElimEqns ::
proxy t
instance Eliminator IsTerm where
elimSigD _ = SigD
elimTypeSig _ dataVarBndrs predVarBndr singVarBndr caseTypes returnType =
ForallT (changeTVFlags SpecifiedSpec $
dataVarBndrs ++ [predVarBndr, singVarBndr]) [] $
ravel (singType (tvName singVarBndr):caseTypes) returnType
prependElimCaseTypeVar _ dataName predVar var varType t =
ForallT [kindedTVSpecified var varType] [] $
ravel (singType var:maybeToList (mbInductiveType dataName predVar var varType)) t
elimT st k = go @s k
go ( SMkT ( sx : : Sing x ) ( sxs : : Sing xs ) ) =
( go @xs )
This reduces the likelihood of recursive calls falling afoul of GHC 's
qElimEqns _ elimName dataName _dataVarBndrs predVarBndr singVarBndr _caseTypes cons = do
singTermVar <- newName "s"
caseVars <- newNameList "p" $ length cons
goName <- newName "go"
let singTypeVar = tvName singVarBndr
goSingTypeVar <- newName $ nameBase singTypeVar
let elimRHS = VarE goName `AppTypeE` VarT singTypeVar `AppE` VarE singTermVar
goSingVarBndr = mapTVName (const goSingTypeVar) singVarBndr
goReturnType = predType (tvName predVarBndr) (VarT goSingTypeVar)
goType = ForallT (changeTVFlags SpecifiedSpec [goSingVarBndr]) [] $
ArrowT `AppT` singType goSingTypeVar `AppT` goReturnType
goClauses
<- if null cons
then pure [Clause [VarP singTermVar] (NormalB (CaseE (VarE singTermVar) [])) []]
else zipWithM (goCaseClause goName dataName) caseVars cons
pure $ FunD elimName [ Clause (map VarP (singTermVar:caseVars)) (NormalB elimRHS)
[SigD goName goType, FunD goName goClauses] ]
instance Eliminator IsType where
elimSigD _ = KiSigD
elimTypeSig _ dataVarBndrs predVarBndr singVarBndr caseTypes returnType =
ForallT (changeTVFlags SpecifiedSpec dataVarBndrs) [] $
ForallVisT [predVarBndr, singVarBndr] $
ravel caseTypes returnType
prependElimCaseTypeVar _ dataName predVar var varType t =
ForallVisT [kindedTV var varType] $
ravelDefun (maybeToList (mbInductiveType dataName predVar var varType)) t
qElimEqns _ elimName dataName dataVarBndrs predVarBndr singVarBndr caseTypes cons = do
caseVarBndrs <- replicateM (length caseTypes) (plainTV <$> newName "p")
let predVar = tvName predVarBndr
singVar = tvName singVarBndr
tyFamHead = TypeFamilyHead elimName
(plainTV predVar:plainTV singVar:caseVarBndrs)
NoSig Nothing
caseEqns <- itraverse (\i -> caseTySynEqn elimName dataName
dataVarBndrs predVarBndr i caseTypes) cons
pure $ ClosedTypeFamilyD tyFamHead caseEqns
mbInductiveType :: Name -> Name -> Name -> Kind -> Maybe Type
mbInductiveType dataName predVar var varType =
mbInductiveCase dataName varType $ const $ predType predVar $ VarT var
mbInductiveCase :: Name -> Type -> ([TypeArg] -> a) -> Maybe a
mbInductiveCase dataName varType inductiveArg
= case unfoldType varType of
(headTy, argTys)
| ListT <- headTy
, dataName == ''[]
-> Just $ inductiveArg argTys
| ConT n <- headTy
, dataName == n
-> Just $ inductiveArg argTys
| otherwise
-> Nothing
| Construct a type of the form @'Sing ' given @x@.
singType :: Name -> Type
singType x = ConT ''Sing `AppT` VarT x
| Construct a type of the form @'Apply ' p ty@ given @p@ and @ty@.
predType :: Name -> Type -> Type
predType p ty = ConT ''Apply `AppT` VarT p `AppT` ty
newNameList :: String -> Int -> Q [Name]
newNameList prefix n = ireplicateA n $ newName . (prefix ++) . show
eliminatorName :: Name -> String
eliminatorName n
| first:_ <- nStr
, isUpper first
= "elim" ++ nStr
| otherwise
= "~>" ++ nStr
where
nStr = nameBase n
Construct a function type , separating the arguments with - >
ravel :: [Type] -> Type -> Type
ravel args res = go args
where
go [] = res
go (h:t) = AppT (AppT ArrowT h) (go t)
Construct a function type , separating the arguments with ~ >
ravelDefun :: [Type] -> Type -> Type
ravelDefun args res = go args
where
go [] = res
go (h:t) = AppT (AppT (ConT ''(~>)) h) (go t)
foldAppE :: Exp -> [Exp] -> Exp
foldAppE = foldl' AppE
foldAppT :: Type -> [Type] -> Type
foldAppT = foldl' AppT
foldAppDefunT :: Type -> [Type] -> Type
foldAppDefunT = foldl' (\x y -> ConT ''Apply `AppT` x `AppT` y)
foldAppKindT :: Type -> [Type] -> Type
foldAppKindT = foldl' AppKindT
itraverse :: Applicative f => (Int -> a -> f b) -> [a] -> f [b]
itraverse f xs0 = go xs0 0 where
go [] _ = pure []
go (x:xs) n = (:) <$> f n x <*> (go xs $! (n + 1))
ireplicateA :: Applicative f => Int -> (Int -> f a) -> f [a]
ireplicateA cnt0 f =
loop cnt0 0
where
loop cnt n
| cnt <= 0 = pure []
| otherwise = liftA2 (:) (f n) (loop (cnt - 1) $! (n + 1))
This was adapted from a similar algorithm used in
( -lang/Idris-dev/blob/a13caeb4e50d0c096d34506f2ebf6b9d140a07aa/src/Idris/Elab/Utils.hs#L401-L468 ) ,
findParams :: DatatypeInfo -> [Int]
findParams (DatatypeInfo { datatypeName = dataName
, datatypeInstTypes = instTys
, datatypeCons = cons
}) =
let allapps = map getDataApp cons
conParams = map paramPos allapps
in inAll conParams
where
inAll :: Eq pos => [[pos]] -> [pos]
inAll [] = []
inAll (x : xs) = filter (\p -> all (\ps -> p `elem` ps) xs) x
paramPos :: Eq name => [[Maybe name]] -> [Int]
paramPos [] = []
paramPos (args : rest)
= dropNothing $ keepSame (zip [0..] args) rest
dropNothing :: [(pos, Maybe name)] -> [pos]
dropNothing [] = []
dropNothing ((_, Nothing) : ts) = dropNothing ts
dropNothing ((x, _) : ts) = x : dropNothing ts
keepSame :: Eq name =>
[(pos, Maybe name)] -> [[Maybe name]] ->
[(pos, Maybe name)]
keepSame as [] = as
keepSame as (args : rest) = keepSame (update as args) rest
update :: Eq name => [(pos, Maybe name)] -> [Maybe name] -> [(pos, Maybe name)]
update [] _ = []
update _ [] = []
update ((n, Just x) : as) (Just x' : args)
| x == x' = (n, Just x) : update as args
update ((n, _) : as) (_ : args) = (n, Nothing) : update as args
getDataApp :: ConstructorInfo -> [[Maybe Name]]
getDataApp (ConstructorInfo { constructorFields = fields }) =
concatMap getThem $
fields ++ [ applyType (ConT dataName) $ map TANormal
$ map unSigType instTys
]
where
getThem :: Type -> [[Maybe Name]]
getThem ty = maybeToList $ mbInductiveCase dataName ty inductiveArg
inductiveArg :: [TypeArg] -> [Maybe Name]
inductiveArg argTys =
let visArgTys = filterTANormals argTys
in mParam visArgTys visArgTys
in the return type , counting only the first time they appear in
mParam :: [Type] -> [Type] -> [Maybe Name]
mParam _ [] = []
mParam args (VarT n:rest)
| paramIn False n args
= Just n : mParam (filter (noN n) args) rest
mParam args (_:rest) = Nothing : mParam args rest
paramIn :: Bool -> Name -> [Type] -> Bool
paramIn ok _ [] = ok
paramIn ok n (VarT t:ts) = paramIn (ok || n == t) n ts
paramIn ok n (t:ts)
| otherwise = paramIn ok n ts
noN :: Name -> Type -> Bool
noN n (VarT t) = n /= t
noN _ _ = False
unSigType :: Type -> Type
unSigType (SigT t _) = t
unSigType (AppT f x) = AppT (unSigType f) (unSigType x)
unSigType (ForallT tvbs ctxt t) = ForallT tvbs (map unSigType ctxt) (unSigType t)
unSigType (InfixT t1 n t2) = InfixT (unSigType t1) n (unSigType t2)
unSigType (UInfixT t1 n t2) = UInfixT (unSigType t1) n (unSigType t2)
unSigType (ParensT t) = ParensT (unSigType t)
unSigType (AppKindT t k) = AppKindT (unSigType t) (unSigType k)
unSigType (ImplicitParamT n t) = ImplicitParamT n (unSigType t)
unSigType t = t
upcase :: String -> String
upcase str
| isHsLetter first
= toUpper first : tail str
| otherwise
= str
where
first = head str
isHsLetter :: Char -> Bool
isHsLetter c = isLetter c || c == '_'
|
1fb633a401dce4698484c576cdfc02dbdeda6407d319dcccb9c5a7dbc9b2ad82
|
imitator-model-checker/imitator
|
AlgoEFopt.mli
|
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* IMITATOR
*
* Université Paris 13 , LIPN , CNRS , France
* Université de Lorraine , CNRS , , LORIA , Nancy , France
*
* Module description : " EF optimized " algorithm : minimization or minimization of a parameter valuation for which there exists a run leading to some states [ ABPP19 ]
*
* File contributors : * Created : 2017/05/02
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* IMITATOR
*
* Université Paris 13, LIPN, CNRS, France
* Université de Lorraine, CNRS, Inria, LORIA, Nancy, France
*
* Module description: "EF optimized" algorithm: minimization or minimization of a parameter valuation for which there exists a run leading to some states [ABPP19]
*
* File contributors : Étienne André
* Created : 2017/05/02
*
************************************************************)
(************************************************************)
(* Modules *)
(************************************************************)
open AlgoStateBased
open State
(************************************************************)
(* Class definition *)
(************************************************************)
class virtual algoEFopt : AbstractProperty.state_predicate -> Automaton.parameter_index ->
object inherit algoStateBased
(************************************************************)
(* Class variables *)
(************************************************************)
(************************************************************)
(* Class methods *)
(************************************************************)
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
(* Set the 'synthesize_valuations' flag (must be done right after creating the algorithm object!) *)
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
method set_synthesize_valuations : bool -> unit
(*------------------------------------------------------------*)
(* Instantiating min/max *)
(*------------------------------------------------------------*)
(* Function to remove upper bounds (if minimum) or lower bounds (if maximum) *)
method virtual remove_bounds : Automaton.parameter_index list -> Automaton.parameter_index list -> LinearConstraint.p_linear_constraint -> unit
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
(* Function to negate an inequality (to be defined in subclasses) *)
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
method virtual negate_inequality : LinearConstraint.p_linear_constraint -> LinearConstraint.p_linear_constraint
(* The closed operator (>= for minimization, and <= for maximization) *)
method virtual closed_op : LinearConstraint.op
(* Various strings *)
method virtual str_optimum : string
method virtual str_upper_lower : string
(*------------------------------------------------------------*)
(* Algorithmic methods *)
(*------------------------------------------------------------*)
method run : unit -> Result.imitator_result
(*------------------------------------------------------------*)
(* Add a new state to the state space (if indeed needed) *)
(* Return true if the state is not discarded by the algorithm, i.e., if it is either added OR was already present before *)
Can raise an exception TerminateAnalysis to lead to an immediate termination
(*------------------------------------------------------------*)
(*** TODO: return the list of actually added states ***)
method add_a_new_state : state_index -> StateSpace.combined_transition -> State.state -> bool
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
(** Actions to perform with the initial state; returns true unless the initial state cannot be kept (in which case the algorithm will stop immediately) *)
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
method process_initial_state : State.state -> bool
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
(* Actions to perform when meeting a state with no successors: nothing to do for this algorithm *)
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
method process_deadlock_state : state_index -> unit
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
(** Actions to perform at the end of the computation of the *successors* of post^n (i.e., when this method is called, the successors were just computed). Nothing to do for this algorithm. *)
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
method process_post_n : state_index list -> unit
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
(** Check whether the algorithm should terminate at the end of some post, independently of the number of states to be processed (e.g., if the constraint is already true or false) *)
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
method check_termination_at_post_n : bool
method compute_result : Result.imitator_result
end
| null |
https://raw.githubusercontent.com/imitator-model-checker/imitator/105408ae2bd8c3e3291f286e4d127defd492a58b/src/AlgoEFopt.mli
|
ocaml
|
**********************************************************
Modules
**********************************************************
**********************************************************
Class definition
**********************************************************
**********************************************************
Class variables
**********************************************************
**********************************************************
Class methods
**********************************************************
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
Set the 'synthesize_valuations' flag (must be done right after creating the algorithm object!)
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
------------------------------------------------------------
Instantiating min/max
------------------------------------------------------------
Function to remove upper bounds (if minimum) or lower bounds (if maximum)
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
Function to negate an inequality (to be defined in subclasses)
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
The closed operator (>= for minimization, and <= for maximization)
Various strings
------------------------------------------------------------
Algorithmic methods
------------------------------------------------------------
------------------------------------------------------------
Add a new state to the state space (if indeed needed)
Return true if the state is not discarded by the algorithm, i.e., if it is either added OR was already present before
------------------------------------------------------------
** TODO: return the list of actually added states **
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
* Actions to perform with the initial state; returns true unless the initial state cannot be kept (in which case the algorithm will stop immediately)
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
Actions to perform when meeting a state with no successors: nothing to do for this algorithm
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
* Actions to perform at the end of the computation of the *successors* of post^n (i.e., when this method is called, the successors were just computed). Nothing to do for this algorithm.
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
* Check whether the algorithm should terminate at the end of some post, independently of the number of states to be processed (e.g., if the constraint is already true or false)
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
|
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* IMITATOR
*
* Université Paris 13 , LIPN , CNRS , France
* Université de Lorraine , CNRS , , LORIA , Nancy , France
*
* Module description : " EF optimized " algorithm : minimization or minimization of a parameter valuation for which there exists a run leading to some states [ ABPP19 ]
*
* File contributors : * Created : 2017/05/02
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* IMITATOR
*
* Université Paris 13, LIPN, CNRS, France
* Université de Lorraine, CNRS, Inria, LORIA, Nancy, France
*
* Module description: "EF optimized" algorithm: minimization or minimization of a parameter valuation for which there exists a run leading to some states [ABPP19]
*
* File contributors : Étienne André
* Created : 2017/05/02
*
************************************************************)
open AlgoStateBased
open State
class virtual algoEFopt : AbstractProperty.state_predicate -> Automaton.parameter_index ->
object inherit algoStateBased
method set_synthesize_valuations : bool -> unit
method virtual remove_bounds : Automaton.parameter_index list -> Automaton.parameter_index list -> LinearConstraint.p_linear_constraint -> unit
method virtual negate_inequality : LinearConstraint.p_linear_constraint -> LinearConstraint.p_linear_constraint
method virtual closed_op : LinearConstraint.op
method virtual str_optimum : string
method virtual str_upper_lower : string
method run : unit -> Result.imitator_result
Can raise an exception TerminateAnalysis to lead to an immediate termination
method add_a_new_state : state_index -> StateSpace.combined_transition -> State.state -> bool
method process_initial_state : State.state -> bool
method process_deadlock_state : state_index -> unit
method process_post_n : state_index list -> unit
method check_termination_at_post_n : bool
method compute_result : Result.imitator_result
end
|
9dce36924119a760c38289054be812bc5d2610f37c8d6bfc06e018aa2144b16f
|
xsc/pandect
|
core.clj
|
(ns ^:no-doc pandect.gen.core
(:import [java.io File FileInputStream]))
# # Concept
;;
;; Instead of having types that implement protocols that perform
;; the actual digest/checksum calculations (pandect <= 0.2.1), we
;; will have a protocol for code generators to be used to create
;; the digest/checksum functions in pandect.core at compile
;; time.
# # Code Generator Protocols
(defprotocol CodeGen
"Protocol for Algorithm Code Generators."
(algorithm-string [this]
"Get String representing the Algorithm this Code Generator is built
for."))
(defprotocol Generator
"Protocol for the actual code generation based on algorithm code generators."
(can-generate? [this code-gen]
"Can this generator process the given algorithm generator?")
(generate-protocol [this code-gen id buffer-size]
"Generate and implement protocol for the types that should be processable.
The given symbol should be used as the hash/HMAC function name.")
(generate-functions [this code-gen id f]
"Generate functions relying on the protocol function given in `id`. `f` is the
symbol to be used as the base function name; `buffer-size` is the form used to
lookup the buffer size for stream processing."))
# # Code Generator List
(defonce ^:private code-generators {})
(defn register-algorithm!
"Register new algorithm code generator."
([code-gen]
(register-algorithm! {:name (algorithm-string code-gen)} code-gen))
([{:keys [name requires docstring]} & code-gens]
(alter-var-root
#'code-generators
(fn [gens]
(-> gens
(update-in [name :docstring] #(or % docstring))
(update-in [name :requires] concat requires)
(update-in [name :code-gens]
concat (filter identity code-gens)))))))
(defn get-code-generators
"Lookup code generators by algorithm."
[algorithm-string]
(let [v (code-generators algorithm-string ::none)]
(if (= v ::none)
(println "WARN: No such Code Generator:" algorithm-string)
v)))
;; ## Helpers
(defn wrap-file-stream
"Replace the given symbol's value with an input stream."
([generator-code sym]
(->> (vary-meta sym assoc :tag `File)
(wrap-file-stream generator-code sym)))
([generator-code sym fsym]
(let [wrap-fn (condp = (:tag (meta fsym))
`File `clojure.java.io/as-file
`String `str)]
`(with-open [~sym (FileInputStream. (~wrap-fn ~fsym))]
~generator-code))))
(defn as-sym
[sym & suffixes]
(symbol (apply str (name sym) suffixes)))
(defn symbol+
[sym suffix]
(cond (= suffix :*) (symbol (str (name sym) "*"))
suffix (symbol (str (name sym) "-" (name suffix)))
:else sym))
# # Generation
(defn generate
"Generate algorithm functions based on the given generators."
[generator code-gen f buffer-size]
(when (can-generate? generator code-gen)
(let [id (gensym (str "compute-" (name f)))]
`(do
~(generate-protocol generator code-gen id buffer-size)
~(generate-functions generator code-gen id f)))))
| null |
https://raw.githubusercontent.com/xsc/pandect/ffc95e81484045ddbe235a2f4208bd5677f1195b/src/pandect/gen/core.clj
|
clojure
|
Instead of having types that implement protocols that perform
the actual digest/checksum calculations (pandect <= 0.2.1), we
will have a protocol for code generators to be used to create
the digest/checksum functions in pandect.core at compile
time.
`buffer-size` is the form used to
## Helpers
|
(ns ^:no-doc pandect.gen.core
(:import [java.io File FileInputStream]))
# # Concept
# # Code Generator Protocols
(defprotocol CodeGen
"Protocol for Algorithm Code Generators."
(algorithm-string [this]
"Get String representing the Algorithm this Code Generator is built
for."))
(defprotocol Generator
"Protocol for the actual code generation based on algorithm code generators."
(can-generate? [this code-gen]
"Can this generator process the given algorithm generator?")
(generate-protocol [this code-gen id buffer-size]
"Generate and implement protocol for the types that should be processable.
The given symbol should be used as the hash/HMAC function name.")
(generate-functions [this code-gen id f]
"Generate functions relying on the protocol function given in `id`. `f` is the
lookup the buffer size for stream processing."))
# # Code Generator List
(defonce ^:private code-generators {})
(defn register-algorithm!
"Register new algorithm code generator."
([code-gen]
(register-algorithm! {:name (algorithm-string code-gen)} code-gen))
([{:keys [name requires docstring]} & code-gens]
(alter-var-root
#'code-generators
(fn [gens]
(-> gens
(update-in [name :docstring] #(or % docstring))
(update-in [name :requires] concat requires)
(update-in [name :code-gens]
concat (filter identity code-gens)))))))
(defn get-code-generators
"Lookup code generators by algorithm."
[algorithm-string]
(let [v (code-generators algorithm-string ::none)]
(if (= v ::none)
(println "WARN: No such Code Generator:" algorithm-string)
v)))
(defn wrap-file-stream
"Replace the given symbol's value with an input stream."
([generator-code sym]
(->> (vary-meta sym assoc :tag `File)
(wrap-file-stream generator-code sym)))
([generator-code sym fsym]
(let [wrap-fn (condp = (:tag (meta fsym))
`File `clojure.java.io/as-file
`String `str)]
`(with-open [~sym (FileInputStream. (~wrap-fn ~fsym))]
~generator-code))))
(defn as-sym
[sym & suffixes]
(symbol (apply str (name sym) suffixes)))
(defn symbol+
[sym suffix]
(cond (= suffix :*) (symbol (str (name sym) "*"))
suffix (symbol (str (name sym) "-" (name suffix)))
:else sym))
# # Generation
(defn generate
"Generate algorithm functions based on the given generators."
[generator code-gen f buffer-size]
(when (can-generate? generator code-gen)
(let [id (gensym (str "compute-" (name f)))]
`(do
~(generate-protocol generator code-gen id buffer-size)
~(generate-functions generator code-gen id f)))))
|
6c99bf11786af64f50515bb5078ff1f1258a97ed3015b62f5bc4d5ef297d24c7
|
jimcrayne/jhc
|
Typeable.hs
|
# OPTIONS_JHC -fffi -funboxed - values #
module Data.Typeable(TypeRep(),Typeable(..),Typeable1(..),Typeable2(..)) where
import Jhc.Prim
import Jhc.String
import Jhc.Prim.Basics
type String_ = BitsPtr_
data TypeRep = TypeRep String_ [TypeRep]
showsAddr__ :: String_ -> [Char] -> [Char]
showsAddr__ a xs = unpackStringFoldr a (:) xs
instance Show TypeRep where
showsPrec _ (TypeRep a []) = showsAddr__ a
showsPrec n (TypeRep a xs) = showParen (n > 9) $ spacesep (showsAddr__ a:map (showsPrec 10) xs) where
spacesep [] = id
spacesep [x] = x
spacesep (x:xs) = x . showChar ' ' . spacesep xs
instance Eq TypeRep where
TypeRep a xs == TypeRep b ys = case c_strcmp (Addr_ a) (Addr_ b) of
0 -> xs == ys
_ -> False
foreign import ccall "strcmp" c_strcmp :: Addr_ -> Addr_ -> Int
foreign import primitive : : a - > TypeRep
foreign import primitive ptypeOf1 : : t a - > TypeRep
foreign import primitive ptypeOf2 : : t a b - > TypeRep
foreign import primitive ptypeOf3 : : t a b c - > TypeRep
foreign import primitive ptypeOf4 : : t a b c d - > TypeRep
foreign import primitive ptypeOf5 : : t a b c d e - > TypeRep
foreign import primitive ptypeOf6 : : t a b c d e f - > TypeRep
foreign import primitive ptypeOf7 : : t a b c d e f g - > TypeRep
foreign import primitive typeRepEq : : TypeRep - > TypeRep - > Bool
foreign import primitive ptypeOf :: a -> TypeRep
foreign import primitive ptypeOf1 :: t a -> TypeRep
foreign import primitive ptypeOf2 :: t a b -> TypeRep
foreign import primitive ptypeOf3 :: t a b c -> TypeRep
foreign import primitive ptypeOf4 :: t a b c d -> TypeRep
foreign import primitive ptypeOf5 :: t a b c d e -> TypeRep
foreign import primitive ptypeOf6 :: t a b c d e f -> TypeRep
foreign import primitive ptypeOf7 :: t a b c d e f g -> TypeRep
foreign import primitive typeRepEq :: TypeRep -> TypeRep -> Bool
-}
class Typeable a where
typeOf :: a -> TypeRep
class Typeable1 f where
typeOf1 :: f a -> TypeRep
class Typeable2 f where
typeOf2 :: f a b -> TypeRep
instance Typeable1 [] where
typeOf1 _ = TypeRep "[]"# []
instance Typeable a => Typeable [a] where
typeOf x = typeOfDefault x
instance ( Typeable a , b ) = > ( a - > b ) where
typeOf x = ( typeOf2 x ` mkAppTy ` arg1 x ) ` mkAppTy ` arg2 x where
arg1 : : ( x - > y ) - > x
: : ( x - > y ) - > y
arg1 = undefined
= undefined
instance ( Typeable a ) = > Typeable1 ( ( - > ) a ) where
typeOf1 x = typeOf1Default x
instance Typeable2 ( - > ) where
typeOf2 _ = TypeRep " - > " # [ ]
instance (Typeable a,Typeable b) => Typeable (a -> b) where
typeOf x = (typeOf2 x `mkAppTy` arg1 x) `mkAppTy` arg2 x where
arg1 :: (x -> y) -> x
arg2 :: (x -> y) -> y
arg1 = undefined
arg2 = undefined
instance (Typeable a) => Typeable1 ((->) a) where
typeOf1 x = typeOf1Default x
instance Typeable2 (->) where
typeOf2 _ = TypeRep "->"# []
-}
instance Typeable2 (,) where
typeOf2 _ = TypeRep "(,)"# []
instance Typeable a => Typeable1 ((,) a) where
typeOf1 x = typeOf1Default x
instance (Typeable b,Typeable a) => Typeable (a,b) where
typeOf x = typeOfDefault x
instance Typeable Char where
typeOf _ = TypeRep "Char"# []
instance Typeable () where
typeOf _ = TypeRep "()"# []
instance Typeable Int where
typeOf _ = TypeRep "Int"# []
instance ( Typeable1 f , a ) = > ( f a ) where
= typeOf1 x ` mkAppTy ` typeOf ( argType x ) where
-- argType :: a b -> b
-- argType = undefined
mkAppTy :: TypeRep -> TypeRep -> TypeRep
mkAppTy (TypeRep x xs) tr = TypeRep x (xs ++ [tr])
-------------------------------------------------------------
--
-- Type-safe cast
--
-------------------------------------------------------------
unsafeCoerce :: a -> b
unsafeCoerce = unsafeCoerce__
-- | The type-safe cast operation
cast :: (Typeable a, Typeable b) => a -> Maybe b
cast x = r where
fromJust (Just x) = x
r = if typeOf x == typeOf (fromJust r)
then Just $ unsafeCoerce x
else Nothing
-- | A flexible variation parameterised in a type constructor
gcast : : ( a , b ) = > c a - > Maybe ( c b )
gcast x = r
where
r = if ( ) = = ( ( fromJust r ) )
then Just $ unsafeCoerce x
else Nothing
: : c x - > x
getArg = undefined
-- | Cast for * - > *
gcast1 : : ( Typeable1 t , Typeable1 t ' ) c ( t a ) - > Maybe ( c ( t ' a ) )
gcast1 x = r
where
r = if ( ) = = ( ( fromJust r ) )
then Just $ unsafeCoerce x
else Nothing
: : c x - > x
getArg = undefined
-- | Cast for * - > * - > *
gcast2 : : ( Typeable2 t , Typeable2 t ' ) c ( t a b ) - > Maybe ( c ( t ' a b ) )
gcast2 x = r
where
r = if typeOf2 ( ) = = typeOf2 ( ( fromJust r ) )
then Just $ unsafeCoerce x
else Nothing
: : c x - > x
getArg = undefined
-- | A flexible variation parameterised in a type constructor
gcast :: (Typeable a, Typeable b) => c a -> Maybe (c b)
gcast x = r
where
r = if typeOf (getArg x) == typeOf (getArg (fromJust r))
then Just $ unsafeCoerce x
else Nothing
getArg :: c x -> x
getArg = undefined
-- | Cast for * -> *
gcast1 :: (Typeable1 t, Typeable1 t') c (t a) -> Maybe (c (t' a))
gcast1 x = r
where
r = if typeOf1 (getArg x) == typeOf1 (getArg (fromJust r))
then Just $ unsafeCoerce x
else Nothing
getArg :: c x -> x
getArg = undefined
-- | Cast for * -> * -> *
gcast2 :: (Typeable2 t, Typeable2 t') c (t a b) -> Maybe (c (t' a b))
gcast2 x = r
where
r = if typeOf2 (getArg x) == typeOf2 (getArg (fromJust r))
then Just $ unsafeCoerce x
else Nothing
getArg :: c x -> x
getArg = undefined
-}
| For defining a ' Typeable ' instance from any ' Typeable1 ' instance .
typeOfDefault :: (Typeable1 t, Typeable a) => t a -> TypeRep
typeOfDefault x = typeOf1 x `mkAppTy` typeOf (argType x)
where
argType :: t a -> a
argType = undefined
-- | For defining a 'Typeable1' instance from any 'Typeable2' instance.
typeOf1Default :: (Typeable2 t, Typeable a) => t a b -> TypeRep
typeOf1Default x = typeOf2 x `mkAppTy` typeOf (argType x)
where
argType :: t a b -> a
argType = undefined
| null |
https://raw.githubusercontent.com/jimcrayne/jhc/1ff035af3d697f9175f8761c8d08edbffde03b4e/lib/haskell-extras/Data/Typeable.hs
|
haskell
|
argType :: a b -> b
argType = undefined
-----------------------------------------------------------
Type-safe cast
-----------------------------------------------------------
| The type-safe cast operation
| A flexible variation parameterised in a type constructor
| Cast for * - > *
| Cast for * - > * - > *
| A flexible variation parameterised in a type constructor
| Cast for * -> *
| Cast for * -> * -> *
| For defining a 'Typeable1' instance from any 'Typeable2' instance.
|
# OPTIONS_JHC -fffi -funboxed - values #
module Data.Typeable(TypeRep(),Typeable(..),Typeable1(..),Typeable2(..)) where
import Jhc.Prim
import Jhc.String
import Jhc.Prim.Basics
type String_ = BitsPtr_
data TypeRep = TypeRep String_ [TypeRep]
showsAddr__ :: String_ -> [Char] -> [Char]
showsAddr__ a xs = unpackStringFoldr a (:) xs
instance Show TypeRep where
showsPrec _ (TypeRep a []) = showsAddr__ a
showsPrec n (TypeRep a xs) = showParen (n > 9) $ spacesep (showsAddr__ a:map (showsPrec 10) xs) where
spacesep [] = id
spacesep [x] = x
spacesep (x:xs) = x . showChar ' ' . spacesep xs
instance Eq TypeRep where
TypeRep a xs == TypeRep b ys = case c_strcmp (Addr_ a) (Addr_ b) of
0 -> xs == ys
_ -> False
foreign import ccall "strcmp" c_strcmp :: Addr_ -> Addr_ -> Int
foreign import primitive : : a - > TypeRep
foreign import primitive ptypeOf1 : : t a - > TypeRep
foreign import primitive ptypeOf2 : : t a b - > TypeRep
foreign import primitive ptypeOf3 : : t a b c - > TypeRep
foreign import primitive ptypeOf4 : : t a b c d - > TypeRep
foreign import primitive ptypeOf5 : : t a b c d e - > TypeRep
foreign import primitive ptypeOf6 : : t a b c d e f - > TypeRep
foreign import primitive ptypeOf7 : : t a b c d e f g - > TypeRep
foreign import primitive typeRepEq : : TypeRep - > TypeRep - > Bool
foreign import primitive ptypeOf :: a -> TypeRep
foreign import primitive ptypeOf1 :: t a -> TypeRep
foreign import primitive ptypeOf2 :: t a b -> TypeRep
foreign import primitive ptypeOf3 :: t a b c -> TypeRep
foreign import primitive ptypeOf4 :: t a b c d -> TypeRep
foreign import primitive ptypeOf5 :: t a b c d e -> TypeRep
foreign import primitive ptypeOf6 :: t a b c d e f -> TypeRep
foreign import primitive ptypeOf7 :: t a b c d e f g -> TypeRep
foreign import primitive typeRepEq :: TypeRep -> TypeRep -> Bool
-}
class Typeable a where
typeOf :: a -> TypeRep
class Typeable1 f where
typeOf1 :: f a -> TypeRep
class Typeable2 f where
typeOf2 :: f a b -> TypeRep
instance Typeable1 [] where
typeOf1 _ = TypeRep "[]"# []
instance Typeable a => Typeable [a] where
typeOf x = typeOfDefault x
instance ( Typeable a , b ) = > ( a - > b ) where
typeOf x = ( typeOf2 x ` mkAppTy ` arg1 x ) ` mkAppTy ` arg2 x where
arg1 : : ( x - > y ) - > x
: : ( x - > y ) - > y
arg1 = undefined
= undefined
instance ( Typeable a ) = > Typeable1 ( ( - > ) a ) where
typeOf1 x = typeOf1Default x
instance Typeable2 ( - > ) where
typeOf2 _ = TypeRep " - > " # [ ]
instance (Typeable a,Typeable b) => Typeable (a -> b) where
typeOf x = (typeOf2 x `mkAppTy` arg1 x) `mkAppTy` arg2 x where
arg1 :: (x -> y) -> x
arg2 :: (x -> y) -> y
arg1 = undefined
arg2 = undefined
instance (Typeable a) => Typeable1 ((->) a) where
typeOf1 x = typeOf1Default x
instance Typeable2 (->) where
typeOf2 _ = TypeRep "->"# []
-}
instance Typeable2 (,) where
typeOf2 _ = TypeRep "(,)"# []
instance Typeable a => Typeable1 ((,) a) where
typeOf1 x = typeOf1Default x
instance (Typeable b,Typeable a) => Typeable (a,b) where
typeOf x = typeOfDefault x
instance Typeable Char where
typeOf _ = TypeRep "Char"# []
instance Typeable () where
typeOf _ = TypeRep "()"# []
instance Typeable Int where
typeOf _ = TypeRep "Int"# []
instance ( Typeable1 f , a ) = > ( f a ) where
= typeOf1 x ` mkAppTy ` typeOf ( argType x ) where
mkAppTy :: TypeRep -> TypeRep -> TypeRep
mkAppTy (TypeRep x xs) tr = TypeRep x (xs ++ [tr])
unsafeCoerce :: a -> b
unsafeCoerce = unsafeCoerce__
cast :: (Typeable a, Typeable b) => a -> Maybe b
cast x = r where
fromJust (Just x) = x
r = if typeOf x == typeOf (fromJust r)
then Just $ unsafeCoerce x
else Nothing
gcast : : ( a , b ) = > c a - > Maybe ( c b )
gcast x = r
where
r = if ( ) = = ( ( fromJust r ) )
then Just $ unsafeCoerce x
else Nothing
: : c x - > x
getArg = undefined
gcast1 : : ( Typeable1 t , Typeable1 t ' ) c ( t a ) - > Maybe ( c ( t ' a ) )
gcast1 x = r
where
r = if ( ) = = ( ( fromJust r ) )
then Just $ unsafeCoerce x
else Nothing
: : c x - > x
getArg = undefined
gcast2 : : ( Typeable2 t , Typeable2 t ' ) c ( t a b ) - > Maybe ( c ( t ' a b ) )
gcast2 x = r
where
r = if typeOf2 ( ) = = typeOf2 ( ( fromJust r ) )
then Just $ unsafeCoerce x
else Nothing
: : c x - > x
getArg = undefined
gcast :: (Typeable a, Typeable b) => c a -> Maybe (c b)
gcast x = r
where
r = if typeOf (getArg x) == typeOf (getArg (fromJust r))
then Just $ unsafeCoerce x
else Nothing
getArg :: c x -> x
getArg = undefined
gcast1 :: (Typeable1 t, Typeable1 t') c (t a) -> Maybe (c (t' a))
gcast1 x = r
where
r = if typeOf1 (getArg x) == typeOf1 (getArg (fromJust r))
then Just $ unsafeCoerce x
else Nothing
getArg :: c x -> x
getArg = undefined
gcast2 :: (Typeable2 t, Typeable2 t') c (t a b) -> Maybe (c (t' a b))
gcast2 x = r
where
r = if typeOf2 (getArg x) == typeOf2 (getArg (fromJust r))
then Just $ unsafeCoerce x
else Nothing
getArg :: c x -> x
getArg = undefined
-}
| For defining a ' Typeable ' instance from any ' Typeable1 ' instance .
typeOfDefault :: (Typeable1 t, Typeable a) => t a -> TypeRep
typeOfDefault x = typeOf1 x `mkAppTy` typeOf (argType x)
where
argType :: t a -> a
argType = undefined
typeOf1Default :: (Typeable2 t, Typeable a) => t a b -> TypeRep
typeOf1Default x = typeOf2 x `mkAppTy` typeOf (argType x)
where
argType :: t a b -> a
argType = undefined
|
7d72006c030c00d19e33c25cc9a2de53af1b6e19594c328a01f7f75278a2edac
|
wesen/ruinwesen
|
html.lisp
|
(in-package :md)
(enable-prototype-syntax)
(enable-interpol-syntax)
(defparameter *host-prefix* ":4242")
(defparameter *elektron-prefix* "/md/")
(defparameter *elektron-dir* "/home/manuel/elektron-dir/")
(defparameter *image-cache-dir* (merge-pathnames
(make-pathname :directory '(:relative "image-cache"))
*elektron-dir*))
(defparameter *logfile* "/tmp/elektron.log")
(defvar *elektron-server*)
(defvar *dispatch-table*)
(defparameter *elektron-css-file* "/files/elektron.css")
(defvar *main-page-uri* "/index")
(defvar *files-uri* "/files/")
(defvar *ajax-uri* "/ajax")
(defun param-map (str assoc)
(cdr (assoc str assoc :test #'string-equal)))
(defgeneric object-to-html (object))
(defmacro md-img-text (text &optional scale &rest foobar)
`(with-html-output (*standard-output* nil)
(:img :src (format nil "/text-image/~a~A" ,text ,(if scale (format nil "?scale=~A" scale) ""))
:alt ,text ,@foobar)))
(defmethod object-to-html ((kit kit))
(with-html-output-to-string (*standard-output* nil)
((:div :class "mdobject" :id (format nil "md-~A" (store-object-id kit)))
(md-img-text "KIT" 2 :class "handle") :br
(md-img-text (md-object-name kit)) :br
(when (md-object-user kit)
(md-img-text (md-user-name (md-object-user kit)))))))
(defmethod object-to-html ((song md-song))
(with-html-output-to-string (*standard-output* nil)
((:div :class "mdobject" :id (format nil "md-~A" (store-object-id song)))
(md-img-text "SONG" 2 :class "handle") :br
((:a :href (format nil "/image/song/~a?scale=2"
(store-object-id song))
:rel "lightbox[song]")
(md-img-text (md-object-name song))) :br
(when (md-object-user song)
(md-img-text (md-user-name (md-object-user song)))))))
(defmethod object-to-html ((pattern md-pattern))
(with-html-output-to-string (*standard-output* nil)
((:div :class "mdobject" :id (format nil "md-~A" (store-object-id pattern)))
(md-img-text "PATTERN" 2 :class "handle") :br
(md-img-text (symbol-name (pattern-name (md-pattern-position pattern)))) :br
(md-img-text (if (md-pattern-kit pattern)
(md-object-name (md-pattern-kit pattern))
"NO KIT")) :br
(when (md-object-user pattern)
(md-img-text (md-user-name (md-object-user pattern)))))))
(defmethod object-to-html ((machine machine))
(with-html-output-to-string (*standard-output* nil)
((:div :class "mdcontainer"
:onmouseover (format nil "javascript:showMdobjectFunctions($(\"func-~A\"), ~A)"
(store-object-id machine)
(store-object-id machine))
)
((:div :class "mdobject" :id (format nil "md-~A" (store-object-id machine)))
(md-img-text "MACHINE" 2 :class "handle") :br
((:a :href (format nil "/image/machine/~a?scale=2"
(store-object-id machine))
:rel "lightbox[machine]")
(md-img-text (machine-name (machine-model machine))) :br
(md-img-text (if (machine-kit machine)
(md-object-name (machine-kit machine))
"NO KIT"))) :br
(when (md-object-user machine)
(md-img-text (md-user-name (md-object-user machine)))))
((:div :id (format nil "func-~A" (store-object-id machine)))))))
(defmethod object-to-html ((user md-user))
(with-html-output-to-string (*standard-output* nil)
((:div :class "mdobject" :id (format nil "md-~A" (store-object-id user)))
(md-img-text "USER" 2 :class "handle") :br
(md-img-text (md-user-name user)))))
(defmethod object-to-html ((import md-import))
(with-html-output-to-string (*standard-output* nil)
((:div :class "mdobject" :id (format nil "md-~A" (store-object-id import)))
(md-img-text "SYSEX" 2 :class "handle") :br
(md-img-text (md-object-name import)) :br
(when (md-object-user import)
(md-img-text (md-user-name (md-object-user import)))))))
(defun start-distance (idx start count)
(abs (floor (/ (- start (* idx count)) count))))
(defun html-search-nav (start count length)
(with-html-output-to-string (*standard-output* nil)
((:div :class "searchnav")
(md-img-text "Results:" 2)
(loop for idx from 0
for strt from 0 by count upto length
for end = (+ strt count)
for distance = (start-distance idx start count)
do (cond ((= distance 0)
(md-img-text idx 2) (princ " "))
((or (< distance 4)
(= idx 0)
(< (start-distance idx length count) 1))
(with-html-output (*standard-output* nil)
((:a :href "#" :onclick (format nil "javascript:searchResults(~A, ~A)"
strt count))
(md-img-text idx 2)) " "))
((< distance 5)
(md-img-text "..." 2) (princ " ")
))))))
(defun html-object-list (objects &key (count 32) (start 0))
(with-output-to-string (s)
(let ((length (length objects)))
(with-html-output (s nil)
(:div
(dolist (obj (subseq objects start (min length (+ start count))))
(princ (object-to-html obj) s)
(princ #\Newline s))))
(princ (html-search-nav start count length) s))))
(defun-ajax md-list (type (start "0") (count "32"))
(let* ((class (param-map type '(("songs" . md-song)
("song" . md-song)
("patterns" . md-pattern)
("pattern" . md-pattern)
("kits" . kit)
("kit" . kit)
("machines" . machine)
("machine" . machine)
("sysex" . md-import))))
(start (or (parse-integer start :junk-allowed t) 0))
(count (or (parse-integer count :junk-allowed t) 32)))
;;; check rights XXX
(html-object-list (store-objects-with-class class) :count count :start start)))
(defun-ajax md-search (query type (count "32") (start "0"))
(let* ((type2 (param-map type '(("songs" . "song")
("patterns" . "pattern")
("kits" . "kit")
("machines" . "machine")
("sysex" . "import"))))
(start (or (parse-integer start :junk-allowed t) 0))
(count (or (parse-integer count :junk-allowed t) 32))
(res (montezuma-get (format nil "+\"~A\" +type:\"~A\"" query type2)
:num-docs count :first-doc start)))
;;; check rights XXX
(html-object-list (mapcar #'first (sort res #'> :key #'second)) :count 20000)))
(defun extract-id (id)
(when id
(multiple-value-bind (match strings)
(scan-to-strings #?r"md-([0-9]+)" id)
(when match
(parse-integer (aref strings 0))))))
(defun user-get-object (id)
(store-object-with-id id))
;; XXX ajax error handling
(defun-ajax add-to-dropbox (id)
(let ((id (extract-id id)))
(format t "parsed id ~A~%" id)
(when id
(let ((obj (user-get-object id)))
(when (< (length (session-value 'dropbox)) 64)
(pushnew obj (session-value 'dropbox))))))
"")
(defun-ajax remove-from-dropbox (id)
(let ((id (extract-id id)))
(format t "parsed id ~A~%" id)
(when id
(let ((obj (user-get-object id)))
(when (member obj (session-value 'dropbox))
(setf (session-value 'dropbox)
(remove obj (session-value 'dropbox)))))))
"")
(defun-ajax dropbox ()
(html-object-list (session-value 'dropbox)))
(defun-ajax stored ()
(html-object-list nil))
(defun start-elektron (&key port)
(setf (hunchentoot:log-file) (make-pathname :defaults *logfile*))
(ensure-directories-exist *elektron-dir*)
(setf *elektron-server*
(hunchentoot:start-server
:port port
:dispatch-table
(list (hunchentoot:create-prefix-dispatcher *main-page-uri* 'md-main-page)
(hunchentoot:create-prefix-dispatcher "/test" 'test-page)
(hunchentoot:create-prefix-dispatcher "/bla" 'test2-page)
(create-function-dispatcher "/ajax/" (list 'ajax-test 'md-list
'md-search
'add-to-dropbox 'remove-from-dropbox
'dropbox
'stored))
(hunchentoot:create-prefix-dispatcher "/image/" 'image-page)
(hunchentoot:create-prefix-dispatcher "/text-image/" 'text-image-page)
(hunchentoot:create-folder-dispatcher-and-handler
*files-uri*
(make-pathname :defaults *elektron-dir*))
'md-main-page))))
(defun stop-elektron ()
(hunchentoot:stop-server *elektron-server*))
(defun test2-page ()
(with-html-output-to-string (*standard-output* nil :prologue t :indent t)
((:html :xmlns "" "en" :lang "en")
(:head (:title "ELEKTRON MD CONVERTER")
#+nil(str (generate-prologue *ajax-processor*))
(:script :type "text/javascript" :src "/files/js/prototype.js")
(:script :type "text/javascript" :src "/files/js/scriptaculous.js")
(:script :type "text/javascript" :src "/files/js/lightbox.js")
(:link :href "/files/lightbox.css" :rel "stylesheet" :type "text/css"))
(:body
((:a :href "/text-image/foo?scale=4" :rel "lightbox")
(:img :src "/text-image/foo"))))))
(defun test-page ()
(start-session)
(with-html-output-to-string (*standard-output* nil :prologue t :indent t)
((:html :xmlns "" "en" :lang "en")
(:head (:title "ELEKTRON MD CONVERTER")
#+nil(str (generate-prologue *ajax-processor*))
(:script :type "text/javascript" :src "/files/js/prototype.js")
(:script :type "text/javascript" :src "/files/js/scriptaculous.js")
(:script :type "text/javascript" :src "/files/js/lightbox.js")
(:link :href *elektron-css-file* :rel "stylesheet" :type "text/css")
(:link :href "/files/lightbox.css" :rel "stylesheet" :type "text/css")
(js-script
(defvar search-type "kits")
(defvar search-style "")
(defvar search-query "")
(defvar search-ajax nil)
(defvar result-drags $A(list))
(defun show-select ()
(.show $("select"))
(setf (slot-value $("q") 'value) ""))
(defun hide-select ()
(.hide $("select")))
(defun select (type)
(let ((elt $(type))
(sels $$(".selected")))
(when sels
(sels.each (lambda (x) (setf x.class-name ""))))
(setf search-type type)
(setf elt.class-name "selected")
(show-select)
(list-type type)))
(defun show-help (message)
(new (-effect.-fade $("help") (create :duration 0.3
:after-finish (lambda ()
(setf (slot-value $("help") 'inner-h-t-m-l)
message)))))
(new (-effect.-appear $("help")
(create :duration 0.3 :queue "end")))
)
(defun show-hint (message)
(let ((elt $("help")))
(unless elt.old-messages
(setf elt.old-messages (list)))
(elt.old-messages.push elt.inner-h-t-m-l)
(setf elt.inner-h-t-m-l message)))
(defun hide-hint ()
(let ((elt $("help")))
(when elt.old-messages
(let ((message (elt.old-messages.pop)))
(when message
(setf elt.inner-h-t-m-l message))))))
(defun open-lightbox(anchor)
(unless (= (typeof my-lightbox)
"undefined")
(my-lightbox.start anchor)))
(defun show-mdobject-functions (elt id)
;; dock style XXX
(let ((funcs $("mdobjectfuncs")))
(unless (and funcs
(not (= (.index-of $A((elt.child-elements)) funcs) -1)))
(when funcs
(funcs.remove))
(+= elt.inner-h-t-m-l (html ((:div :id "mdobjectfuncs" :style "display:none")
((:img :src "/text-image/EDIT"))
" "
((:a :href (+ "/image/object/" id "?scale=2")
:onclick (js-inline
(open-lightbox this)
(return false)))
((:img :src "/text-image/VIEW"))))))
(-effect.-blind-down "mdobjectfuncs" (create :duration 0.5)))))
(defun hide-mdobject-functions ()
(let ((elt $("mdobjectfuncs")))
(when elt
(new (-effect.-blind-up elt (create :duration 0.5
:after-finish (lambda () (elt.remove))))))))
(defun page-load-finished ()
(select "kits"))
(defun add-to-dropbox (id)
(new (-ajax.-request "/ajax/add-to-dropbox"
(create :method "post"
:parameters (create :id id)
:asynchronous t
:on-success (lambda (transport)
(when (= search-type "dropbox")
(list-type "dropbox")))))))
(defun remove-from-dropbox (elt)
(new (-ajax.-request "/ajax/remove-from-dropbox"
(create :method "post"
:parameters (create :id elt.id)
:asynchronous t
:on-success (lambda (transport)
(new (-effect.-puff
elt
(create :duration 0.5)))
#+nil(list-type "dropbox"))))))
(defun refresh-draggables ()
(.each result-drags (lambda (x) (.destroy x)))
(setf result-drags $A(list))
(.each $$(".mdobject")
(lambda (x) (let ((drag
(new (-Draggable x.id
(create :revert t
:handle "handle")))))
(.push result-drags drag))))
(show-help "Drag and drop items by dragging on their title. Add an item to your dropbox by dragging it over the dropbox item.")
)
(defun ajax-results (url params)
(unless params
(setf params (create)))
(setf params.on-complete
refresh-draggables)
(new (-Ajax.-Updater "results" url params)))
(defun search-results (start count)
(cond ((= search-style "list")
(list-type search-type start count))
((= search-style "search")
(search search-query start count))))
(defun list-type (type (start 0) (count 32))
(setf search-style "list")
(cond
((= type "dropbox")
(ajax-results "/ajax/dropbox"))
((= type "stored")
(ajax-results "/ajax/stored"))
(t (ajax-results "/ajax/md-list"
(create :parameters
(create :type search-type
:start start
:count count))))))
(defun search ((my-search-query (slot-value $("q") 'value))
(start 0) (count 32))
(setf search-style "search")
(setf search-query my-search-query)
(ajax-results "/ajax/md-search"
(create :parameters
(create :type search-type
:query search-query
:start start
:count count))))
))
((:body :bgcolor "#ffffff" :color "#000000" :onload (js:js-inline (page-load-finished)))
((:div :id "container")
((:div :id "categories")
((:ul :class "nav")
((:li :id "sysex")
((:a :href "#" :onclick (js:js-inline (select "sysex")))
(md-img-text "SYSEX" 2)))
((:li :id "kits")
((:a :href "#" :onclick (js:js-inline (select "kits")))
(md-img-text "KITS" 2)))
((:li :id "machines")
((:a :href "#" :onclick (js:js-inline (select "machines")))
(md-img-text "MACHINES" 2)))
((:li :id "songs")
((:a :href "#" :onclick (js:js-inline (select "songs")))
(md-img-text "SONGS" 2)))
((:li :id "wavs")
((:a :href "#" :onclick (js:js-inline (select "wavs")))
(md-img-text "WAVS" 2)))
((:li :id "midis")
((:a :href "#" :onclick (js:js-inline (select "midis")))
(md-img-text "MIDIS" 2)))
((:li :id "users")
((:a :href "#" :onclick (js:js-inline (select "users")))
(md-img-text "USERS" 2)))
((:li :id "stored")
((:a :href "#" :onclick (js:js-inline (select "stored")))
(md-img-text "STORED" 2)))
((:li :id "dropbox")
((:a :href "#" :onclick (js:js-inline (select "dropbox")))
(md-img-text "DROPBOX" 2)))
((:li :id "trash")
(md-img-text "TRASH" 2))))
(js-script (-droppables.add "trash"
(create :on-drop (lambda (drag drop evt)
(when (= search-type "dropbox")
(remove-from-dropbox drag)
(new (-effect.-pulsate
drop
(create :pulses 2
:duration 0.5
:from 0.2))))
)
:hoverclass "drophover")))
(js-script (-droppables.add "dropbox"
(create :on-drop (lambda (drag drop evt)
(add-to-dropbox drag.id)
(new (-effect.-pulsate
drop
(create :pulses 2
:duration 0.5
:from 0.2))))
:hoverclass "drophover")))
((:div :id "select")
(:form :action (js:js-inline (search))
(:input :class "simage" :type "image"
:src "/text-image/search:?scale=2")
(:input :id "q" :type "search" :name "q")))
((:div :id "helpholder")
((:div :id "help") "Welcome to MD Editor"))
((:div :id "results"))
)))))
(defmacro with-elektron-page ((&rest params) &rest body)
`(with-html-output-to-string (,@params)
(:html
(:head (:title "ELEKTRON MD CONVERTER")
(:link :rel "shortcut icon" :type "image/x-icon" :href "/files/favicon.ico")
#+nil(:link :href *elektron-css-file* :rel "stylesheet" :type "text/css"))
((:body :bgcolor "#ffffff" :color "#000000")
(:div :align :center
:br :br
(:img :src "/files/pngs/md-sysex.png" :border 0 :alt "MD SYSEX CONVERTER")
:br :br
,@body)))))
(defmacro with-sub-elektron-page ((s title i big &rest params) &rest body)
`(with-html-output (,s nil :indent t ,@params)
(:html
(:head (:title ,title)
(:link :rel "shortcut icon" :type "image/x-icon" :href "/files/favicon.ico"))
((:body :bgcolor "#ffffff" :color "#000000")
(:div :align :center ((:a :href (format nil "/files/~A.html" ,i))
(:img :src ,(if big "/files/sps1-uw.jpg"
"/files/sps1-uw-small.jpg")
:border 0
:alt "image of sps1 uw (c) hageir")
:br :br
(:img :src ,(if big `(format nil "/files/filename-~A.gif" ,i)
"/files/pngs/back.png")
:border 0
:alt ,(if big "FILENAME" "BACK")))
:br :br
,@body)))))
(defun error-page ()
(with-elektron-page (*standard-output* nil :prologue t :indent t)
(:img :src "/files/pngs/sysex-error.png" :border 0
:alt "ERROR IN THE SYSEX FILE! PLEASE UPLOAD AGAIN:")
:br :br
((:form :method :post :enctype "multipart/form-data")
(:input :type "file" :name "test" :maxlength "500000") :br :br
(:input :type :submit :name "upload" :value "UPLOAD"))))
| null |
https://raw.githubusercontent.com/wesen/ruinwesen/9f3ccea85425cf46b57e76144b3114ca342bad0f/md-uw/src/web/html.lisp
|
lisp
|
check rights XXX
check rights XXX
XXX ajax error handling
dock style XXX
|
(in-package :md)
(enable-prototype-syntax)
(enable-interpol-syntax)
(defparameter *host-prefix* ":4242")
(defparameter *elektron-prefix* "/md/")
(defparameter *elektron-dir* "/home/manuel/elektron-dir/")
(defparameter *image-cache-dir* (merge-pathnames
(make-pathname :directory '(:relative "image-cache"))
*elektron-dir*))
(defparameter *logfile* "/tmp/elektron.log")
(defvar *elektron-server*)
(defvar *dispatch-table*)
(defparameter *elektron-css-file* "/files/elektron.css")
(defvar *main-page-uri* "/index")
(defvar *files-uri* "/files/")
(defvar *ajax-uri* "/ajax")
(defun param-map (str assoc)
(cdr (assoc str assoc :test #'string-equal)))
(defgeneric object-to-html (object))
(defmacro md-img-text (text &optional scale &rest foobar)
`(with-html-output (*standard-output* nil)
(:img :src (format nil "/text-image/~a~A" ,text ,(if scale (format nil "?scale=~A" scale) ""))
:alt ,text ,@foobar)))
(defmethod object-to-html ((kit kit))
(with-html-output-to-string (*standard-output* nil)
((:div :class "mdobject" :id (format nil "md-~A" (store-object-id kit)))
(md-img-text "KIT" 2 :class "handle") :br
(md-img-text (md-object-name kit)) :br
(when (md-object-user kit)
(md-img-text (md-user-name (md-object-user kit)))))))
(defmethod object-to-html ((song md-song))
(with-html-output-to-string (*standard-output* nil)
((:div :class "mdobject" :id (format nil "md-~A" (store-object-id song)))
(md-img-text "SONG" 2 :class "handle") :br
((:a :href (format nil "/image/song/~a?scale=2"
(store-object-id song))
:rel "lightbox[song]")
(md-img-text (md-object-name song))) :br
(when (md-object-user song)
(md-img-text (md-user-name (md-object-user song)))))))
(defmethod object-to-html ((pattern md-pattern))
(with-html-output-to-string (*standard-output* nil)
((:div :class "mdobject" :id (format nil "md-~A" (store-object-id pattern)))
(md-img-text "PATTERN" 2 :class "handle") :br
(md-img-text (symbol-name (pattern-name (md-pattern-position pattern)))) :br
(md-img-text (if (md-pattern-kit pattern)
(md-object-name (md-pattern-kit pattern))
"NO KIT")) :br
(when (md-object-user pattern)
(md-img-text (md-user-name (md-object-user pattern)))))))
(defmethod object-to-html ((machine machine))
(with-html-output-to-string (*standard-output* nil)
((:div :class "mdcontainer"
:onmouseover (format nil "javascript:showMdobjectFunctions($(\"func-~A\"), ~A)"
(store-object-id machine)
(store-object-id machine))
)
((:div :class "mdobject" :id (format nil "md-~A" (store-object-id machine)))
(md-img-text "MACHINE" 2 :class "handle") :br
((:a :href (format nil "/image/machine/~a?scale=2"
(store-object-id machine))
:rel "lightbox[machine]")
(md-img-text (machine-name (machine-model machine))) :br
(md-img-text (if (machine-kit machine)
(md-object-name (machine-kit machine))
"NO KIT"))) :br
(when (md-object-user machine)
(md-img-text (md-user-name (md-object-user machine)))))
((:div :id (format nil "func-~A" (store-object-id machine)))))))
(defmethod object-to-html ((user md-user))
(with-html-output-to-string (*standard-output* nil)
((:div :class "mdobject" :id (format nil "md-~A" (store-object-id user)))
(md-img-text "USER" 2 :class "handle") :br
(md-img-text (md-user-name user)))))
(defmethod object-to-html ((import md-import))
(with-html-output-to-string (*standard-output* nil)
((:div :class "mdobject" :id (format nil "md-~A" (store-object-id import)))
(md-img-text "SYSEX" 2 :class "handle") :br
(md-img-text (md-object-name import)) :br
(when (md-object-user import)
(md-img-text (md-user-name (md-object-user import)))))))
(defun start-distance (idx start count)
(abs (floor (/ (- start (* idx count)) count))))
(defun html-search-nav (start count length)
(with-html-output-to-string (*standard-output* nil)
((:div :class "searchnav")
(md-img-text "Results:" 2)
(loop for idx from 0
for strt from 0 by count upto length
for end = (+ strt count)
for distance = (start-distance idx start count)
do (cond ((= distance 0)
(md-img-text idx 2) (princ " "))
((or (< distance 4)
(= idx 0)
(< (start-distance idx length count) 1))
(with-html-output (*standard-output* nil)
((:a :href "#" :onclick (format nil "javascript:searchResults(~A, ~A)"
strt count))
(md-img-text idx 2)) " "))
((< distance 5)
(md-img-text "..." 2) (princ " ")
))))))
(defun html-object-list (objects &key (count 32) (start 0))
(with-output-to-string (s)
(let ((length (length objects)))
(with-html-output (s nil)
(:div
(dolist (obj (subseq objects start (min length (+ start count))))
(princ (object-to-html obj) s)
(princ #\Newline s))))
(princ (html-search-nav start count length) s))))
(defun-ajax md-list (type (start "0") (count "32"))
(let* ((class (param-map type '(("songs" . md-song)
("song" . md-song)
("patterns" . md-pattern)
("pattern" . md-pattern)
("kits" . kit)
("kit" . kit)
("machines" . machine)
("machine" . machine)
("sysex" . md-import))))
(start (or (parse-integer start :junk-allowed t) 0))
(count (or (parse-integer count :junk-allowed t) 32)))
(html-object-list (store-objects-with-class class) :count count :start start)))
(defun-ajax md-search (query type (count "32") (start "0"))
(let* ((type2 (param-map type '(("songs" . "song")
("patterns" . "pattern")
("kits" . "kit")
("machines" . "machine")
("sysex" . "import"))))
(start (or (parse-integer start :junk-allowed t) 0))
(count (or (parse-integer count :junk-allowed t) 32))
(res (montezuma-get (format nil "+\"~A\" +type:\"~A\"" query type2)
:num-docs count :first-doc start)))
(html-object-list (mapcar #'first (sort res #'> :key #'second)) :count 20000)))
(defun extract-id (id)
(when id
(multiple-value-bind (match strings)
(scan-to-strings #?r"md-([0-9]+)" id)
(when match
(parse-integer (aref strings 0))))))
(defun user-get-object (id)
(store-object-with-id id))
(defun-ajax add-to-dropbox (id)
(let ((id (extract-id id)))
(format t "parsed id ~A~%" id)
(when id
(let ((obj (user-get-object id)))
(when (< (length (session-value 'dropbox)) 64)
(pushnew obj (session-value 'dropbox))))))
"")
(defun-ajax remove-from-dropbox (id)
(let ((id (extract-id id)))
(format t "parsed id ~A~%" id)
(when id
(let ((obj (user-get-object id)))
(when (member obj (session-value 'dropbox))
(setf (session-value 'dropbox)
(remove obj (session-value 'dropbox)))))))
"")
(defun-ajax dropbox ()
(html-object-list (session-value 'dropbox)))
(defun-ajax stored ()
(html-object-list nil))
(defun start-elektron (&key port)
(setf (hunchentoot:log-file) (make-pathname :defaults *logfile*))
(ensure-directories-exist *elektron-dir*)
(setf *elektron-server*
(hunchentoot:start-server
:port port
:dispatch-table
(list (hunchentoot:create-prefix-dispatcher *main-page-uri* 'md-main-page)
(hunchentoot:create-prefix-dispatcher "/test" 'test-page)
(hunchentoot:create-prefix-dispatcher "/bla" 'test2-page)
(create-function-dispatcher "/ajax/" (list 'ajax-test 'md-list
'md-search
'add-to-dropbox 'remove-from-dropbox
'dropbox
'stored))
(hunchentoot:create-prefix-dispatcher "/image/" 'image-page)
(hunchentoot:create-prefix-dispatcher "/text-image/" 'text-image-page)
(hunchentoot:create-folder-dispatcher-and-handler
*files-uri*
(make-pathname :defaults *elektron-dir*))
'md-main-page))))
(defun stop-elektron ()
(hunchentoot:stop-server *elektron-server*))
(defun test2-page ()
(with-html-output-to-string (*standard-output* nil :prologue t :indent t)
((:html :xmlns "" "en" :lang "en")
(:head (:title "ELEKTRON MD CONVERTER")
#+nil(str (generate-prologue *ajax-processor*))
(:script :type "text/javascript" :src "/files/js/prototype.js")
(:script :type "text/javascript" :src "/files/js/scriptaculous.js")
(:script :type "text/javascript" :src "/files/js/lightbox.js")
(:link :href "/files/lightbox.css" :rel "stylesheet" :type "text/css"))
(:body
((:a :href "/text-image/foo?scale=4" :rel "lightbox")
(:img :src "/text-image/foo"))))))
(defun test-page ()
(start-session)
(with-html-output-to-string (*standard-output* nil :prologue t :indent t)
((:html :xmlns "" "en" :lang "en")
(:head (:title "ELEKTRON MD CONVERTER")
#+nil(str (generate-prologue *ajax-processor*))
(:script :type "text/javascript" :src "/files/js/prototype.js")
(:script :type "text/javascript" :src "/files/js/scriptaculous.js")
(:script :type "text/javascript" :src "/files/js/lightbox.js")
(:link :href *elektron-css-file* :rel "stylesheet" :type "text/css")
(:link :href "/files/lightbox.css" :rel "stylesheet" :type "text/css")
(js-script
(defvar search-type "kits")
(defvar search-style "")
(defvar search-query "")
(defvar search-ajax nil)
(defvar result-drags $A(list))
(defun show-select ()
(.show $("select"))
(setf (slot-value $("q") 'value) ""))
(defun hide-select ()
(.hide $("select")))
(defun select (type)
(let ((elt $(type))
(sels $$(".selected")))
(when sels
(sels.each (lambda (x) (setf x.class-name ""))))
(setf search-type type)
(setf elt.class-name "selected")
(show-select)
(list-type type)))
(defun show-help (message)
(new (-effect.-fade $("help") (create :duration 0.3
:after-finish (lambda ()
(setf (slot-value $("help") 'inner-h-t-m-l)
message)))))
(new (-effect.-appear $("help")
(create :duration 0.3 :queue "end")))
)
(defun show-hint (message)
(let ((elt $("help")))
(unless elt.old-messages
(setf elt.old-messages (list)))
(elt.old-messages.push elt.inner-h-t-m-l)
(setf elt.inner-h-t-m-l message)))
(defun hide-hint ()
(let ((elt $("help")))
(when elt.old-messages
(let ((message (elt.old-messages.pop)))
(when message
(setf elt.inner-h-t-m-l message))))))
(defun open-lightbox(anchor)
(unless (= (typeof my-lightbox)
"undefined")
(my-lightbox.start anchor)))
(defun show-mdobject-functions (elt id)
(let ((funcs $("mdobjectfuncs")))
(unless (and funcs
(not (= (.index-of $A((elt.child-elements)) funcs) -1)))
(when funcs
(funcs.remove))
(+= elt.inner-h-t-m-l (html ((:div :id "mdobjectfuncs" :style "display:none")
((:img :src "/text-image/EDIT"))
" "
((:a :href (+ "/image/object/" id "?scale=2")
:onclick (js-inline
(open-lightbox this)
(return false)))
((:img :src "/text-image/VIEW"))))))
(-effect.-blind-down "mdobjectfuncs" (create :duration 0.5)))))
(defun hide-mdobject-functions ()
(let ((elt $("mdobjectfuncs")))
(when elt
(new (-effect.-blind-up elt (create :duration 0.5
:after-finish (lambda () (elt.remove))))))))
(defun page-load-finished ()
(select "kits"))
(defun add-to-dropbox (id)
(new (-ajax.-request "/ajax/add-to-dropbox"
(create :method "post"
:parameters (create :id id)
:asynchronous t
:on-success (lambda (transport)
(when (= search-type "dropbox")
(list-type "dropbox")))))))
(defun remove-from-dropbox (elt)
(new (-ajax.-request "/ajax/remove-from-dropbox"
(create :method "post"
:parameters (create :id elt.id)
:asynchronous t
:on-success (lambda (transport)
(new (-effect.-puff
elt
(create :duration 0.5)))
#+nil(list-type "dropbox"))))))
(defun refresh-draggables ()
(.each result-drags (lambda (x) (.destroy x)))
(setf result-drags $A(list))
(.each $$(".mdobject")
(lambda (x) (let ((drag
(new (-Draggable x.id
(create :revert t
:handle "handle")))))
(.push result-drags drag))))
(show-help "Drag and drop items by dragging on their title. Add an item to your dropbox by dragging it over the dropbox item.")
)
(defun ajax-results (url params)
(unless params
(setf params (create)))
(setf params.on-complete
refresh-draggables)
(new (-Ajax.-Updater "results" url params)))
(defun search-results (start count)
(cond ((= search-style "list")
(list-type search-type start count))
((= search-style "search")
(search search-query start count))))
(defun list-type (type (start 0) (count 32))
(setf search-style "list")
(cond
((= type "dropbox")
(ajax-results "/ajax/dropbox"))
((= type "stored")
(ajax-results "/ajax/stored"))
(t (ajax-results "/ajax/md-list"
(create :parameters
(create :type search-type
:start start
:count count))))))
(defun search ((my-search-query (slot-value $("q") 'value))
(start 0) (count 32))
(setf search-style "search")
(setf search-query my-search-query)
(ajax-results "/ajax/md-search"
(create :parameters
(create :type search-type
:query search-query
:start start
:count count))))
))
((:body :bgcolor "#ffffff" :color "#000000" :onload (js:js-inline (page-load-finished)))
((:div :id "container")
((:div :id "categories")
((:ul :class "nav")
((:li :id "sysex")
((:a :href "#" :onclick (js:js-inline (select "sysex")))
(md-img-text "SYSEX" 2)))
((:li :id "kits")
((:a :href "#" :onclick (js:js-inline (select "kits")))
(md-img-text "KITS" 2)))
((:li :id "machines")
((:a :href "#" :onclick (js:js-inline (select "machines")))
(md-img-text "MACHINES" 2)))
((:li :id "songs")
((:a :href "#" :onclick (js:js-inline (select "songs")))
(md-img-text "SONGS" 2)))
((:li :id "wavs")
((:a :href "#" :onclick (js:js-inline (select "wavs")))
(md-img-text "WAVS" 2)))
((:li :id "midis")
((:a :href "#" :onclick (js:js-inline (select "midis")))
(md-img-text "MIDIS" 2)))
((:li :id "users")
((:a :href "#" :onclick (js:js-inline (select "users")))
(md-img-text "USERS" 2)))
((:li :id "stored")
((:a :href "#" :onclick (js:js-inline (select "stored")))
(md-img-text "STORED" 2)))
((:li :id "dropbox")
((:a :href "#" :onclick (js:js-inline (select "dropbox")))
(md-img-text "DROPBOX" 2)))
((:li :id "trash")
(md-img-text "TRASH" 2))))
(js-script (-droppables.add "trash"
(create :on-drop (lambda (drag drop evt)
(when (= search-type "dropbox")
(remove-from-dropbox drag)
(new (-effect.-pulsate
drop
(create :pulses 2
:duration 0.5
:from 0.2))))
)
:hoverclass "drophover")))
(js-script (-droppables.add "dropbox"
(create :on-drop (lambda (drag drop evt)
(add-to-dropbox drag.id)
(new (-effect.-pulsate
drop
(create :pulses 2
:duration 0.5
:from 0.2))))
:hoverclass "drophover")))
((:div :id "select")
(:form :action (js:js-inline (search))
(:input :class "simage" :type "image"
:src "/text-image/search:?scale=2")
(:input :id "q" :type "search" :name "q")))
((:div :id "helpholder")
((:div :id "help") "Welcome to MD Editor"))
((:div :id "results"))
)))))
(defmacro with-elektron-page ((&rest params) &rest body)
`(with-html-output-to-string (,@params)
(:html
(:head (:title "ELEKTRON MD CONVERTER")
(:link :rel "shortcut icon" :type "image/x-icon" :href "/files/favicon.ico")
#+nil(:link :href *elektron-css-file* :rel "stylesheet" :type "text/css"))
((:body :bgcolor "#ffffff" :color "#000000")
(:div :align :center
:br :br
(:img :src "/files/pngs/md-sysex.png" :border 0 :alt "MD SYSEX CONVERTER")
:br :br
,@body)))))
(defmacro with-sub-elektron-page ((s title i big &rest params) &rest body)
`(with-html-output (,s nil :indent t ,@params)
(:html
(:head (:title ,title)
(:link :rel "shortcut icon" :type "image/x-icon" :href "/files/favicon.ico"))
((:body :bgcolor "#ffffff" :color "#000000")
(:div :align :center ((:a :href (format nil "/files/~A.html" ,i))
(:img :src ,(if big "/files/sps1-uw.jpg"
"/files/sps1-uw-small.jpg")
:border 0
:alt "image of sps1 uw (c) hageir")
:br :br
(:img :src ,(if big `(format nil "/files/filename-~A.gif" ,i)
"/files/pngs/back.png")
:border 0
:alt ,(if big "FILENAME" "BACK")))
:br :br
,@body)))))
(defun error-page ()
(with-elektron-page (*standard-output* nil :prologue t :indent t)
(:img :src "/files/pngs/sysex-error.png" :border 0
:alt "ERROR IN THE SYSEX FILE! PLEASE UPLOAD AGAIN:")
:br :br
((:form :method :post :enctype "multipart/form-data")
(:input :type "file" :name "test" :maxlength "500000") :br :br
(:input :type :submit :name "upload" :value "UPLOAD"))))
|
3cddf9acf59d1f12f723c0dc0a124251eff2ed8ac06fd61e7eb8929511cfec78
|
cark/cark.behavior-tree
|
tick_eater.cljc
|
(ns cark.behavior-tree.node-defs.tick-eater
"The :tick-eater node stays :running for a number of ticks, and then succeeds.
parameters:
- :count : An integer, or integer returning function. The number of ticks before succeeding."
(:require [cark.behavior-tree.context :as ctx]
[cark.behavior-tree.db :as db]
[cark.behavior-tree.tree :as tree]
[cark.behavior-tree.type :as type]
[cark.behavior-tree.base-nodes :as bn]
[clojure.spec.alpha :as s]))
(defn log [value]
(tap> value)
value)
(s/def ::count (s/or :function fn?
:integer (s/and int? #(>= % 0))))
(defn compile-node [tree id tag params children]
(let [[type value] (:count params)
get-count (case type
:integer (constantly value)
:function value)]
[(fn tick-eater-tick [ctx arg]
(case (db/get-node-status ctx id)
:fresh (recur (-> (db/set-node-status ctx id :running)
(db/set-node-data id 0))
arg)
:running (let [i (db/get-node-data ctx id)
c (get-count ctx)]
(if (< i c)
(db/update-node-data ctx id inc)
(-> (db/set-node-status ctx id :success)
(db/set-node-data id nil))))))
tree]))
(defn register []
(type/register
(bn/leaf
{::type/tag :tick-eater
::type/params-spec (s/keys :req-un [::count])
::type/compile-func compile-node})))
| null |
https://raw.githubusercontent.com/cark/cark.behavior-tree/4e229fcc2ed3af3c66e74d2c51dda6684927d254/src/main/cark/behavior_tree/node_defs/tick_eater.cljc
|
clojure
|
(ns cark.behavior-tree.node-defs.tick-eater
"The :tick-eater node stays :running for a number of ticks, and then succeeds.
parameters:
- :count : An integer, or integer returning function. The number of ticks before succeeding."
(:require [cark.behavior-tree.context :as ctx]
[cark.behavior-tree.db :as db]
[cark.behavior-tree.tree :as tree]
[cark.behavior-tree.type :as type]
[cark.behavior-tree.base-nodes :as bn]
[clojure.spec.alpha :as s]))
(defn log [value]
(tap> value)
value)
(s/def ::count (s/or :function fn?
:integer (s/and int? #(>= % 0))))
(defn compile-node [tree id tag params children]
(let [[type value] (:count params)
get-count (case type
:integer (constantly value)
:function value)]
[(fn tick-eater-tick [ctx arg]
(case (db/get-node-status ctx id)
:fresh (recur (-> (db/set-node-status ctx id :running)
(db/set-node-data id 0))
arg)
:running (let [i (db/get-node-data ctx id)
c (get-count ctx)]
(if (< i c)
(db/update-node-data ctx id inc)
(-> (db/set-node-status ctx id :success)
(db/set-node-data id nil))))))
tree]))
(defn register []
(type/register
(bn/leaf
{::type/tag :tick-eater
::type/params-spec (s/keys :req-un [::count])
::type/compile-func compile-node})))
|
|
f3f5958007a5b710fc1cc93cd7ba7fc27c974cba420073b69f40356f53f2c0fa
|
maacl/websocket-test
|
gen.clj
|
Copyright ( c ) . All rights reserved .
The use and distribution terms for this software are covered by the Eclipse
;; Public License 1.0 (-1.0.php) which
;; can be found in the file epl-v10.html at the root of this distribution. By
;; using this software in any fashion, you are agreeing to be bound by the
;; terms of this license. You must not remove this notice, or any other, from
;; this software.
(ns compojure.html.gen
"A library for generating HTML output from a tree of vectors. The first item
of the vector is the tag name, the optional second item is a hash of
attributes, and the rest is the body of the tag."
(:use compojure.str-utils
clojure.contrib.def))
(defn optional-attrs
"Adds an optional attribute map to the supplied function's arguments."
[func]
(fn [attrs & body]
(if (map? attrs)
(let [[tag func-attrs & body] (apply func body)]
(apply vector tag (merge func-attrs attrs) body))
(apply func attrs body))))
(defn escape-html
"Change special characters into HTML character entities."
[string]
(.. (str string)
(replace "&" "&")
(replace "<" "<")
(replace ">" ">")
(replace "\"" """)))
(defvar h escape-html
"Shortcut for escape-html")
(defn- map-to-attrs
"Turn a map into a string of HTML attributes, sorted by attribute name."
[attrs]
(map-str
(fn [[key val]]
(if key
(str " " key "=\"" (h val) "\"")))
(sort
(map (fn [[key val]]
(cond
(true? val) [(str* key) (str* key)]
(not val) [nil nil]
:else [(str* key) (str* val)]))
attrs))))
(defn- create-tag
"Wrap some content in an HTML tag."
[tag attrs content]
(str* "<" tag (map-to-attrs attrs) ">"
content
"</" tag ">"))
(defn- create-closed-tag
"Make a closed XML tag with no content."
[tag attrs]
(str* "<" tag (map-to-attrs attrs) " />"))
(defn- expand-seqs
"Expand out all the sequences in a collection."
[coll]
(mapcat
#(if (or (seq? %) (nil? %))
%
(list %))
coll))
(defn- ensure-attrs
"Ensure the tag has a map of attributes."
[[tag & body]]
(if (map? (first body))
(list* tag body)
(list* tag {} body)))
(defvar- css-lexer #"([^\s\.#]+)(?:#([^\s\.#]+))?(?:\.([^\s#]+))?")
(defn- parse-css-tag
"Pulls the id and class attributes from a tag name formatted in a CSS style.
e.g. :div#content -> [:div {:id \"content\"}]
:span.error -> [:span {:class \"error\"}]"
[tag attrs]
(let [[_ tag id classes] (re-matches css-lexer (str* tag))
attrs (merge attrs
(if id {:id id})
(if classes
{:class (.replace classes "." " ")}))]
[tag attrs]))
(declare html)
(defvar- container-tags
#{:a :b :body :dd :div :dl :dt :em :fieldset :form :h1 :h2 :h3 :h4 :h5 :h6
:head :html :i :label :li :ol :pre :script :span :strong :style :textarea
:ul}
"A list of tags that need an explicit ending tag when rendered.")
(defn explicit-ending-tag?
"Returns true if tag needs an explicit ending tag, even if the body of the
tag is empty."
[tag]
(container-tags (keyword (str* tag))))
(defn html-tree
"Turns a tree of vectors into a string of HTML. Any sequences in the
tree are expanded out."
[tree]
(if (vector? tree)
(let [[tag attrs & body] (ensure-attrs tree)
[tag attrs] (parse-css-tag tag attrs)
body (expand-seqs body)]
(if (or (seq body) (explicit-ending-tag? tag))
(create-tag tag attrs (apply html body))
(create-closed-tag tag attrs)))
(str tree)))
(defn html
"Format trees of vectors into a string of HTML."
[& trees]
(map-str html-tree (expand-seqs trees)))
| null |
https://raw.githubusercontent.com/maacl/websocket-test/d79dfdf82762d566cd89b535c3dbede2788bb034/src/compojure/html/gen.clj
|
clojure
|
Public License 1.0 (-1.0.php) which
can be found in the file epl-v10.html at the root of this distribution. By
using this software in any fashion, you are agreeing to be bound by the
terms of this license. You must not remove this notice, or any other, from
this software.
")))
|
Copyright ( c ) . All rights reserved .
The use and distribution terms for this software are covered by the Eclipse
(ns compojure.html.gen
"A library for generating HTML output from a tree of vectors. The first item
of the vector is the tag name, the optional second item is a hash of
attributes, and the rest is the body of the tag."
(:use compojure.str-utils
clojure.contrib.def))
(defn optional-attrs
"Adds an optional attribute map to the supplied function's arguments."
[func]
(fn [attrs & body]
(if (map? attrs)
(let [[tag func-attrs & body] (apply func body)]
(apply vector tag (merge func-attrs attrs) body))
(apply func attrs body))))
(defn escape-html
"Change special characters into HTML character entities."
[string]
(.. (str string)
(replace "&" "&")
(replace "<" "<")
(replace ">" ">")
(defvar h escape-html
"Shortcut for escape-html")
(defn- map-to-attrs
"Turn a map into a string of HTML attributes, sorted by attribute name."
[attrs]
(map-str
(fn [[key val]]
(if key
(str " " key "=\"" (h val) "\"")))
(sort
(map (fn [[key val]]
(cond
(true? val) [(str* key) (str* key)]
(not val) [nil nil]
:else [(str* key) (str* val)]))
attrs))))
(defn- create-tag
"Wrap some content in an HTML tag."
[tag attrs content]
(str* "<" tag (map-to-attrs attrs) ">"
content
"</" tag ">"))
(defn- create-closed-tag
"Make a closed XML tag with no content."
[tag attrs]
(str* "<" tag (map-to-attrs attrs) " />"))
(defn- expand-seqs
"Expand out all the sequences in a collection."
[coll]
(mapcat
#(if (or (seq? %) (nil? %))
%
(list %))
coll))
(defn- ensure-attrs
"Ensure the tag has a map of attributes."
[[tag & body]]
(if (map? (first body))
(list* tag body)
(list* tag {} body)))
(defvar- css-lexer #"([^\s\.#]+)(?:#([^\s\.#]+))?(?:\.([^\s#]+))?")
(defn- parse-css-tag
"Pulls the id and class attributes from a tag name formatted in a CSS style.
e.g. :div#content -> [:div {:id \"content\"}]
:span.error -> [:span {:class \"error\"}]"
[tag attrs]
(let [[_ tag id classes] (re-matches css-lexer (str* tag))
attrs (merge attrs
(if id {:id id})
(if classes
{:class (.replace classes "." " ")}))]
[tag attrs]))
(declare html)
(defvar- container-tags
#{:a :b :body :dd :div :dl :dt :em :fieldset :form :h1 :h2 :h3 :h4 :h5 :h6
:head :html :i :label :li :ol :pre :script :span :strong :style :textarea
:ul}
"A list of tags that need an explicit ending tag when rendered.")
(defn explicit-ending-tag?
"Returns true if tag needs an explicit ending tag, even if the body of the
tag is empty."
[tag]
(container-tags (keyword (str* tag))))
(defn html-tree
"Turns a tree of vectors into a string of HTML. Any sequences in the
tree are expanded out."
[tree]
(if (vector? tree)
(let [[tag attrs & body] (ensure-attrs tree)
[tag attrs] (parse-css-tag tag attrs)
body (expand-seqs body)]
(if (or (seq body) (explicit-ending-tag? tag))
(create-tag tag attrs (apply html body))
(create-closed-tag tag attrs)))
(str tree)))
(defn html
"Format trees of vectors into a string of HTML."
[& trees]
(map-str html-tree (expand-seqs trees)))
|
9093d88b371261c8bc32cbbbd5474cd3b54a0271b04faf690d6431b777820d68
|
haskell-streaming/streaming-attoparsec
|
Streaming.hs
|
|
Here is a simple use of ' parsed ' and standard @Streaming@ segmentation devices
to parse a file in which groups of numbers are separated by blank lines . Such a
problem of \'nesting streams\ ' is described in the @conduit@ context in
< -to-model-nested-streams-with-conduits/32961296 this StackOverflow question > .
> -- $ cat nums.txt
> -- 1
> -- 2
> -- 3
> --
> -- 4
> -- 5
> -- 6
> --
> -- 7
> -- 8
We will sum the groups and stream the results to standard output :
> import Streaming
> import qualified Streaming . Prelude as S
> import qualified Data . ByteString . Streaming . Char8 as Q
> import qualified Data . Attoparsec . ByteString . Char8 as A
> import qualified Data . Attoparsec . ByteString . Streaming as AS
> import Data . Function ( ( & ) )
>
> main : : IO ( )
> main = Q.getContents -- raw bytes
> & AS.parsed -- stream of parsed ` Maybe Int`s ; blank lines are ` Nothing `
> & void -- drop any unparsed nonsense at the end
> & S.split Nothing -- split on blank lines
> & S.maps S.concat -- keep ` Just x ` values in the sub - streams ( cp . )
> & S.mapped S.sum -- sum each substream
> & S.print -- stream results to stdout
>
> = Just < $ > A.scientific < * A.endOfLine < | > Nothing < $ A.endOfLine
> -- $ cat nums.txt | ./atto
> -- 6.0
> -- 15.0
> -- 15.0
Here is a simple use of 'parsed' and standard @Streaming@ segmentation devices
to parse a file in which groups of numbers are separated by blank lines. Such a
problem of \'nesting streams\' is described in the @conduit@ context in
<-to-model-nested-streams-with-conduits/32961296 this StackOverflow question>.
> -- $ cat nums.txt
> -- 1
> -- 2
> -- 3
> --
> -- 4
> -- 5
> -- 6
> --
> -- 7
> -- 8
We will sum the groups and stream the results to standard output:
> import Streaming
> import qualified Streaming.Prelude as S
> import qualified Data.ByteString.Streaming.Char8 as Q
> import qualified Data.Attoparsec.ByteString.Char8 as A
> import qualified Data.Attoparsec.ByteString.Streaming as AS
> import Data.Function ((&))
>
> main :: IO ()
> main = Q.getContents -- raw bytes
> & AS.parsed lineParser -- stream of parsed `Maybe Int`s; blank lines are `Nothing`
> & void -- drop any unparsed nonsense at the end
> & S.split Nothing -- split on blank lines
> & S.maps S.concat -- keep `Just x` values in the sub-streams (cp. catMaybes)
> & S.mapped S.sum -- sum each substream
> & S.print -- stream results to stdout
>
> lineParser = Just <$> A.scientific <* A.endOfLine <|> Nothing <$ A.endOfLine
> -- $ cat nums.txt | ./atto
> -- 6.0
> -- 15.0
> -- 15.0
-}
module Data.Attoparsec.ByteString.Streaming where
import qualified Data.Attoparsec.ByteString as A
import qualified Data.Attoparsec.Internal.Types as T
import qualified Data.ByteString as B
import Data.ByteString.Streaming
import Data.ByteString.Streaming.Internal
import Streaming hiding (concats, unfold)
import Streaming.Internal (Stream(..))
---
-- | Output from parsing errors.
type Errors = ([String], String)
| The result of a parse ( ( [ String ] , String ) a@ ) , with the unconsumed byte stream .
> > > : set -XOverloadedStrings -- the string literal below is a streaming bytestring
> > > ( r , rest1 ) < - AS.parse ( A.scientific < * A.many ' A.space ) " 12.3 4.56 78.3 "
> > > print r
Right 12.3
> > > ( s , rest2 ) < - AS.parse ( A.scientific < * A.many ' A.space ) rest1
> > > print s
Right 4.56
> > > ( t , rest3 ) < - AS.parse ( A.scientific < * A.many ' A.space ) rest2
> > > print t
Right 78.3
> > > Q.putStrLn rest3
-- Nothing left , this prints an empty string .
>>> :set -XOverloadedStrings -- the string literal below is a streaming bytestring
>>> (r,rest1) <- AS.parse (A.scientific <* A.many' A.space) "12.3 4.56 78.3"
>>> print r
Right 12.3
>>> (s,rest2) <- AS.parse (A.scientific <* A.many' A.space) rest1
>>> print s
Right 4.56
>>> (t,rest3) <- AS.parse (A.scientific <* A.many' A.space) rest2
>>> print t
Right 78.3
>>> Q.putStrLn rest3
-- Nothing left, this prints an empty string.
-}
parse :: Monad m => A.Parser a -> ByteString m x -> m (Either Errors a, ByteString m x)
parse parser = begin
where begin p0 = case p0 of
Go m -> m >>= begin
Empty r -> step id (A.parse parser B.empty) (return r)
attoparsec understands " " as eof
| otherwise -> step (chunk bs >>) (A.parse parser bs) p1
step diff res p0 = case res of
T.Fail _ c m -> return (Left (c,m), diff p0)
T.Done a b -> return (Right b, chunk a >> p0)
T.Partial k -> do
let clean p = case p of -- inspect for null chunks before
feeding attoparsec
Empty r -> step diff (k B.empty) (return r)
Chunk bs p1 | B.null bs -> clean p1
| otherwise -> step (diff . (chunk bs >>)) (k bs) p1
clean p0
# INLINABLE parse #
| Apply a parser repeatedly to a stream of bytes , streaming the parsed values ,
but ending when the parser fails or the bytes run out .
> > > S.print . void $ AS.parsed ( A.scientific < * A.many ' A.space ) " 12.3 4.56 78.9 "
12.3
4.56
78.9
but ending when the parser fails or the bytes run out.
>>> S.print . void $ AS.parsed (A.scientific <* A.many' A.space) "12.3 4.56 78.9"
12.3
4.56
78.9
-}
parsed
:: Monad m
^ Attoparsec parser
-> ByteString m r -- ^ Raw input
-> Stream (Of a) m (Either (Errors, ByteString m r) r)
parsed parser = begin
where begin p0 = case p0 of -- inspect for null chunks before
feeding attoparsec
Empty r -> Return (Right r)
Chunk bs p1 | B.null bs -> begin p1
| otherwise -> step (chunk bs >>) (A.parse parser bs) p1
step diffP res p0 = case res of
A.Fail _ c m -> Return (Left ((c,m), diffP p0))
A.Done bs a | B.null bs -> Step (a :> begin p0)
| otherwise -> Step (a :> begin (chunk bs >> p0))
A.Partial k -> do
x <- lift (nextChunk p0)
case x of
Left e -> step diffP (k B.empty) (return e)
Right (bs,p1) | B.null bs -> step diffP res p1
| otherwise -> step (diffP . (chunk bs >>)) (k bs) p1
# INLINABLE parsed #
| null |
https://raw.githubusercontent.com/haskell-streaming/streaming-attoparsec/06c33f898e899c7d81ab64f126236312c47e61d5/Data/Attoparsec/ByteString/Streaming.hs
|
haskell
|
$ cat nums.txt
1
2
3
4
5
6
7
8
raw bytes
stream of parsed ` Maybe Int`s ; blank lines are ` Nothing `
drop any unparsed nonsense at the end
split on blank lines
keep ` Just x ` values in the sub - streams ( cp . )
sum each substream
stream results to stdout
$ cat nums.txt | ./atto
6.0
15.0
15.0
$ cat nums.txt
1
2
3
4
5
6
7
8
raw bytes
stream of parsed `Maybe Int`s; blank lines are `Nothing`
drop any unparsed nonsense at the end
split on blank lines
keep `Just x` values in the sub-streams (cp. catMaybes)
sum each substream
stream results to stdout
$ cat nums.txt | ./atto
6.0
15.0
15.0
-
| Output from parsing errors.
the string literal below is a streaming bytestring
Nothing left , this prints an empty string .
the string literal below is a streaming bytestring
Nothing left, this prints an empty string.
inspect for null chunks before
^ Raw input
inspect for null chunks before
|
|
Here is a simple use of ' parsed ' and standard @Streaming@ segmentation devices
to parse a file in which groups of numbers are separated by blank lines . Such a
problem of \'nesting streams\ ' is described in the @conduit@ context in
< -to-model-nested-streams-with-conduits/32961296 this StackOverflow question > .
We will sum the groups and stream the results to standard output :
> import Streaming
> import qualified Streaming . Prelude as S
> import qualified Data . ByteString . Streaming . Char8 as Q
> import qualified Data . Attoparsec . ByteString . Char8 as A
> import qualified Data . Attoparsec . ByteString . Streaming as AS
> import Data . Function ( ( & ) )
>
> main : : IO ( )
>
> = Just < $ > A.scientific < * A.endOfLine < | > Nothing < $ A.endOfLine
Here is a simple use of 'parsed' and standard @Streaming@ segmentation devices
to parse a file in which groups of numbers are separated by blank lines. Such a
problem of \'nesting streams\' is described in the @conduit@ context in
<-to-model-nested-streams-with-conduits/32961296 this StackOverflow question>.
We will sum the groups and stream the results to standard output:
> import Streaming
> import qualified Streaming.Prelude as S
> import qualified Data.ByteString.Streaming.Char8 as Q
> import qualified Data.Attoparsec.ByteString.Char8 as A
> import qualified Data.Attoparsec.ByteString.Streaming as AS
> import Data.Function ((&))
>
> main :: IO ()
>
> lineParser = Just <$> A.scientific <* A.endOfLine <|> Nothing <$ A.endOfLine
-}
module Data.Attoparsec.ByteString.Streaming where
import qualified Data.Attoparsec.ByteString as A
import qualified Data.Attoparsec.Internal.Types as T
import qualified Data.ByteString as B
import Data.ByteString.Streaming
import Data.ByteString.Streaming.Internal
import Streaming hiding (concats, unfold)
import Streaming.Internal (Stream(..))
type Errors = ([String], String)
| The result of a parse ( ( [ String ] , String ) a@ ) , with the unconsumed byte stream .
> > > ( r , rest1 ) < - AS.parse ( A.scientific < * A.many ' A.space ) " 12.3 4.56 78.3 "
> > > print r
Right 12.3
> > > ( s , rest2 ) < - AS.parse ( A.scientific < * A.many ' A.space ) rest1
> > > print s
Right 4.56
> > > ( t , rest3 ) < - AS.parse ( A.scientific < * A.many ' A.space ) rest2
> > > print t
Right 78.3
> > > Q.putStrLn rest3
>>> (r,rest1) <- AS.parse (A.scientific <* A.many' A.space) "12.3 4.56 78.3"
>>> print r
Right 12.3
>>> (s,rest2) <- AS.parse (A.scientific <* A.many' A.space) rest1
>>> print s
Right 4.56
>>> (t,rest3) <- AS.parse (A.scientific <* A.many' A.space) rest2
>>> print t
Right 78.3
>>> Q.putStrLn rest3
-}
parse :: Monad m => A.Parser a -> ByteString m x -> m (Either Errors a, ByteString m x)
parse parser = begin
where begin p0 = case p0 of
Go m -> m >>= begin
Empty r -> step id (A.parse parser B.empty) (return r)
attoparsec understands " " as eof
| otherwise -> step (chunk bs >>) (A.parse parser bs) p1
step diff res p0 = case res of
T.Fail _ c m -> return (Left (c,m), diff p0)
T.Done a b -> return (Right b, chunk a >> p0)
T.Partial k -> do
feeding attoparsec
Empty r -> step diff (k B.empty) (return r)
Chunk bs p1 | B.null bs -> clean p1
| otherwise -> step (diff . (chunk bs >>)) (k bs) p1
clean p0
# INLINABLE parse #
| Apply a parser repeatedly to a stream of bytes , streaming the parsed values ,
but ending when the parser fails or the bytes run out .
> > > S.print . void $ AS.parsed ( A.scientific < * A.many ' A.space ) " 12.3 4.56 78.9 "
12.3
4.56
78.9
but ending when the parser fails or the bytes run out.
>>> S.print . void $ AS.parsed (A.scientific <* A.many' A.space) "12.3 4.56 78.9"
12.3
4.56
78.9
-}
parsed
:: Monad m
^ Attoparsec parser
-> Stream (Of a) m (Either (Errors, ByteString m r) r)
parsed parser = begin
feeding attoparsec
Empty r -> Return (Right r)
Chunk bs p1 | B.null bs -> begin p1
| otherwise -> step (chunk bs >>) (A.parse parser bs) p1
step diffP res p0 = case res of
A.Fail _ c m -> Return (Left ((c,m), diffP p0))
A.Done bs a | B.null bs -> Step (a :> begin p0)
| otherwise -> Step (a :> begin (chunk bs >> p0))
A.Partial k -> do
x <- lift (nextChunk p0)
case x of
Left e -> step diffP (k B.empty) (return e)
Right (bs,p1) | B.null bs -> step diffP res p1
| otherwise -> step (diffP . (chunk bs >>)) (k bs) p1
# INLINABLE parsed #
|
cf393c2202271df3e6149c45e02c59ed4191bef8fd96bbe5c7207db4a251bde1
|
ygmpkk/house
|
Main.hs
|
module Main where
-- **************************************************************************************************
--
-- This program creates a windows that allows a user to create a RGB colour.
--
The program has been written in Clean 2.0 and uses the Clean Standard Object I / O library 1.2.2
--
-- **************************************************************************************************
import Graphics.UI.ObjectIO
import Prelude hiding (Left)
blackRGB = RGB 0 0 0
whiteRGB = RGB 255 255 255
main :: IO ()
main = do
rgbid <- openR2Id
ids <- openIds 7
startColourPicker rgbid ids
where
startColourPicker rgbid ids = startIO SDI () initialise [ProcessClose closeProcess]
where
initialise ps = do
rgbsize <- controlSize (colourPickControl rgbid ids initrgb Nothing) True Nothing Nothing Nothing
let wdef = Window "Pick a colour" (colourPickControl rgbid ids initrgb Nothing)
[ WindowViewSize rgbsize
, WindowPen [PenBack lightGrey]
]
let mdef = Menu "PickRGB"
( MenuItem "MinRGB" [ MenuFunction (noLS (set rgbid blackRGB))
, MenuShortKey 'n'
]
:+: MenuItem "MaxRGB" [ MenuFunction (noLS (set rgbid whiteRGB))
, MenuShortKey 'm'
]
:+: MenuSeparator []
:+: MenuItem "Quit" [ MenuFunction (noLS closeProcess)
, MenuShortKey 'q'
]
) []
ps <- openWindow undefined wdef ps
ps <- openMenu undefined mdef ps
return ps
where
initrgb = RGB {r=maxRGB,g=maxRGB,b=maxRGB}
set rid rgb ps = fmap snd (syncSend2 rid (InSet rgb) ps)
-- The definition of the text-slider component:
type RGBPickControl ls ps = TupLS SliderControl TextControl ls ps
rgbPickControl :: Colour -> (String,Id,Id) -> Id -> (Colour->Int) -> (Int->Colour->Colour) -> Maybe ItemPos -> RGBPickControl Colour ps
rgbPickControl rgb (text,sid,tid) did get set maybePos =
SliderControl Horizontal length sliderstate slideraction (ControlId sid:controlPos)
:+: TextControl (colourText text (get rgb)) [ControlId tid]
where
controlPos = case maybePos of
Just pos -> [ControlPos pos]
_ -> []
length = PixelWidth (maxRGB-minRGB+1)
sliderstate = SliderState{sliderMin=minRGB, sliderMax=maxRGB, sliderThumb=get rgb}
slideraction :: SliderMove -> GUIFun Colour ps
slideraction move (rgb,ps) = do
setSliderThumb sid y
setControlText tid (colourText text y)
setColourBox did newrgb
return (newrgb, ps)
where
y = case move of
SliderIncSmall -> min (get rgb+1 ) maxRGB
SliderDecSmall -> max (get rgb-1 ) minRGB
SliderIncLarge -> min (get rgb+10) maxRGB
SliderDecLarge -> max (get rgb-10) minRGB
SliderThumb x -> x
newrgb = set y rgb
colourText :: String -> Int -> String
colourText text x = text++" "++show x
-- The definition of a colour box:
type ColourBoxControl ls ps = CustomControl ls ps
colourBoxControl :: Colour -> Id -> Maybe ItemPos -> ColourBoxControl ls pst
colourBoxControl rgb did maybePos =
CustomControl (Size{w=40,h=40}) (colourBoxLook rgb)
((ControlId did) : (case maybePos of (Just pos) -> [ControlPos pos];_->[]))
colourBoxLook :: Colour -> SelectState -> UpdateState -> Draw ()
colourBoxLook colour _ (UpdateState {newFrame=newFrame}) = do
setPenColour colour
fill newFrame
setPenColour black
draw newFrame
setColourBox :: Id -> Colour -> GUI ps ()
setColourBox id rgb = setControlLook id True (True,colourBoxLook rgb)
The definition of the RGB access control :
data In = InGet | InSet Colour
data Out = OutGet Colour | OutSet
type RGBId = R2Id In Out
type ColourPickAccess ps = Receiver2 In Out Colour ps
colourPickAccess :: RGBId -> [(String,Id,Id)] -> Id -> ColourPickAccess ps
colourPickAccess rid rgbpicks did = Receiver2 rid accessRGB []
where
accessRGB :: In -> (Colour,ps) -> GUI ps (Out,(Colour,ps))
accessRGB InGet (rgb,ps) =
return (OutGet rgb,(rgb,ps))
accessRGB (InSet rgb@(RGB r g b)) (_,ps) = do
setColourBox did rgb
setSliderThumbs (map (\(y,(_,sid,_))->(sid,y)) settings)
setControlTexts (map (\(y,(text,_,tid))->(tid,colourText text y)) settings)
return (OutSet,(rgb,ps))
where
settings= zip [r,g,b] rgbpicks
-- The definition of the assembled colour picking control:
type ColourPickControl ls ps
= NewLS ( LayoutControl
(TupLS (LayoutControl (ListLS (TupLS SliderControl TextControl))) (TupLS CustomControl (Receiver2 In Out)))
) ls ps
colourPickControl :: RGBId -> [Id] -> Colour -> Maybe ItemPos -> ColourPickControl ls ps
colourPickControl rgbid ids initrgb maybePos =
NewLS initrgb
(LayoutControl
( LayoutControl
( ListLS
[ rgbPickControl initrgb rpicks did r (\x rgb->rgb{r=x}) left
, rgbPickControl initrgb gpicks did g (\x rgb->rgb{g=x}) left
, rgbPickControl initrgb bpicks did b (\x rgb->rgb{b=x}) left
]) [ControlHMargin 0 0,ControlVMargin 0 0]
:+: colourBoxControl initrgb did Nothing
:+: colourPickAccess rgbid [rpicks,gpicks,bpicks] did
) (case maybePos of Just pos -> [ControlPos pos]; _->[])
)
where
[rid,rtid,gid,gtid,bid,btid,did] = ids
(rtext,gtext,btext) = ("Red","Green","Blue")
(rpicks,gpicks,bpicks) = ((rtext,rid,rtid),(gtext,gid,gtid),(btext,bid,btid))
left = Just (Left,zero)
| null |
https://raw.githubusercontent.com/ygmpkk/house/1ed0eed82139869e85e3c5532f2b579cf2566fa2/ghc-6.2/libraries/ObjectIO/Examples/RGBSelector/Main.hs
|
haskell
|
**************************************************************************************************
This program creates a windows that allows a user to create a RGB colour.
**************************************************************************************************
The definition of the text-slider component:
The definition of a colour box:
The definition of the assembled colour picking control:
|
module Main where
The program has been written in Clean 2.0 and uses the Clean Standard Object I / O library 1.2.2
import Graphics.UI.ObjectIO
import Prelude hiding (Left)
blackRGB = RGB 0 0 0
whiteRGB = RGB 255 255 255
main :: IO ()
main = do
rgbid <- openR2Id
ids <- openIds 7
startColourPicker rgbid ids
where
startColourPicker rgbid ids = startIO SDI () initialise [ProcessClose closeProcess]
where
initialise ps = do
rgbsize <- controlSize (colourPickControl rgbid ids initrgb Nothing) True Nothing Nothing Nothing
let wdef = Window "Pick a colour" (colourPickControl rgbid ids initrgb Nothing)
[ WindowViewSize rgbsize
, WindowPen [PenBack lightGrey]
]
let mdef = Menu "PickRGB"
( MenuItem "MinRGB" [ MenuFunction (noLS (set rgbid blackRGB))
, MenuShortKey 'n'
]
:+: MenuItem "MaxRGB" [ MenuFunction (noLS (set rgbid whiteRGB))
, MenuShortKey 'm'
]
:+: MenuSeparator []
:+: MenuItem "Quit" [ MenuFunction (noLS closeProcess)
, MenuShortKey 'q'
]
) []
ps <- openWindow undefined wdef ps
ps <- openMenu undefined mdef ps
return ps
where
initrgb = RGB {r=maxRGB,g=maxRGB,b=maxRGB}
set rid rgb ps = fmap snd (syncSend2 rid (InSet rgb) ps)
type RGBPickControl ls ps = TupLS SliderControl TextControl ls ps
rgbPickControl :: Colour -> (String,Id,Id) -> Id -> (Colour->Int) -> (Int->Colour->Colour) -> Maybe ItemPos -> RGBPickControl Colour ps
rgbPickControl rgb (text,sid,tid) did get set maybePos =
SliderControl Horizontal length sliderstate slideraction (ControlId sid:controlPos)
:+: TextControl (colourText text (get rgb)) [ControlId tid]
where
controlPos = case maybePos of
Just pos -> [ControlPos pos]
_ -> []
length = PixelWidth (maxRGB-minRGB+1)
sliderstate = SliderState{sliderMin=minRGB, sliderMax=maxRGB, sliderThumb=get rgb}
slideraction :: SliderMove -> GUIFun Colour ps
slideraction move (rgb,ps) = do
setSliderThumb sid y
setControlText tid (colourText text y)
setColourBox did newrgb
return (newrgb, ps)
where
y = case move of
SliderIncSmall -> min (get rgb+1 ) maxRGB
SliderDecSmall -> max (get rgb-1 ) minRGB
SliderIncLarge -> min (get rgb+10) maxRGB
SliderDecLarge -> max (get rgb-10) minRGB
SliderThumb x -> x
newrgb = set y rgb
colourText :: String -> Int -> String
colourText text x = text++" "++show x
type ColourBoxControl ls ps = CustomControl ls ps
colourBoxControl :: Colour -> Id -> Maybe ItemPos -> ColourBoxControl ls pst
colourBoxControl rgb did maybePos =
CustomControl (Size{w=40,h=40}) (colourBoxLook rgb)
((ControlId did) : (case maybePos of (Just pos) -> [ControlPos pos];_->[]))
colourBoxLook :: Colour -> SelectState -> UpdateState -> Draw ()
colourBoxLook colour _ (UpdateState {newFrame=newFrame}) = do
setPenColour colour
fill newFrame
setPenColour black
draw newFrame
setColourBox :: Id -> Colour -> GUI ps ()
setColourBox id rgb = setControlLook id True (True,colourBoxLook rgb)
The definition of the RGB access control :
data In = InGet | InSet Colour
data Out = OutGet Colour | OutSet
type RGBId = R2Id In Out
type ColourPickAccess ps = Receiver2 In Out Colour ps
colourPickAccess :: RGBId -> [(String,Id,Id)] -> Id -> ColourPickAccess ps
colourPickAccess rid rgbpicks did = Receiver2 rid accessRGB []
where
accessRGB :: In -> (Colour,ps) -> GUI ps (Out,(Colour,ps))
accessRGB InGet (rgb,ps) =
return (OutGet rgb,(rgb,ps))
accessRGB (InSet rgb@(RGB r g b)) (_,ps) = do
setColourBox did rgb
setSliderThumbs (map (\(y,(_,sid,_))->(sid,y)) settings)
setControlTexts (map (\(y,(text,_,tid))->(tid,colourText text y)) settings)
return (OutSet,(rgb,ps))
where
settings= zip [r,g,b] rgbpicks
type ColourPickControl ls ps
= NewLS ( LayoutControl
(TupLS (LayoutControl (ListLS (TupLS SliderControl TextControl))) (TupLS CustomControl (Receiver2 In Out)))
) ls ps
colourPickControl :: RGBId -> [Id] -> Colour -> Maybe ItemPos -> ColourPickControl ls ps
colourPickControl rgbid ids initrgb maybePos =
NewLS initrgb
(LayoutControl
( LayoutControl
( ListLS
[ rgbPickControl initrgb rpicks did r (\x rgb->rgb{r=x}) left
, rgbPickControl initrgb gpicks did g (\x rgb->rgb{g=x}) left
, rgbPickControl initrgb bpicks did b (\x rgb->rgb{b=x}) left
]) [ControlHMargin 0 0,ControlVMargin 0 0]
:+: colourBoxControl initrgb did Nothing
:+: colourPickAccess rgbid [rpicks,gpicks,bpicks] did
) (case maybePos of Just pos -> [ControlPos pos]; _->[])
)
where
[rid,rtid,gid,gtid,bid,btid,did] = ids
(rtext,gtext,btext) = ("Red","Green","Blue")
(rpicks,gpicks,bpicks) = ((rtext,rid,rtid),(gtext,gid,gtid),(btext,bid,btid))
left = Just (Left,zero)
|
08656ef301961ce00eabc827659915a5f314ec98579f9daba9b88ad5b5715895
|
lamdu/momentu
|
Events.hs
|
module GUI.Momentu.Main.Events
( Event(..), KeyEvent(..), MouseButtonEvent(..)
) where
import Data.Vector.Vector2 (Vector2(..))
import GUI.Momentu.ModKey (Key, KeyState, ModifierKeys)
import qualified Graphics.UI.GLFW as GLFW
import Prelude
data KeyEvent = KeyEvent
{ keKey :: Key
, keScanCode :: Int
, keState :: KeyState
, keModKeys :: ModifierKeys
} deriving (Show, Eq)
data MouseButtonEvent = MouseButtonEvent
{ mbButton :: GLFW.MouseButton
, mbButtonState :: GLFW.MouseButtonState
, mbModKeys :: ModifierKeys
, mbPosition :: Vector2 Double
-- ^ Position in frame buffer coordinates, which may not be the same as
-- "window coordinates"
, mbPositionInWindowCoords :: Vector2 Double
-- ^ Position in "window coordinates".
-- Since "retina" displays were introduced, window coordindates no longer
-- relate to graphical pixels.
} deriving (Show, Eq)
data Event
= EventKey KeyEvent
| EventChar Char
| EventMouseButton MouseButtonEvent
| EventWindowClose
| EventWindowRefresh
| EventDropPaths [FilePath]
| EventFramebufferSize (Vector2 Int)
deriving (Show, Eq)
| null |
https://raw.githubusercontent.com/lamdu/momentu/7ba3c75469cfbad521d446e2bbefee1ed69d4406/src/GUI/Momentu/Main/Events.hs
|
haskell
|
^ Position in frame buffer coordinates, which may not be the same as
"window coordinates"
^ Position in "window coordinates".
Since "retina" displays were introduced, window coordindates no longer
relate to graphical pixels.
|
module GUI.Momentu.Main.Events
( Event(..), KeyEvent(..), MouseButtonEvent(..)
) where
import Data.Vector.Vector2 (Vector2(..))
import GUI.Momentu.ModKey (Key, KeyState, ModifierKeys)
import qualified Graphics.UI.GLFW as GLFW
import Prelude
data KeyEvent = KeyEvent
{ keKey :: Key
, keScanCode :: Int
, keState :: KeyState
, keModKeys :: ModifierKeys
} deriving (Show, Eq)
data MouseButtonEvent = MouseButtonEvent
{ mbButton :: GLFW.MouseButton
, mbButtonState :: GLFW.MouseButtonState
, mbModKeys :: ModifierKeys
, mbPosition :: Vector2 Double
, mbPositionInWindowCoords :: Vector2 Double
} deriving (Show, Eq)
data Event
= EventKey KeyEvent
| EventChar Char
| EventMouseButton MouseButtonEvent
| EventWindowClose
| EventWindowRefresh
| EventDropPaths [FilePath]
| EventFramebufferSize (Vector2 Int)
deriving (Show, Eq)
|
2515bf42e9b45053768f1e908e3548d93f3b8d794328db8be5ccca030b1e1392
|
propan/geheimtur-demo
|
service.clj
|
(ns geheimtur-demo.service
(:require [io.pedestal.http :as http]
[io.pedestal.http.route :as route]
[io.pedestal.http.body-params :as body-params]
[io.pedestal.interceptor :as interceptor]
[io.pedestal.log :as log]
[geheimtur.interceptor :refer [interactive guard http-basic token]]
[geheimtur.impl.form-based :refer [default-login-handler default-logout-handler]]
[geheimtur.impl.oauth2 :refer [authenticate-handler callback-handler]]
[geheimtur.util.auth :as auth :refer [authenticate]]
[geheimtur-demo.views :as views]
[geheimtur-demo.users :refer [users]]
[cheshire.core :refer [parse-string]]
[ring.middleware.session.cookie :as cookie]
[ring.util.response :as ring-resp]
[ring.util.codec :as ring-codec]))
(defn credentials
[_ {:keys [username password]}]
(when-let [identity (get users username)]
(when (= password (:password identity))
(dissoc identity :password ))))
(defn token-credentials
[_ token]
(case token
"user-secret" (-> (get users "user") (dissoc :password))
"admin-secret" (-> (get users "admin") (dissoc :password))
nil))
(def access-forbidden-interceptor
(interceptor/interceptor
{:name ::access-forbidden-interceptor
:leave (fn [{:keys [response] :as ctx}]
(let [resp (if (or
(= 401 (:status response))
(= 403 (:status response)))
(->
(views/error-page {:title "Access Forbidden" :message (:body response)})
(ring-resp/content-type "text/html;charset=UTF-8"))
response)]
(assoc ctx :response resp)))}))
(def not-found-interceptor
(interceptor/interceptor
{:name ::not-found-interceptor
:leave (fn [{:keys [response] :as ctx}]
(let [resp (if-not (ring-resp/response? response)
(->
(views/error-page {:title "Not Found"
:message "We are sorry, but the page you are looking for does not exist."})
(ring-resp/content-type "text/html;charset=UTF-8"))
response)]
(assoc ctx :response resp)))}))
(defn api-error
[context error]
{:status 403
:headers {}
:body {:error (:reason error)}})
(defn on-github-success
[_ {:keys [identity return]}]
(let [user {:name (:login identity)
:roles #{:user}
:full-name (:name identity)}]
(->
(ring-resp/redirect return)
(authenticate user))))
(defn on-google-success
[_ {:keys [identity return]}]
(let [user {:name (:displayName identity)
:roles #{:user}
:full-name (:displayName identity)}]
(->
(ring-resp/redirect return)
(authenticate user))))
(def providers
{:github {:auth-url ""
:client-id (or (System/getenv "github_client_id") "client-id")
:client-secret (or (System/getenv "github_client_secret") "client-secret")
:scope "user:email"
:token-url ""
:user-info-url ""
;; it is not really needed but serves as an example of how to use a custom parser
:user-info-parse-fn #(-> % :body (parse-string true))
:on-success-handler on-github-success}
:google {:auth-url ""
:client-id (or (System/getenv "google_client_id") "client-id")
:client-secret (or (System/getenv "google_client_secret") "client-secret")
:callback-uri ""
:scope "profile email"
:token-url ""
:user-info-url ""
:on-success-handler on-google-success}})
(def common-interceptors [(body-params/body-params) http/html-body])
(def interactive-interceptors (into common-interceptors [access-forbidden-interceptor (interactive {})]))
(def http-basic-interceptors (into common-interceptors [(http-basic "Geheimtür Demo" credentials)]))
(def routes
#{["/" :get (conj common-interceptors `views/home-page)]
["/login" :get (conj common-interceptors `views/login-page)]
["/login" :post (conj common-interceptors (default-login-handler {:credential-fn credentials
:form-reader identity}))]
["/logout" :get (conj common-interceptors default-logout-handler)]
["/oauth.login" :get (conj common-interceptors (authenticate-handler providers))]
["/oauth.callback" :get (conj common-interceptors (callback-handler providers))]
["/unauthorized" :get (conj common-interceptors `views/unauthorized)]
["/interactive" :get (conj interactive-interceptors `views/interactive-index)]
["/interactive/restricted" :get (into interactive-interceptors [(guard :silent? false) `views/interactive-restricted])]
["/interactive/admin-restricted" :get (into interactive-interceptors [(guard :silent? false :roles #{:admin}) `views/interactive-admin-restricted])]
["/interactive/admin-restricted-hidden" :get (into interactive-interceptors [(guard :roles #{:admin}) `views/interactive-admin-restricted-hidden])]
["/http-basic" :get (conj http-basic-interceptors `views/http-basic-index)]
["/http-basic/restricted" :get (into http-basic-interceptors [(guard :silent? false) `views/http-basic-restricted])]
["/http-basic/admin-restricted" :get (into http-basic-interceptors [(guard :silent? false :roles #{:admin}) `views/http-basic-admin-restricted])]
["/http-basic/admin-restricted-hidden" :get (into http-basic-interceptors [(guard :roles #{:admin}) `views/http-basic-admin-restricted-hidden])]
["/token-based" :get (conj http-basic-interceptors `views/token-based-index)]
["/api/restricted" :get [http/json-body (token token-credentials :error-fn api-error) (guard :silent? false) `views/api-restricted]]
["/api/admin-restricted" :get [http/json-body (token token-credentials :error-fn api-error) (guard :silent? false :roles #{:admin}) `views/api-admin-restricted]]})
(def service {:env :prod
::http/routes routes
::http/resource-path "/public"
::http/not-found-interceptor not-found-interceptor
::http/type :jetty
::http/enable-session {:cookie-name "SID"
:store (cookie/cookie-store)}
::http/port (Integer/valueOf (or (System/getenv "PORT") "8080"))})
| null |
https://raw.githubusercontent.com/propan/geheimtur-demo/55bf863880739b7b262e0a19666a58be768a1b3a/src/geheimtur_demo/service.clj
|
clojure
|
it is not really needed but serves as an example of how to use a custom parser
|
(ns geheimtur-demo.service
(:require [io.pedestal.http :as http]
[io.pedestal.http.route :as route]
[io.pedestal.http.body-params :as body-params]
[io.pedestal.interceptor :as interceptor]
[io.pedestal.log :as log]
[geheimtur.interceptor :refer [interactive guard http-basic token]]
[geheimtur.impl.form-based :refer [default-login-handler default-logout-handler]]
[geheimtur.impl.oauth2 :refer [authenticate-handler callback-handler]]
[geheimtur.util.auth :as auth :refer [authenticate]]
[geheimtur-demo.views :as views]
[geheimtur-demo.users :refer [users]]
[cheshire.core :refer [parse-string]]
[ring.middleware.session.cookie :as cookie]
[ring.util.response :as ring-resp]
[ring.util.codec :as ring-codec]))
(defn credentials
[_ {:keys [username password]}]
(when-let [identity (get users username)]
(when (= password (:password identity))
(dissoc identity :password ))))
(defn token-credentials
[_ token]
(case token
"user-secret" (-> (get users "user") (dissoc :password))
"admin-secret" (-> (get users "admin") (dissoc :password))
nil))
(def access-forbidden-interceptor
(interceptor/interceptor
{:name ::access-forbidden-interceptor
:leave (fn [{:keys [response] :as ctx}]
(let [resp (if (or
(= 401 (:status response))
(= 403 (:status response)))
(->
(views/error-page {:title "Access Forbidden" :message (:body response)})
(ring-resp/content-type "text/html;charset=UTF-8"))
response)]
(assoc ctx :response resp)))}))
(def not-found-interceptor
(interceptor/interceptor
{:name ::not-found-interceptor
:leave (fn [{:keys [response] :as ctx}]
(let [resp (if-not (ring-resp/response? response)
(->
(views/error-page {:title "Not Found"
:message "We are sorry, but the page you are looking for does not exist."})
(ring-resp/content-type "text/html;charset=UTF-8"))
response)]
(assoc ctx :response resp)))}))
(defn api-error
[context error]
{:status 403
:headers {}
:body {:error (:reason error)}})
(defn on-github-success
[_ {:keys [identity return]}]
(let [user {:name (:login identity)
:roles #{:user}
:full-name (:name identity)}]
(->
(ring-resp/redirect return)
(authenticate user))))
(defn on-google-success
[_ {:keys [identity return]}]
(let [user {:name (:displayName identity)
:roles #{:user}
:full-name (:displayName identity)}]
(->
(ring-resp/redirect return)
(authenticate user))))
(def providers
{:github {:auth-url ""
:client-id (or (System/getenv "github_client_id") "client-id")
:client-secret (or (System/getenv "github_client_secret") "client-secret")
:scope "user:email"
:token-url ""
:user-info-url ""
:user-info-parse-fn #(-> % :body (parse-string true))
:on-success-handler on-github-success}
:google {:auth-url ""
:client-id (or (System/getenv "google_client_id") "client-id")
:client-secret (or (System/getenv "google_client_secret") "client-secret")
:callback-uri ""
:scope "profile email"
:token-url ""
:user-info-url ""
:on-success-handler on-google-success}})
(def common-interceptors [(body-params/body-params) http/html-body])
(def interactive-interceptors (into common-interceptors [access-forbidden-interceptor (interactive {})]))
(def http-basic-interceptors (into common-interceptors [(http-basic "Geheimtür Demo" credentials)]))
(def routes
#{["/" :get (conj common-interceptors `views/home-page)]
["/login" :get (conj common-interceptors `views/login-page)]
["/login" :post (conj common-interceptors (default-login-handler {:credential-fn credentials
:form-reader identity}))]
["/logout" :get (conj common-interceptors default-logout-handler)]
["/oauth.login" :get (conj common-interceptors (authenticate-handler providers))]
["/oauth.callback" :get (conj common-interceptors (callback-handler providers))]
["/unauthorized" :get (conj common-interceptors `views/unauthorized)]
["/interactive" :get (conj interactive-interceptors `views/interactive-index)]
["/interactive/restricted" :get (into interactive-interceptors [(guard :silent? false) `views/interactive-restricted])]
["/interactive/admin-restricted" :get (into interactive-interceptors [(guard :silent? false :roles #{:admin}) `views/interactive-admin-restricted])]
["/interactive/admin-restricted-hidden" :get (into interactive-interceptors [(guard :roles #{:admin}) `views/interactive-admin-restricted-hidden])]
["/http-basic" :get (conj http-basic-interceptors `views/http-basic-index)]
["/http-basic/restricted" :get (into http-basic-interceptors [(guard :silent? false) `views/http-basic-restricted])]
["/http-basic/admin-restricted" :get (into http-basic-interceptors [(guard :silent? false :roles #{:admin}) `views/http-basic-admin-restricted])]
["/http-basic/admin-restricted-hidden" :get (into http-basic-interceptors [(guard :roles #{:admin}) `views/http-basic-admin-restricted-hidden])]
["/token-based" :get (conj http-basic-interceptors `views/token-based-index)]
["/api/restricted" :get [http/json-body (token token-credentials :error-fn api-error) (guard :silent? false) `views/api-restricted]]
["/api/admin-restricted" :get [http/json-body (token token-credentials :error-fn api-error) (guard :silent? false :roles #{:admin}) `views/api-admin-restricted]]})
(def service {:env :prod
::http/routes routes
::http/resource-path "/public"
::http/not-found-interceptor not-found-interceptor
::http/type :jetty
::http/enable-session {:cookie-name "SID"
:store (cookie/cookie-store)}
::http/port (Integer/valueOf (or (System/getenv "PORT") "8080"))})
|
e163bb4f695816f06b58ae81e33822aa9851e57e1aa2b0276eb3f2e62382a911
|
antoniogarrote/clojure-grizzly-trial
|
xsd.clj
|
(comment
"XML Schema vocabulary"
)
(ns com.agh.webserver.framework.persistence.rdf.vocabularies.xsd)
(use 'com.agh.webserver.framework.persistence.rdf)
(defmethod rdf-ns :xsd [x]
"XMLSchema namespace: #"
(struct uri "#" :xsd))
(defn xsd-string []
(build-uri (rdf-ns :xsd) "string"))
(defn xsd-float []
(build-uri (rdf-ns :xsd) "float"))
(defn xsd-decimal []
(build-uri (rdf-ns :xsd) "decimal"))
(defn xsd-double []
(build-uri (rdf-ns :xsd) "double"))
(defn literal-string
"Builds a new literal string"
([value]
(build-literal value))
([value lang]
(build-literal value lang)))
(defn literal-decimal
"Builds a new literal decimal"
([value]
(build-literal value (xsd-decimal))))
(defn literal-double
"Builds a new literal double"
([value]
(build-literal value (xsd-double))))
(defn literal-float
"Builds a new literal float"
([value]
(build-literal value (xsd-float))))
;; to-rdf conversions
(defmethod to-rdf #=java.lang.Double [something]
(literal-double something))
(defmethod to-rdf #=java.lang.Float [something]
(literal-float something))
(defmethod to-rdf #=java.lang.Number [something]
(literal-decimal something))
(comment
"Tests"
)
(use 'clojure.contrib.test-is)
(deftest test-xsd-ns
(is (= (rdf-ns :xsd)
{:prefix "#", :value :xsd})))
(deftest test-xsd-string
(is (= (xsd-string)
{:prefix :xsd, :value "string"})))
(deftest test-literal-string-1
(is (= (literal-string "test")
{:value "test" :datatype {:prefix :xsd, :value "string"} :lang ""})))
(deftest test-literal-string-2
(is (= (literal-string "test" "en-GB")
{:value "test" :datatype {:prefix :xsd, :value "string"} :lang "en-GB"})))
(deftest test-xsd-float
(is (= (xsd-float)
{:prefix :xsd, :value "float"})))
(deftest test-xsd-decimal
(is (= (xsd-decimal)
{:prefix :xsd, :value "decimal"})))
(deftest test-xsd-double
(is (= (xsd-double)
{:prefix :xsd, :value "double"})))
(deftest test-literal-decimal
(is (= (literal-decimal 1)
{:value 1 :lang "" :datatype {:prefix :xsd, :value "decimal"}})))
(deftest test-literal-float
(is (= (literal-float 1.0)
{:value 1.0 :lang "" :datatype {:prefix :xsd, :value "float"}})))
(deftest test-literal-double
(is (= (literal-double 2)
{:value 2 :lang "" :datatype {:prefix :xsd, :value "double"}})))
(deftest test-to-rdf-double
(is (= (to-rdf 2.0)
{:value 2.0 :lang "" :datatype {:prefix :xsd, :value "double"}})))
(deftest test-to-rdf-decimal
(is (= (to-rdf 2)
{:value 2 :lang "" :datatype {:prefix :xsd, :value "decimal"}})))
| null |
https://raw.githubusercontent.com/antoniogarrote/clojure-grizzly-trial/9282179818cc5247b796dd6eb9ab6ccb721100a3/com/agh/webserver/framework/persistence/rdf/vocabularies/xsd.clj
|
clojure
|
to-rdf conversions
|
(comment
"XML Schema vocabulary"
)
(ns com.agh.webserver.framework.persistence.rdf.vocabularies.xsd)
(use 'com.agh.webserver.framework.persistence.rdf)
(defmethod rdf-ns :xsd [x]
"XMLSchema namespace: #"
(struct uri "#" :xsd))
(defn xsd-string []
(build-uri (rdf-ns :xsd) "string"))
(defn xsd-float []
(build-uri (rdf-ns :xsd) "float"))
(defn xsd-decimal []
(build-uri (rdf-ns :xsd) "decimal"))
(defn xsd-double []
(build-uri (rdf-ns :xsd) "double"))
(defn literal-string
"Builds a new literal string"
([value]
(build-literal value))
([value lang]
(build-literal value lang)))
(defn literal-decimal
"Builds a new literal decimal"
([value]
(build-literal value (xsd-decimal))))
(defn literal-double
"Builds a new literal double"
([value]
(build-literal value (xsd-double))))
(defn literal-float
"Builds a new literal float"
([value]
(build-literal value (xsd-float))))
(defmethod to-rdf #=java.lang.Double [something]
(literal-double something))
(defmethod to-rdf #=java.lang.Float [something]
(literal-float something))
(defmethod to-rdf #=java.lang.Number [something]
(literal-decimal something))
(comment
"Tests"
)
(use 'clojure.contrib.test-is)
(deftest test-xsd-ns
(is (= (rdf-ns :xsd)
{:prefix "#", :value :xsd})))
(deftest test-xsd-string
(is (= (xsd-string)
{:prefix :xsd, :value "string"})))
(deftest test-literal-string-1
(is (= (literal-string "test")
{:value "test" :datatype {:prefix :xsd, :value "string"} :lang ""})))
(deftest test-literal-string-2
(is (= (literal-string "test" "en-GB")
{:value "test" :datatype {:prefix :xsd, :value "string"} :lang "en-GB"})))
(deftest test-xsd-float
(is (= (xsd-float)
{:prefix :xsd, :value "float"})))
(deftest test-xsd-decimal
(is (= (xsd-decimal)
{:prefix :xsd, :value "decimal"})))
(deftest test-xsd-double
(is (= (xsd-double)
{:prefix :xsd, :value "double"})))
(deftest test-literal-decimal
(is (= (literal-decimal 1)
{:value 1 :lang "" :datatype {:prefix :xsd, :value "decimal"}})))
(deftest test-literal-float
(is (= (literal-float 1.0)
{:value 1.0 :lang "" :datatype {:prefix :xsd, :value "float"}})))
(deftest test-literal-double
(is (= (literal-double 2)
{:value 2 :lang "" :datatype {:prefix :xsd, :value "double"}})))
(deftest test-to-rdf-double
(is (= (to-rdf 2.0)
{:value 2.0 :lang "" :datatype {:prefix :xsd, :value "double"}})))
(deftest test-to-rdf-decimal
(is (= (to-rdf 2)
{:value 2 :lang "" :datatype {:prefix :xsd, :value "decimal"}})))
|
f37033c8d5c64ab5a5a1aa07b328c43489b53c77efe5b4bef13e3fa076a7c89c
|
broadinstitute/wfl
|
aou.clj
|
(ns wfl.module.aou
"Process Arrays for the All Of Us project."
(:require [clojure.spec.alpha :as s]
[clojure.string :as str]
[wfl.api.workloads :as workloads :refer [defoverload]]
[wfl.jdbc :as jdbc]
[wfl.log :as log]
[wfl.module.all :as all]
[wfl.module.batch :as batch]
[wfl.references :as references]
[wfl.service.cromwell :as cromwell]
[wfl.service.postgres :as postgres]
[wfl.util :as util]
[wfl.wfl :as wfl])
(:import [java.sql Timestamp]
[java.time Instant]))
This must agree with the cloud function .
;;
(def pipeline "AllOfUsArrays")
;; specs
(s/def ::analysis_version_number integer?)
(s/def ::chip_well_barcode string?)
(s/def ::append-to-aou-request (s/keys :req-un [::notifications ::all/uuid]))
(s/def ::append-to-aou-response (s/* ::workflow-inputs))
(s/def ::workflow-inputs (s/keys :req-un [::analysis_version_number
::chip_well_barcode]))
(s/def ::notifications (s/* ::sample))
(s/def ::sample (s/keys :req-un [::analysis_version_number
::chip_well_barcode]))
(def workflow-wdl
"The top-level WDL file and its version."
{:release "Arrays_v2.6.3"
:path "pipelines/broad/arrays/single_sample/Arrays.wdl"})
(def cromwell-label-map
"The WDL label applied to Cromwell metadata."
{(keyword wfl/the-name)
pipeline})
(def cromwell-label
"The WDL label applied to Cromwell metadata."
(let [[key value] (first cromwell-label-map)]
(str (name key) ":" value)))
(def fingerprinting
"Fingerprinting inputs for arrays."
{:fingerprint_genotypes_vcf_file nil
:fingerprint_genotypes_vcf_index_file nil
:haplotype_database_file "gs-public-data--broad-references/hg19/v0/Homo_sapiens_assembly19.haplotype_database.txt"
:variant_rsids_file "gs-references-private/hg19/v0/Homo_sapiens_assembly19.haplotype_database.snps.list"})
(def other-inputs
"Miscellaneous inputs for arrays."
{:contamination_controls_vcf nil
:subsampled_metrics_interval_list nil
:disk_size 100
:preemptible_tries 3})
(def ^:private known-cromwells
["-gotc-auth.gotc-dev.broadinstitute.org"
"-aou.gotc-prod.broadinstitute.org"])
(def ^:private inputs+options
[{:environment "dev"
:vault_token_path "gs-dsp-gotc-arrays-dev-tokens/arrayswdl.token"}
{:environment "prod"
:vault_token_path "gs-dsp-gotc-arrays-prod-tokens/arrayswdl.token"}])
(defn ^:private cromwell->inputs+options
"Map cromwell URL to workflow inputs and options for submitting an AllOfUs Arrays workflow.
The returned environment string here is just a default, input file may specify override."
[url]
((zipmap known-cromwells inputs+options) (util/de-slashify url)))
(defn ^:private is-known-cromwell-url?
[url]
(if-let [known-url (->> url
util/de-slashify
((set known-cromwells)))]
known-url
(throw (ex-info "Unknown Cromwell URL provided."
{:cromwell url
:known-cromwells known-cromwells}))))
(defn get-per-sample-inputs
"Throw or return per-sample INPUTS."
[inputs]
(let [mandatory-keys [:analysis_version_number
:bead_pool_manifest_file
:call_rate_threshold
:chip_well_barcode
:cluster_file
:extended_chip_manifest_file
:green_idat_cloud_path
:params_file
:red_idat_cloud_path
:reported_gender
:sample_alias
:sample_lsid]
optional-keys [;; genotype concordance inputs
:control_sample_vcf_file
:control_sample_vcf_index_file
:control_sample_intervals_file
:control_sample_name
cloud path of a thresholds file to be used with zCall
:zcall_thresholds_file
cloud path of the Illumina gender cluster file
:gender_cluster_file
arbitrary path to be used by BAFRegress
:minor_allele_frequency_file
some message - specified environment to override WFL 's
:environment
some message - specified vault token path to override WFL 's
:vault_token_path]
mandatory (select-keys inputs mandatory-keys)
optional (select-keys inputs optional-keys)
missing (vec (keep (fn [k] (when (nil? (k mandatory)) k)) mandatory-keys))]
(when (seq missing)
(throw (Exception. (format "Missing per-sample inputs: %s" missing))))
(merge optional mandatory)))
(defn make-inputs
"Return inputs for AoU Arrays processing in Cromwell given URL from PER-SAMPLE-INPUTS."
[url per-sample-inputs]
(-> (merge references/hg19-arrays-references
fingerprinting
other-inputs
(cromwell->inputs+options url)
(get-per-sample-inputs per-sample-inputs))
(update :environment str/lower-case)
(util/prefix-keys :Arrays.)))
(def ^:private default-options
{:use_relative_output_paths true
:read_from_cache true
:write_to_cache true
:default_runtime_attributes
{:zones "us-central1-a us-central1-b us-central1-c us-central1-f"
:maxRetries 1}})
(def ^:private primary-keys
"These uniquely identify a sample so use them as a primary key."
[:chip_well_barcode :analysis_version_number])
(defn make-labels
"Return labels for aou arrays pipeline from PER-SAMPLE-INPUTS and OTHER-LABELS."
[per-sample-inputs other-labels]
(merge cromwell-label-map
(select-keys per-sample-inputs primary-keys)
other-labels))
(defn ^:private submit-aou-workflow
"Submit one workflow to Cromwell URL given PER-SAMPLE-INPUTS,
WORKFLOW-OPTIONS and OTHER-LABELS."
[url per-sample-inputs workflow-options other-labels]
(cromwell/submit-workflow
url
workflow-wdl
(make-inputs url per-sample-inputs)
workflow-options
(make-labels per-sample-inputs other-labels)))
;; Update the workload table row with the name of the AllOfUsArrays table.
;; -numeric.html#DATATYPE-SERIAL
;;
(defn ^:private make-new-aou-workload!
"Use transaction `tx` to record a new `workload` and return its `id`."
[tx workload]
(let [id (->> workload (jdbc/insert! tx :workload) first :id)
table (format "%s_%09d" pipeline id)
table_seq (format "%s_id_seq" table)
kind (format (str/join \space ["UPDATE workload"
"SET pipeline = '%s'::pipeline"
"WHERE id = '%s'"]) pipeline id)
index (format "CREATE SEQUENCE %s AS bigint" table_seq)
work (format (str/join \space ["CREATE TABLE %s OF %s"
"(PRIMARY KEY"
"(analysis_version_number,"
"chip_well_barcode),"
"id WITH OPTIONS NOT NULL"
"DEFAULT nextval('%s'))"])
table pipeline table_seq)
alter (format "ALTER SEQUENCE %s OWNED BY %s.id" table_seq table)]
(jdbc/db-do-commands tx [kind index work alter])
(jdbc/update! tx :workload {:items table} ["id = ?" id])
id))
(defn ^:private add-aou-workload!
"Use transaction `tx` to find a workload matching `request`, or make a
new one, and return the workload's `id`. "
[tx request]
(let [{:keys [creator executor pipeline project output watchers]} request
slashified (util/slashify output)
{:keys [release path]} workflow-wdl
query-string (str/join \space ["SELECT * FROM workload"
"WHERE stopped is null"
"AND project = ?"
"AND pipeline = ?::pipeline"
"AND release = ?"
"AND output = ?"])
workloads (jdbc/query tx [query-string project pipeline
release slashified])
n (count workloads)]
(when (> n 1)
(log/error "Too many workloads" :count n :workloads workloads))
(if-let [workload (first workloads)]
(:id workload)
(let [{:keys [commit version]} (wfl/get-the-version)]
(make-new-aou-workload! tx {:commit commit
:creator creator
:executor executor
:output slashified
:project project
:release release
:uuid (random-uuid)
:version version
:watchers (pr-str watchers)
:wdl path})))))
(defn ^:private start-aou-workload!
"Use transaction `tx` to start `workload` so it becomes append-able."
[tx {:keys [id] :as workload}]
(if (:started workload)
workload
(let [now {:started (Timestamp/from (Instant/now))}]
(jdbc/update! tx :workload now ["id = ?" id])
(merge workload now))))
(defn ^:private primary-values [sample]
(mapv sample primary-keys))
(defn ^:private get-existing-samples [tx table samples]
(letfn [(extract-primary-values [xs]
(reduce (partial map conj) [#{""} #{-1}] (map primary-values xs)))
(assemble-query [[barcodes versions]]
(str/join " "
["SELECT chip_well_barcode, analysis_version_number FROM"
table
(format "WHERE chip_well_barcode in %s" barcodes)
(format "AND analysis_version_number in %s" versions)]))]
(->> samples
extract-primary-values
(map util/to-quoted-comma-separated-list)
assemble-query
(jdbc/query tx)
extract-primary-values)))
(defn ^:private remove-existing-samples
"Retain all `samples` with unique `known-keys`."
[samples known-keys]
(letfn [(go [[known-values xs] sample]
(let [values (primary-values sample)]
[(map conj known-values values)
(if-not (every? identity (map contains? known-values values))
(conj xs sample)
xs)]))]
(second (reduce go [known-keys []] samples))))
(defn append-to-workload!
"Use transaction `tx` to add `notifications` (samples) to `workload`.
Note: - The `workload` must be `started` in order to be append-able.
- All samples being appended will be submitted immediately."
[tx notifications {:keys [uuid items output executor] :as workload}]
(when-not (:started workload)
(throw (Exception. (format "Workload %s is not started" uuid))))
(when (:stopped workload)
(throw (Exception. (format "Workload %s has been stopped" uuid))))
(letfn [(submit! [url sample]
(let [output-path (str output
(str/join "/" (primary-values sample)))
workflow-options (util/deep-merge
default-options
{:final_workflow_outputs_dir output-path})]
(->> {:workload uuid}
(submit-aou-workflow url sample workflow-options)
str ; coerce java.util.UUID -> string
(assoc (select-keys sample primary-keys)
:updated (Timestamp/from (Instant/now))
:status "Submitted"
:uuid))))]
(let [executor (is-known-cromwell-url? executor)
submitted-samples (map (partial submit! executor)
(remove-existing-samples
notifications
(get-existing-samples
tx items notifications)))]
(jdbc/insert-multi! tx items submitted-samples)
submitted-samples)))
(defn ^:private aou-workflows
[tx {:keys [items] :as _workload}]
(batch/tag-workflows
(batch/pre-v0_4_0-deserialize-workflows (postgres/get-table tx items))))
(defn ^:private aou-workflows-by-filters
[tx {:keys [items] :as _workload} {:keys [status] :as _filters}]
(batch/tag-workflows
(batch/pre-v0_4_0-deserialize-workflows
(batch/query-workflows-with-status tx items status))))
(defmethod workloads/create-workload!
pipeline
[tx request]
(workloads/load-workload-for-id tx (add-aou-workload! tx request)))
(defoverload workloads/start-workload! pipeline start-aou-workload!)
(defoverload workloads/stop-workload! pipeline batch/stop-workload!)
(defmethod workloads/update-workload!
pipeline
[{:keys [id started stopped finished] :as _workload-record}]
(jdbc/with-db-transaction [tx (postgres/wfl-db-config)]
(letfn [(load-workload []
(workloads/load-workload-for-id tx id))
(update! [workload]
(batch/update-workflow-statuses! tx workload)
(when stopped
(batch/update-workload-status! tx workload))
(load-workload))]
(if (and started (not finished))
(update! (load-workload))
(load-workload)))))
(defoverload workloads/workflows pipeline aou-workflows)
(defoverload workloads/workflows-by-filters pipeline aou-workflows-by-filters)
(defoverload workloads/retry pipeline batch/retry-unsupported)
(defoverload workloads/load-workload-impl pipeline batch/load-batch-workload-impl)
(defoverload workloads/to-edn pipeline batch/workload-to-edn)
| null |
https://raw.githubusercontent.com/broadinstitute/wfl/ca30908a6b62aa3ea8e5e15c3b410263d0173ee9/api/src/wfl/module/aou.clj
|
clojure
|
specs
genotype concordance inputs
Update the workload table row with the name of the AllOfUsArrays table.
-numeric.html#DATATYPE-SERIAL
coerce java.util.UUID -> string
|
(ns wfl.module.aou
"Process Arrays for the All Of Us project."
(:require [clojure.spec.alpha :as s]
[clojure.string :as str]
[wfl.api.workloads :as workloads :refer [defoverload]]
[wfl.jdbc :as jdbc]
[wfl.log :as log]
[wfl.module.all :as all]
[wfl.module.batch :as batch]
[wfl.references :as references]
[wfl.service.cromwell :as cromwell]
[wfl.service.postgres :as postgres]
[wfl.util :as util]
[wfl.wfl :as wfl])
(:import [java.sql Timestamp]
[java.time Instant]))
This must agree with the cloud function .
(def pipeline "AllOfUsArrays")
(s/def ::analysis_version_number integer?)
(s/def ::chip_well_barcode string?)
(s/def ::append-to-aou-request (s/keys :req-un [::notifications ::all/uuid]))
(s/def ::append-to-aou-response (s/* ::workflow-inputs))
(s/def ::workflow-inputs (s/keys :req-un [::analysis_version_number
::chip_well_barcode]))
(s/def ::notifications (s/* ::sample))
(s/def ::sample (s/keys :req-un [::analysis_version_number
::chip_well_barcode]))
(def workflow-wdl
"The top-level WDL file and its version."
{:release "Arrays_v2.6.3"
:path "pipelines/broad/arrays/single_sample/Arrays.wdl"})
(def cromwell-label-map
"The WDL label applied to Cromwell metadata."
{(keyword wfl/the-name)
pipeline})
(def cromwell-label
"The WDL label applied to Cromwell metadata."
(let [[key value] (first cromwell-label-map)]
(str (name key) ":" value)))
(def fingerprinting
"Fingerprinting inputs for arrays."
{:fingerprint_genotypes_vcf_file nil
:fingerprint_genotypes_vcf_index_file nil
:haplotype_database_file "gs-public-data--broad-references/hg19/v0/Homo_sapiens_assembly19.haplotype_database.txt"
:variant_rsids_file "gs-references-private/hg19/v0/Homo_sapiens_assembly19.haplotype_database.snps.list"})
(def other-inputs
"Miscellaneous inputs for arrays."
{:contamination_controls_vcf nil
:subsampled_metrics_interval_list nil
:disk_size 100
:preemptible_tries 3})
(def ^:private known-cromwells
["-gotc-auth.gotc-dev.broadinstitute.org"
"-aou.gotc-prod.broadinstitute.org"])
(def ^:private inputs+options
[{:environment "dev"
:vault_token_path "gs-dsp-gotc-arrays-dev-tokens/arrayswdl.token"}
{:environment "prod"
:vault_token_path "gs-dsp-gotc-arrays-prod-tokens/arrayswdl.token"}])
(defn ^:private cromwell->inputs+options
"Map cromwell URL to workflow inputs and options for submitting an AllOfUs Arrays workflow.
The returned environment string here is just a default, input file may specify override."
[url]
((zipmap known-cromwells inputs+options) (util/de-slashify url)))
(defn ^:private is-known-cromwell-url?
[url]
(if-let [known-url (->> url
util/de-slashify
((set known-cromwells)))]
known-url
(throw (ex-info "Unknown Cromwell URL provided."
{:cromwell url
:known-cromwells known-cromwells}))))
(defn get-per-sample-inputs
"Throw or return per-sample INPUTS."
[inputs]
(let [mandatory-keys [:analysis_version_number
:bead_pool_manifest_file
:call_rate_threshold
:chip_well_barcode
:cluster_file
:extended_chip_manifest_file
:green_idat_cloud_path
:params_file
:red_idat_cloud_path
:reported_gender
:sample_alias
:sample_lsid]
:control_sample_vcf_file
:control_sample_vcf_index_file
:control_sample_intervals_file
:control_sample_name
cloud path of a thresholds file to be used with zCall
:zcall_thresholds_file
cloud path of the Illumina gender cluster file
:gender_cluster_file
arbitrary path to be used by BAFRegress
:minor_allele_frequency_file
some message - specified environment to override WFL 's
:environment
some message - specified vault token path to override WFL 's
:vault_token_path]
mandatory (select-keys inputs mandatory-keys)
optional (select-keys inputs optional-keys)
missing (vec (keep (fn [k] (when (nil? (k mandatory)) k)) mandatory-keys))]
(when (seq missing)
(throw (Exception. (format "Missing per-sample inputs: %s" missing))))
(merge optional mandatory)))
(defn make-inputs
"Return inputs for AoU Arrays processing in Cromwell given URL from PER-SAMPLE-INPUTS."
[url per-sample-inputs]
(-> (merge references/hg19-arrays-references
fingerprinting
other-inputs
(cromwell->inputs+options url)
(get-per-sample-inputs per-sample-inputs))
(update :environment str/lower-case)
(util/prefix-keys :Arrays.)))
(def ^:private default-options
{:use_relative_output_paths true
:read_from_cache true
:write_to_cache true
:default_runtime_attributes
{:zones "us-central1-a us-central1-b us-central1-c us-central1-f"
:maxRetries 1}})
(def ^:private primary-keys
"These uniquely identify a sample so use them as a primary key."
[:chip_well_barcode :analysis_version_number])
(defn make-labels
"Return labels for aou arrays pipeline from PER-SAMPLE-INPUTS and OTHER-LABELS."
[per-sample-inputs other-labels]
(merge cromwell-label-map
(select-keys per-sample-inputs primary-keys)
other-labels))
(defn ^:private submit-aou-workflow
"Submit one workflow to Cromwell URL given PER-SAMPLE-INPUTS,
WORKFLOW-OPTIONS and OTHER-LABELS."
[url per-sample-inputs workflow-options other-labels]
(cromwell/submit-workflow
url
workflow-wdl
(make-inputs url per-sample-inputs)
workflow-options
(make-labels per-sample-inputs other-labels)))
(defn ^:private make-new-aou-workload!
"Use transaction `tx` to record a new `workload` and return its `id`."
[tx workload]
(let [id (->> workload (jdbc/insert! tx :workload) first :id)
table (format "%s_%09d" pipeline id)
table_seq (format "%s_id_seq" table)
kind (format (str/join \space ["UPDATE workload"
"SET pipeline = '%s'::pipeline"
"WHERE id = '%s'"]) pipeline id)
index (format "CREATE SEQUENCE %s AS bigint" table_seq)
work (format (str/join \space ["CREATE TABLE %s OF %s"
"(PRIMARY KEY"
"(analysis_version_number,"
"chip_well_barcode),"
"id WITH OPTIONS NOT NULL"
"DEFAULT nextval('%s'))"])
table pipeline table_seq)
alter (format "ALTER SEQUENCE %s OWNED BY %s.id" table_seq table)]
(jdbc/db-do-commands tx [kind index work alter])
(jdbc/update! tx :workload {:items table} ["id = ?" id])
id))
(defn ^:private add-aou-workload!
"Use transaction `tx` to find a workload matching `request`, or make a
new one, and return the workload's `id`. "
[tx request]
(let [{:keys [creator executor pipeline project output watchers]} request
slashified (util/slashify output)
{:keys [release path]} workflow-wdl
query-string (str/join \space ["SELECT * FROM workload"
"WHERE stopped is null"
"AND project = ?"
"AND pipeline = ?::pipeline"
"AND release = ?"
"AND output = ?"])
workloads (jdbc/query tx [query-string project pipeline
release slashified])
n (count workloads)]
(when (> n 1)
(log/error "Too many workloads" :count n :workloads workloads))
(if-let [workload (first workloads)]
(:id workload)
(let [{:keys [commit version]} (wfl/get-the-version)]
(make-new-aou-workload! tx {:commit commit
:creator creator
:executor executor
:output slashified
:project project
:release release
:uuid (random-uuid)
:version version
:watchers (pr-str watchers)
:wdl path})))))
(defn ^:private start-aou-workload!
"Use transaction `tx` to start `workload` so it becomes append-able."
[tx {:keys [id] :as workload}]
(if (:started workload)
workload
(let [now {:started (Timestamp/from (Instant/now))}]
(jdbc/update! tx :workload now ["id = ?" id])
(merge workload now))))
(defn ^:private primary-values [sample]
(mapv sample primary-keys))
(defn ^:private get-existing-samples [tx table samples]
(letfn [(extract-primary-values [xs]
(reduce (partial map conj) [#{""} #{-1}] (map primary-values xs)))
(assemble-query [[barcodes versions]]
(str/join " "
["SELECT chip_well_barcode, analysis_version_number FROM"
table
(format "WHERE chip_well_barcode in %s" barcodes)
(format "AND analysis_version_number in %s" versions)]))]
(->> samples
extract-primary-values
(map util/to-quoted-comma-separated-list)
assemble-query
(jdbc/query tx)
extract-primary-values)))
(defn ^:private remove-existing-samples
"Retain all `samples` with unique `known-keys`."
[samples known-keys]
(letfn [(go [[known-values xs] sample]
(let [values (primary-values sample)]
[(map conj known-values values)
(if-not (every? identity (map contains? known-values values))
(conj xs sample)
xs)]))]
(second (reduce go [known-keys []] samples))))
(defn append-to-workload!
"Use transaction `tx` to add `notifications` (samples) to `workload`.
Note: - The `workload` must be `started` in order to be append-able.
- All samples being appended will be submitted immediately."
[tx notifications {:keys [uuid items output executor] :as workload}]
(when-not (:started workload)
(throw (Exception. (format "Workload %s is not started" uuid))))
(when (:stopped workload)
(throw (Exception. (format "Workload %s has been stopped" uuid))))
(letfn [(submit! [url sample]
(let [output-path (str output
(str/join "/" (primary-values sample)))
workflow-options (util/deep-merge
default-options
{:final_workflow_outputs_dir output-path})]
(->> {:workload uuid}
(submit-aou-workflow url sample workflow-options)
(assoc (select-keys sample primary-keys)
:updated (Timestamp/from (Instant/now))
:status "Submitted"
:uuid))))]
(let [executor (is-known-cromwell-url? executor)
submitted-samples (map (partial submit! executor)
(remove-existing-samples
notifications
(get-existing-samples
tx items notifications)))]
(jdbc/insert-multi! tx items submitted-samples)
submitted-samples)))
(defn ^:private aou-workflows
[tx {:keys [items] :as _workload}]
(batch/tag-workflows
(batch/pre-v0_4_0-deserialize-workflows (postgres/get-table tx items))))
(defn ^:private aou-workflows-by-filters
[tx {:keys [items] :as _workload} {:keys [status] :as _filters}]
(batch/tag-workflows
(batch/pre-v0_4_0-deserialize-workflows
(batch/query-workflows-with-status tx items status))))
(defmethod workloads/create-workload!
pipeline
[tx request]
(workloads/load-workload-for-id tx (add-aou-workload! tx request)))
(defoverload workloads/start-workload! pipeline start-aou-workload!)
(defoverload workloads/stop-workload! pipeline batch/stop-workload!)
(defmethod workloads/update-workload!
pipeline
[{:keys [id started stopped finished] :as _workload-record}]
(jdbc/with-db-transaction [tx (postgres/wfl-db-config)]
(letfn [(load-workload []
(workloads/load-workload-for-id tx id))
(update! [workload]
(batch/update-workflow-statuses! tx workload)
(when stopped
(batch/update-workload-status! tx workload))
(load-workload))]
(if (and started (not finished))
(update! (load-workload))
(load-workload)))))
(defoverload workloads/workflows pipeline aou-workflows)
(defoverload workloads/workflows-by-filters pipeline aou-workflows-by-filters)
(defoverload workloads/retry pipeline batch/retry-unsupported)
(defoverload workloads/load-workload-impl pipeline batch/load-batch-workload-impl)
(defoverload workloads/to-edn pipeline batch/workload-to-edn)
|
8b97456d903e69079de9b3b012adf62c4fe2a6b5d5cb76739b3b2a6c1105de62
|
CodyReichert/qi
|
tests.lisp
|
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; tests.lisp --- trivial-garbage tests.
;;;
This software is placed in the public domain by
;;; <> and is provided with absolutely no
;;; warranty.
(defpackage #:trivial-garbage-tests
(:use #:cl #:trivial-garbage #:regression-test)
(:nicknames #:tg-tests)
(:export #:run))
(in-package #:trivial-garbage-tests)
(defun run ()
(let ((*package* (find-package :trivial-garbage-tests)))
(do-tests)
(null (set-difference (regression-test:pending-tests)
rtest::*expected-failures*))))
;;;; Weak Pointers
(deftest pointers.1
(weak-pointer-p (make-weak-pointer 42))
t)
(deftest pointers.2
(weak-pointer-value (make-weak-pointer 42))
42)
;;;; Weak Hashtables
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun sbcl-without-weak-hash-tables-p ()
(if (and (find :sbcl *features*)
(not (find-symbol "HASH-TABLE-WEAKNESS" "SB-EXT")))
'(:and)
'(:or))))
#+(or corman scl #.(tg-tests::sbcl-without-weak-hash-tables-p))
(progn
(pushnew 'hashtables.weak-key.1 rt::*expected-failures*)
(pushnew 'hashtables.weak-key.2 rt::*expected-failures*)
(pushnew 'hashtables.weak-value.1 rt::*expected-failures*))
(deftest hashtables.weak-key.1
(let ((ht (make-weak-hash-table :weakness :key)))
(values (hash-table-p ht)
(hash-table-weakness ht)))
t :key)
(deftest hashtables.weak-key.2
(let ((ht (make-weak-hash-table :weakness :key :test 'eq)))
(values (hash-table-p ht)
(hash-table-weakness ht)))
t :key)
(deftest hashtables.weak-value.1
(let ((ht (make-weak-hash-table :weakness :value)))
(values (hash-table-p ht)
(hash-table-weakness ht)))
t :value)
(deftest hashtables.not-weak.1
(hash-table-weakness (make-hash-table))
nil)
;;;; Finalizers
;;;
;;; These tests are, of course, not very reliable.
(defun dummy (x)
(declare (ignore x))
nil)
(defun test-finalizers-aux (count extra-action)
(let ((cons (list 0))
(obj (string (gensym))))
(dotimes (i count)
(finalize obj (lambda () (incf (car cons)))))
(when extra-action
(cancel-finalization obj)
(when (eq extra-action :add-again)
(dotimes (i count)
(finalize obj (lambda () (incf (car cons)))))))
(setq obj (gensym))
(setq obj (dummy obj))
cons))
(defvar *result*)
;;; I don't really understand this, but it seems to work, and stems
;;; from the observation that typing the code in sequence at the REPL
;;; achieves the desired result. Superstition at its best.
(defmacro voodoo (string)
`(funcall
(compile nil `(lambda ()
(eval (let ((*package* (find-package :tg-tests)))
(read-from-string ,,string)))))))
(defun test-finalizers (count &optional remove)
(gc :full t)
(voodoo (format nil "(setq *result* (test-finalizers-aux ~S ~S))"
count remove))
(voodoo "(gc :full t)")
Normally done by a background thread every 0.3 sec :
#+openmcl (ccl::drain-termination-queue)
;; (an alternative is to sleep a bit)
(voodoo "(car *result*)"))
(deftest finalizers.1
(test-finalizers 1)
1)
(deftest finalizers.2
(test-finalizers 1 t)
0)
(deftest finalizers.3
(test-finalizers 5)
5)
(deftest finalizers.4
(test-finalizers 5 t)
0)
(deftest finalizers.5
(test-finalizers 5 :add-again)
5)
| null |
https://raw.githubusercontent.com/CodyReichert/qi/9cf6d31f40e19f4a7f60891ef7c8c0381ccac66f/dependencies/trivial-garbage-latest/tests.lisp
|
lisp
|
-*- Mode: lisp; indent-tabs-mode: nil -*-
tests.lisp --- trivial-garbage tests.
<> and is provided with absolutely no
warranty.
Weak Pointers
Weak Hashtables
Finalizers
These tests are, of course, not very reliable.
I don't really understand this, but it seems to work, and stems
from the observation that typing the code in sequence at the REPL
achieves the desired result. Superstition at its best.
(an alternative is to sleep a bit)
|
This software is placed in the public domain by
(defpackage #:trivial-garbage-tests
(:use #:cl #:trivial-garbage #:regression-test)
(:nicknames #:tg-tests)
(:export #:run))
(in-package #:trivial-garbage-tests)
(defun run ()
(let ((*package* (find-package :trivial-garbage-tests)))
(do-tests)
(null (set-difference (regression-test:pending-tests)
rtest::*expected-failures*))))
(deftest pointers.1
(weak-pointer-p (make-weak-pointer 42))
t)
(deftest pointers.2
(weak-pointer-value (make-weak-pointer 42))
42)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun sbcl-without-weak-hash-tables-p ()
(if (and (find :sbcl *features*)
(not (find-symbol "HASH-TABLE-WEAKNESS" "SB-EXT")))
'(:and)
'(:or))))
#+(or corman scl #.(tg-tests::sbcl-without-weak-hash-tables-p))
(progn
(pushnew 'hashtables.weak-key.1 rt::*expected-failures*)
(pushnew 'hashtables.weak-key.2 rt::*expected-failures*)
(pushnew 'hashtables.weak-value.1 rt::*expected-failures*))
(deftest hashtables.weak-key.1
(let ((ht (make-weak-hash-table :weakness :key)))
(values (hash-table-p ht)
(hash-table-weakness ht)))
t :key)
(deftest hashtables.weak-key.2
(let ((ht (make-weak-hash-table :weakness :key :test 'eq)))
(values (hash-table-p ht)
(hash-table-weakness ht)))
t :key)
(deftest hashtables.weak-value.1
(let ((ht (make-weak-hash-table :weakness :value)))
(values (hash-table-p ht)
(hash-table-weakness ht)))
t :value)
(deftest hashtables.not-weak.1
(hash-table-weakness (make-hash-table))
nil)
(defun dummy (x)
(declare (ignore x))
nil)
(defun test-finalizers-aux (count extra-action)
(let ((cons (list 0))
(obj (string (gensym))))
(dotimes (i count)
(finalize obj (lambda () (incf (car cons)))))
(when extra-action
(cancel-finalization obj)
(when (eq extra-action :add-again)
(dotimes (i count)
(finalize obj (lambda () (incf (car cons)))))))
(setq obj (gensym))
(setq obj (dummy obj))
cons))
(defvar *result*)
(defmacro voodoo (string)
`(funcall
(compile nil `(lambda ()
(eval (let ((*package* (find-package :tg-tests)))
(read-from-string ,,string)))))))
(defun test-finalizers (count &optional remove)
(gc :full t)
(voodoo (format nil "(setq *result* (test-finalizers-aux ~S ~S))"
count remove))
(voodoo "(gc :full t)")
Normally done by a background thread every 0.3 sec :
#+openmcl (ccl::drain-termination-queue)
(voodoo "(car *result*)"))
(deftest finalizers.1
(test-finalizers 1)
1)
(deftest finalizers.2
(test-finalizers 1 t)
0)
(deftest finalizers.3
(test-finalizers 5)
5)
(deftest finalizers.4
(test-finalizers 5 t)
0)
(deftest finalizers.5
(test-finalizers 5 :add-again)
5)
|
347cd887569f468877938a9ced44bb4a9d2f889047d99eb4e30e9f937fdb5fc0
|
ocamllabs/ocaml-modular-implicits
|
t19ok.ml
|
PR 4758 , PR 4266
module PR_4758 = struct
module type S = sig end
module type Mod = sig
module Other : S
end
module rec A : S = struct end
and C : sig include Mod with module Other = A end = struct
module Other = A
end
module C' = C (* check that we can take an alias *)
module F(X:sig end) = struct type t end
let f (x : F(C).t) = (x : F(C').t)
end
| null |
https://raw.githubusercontent.com/ocamllabs/ocaml-modular-implicits/92e45da5c8a4c2db8b2cd5be28a5bec2ac2181f1/testsuite/tests/typing-recmod/t19ok.ml
|
ocaml
|
check that we can take an alias
|
PR 4758 , PR 4266
module PR_4758 = struct
module type S = sig end
module type Mod = sig
module Other : S
end
module rec A : S = struct end
and C : sig include Mod with module Other = A end = struct
module Other = A
end
module F(X:sig end) = struct type t end
let f (x : F(C).t) = (x : F(C').t)
end
|
ee23d396dc5e06ca1fc68bc070de7df0413b25ec4956f08474bccf937d3f9bb7
|
qfpl/reflex-workshop
|
Fmap.hs
|
|
Copyright : ( c ) 2018 , Commonwealth Scientific and Industrial Research Organisation
License : :
Stability : experimental
Portability : non - portable
Copyright : (c) 2018, Commonwealth Scientific and Industrial Research Organisation
License : BSD3
Maintainer :
Stability : experimental
Portability : non-portable
-}
module Solutions.Behaviors.Instances.Fmap (
fmapSolution
) where
import Reflex
fmapSolution :: Reflex t
=> Behavior t Int
-> Behavior t Int
fmapSolution bIn =
(* 5) <$> bIn
| null |
https://raw.githubusercontent.com/qfpl/reflex-workshop/244ef13fb4b2e884f455eccc50072e98d1668c9e/src/Solutions/Behaviors/Instances/Fmap.hs
|
haskell
|
|
Copyright : ( c ) 2018 , Commonwealth Scientific and Industrial Research Organisation
License : :
Stability : experimental
Portability : non - portable
Copyright : (c) 2018, Commonwealth Scientific and Industrial Research Organisation
License : BSD3
Maintainer :
Stability : experimental
Portability : non-portable
-}
module Solutions.Behaviors.Instances.Fmap (
fmapSolution
) where
import Reflex
fmapSolution :: Reflex t
=> Behavior t Int
-> Behavior t Int
fmapSolution bIn =
(* 5) <$> bIn
|
|
95529ae660de8eaa1ead2d08e58f5de49e7434aef2dd8540e2ed8e0ca8fd5a3a
|
acieroid/scala-am
|
pcounter4.scm
|
(letrec ((counter 0)
(thread (lambda (n)
(letrec ((old counter)
(new (+ old 1)))
(if (cas counter old new)
#t
(thread n)))))
(t1 (fork (thread 1)))
(t2 (fork (thread 2)))
(t3 (fork (thread 3)))
(t4 (fork (thread 4))))
(join t1)
(join t2)
(join t3)
(join t4))
| null |
https://raw.githubusercontent.com/acieroid/scala-am/13ef3befbfc664b77f31f56847c30d60f4ee7dfe/test/concurrentScheme/threads/variations/pcounter4.scm
|
scheme
|
(letrec ((counter 0)
(thread (lambda (n)
(letrec ((old counter)
(new (+ old 1)))
(if (cas counter old new)
#t
(thread n)))))
(t1 (fork (thread 1)))
(t2 (fork (thread 2)))
(t3 (fork (thread 3)))
(t4 (fork (thread 4))))
(join t1)
(join t2)
(join t3)
(join t4))
|
|
6150f9ac4af661d8618dc48da35ad55d2f48b5cdd49b8d6c4e15f1d20bf5c307
|
sigscale/radierl
|
radius_example_accounting_SUITE.erl
|
%%%---------------------------------------------------------------------
2016 - 2017 SigScale Global Inc
@author < > [ ]
%%% @end
%%%
Copyright ( c ) 2016 - 2017 , SigScale Global Inc
%%%
%%% All rights reserved.
%%%
%%% Redistribution and use in source and binary forms, with or without
%%% modification, are permitted provided that the following conditions
%%% are met:
%%%
%%% - Redistributions of source code must retain the above copyright
%%% notice, this list of conditions and the following disclaimer.
%%% - Redistributions in binary form must reproduce the above copyright
%%% notice, this list of conditions and the following disclaimer in
%%% the documentation and/or other materials provided with the
%%% distribution.
- Neither the name of SigScale Global Inc nor the names of its
%%% contributors may be used to endorse or promote products derived
%%% from this software without specific prior written permission.
%%%
%%% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
%%% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
%%% A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE ,
%%% DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
%%% (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
%%% OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
%%%
%%%---------------------------------------------------------------------
@doc Radius authentication callback module tests
%%%--------------------------------------------------------------------
%%%
-module(radius_example_accounting_SUITE).
%% common_test required callbacks
-export([suite/0, init_per_suite/1, end_per_suite/1, sequences/0, all/0]).
-compile(export_all).
-include_lib("common_test/include/ct.hrl").
-include("radius.hrl").
-define(TIMEOUT, 2000).
%%---------------------------------------------------------------------
%% Test server callback functions
%%---------------------------------------------------------------------
( ) - > DefaultData
DefaultData = [ tuple ( ) ]
%% @doc Require variables and set default values for the suite.
%%
suite() ->
[{timetrap, {minutes, 1}}].
%% @spec (Config) -> Config
%% Config = [tuple()]
%% @doc Initiation before the whole suite.
init_per_suite(Config) ->
SharedSecret = "xyzzy5461",
ok = application:start(radius),
DbDir = ?config(priv_dir, Config) ++ "/db",
application:load(mnesia),
ok = application:set_env(mnesia, dir, DbDir),
ok = mnesia:create_schema([node()]),
ok = application:start(mnesia),
{ok, [radius_client, radius_user]} = radius_example:install([node()]),
LogDir = ?config(priv_dir, Config) ++ "log",
ok = file:make_dir(LogDir),
application:load(radius_example),
ok = application:set_env(radius_example, accounting_dir, LogDir),
ok = application:start(radius_example),
{ok, Port} = application:get_env(radius_example, accounting_port),
[{secret, SharedSecret}, {port, Port}, {log_dir, LogDir} | Config].
%% @spec (Config) -> any()
%% Config = [tuple()]
%% @doc Cleanup after the whole suite.
%%
end_per_suite(_Config) ->
ok = application:stop(radius_example),
{atomic, ok} = mnesia:delete_table(radius_user),
{atomic, ok} = mnesia:delete_table(radius_client),
ok = application:stop(mnesia),
ok = mnesia:delete_schema([node()]),
ok = application:stop(radius).
( TestCase , Config ) - > Config
%% Config = [tuple()]
%% @doc Initiation before each test case.
%%
init_per_testcase(_TestCase, Config) ->
{ok, Socket} = gen_udp:open(0, [{active, false}, inet,
{ip, {127, 0, 0, 1}}, binary]),
[{socket, Socket} | Config].
( TestCase , Config ) - > any ( )
%% Config = [tuple()]
%% @doc Cleanup after each test case.
%%
end_per_testcase(_TestCase, Config) ->
Socket = ?config(socket, Config),
ok = gen_udp:close(Socket).
( ) - > Sequences
%% Sequences = [{SeqName, Testcases}]
%% SeqName = atom()
%% Testcases = [atom()]
%% @doc Group test cases into a test sequence.
%%
sequences() ->
[].
( ) - > TestCases
%% TestCases = [Case]
%% Case = atom()
%% @doc Returns a list of all test cases in this test suite.
%%
all() ->
[client_unknown, client, accounting_on, start, interim_update, stop,
accounting_off, log_file].
%%---------------------------------------------------------------------
%% Test cases
%%---------------------------------------------------------------------
client() ->
[{userdata, [{doc, "Add client to database"}]}].
client(Config) ->
Address = {127, 0, 0, 1},
Secret = ?config(secret, Config),
ok = radius_example:add_client(Address, Secret),
{ok, Secret} = radius_example:find_client(Address).
client_unknown() ->
[{userdata, [{doc, "Request from unkown client"}]}].
client_unknown(Config) ->
Id = 0,
RequestAuthenticator = radius:authenticator(),
Attributes0 = radius_attributes:new(),
Attributes = radius_attributes:codec(Attributes0),
Request = radius:codec(#radius{code = ?AccessRequest, id = Id,
authenticator = RequestAuthenticator, attributes = Attributes}),
Address = {127, 0, 0, 1},
Socket = ?config(socket, Config),
Port = ?config(port, Config),
ok = gen_udp:send(Socket, Address, Port, Request),
{error, timeout} = gen_udp:recv(Socket, 0, ?TIMEOUT).
accounting_on() ->
[{userdata, [{doc, "Accounting request; accounting on"}]}].
accounting_on(Config) ->
Id = 0,
Attributes0 = radius_attributes:new(),
Attributes1 = radius_attributes:store(?NasIpAddress,
{192, 168, 1, 16}, Attributes0),
Attributes2 = radius_attributes:store(?AcctStatusType, 7, Attributes1),
Attributes3 = radius_attributes:store(?AcctSessionId, "00000000", Attributes2),
send(Id, Attributes3, Config).
start() ->
[{userdata, [{doc, "Accounting request; user service start"}]}].
start(Config) ->
Id = 1,
UserName = "nemo",
Attributes0 = radius_attributes:new(),
Attributes1 = radius_attributes:store(?AcctStatusType, 1, Attributes0),
Attributes2 = radius_attributes:store(?UserName, UserName, Attributes1),
Attributes3 = radius_attributes:store(?NasIpAddress,
{192, 168, 1, 16}, Attributes2),
Attributes4 = radius_attributes:store(?NasPort, 3, Attributes3),
Attributes5 = radius_attributes:store(?FramedIpAddress,
{172, 30, 1, 116}, Attributes4),
Attributes6 = radius_attributes:store(?AcctSessionId, "00000001", Attributes5),
Attributes7 = radius_attributes:store(?AcctAuthentic, 1, Attributes6),
send(Id, Attributes7, Config).
interim_update() ->
[{userdata, [{doc, "Accounting request; user service interim update"}]}].
interim_update(Config) ->
Id = 2,
Attributes0 = radius_attributes:new(),
Attributes1 = radius_attributes:store(?AcctStatusType, 3, Attributes0),
Attributes2 = radius_attributes:store(?NasIpAddress,
{192, 168, 1, 16}, Attributes1),
Attributes3 = radius_attributes:store(?AcctSessionId, "00000001", Attributes2),
Attributes4 = radius_attributes:store(?AcctSessionTime, 3600, Attributes3),
Attributes5 = radius_attributes:store(?AcctInputOctets, 1231234, Attributes4),
Attributes6 = radius_attributes:store(?AcctOutputOctets, 1234512345, Attributes5),
Attributes7 = radius_attributes:store(?AcctInputPackets, 1234, Attributes6),
Attributes8 = radius_attributes:store(?AcctInputPackets, 16543, Attributes7),
send(Id, Attributes8, Config).
stop() ->
[{userdata, [{doc, "Accounting request; user service stop"}]}].
stop(Config) ->
Id = 3,
UserName = "nemo",
Attributes0 = radius_attributes:new(),
Attributes1 = radius_attributes:store(?AcctStatusType, 2, Attributes0),
Attributes2 = radius_attributes:store(?UserName, UserName, Attributes1),
Attributes3 = radius_attributes:store(?NasIpAddress,
{192, 168, 1, 16}, Attributes2),
Attributes4 = radius_attributes:store(?NasPort, 3, Attributes3),
Attributes5 = radius_attributes:store(?AcctSessionId, "00000001", Attributes4),
Attributes6 = radius_attributes:store(?AcctSessionTime, 3610, Attributes5),
Attributes7 = radius_attributes:store(?AcctInputOctets, 1234567, Attributes6),
Attributes8 = radius_attributes:store(?AcctOutputOctets, 1234567890, Attributes7),
Attributes9 = radius_attributes:store(?AcctInputPackets, 1678, Attributes8),
Attributes10 = radius_attributes:store(?AcctInputPackets, 16789, Attributes9),
Attributes11 = radius_attributes:store(?AcctTerminateCause, 1, Attributes10),
send(Id, Attributes11, Config).
accounting_off() ->
[{userdata, [{doc, "Accounting request; accounting stop"}]}].
accounting_off(Config) ->
Id = 4,
Attributes0 = radius_attributes:new(),
Attributes1 = radius_attributes:store(?AcctStatusType, 7, Attributes0),
Attributes2 = radius_attributes:store(?AcctSessionId, "00000000", Attributes1),
Attributes3 = radius_attributes:store(?NasIpAddress,
{192, 168, 1, 16}, Attributes2),
send(Id, Attributes3, Config).
log_file() ->
[{userdata, [{doc, "Write log to file"}]}].
log_file(Config) ->
Dir = ?config(log_dir, Config),
FileName = Dir ++ "/radius_acct.txt",
ok = radius_example:log_file(FileName),
{ok, _Binary} = file:read_file(FileName).
%%---------------------------------------------------------------------
%% Internal functions
%%---------------------------------------------------------------------
send(Id, AttributeList, Config) ->
SharedSecret = ?config(secret, Config),
Attributes = radius_attributes:codec(AttributeList),
RequestLength = size(Attributes) + 20,
RequestAuthenticator = crypto:hash(md5, [<<?AccountingRequest, Id,
RequestLength:16, 0:128>>, Attributes, SharedSecret]),
Request = radius:codec(#radius{code = ?AccountingRequest, id = Id,
authenticator = RequestAuthenticator, attributes = Attributes}),
Socket = ?config(socket, Config),
Address = {127, 0, 0, 1},
Port = ?config(port, Config),
ok = gen_udp:send(Socket, Address, Port, Request),
{ok, {Address, Port, Response}} = gen_udp:recv(Socket, 0, ?TIMEOUT),
#radius{code = ?AccountingResponse, id = Id,
authenticator = ResponseAuthenticator,
attributes = BinaryResponseAttributes} = radius:codec(Response),
ResponseLength = binary:decode_unsigned(binary:part(Response, 2, 2)),
Hash = crypto:hash(md5, [<<?AccountingResponse, Id, ResponseLength:16>>,
RequestAuthenticator, BinaryResponseAttributes, SharedSecret]),
ResponseAuthenticator = binary_to_list(Hash),
[] = radius_attributes:codec(BinaryResponseAttributes).
| null |
https://raw.githubusercontent.com/sigscale/radierl/2d0b70e7c7d001cc07d31859385904d72e8a5a20/examples/test/radius_example_accounting_SUITE.erl
|
erlang
|
---------------------------------------------------------------------
@end
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------
--------------------------------------------------------------------
common_test required callbacks
---------------------------------------------------------------------
Test server callback functions
---------------------------------------------------------------------
@doc Require variables and set default values for the suite.
@spec (Config) -> Config
Config = [tuple()]
@doc Initiation before the whole suite.
@spec (Config) -> any()
Config = [tuple()]
@doc Cleanup after the whole suite.
Config = [tuple()]
@doc Initiation before each test case.
Config = [tuple()]
@doc Cleanup after each test case.
Sequences = [{SeqName, Testcases}]
SeqName = atom()
Testcases = [atom()]
@doc Group test cases into a test sequence.
TestCases = [Case]
Case = atom()
@doc Returns a list of all test cases in this test suite.
---------------------------------------------------------------------
Test cases
---------------------------------------------------------------------
---------------------------------------------------------------------
Internal functions
---------------------------------------------------------------------
|
2016 - 2017 SigScale Global Inc
@author < > [ ]
Copyright ( c ) 2016 - 2017 , SigScale Global Inc
- Neither the name of SigScale Global Inc nor the names of its
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE ,
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
@doc Radius authentication callback module tests
-module(radius_example_accounting_SUITE).
-export([suite/0, init_per_suite/1, end_per_suite/1, sequences/0, all/0]).
-compile(export_all).
-include_lib("common_test/include/ct.hrl").
-include("radius.hrl").
-define(TIMEOUT, 2000).
( ) - > DefaultData
DefaultData = [ tuple ( ) ]
suite() ->
[{timetrap, {minutes, 1}}].
init_per_suite(Config) ->
SharedSecret = "xyzzy5461",
ok = application:start(radius),
DbDir = ?config(priv_dir, Config) ++ "/db",
application:load(mnesia),
ok = application:set_env(mnesia, dir, DbDir),
ok = mnesia:create_schema([node()]),
ok = application:start(mnesia),
{ok, [radius_client, radius_user]} = radius_example:install([node()]),
LogDir = ?config(priv_dir, Config) ++ "log",
ok = file:make_dir(LogDir),
application:load(radius_example),
ok = application:set_env(radius_example, accounting_dir, LogDir),
ok = application:start(radius_example),
{ok, Port} = application:get_env(radius_example, accounting_port),
[{secret, SharedSecret}, {port, Port}, {log_dir, LogDir} | Config].
end_per_suite(_Config) ->
ok = application:stop(radius_example),
{atomic, ok} = mnesia:delete_table(radius_user),
{atomic, ok} = mnesia:delete_table(radius_client),
ok = application:stop(mnesia),
ok = mnesia:delete_schema([node()]),
ok = application:stop(radius).
( TestCase , Config ) - > Config
init_per_testcase(_TestCase, Config) ->
{ok, Socket} = gen_udp:open(0, [{active, false}, inet,
{ip, {127, 0, 0, 1}}, binary]),
[{socket, Socket} | Config].
( TestCase , Config ) - > any ( )
end_per_testcase(_TestCase, Config) ->
Socket = ?config(socket, Config),
ok = gen_udp:close(Socket).
( ) - > Sequences
sequences() ->
[].
( ) - > TestCases
all() ->
[client_unknown, client, accounting_on, start, interim_update, stop,
accounting_off, log_file].
client() ->
[{userdata, [{doc, "Add client to database"}]}].
client(Config) ->
Address = {127, 0, 0, 1},
Secret = ?config(secret, Config),
ok = radius_example:add_client(Address, Secret),
{ok, Secret} = radius_example:find_client(Address).
client_unknown() ->
[{userdata, [{doc, "Request from unkown client"}]}].
client_unknown(Config) ->
Id = 0,
RequestAuthenticator = radius:authenticator(),
Attributes0 = radius_attributes:new(),
Attributes = radius_attributes:codec(Attributes0),
Request = radius:codec(#radius{code = ?AccessRequest, id = Id,
authenticator = RequestAuthenticator, attributes = Attributes}),
Address = {127, 0, 0, 1},
Socket = ?config(socket, Config),
Port = ?config(port, Config),
ok = gen_udp:send(Socket, Address, Port, Request),
{error, timeout} = gen_udp:recv(Socket, 0, ?TIMEOUT).
accounting_on() ->
[{userdata, [{doc, "Accounting request; accounting on"}]}].
accounting_on(Config) ->
Id = 0,
Attributes0 = radius_attributes:new(),
Attributes1 = radius_attributes:store(?NasIpAddress,
{192, 168, 1, 16}, Attributes0),
Attributes2 = radius_attributes:store(?AcctStatusType, 7, Attributes1),
Attributes3 = radius_attributes:store(?AcctSessionId, "00000000", Attributes2),
send(Id, Attributes3, Config).
start() ->
[{userdata, [{doc, "Accounting request; user service start"}]}].
start(Config) ->
Id = 1,
UserName = "nemo",
Attributes0 = radius_attributes:new(),
Attributes1 = radius_attributes:store(?AcctStatusType, 1, Attributes0),
Attributes2 = radius_attributes:store(?UserName, UserName, Attributes1),
Attributes3 = radius_attributes:store(?NasIpAddress,
{192, 168, 1, 16}, Attributes2),
Attributes4 = radius_attributes:store(?NasPort, 3, Attributes3),
Attributes5 = radius_attributes:store(?FramedIpAddress,
{172, 30, 1, 116}, Attributes4),
Attributes6 = radius_attributes:store(?AcctSessionId, "00000001", Attributes5),
Attributes7 = radius_attributes:store(?AcctAuthentic, 1, Attributes6),
send(Id, Attributes7, Config).
interim_update() ->
[{userdata, [{doc, "Accounting request; user service interim update"}]}].
interim_update(Config) ->
Id = 2,
Attributes0 = radius_attributes:new(),
Attributes1 = radius_attributes:store(?AcctStatusType, 3, Attributes0),
Attributes2 = radius_attributes:store(?NasIpAddress,
{192, 168, 1, 16}, Attributes1),
Attributes3 = radius_attributes:store(?AcctSessionId, "00000001", Attributes2),
Attributes4 = radius_attributes:store(?AcctSessionTime, 3600, Attributes3),
Attributes5 = radius_attributes:store(?AcctInputOctets, 1231234, Attributes4),
Attributes6 = radius_attributes:store(?AcctOutputOctets, 1234512345, Attributes5),
Attributes7 = radius_attributes:store(?AcctInputPackets, 1234, Attributes6),
Attributes8 = radius_attributes:store(?AcctInputPackets, 16543, Attributes7),
send(Id, Attributes8, Config).
stop() ->
[{userdata, [{doc, "Accounting request; user service stop"}]}].
stop(Config) ->
Id = 3,
UserName = "nemo",
Attributes0 = radius_attributes:new(),
Attributes1 = radius_attributes:store(?AcctStatusType, 2, Attributes0),
Attributes2 = radius_attributes:store(?UserName, UserName, Attributes1),
Attributes3 = radius_attributes:store(?NasIpAddress,
{192, 168, 1, 16}, Attributes2),
Attributes4 = radius_attributes:store(?NasPort, 3, Attributes3),
Attributes5 = radius_attributes:store(?AcctSessionId, "00000001", Attributes4),
Attributes6 = radius_attributes:store(?AcctSessionTime, 3610, Attributes5),
Attributes7 = radius_attributes:store(?AcctInputOctets, 1234567, Attributes6),
Attributes8 = radius_attributes:store(?AcctOutputOctets, 1234567890, Attributes7),
Attributes9 = radius_attributes:store(?AcctInputPackets, 1678, Attributes8),
Attributes10 = radius_attributes:store(?AcctInputPackets, 16789, Attributes9),
Attributes11 = radius_attributes:store(?AcctTerminateCause, 1, Attributes10),
send(Id, Attributes11, Config).
accounting_off() ->
[{userdata, [{doc, "Accounting request; accounting stop"}]}].
accounting_off(Config) ->
Id = 4,
Attributes0 = radius_attributes:new(),
Attributes1 = radius_attributes:store(?AcctStatusType, 7, Attributes0),
Attributes2 = radius_attributes:store(?AcctSessionId, "00000000", Attributes1),
Attributes3 = radius_attributes:store(?NasIpAddress,
{192, 168, 1, 16}, Attributes2),
send(Id, Attributes3, Config).
log_file() ->
[{userdata, [{doc, "Write log to file"}]}].
log_file(Config) ->
Dir = ?config(log_dir, Config),
FileName = Dir ++ "/radius_acct.txt",
ok = radius_example:log_file(FileName),
{ok, _Binary} = file:read_file(FileName).
send(Id, AttributeList, Config) ->
SharedSecret = ?config(secret, Config),
Attributes = radius_attributes:codec(AttributeList),
RequestLength = size(Attributes) + 20,
RequestAuthenticator = crypto:hash(md5, [<<?AccountingRequest, Id,
RequestLength:16, 0:128>>, Attributes, SharedSecret]),
Request = radius:codec(#radius{code = ?AccountingRequest, id = Id,
authenticator = RequestAuthenticator, attributes = Attributes}),
Socket = ?config(socket, Config),
Address = {127, 0, 0, 1},
Port = ?config(port, Config),
ok = gen_udp:send(Socket, Address, Port, Request),
{ok, {Address, Port, Response}} = gen_udp:recv(Socket, 0, ?TIMEOUT),
#radius{code = ?AccountingResponse, id = Id,
authenticator = ResponseAuthenticator,
attributes = BinaryResponseAttributes} = radius:codec(Response),
ResponseLength = binary:decode_unsigned(binary:part(Response, 2, 2)),
Hash = crypto:hash(md5, [<<?AccountingResponse, Id, ResponseLength:16>>,
RequestAuthenticator, BinaryResponseAttributes, SharedSecret]),
ResponseAuthenticator = binary_to_list(Hash),
[] = radius_attributes:codec(BinaryResponseAttributes).
|
b4e22f4e5479f17a30dfe217cb6b26dd6254bb65df2835352481983015f1a404
|
clj-commons/seesaw
|
keystroke.clj
|
Copyright ( c ) , 2011 . All rights reserved .
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (-1.0.php)
; which can be found in the file epl-v10.html at the root of this
; distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns seesaw.test.keystroke
(:use seesaw.keystroke)
(:use [lazytest.describe :only (describe it testing)]
[lazytest.expect :only (expect)])
(:import [javax.swing KeyStroke]
[java.awt Toolkit]))
(describe keystroke
(it "creates a keystroke from a descriptor string"
(let [ks (keystroke "ctrl S")]
(expect (= KeyStroke (class ks)))
(expect (= java.awt.event.KeyEvent/VK_S (.getKeyCode ks))))))
(describe keystroke
(it "returns nil for nil input"
(nil? (keystroke nil)))
(it "returns input if it's a KeyStroke"
(let [ks (KeyStroke/getKeyStroke "alt X")]
(expect (= ks (keystroke ks)))))
(it "returns a keystroke for a string"
(let [ks (keystroke "alt X")]
(expect (= java.awt.event.KeyEvent/VK_X (.getKeyCode ks)))))
(it "substitute platform-specific menu modifier for \"menu\" modifier"
(let [ks (keystroke "menu X")]
(expect (= java.awt.event.KeyEvent/VK_X (.getKeyCode ks)))
(expect (= (.. (Toolkit/getDefaultToolkit) getMenuShortcutKeyMask) (bit-and 7 (.getModifiers ks))))))
(it "returns a keystroke for a char"
(let [ks (keystroke \A)]
(expect (= \A (.getKeyChar ks))))))
| null |
https://raw.githubusercontent.com/clj-commons/seesaw/4ca89d0dcdf0557d99d5fa84202b7cc6e2e92263/test/seesaw/test/keystroke.clj
|
clojure
|
The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this
distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software.
|
Copyright ( c ) , 2011 . All rights reserved .
(ns seesaw.test.keystroke
(:use seesaw.keystroke)
(:use [lazytest.describe :only (describe it testing)]
[lazytest.expect :only (expect)])
(:import [javax.swing KeyStroke]
[java.awt Toolkit]))
(describe keystroke
(it "creates a keystroke from a descriptor string"
(let [ks (keystroke "ctrl S")]
(expect (= KeyStroke (class ks)))
(expect (= java.awt.event.KeyEvent/VK_S (.getKeyCode ks))))))
(describe keystroke
(it "returns nil for nil input"
(nil? (keystroke nil)))
(it "returns input if it's a KeyStroke"
(let [ks (KeyStroke/getKeyStroke "alt X")]
(expect (= ks (keystroke ks)))))
(it "returns a keystroke for a string"
(let [ks (keystroke "alt X")]
(expect (= java.awt.event.KeyEvent/VK_X (.getKeyCode ks)))))
(it "substitute platform-specific menu modifier for \"menu\" modifier"
(let [ks (keystroke "menu X")]
(expect (= java.awt.event.KeyEvent/VK_X (.getKeyCode ks)))
(expect (= (.. (Toolkit/getDefaultToolkit) getMenuShortcutKeyMask) (bit-and 7 (.getModifiers ks))))))
(it "returns a keystroke for a char"
(let [ks (keystroke \A)]
(expect (= \A (.getKeyChar ks))))))
|
f00a36ec3e19abfb56ad9a8a3ef640c0f35d2b6d0104b7298df82249f34ec12d
|
robdockins/edison
|
Defaults.hs
|
-- |
-- Module : Data.Edison.Seq.Defaults
Copyright : Copyright ( c ) 1998 , 2008
License : MIT ; see COPYRIGHT file for terms and conditions
--
Maintainer : robdockins AT fastmail DOT fm
-- Stability : internal (unstable)
Portability : GHC , Hugs ( MPTC and FD )
--
-- This module provides default implementations of many of
-- the sequence operations. It is used to fill in implementations
-- and is not intended for end users.
module Data.Edison.Seq.Defaults where
import Prelude hiding (concat,reverse,map,concatMap,foldr,foldl,foldr1,foldl1,
filter,takeWhile,dropWhile,lookup,take,drop,splitAt,
zip,zip3,zipWith,zipWith3,unzip,unzip3,null)
import qualified Control.Monad.Fail as Fail
import Control.Monad
import Data.Char (isSpace)
import Data.Edison.Prelude ( runFail_ )
import Data.Edison.Seq
import qualified Data.Edison.Seq.ListSeq as L
rconsUsingAppend :: Sequence s => a -> s a -> s a
rconsUsingAppend x s = append s (singleton x)
rconsUsingFoldr :: Sequence s => a -> s a -> s a
rconsUsingFoldr x s = foldr lcons (singleton x) s
appendUsingFoldr :: Sequence s => s a -> s a -> s a
appendUsingFoldr s t | null t = s
| otherwise = foldr lcons t s
rviewDefault :: (Fail.MonadFail m, Sequence s) => s a -> m (a, s a)
rviewDefault xs
| null xs = fail $ instanceName xs ++ ".rview: empty sequence"
| otherwise = return (rhead xs, rtail xs)
rtailUsingLview :: (Sequence s) => s a -> s a
rtailUsingLview xs =
case lview xs of
Nothing -> error $ instanceName xs ++ ".rtail: empty sequence"
Just (x, xs) -> rt x xs
where rt x xs =
case lview xs of
Nothing -> empty
Just (y, ys) -> lcons x (rt y ys)
rtailMUsingLview :: (Fail.MonadFail m, Sequence s) => s a -> m (s a)
rtailMUsingLview xs =
case lview xs of
Nothing -> fail $ instanceName xs ++ ".rtailM: empty sequence"
Just (x, xs) -> return (rt x xs)
where rt x xs =
case lview xs of
Nothing -> empty
Just (y, ys) -> lcons x (rt y ys)
concatUsingFoldr :: Sequence s => s (s a) -> s a
concatUsingFoldr = foldr append empty
reverseUsingReverseOnto :: Sequence s => s a -> s a
reverseUsingReverseOnto s = reverseOnto s empty
reverseUsingLists :: Sequence s => s a -> s a
reverseUsingLists = fromList . L.reverse . toList
reverseOntoUsingFoldl :: Sequence s => s a -> s a -> s a
reverseOntoUsingFoldl xs ys = foldl (flip lcons) ys xs
reverseOntoUsingReverse :: Sequence s => s a -> s a -> s a
reverseOntoUsingReverse = append . reverse
fromListUsingCons :: Sequence s => [a] -> s a
fromListUsingCons = L.foldr lcons empty
toListUsingFoldr :: Sequence s => s a -> [a]
toListUsingFoldr = foldr (:) []
mapUsingFoldr :: Sequence s => (a -> b) -> s a -> s b
mapUsingFoldr f = foldr (lcons . f) empty
concatMapUsingFoldr :: Sequence s => (a -> s b) -> s a -> s b
concatMapUsingFoldr f = foldr (append . f) empty
foldrUsingLists :: Sequence s => (a -> b -> b) -> b -> s a -> b
foldrUsingLists f e xs = L.foldr f e (toList xs)
foldr'UsingLists :: Sequence s => (a -> b -> b) -> b -> s a -> b
foldr'UsingLists f e xs = L.foldr' f e (toList xs)
foldlUsingLists :: Sequence s => (b -> a -> b) -> b -> s a -> b
foldlUsingLists f e xs = L.foldl f e (toList xs)
foldl'UsingLists :: Sequence s => (b -> a -> b) -> b -> s a -> b
foldl'UsingLists f e xs = L.foldl' f e (toList xs)
foldr1UsingLists :: Sequence s => (a -> a -> a) -> s a -> a
foldr1UsingLists f xs = L.foldr1 f (toList xs)
foldr1'UsingLists :: Sequence s => (a -> a -> a) -> s a -> a
foldr1'UsingLists f xs = L.foldr1' f (toList xs)
foldl1UsingLists :: Sequence s => (a -> a -> a) -> s a -> a
foldl1UsingLists f xs = L.foldl1 f (toList xs)
foldl1'UsingLists :: Sequence s => (a -> a -> a) -> s a -> a
foldl1'UsingLists f xs = L.foldl1' f (toList xs)
fold1UsingFold :: Sequence s => (a -> a -> a) -> s a -> a
fold1UsingFold f xs =
case lview xs of
Nothing -> error $ instanceName xs ++ ".fold1: empty sequence"
Just (x, xs) -> fold f x xs
fold1'UsingFold' :: Sequence s => (a -> a -> a) -> s a -> a
fold1'UsingFold' f xs =
case lview xs of
Nothing -> error $ instanceName xs ++ ".fold1': empty sequence"
Just (x, xs) -> fold' f x xs
foldr1UsingLview :: Sequence s => (a -> a -> a) -> s a -> a
foldr1UsingLview f xs =
case lview xs of
Nothing -> error $ instanceName xs ++ ".foldr1: empty sequence"
Just (x, xs) -> fr1 x xs
where fr1 x xs =
case lview xs of
Nothing -> x
Just (y,ys) -> f x (fr1 y ys)
foldr1'UsingLview :: Sequence s => (a -> a -> a) -> s a -> a
foldr1'UsingLview f xs =
case lview xs of
Nothing -> error $ instanceName xs ++ ".foldr1': empty sequence"
Just (x,xs) -> fr1 x xs
where fr1 x xs =
case lview xs of
Nothing -> x
Just (y,ys) -> f x $! (fr1 y ys)
foldl1UsingFoldl :: Sequence s => (a -> a -> a) -> s a -> a
foldl1UsingFoldl f xs =
case lview xs of
Nothing -> error $ instanceName xs ++ ".foldl1: empty sequence"
Just (x,xs) -> foldl f x xs
foldl1'UsingFoldl' :: Sequence s => (a -> a -> a) -> s a -> a
foldl1'UsingFoldl' f xs =
case lview xs of
Nothing -> error $ instanceName xs ++ ".foldl1': empty sequence"
Just (x,xs) -> foldl' f x xs
reducerUsingReduce1 :: Sequence s => (a -> a -> a) -> a -> s a -> a
reducerUsingReduce1 f e s
| null s = e
| otherwise = f (reduce1 f s) e
reducer'UsingReduce1' :: Sequence s => (a -> a -> a) -> a -> s a -> a
reducer'UsingReduce1' f e s
| null s = e
| otherwise = f (reduce1' f s) e
reducelUsingReduce1 :: Sequence s => (a -> a -> a) -> a -> s a -> a
reducelUsingReduce1 f e s
| null s = e
| otherwise = f e (reduce1 f s)
reducel'UsingReduce1' :: Sequence s => (a -> a -> a) -> a -> s a -> a
reducel'UsingReduce1' f e s
| null s = e
| otherwise = f e (reduce1' f s)
reduce1UsingLists :: Sequence s => (a -> a -> a) -> s a -> a
reduce1UsingLists f s = L.reduce1 f (toList s)
reduce1'UsingLists :: Sequence s => (a -> a -> a) -> s a -> a
reduce1'UsingLists f s = L.reduce1' f (toList s)
copyUsingLists :: Sequence s => Int -> a -> s a
copyUsingLists n x = fromList (L.copy n x)
inBoundsUsingDrop :: Sequence s => Int -> s a -> Bool
inBoundsUsingDrop i s =
i >= 0 && not (null (drop i s))
inBoundsUsingLookupM :: Sequence s => Int -> s a -> Bool
inBoundsUsingLookupM i s =
case lookupM i s of
Just _ -> True
Nothing -> False
inBoundsUsingSize :: Sequence s => Int -> s a -> Bool
inBoundsUsingSize i s = i >= 0 && i < size s
lookupUsingLookupM :: Sequence s => Int -> s a -> a
lookupUsingLookupM i s = runFail_ (lookupM i s)
lookupUsingDrop :: Sequence s => Int -> s a -> a
lookupUsingDrop i s
| i < 0 || null s' = error $ instanceName s ++ ".lookup: bad subscript"
| otherwise = lhead s'
where s' = drop i s
lookupWithDefaultUsingLookupM :: Sequence s => a -> Int -> s a -> a
lookupWithDefaultUsingLookupM d i s =
case lookupM i s of
Nothing -> d
Just x -> x
lookupWithDefaultUsingDrop :: Sequence s => a -> Int -> s a -> a
lookupWithDefaultUsingDrop d i s
| i < 0 || null s' = d
| otherwise = lhead s'
where s' = drop i s
lookupMUsingDrop :: (Fail.MonadFail m, Sequence s) => Int -> s a -> m a
lookupMUsingDrop i s
-- XXX better error message!
| i < 0 || null s' = fail $ instanceName s
++ ".lookupMUsingDrop: empty sequence"
| otherwise = return (lhead s')
where s' = drop i s
filterUsingLview :: Sequence s => (a -> Bool) -> s a -> s a
filterUsingLview p xs =
case lview xs of
Nothing -> empty
Just (x,xs) -> if p x then lcons x (filter p xs) else filter p xs
filterUsingLists :: Sequence s => (a -> Bool) -> s a -> s a
filterUsingLists p xs =
fromList (L.filter p (toList xs))
filterUsingFoldr :: Sequence s => (a -> Bool) -> s a -> s a
filterUsingFoldr p = foldr pcons empty
where pcons x xs = if p x then lcons x xs else xs
partitionUsingLists :: Sequence s => (a -> Bool) -> s a -> (s a, s a)
partitionUsingLists p xs =
let (ys,zs) = L.partition p (toList xs)
in (fromList ys, fromList zs)
partitionUsingFoldr :: Sequence s => (a -> Bool) -> s a -> (s a, s a)
partitionUsingFoldr p = foldr pcons (empty, empty)
where pcons x (xs, xs') = if p x then (lcons x xs, xs') else (xs, lcons x xs')
updateUsingAdjust :: Sequence s => Int -> a -> s a -> s a
updateUsingAdjust i y = adjust (const y) i
updateUsingSplitAt :: Sequence s => Int -> a -> s a -> s a
updateUsingSplitAt i x xs
| i < 0 = xs
| otherwise = let (ys,zs) = splitAt i xs
in if null zs then xs else append ys (lcons x (ltail zs))
adjustUsingLists :: Sequence s => (a -> a) -> Int -> s a -> s a
adjustUsingLists f i xs = fromList (L.adjust f i (toList xs))
adjustUsingSplitAt :: Sequence s => (a -> a) -> Int -> s a -> s a
adjustUsingSplitAt f i xs
| i < 0 = xs
| otherwise = let (ys,zs) = splitAt i xs
in case lview zs of
Nothing -> xs
Just (z,zs') -> append ys (lcons (f z) zs')
{-
insertAtUsingLists :: Sequence s => Int -> a -> s a -> s a
insertAtUsingLists i x xs =
fromList (L.insertAt i x (toList xs))
insertAtUsingSplitAt :: Sequence s => Int -> a -> s a -> s a
insertAtUsingSplitAt i x xs
| (xs_before, xs_after) <- splitAt i xs =
append xs_before (lcons x xs_after)
deleteAtUsingLists :: Sequence s => Int -> s a -> s a
deleteAtUsingLists i xs = fromList (L.deleteAt i (toList xs))
deleteAtUsingSplitAt :: Sequence s => Int -> s a -> s a
deleteAtUsingSplitAt i xs
| (xs_before, xs_after) <- splitAt i xs =
append xs_before (ltail xs_after)
-}
mapWithIndexUsingLists :: Sequence s => (Int -> a -> b) -> s a -> s b
mapWithIndexUsingLists f xs = fromList (L.mapWithIndex f (toList xs))
foldrWithIndexUsingLists ::
Sequence s => (Int -> a -> b -> b) -> b -> s a -> b
foldrWithIndexUsingLists f e xs = L.foldrWithIndex f e (toList xs)
foldrWithIndex'UsingLists ::
Sequence s => (Int -> a -> b -> b) -> b -> s a -> b
foldrWithIndex'UsingLists f e xs = L.foldrWithIndex' f e (toList xs)
foldlWithIndexUsingLists ::
Sequence s => (b -> Int -> a -> b) -> b -> s a -> b
foldlWithIndexUsingLists f e xs = L.foldlWithIndex f e (toList xs)
foldlWithIndex'UsingLists ::
Sequence s => (b -> Int -> a -> b) -> b -> s a -> b
foldlWithIndex'UsingLists f e xs = L.foldlWithIndex' f e (toList xs)
takeUsingLists :: Sequence s => Int -> s a -> s a
takeUsingLists i s = fromList (L.take i (toList s))
takeUsingLview :: Sequence s => Int -> s a -> s a
takeUsingLview i xs
| i <= 0 = empty
| otherwise = case lview xs of
Nothing -> empty
Just (x,xs') -> lcons x (take (i-1) xs')
dropUsingLists :: Sequence s => Int -> s a -> s a
dropUsingLists i s = fromList (L.drop i (toList s))
dropUsingLtail :: Sequence s => Int -> s a -> s a
dropUsingLtail i xs
| i <= 0 || null xs = xs
| otherwise = dropUsingLtail (i-1) (ltail xs)
splitAtDefault :: Sequence s => Int -> s a -> (s a, s a)
splitAtDefault i s = (take i s, drop i s)
splitAtUsingLview :: Sequence s => Int -> s a -> (s a, s a)
splitAtUsingLview i xs
| i <= 0 = (empty,xs)
| otherwise = case lview xs of
Nothing -> (empty,empty)
Just (x,xs') -> (lcons x ys,zs)
where (ys,zs) = splitAtUsingLview (i-1) xs'
subseqDefault :: Sequence s => Int -> Int -> s a -> s a
subseqDefault i len xs = take len (drop i xs)
takeWhileUsingLview :: Sequence s => (a -> Bool) -> s a -> s a
takeWhileUsingLview p xs =
case lview xs of
Just (x,xs') | p x -> lcons x (takeWhileUsingLview p xs')
_ -> empty
dropWhileUsingLview :: Sequence s => (a -> Bool) -> s a -> s a
dropWhileUsingLview p xs =
case lview xs of
Just (x,xs') | p x -> dropWhileUsingLview p xs'
_ -> xs
splitWhileUsingLview :: Sequence s => (a -> Bool) -> s a -> (s a, s a)
splitWhileUsingLview p xs =
case lview xs of
Just (x,xs') | p x -> let (front, back) = splitWhileUsingLview p xs'
in (lcons x front, back)
_ -> (empty, xs)
zipUsingLview :: Sequence s => s a -> s b -> s (a,b)
zipUsingLview xs ys =
case lview xs of
Nothing -> empty
Just (x,xs') ->
case lview ys of
Nothing -> empty
Just (y,ys') -> lcons (x,y) (zipUsingLview xs' ys')
zip3UsingLview :: Sequence s => s a -> s b -> s c -> s (a,b,c)
zip3UsingLview xs ys zs =
case lview xs of
Nothing -> empty
Just (x,xs') ->
case lview ys of
Nothing -> empty
Just (y,ys') ->
case lview zs of
Nothing -> empty
Just (z,zs') -> lcons (x,y,z) (zip3UsingLview xs' ys' zs')
zipWithUsingLview :: Sequence s => (a -> b -> c) -> s a -> s b -> s c
zipWithUsingLview f xs ys =
case lview xs of
Nothing -> empty
Just (x,xs') ->
case lview ys of
Nothing -> empty
Just (y,ys') -> lcons (f x y) (zipWithUsingLview f xs' ys')
zipWith3UsingLview ::
Sequence s => (a -> b -> c -> d) -> s a -> s b -> s c -> s d
zipWith3UsingLview f xs ys zs =
case lview xs of
Nothing -> empty
Just (x,xs') ->
case lview ys of
Nothing -> empty
Just (y,ys') ->
case lview zs of
Nothing -> empty
Just (z,zs') -> lcons (f x y z) (zipWith3UsingLview f xs' ys' zs')
zipUsingLists :: Sequence s => s a -> s b -> s (a,b)
zipUsingLists xs ys = fromList (L.zip (toList xs) (toList ys))
zip3UsingLists :: Sequence s => s a -> s b -> s c -> s (a,b,c)
zip3UsingLists xs ys zs =
fromList (L.zip3 (toList xs) (toList ys) (toList zs))
zipWithUsingLists :: Sequence s => (a -> b -> c) -> s a -> s b -> s c
zipWithUsingLists f xs ys =
fromList (L.zipWith f (toList xs) (toList ys))
zipWith3UsingLists ::
Sequence s => (a -> b -> c -> d) -> s a -> s b -> s c -> s d
zipWith3UsingLists f xs ys zs =
fromList (L.zipWith3 f (toList xs) (toList ys) (toList zs))
unzipUsingLists :: Sequence s => s (a,b) -> (s a, s b)
unzipUsingLists xys =
case L.unzip (toList xys) of
(xs, ys) -> (fromList xs, fromList ys)
unzipUsingFoldr :: Sequence s => s (a,b) -> (s a, s b)
unzipUsingFoldr = foldr pcons (empty,empty)
where pcons (x,y) (xs,ys) = (lcons x xs, lcons y ys)
unzip3UsingLists :: Sequence s => s (a,b,c) -> (s a, s b, s c)
unzip3UsingLists xyzs =
case L.unzip3 (toList xyzs) of
(xs, ys, zs) -> (fromList xs, fromList ys, fromList zs)
unzip3UsingFoldr :: Sequence s => s (a,b,c) -> (s a, s b, s c)
unzip3UsingFoldr = foldr tcons (empty,empty,empty)
where tcons (x,y,z) (xs,ys,zs) = (lcons x xs, lcons y ys, lcons z zs)
unzipWithUsingLists ::
Sequence s => (a -> b) -> (a -> c) -> s a -> (s b, s c)
unzipWithUsingLists f g xys =
case L.unzipWith f g (toList xys) of
(xs, ys) -> (fromList xs, fromList ys)
unzipWithUsingFoldr ::
Sequence s => (a -> b) -> (a -> c) -> s a -> (s b, s c)
unzipWithUsingFoldr f g = foldr pcons (empty,empty)
where pcons e (xs,ys) = (lcons (f e) xs, lcons (g e) ys)
unzipWith3UsingLists ::
Sequence s => (a -> b) -> (a -> c) -> (a -> d) -> s a -> (s b, s c, s d)
unzipWith3UsingLists f g h xyzs =
case L.unzipWith3 f g h (toList xyzs) of
(xs, ys, zs) -> (fromList xs, fromList ys, fromList zs)
unzipWith3UsingFoldr ::
Sequence s => (a -> b) -> (a -> c) -> (a -> d) -> s a -> (s b, s c, s d)
unzipWith3UsingFoldr f g h = foldr tcons (empty,empty,empty)
where tcons e (xs,ys,zs) = (lcons (f e) xs, lcons (g e) ys, lcons (h e) zs)
showsPrecUsingToList :: (Show a,Sequence s) => Int -> s a -> ShowS
showsPrecUsingToList i xs rest
| i == 0 = concat [ instanceName xs,".fromList "] ++ showsPrec 10 (toList xs) rest
| otherwise = concat ["(",instanceName xs,".fromList "] ++ showsPrec 10 (toList xs) (')':rest)
readsPrecUsingFromList :: (Read a,Sequence s) => Int -> ReadS (s a)
readsPrecUsingFromList _ xs =
let result = maybeParens p xs
p xs = tokenMatch ((instanceName x)++".fromList") xs
>>= readsPrec 10
>>= \(l,rest) -> return (fromList l,rest)
-- play games with the typechecker so we don't have to use
-- extensions for scoped type variables
~[(x,_)] = result
in result
defaultCompare :: (Ord a, Sequence s) => s a -> s a -> Ordering
defaultCompare a b =
case (lview a, lview b) of
(Nothing, Nothing) -> EQ
(Nothing, _ ) -> LT
(_ , Nothing) -> GT
(Just (x,xs), Just (y,ys)) ->
case compare x y of
EQ -> defaultCompare xs ys
c -> c
dropMatch :: (Eq a,MonadPlus m) => [a] -> [a] -> m [a]
dropMatch [] ys = return ys
dropMatch (x:xs) (y:ys)
| x == y = dropMatch xs ys
| otherwise = mzero
dropMatch _ _ = mzero
tokenMatch :: MonadPlus m => String -> String -> m String
tokenMatch token str = dropMatch token (munch str) >>= return . munch
where munch = dropWhile isSpace
readSParens :: ReadS a -> ReadS a
readSParens p xs = return xs
>>= tokenMatch "("
>>= p
>>= \(x,xs') -> return xs'
>>= tokenMatch ")"
>>= \rest -> return (x,rest)
maybeParens :: ReadS a -> ReadS a
maybeParens p xs = readSParens p xs `mplus` p xs
| null |
https://raw.githubusercontent.com/robdockins/edison/e9024cc5b9c4cf6b59d33baf7564e509366c79da/edison-core/src/Data/Edison/Seq/Defaults.hs
|
haskell
|
|
Module : Data.Edison.Seq.Defaults
Stability : internal (unstable)
This module provides default implementations of many of
the sequence operations. It is used to fill in implementations
and is not intended for end users.
XXX better error message!
insertAtUsingLists :: Sequence s => Int -> a -> s a -> s a
insertAtUsingLists i x xs =
fromList (L.insertAt i x (toList xs))
insertAtUsingSplitAt :: Sequence s => Int -> a -> s a -> s a
insertAtUsingSplitAt i x xs
| (xs_before, xs_after) <- splitAt i xs =
append xs_before (lcons x xs_after)
deleteAtUsingLists :: Sequence s => Int -> s a -> s a
deleteAtUsingLists i xs = fromList (L.deleteAt i (toList xs))
deleteAtUsingSplitAt :: Sequence s => Int -> s a -> s a
deleteAtUsingSplitAt i xs
| (xs_before, xs_after) <- splitAt i xs =
append xs_before (ltail xs_after)
play games with the typechecker so we don't have to use
extensions for scoped type variables
|
Copyright : Copyright ( c ) 1998 , 2008
License : MIT ; see COPYRIGHT file for terms and conditions
Maintainer : robdockins AT fastmail DOT fm
Portability : GHC , Hugs ( MPTC and FD )
module Data.Edison.Seq.Defaults where
import Prelude hiding (concat,reverse,map,concatMap,foldr,foldl,foldr1,foldl1,
filter,takeWhile,dropWhile,lookup,take,drop,splitAt,
zip,zip3,zipWith,zipWith3,unzip,unzip3,null)
import qualified Control.Monad.Fail as Fail
import Control.Monad
import Data.Char (isSpace)
import Data.Edison.Prelude ( runFail_ )
import Data.Edison.Seq
import qualified Data.Edison.Seq.ListSeq as L
rconsUsingAppend :: Sequence s => a -> s a -> s a
rconsUsingAppend x s = append s (singleton x)
rconsUsingFoldr :: Sequence s => a -> s a -> s a
rconsUsingFoldr x s = foldr lcons (singleton x) s
appendUsingFoldr :: Sequence s => s a -> s a -> s a
appendUsingFoldr s t | null t = s
| otherwise = foldr lcons t s
rviewDefault :: (Fail.MonadFail m, Sequence s) => s a -> m (a, s a)
rviewDefault xs
| null xs = fail $ instanceName xs ++ ".rview: empty sequence"
| otherwise = return (rhead xs, rtail xs)
rtailUsingLview :: (Sequence s) => s a -> s a
rtailUsingLview xs =
case lview xs of
Nothing -> error $ instanceName xs ++ ".rtail: empty sequence"
Just (x, xs) -> rt x xs
where rt x xs =
case lview xs of
Nothing -> empty
Just (y, ys) -> lcons x (rt y ys)
rtailMUsingLview :: (Fail.MonadFail m, Sequence s) => s a -> m (s a)
rtailMUsingLview xs =
case lview xs of
Nothing -> fail $ instanceName xs ++ ".rtailM: empty sequence"
Just (x, xs) -> return (rt x xs)
where rt x xs =
case lview xs of
Nothing -> empty
Just (y, ys) -> lcons x (rt y ys)
concatUsingFoldr :: Sequence s => s (s a) -> s a
concatUsingFoldr = foldr append empty
reverseUsingReverseOnto :: Sequence s => s a -> s a
reverseUsingReverseOnto s = reverseOnto s empty
reverseUsingLists :: Sequence s => s a -> s a
reverseUsingLists = fromList . L.reverse . toList
reverseOntoUsingFoldl :: Sequence s => s a -> s a -> s a
reverseOntoUsingFoldl xs ys = foldl (flip lcons) ys xs
reverseOntoUsingReverse :: Sequence s => s a -> s a -> s a
reverseOntoUsingReverse = append . reverse
fromListUsingCons :: Sequence s => [a] -> s a
fromListUsingCons = L.foldr lcons empty
toListUsingFoldr :: Sequence s => s a -> [a]
toListUsingFoldr = foldr (:) []
mapUsingFoldr :: Sequence s => (a -> b) -> s a -> s b
mapUsingFoldr f = foldr (lcons . f) empty
concatMapUsingFoldr :: Sequence s => (a -> s b) -> s a -> s b
concatMapUsingFoldr f = foldr (append . f) empty
foldrUsingLists :: Sequence s => (a -> b -> b) -> b -> s a -> b
foldrUsingLists f e xs = L.foldr f e (toList xs)
foldr'UsingLists :: Sequence s => (a -> b -> b) -> b -> s a -> b
foldr'UsingLists f e xs = L.foldr' f e (toList xs)
foldlUsingLists :: Sequence s => (b -> a -> b) -> b -> s a -> b
foldlUsingLists f e xs = L.foldl f e (toList xs)
foldl'UsingLists :: Sequence s => (b -> a -> b) -> b -> s a -> b
foldl'UsingLists f e xs = L.foldl' f e (toList xs)
foldr1UsingLists :: Sequence s => (a -> a -> a) -> s a -> a
foldr1UsingLists f xs = L.foldr1 f (toList xs)
foldr1'UsingLists :: Sequence s => (a -> a -> a) -> s a -> a
foldr1'UsingLists f xs = L.foldr1' f (toList xs)
foldl1UsingLists :: Sequence s => (a -> a -> a) -> s a -> a
foldl1UsingLists f xs = L.foldl1 f (toList xs)
foldl1'UsingLists :: Sequence s => (a -> a -> a) -> s a -> a
foldl1'UsingLists f xs = L.foldl1' f (toList xs)
fold1UsingFold :: Sequence s => (a -> a -> a) -> s a -> a
fold1UsingFold f xs =
case lview xs of
Nothing -> error $ instanceName xs ++ ".fold1: empty sequence"
Just (x, xs) -> fold f x xs
fold1'UsingFold' :: Sequence s => (a -> a -> a) -> s a -> a
fold1'UsingFold' f xs =
case lview xs of
Nothing -> error $ instanceName xs ++ ".fold1': empty sequence"
Just (x, xs) -> fold' f x xs
foldr1UsingLview :: Sequence s => (a -> a -> a) -> s a -> a
foldr1UsingLview f xs =
case lview xs of
Nothing -> error $ instanceName xs ++ ".foldr1: empty sequence"
Just (x, xs) -> fr1 x xs
where fr1 x xs =
case lview xs of
Nothing -> x
Just (y,ys) -> f x (fr1 y ys)
foldr1'UsingLview :: Sequence s => (a -> a -> a) -> s a -> a
foldr1'UsingLview f xs =
case lview xs of
Nothing -> error $ instanceName xs ++ ".foldr1': empty sequence"
Just (x,xs) -> fr1 x xs
where fr1 x xs =
case lview xs of
Nothing -> x
Just (y,ys) -> f x $! (fr1 y ys)
foldl1UsingFoldl :: Sequence s => (a -> a -> a) -> s a -> a
foldl1UsingFoldl f xs =
case lview xs of
Nothing -> error $ instanceName xs ++ ".foldl1: empty sequence"
Just (x,xs) -> foldl f x xs
foldl1'UsingFoldl' :: Sequence s => (a -> a -> a) -> s a -> a
foldl1'UsingFoldl' f xs =
case lview xs of
Nothing -> error $ instanceName xs ++ ".foldl1': empty sequence"
Just (x,xs) -> foldl' f x xs
reducerUsingReduce1 :: Sequence s => (a -> a -> a) -> a -> s a -> a
reducerUsingReduce1 f e s
| null s = e
| otherwise = f (reduce1 f s) e
reducer'UsingReduce1' :: Sequence s => (a -> a -> a) -> a -> s a -> a
reducer'UsingReduce1' f e s
| null s = e
| otherwise = f (reduce1' f s) e
reducelUsingReduce1 :: Sequence s => (a -> a -> a) -> a -> s a -> a
reducelUsingReduce1 f e s
| null s = e
| otherwise = f e (reduce1 f s)
reducel'UsingReduce1' :: Sequence s => (a -> a -> a) -> a -> s a -> a
reducel'UsingReduce1' f e s
| null s = e
| otherwise = f e (reduce1' f s)
reduce1UsingLists :: Sequence s => (a -> a -> a) -> s a -> a
reduce1UsingLists f s = L.reduce1 f (toList s)
reduce1'UsingLists :: Sequence s => (a -> a -> a) -> s a -> a
reduce1'UsingLists f s = L.reduce1' f (toList s)
copyUsingLists :: Sequence s => Int -> a -> s a
copyUsingLists n x = fromList (L.copy n x)
inBoundsUsingDrop :: Sequence s => Int -> s a -> Bool
inBoundsUsingDrop i s =
i >= 0 && not (null (drop i s))
inBoundsUsingLookupM :: Sequence s => Int -> s a -> Bool
inBoundsUsingLookupM i s =
case lookupM i s of
Just _ -> True
Nothing -> False
inBoundsUsingSize :: Sequence s => Int -> s a -> Bool
inBoundsUsingSize i s = i >= 0 && i < size s
lookupUsingLookupM :: Sequence s => Int -> s a -> a
lookupUsingLookupM i s = runFail_ (lookupM i s)
lookupUsingDrop :: Sequence s => Int -> s a -> a
lookupUsingDrop i s
| i < 0 || null s' = error $ instanceName s ++ ".lookup: bad subscript"
| otherwise = lhead s'
where s' = drop i s
lookupWithDefaultUsingLookupM :: Sequence s => a -> Int -> s a -> a
lookupWithDefaultUsingLookupM d i s =
case lookupM i s of
Nothing -> d
Just x -> x
lookupWithDefaultUsingDrop :: Sequence s => a -> Int -> s a -> a
lookupWithDefaultUsingDrop d i s
| i < 0 || null s' = d
| otherwise = lhead s'
where s' = drop i s
lookupMUsingDrop :: (Fail.MonadFail m, Sequence s) => Int -> s a -> m a
lookupMUsingDrop i s
| i < 0 || null s' = fail $ instanceName s
++ ".lookupMUsingDrop: empty sequence"
| otherwise = return (lhead s')
where s' = drop i s
filterUsingLview :: Sequence s => (a -> Bool) -> s a -> s a
filterUsingLview p xs =
case lview xs of
Nothing -> empty
Just (x,xs) -> if p x then lcons x (filter p xs) else filter p xs
filterUsingLists :: Sequence s => (a -> Bool) -> s a -> s a
filterUsingLists p xs =
fromList (L.filter p (toList xs))
filterUsingFoldr :: Sequence s => (a -> Bool) -> s a -> s a
filterUsingFoldr p = foldr pcons empty
where pcons x xs = if p x then lcons x xs else xs
partitionUsingLists :: Sequence s => (a -> Bool) -> s a -> (s a, s a)
partitionUsingLists p xs =
let (ys,zs) = L.partition p (toList xs)
in (fromList ys, fromList zs)
partitionUsingFoldr :: Sequence s => (a -> Bool) -> s a -> (s a, s a)
partitionUsingFoldr p = foldr pcons (empty, empty)
where pcons x (xs, xs') = if p x then (lcons x xs, xs') else (xs, lcons x xs')
updateUsingAdjust :: Sequence s => Int -> a -> s a -> s a
updateUsingAdjust i y = adjust (const y) i
updateUsingSplitAt :: Sequence s => Int -> a -> s a -> s a
updateUsingSplitAt i x xs
| i < 0 = xs
| otherwise = let (ys,zs) = splitAt i xs
in if null zs then xs else append ys (lcons x (ltail zs))
adjustUsingLists :: Sequence s => (a -> a) -> Int -> s a -> s a
adjustUsingLists f i xs = fromList (L.adjust f i (toList xs))
adjustUsingSplitAt :: Sequence s => (a -> a) -> Int -> s a -> s a
adjustUsingSplitAt f i xs
| i < 0 = xs
| otherwise = let (ys,zs) = splitAt i xs
in case lview zs of
Nothing -> xs
Just (z,zs') -> append ys (lcons (f z) zs')
mapWithIndexUsingLists :: Sequence s => (Int -> a -> b) -> s a -> s b
mapWithIndexUsingLists f xs = fromList (L.mapWithIndex f (toList xs))
foldrWithIndexUsingLists ::
Sequence s => (Int -> a -> b -> b) -> b -> s a -> b
foldrWithIndexUsingLists f e xs = L.foldrWithIndex f e (toList xs)
foldrWithIndex'UsingLists ::
Sequence s => (Int -> a -> b -> b) -> b -> s a -> b
foldrWithIndex'UsingLists f e xs = L.foldrWithIndex' f e (toList xs)
foldlWithIndexUsingLists ::
Sequence s => (b -> Int -> a -> b) -> b -> s a -> b
foldlWithIndexUsingLists f e xs = L.foldlWithIndex f e (toList xs)
foldlWithIndex'UsingLists ::
Sequence s => (b -> Int -> a -> b) -> b -> s a -> b
foldlWithIndex'UsingLists f e xs = L.foldlWithIndex' f e (toList xs)
takeUsingLists :: Sequence s => Int -> s a -> s a
takeUsingLists i s = fromList (L.take i (toList s))
takeUsingLview :: Sequence s => Int -> s a -> s a
takeUsingLview i xs
| i <= 0 = empty
| otherwise = case lview xs of
Nothing -> empty
Just (x,xs') -> lcons x (take (i-1) xs')
dropUsingLists :: Sequence s => Int -> s a -> s a
dropUsingLists i s = fromList (L.drop i (toList s))
dropUsingLtail :: Sequence s => Int -> s a -> s a
dropUsingLtail i xs
| i <= 0 || null xs = xs
| otherwise = dropUsingLtail (i-1) (ltail xs)
splitAtDefault :: Sequence s => Int -> s a -> (s a, s a)
splitAtDefault i s = (take i s, drop i s)
splitAtUsingLview :: Sequence s => Int -> s a -> (s a, s a)
splitAtUsingLview i xs
| i <= 0 = (empty,xs)
| otherwise = case lview xs of
Nothing -> (empty,empty)
Just (x,xs') -> (lcons x ys,zs)
where (ys,zs) = splitAtUsingLview (i-1) xs'
subseqDefault :: Sequence s => Int -> Int -> s a -> s a
subseqDefault i len xs = take len (drop i xs)
takeWhileUsingLview :: Sequence s => (a -> Bool) -> s a -> s a
takeWhileUsingLview p xs =
case lview xs of
Just (x,xs') | p x -> lcons x (takeWhileUsingLview p xs')
_ -> empty
dropWhileUsingLview :: Sequence s => (a -> Bool) -> s a -> s a
dropWhileUsingLview p xs =
case lview xs of
Just (x,xs') | p x -> dropWhileUsingLview p xs'
_ -> xs
splitWhileUsingLview :: Sequence s => (a -> Bool) -> s a -> (s a, s a)
splitWhileUsingLview p xs =
case lview xs of
Just (x,xs') | p x -> let (front, back) = splitWhileUsingLview p xs'
in (lcons x front, back)
_ -> (empty, xs)
zipUsingLview :: Sequence s => s a -> s b -> s (a,b)
zipUsingLview xs ys =
case lview xs of
Nothing -> empty
Just (x,xs') ->
case lview ys of
Nothing -> empty
Just (y,ys') -> lcons (x,y) (zipUsingLview xs' ys')
zip3UsingLview :: Sequence s => s a -> s b -> s c -> s (a,b,c)
zip3UsingLview xs ys zs =
case lview xs of
Nothing -> empty
Just (x,xs') ->
case lview ys of
Nothing -> empty
Just (y,ys') ->
case lview zs of
Nothing -> empty
Just (z,zs') -> lcons (x,y,z) (zip3UsingLview xs' ys' zs')
zipWithUsingLview :: Sequence s => (a -> b -> c) -> s a -> s b -> s c
zipWithUsingLview f xs ys =
case lview xs of
Nothing -> empty
Just (x,xs') ->
case lview ys of
Nothing -> empty
Just (y,ys') -> lcons (f x y) (zipWithUsingLview f xs' ys')
zipWith3UsingLview ::
Sequence s => (a -> b -> c -> d) -> s a -> s b -> s c -> s d
zipWith3UsingLview f xs ys zs =
case lview xs of
Nothing -> empty
Just (x,xs') ->
case lview ys of
Nothing -> empty
Just (y,ys') ->
case lview zs of
Nothing -> empty
Just (z,zs') -> lcons (f x y z) (zipWith3UsingLview f xs' ys' zs')
zipUsingLists :: Sequence s => s a -> s b -> s (a,b)
zipUsingLists xs ys = fromList (L.zip (toList xs) (toList ys))
zip3UsingLists :: Sequence s => s a -> s b -> s c -> s (a,b,c)
zip3UsingLists xs ys zs =
fromList (L.zip3 (toList xs) (toList ys) (toList zs))
zipWithUsingLists :: Sequence s => (a -> b -> c) -> s a -> s b -> s c
zipWithUsingLists f xs ys =
fromList (L.zipWith f (toList xs) (toList ys))
zipWith3UsingLists ::
Sequence s => (a -> b -> c -> d) -> s a -> s b -> s c -> s d
zipWith3UsingLists f xs ys zs =
fromList (L.zipWith3 f (toList xs) (toList ys) (toList zs))
unzipUsingLists :: Sequence s => s (a,b) -> (s a, s b)
unzipUsingLists xys =
case L.unzip (toList xys) of
(xs, ys) -> (fromList xs, fromList ys)
unzipUsingFoldr :: Sequence s => s (a,b) -> (s a, s b)
unzipUsingFoldr = foldr pcons (empty,empty)
where pcons (x,y) (xs,ys) = (lcons x xs, lcons y ys)
unzip3UsingLists :: Sequence s => s (a,b,c) -> (s a, s b, s c)
unzip3UsingLists xyzs =
case L.unzip3 (toList xyzs) of
(xs, ys, zs) -> (fromList xs, fromList ys, fromList zs)
unzip3UsingFoldr :: Sequence s => s (a,b,c) -> (s a, s b, s c)
unzip3UsingFoldr = foldr tcons (empty,empty,empty)
where tcons (x,y,z) (xs,ys,zs) = (lcons x xs, lcons y ys, lcons z zs)
unzipWithUsingLists ::
Sequence s => (a -> b) -> (a -> c) -> s a -> (s b, s c)
unzipWithUsingLists f g xys =
case L.unzipWith f g (toList xys) of
(xs, ys) -> (fromList xs, fromList ys)
unzipWithUsingFoldr ::
Sequence s => (a -> b) -> (a -> c) -> s a -> (s b, s c)
unzipWithUsingFoldr f g = foldr pcons (empty,empty)
where pcons e (xs,ys) = (lcons (f e) xs, lcons (g e) ys)
unzipWith3UsingLists ::
Sequence s => (a -> b) -> (a -> c) -> (a -> d) -> s a -> (s b, s c, s d)
unzipWith3UsingLists f g h xyzs =
case L.unzipWith3 f g h (toList xyzs) of
(xs, ys, zs) -> (fromList xs, fromList ys, fromList zs)
unzipWith3UsingFoldr ::
Sequence s => (a -> b) -> (a -> c) -> (a -> d) -> s a -> (s b, s c, s d)
unzipWith3UsingFoldr f g h = foldr tcons (empty,empty,empty)
where tcons e (xs,ys,zs) = (lcons (f e) xs, lcons (g e) ys, lcons (h e) zs)
showsPrecUsingToList :: (Show a,Sequence s) => Int -> s a -> ShowS
showsPrecUsingToList i xs rest
| i == 0 = concat [ instanceName xs,".fromList "] ++ showsPrec 10 (toList xs) rest
| otherwise = concat ["(",instanceName xs,".fromList "] ++ showsPrec 10 (toList xs) (')':rest)
readsPrecUsingFromList :: (Read a,Sequence s) => Int -> ReadS (s a)
readsPrecUsingFromList _ xs =
let result = maybeParens p xs
p xs = tokenMatch ((instanceName x)++".fromList") xs
>>= readsPrec 10
>>= \(l,rest) -> return (fromList l,rest)
~[(x,_)] = result
in result
defaultCompare :: (Ord a, Sequence s) => s a -> s a -> Ordering
defaultCompare a b =
case (lview a, lview b) of
(Nothing, Nothing) -> EQ
(Nothing, _ ) -> LT
(_ , Nothing) -> GT
(Just (x,xs), Just (y,ys)) ->
case compare x y of
EQ -> defaultCompare xs ys
c -> c
dropMatch :: (Eq a,MonadPlus m) => [a] -> [a] -> m [a]
dropMatch [] ys = return ys
dropMatch (x:xs) (y:ys)
| x == y = dropMatch xs ys
| otherwise = mzero
dropMatch _ _ = mzero
tokenMatch :: MonadPlus m => String -> String -> m String
tokenMatch token str = dropMatch token (munch str) >>= return . munch
where munch = dropWhile isSpace
readSParens :: ReadS a -> ReadS a
readSParens p xs = return xs
>>= tokenMatch "("
>>= p
>>= \(x,xs') -> return xs'
>>= tokenMatch ")"
>>= \rest -> return (x,rest)
maybeParens :: ReadS a -> ReadS a
maybeParens p xs = readSParens p xs `mplus` p xs
|
4c2898c5b7766ccbc8b309743c1f6917757695773188ff372f67bd9873e088ce
|
jrm-code-project/LISP-Machine
|
dvi-macros.lisp
|
-*- Mode : LISP ; Syntax : ; Package : DVI ; Base : 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Buffer I/O routines
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(eval-when (eval compile load)
(defmacro bpeek-byte (buff)
`(aref ,buff (fill-pointer ,buff)))
return the next 8 bits from the input
;; stream
`(progn (incf (fill-pointer ,buff))
(aref ,buff (1- (fill-pointer ,buff)))))
(defmacro bget-signed-byte (buff)
`(let ((b (bget-byte ,buff)))
(if (< b 128) b (- b 256))))
(defmacro bget-2-bytes (buff)
`(let* ((a (aref ,buff (fill-pointer ,buff)))
(b (aref ,buff (1+ (fill-pointer ,buff)))))
(incf (fill-pointer ,buff) 2)
a * 256 + b
(defmacro bsigned-pair (buff)
`(let* ((a (aref ,buff (fill-pointer ,buff)))
(b (aref ,buff (1+ (fill-pointer ,buff)))))
(incf (fill-pointer ,buff) 2)
(if (< a 128)
(logior (lsh a 8) b)
(logior (lsh (- a 256) 8) b))))
(defmacro bget-3-bytes (buff)
`(let* ((a (aref ,buff (fill-pointer ,buff)))
(b (aref ,buff (1+ (fill-pointer ,buff))))
(c (aref ,buff (+ 2 (fill-pointer ,buff)))))
(incf (fill-pointer ,buff) 3)
(logior (lsh a 16) (lsh b 8) c)))
(defmacro bsigned-trio (buff)
`(let* ((a (aref ,buff (fill-pointer ,buff)))
(b (aref ,buff (1+ (fill-pointer ,buff))))
(c (aref ,buff (+ 2 (fill-pointer ,buff)))))
(incf (fill-pointer ,buff) 3)
(if (< a 128)
(logior (lsh a 16) (lsh b 8) c)
(logior (lsh (- a 256) 16)(lsh b 8) c))))
(defmacro bsigned-quad (buff)
`(let* ((a (aref ,buff (fill-pointer ,buff)))
(b (aref ,buff (1+ (fill-pointer ,buff))))
(c (aref ,buff (+ 2 (fill-pointer ,buff))))
(d (aref ,buff (+ 3 (fill-pointer ,buff)))))
(incf (fill-pointer ,buff) 4)
(if (< a 128)
(logior (ash a 24)(lsh b 16)(lsh c 8) d)
(logior (ash (- a 256) 24)(lsh b 16)(lsh c 8) d))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Binary file I/O routines
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmacro peek-byte (istr)
`(send ,istr :tyipeek))
return the next 8 bits from the input
;; stream
`(send ,istr :tyi)) ;; handler for eof?
(defmacro get-signed-byte (istr)
`(let ((b (send ,istr :tyi)))
(if (< b 128) b (- b 256))))
(defmacro get-2-bytes (istr)
`(let* ((a (send ,istr :tyi))
(b (send ,istr :tyi)))
a * 256 + b
(defmacro signed-pair (istr)
`(let* ((a (send ,istr :tyi))
(b (send ,istr :tyi)))
(if (< a 128)
(logior (lsh a 8) b)
(logior (lsh (- a 256) 8) b))))
(defmacro get-3-bytes (istr)
`(let* ((a (send ,istr :tyi))
(b (send ,istr :tyi))
(c (send ,istr :tyi)))
(logior (lsh a 16) (lsh b 8) c)))
(defmacro signed-trio (istr)
`(let* ((a (send ,istr :tyi))
(b (send ,istr :tyi))
(c (send ,istr :tyi)))
(if (< a 128)
(logior (lsh a 16) (lsh b 8) c)
(logior (lsh (- a 256) 16)(lsh b 8) c))))
i.e.((a-256 ) * 256 + b ) * 256 + c
(defmacro signed-quad (istr)
`(let* ((a (send ,istr :tyi))
(b (send ,istr :tyi))
(c (send ,istr :tyi))
(d (send ,istr :tyi)))
(if (< a 128)
(logior (ash a 24)(lsh b 16)(lsh c 8) d)
(logior (ash (- a 256) 24)(lsh b 16)(lsh c 8) d))))
)
(defmacro write-byte (ostr byte)
`(send ,ostr :tyo ,byte))
(defmacro write-2-bytes (ostr bytes)
`(progn
(send ,ostr :tyo (ldb (byte 8 8) ,bytes))
(send ,ostr :tyo (ldb (byte 8 0) ,bytes))))
(defmacro write-buffer (buff byte)
`(array-push-extend ,buff ,byte))
(defmacro write2-buffer (buff bytes)
`(progn
(array-push-extend ,buff (ldb (byte 8 8) ,bytes))
(array-push-extend ,buff (ldb (byte 8 0) ,bytes))))
;; go to the end of the file.
(defmacro go-eof (istr)
`(send ,istr :set-pointer (1- (file-stream-length ,istr))))
(defmacro skip-bytes (istr n)
;;go forward n bytes, n can be negative
`(send ,istr :set-pointer (+ (send ,istr :read-pointer) ,n)))
(defsubst move-back (file-buffer n)
;;move back the dvi file by n pages
(let (prev-page-ptr)
(dotimes (i n)
(if ( (bget-byte file-buffer) bop)(bad-dvi "Missing bop"))
(incf (fill-pointer file-buffer) 40) ;get rid of c0 to c9 params
(setq prev-page-ptr (bsigned-quad file-buffer))
(if (> prev-page-ptr 0)
(setf (fill-pointer file-buffer) prev-page-ptr)
(decf (fill-pointer file-buffer) 44)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; subroutines for unit conversions.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defvar conv)
(defvar dvis-per-fix)
(defvar dvi2mica)
;;
;; compute the number of pixels in the height or width of a rule.
;;
(defsubst rule-pixels (x)
(ceiling (* conv x)))
;;convert from dvi units to pixels
(defsubst pixel-round (x)
(round (* conv x)))
(defsubst dvi-round (x)
(// x (float conv)))
;;
(defsubst fix2dvi (x)
(* dvis-per-fix x))
;;
(defsignal dvi-error error ())
(defun bad-dvi (reason &rest args)
(if args
(lexpr-funcall 'ferror 'dvi-error reason args)
(ferror 'dvi-error "Bad dvi: ~S" reason)))
(deff bad-pxl 'bad-dvi)
(defmacro get-fntnum (texfntnum array)
`(loop for i from 0 below (fill-pointer ,array)
do
(if (= (aref ,array i) ,texfntnum)
(return i))))
(defmacro file-length (fbuffer)
`(array-leader ,fbuffer 1))
(defmacro store-file-length (fbuffer length)
`(store-array-leader ,length ,fbuffer 1))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;The following macros are for handling PRESS files
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Puts out command to show characters on the DL.
;;; Uses Show-characters-short if possible.
(defmacro put-pending-characters ()
`(when (plusp pending-characters)
(loop until (< pending-characters 256.) do
(el-byte <Show-Characters>)
(el-byte 255.)
(decf pending-characters 255.)
finally (cond ((> pending-characters 32.)
(el-byte <Show-Characters>)
(el-byte pending-characters))
((plusp pending-characters)
(el-byte (1- (+ <Show-Characters-Short>
pending-characters))))))
(setq pending-characters 0)))
Insert a byte into the EL .
(defmacro el-byte (byte)
`(progn (array-push-extend page-entity-buffer ,byte entity-buffer-extension-size)
(incf entity-list-length)))
Insert a word into the EL .
(defmacro el-word (word)
(once-only (word)
`(progn (el-byte (ldb #o1010 ,word))
(el-byte (ldb #o0010 ,word)))))
Insert a 32 - bit word into the EL .
(defmacro el-32word (word)
(once-only (word)
`(progn (el-byte (ldb #o3010 ,word))
(el-byte (ldb #o2010 ,word))
(el-byte (ldb #o1010 ,word))
(el-byte (ldb #o0010 ,word)))))
;;; Insert a byte into the DL.
(defmacro dl-byte (byte)
`(progn (send output-stream :tyo ,byte)
(incf data-list-length)))
;;; Insert a word into the DL.
(defmacro dl-word (word)
(once-only (word)
`(progn (dl-byte (ldb #o1010 ,word))
(dl-byte (ldb #o0010 ,word)))))
Insert a 32 - bit word into the DL .
(defmacro dl-32word (word)
(once-only (word)
`(progn (dl-byte (ldb #o3010 ,word))
(dl-byte (ldb #o2010 ,word))
(dl-byte (ldb #o1010 ,word))
(dl-byte (ldb #o0010 ,word)))))
;;; File I/O.
(defmacro byte-out (byte)
`(send output-stream :tyo ,byte))
(defmacro word-out (word)
(once-only (word)
`(progn (byte-out (ldb #o1010 ,word))
(byte-out (ldb #o0010 ,word)))))
;;; Output a BCPL string.
(defmacro bcpl-out (string max-length)
`(let ((string-end (min (1+ (string-length ,string)) ,max-length)))
(byte-out (1- string-end))
(send output-stream :string-out ,string 0 (1- string-end))
(pad-bytes-out (- ,max-length string-end))))
(defmacro pad-bytes-out (number)
`(loop repeat ,number do (byte-out 0)))
(defun open-8b-input (filename)
using : characters NIL can confuse some servers into 16 bit mode .
;; (open filename :direction :input :characters nil :byte-size 8)
;; :raw T is quaint but works.
(let ((pathname (send (fs:parse-pathname filename) :translated-pathname)))
(cond ((eq :lispm (send pathname :system-type))
(open filename :direction :input))
('else
(open filename :direction :input :raw t)))))
(defun open-8b-output (filename)
(let ((pathname (send (fs:parse-pathname filename) :translated-pathname)))
(cond ((eq :lispm (send pathname :system-type))
(open filename :direction :output))
('else
(open filename :direction :output :raw t)))))
(defun file-stream-length (file-stream)
if we used : characters NIL and : byte - size 8
;; then some unix servers were give the wrong length.
;; but since we dont, we win.
(send file-stream :length))
(defvar *pxl-filename-prepend* "tex: TeXfonts;")
(defvar *tfm-filename-prepend* "tex: TeXfonts;")
| null |
https://raw.githubusercontent.com/jrm-code-project/LISP-Machine/0a448d27f40761fafabe5775ffc550637be537b2/lambda/gjc/dvi/dvi-macros.lisp
|
lisp
|
Syntax : ; Package : DVI ; Base : 10 -*-
Buffer I/O routines
stream
Binary file I/O routines
stream
handler for eof?
go to the end of the file.
go forward n bytes, n can be negative
move back the dvi file by n pages
get rid of c0 to c9 params
subroutines for unit conversions.
compute the number of pixels in the height or width of a rule.
convert from dvi units to pixels
The following macros are for handling PRESS files
Puts out command to show characters on the DL.
Uses Show-characters-short if possible.
Insert a byte into the DL.
Insert a word into the DL.
File I/O.
Output a BCPL string.
(open filename :direction :input :characters nil :byte-size 8)
:raw T is quaint but works.
then some unix servers were give the wrong length.
but since we dont, we win.
|
(eval-when (eval compile load)
(defmacro bpeek-byte (buff)
`(aref ,buff (fill-pointer ,buff)))
return the next 8 bits from the input
`(progn (incf (fill-pointer ,buff))
(aref ,buff (1- (fill-pointer ,buff)))))
(defmacro bget-signed-byte (buff)
`(let ((b (bget-byte ,buff)))
(if (< b 128) b (- b 256))))
(defmacro bget-2-bytes (buff)
`(let* ((a (aref ,buff (fill-pointer ,buff)))
(b (aref ,buff (1+ (fill-pointer ,buff)))))
(incf (fill-pointer ,buff) 2)
a * 256 + b
(defmacro bsigned-pair (buff)
`(let* ((a (aref ,buff (fill-pointer ,buff)))
(b (aref ,buff (1+ (fill-pointer ,buff)))))
(incf (fill-pointer ,buff) 2)
(if (< a 128)
(logior (lsh a 8) b)
(logior (lsh (- a 256) 8) b))))
(defmacro bget-3-bytes (buff)
`(let* ((a (aref ,buff (fill-pointer ,buff)))
(b (aref ,buff (1+ (fill-pointer ,buff))))
(c (aref ,buff (+ 2 (fill-pointer ,buff)))))
(incf (fill-pointer ,buff) 3)
(logior (lsh a 16) (lsh b 8) c)))
(defmacro bsigned-trio (buff)
`(let* ((a (aref ,buff (fill-pointer ,buff)))
(b (aref ,buff (1+ (fill-pointer ,buff))))
(c (aref ,buff (+ 2 (fill-pointer ,buff)))))
(incf (fill-pointer ,buff) 3)
(if (< a 128)
(logior (lsh a 16) (lsh b 8) c)
(logior (lsh (- a 256) 16)(lsh b 8) c))))
(defmacro bsigned-quad (buff)
`(let* ((a (aref ,buff (fill-pointer ,buff)))
(b (aref ,buff (1+ (fill-pointer ,buff))))
(c (aref ,buff (+ 2 (fill-pointer ,buff))))
(d (aref ,buff (+ 3 (fill-pointer ,buff)))))
(incf (fill-pointer ,buff) 4)
(if (< a 128)
(logior (ash a 24)(lsh b 16)(lsh c 8) d)
(logior (ash (- a 256) 24)(lsh b 16)(lsh c 8) d))))
(defmacro peek-byte (istr)
`(send ,istr :tyipeek))
return the next 8 bits from the input
(defmacro get-signed-byte (istr)
`(let ((b (send ,istr :tyi)))
(if (< b 128) b (- b 256))))
(defmacro get-2-bytes (istr)
`(let* ((a (send ,istr :tyi))
(b (send ,istr :tyi)))
a * 256 + b
(defmacro signed-pair (istr)
`(let* ((a (send ,istr :tyi))
(b (send ,istr :tyi)))
(if (< a 128)
(logior (lsh a 8) b)
(logior (lsh (- a 256) 8) b))))
(defmacro get-3-bytes (istr)
`(let* ((a (send ,istr :tyi))
(b (send ,istr :tyi))
(c (send ,istr :tyi)))
(logior (lsh a 16) (lsh b 8) c)))
(defmacro signed-trio (istr)
`(let* ((a (send ,istr :tyi))
(b (send ,istr :tyi))
(c (send ,istr :tyi)))
(if (< a 128)
(logior (lsh a 16) (lsh b 8) c)
(logior (lsh (- a 256) 16)(lsh b 8) c))))
i.e.((a-256 ) * 256 + b ) * 256 + c
(defmacro signed-quad (istr)
`(let* ((a (send ,istr :tyi))
(b (send ,istr :tyi))
(c (send ,istr :tyi))
(d (send ,istr :tyi)))
(if (< a 128)
(logior (ash a 24)(lsh b 16)(lsh c 8) d)
(logior (ash (- a 256) 24)(lsh b 16)(lsh c 8) d))))
)
(defmacro write-byte (ostr byte)
`(send ,ostr :tyo ,byte))
(defmacro write-2-bytes (ostr bytes)
`(progn
(send ,ostr :tyo (ldb (byte 8 8) ,bytes))
(send ,ostr :tyo (ldb (byte 8 0) ,bytes))))
(defmacro write-buffer (buff byte)
`(array-push-extend ,buff ,byte))
(defmacro write2-buffer (buff bytes)
`(progn
(array-push-extend ,buff (ldb (byte 8 8) ,bytes))
(array-push-extend ,buff (ldb (byte 8 0) ,bytes))))
(defmacro go-eof (istr)
`(send ,istr :set-pointer (1- (file-stream-length ,istr))))
(defmacro skip-bytes (istr n)
`(send ,istr :set-pointer (+ (send ,istr :read-pointer) ,n)))
(defsubst move-back (file-buffer n)
(let (prev-page-ptr)
(dotimes (i n)
(if ( (bget-byte file-buffer) bop)(bad-dvi "Missing bop"))
(setq prev-page-ptr (bsigned-quad file-buffer))
(if (> prev-page-ptr 0)
(setf (fill-pointer file-buffer) prev-page-ptr)
(decf (fill-pointer file-buffer) 44)))))
(defvar conv)
(defvar dvis-per-fix)
(defvar dvi2mica)
(defsubst rule-pixels (x)
(ceiling (* conv x)))
(defsubst pixel-round (x)
(round (* conv x)))
(defsubst dvi-round (x)
(// x (float conv)))
(defsubst fix2dvi (x)
(* dvis-per-fix x))
(defsignal dvi-error error ())
(defun bad-dvi (reason &rest args)
(if args
(lexpr-funcall 'ferror 'dvi-error reason args)
(ferror 'dvi-error "Bad dvi: ~S" reason)))
(deff bad-pxl 'bad-dvi)
(defmacro get-fntnum (texfntnum array)
`(loop for i from 0 below (fill-pointer ,array)
do
(if (= (aref ,array i) ,texfntnum)
(return i))))
(defmacro file-length (fbuffer)
`(array-leader ,fbuffer 1))
(defmacro store-file-length (fbuffer length)
`(store-array-leader ,length ,fbuffer 1))
(defmacro put-pending-characters ()
`(when (plusp pending-characters)
(loop until (< pending-characters 256.) do
(el-byte <Show-Characters>)
(el-byte 255.)
(decf pending-characters 255.)
finally (cond ((> pending-characters 32.)
(el-byte <Show-Characters>)
(el-byte pending-characters))
((plusp pending-characters)
(el-byte (1- (+ <Show-Characters-Short>
pending-characters))))))
(setq pending-characters 0)))
Insert a byte into the EL .
(defmacro el-byte (byte)
`(progn (array-push-extend page-entity-buffer ,byte entity-buffer-extension-size)
(incf entity-list-length)))
Insert a word into the EL .
(defmacro el-word (word)
(once-only (word)
`(progn (el-byte (ldb #o1010 ,word))
(el-byte (ldb #o0010 ,word)))))
Insert a 32 - bit word into the EL .
(defmacro el-32word (word)
(once-only (word)
`(progn (el-byte (ldb #o3010 ,word))
(el-byte (ldb #o2010 ,word))
(el-byte (ldb #o1010 ,word))
(el-byte (ldb #o0010 ,word)))))
(defmacro dl-byte (byte)
`(progn (send output-stream :tyo ,byte)
(incf data-list-length)))
(defmacro dl-word (word)
(once-only (word)
`(progn (dl-byte (ldb #o1010 ,word))
(dl-byte (ldb #o0010 ,word)))))
Insert a 32 - bit word into the DL .
(defmacro dl-32word (word)
(once-only (word)
`(progn (dl-byte (ldb #o3010 ,word))
(dl-byte (ldb #o2010 ,word))
(dl-byte (ldb #o1010 ,word))
(dl-byte (ldb #o0010 ,word)))))
(defmacro byte-out (byte)
`(send output-stream :tyo ,byte))
(defmacro word-out (word)
(once-only (word)
`(progn (byte-out (ldb #o1010 ,word))
(byte-out (ldb #o0010 ,word)))))
(defmacro bcpl-out (string max-length)
`(let ((string-end (min (1+ (string-length ,string)) ,max-length)))
(byte-out (1- string-end))
(send output-stream :string-out ,string 0 (1- string-end))
(pad-bytes-out (- ,max-length string-end))))
(defmacro pad-bytes-out (number)
`(loop repeat ,number do (byte-out 0)))
(defun open-8b-input (filename)
using : characters NIL can confuse some servers into 16 bit mode .
(let ((pathname (send (fs:parse-pathname filename) :translated-pathname)))
(cond ((eq :lispm (send pathname :system-type))
(open filename :direction :input))
('else
(open filename :direction :input :raw t)))))
(defun open-8b-output (filename)
(let ((pathname (send (fs:parse-pathname filename) :translated-pathname)))
(cond ((eq :lispm (send pathname :system-type))
(open filename :direction :output))
('else
(open filename :direction :output :raw t)))))
(defun file-stream-length (file-stream)
if we used : characters NIL and : byte - size 8
(send file-stream :length))
(defvar *pxl-filename-prepend* "tex: TeXfonts;")
(defvar *tfm-filename-prepend* "tex: TeXfonts;")
|
4d3e51680ba8254d4f9920ad69173127e117ad1b6af3639beda046e903affdd6
|
tiensonqin/lymchat
|
channel.clj
|
(ns api.db.channel
(:refer-clojure :exclude [get update])
(:require [clojure.java.jdbc :as j]
[api.db.util :refer [with-now in-placeholders] :as util]
[api.util :refer [flake-id]]
[api.db.user :as user]
[taoensso.carmine :as car]
[api.util :refer [wcar*]]
[environ-plus.core :refer [env]]))
(defonce ^:private table "channels")
(defonce ^:private members-table "channels_members")
(defonce channels-cache (atom []))
zset
(defonce redis-members-key "channels_members:")
(defn exists?
[db name]
(util/exists? db table {:name name}))
(defn member-exists?
[db channel-id user-id]
(util/exists? db members-table {:channel_id channel-id
:user_id user-id}))
(defn cache-get
[id]
(first (filter #(= (str id) (str (:id %))) @channels-cache)))
(defn get
[db id]
(if-let [result (cache-get id)]
result
(when-let [result (-> (j/query db ["select * from channels where id = ?" id])
first)]
(swap! channels-cache conj result)
result)))
(defn create
[db m]
(when-let [channel (-> (j/insert! db table (-> m
(with-now [:created_at])))
first)]
(swap! channels-cache conj channel)
channel))
(defn update
[db id m]
(j/update! db table m ["id = ?" id])
(swap! channels-cache (fn [cache]
(remove #(= id (:id %)) cache)))
(get db id))
(defn delete
[db id]
(j/delete! db table ["id = ?" id])
(swap! channels-cache (fn [cache]
(remove #(= id (:id %)) cache))))
(defn inc-members
[db id]
(j/execute! db ["update channels set members_count = members_count + 1 where id = ?" id]))
(defn dec-members
[db id]
(j/execute! db ["update channels set members_count = members_count - 1 where id = ?" id]))
(defn get-db-members
[db channel-id]
(j/query db ["select * from channels_members where channel_id = ?" channel-id]))
(defn get-members
[id]
(->>
(wcar* (:redis env)
(car/zrange (str redis-members-key id) 0 -1))
(remove nil?)))
(defn get-channels-members-count
[db channels-ids]
(when (seq channels-ids)
(j/query db (cons (format "select * from channels where id in (%s)" (in-placeholders channels-ids)) channels-ids))))
(defn get-users-by-usernames
[id usernames]
(when-not (empty? usernames)
(when-let [members (seq (get-members id))]
(filter #(contains? (set usernames) (:username %)) members))))
(defn get-online-channel-users
[connected-uids channel-id]
(when-let [members (map (comp (fn [s] (if s (str s) s)) :id) (get-members channel-id))]
(clojure.set/intersection (set members) connected-uids)))
(defn join
[db channel-id user-id]
(when-let [r (try (j/insert! db members-table (with-now {:channel_id channel-id
:user_id user-id}
[:created_at]))
(catch Exception e
(prn e)))]
(when-let [user (user/get db user-id [:id :flake_id :name :username :avatar :language :timezone])]
(wcar* (:redis env)
(car/zadd (str redis-members-key channel-id) (:flake_id user) user)))))
(defn leave
[db channel-id user-id]
(when (first (j/delete! db members-table ["channel_id = ? and user_id = ?"
channel-id
user-id]))
(when-let [user (user/get db user-id [:flake_id])]
(wcar* (:redis env)
(car/zremrangebyscore (str redis-members-key channel-id) (:flake-id user) (:flake-id user))))))
(defn get-all
[db]
(j/query db ["select * from channels
where block = false
and is_private = false
order by created_at desc"]))
(defn load-in-memory
[db]
(reset! channels-cache (distinct (get-all db))))
(defn cache-get-all
[]
@channels-cache)
(defn search-by-name-prefix
[q limit]
(some->> @channels-cache
(filter #(re-find (re-pattern (str "(?i)" q)) (:name %)))
(sort (fn [t1 t2]
(if (clojure.string/starts-with?
(clojure.string/lower-case (:name t1))
(clojure.string/lower-case q))
true
false)))
(take limit)))
(defn search-members
[user-id id q limit]
(when q
(when-let [members (seq (get-members id))]
(some->> members
(filter #(and
(not= user-id (str (:id %)))
(or (re-find (re-pattern (str "(?i)" q)) (:username %))
(re-find (re-pattern (str "(?i)" q)) (:name %)))))
(sort (fn [t1 t2]
(if (or
(clojure.string/starts-with?
(clojure.string/lower-case (:name t1))
(clojure.string/lower-case q))
(clojure.string/starts-with?
(clojure.string/lower-case (:username t1))
(clojure.string/lower-case q)))
true
false)))
(take limit)))))
(defn get-recommend
[db]
(let [countries ["United Kingdom" "United States" "China" "Japan" "Spain" "France" "Germany" "Italy" "Denmark" "Sweden" "Norway" "Australia" "Iceland" "Luxembourg" "Switzerland" "Qatar" "New Zealand" "Netherlands" "Finland" "Ireland" "Canada" "Singapore" "Belgium" "Slovenia" "United Arab Emirates" "South Korea" "Chile" "Portugal"]]
{:languages (vec (j/query db ["select * from channels where type = 'language' order by created_at asc"]))
:places (vec (j/query db ["select * from channels where type = 'place' and locale = 'english' order by created_at asc"]))
:chinese-places (vec (j/query db ["select * from channels where type = 'place' and locale = 'chinese' order by created_at asc limit 20"]))
:others (vec (j/query db ["select * from channels where type is null and locale = 'english' order by created_at asc limit 20"]))
:chinese-others (vec (j/query db ["select * from channels where type is null and locale = 'chinese' order by created_at asc limit 20"]))
:nba (vec (j/query db ["select * from channels where type = 'nba' order by created_at asc"]))
:football (vec (j/query db ["select * from channels where type = 'football' order by created_at asc"]))
:countries (let [result (j/query db ["select * from channels where type = 'country' order by created_at asc"])]
(->> (for [country countries]
(filter #(= country (:name %)) result))
(apply concat)
(vec)))
:colleges (vec (j/query db ["select * from channels where type = 'college' order by created_at asc"]))
:chinese-colleges (vec (j/query db ["select * from channels where type = 'chinese-college' order by created_at asc limit 20"]))}))
(defn get-recommend-others
[db locale]
(if (= "Chinese" locale)
(j/query db ["select * from channels where type is null and locale = 'chinese' order by created_at asc limit 20"])
(j/query db ["select * from channels where type is null and locale = 'english' order by created_at asc limit 20"])))
| null |
https://raw.githubusercontent.com/tiensonqin/lymchat/824026607d30c12bc50afb06f677d1fa95ff1f2f/api/src/api/db/channel.clj
|
clojure
|
(ns api.db.channel
(:refer-clojure :exclude [get update])
(:require [clojure.java.jdbc :as j]
[api.db.util :refer [with-now in-placeholders] :as util]
[api.util :refer [flake-id]]
[api.db.user :as user]
[taoensso.carmine :as car]
[api.util :refer [wcar*]]
[environ-plus.core :refer [env]]))
(defonce ^:private table "channels")
(defonce ^:private members-table "channels_members")
(defonce channels-cache (atom []))
zset
(defonce redis-members-key "channels_members:")
(defn exists?
[db name]
(util/exists? db table {:name name}))
(defn member-exists?
[db channel-id user-id]
(util/exists? db members-table {:channel_id channel-id
:user_id user-id}))
(defn cache-get
[id]
(first (filter #(= (str id) (str (:id %))) @channels-cache)))
(defn get
[db id]
(if-let [result (cache-get id)]
result
(when-let [result (-> (j/query db ["select * from channels where id = ?" id])
first)]
(swap! channels-cache conj result)
result)))
(defn create
[db m]
(when-let [channel (-> (j/insert! db table (-> m
(with-now [:created_at])))
first)]
(swap! channels-cache conj channel)
channel))
(defn update
[db id m]
(j/update! db table m ["id = ?" id])
(swap! channels-cache (fn [cache]
(remove #(= id (:id %)) cache)))
(get db id))
(defn delete
[db id]
(j/delete! db table ["id = ?" id])
(swap! channels-cache (fn [cache]
(remove #(= id (:id %)) cache))))
(defn inc-members
[db id]
(j/execute! db ["update channels set members_count = members_count + 1 where id = ?" id]))
(defn dec-members
[db id]
(j/execute! db ["update channels set members_count = members_count - 1 where id = ?" id]))
(defn get-db-members
[db channel-id]
(j/query db ["select * from channels_members where channel_id = ?" channel-id]))
(defn get-members
[id]
(->>
(wcar* (:redis env)
(car/zrange (str redis-members-key id) 0 -1))
(remove nil?)))
(defn get-channels-members-count
[db channels-ids]
(when (seq channels-ids)
(j/query db (cons (format "select * from channels where id in (%s)" (in-placeholders channels-ids)) channels-ids))))
(defn get-users-by-usernames
[id usernames]
(when-not (empty? usernames)
(when-let [members (seq (get-members id))]
(filter #(contains? (set usernames) (:username %)) members))))
(defn get-online-channel-users
[connected-uids channel-id]
(when-let [members (map (comp (fn [s] (if s (str s) s)) :id) (get-members channel-id))]
(clojure.set/intersection (set members) connected-uids)))
(defn join
[db channel-id user-id]
(when-let [r (try (j/insert! db members-table (with-now {:channel_id channel-id
:user_id user-id}
[:created_at]))
(catch Exception e
(prn e)))]
(when-let [user (user/get db user-id [:id :flake_id :name :username :avatar :language :timezone])]
(wcar* (:redis env)
(car/zadd (str redis-members-key channel-id) (:flake_id user) user)))))
(defn leave
[db channel-id user-id]
(when (first (j/delete! db members-table ["channel_id = ? and user_id = ?"
channel-id
user-id]))
(when-let [user (user/get db user-id [:flake_id])]
(wcar* (:redis env)
(car/zremrangebyscore (str redis-members-key channel-id) (:flake-id user) (:flake-id user))))))
(defn get-all
[db]
(j/query db ["select * from channels
where block = false
and is_private = false
order by created_at desc"]))
(defn load-in-memory
[db]
(reset! channels-cache (distinct (get-all db))))
(defn cache-get-all
[]
@channels-cache)
(defn search-by-name-prefix
[q limit]
(some->> @channels-cache
(filter #(re-find (re-pattern (str "(?i)" q)) (:name %)))
(sort (fn [t1 t2]
(if (clojure.string/starts-with?
(clojure.string/lower-case (:name t1))
(clojure.string/lower-case q))
true
false)))
(take limit)))
(defn search-members
[user-id id q limit]
(when q
(when-let [members (seq (get-members id))]
(some->> members
(filter #(and
(not= user-id (str (:id %)))
(or (re-find (re-pattern (str "(?i)" q)) (:username %))
(re-find (re-pattern (str "(?i)" q)) (:name %)))))
(sort (fn [t1 t2]
(if (or
(clojure.string/starts-with?
(clojure.string/lower-case (:name t1))
(clojure.string/lower-case q))
(clojure.string/starts-with?
(clojure.string/lower-case (:username t1))
(clojure.string/lower-case q)))
true
false)))
(take limit)))))
(defn get-recommend
[db]
(let [countries ["United Kingdom" "United States" "China" "Japan" "Spain" "France" "Germany" "Italy" "Denmark" "Sweden" "Norway" "Australia" "Iceland" "Luxembourg" "Switzerland" "Qatar" "New Zealand" "Netherlands" "Finland" "Ireland" "Canada" "Singapore" "Belgium" "Slovenia" "United Arab Emirates" "South Korea" "Chile" "Portugal"]]
{:languages (vec (j/query db ["select * from channels where type = 'language' order by created_at asc"]))
:places (vec (j/query db ["select * from channels where type = 'place' and locale = 'english' order by created_at asc"]))
:chinese-places (vec (j/query db ["select * from channels where type = 'place' and locale = 'chinese' order by created_at asc limit 20"]))
:others (vec (j/query db ["select * from channels where type is null and locale = 'english' order by created_at asc limit 20"]))
:chinese-others (vec (j/query db ["select * from channels where type is null and locale = 'chinese' order by created_at asc limit 20"]))
:nba (vec (j/query db ["select * from channels where type = 'nba' order by created_at asc"]))
:football (vec (j/query db ["select * from channels where type = 'football' order by created_at asc"]))
:countries (let [result (j/query db ["select * from channels where type = 'country' order by created_at asc"])]
(->> (for [country countries]
(filter #(= country (:name %)) result))
(apply concat)
(vec)))
:colleges (vec (j/query db ["select * from channels where type = 'college' order by created_at asc"]))
:chinese-colleges (vec (j/query db ["select * from channels where type = 'chinese-college' order by created_at asc limit 20"]))}))
(defn get-recommend-others
[db locale]
(if (= "Chinese" locale)
(j/query db ["select * from channels where type is null and locale = 'chinese' order by created_at asc limit 20"])
(j/query db ["select * from channels where type is null and locale = 'english' order by created_at asc limit 20"])))
|
|
4b638233786d6605c9aef4b7aa95d3d39a84aa54cb920bfb0ab06787a05ec72a
|
jepsen-io/maelstrom
|
unique_ids.clj
|
(ns maelstrom.workload.unique-ids
"A simple workload for ID generation systems. Clients ask servers to generate
an ID, and the server should respond with an ID. The test verifies that those
IDs are globally unique.
Your node will receive a request body like:
```json
{\"type\": \"generate\",
\"msg_id\": 2}
```
And should respond with something like:
```json
{\"type\": \"generate_ok\",
\"in_reply_to\": 2,
\"id\": 123}
```
IDs may be of any type--strings, booleans, integers, floats, compound JSON
values, etc."
(:require [maelstrom [client :as c]
[net :as net]]
[jepsen [checker :as checker]
[client :as client]
[generator :as gen]
[tests :as tests]]
[schema.core :as s]))
(c/defrpc generate!
"Asks a node to generate a new ID. Servers respond with a generate_ok message
containing an `id` field, which should be a globally unique value. IDs may be
of any type."
{:type (s/eq "generate")}
{:type (s/eq "generate_ok")
:id s/Any})
(defn client
"Constructs a client for ID generation."
([net]
(client net nil nil))
([net conn node]
(reify client/Client
(open! [_ test node]
(client net (c/open! net) node))
(setup! [_ test])
(invoke! [_ test op]
(c/with-errors op #{}
(assoc op :type :ok, :value (:id (generate! conn node {})))))
(teardown! [_ test])
(close! [_ test]
(c/close! conn))
client/Reusable
(reusable? [this test]
true))))
(defn workload
"Constructs a workload for unique ID generation, given options from the CLI
test constructor. Options are:
:net A Maelstrom network"
[opts]
(assoc tests/noop-test
:client (client (:net opts))
:generator (gen/repeat {:f :generate})
:checker (checker/unique-ids)))
| null |
https://raw.githubusercontent.com/jepsen-io/maelstrom/857ce8df26d88cfe9182c5603a77f288023dcca1/src/maelstrom/workload/unique_ids.clj
|
clojure
|
(ns maelstrom.workload.unique-ids
"A simple workload for ID generation systems. Clients ask servers to generate
an ID, and the server should respond with an ID. The test verifies that those
IDs are globally unique.
Your node will receive a request body like:
```json
{\"type\": \"generate\",
\"msg_id\": 2}
```
And should respond with something like:
```json
{\"type\": \"generate_ok\",
\"in_reply_to\": 2,
\"id\": 123}
```
IDs may be of any type--strings, booleans, integers, floats, compound JSON
values, etc."
(:require [maelstrom [client :as c]
[net :as net]]
[jepsen [checker :as checker]
[client :as client]
[generator :as gen]
[tests :as tests]]
[schema.core :as s]))
(c/defrpc generate!
"Asks a node to generate a new ID. Servers respond with a generate_ok message
containing an `id` field, which should be a globally unique value. IDs may be
of any type."
{:type (s/eq "generate")}
{:type (s/eq "generate_ok")
:id s/Any})
(defn client
"Constructs a client for ID generation."
([net]
(client net nil nil))
([net conn node]
(reify client/Client
(open! [_ test node]
(client net (c/open! net) node))
(setup! [_ test])
(invoke! [_ test op]
(c/with-errors op #{}
(assoc op :type :ok, :value (:id (generate! conn node {})))))
(teardown! [_ test])
(close! [_ test]
(c/close! conn))
client/Reusable
(reusable? [this test]
true))))
(defn workload
"Constructs a workload for unique ID generation, given options from the CLI
test constructor. Options are:
:net A Maelstrom network"
[opts]
(assoc tests/noop-test
:client (client (:net opts))
:generator (gen/repeat {:f :generate})
:checker (checker/unique-ids)))
|
|
c116c79555aa9535ceb346b4c676507656b38e2c05a4cd5306425a3ba1aa1d51
|
dundalek/closh
|
cmd2.cljc
|
(defcmd my-hello [x]
(println (str "Hello " x)))
my-hello World
| null |
https://raw.githubusercontent.com/dundalek/closh/b1a7fd310b6511048fbacb8e496f574c8ccfa291/fixtures/script-mode-tests/cmd2.cljc
|
clojure
|
(defcmd my-hello [x]
(println (str "Hello " x)))
my-hello World
|
|
7e660cb5c5035f745aa4e9d7951124750e4c3d4c22de68a5fb101ed52a6d766f
|
ryanpbrewster/haskell
|
shortest_anagram_subsequence.hs
|
-- shortest_anagram_subsequence.hs
Given a little string , L , and a big string , B , find the smallest substring of B , s , such
that s contains an anagram of L. Put another way , find the smallest substring of B , s , such
that for every character c in L , L.count(c ) = = s.count(c )
Given a little string, L, and a big string, B, find the smallest substring of B, s, such
that s contains an anagram of L. Put another way, find the smallest substring of B, s, such
that for every character c in L, L.count(c) == s.count(c)
-}
import qualified Data.HashMap.Strict as M
import qualified Data.Array as A
import Debug.Trace
import Data.List (minimumBy)
import Data.Ord (comparing)
import Data.Char (ord, chr)
import qualified Random.MWC.Pure as RNG
import Control.Monad.State
instance RNG.RangeRandom Char where
range_random (a, b) s =
let (n, s') = RNG.range_random (ord a, ord b) s
in (chr n, s')
randomChars :: RNG.Seed -> [Char]
randomChars initSeed = randomChars' initSeed
where
randomChars' s =
let (ch, s') = RNG.range_random ('a', 'z') s
in ch : randomChars' s'
chunks :: Int -> [a] -> [[a]]
chunks n xs = let (f, rest) = splitAt n xs in f : chunks n rest
main = do
let inputs = map (splitAt 1000) $ chunks 10000 $ randomChars (RNG.seed [])
print [ shortestAnagram little big | (little, big) <- take 10 inputs ]
shortestAnagram :: String -> String -> Int
shortestAnagram little big =
let
littleTally = M.fromListWith (+) $ zip little (repeat 1)
bigArray = A.listArray (1, length big) big
in minimum [ end - start | (start, end) <- locallyMinimalAnagrams littleTally bigArray ]
type Bookends = (Int, Int)
type StringArr = A.Array Int Char
type AnagramTally = M.HashMap Char Int
locallyMinimalAnagrams :: AnagramTally -> StringArr -> [Bookends]
locallyMinimalAnagrams little big = expand (1, 1) little (M.size little)
where
(1, n) = A.bounds big
expand :: Bookends -> AnagramTally -> Int -> [Bookends]
expand (lo, hi) counts numOverThreshold
| hi > n = []
| not ((big A.! hi) `M.member` counts) = expand (lo, hi+1) counts numOverThreshold
| otherwise =
let
x = big A.! hi
c = counts M.! x
counts' = M.adjust (subtract 1) x counts
numOverThreshold' = if c-1 == 0 then numOverThreshold-1 else numOverThreshold
in if numOverThreshold' == 0
then shrink (lo, hi+1) counts'
else expand (lo, hi+1) counts' numOverThreshold'
shrink :: Bookends -> AnagramTally -> [Bookends]
shrink (lo, hi) counts
| not ((big A.! lo) `M.member` counts) = shrink (lo+1, hi) counts
| otherwise =
let
x = big A.! lo
c = counts M.! x
counts' = M.adjust (+1) x counts
in if c == 0
then (lo, hi) : expand (lo+1, hi) counts' 1
else shrink (lo+1, hi) counts'
| null |
https://raw.githubusercontent.com/ryanpbrewster/haskell/6edd0afe234008a48b4871032dedfd143ca6e412/hello-world/shortest_anagram_subsequence.hs
|
haskell
|
shortest_anagram_subsequence.hs
|
Given a little string , L , and a big string , B , find the smallest substring of B , s , such
that s contains an anagram of L. Put another way , find the smallest substring of B , s , such
that for every character c in L , L.count(c ) = = s.count(c )
Given a little string, L, and a big string, B, find the smallest substring of B, s, such
that s contains an anagram of L. Put another way, find the smallest substring of B, s, such
that for every character c in L, L.count(c) == s.count(c)
-}
import qualified Data.HashMap.Strict as M
import qualified Data.Array as A
import Debug.Trace
import Data.List (minimumBy)
import Data.Ord (comparing)
import Data.Char (ord, chr)
import qualified Random.MWC.Pure as RNG
import Control.Monad.State
instance RNG.RangeRandom Char where
range_random (a, b) s =
let (n, s') = RNG.range_random (ord a, ord b) s
in (chr n, s')
randomChars :: RNG.Seed -> [Char]
randomChars initSeed = randomChars' initSeed
where
randomChars' s =
let (ch, s') = RNG.range_random ('a', 'z') s
in ch : randomChars' s'
chunks :: Int -> [a] -> [[a]]
chunks n xs = let (f, rest) = splitAt n xs in f : chunks n rest
main = do
let inputs = map (splitAt 1000) $ chunks 10000 $ randomChars (RNG.seed [])
print [ shortestAnagram little big | (little, big) <- take 10 inputs ]
shortestAnagram :: String -> String -> Int
shortestAnagram little big =
let
littleTally = M.fromListWith (+) $ zip little (repeat 1)
bigArray = A.listArray (1, length big) big
in minimum [ end - start | (start, end) <- locallyMinimalAnagrams littleTally bigArray ]
type Bookends = (Int, Int)
type StringArr = A.Array Int Char
type AnagramTally = M.HashMap Char Int
locallyMinimalAnagrams :: AnagramTally -> StringArr -> [Bookends]
locallyMinimalAnagrams little big = expand (1, 1) little (M.size little)
where
(1, n) = A.bounds big
expand :: Bookends -> AnagramTally -> Int -> [Bookends]
expand (lo, hi) counts numOverThreshold
| hi > n = []
| not ((big A.! hi) `M.member` counts) = expand (lo, hi+1) counts numOverThreshold
| otherwise =
let
x = big A.! hi
c = counts M.! x
counts' = M.adjust (subtract 1) x counts
numOverThreshold' = if c-1 == 0 then numOverThreshold-1 else numOverThreshold
in if numOverThreshold' == 0
then shrink (lo, hi+1) counts'
else expand (lo, hi+1) counts' numOverThreshold'
shrink :: Bookends -> AnagramTally -> [Bookends]
shrink (lo, hi) counts
| not ((big A.! lo) `M.member` counts) = shrink (lo+1, hi) counts
| otherwise =
let
x = big A.! lo
c = counts M.! x
counts' = M.adjust (+1) x counts
in if c == 0
then (lo, hi) : expand (lo+1, hi) counts' 1
else shrink (lo+1, hi) counts'
|
4dee9291b28842a9cdb9c3aa98517f13ff37e87be42fedf80ba48b3dbed44f9f
|
softlab-ntua/bencherl
|
scheduling_multiple_coupled_erratic_actors_test.erl
|
Copyright ( C ) 2008 - 2014 EDF R&D
This file is part of Sim - Diasca .
Sim - Diasca 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 3 of
the License , or ( at your option ) any later version .
Sim - Diasca 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 .
% If not, see </>.
Author : ( )
% Overall unit test of the Sim-Diasca deployment and scheduling framework.
Three coupled erratic actors will be created prior to starting the simulation ,
planning to terminate at tick offsets # 80 , # 100 and # 150 , whereas the
simulation stops at # 120 .
%
-module(scheduling_multiple_coupled_erratic_actors_test).
% For all facilities common to all tests:
-include("test_constructs.hrl").
% Runs a distributed simulation (of course if relevant computing hosts are
% specified).
%
-spec run() -> no_return().
run() ->
?test_start,
Default simulation settings ( 50Hz , batch reproducible ) are used , except
% for the name:
SimulationSettings = #simulation_settings{
simulation_name = "Scheduling multiple coupled erratic actor test"
},
% Default deployment settings (unavailable nodes allowed, on-the-fly
% generation of the deployment package requested), but computing
% hosts are specified (to be updated depending on your environment):
% (note that localhost is implied)
DeploymentSettings = #deployment_settings{
computing_hosts =
{ use_host_file_otherwise_local, "sim-diasca-host-candidates.txt" }
},
% Default load balancing settings (round-robin placement heuristic):
LoadBalancingSettings = #load_balancing_settings{},
?test_info_fmt( "This test will deploy a distributed simulation"
" based on computing hosts specified as ~p.",
[ DeploymentSettings#deployment_settings.computing_hosts ] ),
% Directly created on the user node:
DeploymentManagerPid = sim_diasca:init( SimulationSettings,
DeploymentSettings, LoadBalancingSettings ),
?test_info( "Deployment manager created, retrieving the load balancer." ),
DeploymentManagerPid ! { getLoadBalancer, [], self() },
LoadBalancerPid = test_receive(),
?test_info( "Requesting to the load balancer the creation of "
"a first initial test actor." ),
FirstActorPid = class_Actor:create_initial_actor( class_TestActor,
[ "First test actor", { erratic, _FirstMinRange=5 },
no_creation, _FirstTerminationTickOffset=80 ], LoadBalancerPid ),
FirstActorPid ! { getAAI, [], self() },
2 = test_receive(),
?test_info_fmt( "First actor has for PID ~w and for AAI 2.",
[ FirstActorPid ] ),
?test_info( "First actor has a correct AAI." ),
SecondActorPid = class_Actor:create_initial_actor( class_TestActor,
[ "Second test actor", { erratic, _SecondMinRange=7 },
no_creation, _SecondTerminationTickOffset=100 ], LoadBalancerPid ),
SecondActorPid ! { getAAI, [], self() },
3 = test_receive(),
% Meant to be still living at the end of the simulation:
ThirdActorPid = class_Actor:create_initial_actor( class_TestActor,
["Third test actor", { erratic, _ThirdMinRange=10 },
no_creation, _ThirdTerminationTickOffset=150 ], LoadBalancerPid ),
ThirdActorPid ! { getAAI, [], self() },
4 = test_receive(),
?test_info( "First three actors have correct AAI." ),
?test_info( "Linking actors (full connectivity)." ),
class_TestActor:add_initial_peers( FirstActorPid,
[ SecondActorPid, ThirdActorPid ] ),
class_TestActor:add_initial_peers( SecondActorPid,
[ FirstActorPid, ThirdActorPid ] ),
class_TestActor:add_initial_peers( ThirdActorPid,
[ FirstActorPid, SecondActorPid ] ),
DeploymentManagerPid ! { getRootTimeManager, [], self() },
RootTimeManagerPid = test_receive(),
?test_info( "Starting simulation." ),
RootTimeManagerPid ! { start, [ _StopTick=120, self() ] },
?test_info( "Requesting textual timings (first)." ),
RootTimeManagerPid ! { getTextualTimings, [],self() },
FirstTimingString = test_receive(),
?test_info_fmt( "Received first time: ~s.", [ FirstTimingString ] ),
% Waits until simulation is finished:
receive
simulation_stopped ->
?test_info( "Simulation stopped spontaneously." )
end,
?test_info( "Requesting textual timings (second)." ),
RootTimeManagerPid ! { getTextualTimings, [], self() },
SecondTimingString = test_receive(),
?test_info_fmt( "Received second time: ~s.", [ SecondTimingString ] ),
sim_diasca:shutdown(),
?test_stop.
| null |
https://raw.githubusercontent.com/softlab-ntua/bencherl/317bdbf348def0b2f9ed32cb6621e21083b7e0ca/app/sim-diasca/sim-diasca/src/core/src/scheduling/tests/scheduling_multiple_coupled_erratic_actors_test.erl
|
erlang
|
it under the terms of the GNU Lesser General Public License as
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
If not, see </>.
Overall unit test of the Sim-Diasca deployment and scheduling framework.
For all facilities common to all tests:
Runs a distributed simulation (of course if relevant computing hosts are
specified).
for the name:
Default deployment settings (unavailable nodes allowed, on-the-fly
generation of the deployment package requested), but computing
hosts are specified (to be updated depending on your environment):
(note that localhost is implied)
Default load balancing settings (round-robin placement heuristic):
Directly created on the user node:
Meant to be still living at the end of the simulation:
Waits until simulation is finished:
|
Copyright ( C ) 2008 - 2014 EDF R&D
This file is part of Sim - Diasca .
Sim - Diasca is free software : you can redistribute it and/or modify
published by the Free Software Foundation , either version 3 of
the License , or ( at your option ) any later version .
Sim - Diasca is distributed in the hope that it will be useful ,
GNU Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public
License along with .
Author : ( )
Three coupled erratic actors will be created prior to starting the simulation ,
planning to terminate at tick offsets # 80 , # 100 and # 150 , whereas the
simulation stops at # 120 .
-module(scheduling_multiple_coupled_erratic_actors_test).
-include("test_constructs.hrl").
-spec run() -> no_return().
run() ->
?test_start,
Default simulation settings ( 50Hz , batch reproducible ) are used , except
SimulationSettings = #simulation_settings{
simulation_name = "Scheduling multiple coupled erratic actor test"
},
DeploymentSettings = #deployment_settings{
computing_hosts =
{ use_host_file_otherwise_local, "sim-diasca-host-candidates.txt" }
},
LoadBalancingSettings = #load_balancing_settings{},
?test_info_fmt( "This test will deploy a distributed simulation"
" based on computing hosts specified as ~p.",
[ DeploymentSettings#deployment_settings.computing_hosts ] ),
DeploymentManagerPid = sim_diasca:init( SimulationSettings,
DeploymentSettings, LoadBalancingSettings ),
?test_info( "Deployment manager created, retrieving the load balancer." ),
DeploymentManagerPid ! { getLoadBalancer, [], self() },
LoadBalancerPid = test_receive(),
?test_info( "Requesting to the load balancer the creation of "
"a first initial test actor." ),
FirstActorPid = class_Actor:create_initial_actor( class_TestActor,
[ "First test actor", { erratic, _FirstMinRange=5 },
no_creation, _FirstTerminationTickOffset=80 ], LoadBalancerPid ),
FirstActorPid ! { getAAI, [], self() },
2 = test_receive(),
?test_info_fmt( "First actor has for PID ~w and for AAI 2.",
[ FirstActorPid ] ),
?test_info( "First actor has a correct AAI." ),
SecondActorPid = class_Actor:create_initial_actor( class_TestActor,
[ "Second test actor", { erratic, _SecondMinRange=7 },
no_creation, _SecondTerminationTickOffset=100 ], LoadBalancerPid ),
SecondActorPid ! { getAAI, [], self() },
3 = test_receive(),
ThirdActorPid = class_Actor:create_initial_actor( class_TestActor,
["Third test actor", { erratic, _ThirdMinRange=10 },
no_creation, _ThirdTerminationTickOffset=150 ], LoadBalancerPid ),
ThirdActorPid ! { getAAI, [], self() },
4 = test_receive(),
?test_info( "First three actors have correct AAI." ),
?test_info( "Linking actors (full connectivity)." ),
class_TestActor:add_initial_peers( FirstActorPid,
[ SecondActorPid, ThirdActorPid ] ),
class_TestActor:add_initial_peers( SecondActorPid,
[ FirstActorPid, ThirdActorPid ] ),
class_TestActor:add_initial_peers( ThirdActorPid,
[ FirstActorPid, SecondActorPid ] ),
DeploymentManagerPid ! { getRootTimeManager, [], self() },
RootTimeManagerPid = test_receive(),
?test_info( "Starting simulation." ),
RootTimeManagerPid ! { start, [ _StopTick=120, self() ] },
?test_info( "Requesting textual timings (first)." ),
RootTimeManagerPid ! { getTextualTimings, [],self() },
FirstTimingString = test_receive(),
?test_info_fmt( "Received first time: ~s.", [ FirstTimingString ] ),
receive
simulation_stopped ->
?test_info( "Simulation stopped spontaneously." )
end,
?test_info( "Requesting textual timings (second)." ),
RootTimeManagerPid ! { getTextualTimings, [], self() },
SecondTimingString = test_receive(),
?test_info_fmt( "Received second time: ~s.", [ SecondTimingString ] ),
sim_diasca:shutdown(),
?test_stop.
|
03ef9f6f4c003b74ee67e41caca8bd0367c032e975b8119e0814b4ae9b0ffb1d
|
jrh13/hol-light
|
make.ml
|
(* ========================================================================= *)
Elliptic curves of various forms and specific ones for cryptography .
(* ========================================================================= *)
needs "Library/pocklington.ml";;
needs "Library/primitive.ml";;
needs "Library/grouptheory.ml";;
needs "Library/ringtheory.ml";;
(* ------------------------------------------------------------------------- *)
(* A few extras to support all the curve proofs. *)
(* ------------------------------------------------------------------------- *)
loadt "EC/misc.ml";;
(* ------------------------------------------------------------------------- *)
Short Weierstrass , Montgomery and curves ( independently ) .
(* ------------------------------------------------------------------------- *)
loadt "EC/weierstrass.ml";;
loadt "EC/montgomery.ml";;
loadt "EC/edwards.ml";;
(* ------------------------------------------------------------------------- *)
Projective , Jacobian , projective - without - y , extended projective coords .
(* ------------------------------------------------------------------------- *)
loadt "EC/projective.ml";;
loadt "EC/jacobian.ml";;
loadt "EC/xzprojective.ml";;
loadt "EC/exprojective.ml";;
(* ------------------------------------------------------------------------- *)
(* Some traditional formulas for evaluation in these coordinate systems. *)
(* ------------------------------------------------------------------------- *)
loadt "EC/formulary_projective.ml";;
loadt "EC/formulary_jacobian.ml";;
loadt "EC/formulary_xzprojective.ml";;
(* ------------------------------------------------------------------------- *)
Translations between curves : < - > Montgomery < - > Weierstrass .
(* ------------------------------------------------------------------------- *)
loadt "EC/edmont.ml";;
loadt "EC/montwe.ml";;
(* ------------------------------------------------------------------------- *)
(* Additional computational derived rules. *)
(* ------------------------------------------------------------------------- *)
loadt "EC/excluderoots.ml";;
loadt "EC/computegroup.ml";;
(* ------------------------------------------------------------------------- *)
The NIST curves over prime characteristic fields .
(* ------------------------------------------------------------------------- *)
loadt "EC/nistp192.ml";;
loadt "EC/nistp224.ml";;
loadt "EC/nistp256.ml";;
loadt "EC/nistp384.ml";;
loadt "EC/nistp521.ml";;
(* ------------------------------------------------------------------------- *)
(* The (other) SECG curves over prime characteristic fields *)
(* ------------------------------------------------------------------------- *)
loadt "EC/secp192k1.ml";;
loadt "EC/secp224k1.ml";;
loadt "EC/secp256k1.ml";;
(* ------------------------------------------------------------------------- *)
The family in Edwards , Montgomery and Weierstrass forms .
The first three files are independent , the fourth giving the connections .
(* ------------------------------------------------------------------------- *)
loadt "EC/edwards25519.ml";;
loadt "EC/curve25519.ml";;
loadt "EC/wei25519.ml";;
loadt "EC/family25519.ml";;
(* ------------------------------------------------------------------------- *)
(* The x25519 function, as a mapping of x coordinates over a generalization *)
of with the y coordinate living in an extension field .
(* ------------------------------------------------------------------------- *)
loadt "EC/x25519.ml";;
(* ------------------------------------------------------------------------- *)
(* The Goldilocks curve *)
(* ------------------------------------------------------------------------- *)
loadt "EC/edwards448.ml";;
| null |
https://raw.githubusercontent.com/jrh13/hol-light/1bf0ddf9113e491793774d71116fd498d80dc866/EC/make.ml
|
ocaml
|
=========================================================================
=========================================================================
-------------------------------------------------------------------------
A few extras to support all the curve proofs.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Some traditional formulas for evaluation in these coordinate systems.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Additional computational derived rules.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
The (other) SECG curves over prime characteristic fields
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
The x25519 function, as a mapping of x coordinates over a generalization
-------------------------------------------------------------------------
-------------------------------------------------------------------------
The Goldilocks curve
-------------------------------------------------------------------------
|
Elliptic curves of various forms and specific ones for cryptography .
needs "Library/pocklington.ml";;
needs "Library/primitive.ml";;
needs "Library/grouptheory.ml";;
needs "Library/ringtheory.ml";;
loadt "EC/misc.ml";;
Short Weierstrass , Montgomery and curves ( independently ) .
loadt "EC/weierstrass.ml";;
loadt "EC/montgomery.ml";;
loadt "EC/edwards.ml";;
Projective , Jacobian , projective - without - y , extended projective coords .
loadt "EC/projective.ml";;
loadt "EC/jacobian.ml";;
loadt "EC/xzprojective.ml";;
loadt "EC/exprojective.ml";;
loadt "EC/formulary_projective.ml";;
loadt "EC/formulary_jacobian.ml";;
loadt "EC/formulary_xzprojective.ml";;
Translations between curves : < - > Montgomery < - > Weierstrass .
loadt "EC/edmont.ml";;
loadt "EC/montwe.ml";;
loadt "EC/excluderoots.ml";;
loadt "EC/computegroup.ml";;
The NIST curves over prime characteristic fields .
loadt "EC/nistp192.ml";;
loadt "EC/nistp224.ml";;
loadt "EC/nistp256.ml";;
loadt "EC/nistp384.ml";;
loadt "EC/nistp521.ml";;
loadt "EC/secp192k1.ml";;
loadt "EC/secp224k1.ml";;
loadt "EC/secp256k1.ml";;
The family in Edwards , Montgomery and Weierstrass forms .
The first three files are independent , the fourth giving the connections .
loadt "EC/edwards25519.ml";;
loadt "EC/curve25519.ml";;
loadt "EC/wei25519.ml";;
loadt "EC/family25519.ml";;
of with the y coordinate living in an extension field .
loadt "EC/x25519.ml";;
loadt "EC/edwards448.ml";;
|
0a4a47a3d46e1f0edf17d94bf1d5c708db3e118dd22eba4491c68494ce0e4a49
|
ghc/ghc
|
T21843e.hs
|
module UnicodeSmartQuotes where
badString = "\”"
| null |
https://raw.githubusercontent.com/ghc/ghc/b0ac38133767a8ca7de63112f39436241ff435a0/testsuite/tests/parser/should_fail/T21843e.hs
|
haskell
|
module UnicodeSmartQuotes where
badString = "\”"
|
|
f35d242e2fc05d821ed2317fe88983c85fb367fc2ed3e4b22162f47d6a3ecf42
|
rurban/clisp
|
should-symbol.lisp
|
Copyright ( C ) 2002 - 2004 , < >
;; ALL RIGHTS RESERVED.
;;
$ I d : should - symbol.lisp , v 1.7 2004/02/20 07:23:42 yuji Exp $
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
;; * Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;; * Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in
;; the documentation and/or other materials provided with the
;; distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR 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.
(HANDLER-CASE (PROGN (MAKE-SYMBOL 'NOT-A-STRING))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (MAKE-SYMBOL #\a))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (MAKE-SYMBOL '(NAME)))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (COPY-SYMBOL "NOT A SYMBOL"))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (COPY-SYMBOL #\a))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (COPY-SYMBOL '(NAME)))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (GENSYM 'EAT-THIS))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (GENSYM -1))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (GENSYM #\a))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (GENTEMP 'NOT-A-STRING))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (GENTEMP #\a))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (GENTEMP "TEMP" '(NIL)))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (SYMBOL-FUNCTION "not-a-function"))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (SYMBOL-FUNCTION #\a))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (SYMBOL-FUNCTION '(NIL)))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE
(PROGN (FMAKUNBOUND 'SYMBOL-FOR-TEST) (SYMBOL-FUNCTION 'SYMBOL-FOR-TEST))
(UNDEFINED-FUNCTION NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (SYMBOL-NAME "not-a-symbol"))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (SYMBOL-NAME #\a))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (SYMBOL-NAME '(NIL)))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (SYMBOL-PACKAGE "not-a-symbol"))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (SYMBOL-PACKAGE #\a))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (SYMBOL-PACKAGE '(NIL)))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (SYMBOL-PLIST "not-a-symbol"))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (SYMBOL-PLIST #\a))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (SYMBOL-PLIST '(NIL)))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (SYMBOL-VALUE "not-a-symbol"))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (SYMBOL-VALUE #\a))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (SYMBOL-VALUE '(NIL)))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (PROGN (MAKUNBOUND 'A) (SYMBOL-VALUE 'A)))
(UNBOUND-VARIABLE NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (GET "not-a-symbol" 'A))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (GET #\a 'A))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (GET '(NIL) 'A))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (REMPROP "not-a-symbol" 'A))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (REMPROP #\a 'A))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (REMPROP '(NIL) 'A))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (BOUNDP "not-a-symbol"))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (BOUNDP #\a))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (BOUNDP '(NIL)))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (MAKUNBOUND "not-a-symbol"))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (MAKUNBOUND #\a))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (MAKUNBOUND '(NIL)))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (SET "not-a-symbol" 1))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (SET #\a 0))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (SET '(NIL) 2))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
| null |
https://raw.githubusercontent.com/rurban/clisp/75ed2995ff8f5364bcc18727cde9438cca4e7c2c/sacla-tests/should-symbol.lisp
|
lisp
|
ALL RIGHTS RESERVED.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
LOSS OF USE ,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
Copyright ( C ) 2002 - 2004 , < >
$ I d : should - symbol.lisp , v 1.7 2004/02/20 07:23:42 yuji Exp $
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
(HANDLER-CASE (PROGN (MAKE-SYMBOL 'NOT-A-STRING))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (MAKE-SYMBOL #\a))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (MAKE-SYMBOL '(NAME)))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (COPY-SYMBOL "NOT A SYMBOL"))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (COPY-SYMBOL #\a))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (COPY-SYMBOL '(NAME)))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (GENSYM 'EAT-THIS))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (GENSYM -1))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (GENSYM #\a))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (GENTEMP 'NOT-A-STRING))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (GENTEMP #\a))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (GENTEMP "TEMP" '(NIL)))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (SYMBOL-FUNCTION "not-a-function"))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (SYMBOL-FUNCTION #\a))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (SYMBOL-FUNCTION '(NIL)))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE
(PROGN (FMAKUNBOUND 'SYMBOL-FOR-TEST) (SYMBOL-FUNCTION 'SYMBOL-FOR-TEST))
(UNDEFINED-FUNCTION NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (SYMBOL-NAME "not-a-symbol"))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (SYMBOL-NAME #\a))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (SYMBOL-NAME '(NIL)))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (SYMBOL-PACKAGE "not-a-symbol"))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (SYMBOL-PACKAGE #\a))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (SYMBOL-PACKAGE '(NIL)))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (SYMBOL-PLIST "not-a-symbol"))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (SYMBOL-PLIST #\a))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (SYMBOL-PLIST '(NIL)))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (SYMBOL-VALUE "not-a-symbol"))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (SYMBOL-VALUE #\a))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (SYMBOL-VALUE '(NIL)))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (PROGN (MAKUNBOUND 'A) (SYMBOL-VALUE 'A)))
(UNBOUND-VARIABLE NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (GET "not-a-symbol" 'A))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (GET #\a 'A))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (GET '(NIL) 'A))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (REMPROP "not-a-symbol" 'A))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (REMPROP #\a 'A))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (REMPROP '(NIL) 'A))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (BOUNDP "not-a-symbol"))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (BOUNDP #\a))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (BOUNDP '(NIL)))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (MAKUNBOUND "not-a-symbol"))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (MAKUNBOUND #\a))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (MAKUNBOUND '(NIL)))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (SET "not-a-symbol" 1))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (SET #\a 0))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
(HANDLER-CASE (PROGN (SET '(NIL) 2))
(TYPE-ERROR NIL T)
(ERROR NIL NIL)
(:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
|
872b4991e35f5e27cbc724b5165deddf392290abcf08bbc55bd5745ac45f1fee
|
haslab/HAAP
|
CollisionSimulator.hs
|
# LANGUAGE ScopedTypeVariables #
module Main where
import JSImages
import LI11718
import qualified Tarefa3_2017li1g183 as T3
import System.Environment
import Data.Maybe
import Data.List as List
import qualified Data.Text as Text
import Text.Read
import Control.Monad
import Control.Exception
import GHC.Float
import qualified CodeWorld as CW
import Graphics.Gloss hiding ((.*.),(.+.),(.-.))
import Graphics . Gloss . Data . Picture
import Graphics . Gloss . Interface . Pure . Game
import Graphics . Gloss .
import Graphics . Gloss . Geometry . Line
import Safe
mexe :: (Int,Int) -> Orientacao -> (Int,Int)
mexe (x,y) Este = (x+1,y)
mexe (x,y) Sul = (x,y+1)
mexe (x,y) Oeste = (x-1,y)
mexe (x,y) Norte = (x,y-1)
roda :: Orientacao -> Bool -> Orientacao
roda Este True = Sul
roda Sul True = Oeste
roda Oeste True = Norte
roda Norte True = Este
roda d False = roda (roda (roda d True) True) True
ponto2Pos :: Ponto -> Posicao
ponto2Pos (x,y) = (i,j)
where x' = floor x
y' = floor y
i = x'
j = y'
data EstadoJogo = J { mapaE :: Mapa
, terreno :: Terreno
, jogador :: EstadoCarro
, tamBloco :: Float
, imagens :: [(String,Picture)]
}
data EstadoCarro = C { posicaoC :: (Double,Double)
, direcaoC :: Double
, velocidadeC :: (Double,Double)
, checkPosicao :: Int
, acelera :: Bool
, trava :: Bool
, viraD :: Bool
, viraE :: Bool
}
data Terreno = T { delta_roda :: Double
, delta_acel :: Double
, delta_drag :: Double
, delta_drift :: Double
, delta_gravity :: Double
}
estadoInicial :: Mapa -> Float -> [(String,Picture)] -> EstadoJogo
estadoInicial m@(Mapa p t) tam imgs = J { mapaE = m
, terreno = standard
, jogador = carroInicial t (fst p) 0
, tamBloco = tam
, imagens = imgs
}
posInicial :: Tabuleiro -> Posicao -> Ponto
posInicial t (a,b) = centroPeca tp (a,b)
where (Peca tp _) = (atNote2 "posInicial" t b a)
carroInicial :: Tabuleiro -> Posicao -> Int -> EstadoCarro
carroInicial t (a,b) i = C { posicaoC = posInicial t (a,b)
, direcaoC = 0
, velocidadeC = (0,0)
, checkPosicao = 0
, acelera = False
, trava = False
, viraD = False
, viraE = False
}
standard :: Terreno
rotaçao , angulo / segundo
aceleraçao , velocidade / segundo
abrandamento , velocidade / segundo
, velocidade / segundo
gravidade , velocidade / segundo
}
move :: Double -> EstadoJogo -> EstadoJogo
move n e = e { jogador = c' }
where p = (jogador e)
Mapa _ m = (mapaE e)
c' = moveCarro e n (terreno e) p
moveCarro :: EstadoJogo -> Double -> Terreno -> EstadoCarro -> EstadoCarro
moveCarro b n t c = andaCarro b n t $ rodaCarro n t c
rodaCarro :: Double -> Terreno -> EstadoCarro -> EstadoCarro
rodaCarro t r c | viraD c = c { direcaoC = direcaoC c - (t*delta_roda r)}
| viraE c = c { direcaoC = direcaoC c + (t*delta_roda r)}
| otherwise = c
andaCarro :: EstadoJogo -> Tempo -> Terreno -> EstadoCarro -> EstadoCarro
andaCarro e t r c = maybe (c { posicaoC = posInicial m (fst p0), velocidadeC = (0,0) }) id col
where v' = (velocidadeC c) .+. (t .*. ((accelVec r c) .+. (dragVec r c) .+. (driftVec r c) .+. (gravityVec r b c)))
Mapa p0 m = mapaE e
(i,j) = (ponto2Pos (posicaoC c))
b = atNote2 "andaCarro" m j i
c' = c { velocidadeC = v' }
col = colideEstado (mapaE e) t c'
(vv,va) = componentsToArrow (velocidadeC c)
colideEstado :: Mapa -> Tempo -> EstadoCarro -> Maybe EstadoCarro
colideEstado (Mapa _ tab) tempo e = do
let carro = Carro (posicaoC e) (direcaoC e) (velocidadeC e)
carro' <- T3.movimenta tab tempo carro
return $ e { posicaoC = posicao carro', direcaoC = direcao carro', velocidadeC = velocidade carro' }
accelVec :: Terreno -> EstadoCarro -> (Double,Double)
accelVec t c | acelera c && not (trava c) = arrowToComponents (delta_acel t,direcaoC c)
| trava c && not (acelera c) = arrowToComponents (delta_acel t,direcaoC c + 180)
| otherwise = (0,0)
dragVec :: Terreno -> EstadoCarro -> (Double,Double)
dragVec t c = arrowToComponents (delta_drag t*v,a + 180)
where (v,a) = componentsToArrow (velocidadeC c)
driftVec :: Terreno -> EstadoCarro -> (Double,Double)
driftVec t c = arrowToComponents (driftCoef,driftAngle)
where (vv,av) = componentsToArrow $ velocidadeC c
ad = direcaoC c
driftAngle = if (sin (radians (av-ad))) > 0
then ad-90 -- going right
else ad+90 -- going left
driftCoef = vv * delta_drift t * abs (sin (radians (av-ad)))
gravityVec :: Terreno -> Peca -> EstadoCarro -> (Double,Double)
gravityVec t (Peca (Rampa Sul) _) c = arrowToComponents (delta_gravity t, 90)
gravityVec t (Peca (Rampa Norte) _) c = arrowToComponents (delta_gravity t, 270)
gravityVec t (Peca (Rampa Oeste) _) c = arrowToComponents (delta_gravity t, 0)
gravityVec t (Peca (Rampa Este) _) c = arrowToComponents (delta_gravity t, 180)
gravityVec t _ c = (0,0)
centroPeca :: Tipo -> Posicao -> Ponto
centroPeca (Curva Norte) (a,b) = (toEnum a+0.7,toEnum b+0.7)
centroPeca (Curva Este) (a,b) = (toEnum a+0.3,toEnum b+0.7)
centroPeca (Curva Sul) (a,b) = (toEnum a+0.3,toEnum b+0.3)
centroPeca (Curva Oeste) (a,b) = (toEnum a+0.7,toEnum b+0.3)
centroPeca _ (a,b) = (toEnum a+0.5,toEnum b+0.5)
-- geometry
-- copiado do Gloss para Double
intersecta :: (Ponto,Ponto) -> (Ponto,Ponto) -> Maybe Ponto
intersecta (p1,p2) (p3,p4) | Just p0 <- intersectaL p1 p2 p3 p4
, t12 <- closestPosicaoOnL p1 p2 p0
, t23 <- closestPosicaoOnL p3 p4 p0
, t12 >= 0 && t12 <= 1
, t23 >= 0 && t23 <= 1
= Just p0
| otherwise
= Nothing
-- copiado do Gloss para Double
intersectaL :: Ponto -> Ponto -> Ponto -> Ponto -> Maybe Ponto
intersectaL (x1, y1) (x2, y2) (x3, y3) (x4, y4)
= let dx12 = x1 - x2
dx34 = x3 - x4
dy12 = y1 - y2
dy34 = y3 - y4
den = dx12 * dy34 - dy12 * dx34
in if den == 0
then Nothing
else let det12 = x1*y2 - y1*x2
det34 = x3*y4 - y3*x4
numx = det12 * dx34 - dx12 * det34
numy = det12 * dy34 - dy12 * det34
in Just (numx / den, numy / den)
-- copiado do Gloss para Double
closestPosicaoOnL :: Ponto -> Ponto -> Ponto -> Double
closestPosicaoOnL p1 p2 p3 = (p3 .-. p1) .$. (p2 .-. p1) / (p2 .-. p1) .$. (p2 .-. p1)
(.*.) :: Double -> (Double,Double) -> (Double,Double)
(.*.) x (a,b) = ((x*a),(x*b))
(.+.) :: (Double,Double) -> (Double,Double) -> (Double,Double)
(.+.) (x,y) (a,b) = ((x+a),(y+b))
(.-.) :: (Double,Double) -> (Double,Double) -> (Double,Double)
(.-.) (x,y) (a,b) = ((x-a),(y-b))
the dot product between two ( Double , Double)s
(.$.) :: (Double,Double) -> (Double,Double) -> Double
(.$.) (d1,a1) (d2,a2) = (x1*x2) + (y1*y2)
where (x1,y1) = (d1,a1)
(x2,y2) = (d2,a2)
radians th = th * (pi/180)
degrees th = th * (180/pi)
arrowToComponents :: (Double,Double) -> Ponto
arrowToComponents (v,th) = (getX v th,getY v th)
where getX v th = v * cos (radians (th))
getY v th = v * sin (radians (-th))
componentsToArrow :: Ponto -> (Double,Double)
componentsToArrow (x,0) | x >= 0 = (x,0)
componentsToArrow (x,0) | x < 0 = (x,180)
componentsToArrow (0,y) | y >= 0 = (y,-90)
componentsToArrow (0,y) | y < 0 = (y,90)
componentsToArrow (x,y) = (hyp,dir angle)
where
dir o = case (x >= 0, y >= 0) of
(True,True) -> -o
(True,False) -> o
(False,False) -> 180 - o
(False,True) -> 180 + o
hyp = sqrt ((abs x)^2 + (abs y)^2)
angle = degrees $ atan (abs y / abs x)
dist :: Ponto -> Ponto -> Double
dist (x1,y1) (x2,y2) = sqrt ((x2-x1)^2+(y2-y1)^2)
glossBloco :: EstadoJogo -> Peca -> Picture
glossBloco e (Peca Recta p) = Color (corAltura p) $ Polygon [(0,-tamBloco e),(0,0),(tamBloco e,0),(tamBloco e,-tamBloco e)]
glossBloco e ( Peca Recta p ) = getImage " recta " e --Color ( ) $ Polygon [ ( 0,-tamBloco e),(0,0),(tamBloco e,0),(tamBloco e,-tamBloco e ) ]
glossBloco e (Peca (Rampa Norte) p) = transitaBloco e (corAltura (p+1),corAltura p) False
glossBloco e (Peca (Rampa Oeste) p) = transitaBloco e (corAltura (p+1),corAltura p) True
glossBloco e (Peca (Rampa Sul) p) = transitaBloco e (corAltura p,corAltura (p+1)) False
glossBloco e (Peca (Rampa Este) p) = transitaBloco e (corAltura p,corAltura (p+1)) True
glossBloco e (Peca (Curva Oeste) p) = Pictures [getImage "lava" e,Color (corAltura p) $ Polygon [(0,0),(tamBloco e,0),(tamBloco e,-tamBloco e)]]
glossBloco e (Peca (Curva Sul) p) = Pictures [getImage "lava" e,Color (corAltura p) $ Polygon [(0,-tamBloco e),(tamBloco e,0),(0,0)]]
glossBloco e (Peca (Curva Norte) p) = Pictures [getImage "lava" e,Color (corAltura p) $ Polygon [(0,-tamBloco e),(tamBloco e,-tamBloco e),(tamBloco e,0)]]
glossBloco e (Peca (Curva Este) p) = Pictures [getImage "lava" e,Color (corAltura p) $ Polygon [(0,0),(0,-tamBloco e),(tamBloco e,-tamBloco e)]]
glossBloco e ( ( ) p ) = Rotate 270 $ getImage " curva " e --Color ( ) $ Polygon [ ( 0,0),(tamBloco e,0),(tamBloco e,-tamBloco e ) ]
glossBloco e ( ( ) p ) = Rotate 180 $ getImage " curva " e --Color ( ) $ Polygon [ ( 0,-tamBloco e),(tamBloco e,0),(0,0 ) ]
glossBloco e ( ( ) p ) = Rotate 0 $ getImage " curva " e --Color ( ) $ Polygon [ ( 0,-tamBloco e),(tamBloco e,-tamBloco e),(tamBloco e,0 ) ]
glossBloco e ( ( ) p ) = Rotate 90 $ getImage " curva " e --Color ( ) $ Polygon [ ( 0,0),(0,-tamBloco e),(tamBloco e,-tamBloco e ) ]
glossBloco e (Peca Lava _) = getImage "lava" e--Blank
numalturas = 5
corAltura :: Altura -> Color
corAltura a | a >= 0 = makeColor c c c 1
where c = (toEnum a) * 1 / numalturas
corAltura a | a < 0 = makeColor r 0 0 1
where r = abs (toEnum a) * 1 / numalturas
( 0.2*(toEnum a+2 ) ) ( 0.2*(toEnum a+2 ) ) ( 0.15*(toEnum a+2 ) ) 1
transitaBloco :: EstadoJogo -> (Color,Color) -> Bool -> Picture
transitaBloco e (c1,c2) i = Translate 0 gy $ Rotate g $ Pictures [a,b,c]
where a = Color c1 $ Polygon [(0,0),(tamBloco e/2,-tamBloco e),(tamBloco e,0)]
b = Color c2 $ Polygon [(0,0),(tamBloco e/2,-tamBloco e),(0,-tamBloco e)]
c = Color c2 $ Polygon [(tamBloco e,0),(tamBloco e/2,-tamBloco e),(tamBloco e,-tamBloco e)]
g = if i then -90 else 0
gy = if i then -tamBloco e else 0
glossMapa :: EstadoJogo -> (Float,Float) -> Tabuleiro -> [Picture]
glossMapa e (x,y) [] = []
glossMapa e (x,y) ([]:ls) = glossMapa e (0,y-tamBloco e) ls
glossMapa e ( x , y ) ( ( c : cs):ls ) = ( Translate ( x+(tamBloco e / 2 ) ) ( y-(tamBloco e / 2 ) ) $ glossBloco e c ) : glossMapa e ( x+tamBloco e , y ) ( cs : ls )
glossMapa e (x,y) ((c:cs):ls) = (Translate x y $ glossBloco e c) : glossMapa e (x+tamBloco e,y) (cs:ls)
glossCarro :: EstadoJogo -> Picture
glossCarro s = Translate (double2Float x*tamBloco s) (-double2Float y*tamBloco s) $ Scale 0.5 0.5 $ Rotate (-double2Float a) pic
where (x,y) = posicaoC (jogador s)
a = direcaoC (jogador s)
[ ( -6,5),(6,0),(-6,-5 ) ]
Mapa _ m = mapaE s
t = atNote2 "glossCarro" m (floor y) (floor x)
glossEvento :: Event -> EstadoJogo -> EstadoJogo
glossEvento e s = s { jogador = c' }
where c' = glossEventoCarro e (jogador s)
glossEventoCarro :: Event -> EstadoCarro -> EstadoCarro
glossEventoCarro (EventKey (SpecialKey KeyDown ) kst _ _) e = e { trava = kst == Down }
glossEventoCarro (EventKey (SpecialKey KeyUp ) kst _ _) e = e { acelera = kst == Down }
glossEventoCarro (EventKey (SpecialKey KeyLeft ) kst _ _) e = e { viraE = kst == Down }
glossEventoCarro (EventKey (SpecialKey KeyRight) kst _ _) e = e { viraD = kst == Down }
glossEventoCarro _ st = st
glossTempo :: Float -> EstadoJogo -> EstadoJogo
glossTempo t m = move (float2Double t) m
glossDesenha :: EstadoJogo -> Picture
glossDesenha e = Translate (-toEnum x*(tamBloco e)/2) (toEnum y*(tamBloco e)/2) $ Pictures (m'++meta:[p])
where (Mapa ((i,j),_) m) = mapaE e
m' = glossMapa e (0,0) m
p = glossCarro e
meta = Color green $ Line [((toEnum i*tamBloco e),-(toEnum j*tamBloco e))
,((toEnum i*tamBloco e),-(toEnum j*tamBloco e)-tamBloco e)]
x = (length (head m))
y = (length m)
getImage x e = fromJust $ List.lookup x (imagens e)
joga :: Int -> IO ()
joga i = do
screen@(Display screenx screeny) <- getDisplay
let back = greyN 0.5
x = toEnum (length (head m))
y = toEnum (length m)
tamanhoX::Float = (realToFrac screenx) / (realToFrac x)
tamanhoY::Float = (realToFrac screeny) / (realToFrac y)
tamanho = min tamanhoX tamanhoY
mapas = (map constroi caminhos_validos) ++ mapas_validos
ini@(Mapa p m) = atNote "joga" mapas i
imgs <- loadImages tamanho screen
let e = (estadoInicial ini tamanho imgs)
play screen back 20 e glossDesenha glossEvento glossTempo
main = catch (joga 0) $ \(e::SomeException) -> CW.trace (Text.pack $ displayException e) $ throw e
-- exemplos
caminhos_validos, caminhos_invalidos :: [Caminho]
caminhos_validos = [c_ex1,c_ex1',c_ex2,c_ex3,c_ex4,c_ex5,c_ex6]
caminhos_invalidos = [c_exOL,c_exOP,c_exDM,c_exHM,c_exR,c_exE]
mapas_validos, mapas_invalidos :: [Mapa]
mapas_validos = [m_ex1,m_ex2,m_ex3]
mapas_invalidos = [m_exPI,m_exLV,m_exEX,m_exLH,m_why]
-- bom
c_ex1 :: Caminho
c_ex1 = [Avanca,CurvaEsq,Avanca,CurvaDir,Avanca,CurvaDir,Desce,Avanca,CurvaEsq,CurvaDir
,CurvaEsq,CurvaDir,CurvaDir,CurvaEsq,CurvaDir,CurvaEsq,CurvaEsq,Avanca,Avanca
,Desce,CurvaDir,CurvaDir,Avanca,Avanca,Desce,CurvaEsq,CurvaDir,Sobe,CurvaDir
,CurvaEsq,CurvaDir,CurvaEsq,Avanca,CurvaDir,Sobe,Sobe,Avanca,Avanca,CurvaDir,Avanca]
c_ex1' :: Caminho
c_ex1' = [Avanca,CurvaEsq,Avanca,CurvaDir,Avanca,CurvaDir,Sobe,Avanca,CurvaEsq,CurvaDir
,CurvaEsq,CurvaDir,CurvaDir,CurvaEsq,CurvaDir,CurvaEsq,CurvaEsq,Avanca,Avanca
,Sobe,CurvaDir,CurvaDir,Avanca,Avanca,Sobe,CurvaEsq,CurvaDir,Desce,CurvaDir
,CurvaEsq,CurvaDir,CurvaEsq,Avanca,CurvaDir,Desce,Desce,Avanca,Avanca,CurvaDir,Avanca]
c_ex2 :: Caminho
c_ex2 = [Avanca,CurvaEsq,CurvaEsq,Avanca,CurvaEsq,CurvaEsq]
mapa sobreposto , altura /= da inicial
c_ex3 :: Caminho
c_ex3 = [Desce,CurvaEsq,CurvaEsq,Desce,CurvaEsq,CurvaEsq
,Avanca,CurvaEsq,CurvaEsq,Avanca,CurvaEsq,CurvaEsq]
caminho em 8 ,
c_ex4 :: Caminho
c_ex4 = [Avanca,CurvaDir,Avanca,Avanca,Avanca,CurvaEsq,Avanca,CurvaEsq,Avanca
,CurvaEsq,Avanca,Avanca,Avanca,CurvaDir,Avanca,CurvaDir]
-- caminho minimo válido
c_ex5 :: Caminho
c_ex5 = [CurvaDir,CurvaDir,CurvaDir,CurvaDir]
caminho minimo
c_ex6 :: Caminho
c_ex6 = [Avanca,CurvaDir,Avanca,CurvaDir,Avanca,CurvaDir,Avanca,CurvaDir]
-- mapa nao geravel por caminhos, lava extra a volta
m_ex1 = Mapa ((2,2),Este) [[Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava]
,[Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava]
,[Peca Lava altLava, Peca (Curva Norte) 2,Peca (Curva Este) 2, Peca Lava altLava]
,[Peca Lava altLava, Peca (Curva Oeste) 2,Peca (Curva Sul) 2, Peca Lava altLava]
,[Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava]
,[Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava]
]
mapa nao geravel por caminhos , altura /= inicial rampas
m_ex2 = Mapa ((2,1),Este) [[Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava]
,[Peca Lava altLava, Peca (Curva Norte) 5,Peca (Curva Este) 5, Peca Lava altLava]
,[Peca Lava altLava, Peca (Curva Oeste) 5,Peca (Curva Sul) 5, Peca Lava altLava]
,[Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava]
]
mapa minimo sem
m_ex3 = Mapa ((2,1),Este) [[Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava]
,[Peca Lava altLava, Peca (Curva Norte) 2,Peca Recta 2,Peca (Curva Este) 2, Peca Lava altLava]
,[Peca Lava altLava, Peca Recta 2,Peca Lava altLava,Peca Recta 2, Peca Lava altLava]
,[Peca Lava altLava, Peca (Curva Oeste) 2,Peca Recta 2,Peca (Curva Sul) 2, Peca Lava altLava]
,[Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava]
]
-- testes invalidos
-- aberto
c_exOP :: Caminho
c_exOP = [Avanca,Avanca,CurvaDir,Avanca,Avanca,CurvaEsq,Avanca,CurvaDir,CurvaDir
,Avanca,Avanca,Avanca,CurvaDir,CurvaEsq,Avanca,Avanca,CurvaDir,Avanca,Avanca,CurvaDir,Avanca]
fecha mas direcao errada
c_exDM :: Caminho
c_exDM = [Sobe,CurvaEsq,CurvaEsq,Sobe,CurvaEsq,CurvaEsq
,Avanca,CurvaEsq,CurvaEsq,Avanca,CurvaEsq,Avanca]
-- overlaps, aberto
c_exOL :: Caminho
c_exOL = [Avanca,Avanca,CurvaDir,Avanca,Avanca,CurvaEsq,Avanca,CurvaDir,CurvaDir
,Avanca,CurvaDir,Avanca,CurvaDir,CurvaEsq,Avanca,CurvaDir,Avanca,Avanca,CurvaDir,Avanca]
-- height mismatch
c_exHM :: Caminho
c_exHM = [Avanca,Avanca,CurvaDir,Avanca,Avanca,CurvaEsq,Avanca,CurvaDir,CurvaDir
,Avanca,Sobe,Avanca,CurvaDir,CurvaEsq,Avanca,CurvaDir,Avanca,Avanca,CurvaDir,Avanca]
-- cruza com alturas invalidas
c_exR :: Caminho
c_exR = [Avanca,CurvaDir,Avanca,Avanca,Avanca,CurvaEsq,Sobe,CurvaEsq,Avanca
,CurvaEsq,Avanca,Avanca,Avanca,CurvaDir,Desce,CurvaDir]
caminho vazio
c_exE :: Caminho
c_exE = []
-- posicao inicial invalida
m_exPI = Mapa ((0,0),Este) [[Peca (Curva Norte) 2,Peca (Curva Este) 2],[Peca (Curva Oeste) 2,Peca (Curva Sul) 2]]
-- mapa so lava
m_exLV = Mapa ((0,0),Este) $ theFloorIsLava (5,10)
-- mapa com caminho extra
m_exEX = Mapa ((1,0),Este) [[Peca (Curva Norte) 2,Peca Recta 2,Peca (Curva Este) 2],[Peca Recta 2,Peca Recta 2,Peca Recta 2],[Peca (Curva Oeste) 2,Peca Recta 2,Peca (Curva Sul) 2]]
-- altura da lava invalida
m_exLH = Mapa ((1,0),Este) [[Peca (Curva Norte) 2,Peca Recta 2,Peca (Curva Este) 2],[Peca Recta 2,Peca Lava 2,Peca Recta 2],[Peca (Curva Oeste) 2,Peca Recta 2,Peca (Curva Sul) 2]]
m_why = Mapa ((1,1),Este) [[Peca (Curva Norte) 2,Peca Recta 2,Peca (Curva Este) 2],[Peca Recta 2,Peca Recta 2,Peca Recta 2],[Peca (Curva Oeste) 2,Peca Recta 2,Peca (Curva Sul) 2]]
-- T1
constroi :: Caminho -> Mapa
constroi c = Mapa (partida c,dirInit) $ processa c dirInit altInit (partida c) (theFloorIsLava (dimensao c))
--------------
-- == T1: Solução
--------------
: : ( Int , Int ) - > Orientacao - > ( Int , Int )
( x , y ) Este = ( x+1,y )
( x , y ) Sul = ( x , y+1 )
( x , y ) = ( x-1,y )
( x , y ) Norte = ( x , y-1 )
--
: : Orientacao - > Bool - > Orientacao
--roda Este True = Sul
roda Sul True = Oeste
= Norte
--roda Norte True = Este
--roda d False = roda (roda (roda d True) True) True
theFloorIsLava :: Dimensao -> [[Peca]]
theFloorIsLava (n,m) = replicate m (replicate n (Peca Lava altLava))
processa :: Caminho -> Orientacao -> Altura -> (Int,Int) -> [[Peca]] -> [[Peca]]
processa [] _ _ _ m = m
processa (CurvaDir:c) d a (x,y) m = processa c d' a (mexe (x,y) d') m'
where m' = replace m (x,y) (blocoCurvo d d' a)
d' = roda d True
processa (CurvaEsq:c) d a (x,y) m = processa c d' a (mexe (x,y) d') m'
where m' = replace m (x,y) (blocoCurvo d d' a)
d' = roda d False
processa (Avanca:c) d a (x,y) m = processa c d a (mexe (x,y) d) m'
where m' = replace m (x,y) (Peca Recta a)
processa (s:c) d a (x,y) m = processa c d a' (mexe (x,y) d) m'
where m' = replace m (x,y) p'
a' = adapta s a
p' = (blocoRampa s d) (min a a')
replace :: [[a]] -> (Int,Int) -> a -> [[a]]
replace m (x,y) e = (take y m) ++ [l] ++ (drop (y+1) m)
where l = (take x (atNote "replace" m y)) ++ [e] ++ (drop (x+1) (atNote "replace" m y))
blocoCurvo :: Orientacao -> Orientacao -> Altura -> Peca
blocoCurvo Norte Este = Peca (Curva Norte)
blocoCurvo Este Sul = Peca (Curva Este)
blocoCurvo Sul Oeste = Peca (Curva Sul)
blocoCurvo Oeste Norte = Peca (Curva Oeste)
blocoCurvo m n = blocoCurvo (roda (roda n True) True) (roda (roda m True) True)
Este Norte = =
Sul Este = =
adapta :: Passo -> Altura -> Altura
adapta Sobe a = a+1
adapta Desce a = a-1
adapta _ a = a
blocoRampa :: Passo -> Orientacao -> (Altura -> Peca)
blocoRampa Sobe Norte = Peca (Rampa Norte)
blocoRampa Sobe Oeste = Peca (Rampa Oeste)
blocoRampa Sobe Sul = Peca (Rampa Sul)
blocoRampa Sobe Este = Peca (Rampa Este)
blocoRampa Desce d = blocoRampa Sobe (roda (roda d True) True)
atNote2 str xys x y = atNote str (atNote str xys x) y
| null |
https://raw.githubusercontent.com/haslab/HAAP/5acf9efaf0e5f6cba1c2482e51bda703f405a86f/examples/plab/svn/2017li1g183/src/CollisionSimulator.hs
|
haskell
|
going right
going left
geometry
copiado do Gloss para Double
copiado do Gloss para Double
copiado do Gloss para Double
Color ( ) $ Polygon [ ( 0,-tamBloco e),(0,0),(tamBloco e,0),(tamBloco e,-tamBloco e ) ]
Color ( ) $ Polygon [ ( 0,0),(tamBloco e,0),(tamBloco e,-tamBloco e ) ]
Color ( ) $ Polygon [ ( 0,-tamBloco e),(tamBloco e,0),(0,0 ) ]
Color ( ) $ Polygon [ ( 0,-tamBloco e),(tamBloco e,-tamBloco e),(tamBloco e,0 ) ]
Color ( ) $ Polygon [ ( 0,0),(0,-tamBloco e),(tamBloco e,-tamBloco e ) ]
Blank
exemplos
bom
caminho minimo válido
mapa nao geravel por caminhos, lava extra a volta
testes invalidos
aberto
overlaps, aberto
height mismatch
cruza com alturas invalidas
posicao inicial invalida
mapa so lava
mapa com caminho extra
altura da lava invalida
T1
------------
== T1: Solução
------------
roda Este True = Sul
roda Norte True = Este
roda d False = roda (roda (roda d True) True) True
|
# LANGUAGE ScopedTypeVariables #
module Main where
import JSImages
import LI11718
import qualified Tarefa3_2017li1g183 as T3
import System.Environment
import Data.Maybe
import Data.List as List
import qualified Data.Text as Text
import Text.Read
import Control.Monad
import Control.Exception
import GHC.Float
import qualified CodeWorld as CW
import Graphics.Gloss hiding ((.*.),(.+.),(.-.))
import Graphics . Gloss . Data . Picture
import Graphics . Gloss . Interface . Pure . Game
import Graphics . Gloss .
import Graphics . Gloss . Geometry . Line
import Safe
mexe :: (Int,Int) -> Orientacao -> (Int,Int)
mexe (x,y) Este = (x+1,y)
mexe (x,y) Sul = (x,y+1)
mexe (x,y) Oeste = (x-1,y)
mexe (x,y) Norte = (x,y-1)
roda :: Orientacao -> Bool -> Orientacao
roda Este True = Sul
roda Sul True = Oeste
roda Oeste True = Norte
roda Norte True = Este
roda d False = roda (roda (roda d True) True) True
ponto2Pos :: Ponto -> Posicao
ponto2Pos (x,y) = (i,j)
where x' = floor x
y' = floor y
i = x'
j = y'
data EstadoJogo = J { mapaE :: Mapa
, terreno :: Terreno
, jogador :: EstadoCarro
, tamBloco :: Float
, imagens :: [(String,Picture)]
}
data EstadoCarro = C { posicaoC :: (Double,Double)
, direcaoC :: Double
, velocidadeC :: (Double,Double)
, checkPosicao :: Int
, acelera :: Bool
, trava :: Bool
, viraD :: Bool
, viraE :: Bool
}
data Terreno = T { delta_roda :: Double
, delta_acel :: Double
, delta_drag :: Double
, delta_drift :: Double
, delta_gravity :: Double
}
estadoInicial :: Mapa -> Float -> [(String,Picture)] -> EstadoJogo
estadoInicial m@(Mapa p t) tam imgs = J { mapaE = m
, terreno = standard
, jogador = carroInicial t (fst p) 0
, tamBloco = tam
, imagens = imgs
}
posInicial :: Tabuleiro -> Posicao -> Ponto
posInicial t (a,b) = centroPeca tp (a,b)
where (Peca tp _) = (atNote2 "posInicial" t b a)
carroInicial :: Tabuleiro -> Posicao -> Int -> EstadoCarro
carroInicial t (a,b) i = C { posicaoC = posInicial t (a,b)
, direcaoC = 0
, velocidadeC = (0,0)
, checkPosicao = 0
, acelera = False
, trava = False
, viraD = False
, viraE = False
}
standard :: Terreno
rotaçao , angulo / segundo
aceleraçao , velocidade / segundo
abrandamento , velocidade / segundo
, velocidade / segundo
gravidade , velocidade / segundo
}
move :: Double -> EstadoJogo -> EstadoJogo
move n e = e { jogador = c' }
where p = (jogador e)
Mapa _ m = (mapaE e)
c' = moveCarro e n (terreno e) p
moveCarro :: EstadoJogo -> Double -> Terreno -> EstadoCarro -> EstadoCarro
moveCarro b n t c = andaCarro b n t $ rodaCarro n t c
rodaCarro :: Double -> Terreno -> EstadoCarro -> EstadoCarro
rodaCarro t r c | viraD c = c { direcaoC = direcaoC c - (t*delta_roda r)}
| viraE c = c { direcaoC = direcaoC c + (t*delta_roda r)}
| otherwise = c
andaCarro :: EstadoJogo -> Tempo -> Terreno -> EstadoCarro -> EstadoCarro
andaCarro e t r c = maybe (c { posicaoC = posInicial m (fst p0), velocidadeC = (0,0) }) id col
where v' = (velocidadeC c) .+. (t .*. ((accelVec r c) .+. (dragVec r c) .+. (driftVec r c) .+. (gravityVec r b c)))
Mapa p0 m = mapaE e
(i,j) = (ponto2Pos (posicaoC c))
b = atNote2 "andaCarro" m j i
c' = c { velocidadeC = v' }
col = colideEstado (mapaE e) t c'
(vv,va) = componentsToArrow (velocidadeC c)
colideEstado :: Mapa -> Tempo -> EstadoCarro -> Maybe EstadoCarro
colideEstado (Mapa _ tab) tempo e = do
let carro = Carro (posicaoC e) (direcaoC e) (velocidadeC e)
carro' <- T3.movimenta tab tempo carro
return $ e { posicaoC = posicao carro', direcaoC = direcao carro', velocidadeC = velocidade carro' }
accelVec :: Terreno -> EstadoCarro -> (Double,Double)
accelVec t c | acelera c && not (trava c) = arrowToComponents (delta_acel t,direcaoC c)
| trava c && not (acelera c) = arrowToComponents (delta_acel t,direcaoC c + 180)
| otherwise = (0,0)
dragVec :: Terreno -> EstadoCarro -> (Double,Double)
dragVec t c = arrowToComponents (delta_drag t*v,a + 180)
where (v,a) = componentsToArrow (velocidadeC c)
driftVec :: Terreno -> EstadoCarro -> (Double,Double)
driftVec t c = arrowToComponents (driftCoef,driftAngle)
where (vv,av) = componentsToArrow $ velocidadeC c
ad = direcaoC c
driftAngle = if (sin (radians (av-ad))) > 0
driftCoef = vv * delta_drift t * abs (sin (radians (av-ad)))
gravityVec :: Terreno -> Peca -> EstadoCarro -> (Double,Double)
gravityVec t (Peca (Rampa Sul) _) c = arrowToComponents (delta_gravity t, 90)
gravityVec t (Peca (Rampa Norte) _) c = arrowToComponents (delta_gravity t, 270)
gravityVec t (Peca (Rampa Oeste) _) c = arrowToComponents (delta_gravity t, 0)
gravityVec t (Peca (Rampa Este) _) c = arrowToComponents (delta_gravity t, 180)
gravityVec t _ c = (0,0)
centroPeca :: Tipo -> Posicao -> Ponto
centroPeca (Curva Norte) (a,b) = (toEnum a+0.7,toEnum b+0.7)
centroPeca (Curva Este) (a,b) = (toEnum a+0.3,toEnum b+0.7)
centroPeca (Curva Sul) (a,b) = (toEnum a+0.3,toEnum b+0.3)
centroPeca (Curva Oeste) (a,b) = (toEnum a+0.7,toEnum b+0.3)
centroPeca _ (a,b) = (toEnum a+0.5,toEnum b+0.5)
intersecta :: (Ponto,Ponto) -> (Ponto,Ponto) -> Maybe Ponto
intersecta (p1,p2) (p3,p4) | Just p0 <- intersectaL p1 p2 p3 p4
, t12 <- closestPosicaoOnL p1 p2 p0
, t23 <- closestPosicaoOnL p3 p4 p0
, t12 >= 0 && t12 <= 1
, t23 >= 0 && t23 <= 1
= Just p0
| otherwise
= Nothing
intersectaL :: Ponto -> Ponto -> Ponto -> Ponto -> Maybe Ponto
intersectaL (x1, y1) (x2, y2) (x3, y3) (x4, y4)
= let dx12 = x1 - x2
dx34 = x3 - x4
dy12 = y1 - y2
dy34 = y3 - y4
den = dx12 * dy34 - dy12 * dx34
in if den == 0
then Nothing
else let det12 = x1*y2 - y1*x2
det34 = x3*y4 - y3*x4
numx = det12 * dx34 - dx12 * det34
numy = det12 * dy34 - dy12 * det34
in Just (numx / den, numy / den)
closestPosicaoOnL :: Ponto -> Ponto -> Ponto -> Double
closestPosicaoOnL p1 p2 p3 = (p3 .-. p1) .$. (p2 .-. p1) / (p2 .-. p1) .$. (p2 .-. p1)
(.*.) :: Double -> (Double,Double) -> (Double,Double)
(.*.) x (a,b) = ((x*a),(x*b))
(.+.) :: (Double,Double) -> (Double,Double) -> (Double,Double)
(.+.) (x,y) (a,b) = ((x+a),(y+b))
(.-.) :: (Double,Double) -> (Double,Double) -> (Double,Double)
(.-.) (x,y) (a,b) = ((x-a),(y-b))
the dot product between two ( Double , Double)s
(.$.) :: (Double,Double) -> (Double,Double) -> Double
(.$.) (d1,a1) (d2,a2) = (x1*x2) + (y1*y2)
where (x1,y1) = (d1,a1)
(x2,y2) = (d2,a2)
radians th = th * (pi/180)
degrees th = th * (180/pi)
arrowToComponents :: (Double,Double) -> Ponto
arrowToComponents (v,th) = (getX v th,getY v th)
where getX v th = v * cos (radians (th))
getY v th = v * sin (radians (-th))
componentsToArrow :: Ponto -> (Double,Double)
componentsToArrow (x,0) | x >= 0 = (x,0)
componentsToArrow (x,0) | x < 0 = (x,180)
componentsToArrow (0,y) | y >= 0 = (y,-90)
componentsToArrow (0,y) | y < 0 = (y,90)
componentsToArrow (x,y) = (hyp,dir angle)
where
dir o = case (x >= 0, y >= 0) of
(True,True) -> -o
(True,False) -> o
(False,False) -> 180 - o
(False,True) -> 180 + o
hyp = sqrt ((abs x)^2 + (abs y)^2)
angle = degrees $ atan (abs y / abs x)
dist :: Ponto -> Ponto -> Double
dist (x1,y1) (x2,y2) = sqrt ((x2-x1)^2+(y2-y1)^2)
glossBloco :: EstadoJogo -> Peca -> Picture
glossBloco e (Peca Recta p) = Color (corAltura p) $ Polygon [(0,-tamBloco e),(0,0),(tamBloco e,0),(tamBloco e,-tamBloco e)]
glossBloco e (Peca (Rampa Norte) p) = transitaBloco e (corAltura (p+1),corAltura p) False
glossBloco e (Peca (Rampa Oeste) p) = transitaBloco e (corAltura (p+1),corAltura p) True
glossBloco e (Peca (Rampa Sul) p) = transitaBloco e (corAltura p,corAltura (p+1)) False
glossBloco e (Peca (Rampa Este) p) = transitaBloco e (corAltura p,corAltura (p+1)) True
glossBloco e (Peca (Curva Oeste) p) = Pictures [getImage "lava" e,Color (corAltura p) $ Polygon [(0,0),(tamBloco e,0),(tamBloco e,-tamBloco e)]]
glossBloco e (Peca (Curva Sul) p) = Pictures [getImage "lava" e,Color (corAltura p) $ Polygon [(0,-tamBloco e),(tamBloco e,0),(0,0)]]
glossBloco e (Peca (Curva Norte) p) = Pictures [getImage "lava" e,Color (corAltura p) $ Polygon [(0,-tamBloco e),(tamBloco e,-tamBloco e),(tamBloco e,0)]]
glossBloco e (Peca (Curva Este) p) = Pictures [getImage "lava" e,Color (corAltura p) $ Polygon [(0,0),(0,-tamBloco e),(tamBloco e,-tamBloco e)]]
numalturas = 5
corAltura :: Altura -> Color
corAltura a | a >= 0 = makeColor c c c 1
where c = (toEnum a) * 1 / numalturas
corAltura a | a < 0 = makeColor r 0 0 1
where r = abs (toEnum a) * 1 / numalturas
( 0.2*(toEnum a+2 ) ) ( 0.2*(toEnum a+2 ) ) ( 0.15*(toEnum a+2 ) ) 1
transitaBloco :: EstadoJogo -> (Color,Color) -> Bool -> Picture
transitaBloco e (c1,c2) i = Translate 0 gy $ Rotate g $ Pictures [a,b,c]
where a = Color c1 $ Polygon [(0,0),(tamBloco e/2,-tamBloco e),(tamBloco e,0)]
b = Color c2 $ Polygon [(0,0),(tamBloco e/2,-tamBloco e),(0,-tamBloco e)]
c = Color c2 $ Polygon [(tamBloco e,0),(tamBloco e/2,-tamBloco e),(tamBloco e,-tamBloco e)]
g = if i then -90 else 0
gy = if i then -tamBloco e else 0
glossMapa :: EstadoJogo -> (Float,Float) -> Tabuleiro -> [Picture]
glossMapa e (x,y) [] = []
glossMapa e (x,y) ([]:ls) = glossMapa e (0,y-tamBloco e) ls
glossMapa e ( x , y ) ( ( c : cs):ls ) = ( Translate ( x+(tamBloco e / 2 ) ) ( y-(tamBloco e / 2 ) ) $ glossBloco e c ) : glossMapa e ( x+tamBloco e , y ) ( cs : ls )
glossMapa e (x,y) ((c:cs):ls) = (Translate x y $ glossBloco e c) : glossMapa e (x+tamBloco e,y) (cs:ls)
glossCarro :: EstadoJogo -> Picture
glossCarro s = Translate (double2Float x*tamBloco s) (-double2Float y*tamBloco s) $ Scale 0.5 0.5 $ Rotate (-double2Float a) pic
where (x,y) = posicaoC (jogador s)
a = direcaoC (jogador s)
[ ( -6,5),(6,0),(-6,-5 ) ]
Mapa _ m = mapaE s
t = atNote2 "glossCarro" m (floor y) (floor x)
glossEvento :: Event -> EstadoJogo -> EstadoJogo
glossEvento e s = s { jogador = c' }
where c' = glossEventoCarro e (jogador s)
glossEventoCarro :: Event -> EstadoCarro -> EstadoCarro
glossEventoCarro (EventKey (SpecialKey KeyDown ) kst _ _) e = e { trava = kst == Down }
glossEventoCarro (EventKey (SpecialKey KeyUp ) kst _ _) e = e { acelera = kst == Down }
glossEventoCarro (EventKey (SpecialKey KeyLeft ) kst _ _) e = e { viraE = kst == Down }
glossEventoCarro (EventKey (SpecialKey KeyRight) kst _ _) e = e { viraD = kst == Down }
glossEventoCarro _ st = st
glossTempo :: Float -> EstadoJogo -> EstadoJogo
glossTempo t m = move (float2Double t) m
glossDesenha :: EstadoJogo -> Picture
glossDesenha e = Translate (-toEnum x*(tamBloco e)/2) (toEnum y*(tamBloco e)/2) $ Pictures (m'++meta:[p])
where (Mapa ((i,j),_) m) = mapaE e
m' = glossMapa e (0,0) m
p = glossCarro e
meta = Color green $ Line [((toEnum i*tamBloco e),-(toEnum j*tamBloco e))
,((toEnum i*tamBloco e),-(toEnum j*tamBloco e)-tamBloco e)]
x = (length (head m))
y = (length m)
getImage x e = fromJust $ List.lookup x (imagens e)
joga :: Int -> IO ()
joga i = do
screen@(Display screenx screeny) <- getDisplay
let back = greyN 0.5
x = toEnum (length (head m))
y = toEnum (length m)
tamanhoX::Float = (realToFrac screenx) / (realToFrac x)
tamanhoY::Float = (realToFrac screeny) / (realToFrac y)
tamanho = min tamanhoX tamanhoY
mapas = (map constroi caminhos_validos) ++ mapas_validos
ini@(Mapa p m) = atNote "joga" mapas i
imgs <- loadImages tamanho screen
let e = (estadoInicial ini tamanho imgs)
play screen back 20 e glossDesenha glossEvento glossTempo
main = catch (joga 0) $ \(e::SomeException) -> CW.trace (Text.pack $ displayException e) $ throw e
caminhos_validos, caminhos_invalidos :: [Caminho]
caminhos_validos = [c_ex1,c_ex1',c_ex2,c_ex3,c_ex4,c_ex5,c_ex6]
caminhos_invalidos = [c_exOL,c_exOP,c_exDM,c_exHM,c_exR,c_exE]
mapas_validos, mapas_invalidos :: [Mapa]
mapas_validos = [m_ex1,m_ex2,m_ex3]
mapas_invalidos = [m_exPI,m_exLV,m_exEX,m_exLH,m_why]
c_ex1 :: Caminho
c_ex1 = [Avanca,CurvaEsq,Avanca,CurvaDir,Avanca,CurvaDir,Desce,Avanca,CurvaEsq,CurvaDir
,CurvaEsq,CurvaDir,CurvaDir,CurvaEsq,CurvaDir,CurvaEsq,CurvaEsq,Avanca,Avanca
,Desce,CurvaDir,CurvaDir,Avanca,Avanca,Desce,CurvaEsq,CurvaDir,Sobe,CurvaDir
,CurvaEsq,CurvaDir,CurvaEsq,Avanca,CurvaDir,Sobe,Sobe,Avanca,Avanca,CurvaDir,Avanca]
c_ex1' :: Caminho
c_ex1' = [Avanca,CurvaEsq,Avanca,CurvaDir,Avanca,CurvaDir,Sobe,Avanca,CurvaEsq,CurvaDir
,CurvaEsq,CurvaDir,CurvaDir,CurvaEsq,CurvaDir,CurvaEsq,CurvaEsq,Avanca,Avanca
,Sobe,CurvaDir,CurvaDir,Avanca,Avanca,Sobe,CurvaEsq,CurvaDir,Desce,CurvaDir
,CurvaEsq,CurvaDir,CurvaEsq,Avanca,CurvaDir,Desce,Desce,Avanca,Avanca,CurvaDir,Avanca]
c_ex2 :: Caminho
c_ex2 = [Avanca,CurvaEsq,CurvaEsq,Avanca,CurvaEsq,CurvaEsq]
mapa sobreposto , altura /= da inicial
c_ex3 :: Caminho
c_ex3 = [Desce,CurvaEsq,CurvaEsq,Desce,CurvaEsq,CurvaEsq
,Avanca,CurvaEsq,CurvaEsq,Avanca,CurvaEsq,CurvaEsq]
caminho em 8 ,
c_ex4 :: Caminho
c_ex4 = [Avanca,CurvaDir,Avanca,Avanca,Avanca,CurvaEsq,Avanca,CurvaEsq,Avanca
,CurvaEsq,Avanca,Avanca,Avanca,CurvaDir,Avanca,CurvaDir]
c_ex5 :: Caminho
c_ex5 = [CurvaDir,CurvaDir,CurvaDir,CurvaDir]
caminho minimo
c_ex6 :: Caminho
c_ex6 = [Avanca,CurvaDir,Avanca,CurvaDir,Avanca,CurvaDir,Avanca,CurvaDir]
m_ex1 = Mapa ((2,2),Este) [[Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava]
,[Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava]
,[Peca Lava altLava, Peca (Curva Norte) 2,Peca (Curva Este) 2, Peca Lava altLava]
,[Peca Lava altLava, Peca (Curva Oeste) 2,Peca (Curva Sul) 2, Peca Lava altLava]
,[Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava]
,[Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava]
]
mapa nao geravel por caminhos , altura /= inicial rampas
m_ex2 = Mapa ((2,1),Este) [[Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava]
,[Peca Lava altLava, Peca (Curva Norte) 5,Peca (Curva Este) 5, Peca Lava altLava]
,[Peca Lava altLava, Peca (Curva Oeste) 5,Peca (Curva Sul) 5, Peca Lava altLava]
,[Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava]
]
mapa minimo sem
m_ex3 = Mapa ((2,1),Este) [[Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava]
,[Peca Lava altLava, Peca (Curva Norte) 2,Peca Recta 2,Peca (Curva Este) 2, Peca Lava altLava]
,[Peca Lava altLava, Peca Recta 2,Peca Lava altLava,Peca Recta 2, Peca Lava altLava]
,[Peca Lava altLava, Peca (Curva Oeste) 2,Peca Recta 2,Peca (Curva Sul) 2, Peca Lava altLava]
,[Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava]
]
c_exOP :: Caminho
c_exOP = [Avanca,Avanca,CurvaDir,Avanca,Avanca,CurvaEsq,Avanca,CurvaDir,CurvaDir
,Avanca,Avanca,Avanca,CurvaDir,CurvaEsq,Avanca,Avanca,CurvaDir,Avanca,Avanca,CurvaDir,Avanca]
fecha mas direcao errada
c_exDM :: Caminho
c_exDM = [Sobe,CurvaEsq,CurvaEsq,Sobe,CurvaEsq,CurvaEsq
,Avanca,CurvaEsq,CurvaEsq,Avanca,CurvaEsq,Avanca]
c_exOL :: Caminho
c_exOL = [Avanca,Avanca,CurvaDir,Avanca,Avanca,CurvaEsq,Avanca,CurvaDir,CurvaDir
,Avanca,CurvaDir,Avanca,CurvaDir,CurvaEsq,Avanca,CurvaDir,Avanca,Avanca,CurvaDir,Avanca]
c_exHM :: Caminho
c_exHM = [Avanca,Avanca,CurvaDir,Avanca,Avanca,CurvaEsq,Avanca,CurvaDir,CurvaDir
,Avanca,Sobe,Avanca,CurvaDir,CurvaEsq,Avanca,CurvaDir,Avanca,Avanca,CurvaDir,Avanca]
c_exR :: Caminho
c_exR = [Avanca,CurvaDir,Avanca,Avanca,Avanca,CurvaEsq,Sobe,CurvaEsq,Avanca
,CurvaEsq,Avanca,Avanca,Avanca,CurvaDir,Desce,CurvaDir]
caminho vazio
c_exE :: Caminho
c_exE = []
m_exPI = Mapa ((0,0),Este) [[Peca (Curva Norte) 2,Peca (Curva Este) 2],[Peca (Curva Oeste) 2,Peca (Curva Sul) 2]]
m_exLV = Mapa ((0,0),Este) $ theFloorIsLava (5,10)
m_exEX = Mapa ((1,0),Este) [[Peca (Curva Norte) 2,Peca Recta 2,Peca (Curva Este) 2],[Peca Recta 2,Peca Recta 2,Peca Recta 2],[Peca (Curva Oeste) 2,Peca Recta 2,Peca (Curva Sul) 2]]
m_exLH = Mapa ((1,0),Este) [[Peca (Curva Norte) 2,Peca Recta 2,Peca (Curva Este) 2],[Peca Recta 2,Peca Lava 2,Peca Recta 2],[Peca (Curva Oeste) 2,Peca Recta 2,Peca (Curva Sul) 2]]
m_why = Mapa ((1,1),Este) [[Peca (Curva Norte) 2,Peca Recta 2,Peca (Curva Este) 2],[Peca Recta 2,Peca Recta 2,Peca Recta 2],[Peca (Curva Oeste) 2,Peca Recta 2,Peca (Curva Sul) 2]]
constroi :: Caminho -> Mapa
constroi c = Mapa (partida c,dirInit) $ processa c dirInit altInit (partida c) (theFloorIsLava (dimensao c))
: : ( Int , Int ) - > Orientacao - > ( Int , Int )
( x , y ) Este = ( x+1,y )
( x , y ) Sul = ( x , y+1 )
( x , y ) = ( x-1,y )
( x , y ) Norte = ( x , y-1 )
: : Orientacao - > Bool - > Orientacao
roda Sul True = Oeste
= Norte
theFloorIsLava :: Dimensao -> [[Peca]]
theFloorIsLava (n,m) = replicate m (replicate n (Peca Lava altLava))
processa :: Caminho -> Orientacao -> Altura -> (Int,Int) -> [[Peca]] -> [[Peca]]
processa [] _ _ _ m = m
processa (CurvaDir:c) d a (x,y) m = processa c d' a (mexe (x,y) d') m'
where m' = replace m (x,y) (blocoCurvo d d' a)
d' = roda d True
processa (CurvaEsq:c) d a (x,y) m = processa c d' a (mexe (x,y) d') m'
where m' = replace m (x,y) (blocoCurvo d d' a)
d' = roda d False
processa (Avanca:c) d a (x,y) m = processa c d a (mexe (x,y) d) m'
where m' = replace m (x,y) (Peca Recta a)
processa (s:c) d a (x,y) m = processa c d a' (mexe (x,y) d) m'
where m' = replace m (x,y) p'
a' = adapta s a
p' = (blocoRampa s d) (min a a')
replace :: [[a]] -> (Int,Int) -> a -> [[a]]
replace m (x,y) e = (take y m) ++ [l] ++ (drop (y+1) m)
where l = (take x (atNote "replace" m y)) ++ [e] ++ (drop (x+1) (atNote "replace" m y))
blocoCurvo :: Orientacao -> Orientacao -> Altura -> Peca
blocoCurvo Norte Este = Peca (Curva Norte)
blocoCurvo Este Sul = Peca (Curva Este)
blocoCurvo Sul Oeste = Peca (Curva Sul)
blocoCurvo Oeste Norte = Peca (Curva Oeste)
blocoCurvo m n = blocoCurvo (roda (roda n True) True) (roda (roda m True) True)
Este Norte = =
Sul Este = =
adapta :: Passo -> Altura -> Altura
adapta Sobe a = a+1
adapta Desce a = a-1
adapta _ a = a
blocoRampa :: Passo -> Orientacao -> (Altura -> Peca)
blocoRampa Sobe Norte = Peca (Rampa Norte)
blocoRampa Sobe Oeste = Peca (Rampa Oeste)
blocoRampa Sobe Sul = Peca (Rampa Sul)
blocoRampa Sobe Este = Peca (Rampa Este)
blocoRampa Desce d = blocoRampa Sobe (roda (roda d True) True)
atNote2 str xys x y = atNote str (atNote str xys x) y
|
be11958a7ec1382c0b7f088a607dd15d330512e3e8567c29810293f70cb4a806
|
PapenfussLab/bioshake
|
Platypus.hs
|
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE TemplateHaskell #
{-# LANGUAGE ViewPatterns #-}
module Bioshake.Internal.Platypus where
import Bioshake
import Bioshake.TH
import Control.Monad
import Control.Monad.Trans (lift)
import Data.List
import Development.Shake
import Development.Shake.FilePath
import System.Posix.Files (createLink, rename)
data Call c = Call c deriving Show
buildPlatypus t _ a@(paths -> inputs) [out] = do
let bais = map ( <.> "bai" ) inputs
fai = getRef a <.> "fai"
lift . need $ fai:bais
run "platypus callVariants"
["--bamFiles=" ++ intercalate "," inputs]
["--refFile=" ++ getRef a]
["--output=" ++ out]
["--nCPU=" ++ show t]
$(makeSingleTypes ''Call [''IsVCF] [])
| null |
https://raw.githubusercontent.com/PapenfussLab/bioshake/afeb7219b171e242b6e9bb9e99e2f80c0a099aff/Bioshake/Internal/Platypus.hs
|
haskell
|
# LANGUAGE ViewPatterns #
|
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE TemplateHaskell #
module Bioshake.Internal.Platypus where
import Bioshake
import Bioshake.TH
import Control.Monad
import Control.Monad.Trans (lift)
import Data.List
import Development.Shake
import Development.Shake.FilePath
import System.Posix.Files (createLink, rename)
data Call c = Call c deriving Show
buildPlatypus t _ a@(paths -> inputs) [out] = do
let bais = map ( <.> "bai" ) inputs
fai = getRef a <.> "fai"
lift . need $ fai:bais
run "platypus callVariants"
["--bamFiles=" ++ intercalate "," inputs]
["--refFile=" ++ getRef a]
["--output=" ++ out]
["--nCPU=" ++ show t]
$(makeSingleTypes ''Call [''IsVCF] [])
|
053ccf26f67996cb741177c4edbb8065ee126f584941b4d1c3f469292695f4db
|
heyarne/airsonic-ui
|
subs.cljs
|
(ns airsonic-ui.subs
(:require [re-frame.core :refer [reg-sub subscribe]]
[airsonic-ui.api.helpers :as api]
[airsonic-ui.helpers :refer [kebabify]]
[clojure.string :as str]))
;;
;; app initialization
;;
;; TODO: Computation and extaction is mixed; this could be simpler
(defn- error-notifications [notifications]
(filter (fn [[_ n]]
(= :error (:level n))) notifications))
(defn- no-errors? [db]
(empty? (error-notifications (:notifications db))))
(defn- no-route? [db]
(empty? (:routes/current-route db)))
(defn- no-credentials? [db]
(and (not (empty? (:credentials db)))
(not (get-in db [:credentials :verified?]))))
(defn is-booting?
"The boot process starts with setting up routing and continues if we found
previous credentials and ends when we receive a response from the server."
[db _]
;; so either we don't have any credentials or they are not verified
(and (no-errors? db) (or (no-route? db) (no-credentials? db))))
(reg-sub ::is-booting? is-booting?)
(defn credentials [db _] (:credentials db))
(reg-sub ::credentials credentials)
;; ---
;; user info and roles
;; ---
(defn user-info
"Returns the response to getUser?username=$name; this isn't cached like the
other responses because it's not retrieved via :api/request"
[db _]
(:user db))
(reg-sub :user/info user-info)
(defn user-roles
"Takes only the roles out of a getUser response to make it easier to work with"
[user-info _]
(->>
(filter (fn [[k _]] (re-find #"Role$" (name k))) user-info)
(keep (fn [[role has-role?]]
(when has-role? (str/replace (name role) #"Role$" ""))))
(map kebabify)
(set)))
(reg-sub
:user/roles
:<- [:user/info]
user-roles)
(defn user-role
"Can be used to determine whether a user is allowed to do certain things"
[user-roles [_ role]]
(or (user-roles role) (user-roles :admin)))
(reg-sub
:user/role
:<- [:user/roles]
user-role)
;; ---
;; misc
;; ---
(defn cover-url
"Provides a convenient way for views to get cover images so they don't have
to build them themselves and can live a simple and happy life."
[credentials [_ song size]]
(api/cover-url credentials song size))
(reg-sub
::cover-url
:<- [::credentials]
cover-url)
;; user notifications
(defn notifications [db _] (:notifications db))
(reg-sub ::notifications notifications)
| null |
https://raw.githubusercontent.com/heyarne/airsonic-ui/7adb03d6e2ba0ff764796a57b7e87f62b242c9b7/src/cljs/airsonic_ui/subs.cljs
|
clojure
|
app initialization
TODO: Computation and extaction is mixed; this could be simpler
so either we don't have any credentials or they are not verified
---
user info and roles
---
this isn't cached like the
---
misc
---
user notifications
|
(ns airsonic-ui.subs
(:require [re-frame.core :refer [reg-sub subscribe]]
[airsonic-ui.api.helpers :as api]
[airsonic-ui.helpers :refer [kebabify]]
[clojure.string :as str]))
(defn- error-notifications [notifications]
(filter (fn [[_ n]]
(= :error (:level n))) notifications))
(defn- no-errors? [db]
(empty? (error-notifications (:notifications db))))
(defn- no-route? [db]
(empty? (:routes/current-route db)))
(defn- no-credentials? [db]
(and (not (empty? (:credentials db)))
(not (get-in db [:credentials :verified?]))))
(defn is-booting?
"The boot process starts with setting up routing and continues if we found
previous credentials and ends when we receive a response from the server."
[db _]
(and (no-errors? db) (or (no-route? db) (no-credentials? db))))
(reg-sub ::is-booting? is-booting?)
(defn credentials [db _] (:credentials db))
(reg-sub ::credentials credentials)
(defn user-info
other responses because it's not retrieved via :api/request"
[db _]
(:user db))
(reg-sub :user/info user-info)
(defn user-roles
"Takes only the roles out of a getUser response to make it easier to work with"
[user-info _]
(->>
(filter (fn [[k _]] (re-find #"Role$" (name k))) user-info)
(keep (fn [[role has-role?]]
(when has-role? (str/replace (name role) #"Role$" ""))))
(map kebabify)
(set)))
(reg-sub
:user/roles
:<- [:user/info]
user-roles)
(defn user-role
"Can be used to determine whether a user is allowed to do certain things"
[user-roles [_ role]]
(or (user-roles role) (user-roles :admin)))
(reg-sub
:user/role
:<- [:user/roles]
user-role)
(defn cover-url
"Provides a convenient way for views to get cover images so they don't have
to build them themselves and can live a simple and happy life."
[credentials [_ song size]]
(api/cover-url credentials song size))
(reg-sub
::cover-url
:<- [::credentials]
cover-url)
(defn notifications [db _] (:notifications db))
(reg-sub ::notifications notifications)
|
8541953f5967bbd5d7e7d8fe3f570c58ca665683e1c343ff54e016ac2bc35e17
|
dparis/gen-phzr
|
sprite_batch.cljs
|
(ns phzr.impl.accessors.sprite-batch)
(def sprite-batch-get-properties
{:alive "alive"
:alpha "alpha"
:angle "angle"
:cache-as-bitmap "cacheAsBitmap"
:camera-offset "cameraOffset"
:children "children"
:class-type "classType"
:cursor "cursor"
:cursor-index "cursorIndex"
:enable-body "enableBody"
:enable-body-debug "enableBodyDebug"
:exists "exists"
:filter-area "filterArea"
:filters "filters"
:fixed-to-camera "fixedToCamera"
:hash "hash"
:height "height"
:hit-area "hitArea"
:ignore-destroy "ignoreDestroy"
:length "length"
:mask "mask"
:name "name"
:on-destroy "onDestroy"
:parent "parent"
:pending-destroy "pendingDestroy"
:physics-body-type "physicsBodyType"
:physics-sort-direction "physicsSortDirection"
:physics-type "physicsType"
:pivot "pivot"
:position "position"
:renderable "renderable"
:rotation "rotation"
:scale "scale"
:stage "stage"
:total "total"
:transform-callback "transformCallback"
:transform-callback-context "transformCallbackContext"
:visible "visible"
:width "width"
:world-alpha "worldAlpha"
:world-position "worldPosition"
:world-rotation "worldRotation"
:world-scale "worldScale"
:world-visible "worldVisible"
:x "x"
:y "y"
:z "z"})
(def sprite-batch-set-properties
{:alive "alive"
:alpha "alpha"
:angle "angle"
:cache-as-bitmap "cacheAsBitmap"
:camera-offset "cameraOffset"
:class-type "classType"
:cursor "cursor"
:enable-body "enableBody"
:enable-body-debug "enableBodyDebug"
:exists "exists"
:filter-area "filterArea"
:filters "filters"
:fixed-to-camera "fixedToCamera"
:hash "hash"
:height "height"
:hit-area "hitArea"
:ignore-destroy "ignoreDestroy"
:mask "mask"
:name "name"
:on-destroy "onDestroy"
:pending-destroy "pendingDestroy"
:physics-body-type "physicsBodyType"
:physics-sort-direction "physicsSortDirection"
:pivot "pivot"
:position "position"
:renderable "renderable"
:rotation "rotation"
:scale "scale"
:transform-callback "transformCallback"
:transform-callback-context "transformCallbackContext"
:visible "visible"
:width "width"
:world-visible "worldVisible"
:x "x"
:y "y"
:z "z"})
| null |
https://raw.githubusercontent.com/dparis/gen-phzr/e4c7b272e225ac343718dc15fc84f5f0dce68023/out/impl/accessors/sprite_batch.cljs
|
clojure
|
(ns phzr.impl.accessors.sprite-batch)
(def sprite-batch-get-properties
{:alive "alive"
:alpha "alpha"
:angle "angle"
:cache-as-bitmap "cacheAsBitmap"
:camera-offset "cameraOffset"
:children "children"
:class-type "classType"
:cursor "cursor"
:cursor-index "cursorIndex"
:enable-body "enableBody"
:enable-body-debug "enableBodyDebug"
:exists "exists"
:filter-area "filterArea"
:filters "filters"
:fixed-to-camera "fixedToCamera"
:hash "hash"
:height "height"
:hit-area "hitArea"
:ignore-destroy "ignoreDestroy"
:length "length"
:mask "mask"
:name "name"
:on-destroy "onDestroy"
:parent "parent"
:pending-destroy "pendingDestroy"
:physics-body-type "physicsBodyType"
:physics-sort-direction "physicsSortDirection"
:physics-type "physicsType"
:pivot "pivot"
:position "position"
:renderable "renderable"
:rotation "rotation"
:scale "scale"
:stage "stage"
:total "total"
:transform-callback "transformCallback"
:transform-callback-context "transformCallbackContext"
:visible "visible"
:width "width"
:world-alpha "worldAlpha"
:world-position "worldPosition"
:world-rotation "worldRotation"
:world-scale "worldScale"
:world-visible "worldVisible"
:x "x"
:y "y"
:z "z"})
(def sprite-batch-set-properties
{:alive "alive"
:alpha "alpha"
:angle "angle"
:cache-as-bitmap "cacheAsBitmap"
:camera-offset "cameraOffset"
:class-type "classType"
:cursor "cursor"
:enable-body "enableBody"
:enable-body-debug "enableBodyDebug"
:exists "exists"
:filter-area "filterArea"
:filters "filters"
:fixed-to-camera "fixedToCamera"
:hash "hash"
:height "height"
:hit-area "hitArea"
:ignore-destroy "ignoreDestroy"
:mask "mask"
:name "name"
:on-destroy "onDestroy"
:pending-destroy "pendingDestroy"
:physics-body-type "physicsBodyType"
:physics-sort-direction "physicsSortDirection"
:pivot "pivot"
:position "position"
:renderable "renderable"
:rotation "rotation"
:scale "scale"
:transform-callback "transformCallback"
:transform-callback-context "transformCallbackContext"
:visible "visible"
:width "width"
:world-visible "worldVisible"
:x "x"
:y "y"
:z "z"})
|
|
7f0e1a6476072bf12e4ad59f6b90c40ee8ea76220480d670f98f24334a91f85b
|
RichiH/git-annex
|
TransferrerPool.hs
|
A pool of " git - annex transferkeys " processes
-
- Copyright 2013 < >
-
- Licensed under the GNU GPL version 3 or higher .
-
- Copyright 2013 Joey Hess <>
-
- Licensed under the GNU GPL version 3 or higher.
-}
module Assistant.TransferrerPool where
import Assistant.Common
import Assistant.Types.TransferrerPool
import Types.Transfer
import Utility.Batch
import qualified Command.TransferKeys as T
import Control.Concurrent.STM hiding (check)
import Control.Exception (throw)
import Control.Concurrent
Runs an action with a Transferrer from the pool .
-
- Only one Transferrer is left running in the pool at a time .
- So if this needed to start a new Transferrer , it 's stopped when done .
-
- Only one Transferrer is left running in the pool at a time.
- So if this needed to start a new Transferrer, it's stopped when done.
-}
withTransferrer :: FilePath -> BatchCommandMaker -> TransferrerPool -> (Transferrer -> IO a) -> IO a
withTransferrer program batchmaker pool a = do
(mi, leftinpool) <- atomically (popTransferrerPool pool)
i@(TransferrerPoolItem (Just t) check) <- case mi of
Nothing -> mkTransferrerPoolItem pool =<< mkTransferrer program batchmaker
Just i -> checkTransferrerPoolItem program batchmaker i
v <- tryNonAsync $ a t
if leftinpool == 0
then atomically $ pushTransferrerPool pool i
else do
void $ forkIO $ stopTransferrer t
atomically $ pushTransferrerPool pool $ TransferrerPoolItem Nothing check
either throw return v
Check if a Transferrer from the pool is still ok to be used .
- If not , stop it and start a new one .
- If not, stop it and start a new one. -}
checkTransferrerPoolItem :: FilePath -> BatchCommandMaker -> TransferrerPoolItem -> IO TransferrerPoolItem
checkTransferrerPoolItem program batchmaker i = case i of
TransferrerPoolItem (Just t) check -> ifM check
( return i
, do
stopTransferrer t
new check
)
TransferrerPoolItem Nothing check -> new check
where
new check = do
t <- mkTransferrer program batchmaker
return $ TransferrerPoolItem (Just t) check
Requests that a Transferrer perform a Transfer , and waits for it to
- finish .
- finish. -}
performTransfer :: Transferrer -> Transfer -> TransferInfo -> IO Bool
performTransfer transferrer t info = catchBoolIO $ do
T.sendRequest t info (transferrerWrite transferrer)
T.readResponse (transferrerRead transferrer)
Starts a new git - annex transferkeys process , setting up handles
- that will be used to communicate with it .
- that will be used to communicate with it. -}
mkTransferrer :: FilePath -> BatchCommandMaker -> IO Transferrer
mkTransferrer program batchmaker = do
{- It runs as a batch job. -}
let (program', params') = batchmaker (program, [Param "transferkeys"])
{- It's put into its own group so that the whole group can be
- killed to stop a transfer. -}
(Just writeh, Just readh, _, pid) <- createProcess
(proc program' $ toCommand params')
{ create_group = True
, std_in = CreatePipe
, std_out = CreatePipe
}
return $ Transferrer
{ transferrerRead = readh
, transferrerWrite = writeh
, transferrerHandle = pid
}
Checks if a Transferrer is still running . If not , makes a new one .
checkTransferrer :: FilePath -> BatchCommandMaker -> Transferrer -> IO Transferrer
checkTransferrer program batchmaker t =
maybe (return t) (const $ mkTransferrer program batchmaker)
=<< getProcessExitCode (transferrerHandle t)
{- Closing the fds will stop the transferrer. -}
stopTransferrer :: Transferrer -> IO ()
stopTransferrer t = do
hClose $ transferrerRead t
hClose $ transferrerWrite t
void $ waitForProcess $ transferrerHandle t
| null |
https://raw.githubusercontent.com/RichiH/git-annex/bbcad2b0af8cd9264d0cb86e6ca126ae626171f3/Assistant/TransferrerPool.hs
|
haskell
|
It runs as a batch job.
It's put into its own group so that the whole group can be
- killed to stop a transfer.
Closing the fds will stop the transferrer.
|
A pool of " git - annex transferkeys " processes
-
- Copyright 2013 < >
-
- Licensed under the GNU GPL version 3 or higher .
-
- Copyright 2013 Joey Hess <>
-
- Licensed under the GNU GPL version 3 or higher.
-}
module Assistant.TransferrerPool where
import Assistant.Common
import Assistant.Types.TransferrerPool
import Types.Transfer
import Utility.Batch
import qualified Command.TransferKeys as T
import Control.Concurrent.STM hiding (check)
import Control.Exception (throw)
import Control.Concurrent
Runs an action with a Transferrer from the pool .
-
- Only one Transferrer is left running in the pool at a time .
- So if this needed to start a new Transferrer , it 's stopped when done .
-
- Only one Transferrer is left running in the pool at a time.
- So if this needed to start a new Transferrer, it's stopped when done.
-}
withTransferrer :: FilePath -> BatchCommandMaker -> TransferrerPool -> (Transferrer -> IO a) -> IO a
withTransferrer program batchmaker pool a = do
(mi, leftinpool) <- atomically (popTransferrerPool pool)
i@(TransferrerPoolItem (Just t) check) <- case mi of
Nothing -> mkTransferrerPoolItem pool =<< mkTransferrer program batchmaker
Just i -> checkTransferrerPoolItem program batchmaker i
v <- tryNonAsync $ a t
if leftinpool == 0
then atomically $ pushTransferrerPool pool i
else do
void $ forkIO $ stopTransferrer t
atomically $ pushTransferrerPool pool $ TransferrerPoolItem Nothing check
either throw return v
Check if a Transferrer from the pool is still ok to be used .
- If not , stop it and start a new one .
- If not, stop it and start a new one. -}
checkTransferrerPoolItem :: FilePath -> BatchCommandMaker -> TransferrerPoolItem -> IO TransferrerPoolItem
checkTransferrerPoolItem program batchmaker i = case i of
TransferrerPoolItem (Just t) check -> ifM check
( return i
, do
stopTransferrer t
new check
)
TransferrerPoolItem Nothing check -> new check
where
new check = do
t <- mkTransferrer program batchmaker
return $ TransferrerPoolItem (Just t) check
Requests that a Transferrer perform a Transfer , and waits for it to
- finish .
- finish. -}
performTransfer :: Transferrer -> Transfer -> TransferInfo -> IO Bool
performTransfer transferrer t info = catchBoolIO $ do
T.sendRequest t info (transferrerWrite transferrer)
T.readResponse (transferrerRead transferrer)
Starts a new git - annex transferkeys process , setting up handles
- that will be used to communicate with it .
- that will be used to communicate with it. -}
mkTransferrer :: FilePath -> BatchCommandMaker -> IO Transferrer
mkTransferrer program batchmaker = do
let (program', params') = batchmaker (program, [Param "transferkeys"])
(Just writeh, Just readh, _, pid) <- createProcess
(proc program' $ toCommand params')
{ create_group = True
, std_in = CreatePipe
, std_out = CreatePipe
}
return $ Transferrer
{ transferrerRead = readh
, transferrerWrite = writeh
, transferrerHandle = pid
}
Checks if a Transferrer is still running . If not , makes a new one .
checkTransferrer :: FilePath -> BatchCommandMaker -> Transferrer -> IO Transferrer
checkTransferrer program batchmaker t =
maybe (return t) (const $ mkTransferrer program batchmaker)
=<< getProcessExitCode (transferrerHandle t)
stopTransferrer :: Transferrer -> IO ()
stopTransferrer t = do
hClose $ transferrerRead t
hClose $ transferrerWrite t
void $ waitForProcess $ transferrerHandle t
|
92054b3cec692f682b3caf99af117fb88cf79b81b1d1eee7094262e260e6982a
|
icicle-lang/icicle-ambiata
|
Fact.hs
|
{-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE DeriveFoldable #
# LANGUAGE DeriveFunctor #
# LANGUAGE DeriveGeneric #
{-# LANGUAGE DeriveTraversable #-}
# LANGUAGE LambdaCase #
# LANGUAGE NoImplicitPrelude #
{-# LANGUAGE OverloadedStrings #-}
module Icicle.Data.Fact (
Entity(..)
, Fact(..)
, Fact'(..)
, AsAt(..)
, Value(..)
, Struct(..)
, List(..)
, Encoding(..)
, StructField(..)
, StructFieldType(..)
, structFieldName
, prettyEncodingFlat
, prettyEncodingHang
) where
import Icicle.Common.NanEq
import Icicle.Data.Name
import Icicle.Data.Time
import Icicle.Internal.Pretty
import GHC.Generics
import P
newtype Entity =
Entity {
getEntity :: Text
} deriving (Eq, Ord, Show, Generic, NanEq)
data Fact =
Fact {
factEntity :: Entity
, factAttribute :: InputName
, factValue :: Value
} deriving (Eq, Show, Generic, NanEq)
data Fact' =
Fact' {
factEntity' :: Entity
, factAttribute' :: InputName
, factValue' :: Text
} deriving (Eq, Show, Generic, NanEq)
data AsAt a =
AsAt {
atFact :: a
, atTime :: Time
} deriving (Eq, Show, Generic, NanEq, Functor, Foldable, Traversable)
instance Pretty Entity where
pretty =
pretty . getEntity
--------------------------------------------------------------------------------
data Value =
StringValue Text
| IntValue Int
| DoubleValue Double
| BooleanValue Bool
| TimeValue Time
| StructValue Struct
| ListValue List
| PairValue Value Value
| MapValue [(Value, Value)]
| Tombstone
deriving (Eq, Show, Generic, NanEq)
instance Pretty Value where
pretty v = case v of
StringValue t -> text $ show t
IntValue i -> pretty i
DoubleValue d -> pretty d
BooleanValue b -> pretty b
TimeValue d -> pretty $ renderTime d
StructValue s -> pretty s
ListValue l -> pretty l
PairValue v1 v2 -> encloseSep lparen rparen comma
[pretty v1, pretty v2]
MapValue vs -> pretty vs
Tombstone -> text "tombstone"
--------------------------------------------------------------------------------
data Struct =
Struct [(Text, Value)]
deriving (Eq, Show, Generic, NanEq)
instance Pretty Struct where
pretty (Struct avs) = pretty avs
--------------------------------------------------------------------------------
data List =
List [Value]
deriving (Eq, Show, Generic, NanEq)
instance Pretty List where
pretty (List vs) = pretty vs
--------------------------------------------------------------------------------
data Encoding =
StringEncoding
| IntEncoding
| DoubleEncoding
| BooleanEncoding
| TimeEncoding
| StructEncoding [StructField]
| ListEncoding Encoding
deriving (Eq, Show, Generic, NanEq)
instance Pretty Encoding where
pretty =
prettyEncodingFlat
prettyEncoding :: ([Doc] -> Doc) -> Encoding -> Doc
prettyEncoding xsep = \case
StringEncoding ->
prettyConstructor "String"
IntEncoding ->
prettyConstructor "Int"
DoubleEncoding ->
prettyConstructor "Double"
BooleanEncoding ->
prettyConstructor "Bool"
TimeEncoding ->
prettyConstructor "Time"
StructEncoding ss ->
prettyStructType xsep . with ss $ \(StructField t nm enc) ->
case t of
Mandatory ->
(prettyKeyword "required" <+> annotate AnnBinding (pretty nm), prettyEncoding xsep enc)
Optional ->
(prettyKeyword "optional" <+> annotate AnnBinding (pretty nm), prettyEncoding xsep enc)
ListEncoding l ->
"[" <> prettyEncoding xsep l <> "]"
prettyEncodingFlat :: Encoding -> Doc
prettyEncodingFlat =
prettyEncoding hcat
prettyEncodingHang :: Encoding -> Doc
prettyEncodingHang =
prettyEncoding vsep
data StructField =
StructField StructFieldType Text Encoding
deriving (Eq, Show, Generic, NanEq)
instance Pretty StructField where
pretty (StructField Mandatory attr enc)
= prettyKeyword "required" <+> prettyTypedBest (pretty attr) (pretty enc)
pretty (StructField Optional attr enc)
= prettyKeyword "optional" <+> prettyTypedBest (pretty attr) (pretty enc)
structFieldName :: StructField -> Text
structFieldName (StructField _ attr _) =
attr
data StructFieldType =
Mandatory
| Optional
deriving (Eq, Ord, Show, Generic, NanEq)
| null |
https://raw.githubusercontent.com/icicle-lang/icicle-ambiata/9b9cc45a75f66603007e4db7e5f3ba908cae2df2/icicle-data/src/Icicle/Data/Fact.hs
|
haskell
|
# LANGUAGE DeriveAnyClass #
# LANGUAGE DeriveTraversable #
# LANGUAGE OverloadedStrings #
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
|
# LANGUAGE DeriveFoldable #
# LANGUAGE DeriveFunctor #
# LANGUAGE DeriveGeneric #
# LANGUAGE LambdaCase #
# LANGUAGE NoImplicitPrelude #
module Icicle.Data.Fact (
Entity(..)
, Fact(..)
, Fact'(..)
, AsAt(..)
, Value(..)
, Struct(..)
, List(..)
, Encoding(..)
, StructField(..)
, StructFieldType(..)
, structFieldName
, prettyEncodingFlat
, prettyEncodingHang
) where
import Icicle.Common.NanEq
import Icicle.Data.Name
import Icicle.Data.Time
import Icicle.Internal.Pretty
import GHC.Generics
import P
newtype Entity =
Entity {
getEntity :: Text
} deriving (Eq, Ord, Show, Generic, NanEq)
data Fact =
Fact {
factEntity :: Entity
, factAttribute :: InputName
, factValue :: Value
} deriving (Eq, Show, Generic, NanEq)
data Fact' =
Fact' {
factEntity' :: Entity
, factAttribute' :: InputName
, factValue' :: Text
} deriving (Eq, Show, Generic, NanEq)
data AsAt a =
AsAt {
atFact :: a
, atTime :: Time
} deriving (Eq, Show, Generic, NanEq, Functor, Foldable, Traversable)
instance Pretty Entity where
pretty =
pretty . getEntity
data Value =
StringValue Text
| IntValue Int
| DoubleValue Double
| BooleanValue Bool
| TimeValue Time
| StructValue Struct
| ListValue List
| PairValue Value Value
| MapValue [(Value, Value)]
| Tombstone
deriving (Eq, Show, Generic, NanEq)
instance Pretty Value where
pretty v = case v of
StringValue t -> text $ show t
IntValue i -> pretty i
DoubleValue d -> pretty d
BooleanValue b -> pretty b
TimeValue d -> pretty $ renderTime d
StructValue s -> pretty s
ListValue l -> pretty l
PairValue v1 v2 -> encloseSep lparen rparen comma
[pretty v1, pretty v2]
MapValue vs -> pretty vs
Tombstone -> text "tombstone"
data Struct =
Struct [(Text, Value)]
deriving (Eq, Show, Generic, NanEq)
instance Pretty Struct where
pretty (Struct avs) = pretty avs
data List =
List [Value]
deriving (Eq, Show, Generic, NanEq)
instance Pretty List where
pretty (List vs) = pretty vs
data Encoding =
StringEncoding
| IntEncoding
| DoubleEncoding
| BooleanEncoding
| TimeEncoding
| StructEncoding [StructField]
| ListEncoding Encoding
deriving (Eq, Show, Generic, NanEq)
instance Pretty Encoding where
pretty =
prettyEncodingFlat
prettyEncoding :: ([Doc] -> Doc) -> Encoding -> Doc
prettyEncoding xsep = \case
StringEncoding ->
prettyConstructor "String"
IntEncoding ->
prettyConstructor "Int"
DoubleEncoding ->
prettyConstructor "Double"
BooleanEncoding ->
prettyConstructor "Bool"
TimeEncoding ->
prettyConstructor "Time"
StructEncoding ss ->
prettyStructType xsep . with ss $ \(StructField t nm enc) ->
case t of
Mandatory ->
(prettyKeyword "required" <+> annotate AnnBinding (pretty nm), prettyEncoding xsep enc)
Optional ->
(prettyKeyword "optional" <+> annotate AnnBinding (pretty nm), prettyEncoding xsep enc)
ListEncoding l ->
"[" <> prettyEncoding xsep l <> "]"
prettyEncodingFlat :: Encoding -> Doc
prettyEncodingFlat =
prettyEncoding hcat
prettyEncodingHang :: Encoding -> Doc
prettyEncodingHang =
prettyEncoding vsep
data StructField =
StructField StructFieldType Text Encoding
deriving (Eq, Show, Generic, NanEq)
instance Pretty StructField where
pretty (StructField Mandatory attr enc)
= prettyKeyword "required" <+> prettyTypedBest (pretty attr) (pretty enc)
pretty (StructField Optional attr enc)
= prettyKeyword "optional" <+> prettyTypedBest (pretty attr) (pretty enc)
structFieldName :: StructField -> Text
structFieldName (StructField _ attr _) =
attr
data StructFieldType =
Mandatory
| Optional
deriving (Eq, Ord, Show, Generic, NanEq)
|
52afa6e3c8b5a42b649b5cef7fca6c81f667432a52ead325f92dc07eda456d4b
|
cedlemo/OCaml-GI-ctypes-bindings-generator
|
Gesture_rotate.mli
|
open Ctypes
type t
val t_typ : t typ
val create :
Widget.t ptr -> Gesture.t ptr
val get_angle_delta :
t -> float
| null |
https://raw.githubusercontent.com/cedlemo/OCaml-GI-ctypes-bindings-generator/21a4d449f9dbd6785131979b91aa76877bad2615/tools/Gtk3/Gesture_rotate.mli
|
ocaml
|
open Ctypes
type t
val t_typ : t typ
val create :
Widget.t ptr -> Gesture.t ptr
val get_angle_delta :
t -> float
|
|
e5c262ff9cc2750d1b651b8751500a665ab4997ed0e78d07f18b4a9b1a644d68
|
bootstrapworld/curr
|
backmatterlist-sols.rkt
|
; This file specifies the pages that make up the unnumbered backmatter
; for the workbook for the course containing this resources/workbook directory.
; This list should contain names of .pdf files that are in the pages directory.
; Each list element must include a .pdf extension.
; The backmatter will be generated from these pages in order
("Contracts-Sols.pdf"
)
| null |
https://raw.githubusercontent.com/bootstrapworld/curr/443015255eacc1c902a29978df0e3e8e8f3b9430/courses/algebra/resources/workbook/langs/es-mx/backmatterlist-sols.rkt
|
racket
|
This file specifies the pages that make up the unnumbered backmatter
for the workbook for the course containing this resources/workbook directory.
This list should contain names of .pdf files that are in the pages directory.
Each list element must include a .pdf extension.
The backmatter will be generated from these pages in order
|
("Contracts-Sols.pdf"
)
|
da3ef102f0db337184dbfffa148591ec56c774dd2bd9cb212256a06bee22d609
|
samrushing/irken-compiler
|
f_match5.scm
|
(define (eq? a b)
(%%cexp ('a 'a -> bool) "%0==%1" a b))
(define (error x)
(%%cexp (-> 'a) "goto Lreturn")
(%%cexp (-> 'a) "IRK_UNDEFINED")
)
;; without a default case this should raise a match error
(define flip
0 -> 1
1 -> 0
;; x -> (error "flipped out!")
)
(flip 0)
| null |
https://raw.githubusercontent.com/samrushing/irken-compiler/690da48852d55497f873738df54f14e8e135d006/tests/f_match5.scm
|
scheme
|
without a default case this should raise a match error
x -> (error "flipped out!")
|
(define (eq? a b)
(%%cexp ('a 'a -> bool) "%0==%1" a b))
(define (error x)
(%%cexp (-> 'a) "goto Lreturn")
(%%cexp (-> 'a) "IRK_UNDEFINED")
)
(define flip
0 -> 1
1 -> 0
)
(flip 0)
|
2d55a25e6d58b357bb110cf8f9a825a116ffd892355ca3962f77fc788401fe6d
|
PLTools/GT
|
test014.ml
|
@type a = A of b | C of GT.int GT.list with show
and b = B of c | D of GT.string with show
and c = E of a with show
class show_a_new ((_,fb,_) as prereq) =
object
inherit [_] @a[show] prereq as super
method! c_C () x y = "new " ^ super#c_C () x y
method! c_A () _ x = "new A " ^ (fb () x)
end
let show_a_new eta =
let (f,_,_) = fix_a (new show_a_new) (new show_b_t_stub) (new show_c_t_stub) in
f eta
let _ =
let x = A (B (E (C [1; 2; 3; 4]))) in
let y = B (E (A (D "3"))) in
Printf.printf "%s\n" (GT.transform(a) (new @a[show]) () x);
Printf.printf "%s\n" (GT.transform(b) (new @b[show]) () y);
Printf.printf "%s\n" (show_a_new () x);
| null |
https://raw.githubusercontent.com/PLTools/GT/62d1a424a3336f2317ba67e447a9ff09d179b583/regression/test014.ml
|
ocaml
|
@type a = A of b | C of GT.int GT.list with show
and b = B of c | D of GT.string with show
and c = E of a with show
class show_a_new ((_,fb,_) as prereq) =
object
inherit [_] @a[show] prereq as super
method! c_C () x y = "new " ^ super#c_C () x y
method! c_A () _ x = "new A " ^ (fb () x)
end
let show_a_new eta =
let (f,_,_) = fix_a (new show_a_new) (new show_b_t_stub) (new show_c_t_stub) in
f eta
let _ =
let x = A (B (E (C [1; 2; 3; 4]))) in
let y = B (E (A (D "3"))) in
Printf.printf "%s\n" (GT.transform(a) (new @a[show]) () x);
Printf.printf "%s\n" (GT.transform(b) (new @b[show]) () y);
Printf.printf "%s\n" (show_a_new () x);
|
|
1918d8b1fd932d31d1429f2024c5c32e6ce6c47fa036956a4eba1cb4e8bc2065
|
CorticalComputer/Flatland
|
actuator.erl
|
This source code and work is provided and developed by DXNN Research Group WWW.DXNNResearch . COM
%%
Copyright ( C ) 2012 by , DXNN Research Group ,
%All rights reserved.
%
This code is licensed under the version 3 of the GNU General Public License . Please see the LICENSE file that accompanies this project for the terms of use .
-module(actuator).
-compile(export_all).
-include("records.hrl").
gen(ExoSelf_PId,Node)->
spawn(Node,?MODULE,prep,[ExoSelf_PId]).
prep(ExoSelf_PId) ->
receive
{ExoSelf_PId,{Id,Cx_PId,Scape,ActuatorName,VL,Parameters,Fanin_PIds}} ->
loop(Id,ExoSelf_PId,Cx_PId,Scape,ActuatorName,VL,Parameters,{Fanin_PIds,Fanin_PIds},[])
end.
When is executed it spawns the actuator element and immediately begins to wait for its initial state message .
loop(Id,ExoSelf_PId,Cx_PId,Scape,AName,VL,Parameters,{[From_PId|Fanin_PIds],MFanin_PIds},Acc) ->
receive
{From_PId,forward,Input} ->
loop(Id,ExoSelf_PId,Cx_PId,Scape,AName,VL,Parameters,{Fanin_PIds,MFanin_PIds},lists:append(Input,Acc));
{ExoSelf_PId,terminate} ->
%io:format("Actuator:~p is terminating.~n",[self()])
ok
end;
loop(Id,ExoSelf_PId,Cx_PId,Scape,AName,VL,Parameters,{[],MFanin_PIds},Acc)->
{Fitness,EndFlag} = actuator:AName(ExoSelf_PId,lists:reverse(Acc),Parameters,VL,Scape),
Cx_PId ! {self(),sync,Fitness,EndFlag},
loop(Id,ExoSelf_PId,Cx_PId,Scape,AName,VL,Parameters,{MFanin_PIds,MFanin_PIds},[]).
The actuator process gathers the control signals from the neurons , appending them to the accumulator . The order in which the signals are accumulated into a vector is in the same order as the neuron ids are stored within NIds . Once all the signals have been gathered , the actuator sends cortex the sync signal , executes its function , and then again begins to wait for the neural signals from the output layer by reseting the Fanin_PIds from the second copy of the list .
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ACTUATORS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
two_wheels(ExoSelf_PId,Output,Parameters,VL,Scape)->
OVL = length(Output),
case OVL == VL of
true ->
{Fitness,HaltFlag}=gen_server:call(Scape,{actuator,ExoSelf_PId,two_wheels,Output});
false ->
{Fitness,HaltFlag}=gen_server:call(Scape,{actuator,ExoSelf_PId,two_wheels,lists:append(Output,lists:duplicate(OVL - VL,0))})
end.
| null |
https://raw.githubusercontent.com/CorticalComputer/Flatland/e96378ee0c71d4269e21baaa26c9c4e17d87bf6c/actuator.erl
|
erlang
|
All rights reserved.
io:format("Actuator:~p is terminating.~n",[self()])
ACTUATORS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
This source code and work is provided and developed by DXNN Research Group WWW.DXNNResearch . COM
Copyright ( C ) 2012 by , DXNN Research Group ,
This code is licensed under the version 3 of the GNU General Public License . Please see the LICENSE file that accompanies this project for the terms of use .
-module(actuator).
-compile(export_all).
-include("records.hrl").
gen(ExoSelf_PId,Node)->
spawn(Node,?MODULE,prep,[ExoSelf_PId]).
prep(ExoSelf_PId) ->
receive
{ExoSelf_PId,{Id,Cx_PId,Scape,ActuatorName,VL,Parameters,Fanin_PIds}} ->
loop(Id,ExoSelf_PId,Cx_PId,Scape,ActuatorName,VL,Parameters,{Fanin_PIds,Fanin_PIds},[])
end.
When is executed it spawns the actuator element and immediately begins to wait for its initial state message .
loop(Id,ExoSelf_PId,Cx_PId,Scape,AName,VL,Parameters,{[From_PId|Fanin_PIds],MFanin_PIds},Acc) ->
receive
{From_PId,forward,Input} ->
loop(Id,ExoSelf_PId,Cx_PId,Scape,AName,VL,Parameters,{Fanin_PIds,MFanin_PIds},lists:append(Input,Acc));
{ExoSelf_PId,terminate} ->
ok
end;
loop(Id,ExoSelf_PId,Cx_PId,Scape,AName,VL,Parameters,{[],MFanin_PIds},Acc)->
{Fitness,EndFlag} = actuator:AName(ExoSelf_PId,lists:reverse(Acc),Parameters,VL,Scape),
Cx_PId ! {self(),sync,Fitness,EndFlag},
loop(Id,ExoSelf_PId,Cx_PId,Scape,AName,VL,Parameters,{MFanin_PIds,MFanin_PIds},[]).
The actuator process gathers the control signals from the neurons , appending them to the accumulator . The order in which the signals are accumulated into a vector is in the same order as the neuron ids are stored within NIds . Once all the signals have been gathered , the actuator sends cortex the sync signal , executes its function , and then again begins to wait for the neural signals from the output layer by reseting the Fanin_PIds from the second copy of the list .
two_wheels(ExoSelf_PId,Output,Parameters,VL,Scape)->
OVL = length(Output),
case OVL == VL of
true ->
{Fitness,HaltFlag}=gen_server:call(Scape,{actuator,ExoSelf_PId,two_wheels,Output});
false ->
{Fitness,HaltFlag}=gen_server:call(Scape,{actuator,ExoSelf_PId,two_wheels,lists:append(Output,lists:duplicate(OVL - VL,0))})
end.
|
f03fc5a4f9e9f8ce5dea59208c84eee9060a740b75b8844d9c8a0a87bdf457db
|
kappelmann/engaging-large-scale-functional-programming
|
Exercise02.hs
|
module Exercise02 where
import Data.List(sort)
startupRevenue :: [Int] -> Int
startupRevenue ns= revenueRec l (sort ns)
where l = length ns
revenueRec _ [] = 0
revenueRec l (x:xs) = let next = revenueRec (l-1) xs in
if x*l > next then x*l else next
| null |
https://raw.githubusercontent.com/kappelmann/engaging-large-scale-functional-programming/8ed2c056fbd611f1531230648497cb5436d489e4/resources/contest/example_data/02/uploads/szczebrzeszynskadruzyna/Exercise02.hs
|
haskell
|
module Exercise02 where
import Data.List(sort)
startupRevenue :: [Int] -> Int
startupRevenue ns= revenueRec l (sort ns)
where l = length ns
revenueRec _ [] = 0
revenueRec l (x:xs) = let next = revenueRec (l-1) xs in
if x*l > next then x*l else next
|
|
7995935ce805c4bd1f08be7298cb9bce5d16088c270c381e80acc339d7538548
|
softlab-ntua/bencherl
|
trigger_beh.erl
|
2009 - 2011 Zuse Institute Berlin
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.
@author < >
%% @doc trigger behaviour
@version $ I d : trigger_beh.erl 2639 2012 - 01 - 03 15:00:45Z $
-module(trigger_beh).
-author('').
-vsn('$Id: trigger_beh.erl 2639 2012-01-03 15:00:45Z $').
% for behaviour
-ifndef(have_callback_support).
-export([behaviour_info/1]).
-endif.
-ifdef(have_callback_support).
-type state() :: term().
-callback init(BaseIntervalFun::trigger:interval_fun(), MinIntervalFun::trigger:interval_fun(),
MaxIntervalFun::trigger:interval_fun(), comm:message_tag()) -> state().
-callback now(state()) -> state().
-callback next(state(), IntervalTag::trigger:interval()) -> state().
-callback stop(state()) -> state().
-else.
-spec behaviour_info(atom()) -> [{atom(), arity()}] | undefined.
behaviour_info(callbacks) ->
[
{init, 4},
{now, 1},
{next, 2},
{stop, 1}
];
behaviour_info(_Other) ->
undefined.
-endif.
| null |
https://raw.githubusercontent.com/softlab-ntua/bencherl/317bdbf348def0b2f9ed32cb6621e21083b7e0ca/app/scalaris/src/trigger_beh.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.
@doc trigger behaviour
for behaviour
|
2009 - 2011 Zuse Institute Berlin
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
@author < >
@version $ I d : trigger_beh.erl 2639 2012 - 01 - 03 15:00:45Z $
-module(trigger_beh).
-author('').
-vsn('$Id: trigger_beh.erl 2639 2012-01-03 15:00:45Z $').
-ifndef(have_callback_support).
-export([behaviour_info/1]).
-endif.
-ifdef(have_callback_support).
-type state() :: term().
-callback init(BaseIntervalFun::trigger:interval_fun(), MinIntervalFun::trigger:interval_fun(),
MaxIntervalFun::trigger:interval_fun(), comm:message_tag()) -> state().
-callback now(state()) -> state().
-callback next(state(), IntervalTag::trigger:interval()) -> state().
-callback stop(state()) -> state().
-else.
-spec behaviour_info(atom()) -> [{atom(), arity()}] | undefined.
behaviour_info(callbacks) ->
[
{init, 4},
{now, 1},
{next, 2},
{stop, 1}
];
behaviour_info(_Other) ->
undefined.
-endif.
|
2b4fdde4d0e8184648bcefa7c121e58c76634739e77e02e724c47e1d41561aa7
|
dhess/hpio
|
Types.hs
|
|
Module : System . GPIO.Linux . . Types
Description : Types for Linux @sysfs@ GPIO
Copyright : ( c ) 2019 ,
License : : < >
Stability : experimental
Portability : non - portable
Types used by the various Linux @sysfs@ GPIO implementations .
Module : System.GPIO.Linux.Sysfs.Types
Description : Types for Linux @sysfs@ GPIO
Copyright : (c) 2019, Drew Hess
License : BSD3
Maintainer : Drew Hess <>
Stability : experimental
Portability : non-portable
Types used by the various Linux @sysfs@ GPIO implementations.
-}
{-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE DeriveGeneric #
{-# LANGUAGE Safe #-}
module System.GPIO.Linux.Sysfs.Types
( -- * @sysfs@-specific types
SysfsEdge(..)
, toPinInterruptMode
, toSysfsEdge
-- * Exceptions
, SysfsException(..)
) where
import Protolude
import Data.Data (Data)
import Test.QuickCheck (Arbitrary(..), arbitraryBoundedEnum, genericShrink)
import System.GPIO.Types
(Pin, PinInputMode, PinOutputMode, PinInterruptMode(..),
gpioExceptionToException, gpioExceptionFromException)
| Linux pins that can be configured to generate inputs have an
@edge@ attribute in the @sysfs@ GPIO filesystem . This type
-- represents the values that the @edge@ attribute can take.
--
Note that in Linux @sysfs@ GPIO , the signal edge referred to by the
@edge@ attribute refers to the signal 's /logical/ value ; i.e. , it
takes into account the value of the pin 's @active_low@ attribute .
--
-- This type is isomorphic to the 'PinInterruptMode' type. See
-- 'toPinInterruptMode' and 'toSysfsEdge'.
data SysfsEdge
= None
-- ^ Interrupts disabled
| Rising
-- ^ Interrupt on the (logical) signal's rising edge
| Falling
-- ^ Interrupt on the (logical) signal's falling edge
| Both
-- ^ Interrupt on any change to the signal level
deriving (Bounded,Enum,Eq,Data,Ord,Read,Show,Generic,Typeable)
instance Arbitrary SysfsEdge where
arbitrary = arbitraryBoundedEnum
shrink = genericShrink
| Convert a ' SysfsEdge ' value to its equivalent ' PinInterruptMode '
-- value.
--
-- >>> toPinInterruptMode None
-- Disabled
-- >>> toPinInterruptMode Rising
RisingEdge
-- >>> toPinInterruptMode Falling
FallingEdge
-- >>> toPinInterruptMode Both
-- Level
toPinInterruptMode :: SysfsEdge -> PinInterruptMode
toPinInterruptMode None = Disabled
toPinInterruptMode Rising = RisingEdge
toPinInterruptMode Falling = FallingEdge
toPinInterruptMode Both = Level
| Convert a ' PinInterruptMode ' value to its equivalent ' SysfsEdge '
-- value.
--
-- >>> toSysfsEdge Disabled
-- None
> > > toSysfsEdge RisingEdge
-- Rising
> > > toSysfsEdge FallingEdge
-- Falling
-- >>> toSysfsEdge Level
-- Both
toSysfsEdge :: PinInterruptMode -> SysfsEdge
toSysfsEdge Disabled = None
toSysfsEdge RisingEdge = Rising
toSysfsEdge FallingEdge = Falling
toSysfsEdge Level = Both
| Exceptions that can be thrown by @sysfs@ computations ( in
addition to standard ' System . IO.Error . IOError ' exceptions , of
-- course).
--
-- The @UnexpectedX@ values are truly exceptional and mean that, while
the @sysfs@ attribute for the given pin exists , the contents of the
-- attribute do not match any expected value for that attribute, which
probably means that the package is incompatible with the @sysfs@
-- filesystem due to a kernel-level change.
data SysfsException
= SysfsNotPresent
^ The @sysfs@ filesystem does not exist
| SysfsError
^ Something in the @sysfs@ filesystem does not behave as
expected ( could indicate a change in @sysfs@ behavior that the
-- package does not expect)
| SysfsPermissionDenied
^ The @sysfs@ operation is not permitted due to insufficient
-- permissions
| PermissionDenied Pin
-- ^ The operation on the specified pin is not permitted, either
-- due to insufficient permissions, or because the pin's attribute
-- cannot be modified (e.g., trying to write to a pin that's
-- configured for input)
| InvalidOperation Pin
-- ^ The operation is invalid for the specified pin, or in the
-- specified pin's current configuration
| AlreadyExported Pin
-- ^ The pin has already been exported
| InvalidPin Pin
-- ^ The specified pin does not exist
| NotExported Pin
^ The pin has been un - exported or does not exist
| UnsupportedInputMode PinInputMode Pin
-- ^ The pin does not support the specified input mode
| UnsupportedOutputMode PinOutputMode Pin
-- ^ The pin does not support the specified output mode
| NoDirectionAttribute Pin
-- ^ The pin does not have a @direction@ attribute
| NoEdgeAttribute Pin
-- ^ The pin does not have an @edge@ attribute
| UnexpectedDirection Pin Text
-- ^ An unexpected value was read from the pin's @direction@
-- attribute
| UnexpectedValue Pin Text
-- ^ An unexpected value was read from the pin's @value@
-- attribute
| UnexpectedEdge Pin Text
-- ^ An unexpected value was read from the pin's @edge@
-- attribute
| UnexpectedActiveLow Pin Text
^ An unexpected value was read from the pin 's @active_low@
-- attribute
| UnexpectedContents FilePath Text
-- ^ An unexpected value was read from the specified file
| InternalError Text
-- ^ An internal error has occurred in the interpreter, something
-- which should "never happen" and should be reported to the
-- package maintainer
deriving (Eq,Show,Typeable)
instance Exception SysfsException where
toException = gpioExceptionToException
fromException = gpioExceptionFromException
| null |
https://raw.githubusercontent.com/dhess/hpio/27004ef379db5d35e240222d6ba4cf91da9ec14d/src/System/GPIO/Linux/Sysfs/Types.hs
|
haskell
|
# LANGUAGE DeriveDataTypeable #
# LANGUAGE Safe #
* @sysfs@-specific types
* Exceptions
represents the values that the @edge@ attribute can take.
This type is isomorphic to the 'PinInterruptMode' type. See
'toPinInterruptMode' and 'toSysfsEdge'.
^ Interrupts disabled
^ Interrupt on the (logical) signal's rising edge
^ Interrupt on the (logical) signal's falling edge
^ Interrupt on any change to the signal level
value.
>>> toPinInterruptMode None
Disabled
>>> toPinInterruptMode Rising
>>> toPinInterruptMode Falling
>>> toPinInterruptMode Both
Level
value.
>>> toSysfsEdge Disabled
None
Rising
Falling
>>> toSysfsEdge Level
Both
course).
The @UnexpectedX@ values are truly exceptional and mean that, while
attribute do not match any expected value for that attribute, which
filesystem due to a kernel-level change.
package does not expect)
permissions
^ The operation on the specified pin is not permitted, either
due to insufficient permissions, or because the pin's attribute
cannot be modified (e.g., trying to write to a pin that's
configured for input)
^ The operation is invalid for the specified pin, or in the
specified pin's current configuration
^ The pin has already been exported
^ The specified pin does not exist
^ The pin does not support the specified input mode
^ The pin does not support the specified output mode
^ The pin does not have a @direction@ attribute
^ The pin does not have an @edge@ attribute
^ An unexpected value was read from the pin's @direction@
attribute
^ An unexpected value was read from the pin's @value@
attribute
^ An unexpected value was read from the pin's @edge@
attribute
attribute
^ An unexpected value was read from the specified file
^ An internal error has occurred in the interpreter, something
which should "never happen" and should be reported to the
package maintainer
|
|
Module : System . GPIO.Linux . . Types
Description : Types for Linux @sysfs@ GPIO
Copyright : ( c ) 2019 ,
License : : < >
Stability : experimental
Portability : non - portable
Types used by the various Linux @sysfs@ GPIO implementations .
Module : System.GPIO.Linux.Sysfs.Types
Description : Types for Linux @sysfs@ GPIO
Copyright : (c) 2019, Drew Hess
License : BSD3
Maintainer : Drew Hess <>
Stability : experimental
Portability : non-portable
Types used by the various Linux @sysfs@ GPIO implementations.
-}
# LANGUAGE DeriveGeneric #
module System.GPIO.Linux.Sysfs.Types
SysfsEdge(..)
, toPinInterruptMode
, toSysfsEdge
, SysfsException(..)
) where
import Protolude
import Data.Data (Data)
import Test.QuickCheck (Arbitrary(..), arbitraryBoundedEnum, genericShrink)
import System.GPIO.Types
(Pin, PinInputMode, PinOutputMode, PinInterruptMode(..),
gpioExceptionToException, gpioExceptionFromException)
| Linux pins that can be configured to generate inputs have an
@edge@ attribute in the @sysfs@ GPIO filesystem . This type
Note that in Linux @sysfs@ GPIO , the signal edge referred to by the
@edge@ attribute refers to the signal 's /logical/ value ; i.e. , it
takes into account the value of the pin 's @active_low@ attribute .
data SysfsEdge
= None
| Rising
| Falling
| Both
deriving (Bounded,Enum,Eq,Data,Ord,Read,Show,Generic,Typeable)
instance Arbitrary SysfsEdge where
arbitrary = arbitraryBoundedEnum
shrink = genericShrink
| Convert a ' SysfsEdge ' value to its equivalent ' PinInterruptMode '
RisingEdge
FallingEdge
toPinInterruptMode :: SysfsEdge -> PinInterruptMode
toPinInterruptMode None = Disabled
toPinInterruptMode Rising = RisingEdge
toPinInterruptMode Falling = FallingEdge
toPinInterruptMode Both = Level
| Convert a ' PinInterruptMode ' value to its equivalent ' SysfsEdge '
> > > toSysfsEdge RisingEdge
> > > toSysfsEdge FallingEdge
toSysfsEdge :: PinInterruptMode -> SysfsEdge
toSysfsEdge Disabled = None
toSysfsEdge RisingEdge = Rising
toSysfsEdge FallingEdge = Falling
toSysfsEdge Level = Both
| Exceptions that can be thrown by @sysfs@ computations ( in
addition to standard ' System . IO.Error . IOError ' exceptions , of
the @sysfs@ attribute for the given pin exists , the contents of the
probably means that the package is incompatible with the @sysfs@
data SysfsException
= SysfsNotPresent
^ The @sysfs@ filesystem does not exist
| SysfsError
^ Something in the @sysfs@ filesystem does not behave as
expected ( could indicate a change in @sysfs@ behavior that the
| SysfsPermissionDenied
^ The @sysfs@ operation is not permitted due to insufficient
| PermissionDenied Pin
| InvalidOperation Pin
| AlreadyExported Pin
| InvalidPin Pin
| NotExported Pin
^ The pin has been un - exported or does not exist
| UnsupportedInputMode PinInputMode Pin
| UnsupportedOutputMode PinOutputMode Pin
| NoDirectionAttribute Pin
| NoEdgeAttribute Pin
| UnexpectedDirection Pin Text
| UnexpectedValue Pin Text
| UnexpectedEdge Pin Text
| UnexpectedActiveLow Pin Text
^ An unexpected value was read from the pin 's @active_low@
| UnexpectedContents FilePath Text
| InternalError Text
deriving (Eq,Show,Typeable)
instance Exception SysfsException where
toException = gpioExceptionToException
fromException = gpioExceptionFromException
|
63e1cfb73b8323a329b568a020d8441b17862bc30d4bc207f4f4c2e3b8832e97
|
haskell/zlib
|
Utils.hs
|
# OPTIONS_GHC -fno - warn - orphans #
module Utils where
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString as BS
import Test.QuickCheck
-------------------
-- QuickCheck Utils
maxStrSize :: Double
maxStrSize = 500
-- convert a QC size parameter into one for generating long lists,
-- growing inverse exponentially up to maxStrSize
strSize :: Int -> Int
strSize n = floor (maxStrSize * (1 - 2 ** (-fromIntegral n/100)))
instance Arbitrary BL.ByteString where
arbitrary = sized $ \sz -> fmap BL.fromChunks $ listOf $ resize (sz `div` 2) arbitrary
shrink = map BL.pack . shrink . BL.unpack
instance Arbitrary BS.ByteString where
arbitrary = sized $ \sz -> resize (strSize sz) $ fmap BS.pack $ listOf $ arbitrary
shrink = map BS.pack . shrink . BS.unpack
| null |
https://raw.githubusercontent.com/haskell/zlib/7fe9bd49c28be0b5b523e7e78a91638ecea4d28d/test/Utils.hs
|
haskell
|
-----------------
QuickCheck Utils
convert a QC size parameter into one for generating long lists,
growing inverse exponentially up to maxStrSize
|
# OPTIONS_GHC -fno - warn - orphans #
module Utils where
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString as BS
import Test.QuickCheck
maxStrSize :: Double
maxStrSize = 500
strSize :: Int -> Int
strSize n = floor (maxStrSize * (1 - 2 ** (-fromIntegral n/100)))
instance Arbitrary BL.ByteString where
arbitrary = sized $ \sz -> fmap BL.fromChunks $ listOf $ resize (sz `div` 2) arbitrary
shrink = map BL.pack . shrink . BL.unpack
instance Arbitrary BS.ByteString where
arbitrary = sized $ \sz -> resize (strSize sz) $ fmap BS.pack $ listOf $ arbitrary
shrink = map BS.pack . shrink . BS.unpack
|
f1c103898b0ec00d49877e383663823132bd5a36e98942c64d5a28821092ee4e
|
pink-gorilla/notebook
|
completion.cljs
|
(ns demo.views.completion
(:require
[taoensso.timbre :refer-macros [info]]
[re-frame.core :as rf]
[pinkgorilla.notebook-ui.completion.component :refer [completion-component]]))
(rf/reg-event-db
:nrepl/completion-demo
(fn [db [_]]
(assoc-in db [:completion]
{:docstring "clojure.core/doseq\n([seq-exprs & body])\nMacro\n Repeatedly executes body (presumably for side-effects) with\n bindings and filtering as provided by \"for\". Does not retain\n the head of the sequence. Returns nil.\n"
:candidates [{:candidate "map", :type :function, :ns "clojure.core"}
{:candidate "max", :type :function, :ns "clojure.core"}
{:candidate "map?", :type :function, :ns "clojure.core"}
{:candidate "mapv", :type :function, :ns "clojure.core"}
{:candidate "mapcat", :type :function, :ns "clojure.core"}
{:candidate "max-key", :type :function, :ns "clojure.core"}
{:candidate "make-array", :type :function, :ns "clojure.core"}
{:candidate "map-entry?", :type :function, :ns "clojure.core"}
{:candidate "macroexpand", :type :function, :ns "clojure.core"}
{:candidate "map-indexed", :type :function, :ns "clojure.core"}
{:candidate "macroexpand-1", :type :function, :ns "clojure.core"}
{:candidate "make-hierarchy", :type :function, :ns "clojure.core"}]})))
(def docstring-res
"clojure.core/doseq\n([seq-exprs & body])\nMacro\n Repeatedly executes body (presumably for side-effects) with\n bindings and filtering as provided by \"for\". Does not retain\n the head of the sequence. Returns nil.\n")
(defn completion-demo []
(rf/dispatch [:nrepl/completion-demo])
[:div {:class "text-red-500 text-lg"}
[:p "For this to work nrepl needs to be connected!"]
[:input {:on-change (fn [s evt]
(println "evt:" evt)
( dispatch [: nrepl / completion (: text ) " user " " " ] )
)}]
[completion-component]])
| null |
https://raw.githubusercontent.com/pink-gorilla/notebook/26c33706987cdc8ef2a5447c0ae892eb359731a0/profiles/webly/src/demo/views/completion.cljs
|
clojure
|
(ns demo.views.completion
(:require
[taoensso.timbre :refer-macros [info]]
[re-frame.core :as rf]
[pinkgorilla.notebook-ui.completion.component :refer [completion-component]]))
(rf/reg-event-db
:nrepl/completion-demo
(fn [db [_]]
(assoc-in db [:completion]
{:docstring "clojure.core/doseq\n([seq-exprs & body])\nMacro\n Repeatedly executes body (presumably for side-effects) with\n bindings and filtering as provided by \"for\". Does not retain\n the head of the sequence. Returns nil.\n"
:candidates [{:candidate "map", :type :function, :ns "clojure.core"}
{:candidate "max", :type :function, :ns "clojure.core"}
{:candidate "map?", :type :function, :ns "clojure.core"}
{:candidate "mapv", :type :function, :ns "clojure.core"}
{:candidate "mapcat", :type :function, :ns "clojure.core"}
{:candidate "max-key", :type :function, :ns "clojure.core"}
{:candidate "make-array", :type :function, :ns "clojure.core"}
{:candidate "map-entry?", :type :function, :ns "clojure.core"}
{:candidate "macroexpand", :type :function, :ns "clojure.core"}
{:candidate "map-indexed", :type :function, :ns "clojure.core"}
{:candidate "macroexpand-1", :type :function, :ns "clojure.core"}
{:candidate "make-hierarchy", :type :function, :ns "clojure.core"}]})))
(def docstring-res
"clojure.core/doseq\n([seq-exprs & body])\nMacro\n Repeatedly executes body (presumably for side-effects) with\n bindings and filtering as provided by \"for\". Does not retain\n the head of the sequence. Returns nil.\n")
(defn completion-demo []
(rf/dispatch [:nrepl/completion-demo])
[:div {:class "text-red-500 text-lg"}
[:p "For this to work nrepl needs to be connected!"]
[:input {:on-change (fn [s evt]
(println "evt:" evt)
( dispatch [: nrepl / completion (: text ) " user " " " ] )
)}]
[completion-component]])
|
|
b2470cb0140cfbcd2d6260a223b0d840815303928042628ef455ba229c2466e6
|
ds-wizard/engine-backend
|
DocumentCreateDTO.hs
|
module Wizard.Api.Resource.Document.DocumentCreateDTO where
import qualified Data.UUID as U
import GHC.Generics
data DocumentCreateDTO = DocumentCreateDTO
{ name :: String
, questionnaireUuid :: U.UUID
, questionnaireEventUuid :: Maybe U.UUID
, documentTemplateId :: String
, formatUuid :: U.UUID
}
deriving (Show, Eq, Generic)
| null |
https://raw.githubusercontent.com/ds-wizard/engine-backend/d392b751192a646064305d3534c57becaa229f28/engine-wizard/src/Wizard/Api/Resource/Document/DocumentCreateDTO.hs
|
haskell
|
module Wizard.Api.Resource.Document.DocumentCreateDTO where
import qualified Data.UUID as U
import GHC.Generics
data DocumentCreateDTO = DocumentCreateDTO
{ name :: String
, questionnaireUuid :: U.UUID
, questionnaireEventUuid :: Maybe U.UUID
, documentTemplateId :: String
, formatUuid :: U.UUID
}
deriving (Show, Eq, Generic)
|
|
757f222a8372438aeb741e72b586da00184b5ab702c2342abc2be5d76c239b8a
|
facebook/pyre-check
|
functionDefinition.ml
|
* 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.
*)
(* TODO(T132410158) Add a module-level doc comment. *)
open Core
open Ast
open Statement
module Sibling = struct
module Kind = struct
type t =
| Overload
| PropertySetter
[@@deriving sexp, compare]
end
type t = {
kind: Kind.t;
body: Define.t Node.t;
}
[@@deriving sexp, compare]
end
type t = {
qualifier: Reference.t;
body: Define.t Node.t option;
siblings: Sibling.t list;
}
[@@deriving sexp, compare]
let all_bodies { body; siblings; _ } =
let sibling_bodies = List.map siblings ~f:(fun { Sibling.body; _ } -> body) in
match body with
| None -> sibling_bodies
| Some body -> body :: sibling_bodies
let collect_typecheck_units { Source.statements; _ } =
TODO ( T57944324 ): Support checking classes that are nested inside function bodies
let rec collect_from_statement ~ignore_class sofar { Node.value; location } =
match value with
| Statement.Class ({ Class.name; body; _ } as class_) ->
if ignore_class then (
Log.debug
"Dropping the body of class %a as it is nested inside a function"
Reference.pp
name;
sofar)
else
let sofar =
let define = Class.toplevel_define class_ |> Node.create ~location in
define :: sofar
in
List.fold body ~init:sofar ~f:(collect_from_statement ~ignore_class)
| Define ({ Define.body; _ } as define) ->
let sofar = { Node.location; Node.value = define } :: sofar in
List.fold body ~init:sofar ~f:(collect_from_statement ~ignore_class:true)
| Match { Match.cases; _ } ->
let from_case sofar { Match.Case.body; _ } =
List.fold body ~init:sofar ~f:(collect_from_statement ~ignore_class)
in
List.fold cases ~init:sofar ~f:from_case
| For { For.body; orelse; _ }
| If { If.body; orelse; _ }
| While { While.body; orelse; _ } ->
let sofar = List.fold body ~init:sofar ~f:(collect_from_statement ~ignore_class) in
List.fold orelse ~init:sofar ~f:(collect_from_statement ~ignore_class)
| Try { Try.body; handlers; orelse; finally } ->
let sofar = List.fold body ~init:sofar ~f:(collect_from_statement ~ignore_class) in
let sofar =
List.fold handlers ~init:sofar ~f:(fun sofar { Try.Handler.body; _ } ->
List.fold body ~init:sofar ~f:(collect_from_statement ~ignore_class))
in
let sofar = List.fold orelse ~init:sofar ~f:(collect_from_statement ~ignore_class) in
List.fold finally ~init:sofar ~f:(collect_from_statement ~ignore_class)
| With { With.body; _ } -> List.fold body ~init:sofar ~f:(collect_from_statement ~ignore_class)
| Assign _
| Assert _
| Break
| Continue
| Delete _
| Expression _
| Global _
| Import _
| Nonlocal _
| Pass
| Raise _
| Return _ ->
sofar
in
let drop_nested_body { Node.value = { Define.body; _ } as define; location } =
let new_define =
let rec drop_nested_body_in_statement = function
| Statement.Class definition -> Statement.Class { definition with body = [] }
| Define { Define.signature; _ } ->
Statement.Define { Define.signature; captures = []; unbound_names = []; body = [] }
| For ({ For.body; orelse; _ } as for_statement) ->
Statement.For
{
for_statement with
body = drop_nested_body_in_statements body;
orelse = drop_nested_body_in_statements orelse;
}
| Match ({ Match.cases; _ } as match_statement) ->
Statement.Match
{
match_statement with
cases =
List.map cases ~f:(fun ({ Match.Case.body; _ } as case) ->
{ case with Match.Case.body = drop_nested_body_in_statements body });
}
| If ({ If.body; orelse; _ } as if_statement) ->
Statement.If
{
if_statement with
body = drop_nested_body_in_statements body;
orelse = drop_nested_body_in_statements orelse;
}
| While ({ While.body; orelse; _ } as while_statement) ->
Statement.While
{
while_statement with
body = drop_nested_body_in_statements body;
orelse = drop_nested_body_in_statements orelse;
}
| Try { Try.body; handlers; orelse; finally } ->
Statement.Try
{
Try.body = drop_nested_body_in_statements body;
handlers =
List.map handlers ~f:(fun ({ Try.Handler.body; _ } as handler) ->
{ handler with Try.Handler.body = drop_nested_body_in_statements body });
orelse = drop_nested_body_in_statements orelse;
finally = drop_nested_body_in_statements finally;
}
| With ({ With.body; _ } as with_statement) ->
Statement.With { with_statement with body = drop_nested_body_in_statements body }
| _ as statement -> statement
and drop_nested_body_in_statements statements =
List.map statements ~f:(Node.map ~f:drop_nested_body_in_statement)
in
{ define with Define.body = drop_nested_body_in_statements body }
in
{ Node.value = new_define; location }
in
List.fold statements ~init:[] ~f:(collect_from_statement ~ignore_class:false)
|> List.map ~f:drop_nested_body
let collect_defines ({ Source.module_path = { ModulePath.qualifier; _ }; _ } as source) =
let all_defines = collect_typecheck_units source in
let table = Reference.Table.create () in
let process_define ({ Node.value = define; _ } as define_node) =
let define_name = Define.name define in
let sibling =
let open Sibling in
if Define.is_overloaded_function define then
Some { kind = Kind.Overload; body = define_node }
else if Define.is_property_setter define then
Some { kind = Kind.PropertySetter; body = define_node }
else
None
in
let update = function
| None -> (
match sibling with
| Some sibling -> None, [sibling]
| None -> Some define_node, [])
| Some (body, siblings) -> (
match sibling with
| Some sibling -> body, sibling :: siblings
| None ->
if Option.is_some body then (
Log.debug
"Dropping the body of function %a as it has duplicated name with other functions"
Reference.pp
define_name;
(* Last definition wins -- collector returns functions in reverse order *)
body, siblings)
else
Some define_node, siblings)
in
Hashtbl.update table define_name ~f:update
in
let collect_definition ~key ~data:(body, overloads) collected =
let siblings = List.sort overloads ~compare:Sibling.compare in
(key, { qualifier; body; siblings }) :: collected
in
let all_defines =
(* Take into account module toplevel *)
Source.top_level_define_node source :: all_defines
in
List.iter all_defines ~f:process_define;
Hashtbl.fold table ~init:[] ~f:collect_definition
| null |
https://raw.githubusercontent.com/facebook/pyre-check/98b8362ffa5c715c708676c1a37a52647ce79fe0/source/analysis/functionDefinition.ml
|
ocaml
|
TODO(T132410158) Add a module-level doc comment.
Last definition wins -- collector returns functions in reverse order
Take into account module toplevel
|
* 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.
*)
open Core
open Ast
open Statement
module Sibling = struct
module Kind = struct
type t =
| Overload
| PropertySetter
[@@deriving sexp, compare]
end
type t = {
kind: Kind.t;
body: Define.t Node.t;
}
[@@deriving sexp, compare]
end
type t = {
qualifier: Reference.t;
body: Define.t Node.t option;
siblings: Sibling.t list;
}
[@@deriving sexp, compare]
let all_bodies { body; siblings; _ } =
let sibling_bodies = List.map siblings ~f:(fun { Sibling.body; _ } -> body) in
match body with
| None -> sibling_bodies
| Some body -> body :: sibling_bodies
let collect_typecheck_units { Source.statements; _ } =
TODO ( T57944324 ): Support checking classes that are nested inside function bodies
let rec collect_from_statement ~ignore_class sofar { Node.value; location } =
match value with
| Statement.Class ({ Class.name; body; _ } as class_) ->
if ignore_class then (
Log.debug
"Dropping the body of class %a as it is nested inside a function"
Reference.pp
name;
sofar)
else
let sofar =
let define = Class.toplevel_define class_ |> Node.create ~location in
define :: sofar
in
List.fold body ~init:sofar ~f:(collect_from_statement ~ignore_class)
| Define ({ Define.body; _ } as define) ->
let sofar = { Node.location; Node.value = define } :: sofar in
List.fold body ~init:sofar ~f:(collect_from_statement ~ignore_class:true)
| Match { Match.cases; _ } ->
let from_case sofar { Match.Case.body; _ } =
List.fold body ~init:sofar ~f:(collect_from_statement ~ignore_class)
in
List.fold cases ~init:sofar ~f:from_case
| For { For.body; orelse; _ }
| If { If.body; orelse; _ }
| While { While.body; orelse; _ } ->
let sofar = List.fold body ~init:sofar ~f:(collect_from_statement ~ignore_class) in
List.fold orelse ~init:sofar ~f:(collect_from_statement ~ignore_class)
| Try { Try.body; handlers; orelse; finally } ->
let sofar = List.fold body ~init:sofar ~f:(collect_from_statement ~ignore_class) in
let sofar =
List.fold handlers ~init:sofar ~f:(fun sofar { Try.Handler.body; _ } ->
List.fold body ~init:sofar ~f:(collect_from_statement ~ignore_class))
in
let sofar = List.fold orelse ~init:sofar ~f:(collect_from_statement ~ignore_class) in
List.fold finally ~init:sofar ~f:(collect_from_statement ~ignore_class)
| With { With.body; _ } -> List.fold body ~init:sofar ~f:(collect_from_statement ~ignore_class)
| Assign _
| Assert _
| Break
| Continue
| Delete _
| Expression _
| Global _
| Import _
| Nonlocal _
| Pass
| Raise _
| Return _ ->
sofar
in
let drop_nested_body { Node.value = { Define.body; _ } as define; location } =
let new_define =
let rec drop_nested_body_in_statement = function
| Statement.Class definition -> Statement.Class { definition with body = [] }
| Define { Define.signature; _ } ->
Statement.Define { Define.signature; captures = []; unbound_names = []; body = [] }
| For ({ For.body; orelse; _ } as for_statement) ->
Statement.For
{
for_statement with
body = drop_nested_body_in_statements body;
orelse = drop_nested_body_in_statements orelse;
}
| Match ({ Match.cases; _ } as match_statement) ->
Statement.Match
{
match_statement with
cases =
List.map cases ~f:(fun ({ Match.Case.body; _ } as case) ->
{ case with Match.Case.body = drop_nested_body_in_statements body });
}
| If ({ If.body; orelse; _ } as if_statement) ->
Statement.If
{
if_statement with
body = drop_nested_body_in_statements body;
orelse = drop_nested_body_in_statements orelse;
}
| While ({ While.body; orelse; _ } as while_statement) ->
Statement.While
{
while_statement with
body = drop_nested_body_in_statements body;
orelse = drop_nested_body_in_statements orelse;
}
| Try { Try.body; handlers; orelse; finally } ->
Statement.Try
{
Try.body = drop_nested_body_in_statements body;
handlers =
List.map handlers ~f:(fun ({ Try.Handler.body; _ } as handler) ->
{ handler with Try.Handler.body = drop_nested_body_in_statements body });
orelse = drop_nested_body_in_statements orelse;
finally = drop_nested_body_in_statements finally;
}
| With ({ With.body; _ } as with_statement) ->
Statement.With { with_statement with body = drop_nested_body_in_statements body }
| _ as statement -> statement
and drop_nested_body_in_statements statements =
List.map statements ~f:(Node.map ~f:drop_nested_body_in_statement)
in
{ define with Define.body = drop_nested_body_in_statements body }
in
{ Node.value = new_define; location }
in
List.fold statements ~init:[] ~f:(collect_from_statement ~ignore_class:false)
|> List.map ~f:drop_nested_body
let collect_defines ({ Source.module_path = { ModulePath.qualifier; _ }; _ } as source) =
let all_defines = collect_typecheck_units source in
let table = Reference.Table.create () in
let process_define ({ Node.value = define; _ } as define_node) =
let define_name = Define.name define in
let sibling =
let open Sibling in
if Define.is_overloaded_function define then
Some { kind = Kind.Overload; body = define_node }
else if Define.is_property_setter define then
Some { kind = Kind.PropertySetter; body = define_node }
else
None
in
let update = function
| None -> (
match sibling with
| Some sibling -> None, [sibling]
| None -> Some define_node, [])
| Some (body, siblings) -> (
match sibling with
| Some sibling -> body, sibling :: siblings
| None ->
if Option.is_some body then (
Log.debug
"Dropping the body of function %a as it has duplicated name with other functions"
Reference.pp
define_name;
body, siblings)
else
Some define_node, siblings)
in
Hashtbl.update table define_name ~f:update
in
let collect_definition ~key ~data:(body, overloads) collected =
let siblings = List.sort overloads ~compare:Sibling.compare in
(key, { qualifier; body; siblings }) :: collected
in
let all_defines =
Source.top_level_define_node source :: all_defines
in
List.iter all_defines ~f:process_define;
Hashtbl.fold table ~init:[] ~f:collect_definition
|
c9d5f18fdfa596494336fe0d6b0822861db93a073b8ee680d35978bb825d216b
|
elm/package.elm-lang.org
|
Migrate.hs
|
# OPTIONS_GHC -Wall #
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Monad (forM_)
import Control.Monad.Trans (liftIO)
import qualified Data.Set as Set
import System.Console.CmdArgs
import qualified System.Directory as Dir
import qualified Crawl
import qualified Elm.Package as Pkg
import qualified GetDates as Dates
import qualified Task
import qualified MoveDocs as Docs
import qualified MoveElmJson as ElmJson
import qualified MoveReadme as Readme
data Flags =
Flags
{ batch :: Int
, github :: String
}
deriving (Data,Typeable,Show,Eq)
flags :: Flags
flags =
Flags
{ batch = 40
&= help "Maximum number of packages to process"
, github = ""
&= help "OAuth token for talking to GitHub"
}
-- MAIN
main :: IO ()
main =
do cargs <- cmdArgs flags
Task.run (github cargs) $
do liftIO $ putStrLn "---- CRAWLING DIRECTORIES ----"
newPackages <- skipProblems <$> Crawl.newPackages
liftIO $ putStrLn "---- MOVING ASSETS ----"
mapM_ moveAssets newPackages
liftIO $ putStrLn "---- CHECKING RELEASE DATES ----"
Dates.get =<< Crawl.upgradingPackages
liftIO $ putStrLn "DONE"
moveAssets :: Crawl.Package -> Task.Task ()
moveAssets (Crawl.Package pkg vsns) =
forM_ vsns $ \vsn ->
Task.attempt pkg vsn $
do liftIO $ putStrLn $ Pkg.toString pkg ++ " " ++ Pkg.versionToString vsn
liftIO $ Dir.createDirectoryIfMissing True (Crawl.newDir pkg vsn)
Readme.move pkg vsn
ElmJson.move pkg vsn
Docs.move pkg vsn
-- PROBLEM PACKAGES
skipProblems :: [Crawl.Package] -> [Crawl.Package]
skipProblems packages =
filter (\(Crawl.Package pkg _) -> not (Set.member pkg problemPackages)) packages
problemPackages :: Set.Set Pkg.Name
problemPackages =
Set.fromList
[ Pkg.Name "joneshf" "elm-proof" -- crazy module name in docs
, Pkg.Name "adam-r-kowalski" "elm-css-legacy" -- deleted
, Pkg.Name "danstn" "elm-postgrest" -- deleted
, Pkg.Name "elm-community" "elm-function-extra" -- deleted
, Pkg.Name "elm-community" "elm-undo-redo" -- deleted
, Pkg.Name "folkertdev" "elm-ordereddict" -- deleted
, Pkg.Name "frenchdonuts" "elm-autocomplete" -- too weird
, Pkg.Name "geekyme" "elm-charts" -- deleted
, Pkg.Name "humio" "elm-plot" -- missing tags / why fork?
, Pkg.Name "izdi" "junk" -- deleted
, Pkg.Name "JasonGFitzpatrick" "elm-router" -- deleted
, Pkg.Name "jasonmahr" "html-escaped-unicode" -- deleted
, Pkg.Name "JOEANDAVERDE" "flex-html" -- deleted
, Pkg.Name "joonazan" "elm-ast" -- missing tags / why fork?
, Pkg.Name "jvoigtlaender" "elm-drag-and-drop" -- deleted
, Pkg.Name "lagunoff" "elm-mdl" -- deleted
, Pkg.Name "lukewestby-fake-elm-lang-1" "redirect-test-1" -- deleted
, Pkg.Name "nicklawls" "elm-html-animation" -- deleted
, Pkg.Name "nvaldes" "elm-bootstrap" -- deprecated / -lang/package.elm-lang.org/issues/227
, Pkg.Name "omarroth" "elm-dom" -- deleted
, Pkg.Name "omarroth" "elm-parts" -- deleted
, Pkg.Name "rluiten" "lunrelm" -- deprecated
, Pkg.Name "stasdavydov" "elm-cart" -- unlicensed
, Pkg.Name "RomanErnst" "updated-list" -- deleted
, Pkg.Name "Spottt" "elm-dialog" -- missing tags / why fork?
, Pkg.Name "terezka" "elm-view-utils" -- renamed
, Pkg.Name "williamwhitacre" "gigan" -- renamed / unlicensed
signals / unlicensed but BSD3
, Pkg.Name "wittjosiah" "elm-css" -- deleted
, Pkg.Name "z5h" "time-app" -- deprecated
]
| null |
https://raw.githubusercontent.com/elm/package.elm-lang.org/d4d5a997a5d9d6622694c488e6a3ae9f537da761/migration/Migrate.hs
|
haskell
|
# LANGUAGE DeriveDataTypeable #
# LANGUAGE OverloadedStrings #
MAIN
PROBLEM PACKAGES
crazy module name in docs
deleted
deleted
deleted
deleted
deleted
too weird
deleted
missing tags / why fork?
deleted
deleted
deleted
deleted
missing tags / why fork?
deleted
deleted
deleted
deleted
deprecated / -lang/package.elm-lang.org/issues/227
deleted
deleted
deprecated
unlicensed
deleted
missing tags / why fork?
renamed
renamed / unlicensed
deleted
deprecated
|
# OPTIONS_GHC -Wall #
module Main where
import Control.Monad (forM_)
import Control.Monad.Trans (liftIO)
import qualified Data.Set as Set
import System.Console.CmdArgs
import qualified System.Directory as Dir
import qualified Crawl
import qualified Elm.Package as Pkg
import qualified GetDates as Dates
import qualified Task
import qualified MoveDocs as Docs
import qualified MoveElmJson as ElmJson
import qualified MoveReadme as Readme
data Flags =
Flags
{ batch :: Int
, github :: String
}
deriving (Data,Typeable,Show,Eq)
flags :: Flags
flags =
Flags
{ batch = 40
&= help "Maximum number of packages to process"
, github = ""
&= help "OAuth token for talking to GitHub"
}
main :: IO ()
main =
do cargs <- cmdArgs flags
Task.run (github cargs) $
do liftIO $ putStrLn "---- CRAWLING DIRECTORIES ----"
newPackages <- skipProblems <$> Crawl.newPackages
liftIO $ putStrLn "---- MOVING ASSETS ----"
mapM_ moveAssets newPackages
liftIO $ putStrLn "---- CHECKING RELEASE DATES ----"
Dates.get =<< Crawl.upgradingPackages
liftIO $ putStrLn "DONE"
moveAssets :: Crawl.Package -> Task.Task ()
moveAssets (Crawl.Package pkg vsns) =
forM_ vsns $ \vsn ->
Task.attempt pkg vsn $
do liftIO $ putStrLn $ Pkg.toString pkg ++ " " ++ Pkg.versionToString vsn
liftIO $ Dir.createDirectoryIfMissing True (Crawl.newDir pkg vsn)
Readme.move pkg vsn
ElmJson.move pkg vsn
Docs.move pkg vsn
skipProblems :: [Crawl.Package] -> [Crawl.Package]
skipProblems packages =
filter (\(Crawl.Package pkg _) -> not (Set.member pkg problemPackages)) packages
problemPackages :: Set.Set Pkg.Name
problemPackages =
Set.fromList
signals / unlicensed but BSD3
]
|
564257d281558b7598ceaf410ec953bd9cf1fb0c3080e83b4fb2d8a1a261cc5c
|
haskell-repa/repa
|
Object.hs
|
# LANGUAGE UndecidableInstances #
module Data.Repa.Convert.Format.Object
( Object (..)
, ObjectFormat
, ObjectFields
, Field (..)
, mkObject)
where
import Data.Repa.Convert.Internal.Format
import Data.Repa.Convert.Internal.Packable
import Data.Repa.Convert.Internal.Packer
import Data.Repa.Convert.Format.String
import Data.Repa.Convert.Format.Binary
import Data.Repa.Scalar.Product
import Data.Word
import Data.Char
import GHC.Exts
import Data.Text (Text)
import qualified Data.Text as T
-- | Format of a simple object format with labeled fields.
data Object fields where
Object
:: ObjectFields fields
-> Object fields
-- | Resents the fields of a JSON object.
data ObjectFields fields where
ObjectFieldsNil
:: ObjectFields ()
ObjectFieldsCons
Meta data about this format .
-> !Text -- Name of head field
-> !f -- Format of head field.
-> Maybe (Value f -> Bool) -- Predicate to determine whether to emit value.
Spec for rest of fields .
-> ObjectFields (f :*: fs)
| Precomputed information about this format .
data ObjectMeta
= ObjectMeta
{ -- | Length of this format, in fields.
omFieldCount :: !Int
-- | Minimum length of this format, in bytes.
, omMinSize :: !Int
-- | Fixed size of this format.
, omFixedSize :: !(Maybe Int) }
---------------------------------------------------------------------------------------------------
-- | Make an object format with the given labeled fields. For example:
--
-- @> let fmt = mkObject
$ Field " index " IntAsc Nothing
-- :*: Field "message" (VarCharString \'-\') Nothing
:* : Field " value " ( " NULL " DoubleAsc ) ( Just isJust )
-- :*: ()
-- @
--
-- Packing this produces:
--
-- @
> let Just str = packToString fmt ( 27 :* : " foo " :* : Nothing :* : ( ) )
>
-- > {"index":27,"message":"foo"}
-- @
--
-- Note that the encodings that this format can generate are a superset of
the JavaScript Object Notation ( JSON ) . With the format , the fields
of an object can directly encode dates and other values , wheras in JSON
-- these values must be represented by strings.
--
mkObject :: ObjectFormat f
=> f -> Object (ObjectFormat' f)
mkObject f = Object (mkObjectFields f)
class ObjectFormat f where
type ObjectFormat' f
mkObjectFields :: f -> ObjectFields (ObjectFormat' f)
instance ObjectFormat () where
type ObjectFormat' () = ()
mkObjectFields () = ObjectFieldsNil
# INLINE mkObjectFields #
-- | A single field in an object.
data Field f
= Field
{ fieldName :: String
, fieldFormat :: f
, fieldInclude :: Maybe (Value f -> Bool) }
instance ( Format f1
, ObjectFormat fs)
=> ObjectFormat (Field f1 :*: fs) where
type ObjectFormat' (Field f1 :*: fs)
= f1 :*: ObjectFormat' fs
mkObjectFields (Field label f1 mKeep :*: fs)
= case mkObjectFields fs of
ObjectFieldsNil
-> ObjectFieldsCons
(ObjectMeta
{ omFieldCount = 1
-- Smallest JSON object looks like:
{ " LABEL":VALUE } , so there are 5 extra characters .
, omMinSize = 5 + length label + minSize f1
, omFixedSize = fmap (+ (5 + length label)) $ fixedSize f1 })
(T.pack label) f1 mKeep ObjectFieldsNil
cc@(ObjectFieldsCons jm _ _ _ _)
-> ObjectFieldsCons
(ObjectMeta
{ omFieldCount = 1 + omFieldCount jm
-- Adding a new field makes the object look like:
{ " LABEL1":VALUE1,"LABEL2":VALUE2 } , so there are 4 extra
-- characters for addiitonal field, 1x',' + 2x'"' + 1x':'
, omMinSize = 4 + minSize f1 + omMinSize jm
, omFixedSize
= do s1 <- fixedSize f1
ss <- omFixedSize jm
return $ s1 + 4 + ss })
(T.pack label) f1 mKeep cc
# INLINE mkObjectFields #
---------------------------------------------------------------------------------------------------
instance ( Format (ObjectFields fs)
, Value (ObjectFields fs) ~ Value fs)
=> Format (Object fs) where
type Value (Object fs)
= Value fs
fieldCount (Object _)
= 1
# INLINE fieldCount #
minSize (Object fs)
= 2 + minSize fs
# INLINE minSize #
fixedSize (Object fs)
= do sz <- fixedSize fs
return (2 + sz)
# INLINE fixedSize #
packedSize (Object fs) xs
= do ps <- packedSize fs xs
return $ 2 + ps
# INLINE packedSize #
---------------------------------------------------------------------------------------------------
instance Format (ObjectFields ()) where
type Value (ObjectFields ()) = ()
fieldCount ObjectFieldsNil = 0
minSize ObjectFieldsNil = 0
fixedSize ObjectFieldsNil = return 0
packedSize ObjectFieldsNil _ = return 0
# INLINE fieldCount #
{-# INLINE minSize #-}
{-# INLINE fixedSize #-}
# INLINE packedSize #
instance Packable (ObjectFields ()) where
packer _fmt _val dst _fails k
= k dst
{-# INLINE packer #-}
instance Unpackable (ObjectFields ()) where
unpacker _fmt start _end _stop _fail eat
= eat start ()
# INLINE unpacker #
instance ( Format f1, Format (ObjectFields fs)
, Value (ObjectFields fs) ~ Value fs)
=> Format (ObjectFields (f1 :*: fs)) where
type Value (ObjectFields (f1 :*: fs))
= Value f1 :*: Value fs
fieldCount (ObjectFieldsCons jm _l1 _f1 _keep _jfs)
= omFieldCount jm
# INLINE fieldCount #
minSize (ObjectFieldsCons jm _l1 _f1 _keep _jfs)
= omMinSize jm
# INLINE minSize #
fixedSize (ObjectFieldsCons jm _l1 _f1 _keep _jfs)
= omFixedSize jm
# INLINE fixedSize #
packedSize (ObjectFieldsCons _jm l1 f1 _keep jfs) (x1 :*: xs)
= do sl <- packedSize VarCharString (T.unpack l1)
s1 <- packedSize f1 x1
ss <- packedSize jfs xs
let sSep = zeroOrOne (fieldCount jfs)
return $ sl + 1 + s1 + sSep + ss
# INLINE packedSize #
---------------------------------------------------------------------------------------------------
instance ( Format (Object f)
, Value (ObjectFields f) ~ Value f
, Packable (ObjectFields f))
=> Packable (Object f) where
pack (Object fs) xs
= pack Word8be (w8 $ ord '{')
<> pack fs xs
<> pack Word8be (w8 $ ord '}')
# INLINE pack #
packer f v
= fromPacker $ pack f v
{-# INLINE packer #-}
---------------------------------------------------------------------------------------------------
instance ( Packable f1
, Value (ObjectFields ()) ~ Value ())
=> Packable (ObjectFields (f1 :*: ())) where
pack (ObjectFieldsCons _jm l1 f1 _keep _jfs) (x1 :*: _)
= pack VarCharString (T.unpack l1)
<> pack Word8be (w8 $ ord ':')
<> pack f1 x1
# INLINE pack #
packer f v
= fromPacker $ pack f v
{-# INLINE packer #-}
instance ( Packable f1
, Packable (ObjectFields (f2 :*: fs))
, Value (ObjectFields (f2 :*: fs)) ~ Value (f2 :*: fs)
, Value (ObjectFields fs) ~ Value fs)
=> Packable (ObjectFields (f1 :*: f2 :*: fs)) where
-- Pack a field into the object,
-- only keeping it if the keep flag is true.
pack (ObjectFieldsCons _jm l1 f1 mKeep jfs) (x1 :*: xs)
= if (case mKeep of
Just keep -> keep x1
_ -> True)
then here
else rest
where
here = pack VarCharString (T.unpack l1)
<> pack Word8be (w8 $ ord ':')
<> pack f1 x1
<> pack Word8be (w8 $ ord ',')
<> rest
rest = pack jfs xs
# INLINE pack #
packer f v
= fromPacker $ pack f v
{-# INLINE packer #-}
---------------------------------------------------------------------------------------------------
w8 :: Integral a => a -> Word8
w8 = fromIntegral
{-# INLINE w8 #-}
-- | Branchless equality used to avoid compile-time explosion in size of core code.
zeroOrOne :: Int -> Int
zeroOrOne (I# i) = I# (1# -# (0# ==# i))
# INLINE zeroOrOne #
| null |
https://raw.githubusercontent.com/haskell-repa/repa/c867025e99fd008f094a5b18ce4dabd29bed00ba/repa-convert/Data/Repa/Convert/Format/Object.hs
|
haskell
|
| Format of a simple object format with labeled fields.
| Resents the fields of a JSON object.
Name of head field
Format of head field.
Predicate to determine whether to emit value.
| Length of this format, in fields.
| Minimum length of this format, in bytes.
| Fixed size of this format.
-------------------------------------------------------------------------------------------------
| Make an object format with the given labeled fields. For example:
@> let fmt = mkObject
:*: Field "message" (VarCharString \'-\') Nothing
:*: ()
@
Packing this produces:
@
> {"index":27,"message":"foo"}
@
Note that the encodings that this format can generate are a superset of
these values must be represented by strings.
| A single field in an object.
Smallest JSON object looks like:
Adding a new field makes the object look like:
characters for addiitonal field, 1x',' + 2x'"' + 1x':'
-------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------
# INLINE minSize #
# INLINE fixedSize #
# INLINE packer #
-------------------------------------------------------------------------------------------------
# INLINE packer #
-------------------------------------------------------------------------------------------------
# INLINE packer #
Pack a field into the object,
only keeping it if the keep flag is true.
# INLINE packer #
-------------------------------------------------------------------------------------------------
# INLINE w8 #
| Branchless equality used to avoid compile-time explosion in size of core code.
|
# LANGUAGE UndecidableInstances #
module Data.Repa.Convert.Format.Object
( Object (..)
, ObjectFormat
, ObjectFields
, Field (..)
, mkObject)
where
import Data.Repa.Convert.Internal.Format
import Data.Repa.Convert.Internal.Packable
import Data.Repa.Convert.Internal.Packer
import Data.Repa.Convert.Format.String
import Data.Repa.Convert.Format.Binary
import Data.Repa.Scalar.Product
import Data.Word
import Data.Char
import GHC.Exts
import Data.Text (Text)
import qualified Data.Text as T
data Object fields where
Object
:: ObjectFields fields
-> Object fields
data ObjectFields fields where
ObjectFieldsNil
:: ObjectFields ()
ObjectFieldsCons
Meta data about this format .
Spec for rest of fields .
-> ObjectFields (f :*: fs)
| Precomputed information about this format .
data ObjectMeta
= ObjectMeta
omFieldCount :: !Int
, omMinSize :: !Int
, omFixedSize :: !(Maybe Int) }
$ Field " index " IntAsc Nothing
:* : Field " value " ( " NULL " DoubleAsc ) ( Just isJust )
> let Just str = packToString fmt ( 27 :* : " foo " :* : Nothing :* : ( ) )
>
the JavaScript Object Notation ( JSON ) . With the format , the fields
of an object can directly encode dates and other values , wheras in JSON
mkObject :: ObjectFormat f
=> f -> Object (ObjectFormat' f)
mkObject f = Object (mkObjectFields f)
class ObjectFormat f where
type ObjectFormat' f
mkObjectFields :: f -> ObjectFields (ObjectFormat' f)
instance ObjectFormat () where
type ObjectFormat' () = ()
mkObjectFields () = ObjectFieldsNil
# INLINE mkObjectFields #
data Field f
= Field
{ fieldName :: String
, fieldFormat :: f
, fieldInclude :: Maybe (Value f -> Bool) }
instance ( Format f1
, ObjectFormat fs)
=> ObjectFormat (Field f1 :*: fs) where
type ObjectFormat' (Field f1 :*: fs)
= f1 :*: ObjectFormat' fs
mkObjectFields (Field label f1 mKeep :*: fs)
= case mkObjectFields fs of
ObjectFieldsNil
-> ObjectFieldsCons
(ObjectMeta
{ omFieldCount = 1
{ " LABEL":VALUE } , so there are 5 extra characters .
, omMinSize = 5 + length label + minSize f1
, omFixedSize = fmap (+ (5 + length label)) $ fixedSize f1 })
(T.pack label) f1 mKeep ObjectFieldsNil
cc@(ObjectFieldsCons jm _ _ _ _)
-> ObjectFieldsCons
(ObjectMeta
{ omFieldCount = 1 + omFieldCount jm
{ " LABEL1":VALUE1,"LABEL2":VALUE2 } , so there are 4 extra
, omMinSize = 4 + minSize f1 + omMinSize jm
, omFixedSize
= do s1 <- fixedSize f1
ss <- omFixedSize jm
return $ s1 + 4 + ss })
(T.pack label) f1 mKeep cc
# INLINE mkObjectFields #
instance ( Format (ObjectFields fs)
, Value (ObjectFields fs) ~ Value fs)
=> Format (Object fs) where
type Value (Object fs)
= Value fs
fieldCount (Object _)
= 1
# INLINE fieldCount #
minSize (Object fs)
= 2 + minSize fs
# INLINE minSize #
fixedSize (Object fs)
= do sz <- fixedSize fs
return (2 + sz)
# INLINE fixedSize #
packedSize (Object fs) xs
= do ps <- packedSize fs xs
return $ 2 + ps
# INLINE packedSize #
instance Format (ObjectFields ()) where
type Value (ObjectFields ()) = ()
fieldCount ObjectFieldsNil = 0
minSize ObjectFieldsNil = 0
fixedSize ObjectFieldsNil = return 0
packedSize ObjectFieldsNil _ = return 0
# INLINE fieldCount #
# INLINE packedSize #
instance Packable (ObjectFields ()) where
packer _fmt _val dst _fails k
= k dst
instance Unpackable (ObjectFields ()) where
unpacker _fmt start _end _stop _fail eat
= eat start ()
# INLINE unpacker #
instance ( Format f1, Format (ObjectFields fs)
, Value (ObjectFields fs) ~ Value fs)
=> Format (ObjectFields (f1 :*: fs)) where
type Value (ObjectFields (f1 :*: fs))
= Value f1 :*: Value fs
fieldCount (ObjectFieldsCons jm _l1 _f1 _keep _jfs)
= omFieldCount jm
# INLINE fieldCount #
minSize (ObjectFieldsCons jm _l1 _f1 _keep _jfs)
= omMinSize jm
# INLINE minSize #
fixedSize (ObjectFieldsCons jm _l1 _f1 _keep _jfs)
= omFixedSize jm
# INLINE fixedSize #
packedSize (ObjectFieldsCons _jm l1 f1 _keep jfs) (x1 :*: xs)
= do sl <- packedSize VarCharString (T.unpack l1)
s1 <- packedSize f1 x1
ss <- packedSize jfs xs
let sSep = zeroOrOne (fieldCount jfs)
return $ sl + 1 + s1 + sSep + ss
# INLINE packedSize #
instance ( Format (Object f)
, Value (ObjectFields f) ~ Value f
, Packable (ObjectFields f))
=> Packable (Object f) where
pack (Object fs) xs
= pack Word8be (w8 $ ord '{')
<> pack fs xs
<> pack Word8be (w8 $ ord '}')
# INLINE pack #
packer f v
= fromPacker $ pack f v
instance ( Packable f1
, Value (ObjectFields ()) ~ Value ())
=> Packable (ObjectFields (f1 :*: ())) where
pack (ObjectFieldsCons _jm l1 f1 _keep _jfs) (x1 :*: _)
= pack VarCharString (T.unpack l1)
<> pack Word8be (w8 $ ord ':')
<> pack f1 x1
# INLINE pack #
packer f v
= fromPacker $ pack f v
instance ( Packable f1
, Packable (ObjectFields (f2 :*: fs))
, Value (ObjectFields (f2 :*: fs)) ~ Value (f2 :*: fs)
, Value (ObjectFields fs) ~ Value fs)
=> Packable (ObjectFields (f1 :*: f2 :*: fs)) where
pack (ObjectFieldsCons _jm l1 f1 mKeep jfs) (x1 :*: xs)
= if (case mKeep of
Just keep -> keep x1
_ -> True)
then here
else rest
where
here = pack VarCharString (T.unpack l1)
<> pack Word8be (w8 $ ord ':')
<> pack f1 x1
<> pack Word8be (w8 $ ord ',')
<> rest
rest = pack jfs xs
# INLINE pack #
packer f v
= fromPacker $ pack f v
w8 :: Integral a => a -> Word8
w8 = fromIntegral
zeroOrOne :: Int -> Int
zeroOrOne (I# i) = I# (1# -# (0# ==# i))
# INLINE zeroOrOne #
|
3a3b3fc542f09dafbaba54fe06a45ad03d6fbbffaa00586a362f10d4f256b784
|
egonSchiele/dominion
|
Internal.hs
|
module Dominion.Internal (
-- | Note: You shouldn't need to import this module...the
interesting functions are re - exported by the Dominion module .
--
-- Use any other functions in here at your own risk.
module Dominion.Internal
) where
import Control.Applicative
import Control.Arrow
import Control.Lens hiding (has, indices)
import Control.Monad (liftM)
import Control.Monad.State hiding (state)
import Data.List
import Data.Map.Lazy ((!))
import qualified Data.Map.Lazy as M
import Data.Maybe
import Data.Ord
import qualified Dominion.Cards as CA
import qualified Dominion.Types as T
import Dominion.Utils
import Prelude hiding (log)
import System.IO.Unsafe
import Text.Printf
-- | see all of the cards in a player's hand.
--
-- > cards <- currentHand playerId
currentHand :: T.PlayerId -> T.Dominion [T.Card]
currentHand playerId = (^. T.hand) <$> getPlayer playerId
-- | see if a player has a card in his hand.
--
-- > hasCard <- playerId `has` chapel
has :: T.PlayerId -> T.Card -> T.Dominion Bool
has playerId card = do
player <- getPlayer playerId
return $ card `elem` (player ^. T.hand)
-- | see how many of this card a player has.
--
-- > numMarkets <- countNum playerId market
countNum :: T.PlayerId -> T.Card -> T.Dominion Int
countNum playerId card = do
player <- getPlayer playerId
let allCards = player ^. T.deck ++ player ^. T.discard ++ player ^. T.hand
return $ count card allCards
-- | What this card is worth in money.
coinValue :: T.Card -> Int
coinValue card = sum $ map effect (card ^. T.effects)
where effect (T.CoinValue num) = num
effect _ = 0
-- | Get the current round number.
getRound :: T.Dominion Int
getRound = T._round <$> get
-- | How much money this player's hand is worth (also counts any money you
-- get from action cards, like +1 from market).
handValue :: T.PlayerId -> T.Dominion Int
handValue playerId = do
player <- getPlayer playerId
return $ sum (map coinValue (player ^. T.hand)) + (player ^. T.extraMoney)
-- | Check if this card's pile is empty. Returns True is the card is not in play.
pileEmpty :: T.Card -> T.Dominion Bool
pileEmpty card = do
state <- get
return $ case M.lookup card (state ^. T.cards) of
Nothing -> True
Just x -> x == 0
-- | Returns the card, or Nothing if that pile is empty.
-- Useful because it automatically checks whether the pile is empty, and
-- modifies state to subtract a card from the pile correctly.
getCard :: T.Card -> T.Dominion (Maybe T.Card)
getCard card = do
empty <- pileEmpty card
if empty
then return Nothing
else do
modify $ over T.cards (decrement card)
return $ Just card
-- | Convenience function. Prints out a line if verbose, AND prints out
-- info about the related player...name, money, # of buys, # of actions.
log :: T.PlayerId -> String -> T.Dominion ()
log playerId str = do
player <- getPlayer playerId
money <- handValue playerId
let name = player ^. T.playerName
buys = player ^. T.buys
actions = player ^. T.actions
statusLine = printf "[player %s, name: %s, money: %s, buys: %s, actions: %s]" (yellow . show $ playerId) (yellow name) (green . show $ money) (green . show $ buys) (red . show $ actions)
log_ $ statusLine ++ ": " ++ green str
-- | Like `log` but doesn't print out info about a player
log_ :: String -> T.Dominion ()
log_ str = do
state <- get
when (state ^. T.verbose) $ liftIO . putStrLn $ str
gameOver :: M.Map T.Card Int -> Bool
gameOver cards
| cards ! CA.province == 0 = True
| M.size (M.filter (== 0) cards) >= 3 = True
| otherwise = False
-- | Given a player id and a number of cards to draw, draws that many cards
-- from the deck, shuffling if necessary.
drawFromDeck :: T.PlayerId -> Int -> T.Dominion [T.Card]
drawFromDeck playerId numCards = do
player <- getPlayer playerId
let deck = player ^. T.deck
if length deck >= numCards
then draw numCards
else do
let inDeck = length deck
lastCards <- draw inDeck
shuffleDeck playerId
liftM (++ lastCards) $ draw (numCards - inDeck)
where
draw numCards = do
player <- getPlayer playerId
let drawnCards = take numCards (player ^. T.deck)
modifyPlayer playerId $ over T.deck (drop numCards) . over T.hand (++ drawnCards)
return drawnCards
-- | Like `modify` for the `State` monad, but works on players.
-- Takes a player id and a function that modifies the player.
modifyPlayer :: T.PlayerId -> (T.Player -> T.Player) -> T.Dominion ()
modifyPlayer playerId func = modify $ over (T.players . element playerId) func
| Like ` modifyPlayer ` , but modifies every player * except * the one specified with the player i d.
modifyOtherPlayers :: T.PlayerId -> (T.Player -> T.Player) -> T.Dominion ()
modifyOtherPlayers playerId func = do
state <- get
let players = indices (state ^. T.players) \\ [playerId]
forM_ players $ \pid -> modify $ over (T.players . element pid) func
setupForTurn :: T.PlayerId -> T.Dominion ()
setupForTurn playerId = do
drawFromDeck playerId 5
modifyPlayer playerId $ set T.actions 1 . set T.buys 1 . set T.extraMoney 0
playTurn :: T.PlayerId -> T.Strategy -> T.Dominion ()
playTurn playerId strategy = do
roundNum <- getRound
when (roundNum == 1) $ setupForTurn playerId
player <- getPlayer playerId
log playerId $ "player's hand has: " ++ (show . map T._name $ player ^. T.hand)
strategy playerId
discardHand playerId
-- we draw from deck *after* to set up the next hand NOW,
-- instead of calling this at the beginning of the function.
-- The reason is, if someone else plays a militia, or a council room,
-- these players need to be able to modify their deck accordingly
-- even if its not their turn.
setupForTurn playerId
makeGameState :: [T.Option] -> [T.Player] -> IO T.GameState
makeGameState options players = do
actionCards_ <- deckShuffle CA.allActionCards
let requiredCards = take 10 $ fromMaybe [] (findCards options)
verbose = fromMaybe False (findLog options)
actionCards = take (10 - length requiredCards) actionCards_ ++ requiredCards
cards = M.fromList ([(CA.copper, 60), (CA.silver, 40), (CA.gold, 30),
(CA.estate, 12), (CA.duchy, 12), (CA.province, 12)]
++ [(c, 10) | c <- actionCards])
return $ T.GameState players cards 1 verbose
game :: [T.Strategy] -> T.Dominion ()
game strategies = do
state <- get
let ids = indices $ state ^. T.players
forM_ (zip ids strategies) (uncurry playTurn)
run :: T.GameState -> [T.Strategy] -> IO T.Result
run state strategies = do
(_, newState) <- runStateT (game strategies) state
let cards = newState ^. T.cards
if gameOver cards
then returnResults newState
else run (over T.round (+1) newState) strategies
returnResults :: T.GameState -> IO T.Result
returnResults state = do
let results = map (id &&& countPoints) (state ^. T.players)
winner = view (_1 . T.playerName) $ maximumBy (comparing snd) results
when (state ^. T.verbose) $ do
putStrLn "Game Over!"
forM_ results $ \(player, points) -> putStrLn $
printf "player %s got %d points" (player ^. T.playerName) points
return $ T.Result results winner
isAction card = T.Action `elem` (card ^. T.cardType)
isAttack card = T.Attack `elem` (card ^. T.cardType)
isReaction card = T.Reaction `elem` (card ^. T.cardType)
isTreasure card = T.Treasure `elem` (card ^. T.cardType)
isVictory card = T.Victory `elem` (card ^. T.cardType)
countPoints :: T.Player -> Int
countPoints player = sum $ map countValue effects
where cards = player ^. T.deck ++ player ^. T.discard ++ player ^. T.hand
victoryCards = filter isVictory cards
effects = concatMap T._effects victoryCards
countValue (T.VPValue x) = x
countValue (T.GardensEffect) = length cards `div` 10
countValue _ = 0
-- | Get player from game state specified by this id.
-- This is useful sometimes:
--
> import qualified Dominion . Types as T
> import Control . Lens
-- >
-- > player <- getPlayer playerId
-- >
-- > -- How many buys does this player have?
-- > player ^. T.buys
-- >
-- > -- How many actions does this player have?
-- > player ^. T.actions
getPlayer :: T.PlayerId -> T.Dominion T.Player
getPlayer playerId = do
state <- get
return $ (state ^. T.players) !! playerId
| Convenience function . @ 4 \`cardsOf\ ` estate @ is the same as @ take 4 . repeat $ estate @
cardsOf = replicate
eitherToBool :: Either String () -> Bool
eitherToBool (Left _) = False
eitherToBool (Right _) = True
-- | Move this players discards + hand into his deck and shuffle the deck.
shuffleDeck :: T.PlayerId -> T.Dominion ()
shuffleDeck playerId = modifyPlayer playerId shuffleDeck_
shuffleDeck_ :: T.Player -> T.Player
shuffleDeck_ player = set T.discard [] $ set T.deck newDeck player
where discard = player ^. T.discard
deck = player ^. T.deck
hand = player ^. T.hand
newDeck = unsafePerformIO $ deckShuffle (deck ++ discard ++ hand)
-- | Check that this player is able to purchase this card. Returns
-- a `Right` if they can purchase the card, otherwise returns a `Left` with
-- the reason why they can't purchase it.
validateBuy :: T.PlayerId -> T.Card -> T.Dominion (T.PlayResult ())
validateBuy playerId card = do
money <- handValue playerId
state <- get
player <- getPlayer playerId
cardGone <- pileEmpty card
return $ do
failIf (money < (card ^. T.cost)) $ printf "Not enough money. You have %d but this card costs %d" money (card ^. T.cost)
failIf cardGone $ printf "We've run out of that card (%s)" (card ^. T.name)
failIf ((player ^. T.buys) < 1) "You don't have any buys remaining!"
-- | Check that this player is able to play this card. Returns
-- a `Right` if they can play the card, otherwise returns a `Left` with
-- the reason why they can't play it.
validatePlay :: T.PlayerId -> T.Card -> T.Dominion (T.PlayResult ())
validatePlay playerId card = do
player <- getPlayer playerId
return $ do
failIf (not (isAction card)) $ printf "%s is not an action card" (card ^. T.name)
failIf ((player ^. T.actions) < 1) "You don't have any actions remaining!"
failIf (card `notElem` (player ^. T.hand)) $ printf
"You can't play a %s because you don't have it in your hand!" (card ^. T.name)
-- Discard this player's hand.
discardHand :: T.PlayerId -> T.Dominion ()
discardHand playerId = modifyPlayer playerId $ \player -> set T.hand [] $ over T.discard (++ (player ^. T.hand)) player
-- for parsing options
findIteration :: [T.Option] -> Maybe Int
findIteration [] = Nothing
findIteration (T.Iterations x : xs) = Just x
findIteration (_:xs) = findIteration xs
-- for parsing options
findLog :: [T.Option] -> Maybe Bool
findLog [] = Nothing
findLog (T.Log x : xs) = Just x
findLog (_:xs) = findLog xs
-- for parsing options
findCards :: [T.Option] -> Maybe [T.Card]
findCards [] = Nothing
findCards (T.Cards x : xs) = Just x
findCards (_:xs) = findCards xs
-- | Keep drawing a card until the provided function returns true.
-- The function gets a list of the cards drawn so far,
most recent first . Returns a list of all the cards drawn ( these cards
-- are also placed into the player's hand)
drawsUntil :: T.PlayerId -> ([T.Card] -> T.Dominion Bool) -> T.Dominion [T.Card]
drawsUntil = drawsUntil_ []
-- internal use for drawsUntil
drawsUntil_ :: [T.Card] -> T.PlayerId -> ([T.Card] -> T.Dominion Bool) -> T.Dominion [T.Card]
drawsUntil_ alreadyDrawn playerId func = do
drawnCards <- drawFromDeck playerId 1
let cards = drawnCards ++ alreadyDrawn
stopDrawing <- func cards
if stopDrawing
then return cards
else drawsUntil_ cards playerId func
-- Does this card say you trash it when you play it?
trashThisCard :: T.Card -> Bool
trashThisCard card = T.TrashThisCard `elem` (card ^. T.effects)
-- | Player trashes the given card.
trashesCard :: T.PlayerId -> T.Card -> T.Dominion ()
playerId `trashesCard` card = do
hasCard <- playerId `has` card
when hasCard $ modifyPlayer playerId (over T.hand (delete card))
-- | Player discards the given card.
discardsCard :: T.PlayerId -> T.Card -> T.Dominion ()
playerId `discardsCard` card = do
hasCard <- playerId `has` card
when hasCard $ modifyPlayer playerId $ over T.hand (delete card) . over T.discard (card:)
-- Player returns the given card to the top of their deck.
returnsCard :: T.PlayerId -> T.Card -> T.Dominion ()
playerId `returnsCard` card = do
hasCard <- playerId `has` card
when hasCard $ modifyPlayer playerId $ over T.hand (delete card) . over T.deck (card:)
-- If the top card in the player's deck is one of the cards
-- listed in the provided array, then discard that card (used with spy).
discardTopCard :: [T.Card] -> T.Player -> T.Player
discardTopCard cards player = if topCard `elem` cards
then set T.deck (tail deck) . over T.discard (topCard:) $ player
else player
where topCard = head $ player ^. T.deck
deck = player ^. T.deck
-- If this player has a victory card in his/her hand,
-- it is put on top of their deck *unless* they have a moat in their hand.
-- Used with militia.
returnVPCard :: T.Player -> T.Player
returnVPCard player = let hand = player ^. T.hand
victoryCards = filter isVictory hand
card = head victoryCards
in if CA.moat `elem` hand || null victoryCards
then player
else over T.hand (delete card) $ over T.deck (card:) player
-- TODO how do they choose what to discard??
-- Right now I'm just choosing to discard the least expensive.
-- | Player discards down to x cards.
discardsTo :: T.Player -> Int -> T.Player
player `discardsTo` x = set T.hand toKeep . over T.discard (++ toDiscard) $ player
where hand = sortBy (comparing T._cost) $ player ^. T.hand
toDiscard = take (length hand - x) hand
toKeep = hand \\ toDiscard
-- | Used internally by the `plays` function. Each card has a list of
effects ( like has ` PlusCard 3 ` ) . This function applies the given
-- effect. It returns `Nothing` if the effect doesn't need a `Followup`,
-- or it returns a `Just Followup`.
usesEffect :: T.PlayerId -> T.CardEffect -> T.Dominion (Maybe T.Followup)
playerId `usesEffect` (T.PlusAction x) = do
log playerId ("+ " ++ show x ++ " actions")
modifyPlayer playerId $ over T.actions (+x)
return Nothing
playerId `usesEffect` (T.PlusCoin x) = do
log playerId ("+ " ++ show x ++ " coin")
modifyPlayer playerId $ over T.extraMoney (+x)
return Nothing
playerId `usesEffect` (T.PlusBuy x) = do
log playerId ("+ " ++ show x ++ " buys")
modifyPlayer playerId $ over T.buys (+x)
return Nothing
playerId `usesEffect` (T.PlusCard x) = do
log playerId ("+ " ++ show x ++ " cards")
drawFromDeck playerId x
return Nothing
playerId `usesEffect` effect@(T.PlayActionCard x) = return $ Just (playerId, effect)
playerId `usesEffect` (T.AdventurerEffect) = do
log playerId "finding the next two treasures from your deck..."
drawnCards <- playerId `drawsUntil` (\cards -> return $ countBy isTreasure cards == 2)
-- the cards that weren't treasures need to be discarded
forM_ (filter (not . isTreasure) drawnCards) $ \card -> playerId `discardsCard` card
return Nothing
playerId `usesEffect` (T.BureaucratEffect) = do
card_ <- getCard CA.silver
case card_ of
Nothing -> return ()
Just card -> do
log playerId "+ silver"
modifyPlayer playerId $ over T.deck (card:)
modifyOtherPlayers playerId returnVPCard
return Nothing
playerId `usesEffect` T.CellarEffect = return $ Just (playerId, T.CellarEffect)
playerId `usesEffect` T.ChancellorEffect = return $ Just (playerId, T.ChancellorEffect)
playerId `usesEffect` effect@(T.TrashCards x) = do
log playerId ("Trash up to " ++ show x ++ " cards from your hand.")
return $ Just (playerId, effect)
playerId `usesEffect` effect@(T.OthersPlusCard x) = do
log playerId ("Every other player draws " ++ show x ++ " card.")
state <- get
let players = indices (state ^. T.players) \\ [playerId]
forM_ players $ \pid -> drawFromDeck pid 1
return Nothing
playerId `usesEffect` effect@(T.GainCardUpto x) = do
log playerId ("Gain a card costing up to " ++ show x ++ " coins.")
return $ Just (playerId, effect)
TODO this does n't set aside any action cards .
-- How do I implement the logic for choosing that?
-- Basically it allows the player to go through
-- and choose the action card they want?
playerId `usesEffect` = do
log playerId "Drawing to 7 cards..."
drawsUntil playerId $ \_ -> do
player <- getPlayer playerId
return $ length (player ^. T.hand) == 7
return Nothing
NOTE : one side effect of this + council room is :
-- every player needs to draw their next hand immediately
-- after they finish playing, instead of at the start of when
-- they play. Otherwise suppose someone plays a council room
-- followed by a militia. I need to codify that properly.
playerId `usesEffect` effect@(T.OthersDiscardTo x) = do
log playerId ("Every other player discards down to " ++ show x ++ " cards.")
modifyOtherPlayers playerId (`discardsTo` x)
return Nothing
playerId `usesEffect` T.MineEffect = return $ Just (playerId, T.MineEffect)
playerId `usesEffect` T.MoneylenderEffect = do
hasCard <- playerId `has` CA.copper
when hasCard $ do
log playerId "Trashing a copper. +3 coin"
playerId `trashesCard` CA.copper
modifyPlayer playerId $ over T.extraMoney (+3)
return Nothing
playerId `usesEffect` T.RemodelEffect = return $ Just (playerId, T.RemodelEffect)
playerId `usesEffect` T.SpyEffect = return $ Just (playerId, T.SpyEffect)
playerId `usesEffect` T.ThiefEffect = return $ Just (playerId, T.ThiefEffect)
playerId `usesEffect` (T.OthersGainCurse x) = do
log playerId ("All other players gain " ++ show x ++ " curses.")
let card = CA.curse
empty <- pileEmpty card
if empty
then return Nothing
else do
modifyOtherPlayers playerId (over T.discard (card:))
state <- get
times (length (state ^. T.players) - 1) $ do
modify $ over T.cards (decrement card)
return ()
return Nothing
-- only counted at the end of the game.
playerId `usesEffect` T.GardensEffect = return Nothing
playerId `usesEffect` _ = return Nothing
-- | Given a name, creates a player with that name.
makePlayer :: String -> T.Player
makePlayer name = T.Player name [] (7 `cardsOf` CA.copper ++ 3 `cardsOf` CA.estate) [] 1 1 0
-- Checks that the player can gain the given card, then adds it to his/her
-- discard pile.
gainCardUpTo :: T.PlayerId -> Int -> T.Card -> T.Dominion (T.PlayResult (Maybe [T.Followup]))
gainCardUpTo playerId value card =
if (card ^. T.cost) > value
then return . Left $ printf "Card is too expensive. You can gain a card costing up to %d but this card costs %d" value (card ^. T.cost)
else do
result <- getCard card
case result of
Nothing -> return . Left $ printf "We've run out of that card (%s)" (card ^. T.name)
(Just card_) -> do
modifyPlayer playerId $ over T.discard (card_:)
return $ Right Nothing
| null |
https://raw.githubusercontent.com/egonSchiele/dominion/a4b7300f2e445da5e7cfcc1cf9029243a3561ed6/src/Dominion/Internal.hs
|
haskell
|
| Note: You shouldn't need to import this module...the
Use any other functions in here at your own risk.
| see all of the cards in a player's hand.
> cards <- currentHand playerId
| see if a player has a card in his hand.
> hasCard <- playerId `has` chapel
| see how many of this card a player has.
> numMarkets <- countNum playerId market
| What this card is worth in money.
| Get the current round number.
| How much money this player's hand is worth (also counts any money you
get from action cards, like +1 from market).
| Check if this card's pile is empty. Returns True is the card is not in play.
| Returns the card, or Nothing if that pile is empty.
Useful because it automatically checks whether the pile is empty, and
modifies state to subtract a card from the pile correctly.
| Convenience function. Prints out a line if verbose, AND prints out
info about the related player...name, money, # of buys, # of actions.
| Like `log` but doesn't print out info about a player
| Given a player id and a number of cards to draw, draws that many cards
from the deck, shuffling if necessary.
| Like `modify` for the `State` monad, but works on players.
Takes a player id and a function that modifies the player.
we draw from deck *after* to set up the next hand NOW,
instead of calling this at the beginning of the function.
The reason is, if someone else plays a militia, or a council room,
these players need to be able to modify their deck accordingly
even if its not their turn.
| Get player from game state specified by this id.
This is useful sometimes:
>
> player <- getPlayer playerId
>
> -- How many buys does this player have?
> player ^. T.buys
>
> -- How many actions does this player have?
> player ^. T.actions
| Move this players discards + hand into his deck and shuffle the deck.
| Check that this player is able to purchase this card. Returns
a `Right` if they can purchase the card, otherwise returns a `Left` with
the reason why they can't purchase it.
| Check that this player is able to play this card. Returns
a `Right` if they can play the card, otherwise returns a `Left` with
the reason why they can't play it.
Discard this player's hand.
for parsing options
for parsing options
for parsing options
| Keep drawing a card until the provided function returns true.
The function gets a list of the cards drawn so far,
are also placed into the player's hand)
internal use for drawsUntil
Does this card say you trash it when you play it?
| Player trashes the given card.
| Player discards the given card.
Player returns the given card to the top of their deck.
If the top card in the player's deck is one of the cards
listed in the provided array, then discard that card (used with spy).
If this player has a victory card in his/her hand,
it is put on top of their deck *unless* they have a moat in their hand.
Used with militia.
TODO how do they choose what to discard??
Right now I'm just choosing to discard the least expensive.
| Player discards down to x cards.
| Used internally by the `plays` function. Each card has a list of
effect. It returns `Nothing` if the effect doesn't need a `Followup`,
or it returns a `Just Followup`.
the cards that weren't treasures need to be discarded
How do I implement the logic for choosing that?
Basically it allows the player to go through
and choose the action card they want?
every player needs to draw their next hand immediately
after they finish playing, instead of at the start of when
they play. Otherwise suppose someone plays a council room
followed by a militia. I need to codify that properly.
only counted at the end of the game.
| Given a name, creates a player with that name.
Checks that the player can gain the given card, then adds it to his/her
discard pile.
|
module Dominion.Internal (
interesting functions are re - exported by the Dominion module .
module Dominion.Internal
) where
import Control.Applicative
import Control.Arrow
import Control.Lens hiding (has, indices)
import Control.Monad (liftM)
import Control.Monad.State hiding (state)
import Data.List
import Data.Map.Lazy ((!))
import qualified Data.Map.Lazy as M
import Data.Maybe
import Data.Ord
import qualified Dominion.Cards as CA
import qualified Dominion.Types as T
import Dominion.Utils
import Prelude hiding (log)
import System.IO.Unsafe
import Text.Printf
currentHand :: T.PlayerId -> T.Dominion [T.Card]
currentHand playerId = (^. T.hand) <$> getPlayer playerId
has :: T.PlayerId -> T.Card -> T.Dominion Bool
has playerId card = do
player <- getPlayer playerId
return $ card `elem` (player ^. T.hand)
countNum :: T.PlayerId -> T.Card -> T.Dominion Int
countNum playerId card = do
player <- getPlayer playerId
let allCards = player ^. T.deck ++ player ^. T.discard ++ player ^. T.hand
return $ count card allCards
coinValue :: T.Card -> Int
coinValue card = sum $ map effect (card ^. T.effects)
where effect (T.CoinValue num) = num
effect _ = 0
getRound :: T.Dominion Int
getRound = T._round <$> get
handValue :: T.PlayerId -> T.Dominion Int
handValue playerId = do
player <- getPlayer playerId
return $ sum (map coinValue (player ^. T.hand)) + (player ^. T.extraMoney)
pileEmpty :: T.Card -> T.Dominion Bool
pileEmpty card = do
state <- get
return $ case M.lookup card (state ^. T.cards) of
Nothing -> True
Just x -> x == 0
getCard :: T.Card -> T.Dominion (Maybe T.Card)
getCard card = do
empty <- pileEmpty card
if empty
then return Nothing
else do
modify $ over T.cards (decrement card)
return $ Just card
log :: T.PlayerId -> String -> T.Dominion ()
log playerId str = do
player <- getPlayer playerId
money <- handValue playerId
let name = player ^. T.playerName
buys = player ^. T.buys
actions = player ^. T.actions
statusLine = printf "[player %s, name: %s, money: %s, buys: %s, actions: %s]" (yellow . show $ playerId) (yellow name) (green . show $ money) (green . show $ buys) (red . show $ actions)
log_ $ statusLine ++ ": " ++ green str
log_ :: String -> T.Dominion ()
log_ str = do
state <- get
when (state ^. T.verbose) $ liftIO . putStrLn $ str
gameOver :: M.Map T.Card Int -> Bool
gameOver cards
| cards ! CA.province == 0 = True
| M.size (M.filter (== 0) cards) >= 3 = True
| otherwise = False
drawFromDeck :: T.PlayerId -> Int -> T.Dominion [T.Card]
drawFromDeck playerId numCards = do
player <- getPlayer playerId
let deck = player ^. T.deck
if length deck >= numCards
then draw numCards
else do
let inDeck = length deck
lastCards <- draw inDeck
shuffleDeck playerId
liftM (++ lastCards) $ draw (numCards - inDeck)
where
draw numCards = do
player <- getPlayer playerId
let drawnCards = take numCards (player ^. T.deck)
modifyPlayer playerId $ over T.deck (drop numCards) . over T.hand (++ drawnCards)
return drawnCards
modifyPlayer :: T.PlayerId -> (T.Player -> T.Player) -> T.Dominion ()
modifyPlayer playerId func = modify $ over (T.players . element playerId) func
| Like ` modifyPlayer ` , but modifies every player * except * the one specified with the player i d.
modifyOtherPlayers :: T.PlayerId -> (T.Player -> T.Player) -> T.Dominion ()
modifyOtherPlayers playerId func = do
state <- get
let players = indices (state ^. T.players) \\ [playerId]
forM_ players $ \pid -> modify $ over (T.players . element pid) func
setupForTurn :: T.PlayerId -> T.Dominion ()
setupForTurn playerId = do
drawFromDeck playerId 5
modifyPlayer playerId $ set T.actions 1 . set T.buys 1 . set T.extraMoney 0
playTurn :: T.PlayerId -> T.Strategy -> T.Dominion ()
playTurn playerId strategy = do
roundNum <- getRound
when (roundNum == 1) $ setupForTurn playerId
player <- getPlayer playerId
log playerId $ "player's hand has: " ++ (show . map T._name $ player ^. T.hand)
strategy playerId
discardHand playerId
setupForTurn playerId
makeGameState :: [T.Option] -> [T.Player] -> IO T.GameState
makeGameState options players = do
actionCards_ <- deckShuffle CA.allActionCards
let requiredCards = take 10 $ fromMaybe [] (findCards options)
verbose = fromMaybe False (findLog options)
actionCards = take (10 - length requiredCards) actionCards_ ++ requiredCards
cards = M.fromList ([(CA.copper, 60), (CA.silver, 40), (CA.gold, 30),
(CA.estate, 12), (CA.duchy, 12), (CA.province, 12)]
++ [(c, 10) | c <- actionCards])
return $ T.GameState players cards 1 verbose
game :: [T.Strategy] -> T.Dominion ()
game strategies = do
state <- get
let ids = indices $ state ^. T.players
forM_ (zip ids strategies) (uncurry playTurn)
run :: T.GameState -> [T.Strategy] -> IO T.Result
run state strategies = do
(_, newState) <- runStateT (game strategies) state
let cards = newState ^. T.cards
if gameOver cards
then returnResults newState
else run (over T.round (+1) newState) strategies
returnResults :: T.GameState -> IO T.Result
returnResults state = do
let results = map (id &&& countPoints) (state ^. T.players)
winner = view (_1 . T.playerName) $ maximumBy (comparing snd) results
when (state ^. T.verbose) $ do
putStrLn "Game Over!"
forM_ results $ \(player, points) -> putStrLn $
printf "player %s got %d points" (player ^. T.playerName) points
return $ T.Result results winner
isAction card = T.Action `elem` (card ^. T.cardType)
isAttack card = T.Attack `elem` (card ^. T.cardType)
isReaction card = T.Reaction `elem` (card ^. T.cardType)
isTreasure card = T.Treasure `elem` (card ^. T.cardType)
isVictory card = T.Victory `elem` (card ^. T.cardType)
countPoints :: T.Player -> Int
countPoints player = sum $ map countValue effects
where cards = player ^. T.deck ++ player ^. T.discard ++ player ^. T.hand
victoryCards = filter isVictory cards
effects = concatMap T._effects victoryCards
countValue (T.VPValue x) = x
countValue (T.GardensEffect) = length cards `div` 10
countValue _ = 0
> import qualified Dominion . Types as T
> import Control . Lens
getPlayer :: T.PlayerId -> T.Dominion T.Player
getPlayer playerId = do
state <- get
return $ (state ^. T.players) !! playerId
| Convenience function . @ 4 \`cardsOf\ ` estate @ is the same as @ take 4 . repeat $ estate @
cardsOf = replicate
eitherToBool :: Either String () -> Bool
eitherToBool (Left _) = False
eitherToBool (Right _) = True
shuffleDeck :: T.PlayerId -> T.Dominion ()
shuffleDeck playerId = modifyPlayer playerId shuffleDeck_
shuffleDeck_ :: T.Player -> T.Player
shuffleDeck_ player = set T.discard [] $ set T.deck newDeck player
where discard = player ^. T.discard
deck = player ^. T.deck
hand = player ^. T.hand
newDeck = unsafePerformIO $ deckShuffle (deck ++ discard ++ hand)
validateBuy :: T.PlayerId -> T.Card -> T.Dominion (T.PlayResult ())
validateBuy playerId card = do
money <- handValue playerId
state <- get
player <- getPlayer playerId
cardGone <- pileEmpty card
return $ do
failIf (money < (card ^. T.cost)) $ printf "Not enough money. You have %d but this card costs %d" money (card ^. T.cost)
failIf cardGone $ printf "We've run out of that card (%s)" (card ^. T.name)
failIf ((player ^. T.buys) < 1) "You don't have any buys remaining!"
validatePlay :: T.PlayerId -> T.Card -> T.Dominion (T.PlayResult ())
validatePlay playerId card = do
player <- getPlayer playerId
return $ do
failIf (not (isAction card)) $ printf "%s is not an action card" (card ^. T.name)
failIf ((player ^. T.actions) < 1) "You don't have any actions remaining!"
failIf (card `notElem` (player ^. T.hand)) $ printf
"You can't play a %s because you don't have it in your hand!" (card ^. T.name)
discardHand :: T.PlayerId -> T.Dominion ()
discardHand playerId = modifyPlayer playerId $ \player -> set T.hand [] $ over T.discard (++ (player ^. T.hand)) player
findIteration :: [T.Option] -> Maybe Int
findIteration [] = Nothing
findIteration (T.Iterations x : xs) = Just x
findIteration (_:xs) = findIteration xs
findLog :: [T.Option] -> Maybe Bool
findLog [] = Nothing
findLog (T.Log x : xs) = Just x
findLog (_:xs) = findLog xs
findCards :: [T.Option] -> Maybe [T.Card]
findCards [] = Nothing
findCards (T.Cards x : xs) = Just x
findCards (_:xs) = findCards xs
most recent first . Returns a list of all the cards drawn ( these cards
drawsUntil :: T.PlayerId -> ([T.Card] -> T.Dominion Bool) -> T.Dominion [T.Card]
drawsUntil = drawsUntil_ []
drawsUntil_ :: [T.Card] -> T.PlayerId -> ([T.Card] -> T.Dominion Bool) -> T.Dominion [T.Card]
drawsUntil_ alreadyDrawn playerId func = do
drawnCards <- drawFromDeck playerId 1
let cards = drawnCards ++ alreadyDrawn
stopDrawing <- func cards
if stopDrawing
then return cards
else drawsUntil_ cards playerId func
trashThisCard :: T.Card -> Bool
trashThisCard card = T.TrashThisCard `elem` (card ^. T.effects)
trashesCard :: T.PlayerId -> T.Card -> T.Dominion ()
playerId `trashesCard` card = do
hasCard <- playerId `has` card
when hasCard $ modifyPlayer playerId (over T.hand (delete card))
discardsCard :: T.PlayerId -> T.Card -> T.Dominion ()
playerId `discardsCard` card = do
hasCard <- playerId `has` card
when hasCard $ modifyPlayer playerId $ over T.hand (delete card) . over T.discard (card:)
returnsCard :: T.PlayerId -> T.Card -> T.Dominion ()
playerId `returnsCard` card = do
hasCard <- playerId `has` card
when hasCard $ modifyPlayer playerId $ over T.hand (delete card) . over T.deck (card:)
discardTopCard :: [T.Card] -> T.Player -> T.Player
discardTopCard cards player = if topCard `elem` cards
then set T.deck (tail deck) . over T.discard (topCard:) $ player
else player
where topCard = head $ player ^. T.deck
deck = player ^. T.deck
returnVPCard :: T.Player -> T.Player
returnVPCard player = let hand = player ^. T.hand
victoryCards = filter isVictory hand
card = head victoryCards
in if CA.moat `elem` hand || null victoryCards
then player
else over T.hand (delete card) $ over T.deck (card:) player
discardsTo :: T.Player -> Int -> T.Player
player `discardsTo` x = set T.hand toKeep . over T.discard (++ toDiscard) $ player
where hand = sortBy (comparing T._cost) $ player ^. T.hand
toDiscard = take (length hand - x) hand
toKeep = hand \\ toDiscard
effects ( like has ` PlusCard 3 ` ) . This function applies the given
usesEffect :: T.PlayerId -> T.CardEffect -> T.Dominion (Maybe T.Followup)
playerId `usesEffect` (T.PlusAction x) = do
log playerId ("+ " ++ show x ++ " actions")
modifyPlayer playerId $ over T.actions (+x)
return Nothing
playerId `usesEffect` (T.PlusCoin x) = do
log playerId ("+ " ++ show x ++ " coin")
modifyPlayer playerId $ over T.extraMoney (+x)
return Nothing
playerId `usesEffect` (T.PlusBuy x) = do
log playerId ("+ " ++ show x ++ " buys")
modifyPlayer playerId $ over T.buys (+x)
return Nothing
playerId `usesEffect` (T.PlusCard x) = do
log playerId ("+ " ++ show x ++ " cards")
drawFromDeck playerId x
return Nothing
playerId `usesEffect` effect@(T.PlayActionCard x) = return $ Just (playerId, effect)
playerId `usesEffect` (T.AdventurerEffect) = do
log playerId "finding the next two treasures from your deck..."
drawnCards <- playerId `drawsUntil` (\cards -> return $ countBy isTreasure cards == 2)
forM_ (filter (not . isTreasure) drawnCards) $ \card -> playerId `discardsCard` card
return Nothing
playerId `usesEffect` (T.BureaucratEffect) = do
card_ <- getCard CA.silver
case card_ of
Nothing -> return ()
Just card -> do
log playerId "+ silver"
modifyPlayer playerId $ over T.deck (card:)
modifyOtherPlayers playerId returnVPCard
return Nothing
playerId `usesEffect` T.CellarEffect = return $ Just (playerId, T.CellarEffect)
playerId `usesEffect` T.ChancellorEffect = return $ Just (playerId, T.ChancellorEffect)
playerId `usesEffect` effect@(T.TrashCards x) = do
log playerId ("Trash up to " ++ show x ++ " cards from your hand.")
return $ Just (playerId, effect)
playerId `usesEffect` effect@(T.OthersPlusCard x) = do
log playerId ("Every other player draws " ++ show x ++ " card.")
state <- get
let players = indices (state ^. T.players) \\ [playerId]
forM_ players $ \pid -> drawFromDeck pid 1
return Nothing
playerId `usesEffect` effect@(T.GainCardUpto x) = do
log playerId ("Gain a card costing up to " ++ show x ++ " coins.")
return $ Just (playerId, effect)
TODO this does n't set aside any action cards .
playerId `usesEffect` = do
log playerId "Drawing to 7 cards..."
drawsUntil playerId $ \_ -> do
player <- getPlayer playerId
return $ length (player ^. T.hand) == 7
return Nothing
NOTE : one side effect of this + council room is :
playerId `usesEffect` effect@(T.OthersDiscardTo x) = do
log playerId ("Every other player discards down to " ++ show x ++ " cards.")
modifyOtherPlayers playerId (`discardsTo` x)
return Nothing
playerId `usesEffect` T.MineEffect = return $ Just (playerId, T.MineEffect)
playerId `usesEffect` T.MoneylenderEffect = do
hasCard <- playerId `has` CA.copper
when hasCard $ do
log playerId "Trashing a copper. +3 coin"
playerId `trashesCard` CA.copper
modifyPlayer playerId $ over T.extraMoney (+3)
return Nothing
playerId `usesEffect` T.RemodelEffect = return $ Just (playerId, T.RemodelEffect)
playerId `usesEffect` T.SpyEffect = return $ Just (playerId, T.SpyEffect)
playerId `usesEffect` T.ThiefEffect = return $ Just (playerId, T.ThiefEffect)
playerId `usesEffect` (T.OthersGainCurse x) = do
log playerId ("All other players gain " ++ show x ++ " curses.")
let card = CA.curse
empty <- pileEmpty card
if empty
then return Nothing
else do
modifyOtherPlayers playerId (over T.discard (card:))
state <- get
times (length (state ^. T.players) - 1) $ do
modify $ over T.cards (decrement card)
return ()
return Nothing
playerId `usesEffect` T.GardensEffect = return Nothing
playerId `usesEffect` _ = return Nothing
makePlayer :: String -> T.Player
makePlayer name = T.Player name [] (7 `cardsOf` CA.copper ++ 3 `cardsOf` CA.estate) [] 1 1 0
gainCardUpTo :: T.PlayerId -> Int -> T.Card -> T.Dominion (T.PlayResult (Maybe [T.Followup]))
gainCardUpTo playerId value card =
if (card ^. T.cost) > value
then return . Left $ printf "Card is too expensive. You can gain a card costing up to %d but this card costs %d" value (card ^. T.cost)
else do
result <- getCard card
case result of
Nothing -> return . Left $ printf "We've run out of that card (%s)" (card ^. T.name)
(Just card_) -> do
modifyPlayer playerId $ over T.discard (card_:)
return $ Right Nothing
|
7bb375f7d5360d54f00d86fc52b431e045285ceb8c408b2e774dca5e06891e02
|
adrieng/pulsar
|
parse.ml
|
This file is part of Pulsar , a temporal functional language .
* Copyright ( C ) 2017
*
* 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 LICENSE file in the top - level directory .
* Copyright (C) 2017 Adrien Guatto
*
* 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 LICENSE file in the top-level directory.
*)
let parse_pulsar_file filename =
Compiler.Prop.set_file filename;
let ic =
try open_in filename
with Sys_error msg ->
let body fmt () =
Format.fprintf fmt "Could not open file %s\n%s" filename msg
in
Compiler.Diagnostic.error ~body ()
in
let lex = Lexer.ctx_from_utf8_channel ~filename ic in
let supplier () =
let tok, start, stop = Lexer.next_token_pos lex in
if !Options.debug
then Format.eprintf "%a @?" Lexer.print_token tok;
tok, start, stop
in
let chk =
let initial_pos =
Lexing.{ pos_fname = filename;
pos_lnum = 0;
pos_bol = 0;
pos_cnum = 0; }
in
Parser.Incremental.file initial_pos
in
let file = Parser.MenhirInterpreter.loop supplier chk in
close_in ic;
file
let pass =
Compiler.Pass.atomic
~pp_out:Raw_tree.T.print_file
~name:"parsing"
parse_pulsar_file
| null |
https://raw.githubusercontent.com/adrieng/pulsar/c3901388659d9c7978b04dce0815e3ff9aea1a0c/pulsar-lib/parse.ml
|
ocaml
|
This file is part of Pulsar , a temporal functional language .
* Copyright ( C ) 2017
*
* 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 LICENSE file in the top - level directory .
* Copyright (C) 2017 Adrien Guatto
*
* 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 LICENSE file in the top-level directory.
*)
let parse_pulsar_file filename =
Compiler.Prop.set_file filename;
let ic =
try open_in filename
with Sys_error msg ->
let body fmt () =
Format.fprintf fmt "Could not open file %s\n%s" filename msg
in
Compiler.Diagnostic.error ~body ()
in
let lex = Lexer.ctx_from_utf8_channel ~filename ic in
let supplier () =
let tok, start, stop = Lexer.next_token_pos lex in
if !Options.debug
then Format.eprintf "%a @?" Lexer.print_token tok;
tok, start, stop
in
let chk =
let initial_pos =
Lexing.{ pos_fname = filename;
pos_lnum = 0;
pos_bol = 0;
pos_cnum = 0; }
in
Parser.Incremental.file initial_pos
in
let file = Parser.MenhirInterpreter.loop supplier chk in
close_in ic;
file
let pass =
Compiler.Pass.atomic
~pp_out:Raw_tree.T.print_file
~name:"parsing"
parse_pulsar_file
|
|
6b0e994ffd7f6dc171b06bd250dee3f7b77002b9b639c1c425c8dca28d54796d
|
grin-compiler/ghc-wpc-sample-programs
|
SemiRing.hs
|
module Agda.Utils.SemiRing where
-- | Semirings (<>).
class SemiRing a where
ozero :: a
oone :: a
oplus :: a -> a -> a
otimes :: a -> a -> a
instance SemiRing () where
ozero = ()
oone = ()
oplus _ _ = ()
otimes _ _ = ()
instance SemiRing a => SemiRing (Maybe a) where
ozero = Nothing
oone = Just oone
oplus Nothing y = y
oplus x Nothing = x
oplus (Just x) (Just y) = Just (oplus x y)
otimes Nothing _ = Nothing
otimes _ Nothing = Nothing
otimes (Just x) (Just y) = Just (otimes x y)
-- | Star semirings
-- (<#Star_semirings>).
class SemiRing a => StarSemiRing a where
ostar :: a -> a
instance StarSemiRing () where
ostar _ = ()
instance StarSemiRing a => StarSemiRing (Maybe a) where
ostar Nothing = oone
ostar (Just x) = Just (ostar x)
| null |
https://raw.githubusercontent.com/grin-compiler/ghc-wpc-sample-programs/0e3a9b8b7cc3fa0da7c77fb7588dd4830fb087f7/Agda-2.6.1/src/full/Agda/Utils/SemiRing.hs
|
haskell
|
| Semirings (<>).
| Star semirings
(<#Star_semirings>).
|
module Agda.Utils.SemiRing where
class SemiRing a where
ozero :: a
oone :: a
oplus :: a -> a -> a
otimes :: a -> a -> a
instance SemiRing () where
ozero = ()
oone = ()
oplus _ _ = ()
otimes _ _ = ()
instance SemiRing a => SemiRing (Maybe a) where
ozero = Nothing
oone = Just oone
oplus Nothing y = y
oplus x Nothing = x
oplus (Just x) (Just y) = Just (oplus x y)
otimes Nothing _ = Nothing
otimes _ Nothing = Nothing
otimes (Just x) (Just y) = Just (otimes x y)
class SemiRing a => StarSemiRing a where
ostar :: a -> a
instance StarSemiRing () where
ostar _ = ()
instance StarSemiRing a => StarSemiRing (Maybe a) where
ostar Nothing = oone
ostar (Just x) = Just (ostar x)
|
8a1d231a0d8c845d084438d853b29ea6bcf8a231e1c456f735f80db4efbcf5df
|
irastypain/sicp-on-language-racket
|
test_exercise_2_09.rkt
|
#lang racket
(require rackunit
"../../src/chapter02/exercise_2_09.rkt"
"../../src/lib/interval-arithmetic.rkt")
(define ab (make-interval 1 3))
(define cd (make-interval 2 5))
(define radius-ab (radius-interval ab))
(define radius-cd (radius-interval cd))
(check-equal? (radius-interval (add-interval ab cd))
(+ (radius-interval ab)
(radius-interval cd))
(printf "test#1 2.09 passed\n"))
(check-equal? (radius-interval (sub-interval ab cd))
(+ (radius-interval ab)
(radius-interval cd))
(printf "test#2 2.09 passed\n"))
| null |
https://raw.githubusercontent.com/irastypain/sicp-on-language-racket/0052f91d3c2432a00e7e15310f416cb77eeb4c9c/test/chapter02/test_exercise_2_09.rkt
|
racket
|
#lang racket
(require rackunit
"../../src/chapter02/exercise_2_09.rkt"
"../../src/lib/interval-arithmetic.rkt")
(define ab (make-interval 1 3))
(define cd (make-interval 2 5))
(define radius-ab (radius-interval ab))
(define radius-cd (radius-interval cd))
(check-equal? (radius-interval (add-interval ab cd))
(+ (radius-interval ab)
(radius-interval cd))
(printf "test#1 2.09 passed\n"))
(check-equal? (radius-interval (sub-interval ab cd))
(+ (radius-interval ab)
(radius-interval cd))
(printf "test#2 2.09 passed\n"))
|
|
674d5094f0a8d461f7878ab0cb40133a4b324025853c59d97a6fb3606db78084
|
keechma/forms
|
re_frame.cljs
|
(ns forms.re-frame
(:require [clojure.string :as str]
[forms.util :refer [key-to-path]]
[forms.dirty :refer [calculate-dirty-fields]]
[re-frame.core :as rf]))
(defn ^:private init-state
[data validator opts]
{:errors {}
:init-data data
:data (or data {})
:cached-dirty-key-paths #{}
:dirty-key-paths #{}
:validator validator
:opts opts})
(defn errors-keypaths
"Calculates the error key paths from the error map. It is used to mark
all invalid key paths as dirty"
([data] (distinct (:results (errors-keypaths data [] {:results []}))))
([data path results]
(reduce-kv (fn [m k v]
(if (= k :$errors$)
(assoc m :results (conj (:results m) path))
(if (or (vector? v) (map? v))
(let [{:keys [results lengths]} m
new-path (conj path k)
child-paths (errors-keypaths v new-path m)
new-results (:results child-paths)]
{:results (concat results new-results)})
(if (nil? v)
m
(assoc m :results (conj (:results m) (conj path k))))))) results data)))
(defn form-path->db-path
[form-path]
(conj form-path [::form]))
(rf/reg-sub ::form
(fn form [db [_ form-path]]
(get-in db (form-path->db-path form-path))))
(rf/reg-sub ::data
(fn data [db [_ form-path]]
(get-in db (conj (form-path->db-path form-path) :data))))
(rf/reg-sub ::cached-dirty-key-paths
(fn data [db [_ form-path]]
(get-in db (conj (form-path->db-path form-path) :cached-dirty-key-paths))))
(rf/reg-sub ::dirty-key-paths
(fn data [db [_ form-path]]
(get-in db (conj (form-path->db-path form-path) :dirty-key-paths))))
(rf/reg-sub ::data-for-path
(fn data-for-path [db [_ form-path key-path]]
(get-in db (into (conj (form-path->db-path form-path) :data) (key-to-path key-path)))))
(rf/reg-sub ::errors
(fn errors [db [_ form-path]]
(get-in db (conj (form-path->db-path form-path) :errors))))
(defn errors-for-path
[db [_ form-path key-path]]
(let [path (key-to-path key-path)
is-dirty? (contains? (:dirty-key-paths (get-in db (form-path->db-path form-path))) path)]
(when is-dirty?
(get-in db (into (conj (form-path->db-path form-path) :errors) (conj path :$errors$))))))
(rf/reg-sub ::errors-for-path
errors-for-path)
(rf/reg-event-db ::init!
(fn init! [db [_ form-path form-data]]
(assoc-in db (form-path->db-path form-path) form-data)))
(defn mark-dirty!
[form-state]
(let [validator (:validator form-state)
errors (validator (:data form-state))
errors-keypaths (errors-keypaths errors)
current-dirty-paths (:dirty-key-paths form-state)]
(assoc form-state
:cached-dirty-key-paths (set (concat (:cached-dirty-key-paths form-state) errors-keypaths))
:dirty-key-paths (set errors-keypaths))))
(defn mark-dirty-paths!
[form-state]
(let [dirty-paths (calculate-dirty-fields (:init-data form-state) (:data form-state))]
(assoc form-state :dirty-key-paths (set (concat dirty-paths
(:cached-dirty-key-paths form-state))))))
(defn validate!
[db [_ form-path dirty-only?]]
(let [dirty-db (if dirty-only?
(update-in db (form-path->db-path form-path) mark-dirty-paths!)
(update-in db (form-path->db-path form-path) mark-dirty!))
validator (:validator (get-in dirty-db (form-path->db-path form-path)))]
(update-in dirty-db (conj (form-path->db-path form-path)) assoc :errors (validator (:data (get-in dirty-db (form-path->db-path form-path)))))))
(rf/reg-event-db ::validate!
validate!)
(rf/reg-event-db ::commit!
(fn commit! [db [_ form-path]]
(let [form-state (get-in db (form-path->db-path form-path))
commit-fn (get-in form-state [:opts :on-commit])
dirty-db (update-in db (form-path->db-path form-path) mark-dirty!)
validated-db (validate! dirty-db [nil form-path])
new-form-state (get-in validated-db (form-path->db-path form-path))]
(commit-fn new-form-state)
validated-db)))
(rf/reg-event-db ::update!
(fn update! [db [_ form-path data]]
(let [updated-db (update-in db (form-path->db-path form-path) assoc :data data)
dirty-db (update-in updated-db (form-path->db-path form-path) mark-dirty-paths!)]
(validate! dirty-db [nil form-path true]))))
(rf/reg-event-db ::mark-dirty!
(fn mark-dirty!-ev [db [_ form-path]]
(update-in db (form-path->db-path form-path) mark-dirty!)))
(rf/reg-event-db ::mark-dirty-paths!
(fn mark-dirty-paths!-ev [db [_ form-path]]
(update-in db (form-path->db-path form-path) mark-dirty-paths!)))
(rf/reg-sub ::dirty-paths-valid?
(fn dirty-paths-valid? [db [_ form-path]]
(let [form-state (get-in db (form-path->db-path form-path))
errors (:errors form-state)
dirty-paths (:dirty-key-paths form-state)
valid-paths (take-while
(fn [path]
(nil? (get-in errors path))) dirty-paths)]
(= (count valid-paths) (count dirty-paths)))))
(rf/reg-event-db ::clear-cached-dirty-key-paths!
(fn mark-dirty-paths!-ev [db [_ form-path]]
(update-in db (form-path->db-path form-path) assoc :cached-dirty-key-paths #{})))
(defn is-valid?
[form-state]
(let [errors (:errors form-state)]
(= errors {})))
(rf/reg-sub ::is-valid?
(fn is-valid?-ev [db [_ form-path]]
(let [form-state (get-in db (form-path->db-path form-path))]
(is-valid? form-state))))
(rf/reg-sub ::is-valid-path?
(fn is-valid-path? [db [_ form-path key-path]]
(nil? (errors-for-path db [nil form-path key-path]))))
(defn ^:private with-default-opts [opts]
(merge {:on-commit (fn on-commit-placeholder [_])
:auto-validate? false} opts))
(rf/reg-event-db ::reset-form!
(fn reset-form! [db [_ form-path init-data*]]
(let [{:keys [:init-data :validator :opts]} (get-in db (form-path->db-path form-path))]
(if init-data*
(update-in db (form-path->db-path form-path) merge (init-state init-data* validator (with-default-opts opts)))
(update-in db (form-path->db-path form-path) merge (init-state init-data validator (with-default-opts opts)))))))
(defn set-value
[db [_ form-path key-path value]]
(let [form-state (get-in db (form-path->db-path form-path))
auto-validate? (get-in form-state [:opts :auto-validate?])
setted-db (assoc-in db (into (conj (form-path->db-path form-path) :data) (key-to-path key-path)) value)]
(if auto-validate?
(let [old-value (get-in db (into (conj (form-path->db-path form-path) :data) (key-to-path key-path)))]
(if (= value old-value)
setted-db
(-> setted-db
(update-in (form-path->db-path form-path) mark-dirty-paths!)
(validate! [nil form-path true]))))
setted-db)))
(rf/reg-event-db ::set! set-value)
(defn constructor
"Form constructor. It accepts the following arguments:
- `validator` - returned either by the `form.validator/validator` or `form.validator/comp-validators` function
- `path` - path in the db where to put the form
- `data` - initial data map
- `opts` - map with the form options:
+ `:on-commit` - function to be called when the form is commited (by calling `(commit! form)`)
+ `:auto-validate?` - should the form be validated on any data change"
([validator] (partial constructor validator))
([validator path] (partial constructor validator path))
([validator path data] (constructor validator path data {}))
([validator path data opts]
(rf/dispatch [::init! path (init-state data validator (with-default-opts opts))])))
| null |
https://raw.githubusercontent.com/keechma/forms/5a9e02b76a4b5efd441f9a71e9831b2161139fdd/src/forms/re_frame.cljs
|
clojure
|
(ns forms.re-frame
(:require [clojure.string :as str]
[forms.util :refer [key-to-path]]
[forms.dirty :refer [calculate-dirty-fields]]
[re-frame.core :as rf]))
(defn ^:private init-state
[data validator opts]
{:errors {}
:init-data data
:data (or data {})
:cached-dirty-key-paths #{}
:dirty-key-paths #{}
:validator validator
:opts opts})
(defn errors-keypaths
"Calculates the error key paths from the error map. It is used to mark
all invalid key paths as dirty"
([data] (distinct (:results (errors-keypaths data [] {:results []}))))
([data path results]
(reduce-kv (fn [m k v]
(if (= k :$errors$)
(assoc m :results (conj (:results m) path))
(if (or (vector? v) (map? v))
(let [{:keys [results lengths]} m
new-path (conj path k)
child-paths (errors-keypaths v new-path m)
new-results (:results child-paths)]
{:results (concat results new-results)})
(if (nil? v)
m
(assoc m :results (conj (:results m) (conj path k))))))) results data)))
(defn form-path->db-path
[form-path]
(conj form-path [::form]))
(rf/reg-sub ::form
(fn form [db [_ form-path]]
(get-in db (form-path->db-path form-path))))
(rf/reg-sub ::data
(fn data [db [_ form-path]]
(get-in db (conj (form-path->db-path form-path) :data))))
(rf/reg-sub ::cached-dirty-key-paths
(fn data [db [_ form-path]]
(get-in db (conj (form-path->db-path form-path) :cached-dirty-key-paths))))
(rf/reg-sub ::dirty-key-paths
(fn data [db [_ form-path]]
(get-in db (conj (form-path->db-path form-path) :dirty-key-paths))))
(rf/reg-sub ::data-for-path
(fn data-for-path [db [_ form-path key-path]]
(get-in db (into (conj (form-path->db-path form-path) :data) (key-to-path key-path)))))
(rf/reg-sub ::errors
(fn errors [db [_ form-path]]
(get-in db (conj (form-path->db-path form-path) :errors))))
(defn errors-for-path
[db [_ form-path key-path]]
(let [path (key-to-path key-path)
is-dirty? (contains? (:dirty-key-paths (get-in db (form-path->db-path form-path))) path)]
(when is-dirty?
(get-in db (into (conj (form-path->db-path form-path) :errors) (conj path :$errors$))))))
(rf/reg-sub ::errors-for-path
errors-for-path)
(rf/reg-event-db ::init!
(fn init! [db [_ form-path form-data]]
(assoc-in db (form-path->db-path form-path) form-data)))
(defn mark-dirty!
[form-state]
(let [validator (:validator form-state)
errors (validator (:data form-state))
errors-keypaths (errors-keypaths errors)
current-dirty-paths (:dirty-key-paths form-state)]
(assoc form-state
:cached-dirty-key-paths (set (concat (:cached-dirty-key-paths form-state) errors-keypaths))
:dirty-key-paths (set errors-keypaths))))
(defn mark-dirty-paths!
[form-state]
(let [dirty-paths (calculate-dirty-fields (:init-data form-state) (:data form-state))]
(assoc form-state :dirty-key-paths (set (concat dirty-paths
(:cached-dirty-key-paths form-state))))))
(defn validate!
[db [_ form-path dirty-only?]]
(let [dirty-db (if dirty-only?
(update-in db (form-path->db-path form-path) mark-dirty-paths!)
(update-in db (form-path->db-path form-path) mark-dirty!))
validator (:validator (get-in dirty-db (form-path->db-path form-path)))]
(update-in dirty-db (conj (form-path->db-path form-path)) assoc :errors (validator (:data (get-in dirty-db (form-path->db-path form-path)))))))
(rf/reg-event-db ::validate!
validate!)
(rf/reg-event-db ::commit!
(fn commit! [db [_ form-path]]
(let [form-state (get-in db (form-path->db-path form-path))
commit-fn (get-in form-state [:opts :on-commit])
dirty-db (update-in db (form-path->db-path form-path) mark-dirty!)
validated-db (validate! dirty-db [nil form-path])
new-form-state (get-in validated-db (form-path->db-path form-path))]
(commit-fn new-form-state)
validated-db)))
(rf/reg-event-db ::update!
(fn update! [db [_ form-path data]]
(let [updated-db (update-in db (form-path->db-path form-path) assoc :data data)
dirty-db (update-in updated-db (form-path->db-path form-path) mark-dirty-paths!)]
(validate! dirty-db [nil form-path true]))))
(rf/reg-event-db ::mark-dirty!
(fn mark-dirty!-ev [db [_ form-path]]
(update-in db (form-path->db-path form-path) mark-dirty!)))
(rf/reg-event-db ::mark-dirty-paths!
(fn mark-dirty-paths!-ev [db [_ form-path]]
(update-in db (form-path->db-path form-path) mark-dirty-paths!)))
(rf/reg-sub ::dirty-paths-valid?
(fn dirty-paths-valid? [db [_ form-path]]
(let [form-state (get-in db (form-path->db-path form-path))
errors (:errors form-state)
dirty-paths (:dirty-key-paths form-state)
valid-paths (take-while
(fn [path]
(nil? (get-in errors path))) dirty-paths)]
(= (count valid-paths) (count dirty-paths)))))
(rf/reg-event-db ::clear-cached-dirty-key-paths!
(fn mark-dirty-paths!-ev [db [_ form-path]]
(update-in db (form-path->db-path form-path) assoc :cached-dirty-key-paths #{})))
(defn is-valid?
[form-state]
(let [errors (:errors form-state)]
(= errors {})))
(rf/reg-sub ::is-valid?
(fn is-valid?-ev [db [_ form-path]]
(let [form-state (get-in db (form-path->db-path form-path))]
(is-valid? form-state))))
(rf/reg-sub ::is-valid-path?
(fn is-valid-path? [db [_ form-path key-path]]
(nil? (errors-for-path db [nil form-path key-path]))))
(defn ^:private with-default-opts [opts]
(merge {:on-commit (fn on-commit-placeholder [_])
:auto-validate? false} opts))
(rf/reg-event-db ::reset-form!
(fn reset-form! [db [_ form-path init-data*]]
(let [{:keys [:init-data :validator :opts]} (get-in db (form-path->db-path form-path))]
(if init-data*
(update-in db (form-path->db-path form-path) merge (init-state init-data* validator (with-default-opts opts)))
(update-in db (form-path->db-path form-path) merge (init-state init-data validator (with-default-opts opts)))))))
(defn set-value
[db [_ form-path key-path value]]
(let [form-state (get-in db (form-path->db-path form-path))
auto-validate? (get-in form-state [:opts :auto-validate?])
setted-db (assoc-in db (into (conj (form-path->db-path form-path) :data) (key-to-path key-path)) value)]
(if auto-validate?
(let [old-value (get-in db (into (conj (form-path->db-path form-path) :data) (key-to-path key-path)))]
(if (= value old-value)
setted-db
(-> setted-db
(update-in (form-path->db-path form-path) mark-dirty-paths!)
(validate! [nil form-path true]))))
setted-db)))
(rf/reg-event-db ::set! set-value)
(defn constructor
"Form constructor. It accepts the following arguments:
- `validator` - returned either by the `form.validator/validator` or `form.validator/comp-validators` function
- `path` - path in the db where to put the form
- `data` - initial data map
- `opts` - map with the form options:
+ `:on-commit` - function to be called when the form is commited (by calling `(commit! form)`)
+ `:auto-validate?` - should the form be validated on any data change"
([validator] (partial constructor validator))
([validator path] (partial constructor validator path))
([validator path data] (constructor validator path data {}))
([validator path data opts]
(rf/dispatch [::init! path (init-state data validator (with-default-opts opts))])))
|
|
0d60f242690969b351724a0ca0229c7fc5c562f57f8022958019332d10b7e362
|
mainland/nikola
|
Mutable.hs
|
# LANGUAGE CPP #
{-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE ScopedTypeVariables #
-- |
-- Module : Data.Vector.Storable.Mutable
Copyright : ( c ) Roman Leshchinskiy 2009 - 2010
Copyright : ( c ) 2012
-- License : BSD-style
--
Maintainer : < >
-- Stability : experimental
-- Portability : non-portable
--
Mutable vectors based on .
--
module Data.Vector.CUDA.Storable.Mutable (
* Mutable vectors of ' ' types
MVector(..), IOVector, STVector, Storable,
-- * Accessors
-- ** Length information
length, null,
-- ** Extracting subvectors
slice, init, tail, take, drop, splitAt,
unsafeSlice, unsafeInit, unsafeTail, unsafeTake, unsafeDrop,
-- ** Overlapping
overlaps,
-- * Construction
-- ** Initialisation
new, unsafeNew, replicate, replicateM, clone,
-- ** Growing
grow, unsafeGrow,
-- ** Restricting memory usage
clear,
-- * Accessing individual elements
read, write, swap,
unsafeRead, unsafeWrite, unsafeSwap,
-- * Modifying vectors
-- ** Filling and copying
set, copy, move, unsafeCopy, unsafeMove,
-- * Unsafe conversions
unsafeCast,
-- * Raw pointers
unsafeFromForeignDevPtr, unsafeFromForeignDevPtr0,
unsafeToForeignDevPtr, unsafeToForeignDevPtr0,
unsafeWith
) where
import Prelude hiding ( length, null, replicate, reverse, map, read,
take, drop, splitAt, init, tail )
import Control.Monad.Primitive
import Data.Typeable (Typeable)
import qualified Data.Vector.Generic.Mutable as G
import Data.Vector.CUDA.Storable.Internal
import Foreign.CUDA.Driver.Marshal
import Foreign.CUDA.ForeignPtr
import Foreign.CUDA.Ptr
import Foreign.CUDA.Storable
import Foreign.Storable
-- | Mutable 'Storable'-based CUDA vectors
data MVector s a = MVector {-# UNPACK #-} !Int
{-# UNPACK #-} !(ForeignDevicePtr a)
deriving ( Typeable )
type IOVector = MVector RealWorld
type STVector s = MVector s
instance Storable a => G.MVector MVector a where
# INLINE basicLength #
basicLength (MVector n _) = n
# INLINE basicUnsafeSlice #
basicUnsafeSlice j m (MVector _ fp) = MVector m (updPtr (`advanceDevPtr` j) fp)
-- FIXME: this relies on non-portable pointer comparisons
# INLINE basicOverlaps #
basicOverlaps (MVector m fp) (MVector n fq)
= between p q (q `advanceDevPtr` n) || between q p (p `advanceDevPtr` m)
where
between x y z = x >= y && x < z
p = getPtr fp
q = getPtr fq
# INLINE basicUnsafeNew #
basicUnsafeNew n
= unsafePrimToPrim
$ do
fp <- mallocVector n
return $ MVector n fp
# INLINE basicUnsafeRead #
basicUnsafeRead (MVector _ fp) i
= unsafePrimToPrim
$ withForeignDevPtr fp (`peekDevElemOff` i)
# INLINE basicUnsafeWrite #
basicUnsafeWrite (MVector _ fp) i x
= unsafePrimToPrim
$ withForeignDevPtr fp $ \p -> pokeDevElemOff p i x
# INLINE basicUnsafeCopy #
basicUnsafeCopy (MVector n fp) (MVector _ fq)
= unsafePrimToPrim
$ withForeignDevPtr fp $ \p ->
withForeignDevPtr fq $ \q ->
copyArrayAsync n q p
# INLINE mallocVector #
mallocVector :: Storable a => Int -> IO (ForeignDevicePtr a)
mallocVector = mallocForeignDevPtrArray
-- Length information
-- ------------------
-- | Length of the mutable vector.
length :: Storable a => MVector s a -> Int
# INLINE length #
length = G.length
-- | Check whether the vector is empty
null :: Storable a => MVector s a -> Bool
# INLINE null #
null = G.null
-- Extracting subvectors
-- ---------------------
-- | Yield a part of the mutable vector without copying it.
slice :: Storable a => Int -> Int -> MVector s a -> MVector s a
# INLINE slice #
slice = G.slice
take :: Storable a => Int -> MVector s a -> MVector s a
{-# INLINE take #-}
take = G.take
drop :: Storable a => Int -> MVector s a -> MVector s a
{-# INLINE drop #-}
drop = G.drop
splitAt :: Storable a => Int -> MVector s a -> (MVector s a, MVector s a)
# INLINE splitAt #
splitAt = G.splitAt
init :: Storable a => MVector s a -> MVector s a
# INLINE init #
init = G.init
tail :: Storable a => MVector s a -> MVector s a
# INLINE tail #
tail = G.tail
-- | Yield a part of the mutable vector without copying it. No bounds checks
-- are performed.
unsafeSlice :: Storable a
=> Int -- ^ starting index
-> Int -- ^ length of the slice
-> MVector s a
-> MVector s a
# INLINE unsafeSlice #
unsafeSlice = G.unsafeSlice
unsafeTake :: Storable a => Int -> MVector s a -> MVector s a
# INLINE unsafeTake #
unsafeTake = G.unsafeTake
unsafeDrop :: Storable a => Int -> MVector s a -> MVector s a
# INLINE unsafeDrop #
unsafeDrop = G.unsafeDrop
unsafeInit :: Storable a => MVector s a -> MVector s a
{-# INLINE unsafeInit #-}
unsafeInit = G.unsafeInit
unsafeTail :: Storable a => MVector s a -> MVector s a
# INLINE unsafeTail #
unsafeTail = G.unsafeTail
-- Overlapping
-- -----------
Check whether two vectors overlap .
overlaps :: Storable a => MVector s a -> MVector s a -> Bool
# INLINE overlaps #
overlaps = G.overlaps
-- Initialisation
-- --------------
-- | Create a mutable vector of the given length.
new :: (PrimMonad m, Storable a) => Int -> m (MVector (PrimState m) a)
{-# INLINE new #-}
new = G.new
-- | Create a mutable vector of the given length. The length is not checked.
unsafeNew :: (PrimMonad m, Storable a) => Int -> m (MVector (PrimState m) a)
# INLINE unsafeNew #
unsafeNew = G.unsafeNew
-- | Create a mutable vector of the given length (0 if the length is negative)
-- and fill it with an initial value.
replicate :: (PrimMonad m, Storable a) => Int -> a -> m (MVector (PrimState m) a)
# INLINE replicate #
replicate = G.replicate
-- | Create a mutable vector of the given length (0 if the length is negative)
-- and fill it with values produced by repeatedly executing the monadic action.
replicateM :: (PrimMonad m, Storable a) => Int -> m a -> m (MVector (PrimState m) a)
# INLINE replicateM #
replicateM = G.replicateM
-- | Create a copy of a mutable vector.
clone :: (PrimMonad m, Storable a)
=> MVector (PrimState m) a -> m (MVector (PrimState m) a)
# INLINE clone #
clone = G.clone
-- Growing
-- -------
-- | Grow a vector by the given number of elements. The number must be
-- positive.
grow :: (PrimMonad m, Storable a)
=> MVector (PrimState m) a -> Int -> m (MVector (PrimState m) a)
# INLINE grow #
grow = G.grow
-- | Grow a vector by the given number of elements. The number must be
-- positive but this is not checked.
unsafeGrow :: (PrimMonad m, Storable a)
=> MVector (PrimState m) a -> Int -> m (MVector (PrimState m) a)
# INLINE unsafeGrow #
unsafeGrow = G.unsafeGrow
-- Restricting memory usage
-- ------------------------
-- | Reset all elements of the vector to some undefined value, clearing all
-- references to external objects. This is usually a noop for unboxed vectors.
clear :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> m ()
# INLINE clear #
clear = G.clear
-- Accessing individual elements
-- -----------------------------
-- | Yield the element at the given position.
read :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> Int -> m a
# INLINE read #
read = G.read
-- | Replace the element at the given position.
write
:: (PrimMonad m, Storable a) => MVector (PrimState m) a -> Int -> a -> m ()
# INLINE write #
write = G.write
-- | Swap the elements at the given positions.
swap
:: (PrimMonad m, Storable a) => MVector (PrimState m) a -> Int -> Int -> m ()
# INLINE swap #
swap = G.swap
-- | Yield the element at the given position. No bounds checks are performed.
unsafeRead :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> Int -> m a
# INLINE unsafeRead #
unsafeRead = G.unsafeRead
-- | Replace the element at the given position. No bounds checks are performed.
unsafeWrite
:: (PrimMonad m, Storable a) => MVector (PrimState m) a -> Int -> a -> m ()
# INLINE unsafeWrite #
unsafeWrite = G.unsafeWrite
-- | Swap the elements at the given positions. No bounds checks are performed.
unsafeSwap
:: (PrimMonad m, Storable a) => MVector (PrimState m) a -> Int -> Int -> m ()
# INLINE unsafeSwap #
unsafeSwap = G.unsafeSwap
-- Filling and copying
-- -------------------
-- | Set all elements of the vector to the given value.
set :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> a -> m ()
{-# INLINE set #-}
set = G.set
| Copy a vector . The two vectors must have the same length and may not
-- overlap.
copy :: (PrimMonad m, Storable a)
=> MVector (PrimState m) a -> MVector (PrimState m) a -> m ()
# INLINE copy #
copy = G.copy
| Copy a vector . The two vectors must have the same length and may not
-- overlap. This is not checked.
unsafeCopy :: (PrimMonad m, Storable a)
=> MVector (PrimState m) a -- ^ target
-> MVector (PrimState m) a -- ^ source
-> m ()
# INLINE unsafeCopy #
unsafeCopy = G.unsafeCopy
| Move the contents of a vector . The two vectors must have the same
-- length.
--
-- If the vectors do not overlap, then this is equivalent to 'copy'.
-- Otherwise, the copying is performed as if the source vector were
-- copied to a temporary vector and then the temporary vector was copied
-- to the target vector.
move :: (PrimMonad m, Storable a)
=> MVector (PrimState m) a -> MVector (PrimState m) a -> m ()
# INLINE move #
move = G.move
| Move the contents of a vector . The two vectors must have the same
-- length, but this is not checked.
--
-- If the vectors do not overlap, then this is equivalent to 'unsafeCopy'.
-- Otherwise, the copying is performed as if the source vector were
-- copied to a temporary vector and then the temporary vector was copied
-- to the target vector.
unsafeMove :: (PrimMonad m, Storable a)
=> MVector (PrimState m) a -- ^ target
-> MVector (PrimState m) a -- ^ source
-> m ()
# INLINE unsafeMove #
unsafeMove = G.unsafeMove
-- Unsafe conversions
-- ------------------
| /O(1)/ Unsafely cast a mutable vector from one element type to another .
-- The operation just changes the type of the underlying pointer and does not
-- modify the elements.
--
-- The resulting vector contains as many elements as can fit into the
-- underlying memory block.
--
unsafeCast :: forall a b s.
(Storable a, Storable b) => MVector s a -> MVector s b
# INLINE unsafeCast #
unsafeCast (MVector n fp)
= MVector ((n * sizeOf (undefined :: a)) `div` sizeOf (undefined :: b))
(castForeignDevPtr fp)
-- Raw pointers
-- ------------
-- | Create a mutable vector from a 'ForeignPtr' with an offset and a length.
--
-- Modifying data through the 'ForeignPtr' afterwards is unsafe if the vector
-- could have been frozen before the modification.
--
-- If your offset is 0 it is more efficient to use 'unsafeFromForeignDevPtr0'.
unsafeFromForeignDevPtr :: Storable a
=> ForeignDevicePtr a -- ^ pointer
-> Int -- ^ offset
-> Int -- ^ length
-> MVector s a
# INLINE unsafeFromForeignDevPtr #
unsafeFromForeignDevPtr fp i n = unsafeFromForeignDevPtr0 fp' n
where
fp' = updPtr (`advanceDevPtr` i) fp
# RULES
" unsafeFromForeignDevPtr fp 0 n - > unsafeFromForeignDevPtr0 fp n " forall fp n.
unsafeFromForeignDevPtr fp 0 n = unsafeFromForeignDevPtr0 fp n
#
"unsafeFromForeignDevPtr fp 0 n -> unsafeFromForeignDevPtr0 fp n " forall fp n.
unsafeFromForeignDevPtr fp 0 n = unsafeFromForeignDevPtr0 fp n
#-}
-- | /O(1)/ Create a mutable vector from a 'ForeignDevicePtr' and a length.
--
-- It is assumed the pointer points directly to the data (no offset). Use
-- `unsafeFromForeignDevPtr` if you need to specify an offset.
--
-- Modifying data through the 'ForeignDevicePtr' afterwards is unsafe if the
-- vector could have been frozen before the modification.
unsafeFromForeignDevPtr0 :: Storable a
=> ForeignDevicePtr a -- ^ pointer
-> Int -- ^ length
-> MVector s a
# INLINE unsafeFromForeignDevPtr0 #
unsafeFromForeignDevPtr0 fp n = MVector n fp
-- | Yield the underlying 'ForeignDevicePtr' together with the offset to the
-- data and its length. Modifying the data through the 'ForeignDevicePtr' is
-- unsafe if the vector could have frozen before the modification.
unsafeToForeignDevPtr :: Storable a => MVector s a -> (ForeignDevicePtr a, Int, Int)
# INLINE unsafeToForeignDevPtr #
unsafeToForeignDevPtr (MVector n fp) = (fp, 0, n)
-- | /O(1)/ Yield the underlying 'ForeignDevicePtr' together with its length.
--
-- You can assume the pointer points directly to the data (no offset).
--
-- Modifying the data through the 'ForeignDevicePtr' is unsafe if the vector
-- could have frozen before the modification.
unsafeToForeignDevPtr0 :: Storable a => MVector s a -> (ForeignDevicePtr a, Int)
# INLINE unsafeToForeignDevPtr0 #
unsafeToForeignDevPtr0 (MVector n fp) = (fp, n)
| Pass a pointer to the vector 's data to the IO action . Modifying data
-- through the pointer is unsafe if the vector could have been frozen before the
-- modification.
unsafeWith :: Storable a => IOVector a -> (DevicePtr a -> IO b) -> IO b
# INLINE unsafeWith #
unsafeWith (MVector _ fp) = withForeignDevPtr fp
| null |
https://raw.githubusercontent.com/mainland/nikola/d86398888c0a76f8ad1556a269a708de9dd92644/src/Data/Vector/CUDA/Storable/Mutable.hs
|
haskell
|
# LANGUAGE DeriveDataTypeable #
|
Module : Data.Vector.Storable.Mutable
License : BSD-style
Stability : experimental
Portability : non-portable
* Accessors
** Length information
** Extracting subvectors
** Overlapping
* Construction
** Initialisation
** Growing
** Restricting memory usage
* Accessing individual elements
* Modifying vectors
** Filling and copying
* Unsafe conversions
* Raw pointers
| Mutable 'Storable'-based CUDA vectors
# UNPACK #
# UNPACK #
FIXME: this relies on non-portable pointer comparisons
Length information
------------------
| Length of the mutable vector.
| Check whether the vector is empty
Extracting subvectors
---------------------
| Yield a part of the mutable vector without copying it.
# INLINE take #
# INLINE drop #
| Yield a part of the mutable vector without copying it. No bounds checks
are performed.
^ starting index
^ length of the slice
# INLINE unsafeInit #
Overlapping
-----------
Initialisation
--------------
| Create a mutable vector of the given length.
# INLINE new #
| Create a mutable vector of the given length. The length is not checked.
| Create a mutable vector of the given length (0 if the length is negative)
and fill it with an initial value.
| Create a mutable vector of the given length (0 if the length is negative)
and fill it with values produced by repeatedly executing the monadic action.
| Create a copy of a mutable vector.
Growing
-------
| Grow a vector by the given number of elements. The number must be
positive.
| Grow a vector by the given number of elements. The number must be
positive but this is not checked.
Restricting memory usage
------------------------
| Reset all elements of the vector to some undefined value, clearing all
references to external objects. This is usually a noop for unboxed vectors.
Accessing individual elements
-----------------------------
| Yield the element at the given position.
| Replace the element at the given position.
| Swap the elements at the given positions.
| Yield the element at the given position. No bounds checks are performed.
| Replace the element at the given position. No bounds checks are performed.
| Swap the elements at the given positions. No bounds checks are performed.
Filling and copying
-------------------
| Set all elements of the vector to the given value.
# INLINE set #
overlap.
overlap. This is not checked.
^ target
^ source
length.
If the vectors do not overlap, then this is equivalent to 'copy'.
Otherwise, the copying is performed as if the source vector were
copied to a temporary vector and then the temporary vector was copied
to the target vector.
length, but this is not checked.
If the vectors do not overlap, then this is equivalent to 'unsafeCopy'.
Otherwise, the copying is performed as if the source vector were
copied to a temporary vector and then the temporary vector was copied
to the target vector.
^ target
^ source
Unsafe conversions
------------------
The operation just changes the type of the underlying pointer and does not
modify the elements.
The resulting vector contains as many elements as can fit into the
underlying memory block.
Raw pointers
------------
| Create a mutable vector from a 'ForeignPtr' with an offset and a length.
Modifying data through the 'ForeignPtr' afterwards is unsafe if the vector
could have been frozen before the modification.
If your offset is 0 it is more efficient to use 'unsafeFromForeignDevPtr0'.
^ pointer
^ offset
^ length
| /O(1)/ Create a mutable vector from a 'ForeignDevicePtr' and a length.
It is assumed the pointer points directly to the data (no offset). Use
`unsafeFromForeignDevPtr` if you need to specify an offset.
Modifying data through the 'ForeignDevicePtr' afterwards is unsafe if the
vector could have been frozen before the modification.
^ pointer
^ length
| Yield the underlying 'ForeignDevicePtr' together with the offset to the
data and its length. Modifying the data through the 'ForeignDevicePtr' is
unsafe if the vector could have frozen before the modification.
| /O(1)/ Yield the underlying 'ForeignDevicePtr' together with its length.
You can assume the pointer points directly to the data (no offset).
Modifying the data through the 'ForeignDevicePtr' is unsafe if the vector
could have frozen before the modification.
through the pointer is unsafe if the vector could have been frozen before the
modification.
|
# LANGUAGE CPP #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE ScopedTypeVariables #
Copyright : ( c ) Roman Leshchinskiy 2009 - 2010
Copyright : ( c ) 2012
Maintainer : < >
Mutable vectors based on .
module Data.Vector.CUDA.Storable.Mutable (
* Mutable vectors of ' ' types
MVector(..), IOVector, STVector, Storable,
length, null,
slice, init, tail, take, drop, splitAt,
unsafeSlice, unsafeInit, unsafeTail, unsafeTake, unsafeDrop,
overlaps,
new, unsafeNew, replicate, replicateM, clone,
grow, unsafeGrow,
clear,
read, write, swap,
unsafeRead, unsafeWrite, unsafeSwap,
set, copy, move, unsafeCopy, unsafeMove,
unsafeCast,
unsafeFromForeignDevPtr, unsafeFromForeignDevPtr0,
unsafeToForeignDevPtr, unsafeToForeignDevPtr0,
unsafeWith
) where
import Prelude hiding ( length, null, replicate, reverse, map, read,
take, drop, splitAt, init, tail )
import Control.Monad.Primitive
import Data.Typeable (Typeable)
import qualified Data.Vector.Generic.Mutable as G
import Data.Vector.CUDA.Storable.Internal
import Foreign.CUDA.Driver.Marshal
import Foreign.CUDA.ForeignPtr
import Foreign.CUDA.Ptr
import Foreign.CUDA.Storable
import Foreign.Storable
deriving ( Typeable )
type IOVector = MVector RealWorld
type STVector s = MVector s
instance Storable a => G.MVector MVector a where
# INLINE basicLength #
basicLength (MVector n _) = n
# INLINE basicUnsafeSlice #
basicUnsafeSlice j m (MVector _ fp) = MVector m (updPtr (`advanceDevPtr` j) fp)
# INLINE basicOverlaps #
basicOverlaps (MVector m fp) (MVector n fq)
= between p q (q `advanceDevPtr` n) || between q p (p `advanceDevPtr` m)
where
between x y z = x >= y && x < z
p = getPtr fp
q = getPtr fq
# INLINE basicUnsafeNew #
basicUnsafeNew n
= unsafePrimToPrim
$ do
fp <- mallocVector n
return $ MVector n fp
# INLINE basicUnsafeRead #
basicUnsafeRead (MVector _ fp) i
= unsafePrimToPrim
$ withForeignDevPtr fp (`peekDevElemOff` i)
# INLINE basicUnsafeWrite #
basicUnsafeWrite (MVector _ fp) i x
= unsafePrimToPrim
$ withForeignDevPtr fp $ \p -> pokeDevElemOff p i x
# INLINE basicUnsafeCopy #
basicUnsafeCopy (MVector n fp) (MVector _ fq)
= unsafePrimToPrim
$ withForeignDevPtr fp $ \p ->
withForeignDevPtr fq $ \q ->
copyArrayAsync n q p
# INLINE mallocVector #
mallocVector :: Storable a => Int -> IO (ForeignDevicePtr a)
mallocVector = mallocForeignDevPtrArray
length :: Storable a => MVector s a -> Int
# INLINE length #
length = G.length
null :: Storable a => MVector s a -> Bool
# INLINE null #
null = G.null
slice :: Storable a => Int -> Int -> MVector s a -> MVector s a
# INLINE slice #
slice = G.slice
take :: Storable a => Int -> MVector s a -> MVector s a
take = G.take
drop :: Storable a => Int -> MVector s a -> MVector s a
drop = G.drop
splitAt :: Storable a => Int -> MVector s a -> (MVector s a, MVector s a)
# INLINE splitAt #
splitAt = G.splitAt
init :: Storable a => MVector s a -> MVector s a
# INLINE init #
init = G.init
tail :: Storable a => MVector s a -> MVector s a
# INLINE tail #
tail = G.tail
unsafeSlice :: Storable a
-> MVector s a
-> MVector s a
# INLINE unsafeSlice #
unsafeSlice = G.unsafeSlice
unsafeTake :: Storable a => Int -> MVector s a -> MVector s a
# INLINE unsafeTake #
unsafeTake = G.unsafeTake
unsafeDrop :: Storable a => Int -> MVector s a -> MVector s a
# INLINE unsafeDrop #
unsafeDrop = G.unsafeDrop
unsafeInit :: Storable a => MVector s a -> MVector s a
unsafeInit = G.unsafeInit
unsafeTail :: Storable a => MVector s a -> MVector s a
# INLINE unsafeTail #
unsafeTail = G.unsafeTail
Check whether two vectors overlap .
overlaps :: Storable a => MVector s a -> MVector s a -> Bool
# INLINE overlaps #
overlaps = G.overlaps
new :: (PrimMonad m, Storable a) => Int -> m (MVector (PrimState m) a)
new = G.new
unsafeNew :: (PrimMonad m, Storable a) => Int -> m (MVector (PrimState m) a)
# INLINE unsafeNew #
unsafeNew = G.unsafeNew
replicate :: (PrimMonad m, Storable a) => Int -> a -> m (MVector (PrimState m) a)
# INLINE replicate #
replicate = G.replicate
replicateM :: (PrimMonad m, Storable a) => Int -> m a -> m (MVector (PrimState m) a)
# INLINE replicateM #
replicateM = G.replicateM
clone :: (PrimMonad m, Storable a)
=> MVector (PrimState m) a -> m (MVector (PrimState m) a)
# INLINE clone #
clone = G.clone
grow :: (PrimMonad m, Storable a)
=> MVector (PrimState m) a -> Int -> m (MVector (PrimState m) a)
# INLINE grow #
grow = G.grow
unsafeGrow :: (PrimMonad m, Storable a)
=> MVector (PrimState m) a -> Int -> m (MVector (PrimState m) a)
# INLINE unsafeGrow #
unsafeGrow = G.unsafeGrow
clear :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> m ()
# INLINE clear #
clear = G.clear
read :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> Int -> m a
# INLINE read #
read = G.read
write
:: (PrimMonad m, Storable a) => MVector (PrimState m) a -> Int -> a -> m ()
# INLINE write #
write = G.write
swap
:: (PrimMonad m, Storable a) => MVector (PrimState m) a -> Int -> Int -> m ()
# INLINE swap #
swap = G.swap
unsafeRead :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> Int -> m a
# INLINE unsafeRead #
unsafeRead = G.unsafeRead
unsafeWrite
:: (PrimMonad m, Storable a) => MVector (PrimState m) a -> Int -> a -> m ()
# INLINE unsafeWrite #
unsafeWrite = G.unsafeWrite
unsafeSwap
:: (PrimMonad m, Storable a) => MVector (PrimState m) a -> Int -> Int -> m ()
# INLINE unsafeSwap #
unsafeSwap = G.unsafeSwap
set :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> a -> m ()
set = G.set
| Copy a vector . The two vectors must have the same length and may not
copy :: (PrimMonad m, Storable a)
=> MVector (PrimState m) a -> MVector (PrimState m) a -> m ()
# INLINE copy #
copy = G.copy
| Copy a vector . The two vectors must have the same length and may not
unsafeCopy :: (PrimMonad m, Storable a)
-> m ()
# INLINE unsafeCopy #
unsafeCopy = G.unsafeCopy
| Move the contents of a vector . The two vectors must have the same
move :: (PrimMonad m, Storable a)
=> MVector (PrimState m) a -> MVector (PrimState m) a -> m ()
# INLINE move #
move = G.move
| Move the contents of a vector . The two vectors must have the same
unsafeMove :: (PrimMonad m, Storable a)
-> m ()
# INLINE unsafeMove #
unsafeMove = G.unsafeMove
| /O(1)/ Unsafely cast a mutable vector from one element type to another .
unsafeCast :: forall a b s.
(Storable a, Storable b) => MVector s a -> MVector s b
# INLINE unsafeCast #
unsafeCast (MVector n fp)
= MVector ((n * sizeOf (undefined :: a)) `div` sizeOf (undefined :: b))
(castForeignDevPtr fp)
unsafeFromForeignDevPtr :: Storable a
-> MVector s a
# INLINE unsafeFromForeignDevPtr #
unsafeFromForeignDevPtr fp i n = unsafeFromForeignDevPtr0 fp' n
where
fp' = updPtr (`advanceDevPtr` i) fp
# RULES
" unsafeFromForeignDevPtr fp 0 n - > unsafeFromForeignDevPtr0 fp n " forall fp n.
unsafeFromForeignDevPtr fp 0 n = unsafeFromForeignDevPtr0 fp n
#
"unsafeFromForeignDevPtr fp 0 n -> unsafeFromForeignDevPtr0 fp n " forall fp n.
unsafeFromForeignDevPtr fp 0 n = unsafeFromForeignDevPtr0 fp n
#-}
unsafeFromForeignDevPtr0 :: Storable a
-> MVector s a
# INLINE unsafeFromForeignDevPtr0 #
unsafeFromForeignDevPtr0 fp n = MVector n fp
unsafeToForeignDevPtr :: Storable a => MVector s a -> (ForeignDevicePtr a, Int, Int)
# INLINE unsafeToForeignDevPtr #
unsafeToForeignDevPtr (MVector n fp) = (fp, 0, n)
unsafeToForeignDevPtr0 :: Storable a => MVector s a -> (ForeignDevicePtr a, Int)
# INLINE unsafeToForeignDevPtr0 #
unsafeToForeignDevPtr0 (MVector n fp) = (fp, n)
| Pass a pointer to the vector 's data to the IO action . Modifying data
unsafeWith :: Storable a => IOVector a -> (DevicePtr a -> IO b) -> IO b
# INLINE unsafeWith #
unsafeWith (MVector _ fp) = withForeignDevPtr fp
|
f3b3c3587997c49fa4624d8a61e8fa0f4ae2dfebe2a2a86558401b4b5c4b7868
|
xapi-project/xen-api
|
test_rrdd_monitor.ml
|
let ds_a =
Ds.ds_make ~name:"ds_a" ~units:"(fraction)" ~description:"datasource a"
~value:(Rrd.VT_Float 1.0) ~ty:Rrd.Gauge ~default:true ()
let ds_b =
Ds.ds_make ~name:"ds_b" ~units:"(fraction)" ~description:"datasource b"
~value:(Rrd.VT_Float 2.0) ~ty:Rrd.Gauge ~default:true ()
let reset_rrdd_shared_state () =
Hashtbl.clear Rrdd_shared.vm_rrds ;
Rrdd_shared.host_rrd := None
let pp_ds =
Fmt.(
Dump.record
[
Dump.field "ds_name" (fun t -> t.Ds.ds_name) string
; Dump.field "ds_description" (fun t -> t.Ds.ds_description) string
; Dump.field "ds_default" (fun t -> t.Ds.ds_default) bool
; Dump.field "ds_min" (fun t -> t.Ds.ds_min) float
; Dump.field "ds_max" (fun t -> t.Ds.ds_max) float
; Dump.field "ds_units" (fun t -> t.Ds.ds_units) string
]
)
let ds = Alcotest.testable pp_ds (fun a b -> String.equal a.ds_name b.ds_name)
let dss_of_rrds rrds =
Hashtbl.fold (fun k v acc -> (k, v.Rrdd_shared.dss) :: acc) rrds []
|> List.fast_sort Stdlib.compare
let check_datasources kind rdds expected_dss =
match rdds with
| None when expected_dss <> [] ->
Alcotest.fail (Printf.sprintf "%s RRD must be created" kind)
| None ->
()
| Some actual_rdds ->
let actual_dss = dss_of_rrds actual_rdds in
let expected_dss = List.fast_sort Stdlib.compare expected_dss in
Alcotest.(check @@ list @@ pair string (list ds))
(Printf.sprintf "%s rrds are not expected" kind)
actual_dss expected_dss
let host_rrds rrd_info =
Option.bind rrd_info @@ fun rrd_info ->
let h = Hashtbl.create 1 in
if rrd_info.Rrdd_shared.dss <> [] then
Hashtbl.add h "host" rrd_info ;
Some h
let update_rrds_test ~dss ~uuid_domids ~paused_vms ~expected_vm_rrds
~expected_sr_rrds ~expected_host_dss =
let test () =
reset_rrdd_shared_state () ;
Rrdd_monitor.update_rrds 12345.0 dss uuid_domids paused_vms ;
check_datasources "VM" (Some Rrdd_shared.vm_rrds) expected_vm_rrds ;
check_datasources "SR" (Some Rrdd_shared.sr_rrds) expected_sr_rrds ;
check_datasources "Host" (host_rrds !Rrdd_shared.host_rrd) expected_host_dss
in
[("", `Quick, test)]
let update_rrds =
let open Rrd in
[
( "Null update"
, update_rrds_test ~dss:[] ~uuid_domids:[] ~paused_vms:[]
~expected_vm_rrds:[] ~expected_sr_rrds:[] ~expected_host_dss:[]
)
; ( "Single host update"
, update_rrds_test ~dss:[(Host, ds_a)] ~uuid_domids:[] ~paused_vms:[]
~expected_vm_rrds:[] ~expected_sr_rrds:[]
~expected_host_dss:[("host", [ds_a])]
)
; ( "Multiple host updates"
, update_rrds_test
~dss:[(Host, ds_a); (Host, ds_b)]
~uuid_domids:[] ~paused_vms:[] ~expected_vm_rrds:[] ~expected_sr_rrds:[]
~expected_host_dss:[("host", [ds_a; ds_b])]
)
; ( "Single non-resident VM update"
, update_rrds_test ~dss:[(VM "a", ds_a)] ~uuid_domids:[] ~paused_vms:[]
~expected_vm_rrds:[] ~expected_sr_rrds:[] ~expected_host_dss:[]
)
; ( "Multiple non-resident VM updates"
, update_rrds_test
~dss:[(VM "a", ds_a); (VM "b", ds_a)]
~uuid_domids:[] ~paused_vms:[] ~expected_vm_rrds:[] ~expected_sr_rrds:[]
~expected_host_dss:[]
)
; ( "Single resident VM update"
, update_rrds_test ~dss:[(VM "a", ds_a)] ~uuid_domids:[("a", 1)]
~paused_vms:[]
~expected_vm_rrds:[("a", [ds_a])]
~expected_sr_rrds:[] ~expected_host_dss:[]
)
; ( "Multiple resident VM updates"
, update_rrds_test
~dss:[(VM "a", ds_a); (VM "b", ds_a); (VM "b", ds_b)]
~uuid_domids:[("a", 1); ("b", 1)] ~paused_vms:[]
~expected_vm_rrds:[("a", [ds_a]); ("b", [ds_a; ds_b])]
~expected_sr_rrds:[] ~expected_host_dss:[]
)
; ( "Multiple resident and non-resident VM updates"
, update_rrds_test
~dss:[(VM "a", ds_a); (VM "b", ds_a); (VM "c", ds_a)]
~uuid_domids:[("a", 1); ("b", 1)] ~paused_vms:[]
~expected_vm_rrds:[("a", [ds_a]); ("b", [ds_a])]
~expected_sr_rrds:[] ~expected_host_dss:[]
)
; ( "Multiple SR updates"
, update_rrds_test
~dss:[(SR "a", ds_a); (SR "b", ds_a); (SR "b", ds_b)]
~uuid_domids:[] ~paused_vms:[] ~expected_vm_rrds:[]
~expected_sr_rrds:[("a", [ds_a]); ("b", [ds_a; ds_b])]
~expected_host_dss:[]
)
]
let () = Alcotest.run "RRD daemon monitor test" update_rrds
| null |
https://raw.githubusercontent.com/xapi-project/xen-api/751163d0033765a7c27e84cedaefcdef3b61a53d/ocaml/xcp-rrdd/test/rrdd/test_rrdd_monitor.ml
|
ocaml
|
let ds_a =
Ds.ds_make ~name:"ds_a" ~units:"(fraction)" ~description:"datasource a"
~value:(Rrd.VT_Float 1.0) ~ty:Rrd.Gauge ~default:true ()
let ds_b =
Ds.ds_make ~name:"ds_b" ~units:"(fraction)" ~description:"datasource b"
~value:(Rrd.VT_Float 2.0) ~ty:Rrd.Gauge ~default:true ()
let reset_rrdd_shared_state () =
Hashtbl.clear Rrdd_shared.vm_rrds ;
Rrdd_shared.host_rrd := None
let pp_ds =
Fmt.(
Dump.record
[
Dump.field "ds_name" (fun t -> t.Ds.ds_name) string
; Dump.field "ds_description" (fun t -> t.Ds.ds_description) string
; Dump.field "ds_default" (fun t -> t.Ds.ds_default) bool
; Dump.field "ds_min" (fun t -> t.Ds.ds_min) float
; Dump.field "ds_max" (fun t -> t.Ds.ds_max) float
; Dump.field "ds_units" (fun t -> t.Ds.ds_units) string
]
)
let ds = Alcotest.testable pp_ds (fun a b -> String.equal a.ds_name b.ds_name)
let dss_of_rrds rrds =
Hashtbl.fold (fun k v acc -> (k, v.Rrdd_shared.dss) :: acc) rrds []
|> List.fast_sort Stdlib.compare
let check_datasources kind rdds expected_dss =
match rdds with
| None when expected_dss <> [] ->
Alcotest.fail (Printf.sprintf "%s RRD must be created" kind)
| None ->
()
| Some actual_rdds ->
let actual_dss = dss_of_rrds actual_rdds in
let expected_dss = List.fast_sort Stdlib.compare expected_dss in
Alcotest.(check @@ list @@ pair string (list ds))
(Printf.sprintf "%s rrds are not expected" kind)
actual_dss expected_dss
let host_rrds rrd_info =
Option.bind rrd_info @@ fun rrd_info ->
let h = Hashtbl.create 1 in
if rrd_info.Rrdd_shared.dss <> [] then
Hashtbl.add h "host" rrd_info ;
Some h
let update_rrds_test ~dss ~uuid_domids ~paused_vms ~expected_vm_rrds
~expected_sr_rrds ~expected_host_dss =
let test () =
reset_rrdd_shared_state () ;
Rrdd_monitor.update_rrds 12345.0 dss uuid_domids paused_vms ;
check_datasources "VM" (Some Rrdd_shared.vm_rrds) expected_vm_rrds ;
check_datasources "SR" (Some Rrdd_shared.sr_rrds) expected_sr_rrds ;
check_datasources "Host" (host_rrds !Rrdd_shared.host_rrd) expected_host_dss
in
[("", `Quick, test)]
let update_rrds =
let open Rrd in
[
( "Null update"
, update_rrds_test ~dss:[] ~uuid_domids:[] ~paused_vms:[]
~expected_vm_rrds:[] ~expected_sr_rrds:[] ~expected_host_dss:[]
)
; ( "Single host update"
, update_rrds_test ~dss:[(Host, ds_a)] ~uuid_domids:[] ~paused_vms:[]
~expected_vm_rrds:[] ~expected_sr_rrds:[]
~expected_host_dss:[("host", [ds_a])]
)
; ( "Multiple host updates"
, update_rrds_test
~dss:[(Host, ds_a); (Host, ds_b)]
~uuid_domids:[] ~paused_vms:[] ~expected_vm_rrds:[] ~expected_sr_rrds:[]
~expected_host_dss:[("host", [ds_a; ds_b])]
)
; ( "Single non-resident VM update"
, update_rrds_test ~dss:[(VM "a", ds_a)] ~uuid_domids:[] ~paused_vms:[]
~expected_vm_rrds:[] ~expected_sr_rrds:[] ~expected_host_dss:[]
)
; ( "Multiple non-resident VM updates"
, update_rrds_test
~dss:[(VM "a", ds_a); (VM "b", ds_a)]
~uuid_domids:[] ~paused_vms:[] ~expected_vm_rrds:[] ~expected_sr_rrds:[]
~expected_host_dss:[]
)
; ( "Single resident VM update"
, update_rrds_test ~dss:[(VM "a", ds_a)] ~uuid_domids:[("a", 1)]
~paused_vms:[]
~expected_vm_rrds:[("a", [ds_a])]
~expected_sr_rrds:[] ~expected_host_dss:[]
)
; ( "Multiple resident VM updates"
, update_rrds_test
~dss:[(VM "a", ds_a); (VM "b", ds_a); (VM "b", ds_b)]
~uuid_domids:[("a", 1); ("b", 1)] ~paused_vms:[]
~expected_vm_rrds:[("a", [ds_a]); ("b", [ds_a; ds_b])]
~expected_sr_rrds:[] ~expected_host_dss:[]
)
; ( "Multiple resident and non-resident VM updates"
, update_rrds_test
~dss:[(VM "a", ds_a); (VM "b", ds_a); (VM "c", ds_a)]
~uuid_domids:[("a", 1); ("b", 1)] ~paused_vms:[]
~expected_vm_rrds:[("a", [ds_a]); ("b", [ds_a])]
~expected_sr_rrds:[] ~expected_host_dss:[]
)
; ( "Multiple SR updates"
, update_rrds_test
~dss:[(SR "a", ds_a); (SR "b", ds_a); (SR "b", ds_b)]
~uuid_domids:[] ~paused_vms:[] ~expected_vm_rrds:[]
~expected_sr_rrds:[("a", [ds_a]); ("b", [ds_a; ds_b])]
~expected_host_dss:[]
)
]
let () = Alcotest.run "RRD daemon monitor test" update_rrds
|
|
95024fa19506be9d49f1203a9bf63606f3a5ed83ad579bd853f3b204443d878f
|
Vortecsmaster/EmurgoAcademyPlutusExamples
|
JustRedeemer.hs
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE NoImplicitPrelude #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedStrings #-}
module JustRedeemer where
PlutusTx
import PlutusTx (Data (..))
import qualified PlutusTx
import qualified PlutusTx.Builtins as Builtins
import PlutusTx.Prelude hiding (Semigroup(..), unless)
--Contract Monad
import Plutus.Contract
--Ledger
import Ledger hiding (singleton)
import qualified Ledger.Address as V1Address
Same library name , different functions for V1 and V2 in some cases
import qualified Ledger . Scripts as Scripts
New library name for Typed and some new fuctions
import Ledger.Ada as Ada
Trace Emulator
import Plutus.Trace
import qualified Plutus.Trace.Emulator as Emulator
import qualified Wallet.Emulator.Wallet as Wallet
( broken )
import Playground . Contract ( printJson , printSchemas , ensureKnownCurrencies , stage )
import Playground . TH ( mkKnownCurrencies , mkSchemaDefinitions )
import Playground . Types ( ( .. ) )
--"Normal " Haskell
import Playground.Contract (printJson, printSchemas, ensureKnownCurrencies, stage)
import Playground.TH (mkKnownCurrencies, mkSchemaDefinitions)
import Playground.Types (KnownCurrency (..))
--"Normal" Haskell -}
import Control.Monad hiding (fmap)
import Data.Map as Map
import Data.Text (Text)
import Data.Void (Void)
import Prelude (IO, Semigroup (..), String, show)
import Text.Printf (printf)
import Control.Monad.Freer.Extras as Extras
# OPTIONS_GHC -fno - warn - unused - imports #
--THE ON-CHAIN CODE
# INLINABLE justRedeemer #
justRedeemer :: BuiltinData -> BuiltinData -> BuiltinData -> ()
justRedeemer _ redeemer _
| redeemer == Builtins.mkI 42 = ()
| otherwise = traceError "Wrong Redeemer"
validator :: Validator
validator = mkValidatorScript $$(PlutusTx.compile [|| justRedeemer ||])
valHash :: Ledger.ValidatorHash
valHash = Scripts.validatorHash validator -- just the hash of the validator
scrAddress :: V1Address.Address
Could n't find a new version of scriptAddress for unTyped Scripts
--replaces:
--scrAddress = scriptAddress validator
--THE OFFCHAIN CODE
type GiftSchema =
Endpoint "give" Integer
.\/ Endpoint "grab" Integer
give :: AsContractError e => Integer -> Contract w s e ()
give amount = do
This Tx needs an output , that s its going to be the Script Address , Datum MUST be specified , so is created and the ammount of lovelaces
This line submit the Tx
void $ awaitTxConfirmed $ getCardanoTxId ledgerTx --This line waits for confirmation
Plutus.Contract.logInfo @String $ printf "made a gift of %d lovelace" amount --This line log info,usable on the PP(Plutus Playground)
The Contract s = Schema e = Error or value restricted from AsContractError
grab n = do
utxos <- utxosAt scrAddress -- This will find all UTXOs that sit at the script address
let orefs = fst <$> Map.toList utxos -- This get all the references of the UTXOs
lookups = Constraints.unspentOutputs utxos <> -- Tell where to find all the UTXOS
and inform about the actual validator ( the spending tx needs to provide the actual validator )
tx :: TxConstraints Void Void
Define the TX giving constrains , one for each UTXO sitting on this addrs ,
must provide a redeemer
Allow the wallet to construct the tx with the necesary information
void $ awaitTxConfirmed $ getCardanoTxId ledgerTx -- Wait for confirmation
Plutus.Contract.logInfo @String $ "collected gifts" -- Log information
endpoints :: Contract () GiftSchema Text ()
endpoints = awaitPromise (give' `select` grab') >> endpoints -- Asynchronously wait for the endpoints interactions from the wallet
where -- and recursively wait for the endpoints all over again
give' = endpoint @"give" give -- block until give
grab' = endpoint @"grab" grab
-- block until grab
Playground broken at the moment - September 2022
mkSchemaDefinitions '' GiftSchema -- Generate the Schema for the playground
-- mkKnownCurrencies []
--SIMULATION
test :: IO ()
test = runEmulatorTraceIO $ do
h1 <- activateContractWallet (Wallet.knownWallet 1) endpoints
h2 <- activateContractWallet (Wallet.knownWallet 2) endpoints
callEndpoint @"give" h1 $ 51000000
void $ Emulator.waitNSlots 11
callEndpoint @"grab" h2 42
s <- Emulator.waitNSlots 11
MakeKnown currencies for the playground to have some ADA available
| null |
https://raw.githubusercontent.com/Vortecsmaster/EmurgoAcademyPlutusExamples/4532f1809d32c1b736d5b56e4a3564c631bb6d2b/V1/JustValidators/src/JustRedeemer.hs
|
haskell
|
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE TypeOperators #
# LANGUAGE OverloadedStrings #
Contract Monad
Ledger
"Normal " Haskell
"Normal" Haskell -}
THE ON-CHAIN CODE
just the hash of the validator
replaces:
scrAddress = scriptAddress validator
THE OFFCHAIN CODE
This line waits for confirmation
This line log info,usable on the PP(Plutus Playground)
This will find all UTXOs that sit at the script address
This get all the references of the UTXOs
Tell where to find all the UTXOS
Wait for confirmation
Log information
Asynchronously wait for the endpoints interactions from the wallet
and recursively wait for the endpoints all over again
block until give
block until grab
Generate the Schema for the playground
mkKnownCurrencies []
SIMULATION
|
# LANGUAGE NoImplicitPrelude #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
module JustRedeemer where
PlutusTx
import PlutusTx (Data (..))
import qualified PlutusTx
import qualified PlutusTx.Builtins as Builtins
import PlutusTx.Prelude hiding (Semigroup(..), unless)
import Plutus.Contract
import Ledger hiding (singleton)
import qualified Ledger.Address as V1Address
Same library name , different functions for V1 and V2 in some cases
import qualified Ledger . Scripts as Scripts
New library name for Typed and some new fuctions
import Ledger.Ada as Ada
Trace Emulator
import Plutus.Trace
import qualified Plutus.Trace.Emulator as Emulator
import qualified Wallet.Emulator.Wallet as Wallet
( broken )
import Playground . Contract ( printJson , printSchemas , ensureKnownCurrencies , stage )
import Playground . TH ( mkKnownCurrencies , mkSchemaDefinitions )
import Playground . Types ( ( .. ) )
import Playground.Contract (printJson, printSchemas, ensureKnownCurrencies, stage)
import Playground.TH (mkKnownCurrencies, mkSchemaDefinitions)
import Playground.Types (KnownCurrency (..))
import Control.Monad hiding (fmap)
import Data.Map as Map
import Data.Text (Text)
import Data.Void (Void)
import Prelude (IO, Semigroup (..), String, show)
import Text.Printf (printf)
import Control.Monad.Freer.Extras as Extras
# OPTIONS_GHC -fno - warn - unused - imports #
# INLINABLE justRedeemer #
justRedeemer :: BuiltinData -> BuiltinData -> BuiltinData -> ()
justRedeemer _ redeemer _
| redeemer == Builtins.mkI 42 = ()
| otherwise = traceError "Wrong Redeemer"
validator :: Validator
validator = mkValidatorScript $$(PlutusTx.compile [|| justRedeemer ||])
valHash :: Ledger.ValidatorHash
scrAddress :: V1Address.Address
Could n't find a new version of scriptAddress for unTyped Scripts
type GiftSchema =
Endpoint "give" Integer
.\/ Endpoint "grab" Integer
give :: AsContractError e => Integer -> Contract w s e ()
give amount = do
This Tx needs an output , that s its going to be the Script Address , Datum MUST be specified , so is created and the ammount of lovelaces
This line submit the Tx
The Contract s = Schema e = Error or value restricted from AsContractError
grab n = do
and inform about the actual validator ( the spending tx needs to provide the actual validator )
tx :: TxConstraints Void Void
Define the TX giving constrains , one for each UTXO sitting on this addrs ,
must provide a redeemer
Allow the wallet to construct the tx with the necesary information
endpoints :: Contract () GiftSchema Text ()
grab' = endpoint @"grab" grab
Playground broken at the moment - September 2022
test :: IO ()
test = runEmulatorTraceIO $ do
h1 <- activateContractWallet (Wallet.knownWallet 1) endpoints
h2 <- activateContractWallet (Wallet.knownWallet 2) endpoints
callEndpoint @"give" h1 $ 51000000
void $ Emulator.waitNSlots 11
callEndpoint @"grab" h2 42
s <- Emulator.waitNSlots 11
MakeKnown currencies for the playground to have some ADA available
|
240034c5b51f98a6b1e1180fbd92b20f37ed872e91246dca3a917f567d2195c1
|
ghc/packages-dph
|
Bool.hs
|
{-# OPTIONS_GHC -fvectorise #-}
module Data.Array.Parallel.Prelude.Bool
( Bool(..)
, otherwise, (&&), (||), not, andP, orP
, fromBool, toBool
)
where
import Data.Array.Parallel.Prim () -- dependency required by the vectoriser
import Data.Array.Parallel.Prelude.Base
import Data.Array.Parallel.Lifted.Closure
import Data.Array.Parallel.PArray.PReprInstances
import Data.Array.Parallel.Lifted.Scalar
import qualified Data.Array.Parallel.Unlifted as U
import Data.Bits
We re - export ' Prelude.otherwise ' as is as it is special - cased in the
{-# VECTORISE (&&) = (&&*) #-}
(&&*) :: Bool :-> Bool :-> Bool
# INLINE ( & & * ) #
(&&*) = closure2 (&&) and_l
# NOVECTORISE ( & & * ) #
and_l :: PArray Bool -> PArray Bool -> PArray Bool
# INLINE and_l #
and_l (PArray n# bs) (PArray _ cs)
= PArray n# $
case bs of { PBool sel1 ->
case cs of { PBool sel2 ->
PBool $ U.tagsToSel2 (U.zipWith (.&.) (U.tagsSel2 sel1) (U.tagsSel2 sel2)) }}
# NOVECTORISE and_l #
{-# VECTORISE (||) = (||*) #-}
(||*) :: Bool :-> Bool :-> Bool
{-# INLINE (||*) #-}
(||*) = closure2 (||) or_l
{-# NOVECTORISE (||*) #-}
or_l :: PArray Bool -> PArray Bool -> PArray Bool
# INLINE or_l #
or_l (PArray n# bs) (PArray _ cs)
= PArray n# $
case bs of { PBool sel1 ->
case cs of { PBool sel2 ->
PBool $ U.tagsToSel2 (U.zipWith (.|.) (U.tagsSel2 sel1) (U.tagsSel2 sel2)) }}
# NOVECTORISE or_l #
{-# VECTORISE not = not_v #-}
not_v :: Bool :-> Bool
# INLINE not_v #
not_v = closure1 not not_l
# NOVECTORISE not_v #
not_l :: PArray Bool -> PArray Bool
# INLINE not_l #
not_l (PArray n# bs)
= PArray n# $
case bs of { PBool sel ->
PBool $ U.tagsToSel2 (U.map complement (U.tagsSel2 sel)) }
# NOVECTORISE not_l #
andP:: PArr Bool -> Bool
# NOINLINE andP #
andP _ = True
{-# VECTORISE andP = andP_v #-}
andP_v :: PArray Bool :-> Bool
# INLINE andP_v #
andP_v = closure1 (scalar_fold (&&) True) (scalar_folds (&&) True)
# NOVECTORISE andP_v #
orP:: PArr Bool -> Bool
# NOINLINE orP #
orP _ = True
# VECTORISE orP = orP_v #
orP_v :: PArray Bool :-> Bool
# INLINE orP_v #
orP_v = closure1 (scalar_fold (||) False) (scalar_folds (||) False)
# NOVECTORISE orP_v #
fromBool :: Bool -> Int
fromBool False = 0
fromBool True = 1
toBool :: Int -> Bool
toBool 0 = False
toBool _ = True
| null |
https://raw.githubusercontent.com/ghc/packages-dph/64eca669f13f4d216af9024474a3fc73ce101793/dph-lifted-copy/Data/Array/Parallel/Prelude/Bool.hs
|
haskell
|
# OPTIONS_GHC -fvectorise #
dependency required by the vectoriser
# VECTORISE (&&) = (&&*) #
# VECTORISE (||) = (||*) #
# INLINE (||*) #
# NOVECTORISE (||*) #
# VECTORISE not = not_v #
# VECTORISE andP = andP_v #
|
module Data.Array.Parallel.Prelude.Bool
( Bool(..)
, otherwise, (&&), (||), not, andP, orP
, fromBool, toBool
)
where
import Data.Array.Parallel.Prelude.Base
import Data.Array.Parallel.Lifted.Closure
import Data.Array.Parallel.PArray.PReprInstances
import Data.Array.Parallel.Lifted.Scalar
import qualified Data.Array.Parallel.Unlifted as U
import Data.Bits
We re - export ' Prelude.otherwise ' as is as it is special - cased in the
(&&*) :: Bool :-> Bool :-> Bool
# INLINE ( & & * ) #
(&&*) = closure2 (&&) and_l
# NOVECTORISE ( & & * ) #
and_l :: PArray Bool -> PArray Bool -> PArray Bool
# INLINE and_l #
and_l (PArray n# bs) (PArray _ cs)
= PArray n# $
case bs of { PBool sel1 ->
case cs of { PBool sel2 ->
PBool $ U.tagsToSel2 (U.zipWith (.&.) (U.tagsSel2 sel1) (U.tagsSel2 sel2)) }}
# NOVECTORISE and_l #
(||*) :: Bool :-> Bool :-> Bool
(||*) = closure2 (||) or_l
or_l :: PArray Bool -> PArray Bool -> PArray Bool
# INLINE or_l #
or_l (PArray n# bs) (PArray _ cs)
= PArray n# $
case bs of { PBool sel1 ->
case cs of { PBool sel2 ->
PBool $ U.tagsToSel2 (U.zipWith (.|.) (U.tagsSel2 sel1) (U.tagsSel2 sel2)) }}
# NOVECTORISE or_l #
not_v :: Bool :-> Bool
# INLINE not_v #
not_v = closure1 not not_l
# NOVECTORISE not_v #
not_l :: PArray Bool -> PArray Bool
# INLINE not_l #
not_l (PArray n# bs)
= PArray n# $
case bs of { PBool sel ->
PBool $ U.tagsToSel2 (U.map complement (U.tagsSel2 sel)) }
# NOVECTORISE not_l #
andP:: PArr Bool -> Bool
# NOINLINE andP #
andP _ = True
andP_v :: PArray Bool :-> Bool
# INLINE andP_v #
andP_v = closure1 (scalar_fold (&&) True) (scalar_folds (&&) True)
# NOVECTORISE andP_v #
orP:: PArr Bool -> Bool
# NOINLINE orP #
orP _ = True
# VECTORISE orP = orP_v #
orP_v :: PArray Bool :-> Bool
# INLINE orP_v #
orP_v = closure1 (scalar_fold (||) False) (scalar_folds (||) False)
# NOVECTORISE orP_v #
fromBool :: Bool -> Int
fromBool False = 0
fromBool True = 1
toBool :: Int -> Bool
toBool 0 = False
toBool _ = True
|
1b36b8bdc2302a296855af2d602f036ba6d94623db15fb7b3b4de1f47f68e9e2
|
marigold-dev/deku
|
imports.mli
|
open Wasm
exception Type_error
val imports : 'inst. unit -> (Utf8.t * Instance.extern) list
val alloc : Value.t * Value.t -> int64
val read : int64 -> Value.t
| null |
https://raw.githubusercontent.com/marigold-dev/deku/a26f31e0560ad12fd86cf7fa4667bb147247c7ef/deku-c/wasm-vm-ocaml/imports.mli
|
ocaml
|
open Wasm
exception Type_error
val imports : 'inst. unit -> (Utf8.t * Instance.extern) list
val alloc : Value.t * Value.t -> int64
val read : int64 -> Value.t
|
|
d1dd72bc4a22478b0de527a38cf0d6db47ce1624c65dbfb7b0c6a8aa90bcc615
|
nkpart/kit
|
Builder.hs
|
{-# LANGUAGE PackageImports #-}
# LANGUAGE DeriveFunctor #
{-# LANGUAGE DeriveTraversable #-}
# LANGUAGE DeriveFoldable #
module Kit.Xcode.Builder (renderXcodeProject, SourceGroup(..)) where
import Prelude hiding (mapM)
import Data.Traversable as T (mapM, Traversable)
import Data.Foldable (Foldable)
import Kit.Xcode.Common
import Kit.Xcode.ProjectFileTemplate
import Kit.FlaggedFile
import Text.PList
import qualified Text.PList.PrettyPrint as PList (ppFlat)
import Kit.Util
import Data.List (nub, sortBy)
import "mtl" Control.Monad.State
import System.FilePath
import Data.Function (on)
data SourceGroup a = SourceGroup {
sourceGroupName :: String,
sourceGroupHeaders :: [a],
sourceGroupSources :: [a],
sourceGroupLibs :: [a],
sourceGroupFrameworks :: [a]
} deriving (Functor, Foldable, Traversable)
createBuildFile :: Integer -> FlaggedFile -> PBXBuildFile
createBuildFile i ffpath = PBXBuildFile uuid1 (PBXFileReference uuid2 path) compileFlags
where uuid1 = uuid i
uuid2 = uuid $ i + 10000000
path = flaggedFilePath ffpath
compileFlags = flaggedFileFlags ffpath
buildFileFromState :: FlaggedFile -> State [Integer] PBXBuildFile
buildFileFromState filePath = flip createBuildFile filePath <$> popS
| Render an Xcode project !
renderXcodeProject ::
[SourceGroup FlaggedFile]
-> String -- ^ Output lib name
-> String
renderXcodeProject sourceGroups outputLibName = fst . flip runState [(1::Integer)..] $ do
let libs = concatMap sourceGroupLibs sourceGroups
buildFileGroups <- T.mapM (T.mapM buildFileFromState) sourceGroups
let headerBuildFiles = concatMap sourceGroupHeaders buildFileGroups
sourceBuildFiles = concatMap sourceGroupSources buildFileGroups
Build File Items
frameworkBuildFiles = concatMap sourceGroupFrameworks buildFileGroups
let allBuildFiles = sourceBuildFiles ++ headerBuildFiles ++ libBuildFiles ++ frameworkBuildFiles
-- Build And FileRef sections
bfs = buildFileSection allBuildFiles
frs = fileReferenceSection (map buildFileReference allBuildFiles) outputLibName
Groups
classes = classesGroup $ filter (not . null . snd) $ map groupFileRefs buildFileGroups
where groupFileRefs (SourceGroup n hs ss _ _) = (n, sortBy (compare `on` (takeFileName . fileReferencePath)) $ map buildFileReference (hs ++ ss))
fg = frameworksGroup $ filter (not . null . snd) $ map groupLibRefs buildFileGroups
where groupLibRefs (SourceGroup n _ _ ls fs) = (n, map buildFileReference (ls ++ fs))
-- classes = classesGroup $ sortBy (compare `on` (takeFileName . fileReferencePath)) $ map buildFileReference (sourceBuildFiles ++ headerBuildFiles)
-- fg = frameworksGroup $ map buildFileReference (libBuildFiles ++ frameworkBuildFiles)
-- Phases
headersPhase = headersBuildPhase headerBuildFiles
srcsPhase = sourcesBuildPhase sourceBuildFiles
frameworksPhase = frameworksBuildPhase (libBuildFiles ++ frameworkBuildFiles)
copyFrameworksPhase = copyFrameworksBuildPhase frameworkBuildFiles
UUID indices
libDirs = nub $ map (dropFileName . flaggedFilePath) libs
return . PList.ppFlat $ makeProjectPList (bfs ++ frs ++ [classes, headersPhase, srcsPhase, frameworksPhase, copyFrameworksPhase, fg]) libDirs
buildFileSection :: [PBXBuildFile] -> [PListObjectItem]
buildFileSection bfs = map buildFileItem bfs ++ [
"4728C530117C02B10027D7D1" ~> buildFile kitConfigRefUUID "",
"AA747D9F0F9514B9006C5449" ~> buildFile "AA747D9E0F9514B9006C5449" "",
"AACBBE4A0F95108600F1A2B1" ~> buildFile "AACBBE490F95108600F1A2B1" ""
]
fileReferenceSection :: [PBXFileReference] -> String -> [PListObjectItem]
fileReferenceSection refs archiveName = map fileReferenceItem refs ++ [
kitConfigRefUUID ~> obj [
"isa" ~> val "PBXFileReference",
"fileEncoding" ~> val "4",
"lastKnownFileType" ~> val "text.xcconfig",
"path" ~> val "DepsOnly.xcconfig",
"sourceTree" ~> val "<group>"
],
"AA747D9E0F9514B9006C5449" ~> obj [
"isa" ~> val "PBXFileReference",
"fileEncoding" ~> val "4",
"lastKnownFileType" ~> val "sourcecode.c.h",
"path" ~> val "Prefix.pch",
"sourceTree" ~> val "SOURCE_ROOT"
],
"AACBBE490F95108600F1A2B1" ~> obj [
"isa" ~> val "PBXFileReference",
"lastKnownFileType" ~> val "wrapper.framework",
"name" ~> val "Foundation.framework",
"path" ~> val "System/Library/Frameworks/Foundation.framework",
"sourceTree" ~> val "SDKROOT"
],
productRefUUID ~> obj [
"isa" ~> val "PBXFileReference",
"explicitFileType" ~> val "archive.ar",
"includeInIndex" ~> val "0",
"path" ~> val archiveName,
"sourceTree" ~> val "BUILT_PRODUCTS_DIR"
]
]
classesGroup :: [(String, [PBXFileReference])] -> PListObjectItem
classesGroup files = classesGroupUUID ~> group "Classes" (map renderGroup files)
where renderGroup (groupName, fs) = group groupName $ map (val . fileReferenceId) fs
frameworksGroup :: [(String, [PBXFileReference])] -> PListObjectItem
frameworksGroup files = frameworksGroupUUID ~> group "Frameworks" (val "AACBBE490F95108600F1A2B1" : map renderGroup files)
where renderGroup (groupName, fs) = group groupName $ map (val . fileReferenceId) fs
frameworksBuildPhase :: [PBXBuildFile] -> PListObjectItem
frameworksBuildPhase libs = frameworksBuildPhaseUUID ~> obj [
"isa" ~> val "PBXFrameworksBuildPhase",
"buildActionMask" ~> val "2147483647",
"files" ~> arr (val "AACBBE4A0F95108600F1A2B1" : map (val . buildFileId) libs),
"runOnlyForDeploymentPostprocessing" ~> val "0"
]
headersBuildPhase :: [PBXBuildFile] -> PListObjectItem
headersBuildPhase bfs = headersBuildPhaseUUID ~> obj [
"isa" ~> val "PBXHeadersBuildPhase",
"buildActionMask" ~> val "2147483647",
"files" ~> arr (val "AA747D9F0F9514B9006C5449" : map (val . buildFileId) bfs),
"runOnlyForDeploymentPostprocessing" ~> val "0"
]
sourcesBuildPhase :: [PBXBuildFile] -> PListObjectItem
sourcesBuildPhase bfs = sourcesBuildPhaseUUID ~> obj [
"isa" ~> val "PBXSourcesBuildPhase",
"buildActionMask" ~> val "22147483647147483647",
"files" ~> arr (map (val . buildFileId) bfs),
"runOnlyForDeploymentPostprocessing" ~> val "0"
]
copyFrameworksBuildPhase :: [PBXBuildFile] -> PListObjectItem
copyFrameworksBuildPhase frameworks = copyFrameworksBuildPhaseUUID ~> obj [
"isa" ~> val "PBXCopyFilesBuildPhase",
"buildActionMask" ~> val "2147483647",
"files" ~> arr (map (val . buildFileId) frameworks),
"name" ~> val "Copy Frameworks",
"dstPath" ~> val "\"\"",
"dstSubfolderSpec" ~> val "10", -- this is the "Frameworks" destination, whatever
"runOnlyForDeploymentPostprocessing" ~> val "0"
]
| null |
https://raw.githubusercontent.com/nkpart/kit/ed217ddbc90688350e52156503cca092c9bf8300/Kit/Xcode/Builder.hs
|
haskell
|
# LANGUAGE PackageImports #
# LANGUAGE DeriveTraversable #
^ Output lib name
Build And FileRef sections
classes = classesGroup $ sortBy (compare `on` (takeFileName . fileReferencePath)) $ map buildFileReference (sourceBuildFiles ++ headerBuildFiles)
fg = frameworksGroup $ map buildFileReference (libBuildFiles ++ frameworkBuildFiles)
Phases
this is the "Frameworks" destination, whatever
|
# LANGUAGE DeriveFunctor #
# LANGUAGE DeriveFoldable #
module Kit.Xcode.Builder (renderXcodeProject, SourceGroup(..)) where
import Prelude hiding (mapM)
import Data.Traversable as T (mapM, Traversable)
import Data.Foldable (Foldable)
import Kit.Xcode.Common
import Kit.Xcode.ProjectFileTemplate
import Kit.FlaggedFile
import Text.PList
import qualified Text.PList.PrettyPrint as PList (ppFlat)
import Kit.Util
import Data.List (nub, sortBy)
import "mtl" Control.Monad.State
import System.FilePath
import Data.Function (on)
data SourceGroup a = SourceGroup {
sourceGroupName :: String,
sourceGroupHeaders :: [a],
sourceGroupSources :: [a],
sourceGroupLibs :: [a],
sourceGroupFrameworks :: [a]
} deriving (Functor, Foldable, Traversable)
createBuildFile :: Integer -> FlaggedFile -> PBXBuildFile
createBuildFile i ffpath = PBXBuildFile uuid1 (PBXFileReference uuid2 path) compileFlags
where uuid1 = uuid i
uuid2 = uuid $ i + 10000000
path = flaggedFilePath ffpath
compileFlags = flaggedFileFlags ffpath
buildFileFromState :: FlaggedFile -> State [Integer] PBXBuildFile
buildFileFromState filePath = flip createBuildFile filePath <$> popS
| Render an Xcode project !
renderXcodeProject ::
[SourceGroup FlaggedFile]
-> String
renderXcodeProject sourceGroups outputLibName = fst . flip runState [(1::Integer)..] $ do
let libs = concatMap sourceGroupLibs sourceGroups
buildFileGroups <- T.mapM (T.mapM buildFileFromState) sourceGroups
let headerBuildFiles = concatMap sourceGroupHeaders buildFileGroups
sourceBuildFiles = concatMap sourceGroupSources buildFileGroups
Build File Items
frameworkBuildFiles = concatMap sourceGroupFrameworks buildFileGroups
let allBuildFiles = sourceBuildFiles ++ headerBuildFiles ++ libBuildFiles ++ frameworkBuildFiles
bfs = buildFileSection allBuildFiles
frs = fileReferenceSection (map buildFileReference allBuildFiles) outputLibName
Groups
classes = classesGroup $ filter (not . null . snd) $ map groupFileRefs buildFileGroups
where groupFileRefs (SourceGroup n hs ss _ _) = (n, sortBy (compare `on` (takeFileName . fileReferencePath)) $ map buildFileReference (hs ++ ss))
fg = frameworksGroup $ filter (not . null . snd) $ map groupLibRefs buildFileGroups
where groupLibRefs (SourceGroup n _ _ ls fs) = (n, map buildFileReference (ls ++ fs))
headersPhase = headersBuildPhase headerBuildFiles
srcsPhase = sourcesBuildPhase sourceBuildFiles
frameworksPhase = frameworksBuildPhase (libBuildFiles ++ frameworkBuildFiles)
copyFrameworksPhase = copyFrameworksBuildPhase frameworkBuildFiles
UUID indices
libDirs = nub $ map (dropFileName . flaggedFilePath) libs
return . PList.ppFlat $ makeProjectPList (bfs ++ frs ++ [classes, headersPhase, srcsPhase, frameworksPhase, copyFrameworksPhase, fg]) libDirs
buildFileSection :: [PBXBuildFile] -> [PListObjectItem]
buildFileSection bfs = map buildFileItem bfs ++ [
"4728C530117C02B10027D7D1" ~> buildFile kitConfigRefUUID "",
"AA747D9F0F9514B9006C5449" ~> buildFile "AA747D9E0F9514B9006C5449" "",
"AACBBE4A0F95108600F1A2B1" ~> buildFile "AACBBE490F95108600F1A2B1" ""
]
fileReferenceSection :: [PBXFileReference] -> String -> [PListObjectItem]
fileReferenceSection refs archiveName = map fileReferenceItem refs ++ [
kitConfigRefUUID ~> obj [
"isa" ~> val "PBXFileReference",
"fileEncoding" ~> val "4",
"lastKnownFileType" ~> val "text.xcconfig",
"path" ~> val "DepsOnly.xcconfig",
"sourceTree" ~> val "<group>"
],
"AA747D9E0F9514B9006C5449" ~> obj [
"isa" ~> val "PBXFileReference",
"fileEncoding" ~> val "4",
"lastKnownFileType" ~> val "sourcecode.c.h",
"path" ~> val "Prefix.pch",
"sourceTree" ~> val "SOURCE_ROOT"
],
"AACBBE490F95108600F1A2B1" ~> obj [
"isa" ~> val "PBXFileReference",
"lastKnownFileType" ~> val "wrapper.framework",
"name" ~> val "Foundation.framework",
"path" ~> val "System/Library/Frameworks/Foundation.framework",
"sourceTree" ~> val "SDKROOT"
],
productRefUUID ~> obj [
"isa" ~> val "PBXFileReference",
"explicitFileType" ~> val "archive.ar",
"includeInIndex" ~> val "0",
"path" ~> val archiveName,
"sourceTree" ~> val "BUILT_PRODUCTS_DIR"
]
]
classesGroup :: [(String, [PBXFileReference])] -> PListObjectItem
classesGroup files = classesGroupUUID ~> group "Classes" (map renderGroup files)
where renderGroup (groupName, fs) = group groupName $ map (val . fileReferenceId) fs
frameworksGroup :: [(String, [PBXFileReference])] -> PListObjectItem
frameworksGroup files = frameworksGroupUUID ~> group "Frameworks" (val "AACBBE490F95108600F1A2B1" : map renderGroup files)
where renderGroup (groupName, fs) = group groupName $ map (val . fileReferenceId) fs
frameworksBuildPhase :: [PBXBuildFile] -> PListObjectItem
frameworksBuildPhase libs = frameworksBuildPhaseUUID ~> obj [
"isa" ~> val "PBXFrameworksBuildPhase",
"buildActionMask" ~> val "2147483647",
"files" ~> arr (val "AACBBE4A0F95108600F1A2B1" : map (val . buildFileId) libs),
"runOnlyForDeploymentPostprocessing" ~> val "0"
]
headersBuildPhase :: [PBXBuildFile] -> PListObjectItem
headersBuildPhase bfs = headersBuildPhaseUUID ~> obj [
"isa" ~> val "PBXHeadersBuildPhase",
"buildActionMask" ~> val "2147483647",
"files" ~> arr (val "AA747D9F0F9514B9006C5449" : map (val . buildFileId) bfs),
"runOnlyForDeploymentPostprocessing" ~> val "0"
]
sourcesBuildPhase :: [PBXBuildFile] -> PListObjectItem
sourcesBuildPhase bfs = sourcesBuildPhaseUUID ~> obj [
"isa" ~> val "PBXSourcesBuildPhase",
"buildActionMask" ~> val "22147483647147483647",
"files" ~> arr (map (val . buildFileId) bfs),
"runOnlyForDeploymentPostprocessing" ~> val "0"
]
copyFrameworksBuildPhase :: [PBXBuildFile] -> PListObjectItem
copyFrameworksBuildPhase frameworks = copyFrameworksBuildPhaseUUID ~> obj [
"isa" ~> val "PBXCopyFilesBuildPhase",
"buildActionMask" ~> val "2147483647",
"files" ~> arr (map (val . buildFileId) frameworks),
"name" ~> val "Copy Frameworks",
"dstPath" ~> val "\"\"",
"runOnlyForDeploymentPostprocessing" ~> val "0"
]
|
a762421ad6e5e322a81d783df522f142163b9cd85923a654f41e62a4869cb2d2
|
vikram/lisplibraries
|
test-index-1b.lisp
|
$ I d : test - index-1b.lisp , v 1.2 2006/09/01 13:57:07 alemmens Exp $
(in-package :rs-test)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Class redefinition example
;;;
;;; To run this example:
;;; - First run the indexing example in test-index-1a.lisp.
;;; - Compile and load this file
This will change the class definition of HACKER .
Because of this change , Rucksack will remove some slot indexes and
;;; create (and fill) other slot indexes.
;;; - (SHOW-HACKERS)
;;; Notice that "Hackers indexed by hacker-id." now doesn't list any hackers,
;;; because the ID index was removed.
;;; - (SHOW-HACKERS-BY-AGE)
;;; This will print the hackers sorted by age. It shows that:
( 1 ) the existing hackers all got a new age slot , initialized by
;;; UPDATE-PERSISTENT-INSTANCE-FOR-REDEFINED-CLASS to a random
number according to their initform
( 2 ) a new index has been created for the new age slot
( 3 ) the index has been filled with the new values for the age slot .
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(with-rucksack (rs *hacker-rucksack*)
(with-transaction ()
;; For classes that may change during program development, you should
;; wrap all class definitions in a WITH-RUCKSACK to make sure that
;; the corresponding schemas and indexes are updated correctly.
In this case we redefine the HACKER class : we remove the index for
;; the ID slot, and we add a new AGE slot (with an index).
(defclass hacker ()
((id :initform (gensym "HACKER-")
:reader hacker-id)
(name :initform (random-elt *hackers*)
:accessor name
:index :case-insensitive-string-index)
(age :initform (random 100)
:accessor age
:index :number-index))
(:metaclass persistent-class)
(:index t))))
(defun show-hackers-by-age ()
(with-rucksack (rs *hacker-rucksack*)
(with-transaction ()
(print "Hackers by age.")
(rucksack-map-slot rs 'hacker 'age
(lambda (hacker)
(format t "~&~A has age ~D.~%"
(name hacker)
(age hacker)))))))
| null |
https://raw.githubusercontent.com/vikram/lisplibraries/105e3ef2d165275eb78f36f5090c9e2cdd0754dd/site/rucksack/test-index-1b.lisp
|
lisp
|
Class redefinition example
To run this example:
- First run the indexing example in test-index-1a.lisp.
- Compile and load this file
create (and fill) other slot indexes.
- (SHOW-HACKERS)
Notice that "Hackers indexed by hacker-id." now doesn't list any hackers,
because the ID index was removed.
- (SHOW-HACKERS-BY-AGE)
This will print the hackers sorted by age. It shows that:
UPDATE-PERSISTENT-INSTANCE-FOR-REDEFINED-CLASS to a random
For classes that may change during program development, you should
wrap all class definitions in a WITH-RUCKSACK to make sure that
the corresponding schemas and indexes are updated correctly.
the ID slot, and we add a new AGE slot (with an index).
|
$ I d : test - index-1b.lisp , v 1.2 2006/09/01 13:57:07 alemmens Exp $
(in-package :rs-test)
This will change the class definition of HACKER .
Because of this change , Rucksack will remove some slot indexes and
( 1 ) the existing hackers all got a new age slot , initialized by
number according to their initform
( 2 ) a new index has been created for the new age slot
( 3 ) the index has been filled with the new values for the age slot .
(with-rucksack (rs *hacker-rucksack*)
(with-transaction ()
In this case we redefine the HACKER class : we remove the index for
(defclass hacker ()
((id :initform (gensym "HACKER-")
:reader hacker-id)
(name :initform (random-elt *hackers*)
:accessor name
:index :case-insensitive-string-index)
(age :initform (random 100)
:accessor age
:index :number-index))
(:metaclass persistent-class)
(:index t))))
(defun show-hackers-by-age ()
(with-rucksack (rs *hacker-rucksack*)
(with-transaction ()
(print "Hackers by age.")
(rucksack-map-slot rs 'hacker 'age
(lambda (hacker)
(format t "~&~A has age ~D.~%"
(name hacker)
(age hacker)))))))
|
89e0e501b046bb0ab208776ff4ea19bd084a7ec084e3803aec1a561a235e57f3
|
burgerdev/ocaml-rfc7748
|
curve.ml
|
module type Field = sig
type t
val zero: t
val ( + ): t -> t -> t
val ( - ): t -> t -> t
val double: t -> t
val one: t
val ( * ): t -> t -> t
val ( / ): t -> t -> t
val square: t -> t
end
module type Integral = sig
type t
val zero: t
val one: t
val ( + ): t -> t -> t
val ( mod ): t -> t -> t
val ( asr ): t -> int -> t
val logxor: t -> t -> t
val gt: t -> t -> bool
end
module type Edwards = sig
type integral
type element
val bits: int
val a24: element
val constant_time_conditional_swap: integral -> element -> element -> element * element
end
module Make(F: Field)(I: Integral)(E: Edwards with type integral = I.t and type element = F.t) = struct
open F
let two = I.(one + one)
let bit z n = I.((z asr n) mod two)
let cswap = E.constant_time_conditional_swap
let scale priv pub =
let rec aux x1 x2 x3 z2 z3 swap = function
| t when t < 0 ->
let (x2, _) = cswap swap x2 x3 in
let (z2, _) = cswap swap z2 z3 in
x2 / z2
| t ->
let kt = bit priv t in
let swap = I.(logxor swap kt) in
let (x2, x3) = cswap swap x2 x3 in
let (z2, z3) = cswap swap z2 z3 in
let swap = kt in
let a = x2 + z2 in
let aa = square a in
let b = x2 - z2 in
let bb = square b in
let e = aa - bb in
let c = x3 + z3 in
let d = x3 - z3 in
let da = d * a in
let cb = c * b in
let x3 = square (da + cb) in
let z3 = x1 * square (da - cb) in
let x2 = aa * bb in
let z2 = e * (aa + E.a24 * e) in
aux x1 x2 x3 z2 z3 swap (pred t)
in
let x1 = pub in
let x2 = one in
let z2 = zero in
let x3 = pub in
let z3 = one in
let swap = I.zero in
aux x1 x2 x3 z2 z3 swap (pred E.bits)
end
| null |
https://raw.githubusercontent.com/burgerdev/ocaml-rfc7748/ed034213ff02cd55870ae1387e91deebc9838eb4/src/curve.ml
|
ocaml
|
module type Field = sig
type t
val zero: t
val ( + ): t -> t -> t
val ( - ): t -> t -> t
val double: t -> t
val one: t
val ( * ): t -> t -> t
val ( / ): t -> t -> t
val square: t -> t
end
module type Integral = sig
type t
val zero: t
val one: t
val ( + ): t -> t -> t
val ( mod ): t -> t -> t
val ( asr ): t -> int -> t
val logxor: t -> t -> t
val gt: t -> t -> bool
end
module type Edwards = sig
type integral
type element
val bits: int
val a24: element
val constant_time_conditional_swap: integral -> element -> element -> element * element
end
module Make(F: Field)(I: Integral)(E: Edwards with type integral = I.t and type element = F.t) = struct
open F
let two = I.(one + one)
let bit z n = I.((z asr n) mod two)
let cswap = E.constant_time_conditional_swap
let scale priv pub =
let rec aux x1 x2 x3 z2 z3 swap = function
| t when t < 0 ->
let (x2, _) = cswap swap x2 x3 in
let (z2, _) = cswap swap z2 z3 in
x2 / z2
| t ->
let kt = bit priv t in
let swap = I.(logxor swap kt) in
let (x2, x3) = cswap swap x2 x3 in
let (z2, z3) = cswap swap z2 z3 in
let swap = kt in
let a = x2 + z2 in
let aa = square a in
let b = x2 - z2 in
let bb = square b in
let e = aa - bb in
let c = x3 + z3 in
let d = x3 - z3 in
let da = d * a in
let cb = c * b in
let x3 = square (da + cb) in
let z3 = x1 * square (da - cb) in
let x2 = aa * bb in
let z2 = e * (aa + E.a24 * e) in
aux x1 x2 x3 z2 z3 swap (pred t)
in
let x1 = pub in
let x2 = one in
let z2 = zero in
let x3 = pub in
let z3 = one in
let swap = I.zero in
aux x1 x2 x3 z2 z3 swap (pred E.bits)
end
|
|
ceab3366700b2fd78b39a95a0cfc923c29890ccb9185d68d9d0ffdd72b8a51f1
|
Haskell-OpenAPI-Code-Generator/Stripe-Haskell-Library
|
GetApplePayDomainsDomain.hs
|
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE MultiWayIf #-}
CHANGE WITH CAUTION : This is a generated code file generated by -OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator .
{-# LANGUAGE OverloadedStrings #-}
-- | Contains the different functions to run the operation getApplePayDomainsDomain
module StripeAPI.Operations.GetApplePayDomainsDomain where
import qualified Control.Monad.Fail
import qualified Control.Monad.Trans.Reader
import qualified Data.Aeson
import qualified Data.Aeson as Data.Aeson.Encoding.Internal
import qualified Data.Aeson as Data.Aeson.Types
import qualified Data.Aeson as Data.Aeson.Types.FromJSON
import qualified Data.Aeson as Data.Aeson.Types.Internal
import qualified Data.Aeson as Data.Aeson.Types.ToJSON
import qualified Data.ByteString.Char8
import qualified Data.ByteString.Char8 as Data.ByteString.Internal
import qualified Data.Either
import qualified Data.Foldable
import qualified Data.Functor
import qualified Data.Maybe
import qualified Data.Scientific
import qualified Data.Text
import qualified Data.Text.Internal
import qualified Data.Time.Calendar as Data.Time.Calendar.Days
import qualified Data.Time.LocalTime as Data.Time.LocalTime.Internal.ZonedTime
import qualified Data.Vector
import qualified GHC.Base
import qualified GHC.Classes
import qualified GHC.Int
import qualified GHC.Show
import qualified GHC.Types
import qualified Network.HTTP.Client
import qualified Network.HTTP.Client as Network.HTTP.Client.Request
import qualified Network.HTTP.Client as Network.HTTP.Client.Types
import qualified Network.HTTP.Simple
import qualified Network.HTTP.Types
import qualified Network.HTTP.Types as Network.HTTP.Types.Status
import qualified Network.HTTP.Types as Network.HTTP.Types.URI
import qualified StripeAPI.Common
import StripeAPI.Types
import qualified Prelude as GHC.Integer.Type
import qualified Prelude as GHC.Maybe
-- | > GET /v1/apple_pay/domains/{domain}
--
\<p > Retrieve an apple pay domain.\<\/p >
getApplePayDomainsDomain ::
forall m.
StripeAPI.Common.MonadHTTP m =>
-- | Contains all available parameters of this operation (query and path parameters)
GetApplePayDomainsDomainParameters ->
-- | Monadic computation which returns the result of the operation
StripeAPI.Common.ClientT m (Network.HTTP.Client.Types.Response GetApplePayDomainsDomainResponse)
getApplePayDomainsDomain parameters =
GHC.Base.fmap
( \response_0 ->
GHC.Base.fmap
( Data.Either.either GetApplePayDomainsDomainResponseError GHC.Base.id
GHC.Base.. ( \response body ->
if
| (\status_1 -> Network.HTTP.Types.Status.statusCode status_1 GHC.Classes.== 200) (Network.HTTP.Client.Types.responseStatus response) ->
GetApplePayDomainsDomainResponse200
Data.Functor.<$> ( Data.Aeson.eitherDecodeStrict body ::
Data.Either.Either
GHC.Base.String
ApplePayDomain
)
| GHC.Base.const GHC.Types.True (Network.HTTP.Client.Types.responseStatus response) ->
GetApplePayDomainsDomainResponseDefault
Data.Functor.<$> ( Data.Aeson.eitherDecodeStrict body ::
Data.Either.Either
GHC.Base.String
Error
)
| GHC.Base.otherwise -> Data.Either.Left "Missing default response type"
)
response_0
)
response_0
)
(StripeAPI.Common.doCallWithConfigurationM (Data.Text.toUpper GHC.Base.$ Data.Text.pack "GET") (Data.Text.pack ("/v1/apple_pay/domains/" GHC.Base.++ (Data.ByteString.Char8.unpack (Network.HTTP.Types.URI.urlEncode GHC.Types.True GHC.Base.$ (Data.ByteString.Char8.pack GHC.Base.$ StripeAPI.Common.stringifyModel (getApplePayDomainsDomainParametersPathDomain parameters))) GHC.Base.++ ""))) [StripeAPI.Common.QueryParameter (Data.Text.pack "expand") (Data.Aeson.Types.ToJSON.toJSON Data.Functor.<$> getApplePayDomainsDomainParametersQueryExpand parameters) (Data.Text.pack "deepObject") GHC.Types.True])
-- | Defines the object schema located at @paths.\/v1\/apple_pay\/domains\/{domain}.GET.parameters@ in the specification.
data GetApplePayDomainsDomainParameters = GetApplePayDomainsDomainParameters
{ -- | pathDomain: Represents the parameter named \'domain\'
--
-- Constraints:
--
* Maximum length of 5000
getApplePayDomainsDomainParametersPathDomain :: Data.Text.Internal.Text,
-- | queryExpand: Represents the parameter named \'expand\'
--
-- Specifies which fields in the response should be expanded.
getApplePayDomainsDomainParametersQueryExpand :: (GHC.Maybe.Maybe ([Data.Text.Internal.Text]))
}
deriving
( GHC.Show.Show,
GHC.Classes.Eq
)
instance Data.Aeson.Types.ToJSON.ToJSON GetApplePayDomainsDomainParameters where
toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (["pathDomain" Data.Aeson.Types.ToJSON..= getApplePayDomainsDomainParametersPathDomain obj] : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("queryExpand" Data.Aeson.Types.ToJSON..=)) (getApplePayDomainsDomainParametersQueryExpand obj) : GHC.Base.mempty))
toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (["pathDomain" Data.Aeson.Types.ToJSON..= getApplePayDomainsDomainParametersPathDomain obj] : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("queryExpand" Data.Aeson.Types.ToJSON..=)) (getApplePayDomainsDomainParametersQueryExpand obj) : GHC.Base.mempty)))
instance Data.Aeson.Types.FromJSON.FromJSON GetApplePayDomainsDomainParameters where
parseJSON = Data.Aeson.Types.FromJSON.withObject "GetApplePayDomainsDomainParameters" (\obj -> (GHC.Base.pure GetApplePayDomainsDomainParameters GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "pathDomain")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "queryExpand"))
-- | Create a new 'GetApplePayDomainsDomainParameters' with all required fields.
mkGetApplePayDomainsDomainParameters ::
-- | 'getApplePayDomainsDomainParametersPathDomain'
Data.Text.Internal.Text ->
GetApplePayDomainsDomainParameters
mkGetApplePayDomainsDomainParameters getApplePayDomainsDomainParametersPathDomain =
GetApplePayDomainsDomainParameters
{ getApplePayDomainsDomainParametersPathDomain = getApplePayDomainsDomainParametersPathDomain,
getApplePayDomainsDomainParametersQueryExpand = GHC.Maybe.Nothing
}
-- | Represents a response of the operation 'getApplePayDomainsDomain'.
--
The response constructor is chosen by the status code of the response . If no case matches ( no specific case for the response code , no range case , no default case ) , ' GetApplePayDomainsDomainResponseError ' is used .
data GetApplePayDomainsDomainResponse
= -- | Means either no matching case available or a parse error
GetApplePayDomainsDomainResponseError GHC.Base.String
| -- | Successful response.
GetApplePayDomainsDomainResponse200 ApplePayDomain
| -- | Error response.
GetApplePayDomainsDomainResponseDefault Error
deriving (GHC.Show.Show, GHC.Classes.Eq)
| null |
https://raw.githubusercontent.com/Haskell-OpenAPI-Code-Generator/Stripe-Haskell-Library/ba4401f083ff054f8da68c741f762407919de42f/src/StripeAPI/Operations/GetApplePayDomainsDomain.hs
|
haskell
|
# LANGUAGE ExplicitForAll #
# LANGUAGE MultiWayIf #
# LANGUAGE OverloadedStrings #
| Contains the different functions to run the operation getApplePayDomainsDomain
| > GET /v1/apple_pay/domains/{domain}
| Contains all available parameters of this operation (query and path parameters)
| Monadic computation which returns the result of the operation
| Defines the object schema located at @paths.\/v1\/apple_pay\/domains\/{domain}.GET.parameters@ in the specification.
| pathDomain: Represents the parameter named \'domain\'
Constraints:
| queryExpand: Represents the parameter named \'expand\'
Specifies which fields in the response should be expanded.
| Create a new 'GetApplePayDomainsDomainParameters' with all required fields.
| 'getApplePayDomainsDomainParametersPathDomain'
| Represents a response of the operation 'getApplePayDomainsDomain'.
| Means either no matching case available or a parse error
| Successful response.
| Error response.
|
CHANGE WITH CAUTION : This is a generated code file generated by -OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator .
module StripeAPI.Operations.GetApplePayDomainsDomain where
import qualified Control.Monad.Fail
import qualified Control.Monad.Trans.Reader
import qualified Data.Aeson
import qualified Data.Aeson as Data.Aeson.Encoding.Internal
import qualified Data.Aeson as Data.Aeson.Types
import qualified Data.Aeson as Data.Aeson.Types.FromJSON
import qualified Data.Aeson as Data.Aeson.Types.Internal
import qualified Data.Aeson as Data.Aeson.Types.ToJSON
import qualified Data.ByteString.Char8
import qualified Data.ByteString.Char8 as Data.ByteString.Internal
import qualified Data.Either
import qualified Data.Foldable
import qualified Data.Functor
import qualified Data.Maybe
import qualified Data.Scientific
import qualified Data.Text
import qualified Data.Text.Internal
import qualified Data.Time.Calendar as Data.Time.Calendar.Days
import qualified Data.Time.LocalTime as Data.Time.LocalTime.Internal.ZonedTime
import qualified Data.Vector
import qualified GHC.Base
import qualified GHC.Classes
import qualified GHC.Int
import qualified GHC.Show
import qualified GHC.Types
import qualified Network.HTTP.Client
import qualified Network.HTTP.Client as Network.HTTP.Client.Request
import qualified Network.HTTP.Client as Network.HTTP.Client.Types
import qualified Network.HTTP.Simple
import qualified Network.HTTP.Types
import qualified Network.HTTP.Types as Network.HTTP.Types.Status
import qualified Network.HTTP.Types as Network.HTTP.Types.URI
import qualified StripeAPI.Common
import StripeAPI.Types
import qualified Prelude as GHC.Integer.Type
import qualified Prelude as GHC.Maybe
\<p > Retrieve an apple pay domain.\<\/p >
getApplePayDomainsDomain ::
forall m.
StripeAPI.Common.MonadHTTP m =>
GetApplePayDomainsDomainParameters ->
StripeAPI.Common.ClientT m (Network.HTTP.Client.Types.Response GetApplePayDomainsDomainResponse)
getApplePayDomainsDomain parameters =
GHC.Base.fmap
( \response_0 ->
GHC.Base.fmap
( Data.Either.either GetApplePayDomainsDomainResponseError GHC.Base.id
GHC.Base.. ( \response body ->
if
| (\status_1 -> Network.HTTP.Types.Status.statusCode status_1 GHC.Classes.== 200) (Network.HTTP.Client.Types.responseStatus response) ->
GetApplePayDomainsDomainResponse200
Data.Functor.<$> ( Data.Aeson.eitherDecodeStrict body ::
Data.Either.Either
GHC.Base.String
ApplePayDomain
)
| GHC.Base.const GHC.Types.True (Network.HTTP.Client.Types.responseStatus response) ->
GetApplePayDomainsDomainResponseDefault
Data.Functor.<$> ( Data.Aeson.eitherDecodeStrict body ::
Data.Either.Either
GHC.Base.String
Error
)
| GHC.Base.otherwise -> Data.Either.Left "Missing default response type"
)
response_0
)
response_0
)
(StripeAPI.Common.doCallWithConfigurationM (Data.Text.toUpper GHC.Base.$ Data.Text.pack "GET") (Data.Text.pack ("/v1/apple_pay/domains/" GHC.Base.++ (Data.ByteString.Char8.unpack (Network.HTTP.Types.URI.urlEncode GHC.Types.True GHC.Base.$ (Data.ByteString.Char8.pack GHC.Base.$ StripeAPI.Common.stringifyModel (getApplePayDomainsDomainParametersPathDomain parameters))) GHC.Base.++ ""))) [StripeAPI.Common.QueryParameter (Data.Text.pack "expand") (Data.Aeson.Types.ToJSON.toJSON Data.Functor.<$> getApplePayDomainsDomainParametersQueryExpand parameters) (Data.Text.pack "deepObject") GHC.Types.True])
data GetApplePayDomainsDomainParameters = GetApplePayDomainsDomainParameters
* Maximum length of 5000
getApplePayDomainsDomainParametersPathDomain :: Data.Text.Internal.Text,
getApplePayDomainsDomainParametersQueryExpand :: (GHC.Maybe.Maybe ([Data.Text.Internal.Text]))
}
deriving
( GHC.Show.Show,
GHC.Classes.Eq
)
instance Data.Aeson.Types.ToJSON.ToJSON GetApplePayDomainsDomainParameters where
toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (["pathDomain" Data.Aeson.Types.ToJSON..= getApplePayDomainsDomainParametersPathDomain obj] : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("queryExpand" Data.Aeson.Types.ToJSON..=)) (getApplePayDomainsDomainParametersQueryExpand obj) : GHC.Base.mempty))
toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (["pathDomain" Data.Aeson.Types.ToJSON..= getApplePayDomainsDomainParametersPathDomain obj] : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("queryExpand" Data.Aeson.Types.ToJSON..=)) (getApplePayDomainsDomainParametersQueryExpand obj) : GHC.Base.mempty)))
instance Data.Aeson.Types.FromJSON.FromJSON GetApplePayDomainsDomainParameters where
parseJSON = Data.Aeson.Types.FromJSON.withObject "GetApplePayDomainsDomainParameters" (\obj -> (GHC.Base.pure GetApplePayDomainsDomainParameters GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "pathDomain")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "queryExpand"))
mkGetApplePayDomainsDomainParameters ::
Data.Text.Internal.Text ->
GetApplePayDomainsDomainParameters
mkGetApplePayDomainsDomainParameters getApplePayDomainsDomainParametersPathDomain =
GetApplePayDomainsDomainParameters
{ getApplePayDomainsDomainParametersPathDomain = getApplePayDomainsDomainParametersPathDomain,
getApplePayDomainsDomainParametersQueryExpand = GHC.Maybe.Nothing
}
The response constructor is chosen by the status code of the response . If no case matches ( no specific case for the response code , no range case , no default case ) , ' GetApplePayDomainsDomainResponseError ' is used .
data GetApplePayDomainsDomainResponse
GetApplePayDomainsDomainResponseError GHC.Base.String
GetApplePayDomainsDomainResponse200 ApplePayDomain
GetApplePayDomainsDomainResponseDefault Error
deriving (GHC.Show.Show, GHC.Classes.Eq)
|
c786134b2c84b5ad35505a2b49a109438ca8e7fbca4e3dad46d200a38748b80c
|
thomaseding/hearthshroud
|
Cards.hs
|
{-# LANGUAGE ConstraintKinds #-}
# LANGUAGE DataKinds #
# LANGUAGE NoMonomorphismRestriction #
# LANGUAGE RebindableSyntax #
module Hearth.Authored.CardSet.Basic.Cards (
cards,
healingTotem,
searingTotem,
silverHandRecruit,
stoneclawTotem,
theCoin,
wickedKnife,
wrathOfAirTotem,
) where
--------------------------------------------------------------------------------
import Hearth.Authored.CardSet.Basic.Names hiding (Charge, Windfury)
import Hearth.Combinator.Authoring
import Hearth.Combinator.Authoring.RebindableSyntax
import Hearth.Model.Authoring
import Prelude hiding (fromInteger, sequence)
import qualified Hearth.Authored.CardSet.Basic.Names as Basic
--------------------------------------------------------------------------------
cards :: [Card]
cards = let x = toCard in [
x acidicSwampOoze,
x ancestralHealing,
x animalCompanion,
x arcaneExplosion,
x arcaneIntellect,
x arcaneMissiles,
x arcaneShot,
x arcaniteReaper,
x archmage,
x assassinate,
x assassin'sBlade,
x backstab,
x blessingOfKings,
x blessingOfMight,
x bloodfenRaptor,
x bloodlust,
x bluegillWarrior,
x boar,
x bootyBayBodyguard,
x boulderfistOgre,
x charge,
x chillwindYeti,
x claw,
x cleave,
x consecration,
x coreHound,
x corruption,
x dalaranMage,
x darkscaleHealer,
x deadlyPoison,
x deadlyShot,
x divineSpirit,
x dragonlingMechanic,
x drainLife,
x dreadInfernal,
x elvenArcher,
x excessMana,
x execute,
x fanOfKnives,
x fireball,
x fireElemental,
x flamestrike,
x flametongueTotem,
x frog,
x frostbolt,
x frostNova,
x frostShock,
x frostwolfGrunt,
x frostwolfWarlord,
x gnomishInventor,
x goldshireFootman,
x grimscaleOracle,
x guardianOfKings,
x gurubashiBerserker,
x hammerOfWrath,
x handOfProtection,
x healingTotem,
x healingTouch,
x hellfire,
x heroicStrike,
x hex,
x holyLight,
x holyNova,
x holySmite,
x houndmaster,
x huffer,
x humility,
x hunter'sMark,
x ironbarkProtector,
x innervate,
x ironforgeRifleman,
x killCommand,
x koboldGeomancer,
x kor'kronElite,
x leokk,
x light'sJustice,
x lordOfTheArena,
x magmaRager,
x markOfTheWild,
x mechanicalDragonling,
x mindBlast,
x mindControl,
x mirrorImage_minion,
x mirrorImage_spell,
x misha,
x moonfire,
x mortalCoil,
x multiShot,
x murlocRaider,
x murlocScout,
x murlocTidehunter,
x nightblade,
x northshireCleric,
x noviceEngineer,
x oasisSnapjaw,
x ogreMagi,
x polymorph,
x powerWordShield,
x raidLeader,
x razorfenHunter,
x recklessRocketeer,
x riverCrocolisk,
x rockbiterWeapon,
x sacrificialPact,
x savageRoar,
x searingTotem,
x sen'jinShieldmasta,
x shadowBolt,
x shadowWordDeath,
x shadowWordPain,
x shatteredSunCleric,
x sheep,
x shieldBlock,
x shiv,
x silverbackPatriarch,
x silverHandRecruit,
x sinisterStrike,
x soulfire,
x sprint,
x starfire,
x stoneclawTotem,
x stonetuskBoar,
x stormpikeCommando,
x stormwindChampion,
x stormwindKnight,
x succubus,
x swipe,
x theCoin,
x timberWolf,
x totemicMight,
x tundraRhino,
x voidwalker,
x voodooDoctor,
x warGolem,
x warsongCommander,
x waterElemental,
x whirlwind,
x wickedKnife,
x wildGrowth,
x windfury,
x windspeaker,
x wolfRider,
x wrathOfAirTotem ]
--------------------------------------------------------------------------------
mkMinion :: Class -> BasicCardName -> [Tribe] -> Mana -> Attack -> Health -> [Ability 'Minion'] -> MinionCard
mkMinion = mkMinion' BasicCardName Free
mkSpell :: Class -> BasicCardName -> Mana -> SpellEffect -> SpellCard
mkSpell = mkSpell' BasicCardName Free
mkWeapon :: Class -> BasicCardName -> Mana -> Attack -> Durability -> [Ability 'Weapon'] -> WeaponCard
mkWeapon = mkWeapon' BasicCardName Free
--------------------------------------------------------------------------------
acidicSwampOoze :: MinionCard
acidicSwampOoze = mkMinion Neutral AcidicSwampOoze [] 2 3 2 [
Battlecry $ \this ->
ownerOf this $ \you ->
opponentOf you $ \opponent ->
A $ Weapon [OwnedBy opponent] $ \weapon ->
Effect $ destroy weapon ]
ancestralHealing :: SpellCard
ancestralHealing = mkSpell Shaman AncestralHealing 0 $ \_ ->
A $ Minion [] $ \minion ->
Effect $ sequence [
RestoreToFullHealth $ asCharacter minion,
enchant minion $ Grant Taunt ]
animalCompanion :: SpellCard
animalCompanion = mkSpell Hunter AnimalCompanion 3 $ \this ->
ownerOf this $ \you ->
Effect $ Get $ ChooseOne' $ map (\minion -> Effect $ (Summon minion) $ Rightmost you) [
huffer,
leokk,
misha ]
arcaneExplosion :: SpellCard
arcaneExplosion = mkSpell Mage ArcaneExplosion 2 $ \this ->
ownerOf this $ \you ->
opponentOf you $ \opponent ->
All $ Minions [OwnedBy opponent] $ \enemies ->
Effect $ forEach enemies $ \enemy ->
(this `damages` enemy) 1
arcaneIntellect :: SpellCard
arcaneIntellect = mkSpell Mage ArcaneIntellect 3 $ \this ->
ownerOf this $ \you ->
Effect $ DrawCards you 2
arcaneMissiles :: SpellCard
arcaneMissiles = mkSpell Mage ArcaneMissiles 1 $ \this ->
ownerOf this $ \you ->
opponentOf you $ \opponent ->
Effect $ RandomMissiles [OwnedBy opponent] 3 this
arcaneShot :: SpellCard
arcaneShot = mkSpell Hunter ArcaneShot 1 $ \this ->
A $ Character [] $ \target ->
Effect $ (this `damages` target) 2
arcaniteReaper :: WeaponCard
arcaniteReaper = mkWeapon Warrior ArcaniteReaper 5 5 2 []
archmage :: MinionCard
archmage = mkMinion Neutral Archmage [] 6 4 7 [
SpellDamage 1 ]
assassinate :: SpellCard
assassinate = mkSpell Rogue Assassinate 5 $ \_ ->
A $ Minion [] $ \target ->
Effect $ destroy target
assassin'sBlade :: WeaponCard
assassin'sBlade = mkWeapon Rogue Assassin'sBlade 5 3 4 []
backstab :: SpellCard
backstab = mkSpell Rogue Backstab 0 $ \this ->
A $ Minion [undamaged] $ \target ->
Effect $ (this `damages` target) 2
blessingOfKings :: SpellCard
blessingOfKings = mkSpell Paladin BlessingOfKings 4 $ \_ ->
A $ Minion [] $ \target ->
Effect $ sequence [
enchant target $ gainAttack 4,
enchant target $ GainHealth 4 ]
blessingOfMight :: SpellCard
blessingOfMight = mkSpell Paladin BlessingOfMight 1 $ \_ ->
A $ Minion [] $ \target ->
Effect $ enchant target $ gainAttack 3
bloodfenRaptor :: MinionCard
bloodfenRaptor = mkMinion Neutral BloodfenRaptor [Beast] 2 3 2 []
bloodlust :: SpellCard
bloodlust = mkSpell Shaman Bloodlust 5 $ \this ->
ownerOf this $ \you ->
All $ Minions [OwnedBy you] $ \minions ->
Effect $ forEach minions $ \minion ->
enchant minion $ Until EndOfTurn $ gainAttack 3
bluegillWarrior :: MinionCard
bluegillWarrior = mkMinion Neutral BluegillWarrior [Murloc] 2 2 1 [
Charge ]
boar :: MinionCard
boar = uncollectible $ mkMinion Neutral Boar [Beast] 1 1 1 []
bootyBayBodyguard :: MinionCard
bootyBayBodyguard = mkMinion Neutral BootyBayBodyguard [] 5 5 4 [
Taunt ]
boulderfistOgre :: MinionCard
boulderfistOgre = mkMinion Neutral BoulderfistOgre [] 6 6 7 []
charge :: SpellCard
charge = mkSpell Warrior Basic.Charge 3 $ \this ->
ownerOf this $ \you ->
A $ Minion [OwnedBy you] $ \target ->
Effect $ sequence [
enchant target $ gainAttack 2,
enchant target $ Grant Charge ]
chillwindYeti :: MinionCard
chillwindYeti = mkMinion Neutral ChillwindYeti [] 4 4 5 []
claw :: SpellCard
claw = mkSpell Druid Claw 1 $ \this ->
ownerOf this $ \you ->
Effect $ sequence [
enchant you $ Until EndOfTurn $ gainAttack 2,
GainArmor you 2 ]
cleave :: SpellCard
cleave = mkSpell Warrior Cleave 2 $ \this ->
ownerOf this $ \you ->
opponentOf you $ \opponent ->
Effect $ Get $ A $ Minion [OwnedBy opponent] $ \victim1 ->
A $ Minion [OwnedBy opponent, Not victim1] $ \victim2 ->
Effect $ forEach (handleList [victim1, victim2]) $ \victim ->
(this `damages` victim) 2
consecration :: SpellCard
consecration = mkSpell Paladin Consecration 4 $ \this ->
ownerOf this $ \you ->
opponentOf you $ \opponent ->
All $ Characters [OwnedBy opponent] $ \enemies ->
Effect $ forEach enemies $ \enemy ->
(this `damages` enemy) 2
coreHound :: MinionCard
coreHound = mkMinion Neutral CoreHound [Beast] 7 9 5 []
corruption :: SpellCard
corruption = mkSpell Warlock Corruption 1 $ \this ->
ownerOf this $ \you ->
opponentOf you $ \opponent ->
A $ Minion [OwnedBy opponent] $ \target ->
Effect $ enchant target $ DelayedEffect (Delay 1 BeginOfTurn) $ destroy target
dalaranMage :: MinionCard
dalaranMage = mkMinion Neutral DalaranMage [] 3 1 4 [
SpellDamage 1 ]
darkscaleHealer :: MinionCard
darkscaleHealer = mkMinion Neutral DarkscaleHealer [] 5 4 5 [
Battlecry $ \this ->
ownerOf this $ \you ->
All $ Characters [OwnedBy you] $ \friendlies ->
Effect $ forEach friendlies $ \friendly ->
RestoreHealth friendly 2 ]
deadlyPoison :: SpellCard
deadlyPoison = mkSpell Rogue DeadlyPoison 1 $ \this ->
ownerOf this $ \you ->
A $ Weapon [OwnedBy you] $ \weapon ->
Effect $ enchant weapon $ AttackDelta 2
deadlyShot :: SpellCard
deadlyShot = mkSpell Hunter DeadlyShot 3 $ \this ->
ownerOf this $ \you ->
opponentOf you $ \opponent ->
Effect $ Get $ A $ Minion [OwnedBy opponent] $ \victim ->
Effect $ destroy victim
divineSpirit :: SpellCard
divineSpirit = mkSpell Priest DivineSpirit 2 $ \_ ->
A $ Minion [] $ \target ->
Effect $ enchant target $ StatsScale 1 2
dragonlingMechanic :: MinionCard
dragonlingMechanic = mkMinion Neutral DragonlingMechanic [] 4 2 4 [
Battlecry $ \this ->
Effect $ (Summon mechanicalDragonling) $ RightOf this ]
drainLife :: SpellCard
drainLife = mkSpell Warlock DrainLife 3 $ \this ->
A $ Character [] $ \target ->
ownerOf this $ \you ->
Effect $ sequence [
(this `damages` target) 2,
RestoreHealth (asCharacter you) 2 ]
dreadInfernal :: MinionCard
dreadInfernal = mkMinion Warlock DreadInfernal [Demon] 6 6 6 [
Battlecry $ \this ->
All $ Characters [Not (asCharacter this)] $ \victims ->
Effect $ forEach victims $ \victim ->
(this `damages` victim) 1 ]
elvenArcher :: MinionCard
elvenArcher = mkMinion Neutral ElvenArcher [] 1 1 1 [
Battlecry $ \this ->
A $ Character [] $ \target ->
Effect $ (this `damages` target) 1 ]
excessMana :: SpellCard
excessMana = uncollectible $ mkSpell Druid ExcessMana 0 $ \this ->
ownerOf this $ \you ->
Effect $ DrawCards you 1
execute :: SpellCard
execute = mkSpell Warrior Execute 1 $ \_ ->
A $ Minion [damaged] $ \target ->
Effect $ destroy target
fanOfKnives :: SpellCard
fanOfKnives = mkSpell Rogue FanOfKnives 4 $ \this ->
ownerOf this $ \you ->
opponentOf you $ \opponent ->
All $ Minions [OwnedBy opponent] $ \enemies ->
Effect $ sequence [
forEach enemies $ \enemy ->
(this `damages` enemy) 1,
DrawCards you 1 ]
fireball :: SpellCard
fireball = mkSpell Mage Fireball 4 $ \this ->
A $ Character [] $ \target ->
Effect $ (this `damages` target) 6
fireElemental :: MinionCard
fireElemental = mkMinion Shaman FireElemental [] 6 6 5 [
Battlecry $ \this ->
A $ Character [] $ \target ->
Effect $ (this `damages` target) 3 ]
flamestrike :: SpellCard
flamestrike = mkSpell Mage Flamestrike 7 $ \this ->
ownerOf this $ \you ->
opponentOf you $ \opponent ->
All $ Minions [OwnedBy opponent] $ \victims ->
Effect $ forEach victims $ \victim ->
(this `damages` victim) 4
flametongueTotem :: MinionCard
flametongueTotem = mkMinion Shaman FlametongueTotem [Totem] 2 0 3 [
aura $ \this ->
EachMinion [AdjacentTo this] $ \minion ->
Has minion $ gainAttack 2 ]
frog :: MinionCard
frog = uncollectible $ mkMinion Neutral Frog [Beast] 0 0 1 [
Taunt ]
frostbolt :: SpellCard
frostbolt = mkSpell Mage Frostbolt 2 $ \this ->
A $ Character [] $ \target ->
Effect $ sequence [
(this `damages` target) 3,
Freeze target ]
frostNova :: SpellCard
frostNova = mkSpell Mage FrostNova 3 $ \this ->
ownerOf this $ \you ->
opponentOf you $ \opponent ->
All $ Minions [OwnedBy opponent] $ \victims ->
Effect $ forEach victims $ \victim ->
Freeze (asCharacter victim)
frostShock :: SpellCard
frostShock = mkSpell Shaman FrostShock 1 $ \this ->
A $ Character [] $ \target ->
Effect $ sequence [
(this `damages` target) 1,
Freeze target ]
frostwolfGrunt :: MinionCard
frostwolfGrunt = mkMinion Neutral FrostwolfGrunt [] 2 2 2 [
Taunt ]
frostwolfWarlord :: MinionCard
frostwolfWarlord = mkMinion Neutral FrostwolfWarlord [] 5 4 4 [
Battlecry $ \this ->
ownerOf this $ \you ->
All $ Minions [OwnedBy you, Not this] $ \minions ->
Effect $ forEach minions $ \_ ->
sequence [
enchant this $ gainAttack 1,
enchant this $ GainHealth 1 ]]
gnomishInventor :: MinionCard
gnomishInventor = mkMinion Neutral GnomishInventor [] 4 2 4 [
Battlecry $ \this ->
ownerOf this $ \you ->
Effect $ DrawCards you 1 ]
goldshireFootman :: MinionCard
goldshireFootman = mkMinion Neutral GoldshireFootman [] 1 1 2 [
Taunt ]
grimscaleOracle :: MinionCard
grimscaleOracle = mkMinion Neutral GrimscaleOracle [Murloc] 1 1 1 [
aura $ \this ->
EachMinion [Not this, OfTribe Murloc] $ \minion ->
Has minion $ gainAttack 1 ]
guardianOfKings :: MinionCard
guardianOfKings = mkMinion Paladin GuardianOfKings [] 7 5 6 [
Battlecry $ \this ->
ownerOf this $ \you ->
Effect $ RestoreHealth (asCharacter you) 6 ]
gurubashiBerserker :: MinionCard
gurubashiBerserker = mkMinion Neutral GurubashiBerserker [] 5 2 7 [
observer $ \this ->
DamageIsDealt $ \victim _ _ ->
Effect $ when (asCharacter this `Satisfies` [Is victim]) $ enchant this $ gainAttack 3 ]
hammerOfWrath :: SpellCard
hammerOfWrath = mkSpell Paladin HammerOfWrath 4 $ \this ->
A $ Character [] $ \target ->
ownerOf this $ \you ->
Effect $ sequence [
(this `damages` target) 3,
DrawCards you 1 ]
handOfProtection :: SpellCard
handOfProtection = mkSpell Paladin HandOfProtection 1 $ \_ ->
A $ Minion [] $ \target ->
Effect $ enchant target $ Grant DivineShield
healingTotem :: MinionCard
healingTotem = uncollectible $ mkMinion Shaman HealingTotem [Totem] 1 0 2 [
observer $ \this ->
EndOfTurnEvent $ \player ->
ownerOf this $ \you ->
Effect $ when (player `Satisfies` [Is you]) $ Get $ All $ Minions [OwnedBy you] $ \minions ->
Effect $ forEach minions $ \minion ->
RestoreHealth (asCharacter minion) 1 ]
healingTouch :: SpellCard
healingTouch = mkSpell Druid HealingTouch 3 $ \_ ->
A $ Character [] $ \target ->
Effect $ RestoreHealth target 8
hellfire :: SpellCard
hellfire = mkSpell Warlock Hellfire 4 $ \this ->
All $ Characters [] $ \victims ->
Effect $ forEach victims $ \victim ->
(this `damages` victim) 3
heroicStrike :: SpellCard
heroicStrike = mkSpell Warrior HeroicStrike 2 $ \this ->
ownerOf this $ \you ->
Effect $ enchant you $ Until EndOfTurn $ gainAttack 4
hex :: SpellCard
hex = mkSpell Shaman Hex 3 $ \_ ->
A $ Minion [] $ \target ->
Effect $ Transform target frog
holyLight :: SpellCard
holyLight = mkSpell Paladin HolyLight 2 $ \_ ->
A $ Character [] $ \target ->
Effect $ RestoreHealth target 6
holyNova :: SpellCard
holyNova = mkSpell Priest HolyNova 5 $ \this ->
ownerOf this $ \you ->
opponentOf you $ \opponent ->
All $ Characters [OwnedBy you] $ \friendlies ->
All $ Characters [OwnedBy opponent] $ \enemies ->
Effect $ sequence [
forEach enemies $ \enemy ->
(this `damages` enemy) 2,
forEach friendlies $ \friendly ->
RestoreHealth friendly 2 ]
holySmite :: SpellCard
holySmite = mkSpell Priest HolySmite 1 $ \this ->
A $ Character [] $ \target ->
Effect $ (this `damages` target) 2
houndmaster :: MinionCard
houndmaster = mkMinion Hunter Houndmaster [] 4 4 3 [
Battlecry $ \this ->
ownerOf this $ \you ->
A $ Minion [OwnedBy you, OfTribe Beast] $ \beast ->
Effect $ sequence [
enchant beast $ gainAttack 2,
enchant beast $ GainHealth 2,
enchant beast $ Grant Taunt ]]
huffer :: MinionCard
huffer = uncollectible $ mkMinion Hunter Huffer [Beast] 3 4 2 [
Charge ]
humility :: SpellCard
humility = mkSpell Paladin Humility 1 $ \_ ->
A $ Minion [] $ \target ->
Effect $ enchant target $ ChangeStat $ Left 1
hunter'sMark :: SpellCard
hunter'sMark = mkSpell Hunter Hunter'sMark 1 $ \_ ->
A $ Minion [] $ \target ->
Effect $ enchant target $ ChangeStat $ Right 1
koboldGeomancer :: MinionCard
koboldGeomancer = mkMinion Neutral KoboldGeomancer [] 2 2 2 [
SpellDamage 1 ]
kor'kronElite :: MinionCard
kor'kronElite = mkMinion Warrior Kor'kronElite [] 4 4 3 [
Charge ]
innervate :: SpellCard
innervate = mkSpell Druid Innervate 0 $ \this ->
ownerOf this $ \you ->
Effect $ GainManaCrystals you 2 CrystalTemporary
ironbarkProtector :: MinionCard
ironbarkProtector = mkMinion Druid IronbarkProtector [] 8 8 8 [
Taunt ]
ironforgeRifleman :: MinionCard
ironforgeRifleman = mkMinion Neutral IronforgeRifleman [] 3 2 2 [
Battlecry $ \this ->
A $ Character [] $ \target ->
Effect $ (this `damages` target) 1 ]
killCommand :: SpellCard
killCommand = mkSpell Hunter KillCommand 3 $ \this ->
ownerOf this $ \you ->
A $ Character [] $ \victim -> let
deal = this `damages` victim
in Effect $ if you `Satisfies` [HasMinion [OfTribe Beast]]
then deal 5
else deal 3
leokk :: MinionCard
leokk = uncollectible $ mkMinion Hunter Leokk [Beast] 3 2 4 [
aura $ \this ->
ownerOf this $ \you ->
EachMinion [Not this, OwnedBy you] $ \minion ->
Has minion $ gainAttack 1 ]
light'sJustice :: WeaponCard
light'sJustice = mkWeapon Paladin Light'sJustice 1 1 4 []
lordOfTheArena :: MinionCard
lordOfTheArena = mkMinion Neutral LordOfTheArena [] 6 6 5 [
Taunt ]
markOfTheWild :: SpellCard
markOfTheWild = mkSpell Druid MarkOfTheWild 2 $ \_ ->
A $ Minion [] $ \target ->
Effect $ sequence [
enchant target $ Grant Taunt,
enchant target $ gainAttack 2,
enchant target $ GainHealth 2 ]
magmaRager :: MinionCard
magmaRager = mkMinion Neutral MagmaRager [] 3 5 1 []
mechanicalDragonling :: MinionCard
mechanicalDragonling = uncollectible $ mkMinion Neutral MechanicalDragonling [Mech] 1 2 1 []
mindBlast :: SpellCard
mindBlast = mkSpell Priest MindBlast 2 $ \this ->
ownerOf this $ \you ->
opponentOf you $ \opponent ->
Effect $ (this `damages` opponent) 5
mindControl :: SpellCard
mindControl = mkSpell Priest MindControl 10 $ \this ->
ownerOf this $ \you ->
opponentOf you $ \opponent ->
A $ Minion [OwnedBy opponent] $ \victim ->
Effect $ TakeControl you victim
mirrorImage_minion :: MinionCard
mirrorImage_minion = uncollectible $ mkMinion Mage MirrorImage_Minion [] 1 0 2 [
Taunt ]
mirrorImage_spell :: SpellCard
mirrorImage_spell = mkSpell Mage MirrorImage_Spell 1 $ \this ->
ownerOf this $ \you ->
Effect $ sequence $ replicate 2 $ (Summon mirrorImage_minion) $ Rightmost you
misha :: MinionCard
misha = uncollectible $ mkMinion Hunter Misha [Beast] 3 4 4 [
Taunt ]
moonfire :: SpellCard
moonfire = mkSpell Druid Moonfire 0 $ \this ->
A $ Character [] $ \target ->
Effect $ (this `damages` target) 1
-- TODO:
MortalCoil hitting a KnifeJuggler juggled to death minion ( triggered from say your VioletTeacher )
-- Need to match this behavior -
-- Comprehensive explanation -
mortalCoil :: SpellCard
mortalCoil = mkSpell Warlock MortalCoil 1 $ \this ->
ownerOf this $ \you ->
A $ Minion [] $ \target -> let
effect = (this `damages` target) 1
in Effect $ Observing effect $ DamageIsDealt $ \victim _ source -> let
condition = this `Satisfies` [IsDamageSource source]
`And` victim `Satisfies` [withHealth LessEqual 0]
in Effect $ when condition $ DrawCards you 1
multiShot :: SpellCard
multiShot = mkSpell Hunter MultiShot 4 $ \this ->
ownerOf this $ \you ->
opponentOf you $ \opponent ->
Effect $ Get $ A $ Minion [OwnedBy opponent] $ \victim1 ->
A $ Minion [OwnedBy opponent, Not victim1] $ \victim2 ->
Effect $ forEach (handleList [victim1, victim2]) $ \victim ->
(this `damages` victim) 3
murlocRaider :: MinionCard
murlocRaider = mkMinion Neutral MurlocRaider [Murloc] 1 2 1 []
murlocScout :: MinionCard
murlocScout = uncollectible $ mkMinion Neutral MurlocScout [Murloc] 0 1 1 []
murlocTidehunter :: MinionCard
murlocTidehunter = mkMinion Neutral MurlocTidehunter [Murloc] 2 2 1 [
Battlecry $ \this ->
Effect $ (Summon murlocScout) $ RightOf this ]
nightblade :: MinionCard
nightblade = mkMinion Neutral Nightblade [] 5 4 4 [
Battlecry $ \this ->
ownerOf this $ \you ->
opponentOf you $ \opponent ->
Effect $ (this `damages` opponent) 3 ]
northshireCleric :: MinionCard
northshireCleric = mkMinion Priest NorthshireCleric [] 1 1 3 [
observer $ \this ->
HealthIsRestored $ \recipient _ ->
ownerOf this $ \you ->
Effect $ when (recipient `Satisfies` [IsMinion]) $ DrawCards you 1 ]
noviceEngineer :: MinionCard
noviceEngineer = mkMinion Neutral NoviceEngineer [] 2 1 1 [
Battlecry $ \this ->
ownerOf this $ \you ->
Effect $ DrawCards you 1 ]
oasisSnapjaw :: MinionCard
oasisSnapjaw = mkMinion Neutral OasisSnapjaw [Beast] 4 2 7 []
ogreMagi :: MinionCard
ogreMagi = mkMinion Neutral OgreMagi [] 4 4 4 [
SpellDamage 1 ]
polymorph :: SpellCard
polymorph = mkSpell Mage Polymorph 4 $ \_ ->
A $ Minion [] $ \target ->
Effect $ Transform target sheep
powerWordShield :: SpellCard
powerWordShield = mkSpell Priest PowerWordShield 1 $ \this ->
A $ Minion [] $ \target ->
ownerOf this $ \you ->
Effect $ sequence [
enchant target $ GainHealth 2,
DrawCards you 1 ]
raidLeader :: MinionCard
raidLeader = mkMinion Neutral RaidLeader [] 3 2 2 [
aura $ \this ->
ownerOf this $ \you ->
EachMinion [OwnedBy you, Not this] $ \minion ->
Has minion $ gainAttack 1 ]
razorfenHunter :: MinionCard
razorfenHunter = mkMinion Neutral RazorfenHunter [] 3 2 3 [
Battlecry $ \this ->
Effect $ (Summon boar) $ RightOf this ]
recklessRocketeer :: MinionCard
recklessRocketeer = mkMinion Neutral RecklessRocketeer [] 6 5 2 [
Charge ]
riverCrocolisk :: MinionCard
riverCrocolisk = mkMinion Neutral RiverCrocolisk [Beast] 2 2 3 []
rockbiterWeapon :: SpellCard
rockbiterWeapon = mkSpell Shaman RockbiterWeapon 1 $ \this ->
ownerOf this $ \you ->
A $ Character [OwnedBy you] $ \target ->
Effect $ enchant target $ Until EndOfTurn $ gainAttack 3
sacrificialPact :: SpellCard
sacrificialPact = mkSpell Warlock SacrificialPact 0 $ \this ->
ownerOf this $ \you ->
A $ Minion [OfTribe Demon] $ \demon ->
Effect $ sequence [
destroy demon,
RestoreHealth (asCharacter you) 5 ]
savageRoar :: SpellCard
savageRoar = mkSpell Druid SavageRoar 3 $ \this ->
ownerOf this $ \you ->
All $ Characters [OwnedBy you] $ \friendlies ->
Effect $ forEach friendlies $ \friendly ->
enchant friendly $ Until EndOfTurn $ gainAttack 2
searingTotem :: MinionCard
searingTotem = uncollectible $ mkMinion Shaman SearingTotem [Totem] 1 1 1 []
sen'jinShieldmasta :: MinionCard
sen'jinShieldmasta = mkMinion Neutral Sen'jinShieldmasta [] 4 3 5 [
Taunt ]
shadowBolt :: SpellCard
shadowBolt = mkSpell Warlock ShadowBolt 3 $ \this ->
A $ Minion [] $ \target ->
Effect $ (this `damages` target) 4
shadowWordDeath :: SpellCard
shadowWordDeath = mkSpell Priest ShadowWordDeath 3 $ \_ ->
A $ Minion [withAttack GreaterEqual 5] $ \target ->
Effect $ destroy target
shadowWordPain :: SpellCard
shadowWordPain = mkSpell Priest ShadowWordPain 2 $ \_ ->
A $ Minion [withAttack LessEqual 3] $ \target ->
Effect $ destroy target
shatteredSunCleric :: MinionCard
shatteredSunCleric = mkMinion Neutral ShatteredSunCleric [] 3 3 2 [
Battlecry $ \this ->
ownerOf this $ \you ->
A $ Minion [OwnedBy you] $ \target ->
Effect $ sequence [
enchant target $ gainAttack 1,
enchant target $ GainHealth 1 ]]
sheep :: MinionCard
sheep = uncollectible $ mkMinion Neutral Sheep [Beast] 0 1 1 []
shieldBlock :: SpellCard
shieldBlock = mkSpell Warrior ShieldBlock 3 $ \this ->
ownerOf this $ \you ->
Effect $ sequence [
GainArmor you 5,
DrawCards you 1 ]
shiv :: SpellCard
shiv = mkSpell Rogue Shiv 2 $ \this ->
A $ Character [] $ \target ->
ownerOf this $ \you ->
Effect $ sequence [
(this `damages` target) 1,
DrawCards you 1 ]
silverbackPatriarch :: MinionCard
silverbackPatriarch = mkMinion Neutral SilverbackPatriarch [Beast] 3 1 4 [
Taunt ]
silverHandRecruit :: MinionCard
silverHandRecruit = uncollectible $ mkMinion Paladin SilverHandRecruit [] 1 1 1 []
sinisterStrike :: SpellCard
sinisterStrike = mkSpell Rogue SinisterStrike 1 $ \this ->
ownerOf this $ \you ->
opponentOf you $ \opponent ->
Effect $ (this `damages` opponent) 3
soulfire :: SpellCard
soulfire = mkSpell Warlock Soulfire 1 $ \this ->
ownerOf this $ \you ->
A $ Character [] $ \victim ->
Effect $ sequence [
(this `damages` victim) 4,
DiscardAtRandom you ]
sprint :: SpellCard
sprint = mkSpell Rogue Sprint 7 $ \this ->
ownerOf this $ \you ->
Effect $ DrawCards you 4
starfire :: SpellCard
starfire = mkSpell Druid Starfire 6 $ \this ->
A $ Character [] $ \target ->
ownerOf this $ \you ->
Effect $ sequence [
(this `damages` target) 5,
DrawCards you 1 ]
stoneclawTotem :: MinionCard
stoneclawTotem = uncollectible $ mkMinion Shaman StoneclawTotem [Totem] 1 0 2 [
Taunt ]
stonetuskBoar :: MinionCard
stonetuskBoar = mkMinion Neutral StonetuskBoar [Beast] 1 1 1 [
Charge ]
stormpikeCommando :: MinionCard
stormpikeCommando = mkMinion Neutral StormpikeCommando [] 5 4 2 [
Battlecry $ \this ->
A $ Character [] $ \target ->
Effect $ (this `damages` target) 2 ]
stormwindKnight :: MinionCard
stormwindKnight = mkMinion Neutral StormwindKnight [] 4 2 5 [
Charge ]
stormwindChampion :: MinionCard
stormwindChampion = mkMinion Neutral StormwindChampion [] 7 6 6 [
aura $ \this ->
ownerOf this $ \you ->
EachMinion [OwnedBy you, Not this] $ \minion ->
sequence [
Has minion $ gainAttack 1,
Has minion $ GainHealth 1 ]]
succubus :: MinionCard
succubus = mkMinion Warlock Succubus [Demon] 2 4 3 [
Battlecry $ \this ->
ownerOf this $ \you ->
Effect $ DiscardAtRandom you ]
swipe :: SpellCard
swipe = mkSpell Druid Swipe 4 $ \this ->
ownerOf this $ \you ->
opponentOf you $ \opponent ->
A $ Character [OwnedBy opponent] $ \target ->
All $ Characters [OwnedBy opponent, Not target] $ \others ->
Effect $ sequence [
(this `damages` target) 4,
forEach others $ \other ->
(this `damages` other) 1 ]
theCoin :: SpellCard
theCoin = uncollectible $ mkSpell Neutral TheCoin 0 $ \this ->
ownerOf this $ \you ->
Effect $ GainManaCrystals you 1 CrystalTemporary
timberWolf :: MinionCard
timberWolf = mkMinion Hunter TimberWolf [Beast] 1 1 1 [
aura $ \this ->
ownerOf this $ \you ->
EachMinion [OwnedBy you, Not this, OfTribe Beast] $ \minion ->
Has minion $ gainAttack 1 ]
totemicMight :: SpellCard
totemicMight = mkSpell Shaman TotemicMight 0 $ \this ->
ownerOf this $ \you ->
All $ Minions [OwnedBy you, OfTribe Totem] $ \totems ->
Effect $ forEach totems $ \totem ->
enchant totem $ GainHealth 2
tundraRhino :: MinionCard
tundraRhino = mkMinion Hunter TundraRhino [Beast] 5 2 5 [
aura $ \this ->
ownerOf this $ \you ->
EachMinion [OwnedBy you, OfTribe Beast] $ \minion ->
HasAbility minion Charge ]
voidwalker :: MinionCard
voidwalker = mkMinion Warlock Voidwalker [Demon] 1 1 3 [
Taunt ]
voodooDoctor :: MinionCard
voodooDoctor = mkMinion Neutral VoodooDoctor [] 1 2 1 [
Battlecry $ \_ ->
A $ Character [] $ \character ->
Effect $ RestoreHealth character 2 ]
warGolem :: MinionCard
warGolem = mkMinion Neutral WarGolem [] 7 7 7 []
warsongCommander :: MinionCard
warsongCommander = mkMinion Warrior WarsongCommander [] 3 2 3 [
aura $ \this ->
ownerOf this $ \you ->
EachMinion [OwnedBy you, HasCharge] $ \minion ->
Has minion $ gainAttack 1 ]
waterElemental :: MinionCard
waterElemental = mkMinion Mage WaterElemental [] 4 3 6 [
observer $ \this ->
DamageIsDealt $ \victim _ source ->
Effect $ when (this `Satisfies` [IsDamageSource source]) $ Freeze victim ]
whirlwind :: SpellCard
whirlwind = mkSpell Warrior Whirlwind 1 $ \this ->
All $ Minions [] $ \minions ->
Effect $ forEach minions $ \minion ->
(this `damages` minion) 1
wickedKnife :: WeaponCard
wickedKnife = uncollectible $ mkWeapon Rogue WickedKnife 1 1 2 []
wildGrowth :: SpellCard
wildGrowth = mkSpell Druid WildGrowth 2 $ \this ->
ownerOf this $ \you ->
Effect $ if you `Satisfies` [HasMaxManaCrystals]
then PutInHand you $ CardSpell excessMana
else GainManaCrystals you 1 CrystalEmpty
windfury :: SpellCard
windfury = mkSpell Shaman Basic.Windfury 2 $ \_ ->
A $ Minion [] $ \target ->
Effect $ enchant target $ Grant Windfury
windspeaker :: MinionCard
windspeaker = mkMinion Shaman Windspeaker [] 4 3 3 [
Battlecry $ \this ->
ownerOf this $ \you ->
A $ Minion [OwnedBy you] $ \target ->
Effect $ enchant target $ Grant Windfury ]
wolfRider :: MinionCard
wolfRider = mkMinion Neutral WolfRider [] 3 3 1 [
Charge ]
wrathOfAirTotem :: MinionCard
wrathOfAirTotem = uncollectible $ mkMinion Shaman WrathOfAirTotem [Totem] 1 0 2 [
SpellDamage 1 ]
| null |
https://raw.githubusercontent.com/thomaseding/hearthshroud/b21e2f69f394c94a106a3b57b95aa1a76b8d4003/src/Hearth/Authored/CardSet/Basic/Cards.hs
|
haskell
|
# LANGUAGE ConstraintKinds #
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
TODO:
Need to match this behavior -
Comprehensive explanation -
|
# LANGUAGE DataKinds #
# LANGUAGE NoMonomorphismRestriction #
# LANGUAGE RebindableSyntax #
module Hearth.Authored.CardSet.Basic.Cards (
cards,
healingTotem,
searingTotem,
silverHandRecruit,
stoneclawTotem,
theCoin,
wickedKnife,
wrathOfAirTotem,
) where
import Hearth.Authored.CardSet.Basic.Names hiding (Charge, Windfury)
import Hearth.Combinator.Authoring
import Hearth.Combinator.Authoring.RebindableSyntax
import Hearth.Model.Authoring
import Prelude hiding (fromInteger, sequence)
import qualified Hearth.Authored.CardSet.Basic.Names as Basic
cards :: [Card]
cards = let x = toCard in [
x acidicSwampOoze,
x ancestralHealing,
x animalCompanion,
x arcaneExplosion,
x arcaneIntellect,
x arcaneMissiles,
x arcaneShot,
x arcaniteReaper,
x archmage,
x assassinate,
x assassin'sBlade,
x backstab,
x blessingOfKings,
x blessingOfMight,
x bloodfenRaptor,
x bloodlust,
x bluegillWarrior,
x boar,
x bootyBayBodyguard,
x boulderfistOgre,
x charge,
x chillwindYeti,
x claw,
x cleave,
x consecration,
x coreHound,
x corruption,
x dalaranMage,
x darkscaleHealer,
x deadlyPoison,
x deadlyShot,
x divineSpirit,
x dragonlingMechanic,
x drainLife,
x dreadInfernal,
x elvenArcher,
x excessMana,
x execute,
x fanOfKnives,
x fireball,
x fireElemental,
x flamestrike,
x flametongueTotem,
x frog,
x frostbolt,
x frostNova,
x frostShock,
x frostwolfGrunt,
x frostwolfWarlord,
x gnomishInventor,
x goldshireFootman,
x grimscaleOracle,
x guardianOfKings,
x gurubashiBerserker,
x hammerOfWrath,
x handOfProtection,
x healingTotem,
x healingTouch,
x hellfire,
x heroicStrike,
x hex,
x holyLight,
x holyNova,
x holySmite,
x houndmaster,
x huffer,
x humility,
x hunter'sMark,
x ironbarkProtector,
x innervate,
x ironforgeRifleman,
x killCommand,
x koboldGeomancer,
x kor'kronElite,
x leokk,
x light'sJustice,
x lordOfTheArena,
x magmaRager,
x markOfTheWild,
x mechanicalDragonling,
x mindBlast,
x mindControl,
x mirrorImage_minion,
x mirrorImage_spell,
x misha,
x moonfire,
x mortalCoil,
x multiShot,
x murlocRaider,
x murlocScout,
x murlocTidehunter,
x nightblade,
x northshireCleric,
x noviceEngineer,
x oasisSnapjaw,
x ogreMagi,
x polymorph,
x powerWordShield,
x raidLeader,
x razorfenHunter,
x recklessRocketeer,
x riverCrocolisk,
x rockbiterWeapon,
x sacrificialPact,
x savageRoar,
x searingTotem,
x sen'jinShieldmasta,
x shadowBolt,
x shadowWordDeath,
x shadowWordPain,
x shatteredSunCleric,
x sheep,
x shieldBlock,
x shiv,
x silverbackPatriarch,
x silverHandRecruit,
x sinisterStrike,
x soulfire,
x sprint,
x starfire,
x stoneclawTotem,
x stonetuskBoar,
x stormpikeCommando,
x stormwindChampion,
x stormwindKnight,
x succubus,
x swipe,
x theCoin,
x timberWolf,
x totemicMight,
x tundraRhino,
x voidwalker,
x voodooDoctor,
x warGolem,
x warsongCommander,
x waterElemental,
x whirlwind,
x wickedKnife,
x wildGrowth,
x windfury,
x windspeaker,
x wolfRider,
x wrathOfAirTotem ]
mkMinion :: Class -> BasicCardName -> [Tribe] -> Mana -> Attack -> Health -> [Ability 'Minion'] -> MinionCard
mkMinion = mkMinion' BasicCardName Free
mkSpell :: Class -> BasicCardName -> Mana -> SpellEffect -> SpellCard
mkSpell = mkSpell' BasicCardName Free
mkWeapon :: Class -> BasicCardName -> Mana -> Attack -> Durability -> [Ability 'Weapon'] -> WeaponCard
mkWeapon = mkWeapon' BasicCardName Free
acidicSwampOoze :: MinionCard
acidicSwampOoze = mkMinion Neutral AcidicSwampOoze [] 2 3 2 [
Battlecry $ \this ->
ownerOf this $ \you ->
opponentOf you $ \opponent ->
A $ Weapon [OwnedBy opponent] $ \weapon ->
Effect $ destroy weapon ]
ancestralHealing :: SpellCard
ancestralHealing = mkSpell Shaman AncestralHealing 0 $ \_ ->
A $ Minion [] $ \minion ->
Effect $ sequence [
RestoreToFullHealth $ asCharacter minion,
enchant minion $ Grant Taunt ]
animalCompanion :: SpellCard
animalCompanion = mkSpell Hunter AnimalCompanion 3 $ \this ->
ownerOf this $ \you ->
Effect $ Get $ ChooseOne' $ map (\minion -> Effect $ (Summon minion) $ Rightmost you) [
huffer,
leokk,
misha ]
arcaneExplosion :: SpellCard
arcaneExplosion = mkSpell Mage ArcaneExplosion 2 $ \this ->
ownerOf this $ \you ->
opponentOf you $ \opponent ->
All $ Minions [OwnedBy opponent] $ \enemies ->
Effect $ forEach enemies $ \enemy ->
(this `damages` enemy) 1
arcaneIntellect :: SpellCard
arcaneIntellect = mkSpell Mage ArcaneIntellect 3 $ \this ->
ownerOf this $ \you ->
Effect $ DrawCards you 2
arcaneMissiles :: SpellCard
arcaneMissiles = mkSpell Mage ArcaneMissiles 1 $ \this ->
ownerOf this $ \you ->
opponentOf you $ \opponent ->
Effect $ RandomMissiles [OwnedBy opponent] 3 this
arcaneShot :: SpellCard
arcaneShot = mkSpell Hunter ArcaneShot 1 $ \this ->
A $ Character [] $ \target ->
Effect $ (this `damages` target) 2
arcaniteReaper :: WeaponCard
arcaniteReaper = mkWeapon Warrior ArcaniteReaper 5 5 2 []
archmage :: MinionCard
archmage = mkMinion Neutral Archmage [] 6 4 7 [
SpellDamage 1 ]
assassinate :: SpellCard
assassinate = mkSpell Rogue Assassinate 5 $ \_ ->
A $ Minion [] $ \target ->
Effect $ destroy target
assassin'sBlade :: WeaponCard
assassin'sBlade = mkWeapon Rogue Assassin'sBlade 5 3 4 []
backstab :: SpellCard
backstab = mkSpell Rogue Backstab 0 $ \this ->
A $ Minion [undamaged] $ \target ->
Effect $ (this `damages` target) 2
blessingOfKings :: SpellCard
blessingOfKings = mkSpell Paladin BlessingOfKings 4 $ \_ ->
A $ Minion [] $ \target ->
Effect $ sequence [
enchant target $ gainAttack 4,
enchant target $ GainHealth 4 ]
blessingOfMight :: SpellCard
blessingOfMight = mkSpell Paladin BlessingOfMight 1 $ \_ ->
A $ Minion [] $ \target ->
Effect $ enchant target $ gainAttack 3
bloodfenRaptor :: MinionCard
bloodfenRaptor = mkMinion Neutral BloodfenRaptor [Beast] 2 3 2 []
bloodlust :: SpellCard
bloodlust = mkSpell Shaman Bloodlust 5 $ \this ->
ownerOf this $ \you ->
All $ Minions [OwnedBy you] $ \minions ->
Effect $ forEach minions $ \minion ->
enchant minion $ Until EndOfTurn $ gainAttack 3
bluegillWarrior :: MinionCard
bluegillWarrior = mkMinion Neutral BluegillWarrior [Murloc] 2 2 1 [
Charge ]
boar :: MinionCard
boar = uncollectible $ mkMinion Neutral Boar [Beast] 1 1 1 []
bootyBayBodyguard :: MinionCard
bootyBayBodyguard = mkMinion Neutral BootyBayBodyguard [] 5 5 4 [
Taunt ]
boulderfistOgre :: MinionCard
boulderfistOgre = mkMinion Neutral BoulderfistOgre [] 6 6 7 []
charge :: SpellCard
charge = mkSpell Warrior Basic.Charge 3 $ \this ->
ownerOf this $ \you ->
A $ Minion [OwnedBy you] $ \target ->
Effect $ sequence [
enchant target $ gainAttack 2,
enchant target $ Grant Charge ]
chillwindYeti :: MinionCard
chillwindYeti = mkMinion Neutral ChillwindYeti [] 4 4 5 []
claw :: SpellCard
claw = mkSpell Druid Claw 1 $ \this ->
ownerOf this $ \you ->
Effect $ sequence [
enchant you $ Until EndOfTurn $ gainAttack 2,
GainArmor you 2 ]
cleave :: SpellCard
cleave = mkSpell Warrior Cleave 2 $ \this ->
ownerOf this $ \you ->
opponentOf you $ \opponent ->
Effect $ Get $ A $ Minion [OwnedBy opponent] $ \victim1 ->
A $ Minion [OwnedBy opponent, Not victim1] $ \victim2 ->
Effect $ forEach (handleList [victim1, victim2]) $ \victim ->
(this `damages` victim) 2
consecration :: SpellCard
consecration = mkSpell Paladin Consecration 4 $ \this ->
ownerOf this $ \you ->
opponentOf you $ \opponent ->
All $ Characters [OwnedBy opponent] $ \enemies ->
Effect $ forEach enemies $ \enemy ->
(this `damages` enemy) 2
coreHound :: MinionCard
coreHound = mkMinion Neutral CoreHound [Beast] 7 9 5 []
corruption :: SpellCard
corruption = mkSpell Warlock Corruption 1 $ \this ->
ownerOf this $ \you ->
opponentOf you $ \opponent ->
A $ Minion [OwnedBy opponent] $ \target ->
Effect $ enchant target $ DelayedEffect (Delay 1 BeginOfTurn) $ destroy target
dalaranMage :: MinionCard
dalaranMage = mkMinion Neutral DalaranMage [] 3 1 4 [
SpellDamage 1 ]
darkscaleHealer :: MinionCard
darkscaleHealer = mkMinion Neutral DarkscaleHealer [] 5 4 5 [
Battlecry $ \this ->
ownerOf this $ \you ->
All $ Characters [OwnedBy you] $ \friendlies ->
Effect $ forEach friendlies $ \friendly ->
RestoreHealth friendly 2 ]
deadlyPoison :: SpellCard
deadlyPoison = mkSpell Rogue DeadlyPoison 1 $ \this ->
ownerOf this $ \you ->
A $ Weapon [OwnedBy you] $ \weapon ->
Effect $ enchant weapon $ AttackDelta 2
deadlyShot :: SpellCard
deadlyShot = mkSpell Hunter DeadlyShot 3 $ \this ->
ownerOf this $ \you ->
opponentOf you $ \opponent ->
Effect $ Get $ A $ Minion [OwnedBy opponent] $ \victim ->
Effect $ destroy victim
divineSpirit :: SpellCard
divineSpirit = mkSpell Priest DivineSpirit 2 $ \_ ->
A $ Minion [] $ \target ->
Effect $ enchant target $ StatsScale 1 2
dragonlingMechanic :: MinionCard
dragonlingMechanic = mkMinion Neutral DragonlingMechanic [] 4 2 4 [
Battlecry $ \this ->
Effect $ (Summon mechanicalDragonling) $ RightOf this ]
drainLife :: SpellCard
drainLife = mkSpell Warlock DrainLife 3 $ \this ->
A $ Character [] $ \target ->
ownerOf this $ \you ->
Effect $ sequence [
(this `damages` target) 2,
RestoreHealth (asCharacter you) 2 ]
dreadInfernal :: MinionCard
dreadInfernal = mkMinion Warlock DreadInfernal [Demon] 6 6 6 [
Battlecry $ \this ->
All $ Characters [Not (asCharacter this)] $ \victims ->
Effect $ forEach victims $ \victim ->
(this `damages` victim) 1 ]
elvenArcher :: MinionCard
elvenArcher = mkMinion Neutral ElvenArcher [] 1 1 1 [
Battlecry $ \this ->
A $ Character [] $ \target ->
Effect $ (this `damages` target) 1 ]
excessMana :: SpellCard
excessMana = uncollectible $ mkSpell Druid ExcessMana 0 $ \this ->
ownerOf this $ \you ->
Effect $ DrawCards you 1
execute :: SpellCard
execute = mkSpell Warrior Execute 1 $ \_ ->
A $ Minion [damaged] $ \target ->
Effect $ destroy target
fanOfKnives :: SpellCard
fanOfKnives = mkSpell Rogue FanOfKnives 4 $ \this ->
ownerOf this $ \you ->
opponentOf you $ \opponent ->
All $ Minions [OwnedBy opponent] $ \enemies ->
Effect $ sequence [
forEach enemies $ \enemy ->
(this `damages` enemy) 1,
DrawCards you 1 ]
fireball :: SpellCard
fireball = mkSpell Mage Fireball 4 $ \this ->
A $ Character [] $ \target ->
Effect $ (this `damages` target) 6
fireElemental :: MinionCard
fireElemental = mkMinion Shaman FireElemental [] 6 6 5 [
Battlecry $ \this ->
A $ Character [] $ \target ->
Effect $ (this `damages` target) 3 ]
flamestrike :: SpellCard
flamestrike = mkSpell Mage Flamestrike 7 $ \this ->
ownerOf this $ \you ->
opponentOf you $ \opponent ->
All $ Minions [OwnedBy opponent] $ \victims ->
Effect $ forEach victims $ \victim ->
(this `damages` victim) 4
flametongueTotem :: MinionCard
flametongueTotem = mkMinion Shaman FlametongueTotem [Totem] 2 0 3 [
aura $ \this ->
EachMinion [AdjacentTo this] $ \minion ->
Has minion $ gainAttack 2 ]
frog :: MinionCard
frog = uncollectible $ mkMinion Neutral Frog [Beast] 0 0 1 [
Taunt ]
frostbolt :: SpellCard
frostbolt = mkSpell Mage Frostbolt 2 $ \this ->
A $ Character [] $ \target ->
Effect $ sequence [
(this `damages` target) 3,
Freeze target ]
frostNova :: SpellCard
frostNova = mkSpell Mage FrostNova 3 $ \this ->
ownerOf this $ \you ->
opponentOf you $ \opponent ->
All $ Minions [OwnedBy opponent] $ \victims ->
Effect $ forEach victims $ \victim ->
Freeze (asCharacter victim)
frostShock :: SpellCard
frostShock = mkSpell Shaman FrostShock 1 $ \this ->
A $ Character [] $ \target ->
Effect $ sequence [
(this `damages` target) 1,
Freeze target ]
frostwolfGrunt :: MinionCard
frostwolfGrunt = mkMinion Neutral FrostwolfGrunt [] 2 2 2 [
Taunt ]
frostwolfWarlord :: MinionCard
frostwolfWarlord = mkMinion Neutral FrostwolfWarlord [] 5 4 4 [
Battlecry $ \this ->
ownerOf this $ \you ->
All $ Minions [OwnedBy you, Not this] $ \minions ->
Effect $ forEach minions $ \_ ->
sequence [
enchant this $ gainAttack 1,
enchant this $ GainHealth 1 ]]
gnomishInventor :: MinionCard
gnomishInventor = mkMinion Neutral GnomishInventor [] 4 2 4 [
Battlecry $ \this ->
ownerOf this $ \you ->
Effect $ DrawCards you 1 ]
goldshireFootman :: MinionCard
goldshireFootman = mkMinion Neutral GoldshireFootman [] 1 1 2 [
Taunt ]
grimscaleOracle :: MinionCard
grimscaleOracle = mkMinion Neutral GrimscaleOracle [Murloc] 1 1 1 [
aura $ \this ->
EachMinion [Not this, OfTribe Murloc] $ \minion ->
Has minion $ gainAttack 1 ]
guardianOfKings :: MinionCard
guardianOfKings = mkMinion Paladin GuardianOfKings [] 7 5 6 [
Battlecry $ \this ->
ownerOf this $ \you ->
Effect $ RestoreHealth (asCharacter you) 6 ]
gurubashiBerserker :: MinionCard
gurubashiBerserker = mkMinion Neutral GurubashiBerserker [] 5 2 7 [
observer $ \this ->
DamageIsDealt $ \victim _ _ ->
Effect $ when (asCharacter this `Satisfies` [Is victim]) $ enchant this $ gainAttack 3 ]
hammerOfWrath :: SpellCard
hammerOfWrath = mkSpell Paladin HammerOfWrath 4 $ \this ->
A $ Character [] $ \target ->
ownerOf this $ \you ->
Effect $ sequence [
(this `damages` target) 3,
DrawCards you 1 ]
handOfProtection :: SpellCard
handOfProtection = mkSpell Paladin HandOfProtection 1 $ \_ ->
A $ Minion [] $ \target ->
Effect $ enchant target $ Grant DivineShield
healingTotem :: MinionCard
healingTotem = uncollectible $ mkMinion Shaman HealingTotem [Totem] 1 0 2 [
observer $ \this ->
EndOfTurnEvent $ \player ->
ownerOf this $ \you ->
Effect $ when (player `Satisfies` [Is you]) $ Get $ All $ Minions [OwnedBy you] $ \minions ->
Effect $ forEach minions $ \minion ->
RestoreHealth (asCharacter minion) 1 ]
healingTouch :: SpellCard
healingTouch = mkSpell Druid HealingTouch 3 $ \_ ->
A $ Character [] $ \target ->
Effect $ RestoreHealth target 8
hellfire :: SpellCard
hellfire = mkSpell Warlock Hellfire 4 $ \this ->
All $ Characters [] $ \victims ->
Effect $ forEach victims $ \victim ->
(this `damages` victim) 3
heroicStrike :: SpellCard
heroicStrike = mkSpell Warrior HeroicStrike 2 $ \this ->
ownerOf this $ \you ->
Effect $ enchant you $ Until EndOfTurn $ gainAttack 4
hex :: SpellCard
hex = mkSpell Shaman Hex 3 $ \_ ->
A $ Minion [] $ \target ->
Effect $ Transform target frog
holyLight :: SpellCard
holyLight = mkSpell Paladin HolyLight 2 $ \_ ->
A $ Character [] $ \target ->
Effect $ RestoreHealth target 6
holyNova :: SpellCard
holyNova = mkSpell Priest HolyNova 5 $ \this ->
ownerOf this $ \you ->
opponentOf you $ \opponent ->
All $ Characters [OwnedBy you] $ \friendlies ->
All $ Characters [OwnedBy opponent] $ \enemies ->
Effect $ sequence [
forEach enemies $ \enemy ->
(this `damages` enemy) 2,
forEach friendlies $ \friendly ->
RestoreHealth friendly 2 ]
holySmite :: SpellCard
holySmite = mkSpell Priest HolySmite 1 $ \this ->
A $ Character [] $ \target ->
Effect $ (this `damages` target) 2
houndmaster :: MinionCard
houndmaster = mkMinion Hunter Houndmaster [] 4 4 3 [
Battlecry $ \this ->
ownerOf this $ \you ->
A $ Minion [OwnedBy you, OfTribe Beast] $ \beast ->
Effect $ sequence [
enchant beast $ gainAttack 2,
enchant beast $ GainHealth 2,
enchant beast $ Grant Taunt ]]
huffer :: MinionCard
huffer = uncollectible $ mkMinion Hunter Huffer [Beast] 3 4 2 [
Charge ]
humility :: SpellCard
humility = mkSpell Paladin Humility 1 $ \_ ->
A $ Minion [] $ \target ->
Effect $ enchant target $ ChangeStat $ Left 1
hunter'sMark :: SpellCard
hunter'sMark = mkSpell Hunter Hunter'sMark 1 $ \_ ->
A $ Minion [] $ \target ->
Effect $ enchant target $ ChangeStat $ Right 1
koboldGeomancer :: MinionCard
koboldGeomancer = mkMinion Neutral KoboldGeomancer [] 2 2 2 [
SpellDamage 1 ]
kor'kronElite :: MinionCard
kor'kronElite = mkMinion Warrior Kor'kronElite [] 4 4 3 [
Charge ]
innervate :: SpellCard
innervate = mkSpell Druid Innervate 0 $ \this ->
ownerOf this $ \you ->
Effect $ GainManaCrystals you 2 CrystalTemporary
ironbarkProtector :: MinionCard
ironbarkProtector = mkMinion Druid IronbarkProtector [] 8 8 8 [
Taunt ]
ironforgeRifleman :: MinionCard
ironforgeRifleman = mkMinion Neutral IronforgeRifleman [] 3 2 2 [
Battlecry $ \this ->
A $ Character [] $ \target ->
Effect $ (this `damages` target) 1 ]
killCommand :: SpellCard
killCommand = mkSpell Hunter KillCommand 3 $ \this ->
ownerOf this $ \you ->
A $ Character [] $ \victim -> let
deal = this `damages` victim
in Effect $ if you `Satisfies` [HasMinion [OfTribe Beast]]
then deal 5
else deal 3
leokk :: MinionCard
leokk = uncollectible $ mkMinion Hunter Leokk [Beast] 3 2 4 [
aura $ \this ->
ownerOf this $ \you ->
EachMinion [Not this, OwnedBy you] $ \minion ->
Has minion $ gainAttack 1 ]
light'sJustice :: WeaponCard
light'sJustice = mkWeapon Paladin Light'sJustice 1 1 4 []
lordOfTheArena :: MinionCard
lordOfTheArena = mkMinion Neutral LordOfTheArena [] 6 6 5 [
Taunt ]
markOfTheWild :: SpellCard
markOfTheWild = mkSpell Druid MarkOfTheWild 2 $ \_ ->
A $ Minion [] $ \target ->
Effect $ sequence [
enchant target $ Grant Taunt,
enchant target $ gainAttack 2,
enchant target $ GainHealth 2 ]
magmaRager :: MinionCard
magmaRager = mkMinion Neutral MagmaRager [] 3 5 1 []
mechanicalDragonling :: MinionCard
mechanicalDragonling = uncollectible $ mkMinion Neutral MechanicalDragonling [Mech] 1 2 1 []
mindBlast :: SpellCard
mindBlast = mkSpell Priest MindBlast 2 $ \this ->
ownerOf this $ \you ->
opponentOf you $ \opponent ->
Effect $ (this `damages` opponent) 5
mindControl :: SpellCard
mindControl = mkSpell Priest MindControl 10 $ \this ->
ownerOf this $ \you ->
opponentOf you $ \opponent ->
A $ Minion [OwnedBy opponent] $ \victim ->
Effect $ TakeControl you victim
mirrorImage_minion :: MinionCard
mirrorImage_minion = uncollectible $ mkMinion Mage MirrorImage_Minion [] 1 0 2 [
Taunt ]
mirrorImage_spell :: SpellCard
mirrorImage_spell = mkSpell Mage MirrorImage_Spell 1 $ \this ->
ownerOf this $ \you ->
Effect $ sequence $ replicate 2 $ (Summon mirrorImage_minion) $ Rightmost you
misha :: MinionCard
misha = uncollectible $ mkMinion Hunter Misha [Beast] 3 4 4 [
Taunt ]
moonfire :: SpellCard
moonfire = mkSpell Druid Moonfire 0 $ \this ->
A $ Character [] $ \target ->
Effect $ (this `damages` target) 1
MortalCoil hitting a KnifeJuggler juggled to death minion ( triggered from say your VioletTeacher )
mortalCoil :: SpellCard
mortalCoil = mkSpell Warlock MortalCoil 1 $ \this ->
ownerOf this $ \you ->
A $ Minion [] $ \target -> let
effect = (this `damages` target) 1
in Effect $ Observing effect $ DamageIsDealt $ \victim _ source -> let
condition = this `Satisfies` [IsDamageSource source]
`And` victim `Satisfies` [withHealth LessEqual 0]
in Effect $ when condition $ DrawCards you 1
multiShot :: SpellCard
multiShot = mkSpell Hunter MultiShot 4 $ \this ->
ownerOf this $ \you ->
opponentOf you $ \opponent ->
Effect $ Get $ A $ Minion [OwnedBy opponent] $ \victim1 ->
A $ Minion [OwnedBy opponent, Not victim1] $ \victim2 ->
Effect $ forEach (handleList [victim1, victim2]) $ \victim ->
(this `damages` victim) 3
murlocRaider :: MinionCard
murlocRaider = mkMinion Neutral MurlocRaider [Murloc] 1 2 1 []
murlocScout :: MinionCard
murlocScout = uncollectible $ mkMinion Neutral MurlocScout [Murloc] 0 1 1 []
murlocTidehunter :: MinionCard
murlocTidehunter = mkMinion Neutral MurlocTidehunter [Murloc] 2 2 1 [
Battlecry $ \this ->
Effect $ (Summon murlocScout) $ RightOf this ]
nightblade :: MinionCard
nightblade = mkMinion Neutral Nightblade [] 5 4 4 [
Battlecry $ \this ->
ownerOf this $ \you ->
opponentOf you $ \opponent ->
Effect $ (this `damages` opponent) 3 ]
northshireCleric :: MinionCard
northshireCleric = mkMinion Priest NorthshireCleric [] 1 1 3 [
observer $ \this ->
HealthIsRestored $ \recipient _ ->
ownerOf this $ \you ->
Effect $ when (recipient `Satisfies` [IsMinion]) $ DrawCards you 1 ]
noviceEngineer :: MinionCard
noviceEngineer = mkMinion Neutral NoviceEngineer [] 2 1 1 [
Battlecry $ \this ->
ownerOf this $ \you ->
Effect $ DrawCards you 1 ]
oasisSnapjaw :: MinionCard
oasisSnapjaw = mkMinion Neutral OasisSnapjaw [Beast] 4 2 7 []
ogreMagi :: MinionCard
ogreMagi = mkMinion Neutral OgreMagi [] 4 4 4 [
SpellDamage 1 ]
polymorph :: SpellCard
polymorph = mkSpell Mage Polymorph 4 $ \_ ->
A $ Minion [] $ \target ->
Effect $ Transform target sheep
powerWordShield :: SpellCard
powerWordShield = mkSpell Priest PowerWordShield 1 $ \this ->
A $ Minion [] $ \target ->
ownerOf this $ \you ->
Effect $ sequence [
enchant target $ GainHealth 2,
DrawCards you 1 ]
raidLeader :: MinionCard
raidLeader = mkMinion Neutral RaidLeader [] 3 2 2 [
aura $ \this ->
ownerOf this $ \you ->
EachMinion [OwnedBy you, Not this] $ \minion ->
Has minion $ gainAttack 1 ]
razorfenHunter :: MinionCard
razorfenHunter = mkMinion Neutral RazorfenHunter [] 3 2 3 [
Battlecry $ \this ->
Effect $ (Summon boar) $ RightOf this ]
recklessRocketeer :: MinionCard
recklessRocketeer = mkMinion Neutral RecklessRocketeer [] 6 5 2 [
Charge ]
riverCrocolisk :: MinionCard
riverCrocolisk = mkMinion Neutral RiverCrocolisk [Beast] 2 2 3 []
rockbiterWeapon :: SpellCard
rockbiterWeapon = mkSpell Shaman RockbiterWeapon 1 $ \this ->
ownerOf this $ \you ->
A $ Character [OwnedBy you] $ \target ->
Effect $ enchant target $ Until EndOfTurn $ gainAttack 3
sacrificialPact :: SpellCard
sacrificialPact = mkSpell Warlock SacrificialPact 0 $ \this ->
ownerOf this $ \you ->
A $ Minion [OfTribe Demon] $ \demon ->
Effect $ sequence [
destroy demon,
RestoreHealth (asCharacter you) 5 ]
savageRoar :: SpellCard
savageRoar = mkSpell Druid SavageRoar 3 $ \this ->
ownerOf this $ \you ->
All $ Characters [OwnedBy you] $ \friendlies ->
Effect $ forEach friendlies $ \friendly ->
enchant friendly $ Until EndOfTurn $ gainAttack 2
searingTotem :: MinionCard
searingTotem = uncollectible $ mkMinion Shaman SearingTotem [Totem] 1 1 1 []
sen'jinShieldmasta :: MinionCard
sen'jinShieldmasta = mkMinion Neutral Sen'jinShieldmasta [] 4 3 5 [
Taunt ]
shadowBolt :: SpellCard
shadowBolt = mkSpell Warlock ShadowBolt 3 $ \this ->
A $ Minion [] $ \target ->
Effect $ (this `damages` target) 4
shadowWordDeath :: SpellCard
shadowWordDeath = mkSpell Priest ShadowWordDeath 3 $ \_ ->
A $ Minion [withAttack GreaterEqual 5] $ \target ->
Effect $ destroy target
shadowWordPain :: SpellCard
shadowWordPain = mkSpell Priest ShadowWordPain 2 $ \_ ->
A $ Minion [withAttack LessEqual 3] $ \target ->
Effect $ destroy target
shatteredSunCleric :: MinionCard
shatteredSunCleric = mkMinion Neutral ShatteredSunCleric [] 3 3 2 [
Battlecry $ \this ->
ownerOf this $ \you ->
A $ Minion [OwnedBy you] $ \target ->
Effect $ sequence [
enchant target $ gainAttack 1,
enchant target $ GainHealth 1 ]]
sheep :: MinionCard
sheep = uncollectible $ mkMinion Neutral Sheep [Beast] 0 1 1 []
shieldBlock :: SpellCard
shieldBlock = mkSpell Warrior ShieldBlock 3 $ \this ->
ownerOf this $ \you ->
Effect $ sequence [
GainArmor you 5,
DrawCards you 1 ]
shiv :: SpellCard
shiv = mkSpell Rogue Shiv 2 $ \this ->
A $ Character [] $ \target ->
ownerOf this $ \you ->
Effect $ sequence [
(this `damages` target) 1,
DrawCards you 1 ]
silverbackPatriarch :: MinionCard
silverbackPatriarch = mkMinion Neutral SilverbackPatriarch [Beast] 3 1 4 [
Taunt ]
silverHandRecruit :: MinionCard
silverHandRecruit = uncollectible $ mkMinion Paladin SilverHandRecruit [] 1 1 1 []
sinisterStrike :: SpellCard
sinisterStrike = mkSpell Rogue SinisterStrike 1 $ \this ->
ownerOf this $ \you ->
opponentOf you $ \opponent ->
Effect $ (this `damages` opponent) 3
soulfire :: SpellCard
soulfire = mkSpell Warlock Soulfire 1 $ \this ->
ownerOf this $ \you ->
A $ Character [] $ \victim ->
Effect $ sequence [
(this `damages` victim) 4,
DiscardAtRandom you ]
sprint :: SpellCard
sprint = mkSpell Rogue Sprint 7 $ \this ->
ownerOf this $ \you ->
Effect $ DrawCards you 4
starfire :: SpellCard
starfire = mkSpell Druid Starfire 6 $ \this ->
A $ Character [] $ \target ->
ownerOf this $ \you ->
Effect $ sequence [
(this `damages` target) 5,
DrawCards you 1 ]
stoneclawTotem :: MinionCard
stoneclawTotem = uncollectible $ mkMinion Shaman StoneclawTotem [Totem] 1 0 2 [
Taunt ]
stonetuskBoar :: MinionCard
stonetuskBoar = mkMinion Neutral StonetuskBoar [Beast] 1 1 1 [
Charge ]
stormpikeCommando :: MinionCard
stormpikeCommando = mkMinion Neutral StormpikeCommando [] 5 4 2 [
Battlecry $ \this ->
A $ Character [] $ \target ->
Effect $ (this `damages` target) 2 ]
stormwindKnight :: MinionCard
stormwindKnight = mkMinion Neutral StormwindKnight [] 4 2 5 [
Charge ]
stormwindChampion :: MinionCard
stormwindChampion = mkMinion Neutral StormwindChampion [] 7 6 6 [
aura $ \this ->
ownerOf this $ \you ->
EachMinion [OwnedBy you, Not this] $ \minion ->
sequence [
Has minion $ gainAttack 1,
Has minion $ GainHealth 1 ]]
succubus :: MinionCard
succubus = mkMinion Warlock Succubus [Demon] 2 4 3 [
Battlecry $ \this ->
ownerOf this $ \you ->
Effect $ DiscardAtRandom you ]
swipe :: SpellCard
swipe = mkSpell Druid Swipe 4 $ \this ->
ownerOf this $ \you ->
opponentOf you $ \opponent ->
A $ Character [OwnedBy opponent] $ \target ->
All $ Characters [OwnedBy opponent, Not target] $ \others ->
Effect $ sequence [
(this `damages` target) 4,
forEach others $ \other ->
(this `damages` other) 1 ]
theCoin :: SpellCard
theCoin = uncollectible $ mkSpell Neutral TheCoin 0 $ \this ->
ownerOf this $ \you ->
Effect $ GainManaCrystals you 1 CrystalTemporary
timberWolf :: MinionCard
timberWolf = mkMinion Hunter TimberWolf [Beast] 1 1 1 [
aura $ \this ->
ownerOf this $ \you ->
EachMinion [OwnedBy you, Not this, OfTribe Beast] $ \minion ->
Has minion $ gainAttack 1 ]
totemicMight :: SpellCard
totemicMight = mkSpell Shaman TotemicMight 0 $ \this ->
ownerOf this $ \you ->
All $ Minions [OwnedBy you, OfTribe Totem] $ \totems ->
Effect $ forEach totems $ \totem ->
enchant totem $ GainHealth 2
tundraRhino :: MinionCard
tundraRhino = mkMinion Hunter TundraRhino [Beast] 5 2 5 [
aura $ \this ->
ownerOf this $ \you ->
EachMinion [OwnedBy you, OfTribe Beast] $ \minion ->
HasAbility minion Charge ]
voidwalker :: MinionCard
voidwalker = mkMinion Warlock Voidwalker [Demon] 1 1 3 [
Taunt ]
voodooDoctor :: MinionCard
voodooDoctor = mkMinion Neutral VoodooDoctor [] 1 2 1 [
Battlecry $ \_ ->
A $ Character [] $ \character ->
Effect $ RestoreHealth character 2 ]
warGolem :: MinionCard
warGolem = mkMinion Neutral WarGolem [] 7 7 7 []
warsongCommander :: MinionCard
warsongCommander = mkMinion Warrior WarsongCommander [] 3 2 3 [
aura $ \this ->
ownerOf this $ \you ->
EachMinion [OwnedBy you, HasCharge] $ \minion ->
Has minion $ gainAttack 1 ]
waterElemental :: MinionCard
waterElemental = mkMinion Mage WaterElemental [] 4 3 6 [
observer $ \this ->
DamageIsDealt $ \victim _ source ->
Effect $ when (this `Satisfies` [IsDamageSource source]) $ Freeze victim ]
whirlwind :: SpellCard
whirlwind = mkSpell Warrior Whirlwind 1 $ \this ->
All $ Minions [] $ \minions ->
Effect $ forEach minions $ \minion ->
(this `damages` minion) 1
wickedKnife :: WeaponCard
wickedKnife = uncollectible $ mkWeapon Rogue WickedKnife 1 1 2 []
wildGrowth :: SpellCard
wildGrowth = mkSpell Druid WildGrowth 2 $ \this ->
ownerOf this $ \you ->
Effect $ if you `Satisfies` [HasMaxManaCrystals]
then PutInHand you $ CardSpell excessMana
else GainManaCrystals you 1 CrystalEmpty
windfury :: SpellCard
windfury = mkSpell Shaman Basic.Windfury 2 $ \_ ->
A $ Minion [] $ \target ->
Effect $ enchant target $ Grant Windfury
windspeaker :: MinionCard
windspeaker = mkMinion Shaman Windspeaker [] 4 3 3 [
Battlecry $ \this ->
ownerOf this $ \you ->
A $ Minion [OwnedBy you] $ \target ->
Effect $ enchant target $ Grant Windfury ]
wolfRider :: MinionCard
wolfRider = mkMinion Neutral WolfRider [] 3 3 1 [
Charge ]
wrathOfAirTotem :: MinionCard
wrathOfAirTotem = uncollectible $ mkMinion Shaman WrathOfAirTotem [Totem] 1 0 2 [
SpellDamage 1 ]
|
9ff21e8ef69232c91b62a5638e6ac89046790c0de1f1b3949579a4e7d4ba76c8
|
lemenkov/rtplib
|
sas.erl
|
%%%----------------------------------------------------------------------
Copyright ( c ) 2012 < >
%%%
%%% All rights reserved.
%%%
%%% Redistribution and use in source and binary forms, with or without modification,
%%% are permitted provided that the following conditions are met:
%%%
%%% * Redistributions of source code must retain the above copyright notice, this
%%% list of conditions and the following disclaimer.
%%% * Redistributions in binary form must reproduce the above copyright notice,
%%% this list of conditions and the following disclaimer in the documentation
%%% and/or other materials provided with the distribution.
%%% * Neither the name of the 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 REGENTS 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 REGENTS 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.
%%%
%%%----------------------------------------------------------------------
-module(sas).
-export([b32/1]).
-export([b256/1]).
-on_load(init/0).
init() ->
SoName = case code:priv_dir(rtplib) of
{error, bad_name} -> filename:join("../priv", "sas_nif");
Dir -> filename:join(Dir, "sas_nif")
end,
erlang:load_nif(SoName, 0).
b32(_SASValue) ->
"NIF library not loaded".
b256(_SASValue) ->
"NIF library not loaded".
| null |
https://raw.githubusercontent.com/lemenkov/rtplib/b74a43b41fdb3dcdac6e33c5f2b9196780f7cbc8/src/sas.erl
|
erlang
|
----------------------------------------------------------------------
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the 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 REGENTS 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
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------
|
Copyright ( c ) 2012 < >
DISCLAIMED . IN NO EVENT SHALL THE REGENTS 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 ;
ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
-module(sas).
-export([b32/1]).
-export([b256/1]).
-on_load(init/0).
init() ->
SoName = case code:priv_dir(rtplib) of
{error, bad_name} -> filename:join("../priv", "sas_nif");
Dir -> filename:join(Dir, "sas_nif")
end,
erlang:load_nif(SoName, 0).
b32(_SASValue) ->
"NIF library not loaded".
b256(_SASValue) ->
"NIF library not loaded".
|
5dd656785428eb00cef258b6b89d7a5f603af9ad634203807df4455ba9c7ea3f
|
input-output-hk/cardano-ledger
|
Main.hs
|
module Main where
import Test.Tasty
import Test.VMap
-- ====================================================================================
tests :: TestTree
tests =
testGroup
"vector-map"
[ vMapTests
]
main :: IO ()
main = defaultMain tests
| null |
https://raw.githubusercontent.com/input-output-hk/cardano-ledger/16e4498ab762b77eca4a6191a3d7845a869c13af/libs/vector-map/test/Main.hs
|
haskell
|
====================================================================================
|
module Main where
import Test.Tasty
import Test.VMap
tests :: TestTree
tests =
testGroup
"vector-map"
[ vMapTests
]
main :: IO ()
main = defaultMain tests
|
423d1d7ba778a9b265f2129a130458a06b099de48c89c8e83654aebb7faf6428
|
palletops/carapace
|
shell.clj
|
(ns carapace.shell
"Execute processes from clojure"
(:require
[carapace.proc :as proc]
[carapace.stream :as stream]
[com.palletops.api-builder.api :refer [defn-api]]
[schema.core :as schema :refer [either optional-key]]))
(defonce default-streamer
(delay
(let [s (stream/streamer {})]
(stream/start s)
s)))
(defn- stream-copy-maps
"Given a process p, and a possibly nil input stream or reader,
return a sequence of stream-maps to copy the input stream to the process,
and the output and error streams to *out* and *err*."
[p {:keys [in redirect-error-stream buffer-size buffer] :as options}]
(filter
identity
[(if in
(stream/stream-copy in (:in p) {})
(.close (:in p)))
(stream/stream-copy
(:out p) *out*
(select-keys options [:buffer-size :buffer :flush]))
(when-not redirect-error-stream
(stream/stream-copy (:err p) *err* {:flush flush}))]))
(def ShOptions
{(optional-key :in) (either java.io.InputStream java.io.Reader)
(optional-key :streamer) stream/Streamer
(optional-key :buffer-size) schema/Int
(optional-key :buffer) bytes
(optional-key :redirect-error-stream) schema/Bool
(optional-key :clear) schema/Bool
(optional-key :env) {(either String clojure.lang.Named) String}
(optional-key :directory) String
(optional-key :flush) schema/Bool
(optional-key :stream-maps-f) schema/Any})
(defn-api sh
"Execute a process, returning the exit code.
The process executes `command`, a sequence of strings.
Output goes to *out*."
{:sig [[[String] ShOptions :- schema/Int]]}
[command {:keys [in env clear
streamer buffer-size buffer
redirect-error-stream
flush
stream-maps-f]
:as options
:or {stream-maps-f stream-copy-maps}}]
(let [s (or streamer @default-streamer)
options (merge {:flush true :redirect-error-stream true} options)
p (proc/proc command
(select-keys
options
[:env :clear :directory :redirect-error-stream]))
stream-maps (stream-maps-f p options)]
(doseq [sm stream-maps]
(stream/stream s sm))
(let [e (proc/wait-for p)]
(doseq [sm stream-maps]
(stream/un-stream s sm))
e)))
(defn stream-string-maps
"Return a map with a function and string buffers. The function,
given a process p, and a possibly nil input stream or reader, will
return a sequence of stream-maps to copy the input stream to the
process, and the output streams to string buffers."
[]
(let [out-b (java.io.StringWriter.)
err-b (java.io.StringWriter.)]
{:f (fn [p
{:keys [in redirect-error-stream buffer-size buffer] :as options}]
(filter
identity
[(if in
(stream/stream-copy in (:in p) {})
(.close (:in p)))
(stream/stream-copy
(:out p) out-b
(select-keys options [:buffer-size :buffer :flush]))
(when-not redirect-error-stream
(stream/stream-copy (:err p) err-b {:flush flush}))]))
:out out-b
:err err-b}))
(def ShMapOptions
(dissoc ShOptions (optional-key :stream-maps-f)))
(def ShMap
{:exit schema/Int
:out String
:err String})
(defn-api sh-map
"Execute a process, returning a map with the exit code, the stdout
and the stderr. The process executes `command`, a sequence of
strings."
{:sig [[[String] ShMapOptions :- ShMap]]}
[command {:keys [in env clear
streamer buffer-size buffer
redirect-error-stream
flush]
:as options}]
(let [{:keys [f out err]} (stream-string-maps)
e (sh command (assoc options :stream-maps-f f))]
{:exit e
:out (.toString out)
:err (.toString err)}))
| null |
https://raw.githubusercontent.com/palletops/carapace/6d196bc7a0cda68256a6fb726d5a8a8386146a4d/src/carapace/shell.clj
|
clojure
|
(ns carapace.shell
"Execute processes from clojure"
(:require
[carapace.proc :as proc]
[carapace.stream :as stream]
[com.palletops.api-builder.api :refer [defn-api]]
[schema.core :as schema :refer [either optional-key]]))
(defonce default-streamer
(delay
(let [s (stream/streamer {})]
(stream/start s)
s)))
(defn- stream-copy-maps
"Given a process p, and a possibly nil input stream or reader,
return a sequence of stream-maps to copy the input stream to the process,
and the output and error streams to *out* and *err*."
[p {:keys [in redirect-error-stream buffer-size buffer] :as options}]
(filter
identity
[(if in
(stream/stream-copy in (:in p) {})
(.close (:in p)))
(stream/stream-copy
(:out p) *out*
(select-keys options [:buffer-size :buffer :flush]))
(when-not redirect-error-stream
(stream/stream-copy (:err p) *err* {:flush flush}))]))
(def ShOptions
{(optional-key :in) (either java.io.InputStream java.io.Reader)
(optional-key :streamer) stream/Streamer
(optional-key :buffer-size) schema/Int
(optional-key :buffer) bytes
(optional-key :redirect-error-stream) schema/Bool
(optional-key :clear) schema/Bool
(optional-key :env) {(either String clojure.lang.Named) String}
(optional-key :directory) String
(optional-key :flush) schema/Bool
(optional-key :stream-maps-f) schema/Any})
(defn-api sh
"Execute a process, returning the exit code.
The process executes `command`, a sequence of strings.
Output goes to *out*."
{:sig [[[String] ShOptions :- schema/Int]]}
[command {:keys [in env clear
streamer buffer-size buffer
redirect-error-stream
flush
stream-maps-f]
:as options
:or {stream-maps-f stream-copy-maps}}]
(let [s (or streamer @default-streamer)
options (merge {:flush true :redirect-error-stream true} options)
p (proc/proc command
(select-keys
options
[:env :clear :directory :redirect-error-stream]))
stream-maps (stream-maps-f p options)]
(doseq [sm stream-maps]
(stream/stream s sm))
(let [e (proc/wait-for p)]
(doseq [sm stream-maps]
(stream/un-stream s sm))
e)))
(defn stream-string-maps
"Return a map with a function and string buffers. The function,
given a process p, and a possibly nil input stream or reader, will
return a sequence of stream-maps to copy the input stream to the
process, and the output streams to string buffers."
[]
(let [out-b (java.io.StringWriter.)
err-b (java.io.StringWriter.)]
{:f (fn [p
{:keys [in redirect-error-stream buffer-size buffer] :as options}]
(filter
identity
[(if in
(stream/stream-copy in (:in p) {})
(.close (:in p)))
(stream/stream-copy
(:out p) out-b
(select-keys options [:buffer-size :buffer :flush]))
(when-not redirect-error-stream
(stream/stream-copy (:err p) err-b {:flush flush}))]))
:out out-b
:err err-b}))
(def ShMapOptions
(dissoc ShOptions (optional-key :stream-maps-f)))
(def ShMap
{:exit schema/Int
:out String
:err String})
(defn-api sh-map
"Execute a process, returning a map with the exit code, the stdout
and the stderr. The process executes `command`, a sequence of
strings."
{:sig [[[String] ShMapOptions :- ShMap]]}
[command {:keys [in env clear
streamer buffer-size buffer
redirect-error-stream
flush]
:as options}]
(let [{:keys [f out err]} (stream-string-maps)
e (sh command (assoc options :stream-maps-f f))]
{:exit e
:out (.toString out)
:err (.toString err)}))
|
|
3ecb83ad6b99a8137045a746f375fedc9cb69299a2ed6d55240cd58a3c5651ea
|
k16shikano/hpdft
|
DocumentStructure.hs
|
{-# LANGUAGE OverloadedStrings #-}
|
Module : PDF.DocumentStructure
Description : Function to walk around Document Structure of a PDF file
Copyright : ( c ) , 2020
License : MIT
Maintainer :
Module : PDF.DocumentStructure
Description : Function to walk around Document Structure of a PDF file
Copyright : (c) Keiichiro Shikano, 2020
License : MIT
Maintainer :
-}
module PDF.DocumentStructure
( parseTrailer
, expandObjStm
, rootRef
, contentsStream
, rawStreamByRef
, findKids
, findPages
, findDict
, findDictByRef
, findDictOfType
, findObjFromDict
, findObjFromDictWithRef
, findObjsByRef
, findObjs
, findTrailer
, rawStream
) where
import Data.Char (chr)
import Data.List (find)
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BSL
import qualified Data.ByteString.Builder as B
import qualified Data.Text as T
import Data.Maybe (fromMaybe)
import Numeric (readDec)
import Data.Attoparsec.ByteString.Char8 hiding (take)
import Data.Attoparsec.Combinator
import Control.Applicative
import Codec.Compression.Zlib (decompress)
import Debug.Trace
import PDF.Definition
import PDF.Object
import PDF.ContentStream (parseStream, parseColorSpace)
import PDF.Cmap (parseCMap)
import qualified PDF.OpenType as OpenType
import qualified PDF.CFF as CFF
import qualified PDF.Type1 as Type1
spaces = skipSpace
oneOf = satisfy . inClass
noneOf = satisfy . notInClass
-- find objects
findObjs :: BS.ByteString -> [PDFBS]
findObjs contents = case parseOnly (many1 pdfObj) contents of
Left err -> []
Right rlt -> rlt
findXref :: BS.ByteString -> String
findXref contents = case parseOnly (xref) contents of
Left err -> []
Right rlt -> rlt
findObjsByRef :: Int -> [PDFObj] -> Maybe [Obj]
findObjsByRef x pdfobjs = case find (isRefObj (Just x)) pdfobjs of
Just (_,objs) -> Just objs
Nothing -> Nothing
where
isRefObj (Just x) (y, objs) = if x==y then True else False
isRefObj _ _ = False
findObjFromDictWithRef :: Int -> String -> [PDFObj] -> Maybe Obj
findObjFromDictWithRef ref name objs = case findDictByRef ref objs of
Just d -> findObjFromDict d name
Nothing -> Nothing
findObjFromDict :: Dict -> String -> Maybe Obj
findObjFromDict d name = case find isName d of
Just (_, o) -> Just o
otherwise -> Nothing
where isName (PdfName n, _) = if name == n then True else False
isName _ = False
findDictByRef :: Int -> [PDFObj] -> Maybe Dict
findDictByRef ref objs = case findObjsByRef ref objs of
Just os -> findDict os
Nothing -> Nothing
findDictOfType :: String -> [Obj] -> Maybe Dict
findDictOfType typename objs = case findDict objs of
Just d -> if isType d then Just d else Nothing
Nothing -> Nothing
where
isType dict = (PdfName "/Type",PdfName typename) `elem` dict
findDict :: [Obj] -> Maybe Dict
findDict objs = case find isDict objs of
Just (PdfDict d) -> Just d
otherwise -> Nothing
where
isDict :: Obj -> Bool
isDict (PdfDict d) = True
isDict _ = False
findPages :: Dict -> Maybe Int
findPages dict = case find isPagesRef dict of
Just (_, ObjRef x) -> Just x
Nothing -> Nothing
where
isPagesRef (PdfName "/Pages", ObjRef x) = True
isPagesRef (_,_) = False
findKids :: Dict -> Maybe [Int]
findKids dict = case find isKidsRefs dict of
Just (_, PdfArray arr) -> Just (parseRefsArray arr)
Nothing -> Nothing
where
isKidsRefs (PdfName "/Kids", PdfArray x) = True
isKidsRefs (_,_) = False
contentsStream :: Dict -> PSR -> [PDFObj] -> PDFStream
contentsStream dict st objs = case find contents dict of
Just (PdfName "/Contents", PdfArray arr) -> getContentArray arr
Just (PdfName "/Contents", ObjRef r) ->
case findObjsByRef r objs of
Just [PdfArray arr] -> getContentArray arr
Just _ -> getContent r
Nothing -> error "No content to be shown"
Nothing -> error "No content to be shown"
where
contents (PdfName "/Contents", _) = True
contents _ = False
getContentArray arr = parseContentStream dict st objs $
BSL.concat $ map (rawStreamByRef objs) (parseRefsArray arr)
getContent r = parseContentStream dict st objs $ rawStreamByRef objs r
parseContentStream :: Dict -> PSR -> [PDFObj] -> BSL.ByteString -> PDFStream
parseContentStream dict st objs s =
parseStream (st {fontmaps=fontdict, cmaps=cmap}) s
where fontdict = findFontEncoding dict objs
cmap = findCMap dict objs
rawStreamByRef :: [PDFObj] -> Int -> BSL.ByteString
rawStreamByRef pdfobjs x = case findObjsByRef x pdfobjs of
Just objs -> rawStream objs
Nothing -> error "No object with stream to be shown"
rawStream :: [Obj] -> BSL.ByteString
rawStream objs = case find isStream objs of
Just (PdfStream strm) -> rawStream' (fromMaybe [] $ findDict objs) strm
Nothing -> BSL.pack $ show objs
where
isStream (PdfStream s) = True
isStream _ = False
rawStream' :: Dict -> BSL.ByteString -> BSL.ByteString
rawStream' d s = streamFilter d s
streamFilter d = case find withFilter d of
Just (PdfName "/Filter", PdfName "/FlateDecode")
-> decompress
Just (PdfName "/Filter", PdfName f)
-> error $ "Unknown Stream Compression: " ++ f -- need fix
Just _ -> error $ "No Stream Compression Filter."
Nothing -> id
withFilter (PdfName "/Filter", _) = True
withFilter _ = False
contentsColorSpace :: Dict -> PSR -> [PDFObj] -> [T.Text]
contentsColorSpace dict st objs = case find contents dict of
Just (PdfName "/Contents", PdfArray arr) -> concat $ map (parseColorSpace (st {xcolorspaces=xobjcs}) . rawStreamByRef objs) (parseRefsArray arr)
Just (PdfName "/Contents", ObjRef x) -> parseColorSpace (st {xcolorspaces=xobjcs}) $ rawStreamByRef objs x
Nothing -> error "No content to be shown"
where
contents (PdfName "/Contents", _) = True
contents _ = False
xobjcs = findXObjectColorSpace dict objs
find XObject
findXObjectColorSpace d os = xobjColorSpaceMap (findXObject d os) os
xobjColorSpaceMap dict objs = map pairwise dict
where
pairwise (PdfName n, ObjRef r) = xobjColorSpace r objs
pairwise x = ""
findXObject dict objs = case findResourcesDict dict objs of
Just d -> case findObjFromDict d "/XObject" of
Just (PdfDict d) -> d
otherwise -> []
Nothing -> []
xobjColorSpace :: Int -> [PDFObj] -> String
xobjColorSpace x objs = case findObjFromDictWithRef x "/ColorSpace" objs of
Just (PdfName cs) -> cs
otherwise -> ""
find root ref from Trailer or Cross - Reference Dictionary
parseTrailer :: BS.ByteString -> Maybe Dict
parseTrailer bs = case BS.breakEnd (== '\n') bs of
(source, eofLine)
| "%%EOF" `BS.isPrefixOf` eofLine
-> Just (parseCRDict $ BS.drop (getOffset source) bs)
| source == "" -> Nothing
| otherwise -> parseTrailer (BS.init bs)
getOffset bs = case BS.breakEnd (== '\n') (BS.init bs) of
(_, nstr) -> case readDec $ BS.unpack nstr of
[(n,_)] -> n
_ -> error "Could not find Offset"
parseCRDict :: BS.ByteString -> Dict
parseCRDict rlt = case parseOnly crdict rlt of
Left err -> error $ show (BS.take 100 rlt)
Right (PdfDict dict) -> dict
Right _ -> error "Could not find Cross-Reference dictionary"
where
crdict :: Parser Obj
crdict = do
spaces
(try skipCRtable <|> skipCRstream)
d <- pdfdictionary <* spaces
return d
skipCRtable = ((manyTill anyChar (try $ string "trailer")) >> spaces)
skipCRstream = (many1 digit >> spaces >> digit >> string " obj" >> spaces)
rootRef :: BS.ByteString -> Maybe Int
rootRef bs = case parseTrailer bs of
Just dict -> findRefs isRootRef dict
Nothing -> rootRefFromCRStream bs
rootRefFromCRStream :: BS.ByteString -> Maybe Int
rootRefFromCRStream bs =
let offset = (read . BS.unpack . head . drop 1 . reverse . BS.lines $ (trace (show bs) bs)) :: Int
crstrm = snd . head . findObjs $ BS.drop offset bs
crdict = parseCRDict crstrm
in findRefs isRootRef $ crdict
isRootRef (PdfName "/Root", ObjRef x) = True
isRootRef (_,_) = False
findRefs :: ((Obj,Obj) -> Bool) -> Dict -> Maybe Int
findRefs pred dict = case find pred dict of
Just (_, ObjRef x) -> Just x
Nothing -> Nothing
-- find Info
findTrailer bs = do
case parseTrailer bs of
Just d -> d
Nothing -> []
infoRef bs = case parseTrailer bs of
Just dict -> findRefs isInfoRef dict
Nothing -> error "No ref for info"
isInfoRef (PdfName "/Info", ObjRef x) = True
isInfoRef (_,_) = False
expand PDF 1.5 Object Stream
expandObjStm :: [PDFObj] -> [PDFObj]
expandObjStm os = concat $ map objStm os
objStm :: PDFObj -> [PDFObj]
objStm (n, obj) = case findDictOfType "/ObjStm" obj of
Nothing -> [(n,obj)]
Just _ -> pdfObjStm n $ BSL.toStrict $ rawStream obj
refOffset :: Parser ([(Int, Int)], String)
refOffset = spaces *> ((,)
<$> many1 ((\r o -> (read r :: Int, read o :: Int))
<$> (many1 digit <* spaces)
<*> (many1 digit <* spaces))
<*> many1 anyChar)
pdfObjStm n s =
let (location, objstr) = case parseOnly refOffset s of
Right val -> val
Left err -> error $ "Failed to parse Object Stream: "
in map (\(r,o) -> (r, parseDict $ BS.pack $ drop o objstr)) location
where parseDict s' = case parseOnly pdfdictionary s' of
Right obj -> [obj]
Left _ -> case parseOnly pdfarray s' of
Right obj -> [obj]
Left _ -> case parseOnly pdfletters s' of
Right obj -> [obj]
Left err -> error $ (show err) ++ ":\n Failed to parse obj around; \n"
++ (show $ BS.take 100 s')
make fontmap from page 's /Resources ( see 3.7.2 of PDF Ref . )
findFontEncoding d os = findEncoding (fontObjs d os) os
findEncoding :: Dict -> [PDFObj] -> [(String, Encoding)]
findEncoding dict objs = map pairwise dict
where
pairwise (PdfName n, ObjRef r) = (n, encoding r objs)
pairwise x = ("", NullMap)
fontObjs :: Dict -> [PDFObj] -> Dict
fontObjs dict objs = case findResourcesDict dict objs of
Just d -> case findObjFromDict d "/Font" of
Just (PdfDict d') -> d'
Just (ObjRef x) -> case findDictByRef x objs of
Just d' -> d'
otherwise -> error "cannot find /Font dictionary"
otherwise -> trace (show d) $ []
Nothing -> []
findResourcesDict :: Dict -> [PDFObj] -> Maybe Dict
findResourcesDict dict objs = case find resources dict of
Just (_, ObjRef x) -> findDictByRef x objs
Just (_, PdfDict d) -> Just d
otherwise -> error (show dict)
where
resources (PdfName "/Resources", _) = True
resources _ = False
encoding :: Int -> [PDFObj] -> Encoding
encoding x objs = case subtype of
Just (PdfName "/Type0") -> case encoding of
Just (PdfName "/Identity-H") -> head $ cidSysInfo descendantFonts
TODO " when /Encoding is stream of CMap
Just (PdfName s) -> error $ "Unknown Encoding " ++ (show s) ++ " for a Type0 font. Check " ++ show x
_ -> error $ "Something wrong with a Type0 font. Check " ++ (show x)
Just (PdfName "/Type1") -> case encoding of
Just (ObjRef r) -> case findObjFromDictWithRef r "/Differences" objs of
Just (PdfArray arr) -> charDiff arr
_ -> error "No /Differences"
Just (PdfDict d) -> case findObjFromDict d "/Differences" of
Just (PdfArray arr) -> charDiff arr
_ -> error "No /Differences"
Just (PdfName "/MacRomanEncoding") -> NullMap
Just (PdfName "/MacExpertEncoding") -> NullMap
Just (PdfName "/WinAnsiEncoding") -> NullMap
TODO : FontFile ( Type 1 ) , FontFile2 ( TrueType ) , FontFile3 ( Other than Type1C )
_ -> case findObjFromDict (fontDescriptor' x) "/FontFile3" of
Just (ObjRef fontfile) ->
CFF.encoding $ BSL.toStrict $ rawStreamByRef objs fontfile
_ -> case findObjFromDict (fontDescriptor' x) "/FontFile" of
Just (ObjRef fontfile) ->
Type1.encoding $ BSL.toStrict $ rawStreamByRef objs fontfile
_ -> NullMap
TODO
Just (PdfName "/Type2") -> NullMap
Just (PdfName "/Type3") -> NullMap
_ -> NullMap
where
subtype = get "/Subtype"
encoding = get "/Encoding"
toUnicode = get "/ToUnicode"
get s = findObjFromDictWithRef x s objs
-- Should be an array (or ref to an array) containing refs
descendantFonts :: [Obj]
descendantFonts = case findObjFromDictWithRef x "/DescendantFonts" objs of
Just (PdfArray dfrs) -> dfrs
Just (ObjRef r) -> case findObjsByRef r objs of
Just [(PdfArray dfrs)] -> dfrs
_ -> error $ "Can not find /DescendantFonts entries in " ++ show r
_ -> error $ "Can not find /DescendantFonts itself in " ++ show x
cidSysInfo :: [Obj] -> [Encoding]
cidSysInfo [] = []
cidSysInfo ((ObjRef r):rs) = (cidSysInfo' r):(cidSysInfo rs)
cidSysInfo' dfr = case findObjFromDictWithRef dfr "/CIDSystemInfo" objs of
Just (PdfDict dict) -> getCIDSystemInfo dict
Just (ObjRef r) -> case findDictByRef r objs of
Just dict -> getCIDSystemInfo dict
_ -> error $ "Can not find /CIDSystemInfo entries in" ++ show r
_ -> error $ "Can not find /CidSystemInfo itself " ++ show dfr
fontDescriptor :: [Obj] -> [Dict]
fontDescriptor [] = []
fontDescriptor ((ObjRef r):rs) = (fontDescriptor' r):(fontDescriptor rs)
fontDescriptor' :: Int -> Dict
fontDescriptor' fdr = case findObjFromDictWithRef fdr "/FontDescriptor" objs of
Just (ObjRef r) -> case findDictByRef r objs of
Just dict -> dict
_ -> error $ "No /FontDescriptor entries in " ++ show r
_ -> error $ "Can not find /FontDescriptor itself in " ++ show fdr
getCIDSystemInfo d =
let registry = case findObjFromDict d "/Registry" of
Just (PdfText r) -> r
otherwise -> error "Can not find /Registry"
ordering = case findObjFromDict d "/Ordering" of
Just (PdfText o) -> o
othserwise -> error "Can not find /Ordering"
supplement = case findObjFromDict d "/Supplement" of
Just (PdfNumber s) -> s
otherwise -> error "Can not find /Supprement"
ex . " Adobe - Japan1 "
in if cmap == "Adobe-Japan1"
then CIDmap cmap
else WithCharSet ""
charDiff :: [Obj] -> Encoding
charDiff objs = Encoding $ charmap objs 0
where charmap (PdfNumber x : PdfName n : xs) i =
if i < truncate x then
(chr $ truncate x, n) : (charmap xs $ incr x)
else
(chr $ i, n) : (charmap xs $ i+1)
charmap (PdfName n : xs) i = (chr i, n) : (charmap xs $ i+1)
charmap [] i = []
incr x = (truncate x) + 1
findCMap :: Dict -> [PDFObj] -> [(String, CMap)]
findCMap d objs = map pairwise (fontObjs d objs)
where
pairwise (PdfName n, ObjRef r) = (n, toUnicode r objs)
pairwise x = ("", [])
toUnicode :: Int -> [PDFObj] -> CMap
toUnicode x objs =
case findObjFromDictWithRef x "/ToUnicode" objs of
Just (ObjRef ref) ->
parseCMap $ rawStreamByRef objs ref
otherwise -> noToUnicode x objs
noToUnicode x objs =
case findObjFromDictWithRef x "/DescendantFonts" objs of
Just (ObjRef ref) ->
case findObjsByRef ref objs of
Just [(PdfArray ((ObjRef subref):_))] ->
case findObjFromDictWithRef subref "/FontDescriptor" objs of
Just (ObjRef desc) ->
case findObjFromDictWithRef desc "/FontFile2" objs of
Just (ObjRef fontfile) ->
OpenType.cmap $ BSL.toStrict $ rawStreamByRef objs fontfile
otherwise -> []
otherwise -> []
otherwise -> []
otherwise -> []
| null |
https://raw.githubusercontent.com/k16shikano/hpdft/5a5956b28cc9a4bc85efdfe816d3f064b5225e22/src/PDF/DocumentStructure.hs
|
haskell
|
# LANGUAGE OverloadedStrings #
find objects
need fix
find Info
Should be an array (or ref to an array) containing refs
|
|
Module : PDF.DocumentStructure
Description : Function to walk around Document Structure of a PDF file
Copyright : ( c ) , 2020
License : MIT
Maintainer :
Module : PDF.DocumentStructure
Description : Function to walk around Document Structure of a PDF file
Copyright : (c) Keiichiro Shikano, 2020
License : MIT
Maintainer :
-}
module PDF.DocumentStructure
( parseTrailer
, expandObjStm
, rootRef
, contentsStream
, rawStreamByRef
, findKids
, findPages
, findDict
, findDictByRef
, findDictOfType
, findObjFromDict
, findObjFromDictWithRef
, findObjsByRef
, findObjs
, findTrailer
, rawStream
) where
import Data.Char (chr)
import Data.List (find)
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BSL
import qualified Data.ByteString.Builder as B
import qualified Data.Text as T
import Data.Maybe (fromMaybe)
import Numeric (readDec)
import Data.Attoparsec.ByteString.Char8 hiding (take)
import Data.Attoparsec.Combinator
import Control.Applicative
import Codec.Compression.Zlib (decompress)
import Debug.Trace
import PDF.Definition
import PDF.Object
import PDF.ContentStream (parseStream, parseColorSpace)
import PDF.Cmap (parseCMap)
import qualified PDF.OpenType as OpenType
import qualified PDF.CFF as CFF
import qualified PDF.Type1 as Type1
spaces = skipSpace
oneOf = satisfy . inClass
noneOf = satisfy . notInClass
findObjs :: BS.ByteString -> [PDFBS]
findObjs contents = case parseOnly (many1 pdfObj) contents of
Left err -> []
Right rlt -> rlt
findXref :: BS.ByteString -> String
findXref contents = case parseOnly (xref) contents of
Left err -> []
Right rlt -> rlt
findObjsByRef :: Int -> [PDFObj] -> Maybe [Obj]
findObjsByRef x pdfobjs = case find (isRefObj (Just x)) pdfobjs of
Just (_,objs) -> Just objs
Nothing -> Nothing
where
isRefObj (Just x) (y, objs) = if x==y then True else False
isRefObj _ _ = False
findObjFromDictWithRef :: Int -> String -> [PDFObj] -> Maybe Obj
findObjFromDictWithRef ref name objs = case findDictByRef ref objs of
Just d -> findObjFromDict d name
Nothing -> Nothing
findObjFromDict :: Dict -> String -> Maybe Obj
findObjFromDict d name = case find isName d of
Just (_, o) -> Just o
otherwise -> Nothing
where isName (PdfName n, _) = if name == n then True else False
isName _ = False
findDictByRef :: Int -> [PDFObj] -> Maybe Dict
findDictByRef ref objs = case findObjsByRef ref objs of
Just os -> findDict os
Nothing -> Nothing
findDictOfType :: String -> [Obj] -> Maybe Dict
findDictOfType typename objs = case findDict objs of
Just d -> if isType d then Just d else Nothing
Nothing -> Nothing
where
isType dict = (PdfName "/Type",PdfName typename) `elem` dict
findDict :: [Obj] -> Maybe Dict
findDict objs = case find isDict objs of
Just (PdfDict d) -> Just d
otherwise -> Nothing
where
isDict :: Obj -> Bool
isDict (PdfDict d) = True
isDict _ = False
findPages :: Dict -> Maybe Int
findPages dict = case find isPagesRef dict of
Just (_, ObjRef x) -> Just x
Nothing -> Nothing
where
isPagesRef (PdfName "/Pages", ObjRef x) = True
isPagesRef (_,_) = False
findKids :: Dict -> Maybe [Int]
findKids dict = case find isKidsRefs dict of
Just (_, PdfArray arr) -> Just (parseRefsArray arr)
Nothing -> Nothing
where
isKidsRefs (PdfName "/Kids", PdfArray x) = True
isKidsRefs (_,_) = False
contentsStream :: Dict -> PSR -> [PDFObj] -> PDFStream
contentsStream dict st objs = case find contents dict of
Just (PdfName "/Contents", PdfArray arr) -> getContentArray arr
Just (PdfName "/Contents", ObjRef r) ->
case findObjsByRef r objs of
Just [PdfArray arr] -> getContentArray arr
Just _ -> getContent r
Nothing -> error "No content to be shown"
Nothing -> error "No content to be shown"
where
contents (PdfName "/Contents", _) = True
contents _ = False
getContentArray arr = parseContentStream dict st objs $
BSL.concat $ map (rawStreamByRef objs) (parseRefsArray arr)
getContent r = parseContentStream dict st objs $ rawStreamByRef objs r
parseContentStream :: Dict -> PSR -> [PDFObj] -> BSL.ByteString -> PDFStream
parseContentStream dict st objs s =
parseStream (st {fontmaps=fontdict, cmaps=cmap}) s
where fontdict = findFontEncoding dict objs
cmap = findCMap dict objs
rawStreamByRef :: [PDFObj] -> Int -> BSL.ByteString
rawStreamByRef pdfobjs x = case findObjsByRef x pdfobjs of
Just objs -> rawStream objs
Nothing -> error "No object with stream to be shown"
rawStream :: [Obj] -> BSL.ByteString
rawStream objs = case find isStream objs of
Just (PdfStream strm) -> rawStream' (fromMaybe [] $ findDict objs) strm
Nothing -> BSL.pack $ show objs
where
isStream (PdfStream s) = True
isStream _ = False
rawStream' :: Dict -> BSL.ByteString -> BSL.ByteString
rawStream' d s = streamFilter d s
streamFilter d = case find withFilter d of
Just (PdfName "/Filter", PdfName "/FlateDecode")
-> decompress
Just (PdfName "/Filter", PdfName f)
Just _ -> error $ "No Stream Compression Filter."
Nothing -> id
withFilter (PdfName "/Filter", _) = True
withFilter _ = False
contentsColorSpace :: Dict -> PSR -> [PDFObj] -> [T.Text]
contentsColorSpace dict st objs = case find contents dict of
Just (PdfName "/Contents", PdfArray arr) -> concat $ map (parseColorSpace (st {xcolorspaces=xobjcs}) . rawStreamByRef objs) (parseRefsArray arr)
Just (PdfName "/Contents", ObjRef x) -> parseColorSpace (st {xcolorspaces=xobjcs}) $ rawStreamByRef objs x
Nothing -> error "No content to be shown"
where
contents (PdfName "/Contents", _) = True
contents _ = False
xobjcs = findXObjectColorSpace dict objs
find XObject
findXObjectColorSpace d os = xobjColorSpaceMap (findXObject d os) os
xobjColorSpaceMap dict objs = map pairwise dict
where
pairwise (PdfName n, ObjRef r) = xobjColorSpace r objs
pairwise x = ""
findXObject dict objs = case findResourcesDict dict objs of
Just d -> case findObjFromDict d "/XObject" of
Just (PdfDict d) -> d
otherwise -> []
Nothing -> []
xobjColorSpace :: Int -> [PDFObj] -> String
xobjColorSpace x objs = case findObjFromDictWithRef x "/ColorSpace" objs of
Just (PdfName cs) -> cs
otherwise -> ""
find root ref from Trailer or Cross - Reference Dictionary
parseTrailer :: BS.ByteString -> Maybe Dict
parseTrailer bs = case BS.breakEnd (== '\n') bs of
(source, eofLine)
| "%%EOF" `BS.isPrefixOf` eofLine
-> Just (parseCRDict $ BS.drop (getOffset source) bs)
| source == "" -> Nothing
| otherwise -> parseTrailer (BS.init bs)
getOffset bs = case BS.breakEnd (== '\n') (BS.init bs) of
(_, nstr) -> case readDec $ BS.unpack nstr of
[(n,_)] -> n
_ -> error "Could not find Offset"
parseCRDict :: BS.ByteString -> Dict
parseCRDict rlt = case parseOnly crdict rlt of
Left err -> error $ show (BS.take 100 rlt)
Right (PdfDict dict) -> dict
Right _ -> error "Could not find Cross-Reference dictionary"
where
crdict :: Parser Obj
crdict = do
spaces
(try skipCRtable <|> skipCRstream)
d <- pdfdictionary <* spaces
return d
skipCRtable = ((manyTill anyChar (try $ string "trailer")) >> spaces)
skipCRstream = (many1 digit >> spaces >> digit >> string " obj" >> spaces)
rootRef :: BS.ByteString -> Maybe Int
rootRef bs = case parseTrailer bs of
Just dict -> findRefs isRootRef dict
Nothing -> rootRefFromCRStream bs
rootRefFromCRStream :: BS.ByteString -> Maybe Int
rootRefFromCRStream bs =
let offset = (read . BS.unpack . head . drop 1 . reverse . BS.lines $ (trace (show bs) bs)) :: Int
crstrm = snd . head . findObjs $ BS.drop offset bs
crdict = parseCRDict crstrm
in findRefs isRootRef $ crdict
isRootRef (PdfName "/Root", ObjRef x) = True
isRootRef (_,_) = False
findRefs :: ((Obj,Obj) -> Bool) -> Dict -> Maybe Int
findRefs pred dict = case find pred dict of
Just (_, ObjRef x) -> Just x
Nothing -> Nothing
findTrailer bs = do
case parseTrailer bs of
Just d -> d
Nothing -> []
infoRef bs = case parseTrailer bs of
Just dict -> findRefs isInfoRef dict
Nothing -> error "No ref for info"
isInfoRef (PdfName "/Info", ObjRef x) = True
isInfoRef (_,_) = False
expand PDF 1.5 Object Stream
expandObjStm :: [PDFObj] -> [PDFObj]
expandObjStm os = concat $ map objStm os
objStm :: PDFObj -> [PDFObj]
objStm (n, obj) = case findDictOfType "/ObjStm" obj of
Nothing -> [(n,obj)]
Just _ -> pdfObjStm n $ BSL.toStrict $ rawStream obj
refOffset :: Parser ([(Int, Int)], String)
refOffset = spaces *> ((,)
<$> many1 ((\r o -> (read r :: Int, read o :: Int))
<$> (many1 digit <* spaces)
<*> (many1 digit <* spaces))
<*> many1 anyChar)
pdfObjStm n s =
let (location, objstr) = case parseOnly refOffset s of
Right val -> val
Left err -> error $ "Failed to parse Object Stream: "
in map (\(r,o) -> (r, parseDict $ BS.pack $ drop o objstr)) location
where parseDict s' = case parseOnly pdfdictionary s' of
Right obj -> [obj]
Left _ -> case parseOnly pdfarray s' of
Right obj -> [obj]
Left _ -> case parseOnly pdfletters s' of
Right obj -> [obj]
Left err -> error $ (show err) ++ ":\n Failed to parse obj around; \n"
++ (show $ BS.take 100 s')
make fontmap from page 's /Resources ( see 3.7.2 of PDF Ref . )
findFontEncoding d os = findEncoding (fontObjs d os) os
findEncoding :: Dict -> [PDFObj] -> [(String, Encoding)]
findEncoding dict objs = map pairwise dict
where
pairwise (PdfName n, ObjRef r) = (n, encoding r objs)
pairwise x = ("", NullMap)
fontObjs :: Dict -> [PDFObj] -> Dict
fontObjs dict objs = case findResourcesDict dict objs of
Just d -> case findObjFromDict d "/Font" of
Just (PdfDict d') -> d'
Just (ObjRef x) -> case findDictByRef x objs of
Just d' -> d'
otherwise -> error "cannot find /Font dictionary"
otherwise -> trace (show d) $ []
Nothing -> []
findResourcesDict :: Dict -> [PDFObj] -> Maybe Dict
findResourcesDict dict objs = case find resources dict of
Just (_, ObjRef x) -> findDictByRef x objs
Just (_, PdfDict d) -> Just d
otherwise -> error (show dict)
where
resources (PdfName "/Resources", _) = True
resources _ = False
encoding :: Int -> [PDFObj] -> Encoding
encoding x objs = case subtype of
Just (PdfName "/Type0") -> case encoding of
Just (PdfName "/Identity-H") -> head $ cidSysInfo descendantFonts
TODO " when /Encoding is stream of CMap
Just (PdfName s) -> error $ "Unknown Encoding " ++ (show s) ++ " for a Type0 font. Check " ++ show x
_ -> error $ "Something wrong with a Type0 font. Check " ++ (show x)
Just (PdfName "/Type1") -> case encoding of
Just (ObjRef r) -> case findObjFromDictWithRef r "/Differences" objs of
Just (PdfArray arr) -> charDiff arr
_ -> error "No /Differences"
Just (PdfDict d) -> case findObjFromDict d "/Differences" of
Just (PdfArray arr) -> charDiff arr
_ -> error "No /Differences"
Just (PdfName "/MacRomanEncoding") -> NullMap
Just (PdfName "/MacExpertEncoding") -> NullMap
Just (PdfName "/WinAnsiEncoding") -> NullMap
TODO : FontFile ( Type 1 ) , FontFile2 ( TrueType ) , FontFile3 ( Other than Type1C )
_ -> case findObjFromDict (fontDescriptor' x) "/FontFile3" of
Just (ObjRef fontfile) ->
CFF.encoding $ BSL.toStrict $ rawStreamByRef objs fontfile
_ -> case findObjFromDict (fontDescriptor' x) "/FontFile" of
Just (ObjRef fontfile) ->
Type1.encoding $ BSL.toStrict $ rawStreamByRef objs fontfile
_ -> NullMap
TODO
Just (PdfName "/Type2") -> NullMap
Just (PdfName "/Type3") -> NullMap
_ -> NullMap
where
subtype = get "/Subtype"
encoding = get "/Encoding"
toUnicode = get "/ToUnicode"
get s = findObjFromDictWithRef x s objs
descendantFonts :: [Obj]
descendantFonts = case findObjFromDictWithRef x "/DescendantFonts" objs of
Just (PdfArray dfrs) -> dfrs
Just (ObjRef r) -> case findObjsByRef r objs of
Just [(PdfArray dfrs)] -> dfrs
_ -> error $ "Can not find /DescendantFonts entries in " ++ show r
_ -> error $ "Can not find /DescendantFonts itself in " ++ show x
cidSysInfo :: [Obj] -> [Encoding]
cidSysInfo [] = []
cidSysInfo ((ObjRef r):rs) = (cidSysInfo' r):(cidSysInfo rs)
cidSysInfo' dfr = case findObjFromDictWithRef dfr "/CIDSystemInfo" objs of
Just (PdfDict dict) -> getCIDSystemInfo dict
Just (ObjRef r) -> case findDictByRef r objs of
Just dict -> getCIDSystemInfo dict
_ -> error $ "Can not find /CIDSystemInfo entries in" ++ show r
_ -> error $ "Can not find /CidSystemInfo itself " ++ show dfr
fontDescriptor :: [Obj] -> [Dict]
fontDescriptor [] = []
fontDescriptor ((ObjRef r):rs) = (fontDescriptor' r):(fontDescriptor rs)
fontDescriptor' :: Int -> Dict
fontDescriptor' fdr = case findObjFromDictWithRef fdr "/FontDescriptor" objs of
Just (ObjRef r) -> case findDictByRef r objs of
Just dict -> dict
_ -> error $ "No /FontDescriptor entries in " ++ show r
_ -> error $ "Can not find /FontDescriptor itself in " ++ show fdr
getCIDSystemInfo d =
let registry = case findObjFromDict d "/Registry" of
Just (PdfText r) -> r
otherwise -> error "Can not find /Registry"
ordering = case findObjFromDict d "/Ordering" of
Just (PdfText o) -> o
othserwise -> error "Can not find /Ordering"
supplement = case findObjFromDict d "/Supplement" of
Just (PdfNumber s) -> s
otherwise -> error "Can not find /Supprement"
ex . " Adobe - Japan1 "
in if cmap == "Adobe-Japan1"
then CIDmap cmap
else WithCharSet ""
charDiff :: [Obj] -> Encoding
charDiff objs = Encoding $ charmap objs 0
where charmap (PdfNumber x : PdfName n : xs) i =
if i < truncate x then
(chr $ truncate x, n) : (charmap xs $ incr x)
else
(chr $ i, n) : (charmap xs $ i+1)
charmap (PdfName n : xs) i = (chr i, n) : (charmap xs $ i+1)
charmap [] i = []
incr x = (truncate x) + 1
findCMap :: Dict -> [PDFObj] -> [(String, CMap)]
findCMap d objs = map pairwise (fontObjs d objs)
where
pairwise (PdfName n, ObjRef r) = (n, toUnicode r objs)
pairwise x = ("", [])
toUnicode :: Int -> [PDFObj] -> CMap
toUnicode x objs =
case findObjFromDictWithRef x "/ToUnicode" objs of
Just (ObjRef ref) ->
parseCMap $ rawStreamByRef objs ref
otherwise -> noToUnicode x objs
noToUnicode x objs =
case findObjFromDictWithRef x "/DescendantFonts" objs of
Just (ObjRef ref) ->
case findObjsByRef ref objs of
Just [(PdfArray ((ObjRef subref):_))] ->
case findObjFromDictWithRef subref "/FontDescriptor" objs of
Just (ObjRef desc) ->
case findObjFromDictWithRef desc "/FontFile2" objs of
Just (ObjRef fontfile) ->
OpenType.cmap $ BSL.toStrict $ rawStreamByRef objs fontfile
otherwise -> []
otherwise -> []
otherwise -> []
otherwise -> []
|
ed34396b8d1a7ed639cdeb20997ce652bd37ffcc68d1074207e517221d419ebd
|
juspay/atlas
|
Types.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 : API.Beckn . Types
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 : API.Beckn.Types
Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022
License : Apache 2.0 (see the file LICENSE)
Maintainer :
Stability : experimental
Portability : non-portable
-}
module API.Beckn.Types where
import qualified API.Beckn.OnConfirm.Types as OnConfirm
import qualified API.Beckn.OnSearch.Types as OnSearch
import qualified API.Beckn.OnStatus.Types as OnStatus
import Beckn.Utils.Servant.SignatureAuth
import Servant
type API =
"beckn"
:> SignatureAuth "Authorization"
:> ( OnSearch.API
:<|> OnConfirm.API
:<|> OnStatus.API
)
| null |
https://raw.githubusercontent.com/juspay/atlas/e64b227dc17887fb01c2554db21c08284d18a806/app/parking-bap/src/API/Beckn/Types.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 : API.Beckn . Types
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 : API.Beckn.Types
Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022
License : Apache 2.0 (see the file LICENSE)
Maintainer :
Stability : experimental
Portability : non-portable
-}
module API.Beckn.Types where
import qualified API.Beckn.OnConfirm.Types as OnConfirm
import qualified API.Beckn.OnSearch.Types as OnSearch
import qualified API.Beckn.OnStatus.Types as OnStatus
import Beckn.Utils.Servant.SignatureAuth
import Servant
type API =
"beckn"
:> SignatureAuth "Authorization"
:> ( OnSearch.API
:<|> OnConfirm.API
:<|> OnStatus.API
)
|
|
aad2d87982e4093321583d552f3bfb7079664a2bca3b1112e271cbc56de4f612
|
may-liu/qtalk
|
node_private.erl
|
%%% ====================================================================
` ` The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%%% compliance with the License. You should have received a copy of the
%%% Erlang Public License along with this software. If not, it can be
%%% retrieved via the world wide web at /.
%%%
%%%
Software distributed under the License is distributed on an " AS IS "
%%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%%% the License for the specific language governing rights and limitations
%%% under the License.
%%%
%%%
The Initial Developer of the Original Code is ProcessOne .
Portions created by ProcessOne are Copyright 2006 - 2014 , ProcessOne
All Rights Reserved . ''
This software is copyright 2006 - 2014 , ProcessOne .
%%%
%%%
2006 - 2014 ProcessOne
@author >
%%% [-one.net/]
%%% @version {@vsn}, {@date} {@time}
%%% @end
%%% ====================================================================
-module(node_private).
-author('').
-include("pubsub.hrl").
-include("jlib.hrl").
-behaviour(gen_pubsub_node).
%% Note on function definition
%% included is all defined plugin function
%% it's possible not to define some function at all
%% in that case, warning will be generated at compilation
%% and function call will fail,
%% then mod_pubsub will call function from node_hometree
%% (this makes code cleaner, but execution a little bit longer)
%% API definition
-export([init/3, terminate/2, options/0, features/0,
create_node_permission/6, create_node/2, delete_node/1,
purge_node/2, subscribe_node/8, unsubscribe_node/4,
publish_item/6, delete_item/4, remove_extra_items/3,
get_entity_affiliations/2, get_node_affiliations/1,
get_affiliation/2, set_affiliation/3,
get_entity_subscriptions/2, get_node_subscriptions/1,
get_subscriptions/2, set_subscriptions/4,
get_pending_nodes/2, get_states/1, get_state/2,
set_state/1, get_items/6, get_items/2, get_item/7,
get_item/2, set_item/1, get_item_name/3, node_to_path/1,
path_to_node/1]).
init(Host, ServerHost, Opts) ->
node_hometree:init(Host, ServerHost, Opts).
terminate(Host, ServerHost) ->
node_hometree:terminate(Host, ServerHost).
options() ->
[{deliver_payloads, true}, {notify_config, false},
{notify_delete, false}, {notify_retract, true},
{purge_offline, false}, {persist_items, true},
{max_items, ?MAXITEMS}, {subscribe, true},
{access_model, whitelist}, {roster_groups_allowed, []},
{publish_model, publishers},
{notification_type, headline},
{max_payload_size, ?MAX_PAYLOAD_SIZE},
{send_last_published_item, never},
{deliver_notifications, false},
{presence_based_delivery, false}].
features() ->
[<<"create-nodes">>, <<"delete-nodes">>,
<<"delete-items">>, <<"instant-nodes">>,
<<"outcast-affiliation">>, <<"persistent-items">>,
<<"publish">>, <<"purge-nodes">>, <<"retract-items">>,
<<"retrieve-affiliations">>, <<"retrieve-items">>,
<<"retrieve-subscriptions">>, <<"subscribe">>,
<<"subscription-notifications">>].
create_node_permission(Host, ServerHost, Node,
ParentNode, Owner, Access) ->
node_hometree:create_node_permission(Host, ServerHost,
Node, ParentNode, Owner, Access).
create_node(NodeId, Owner) ->
node_hometree:create_node(NodeId, Owner).
delete_node(Removed) ->
node_hometree:delete_node(Removed).
subscribe_node(NodeId, Sender, Subscriber, AccessModel,
SendLast, PresenceSubscription, RosterGroup, Options) ->
node_hometree:subscribe_node(NodeId, Sender, Subscriber,
AccessModel, SendLast, PresenceSubscription,
RosterGroup, Options).
unsubscribe_node(NodeId, Sender, Subscriber, SubID) ->
node_hometree:unsubscribe_node(NodeId, Sender,
Subscriber, SubID).
publish_item(NodeId, Publisher, Model, MaxItems, ItemId,
Payload) ->
node_hometree:publish_item(NodeId, Publisher, Model,
MaxItems, ItemId, Payload).
remove_extra_items(NodeId, MaxItems, ItemIds) ->
node_hometree:remove_extra_items(NodeId, MaxItems,
ItemIds).
delete_item(NodeId, Publisher, PublishModel, ItemId) ->
node_hometree:delete_item(NodeId, Publisher,
PublishModel, ItemId).
purge_node(NodeId, Owner) ->
node_hometree:purge_node(NodeId, Owner).
get_entity_affiliations(Host, Owner) ->
node_hometree:get_entity_affiliations(Host, Owner).
get_node_affiliations(NodeId) ->
node_hometree:get_node_affiliations(NodeId).
get_affiliation(NodeId, Owner) ->
node_hometree:get_affiliation(NodeId, Owner).
set_affiliation(NodeId, Owner, Affiliation) ->
node_hometree:set_affiliation(NodeId, Owner,
Affiliation).
get_entity_subscriptions(Host, Owner) ->
node_hometree:get_entity_subscriptions(Host, Owner).
get_node_subscriptions(NodeId) ->
node_hometree:get_node_subscriptions(NodeId).
get_subscriptions(NodeId, Owner) ->
node_hometree:get_subscriptions(NodeId, Owner).
set_subscriptions(NodeId, Owner, Subscription, SubId) ->
node_hometree:set_subscriptions(NodeId, Owner,
Subscription, SubId).
get_pending_nodes(Host, Owner) ->
node_hometree:get_pending_nodes(Host, Owner).
get_states(NodeId) -> node_hometree:get_states(NodeId).
get_state(NodeId, JID) ->
node_hometree:get_state(NodeId, JID).
set_state(State) -> node_hometree:set_state(State).
get_items(NodeId, From) ->
node_hometree:get_items(NodeId, From).
get_items(NodeId, JID, AccessModel,
PresenceSubscription, RosterGroup, SubId) ->
node_hometree:get_items(NodeId, JID, AccessModel,
PresenceSubscription, RosterGroup, SubId).
get_item(NodeId, ItemId) ->
node_hometree:get_item(NodeId, ItemId).
get_item(NodeId, ItemId, JID, AccessModel,
PresenceSubscription, RosterGroup, SubId) ->
node_hometree:get_item(NodeId, ItemId, JID, AccessModel,
PresenceSubscription, RosterGroup, SubId).
set_item(Item) -> node_hometree:set_item(Item).
get_item_name(Host, Node, Id) ->
node_hometree:get_item_name(Host, Node, Id).
node_to_path(Node) -> node_flat:node_to_path(Node).
path_to_node(Path) -> node_flat:path_to_node(Path).
| null |
https://raw.githubusercontent.com/may-liu/qtalk/f5431e5a7123975e9656e7ab239e674ce33713cd/qtalk_opensource/src/node_private.erl
|
erlang
|
====================================================================
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved via the world wide web at /.
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
[-one.net/]
@version {@vsn}, {@date} {@time}
@end
====================================================================
Note on function definition
included is all defined plugin function
it's possible not to define some function at all
in that case, warning will be generated at compilation
and function call will fail,
then mod_pubsub will call function from node_hometree
(this makes code cleaner, but execution a little bit longer)
API definition
|
` ` The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
The Initial Developer of the Original Code is ProcessOne .
Portions created by ProcessOne are Copyright 2006 - 2014 , ProcessOne
All Rights Reserved . ''
This software is copyright 2006 - 2014 , ProcessOne .
2006 - 2014 ProcessOne
@author >
-module(node_private).
-author('').
-include("pubsub.hrl").
-include("jlib.hrl").
-behaviour(gen_pubsub_node).
-export([init/3, terminate/2, options/0, features/0,
create_node_permission/6, create_node/2, delete_node/1,
purge_node/2, subscribe_node/8, unsubscribe_node/4,
publish_item/6, delete_item/4, remove_extra_items/3,
get_entity_affiliations/2, get_node_affiliations/1,
get_affiliation/2, set_affiliation/3,
get_entity_subscriptions/2, get_node_subscriptions/1,
get_subscriptions/2, set_subscriptions/4,
get_pending_nodes/2, get_states/1, get_state/2,
set_state/1, get_items/6, get_items/2, get_item/7,
get_item/2, set_item/1, get_item_name/3, node_to_path/1,
path_to_node/1]).
init(Host, ServerHost, Opts) ->
node_hometree:init(Host, ServerHost, Opts).
terminate(Host, ServerHost) ->
node_hometree:terminate(Host, ServerHost).
options() ->
[{deliver_payloads, true}, {notify_config, false},
{notify_delete, false}, {notify_retract, true},
{purge_offline, false}, {persist_items, true},
{max_items, ?MAXITEMS}, {subscribe, true},
{access_model, whitelist}, {roster_groups_allowed, []},
{publish_model, publishers},
{notification_type, headline},
{max_payload_size, ?MAX_PAYLOAD_SIZE},
{send_last_published_item, never},
{deliver_notifications, false},
{presence_based_delivery, false}].
features() ->
[<<"create-nodes">>, <<"delete-nodes">>,
<<"delete-items">>, <<"instant-nodes">>,
<<"outcast-affiliation">>, <<"persistent-items">>,
<<"publish">>, <<"purge-nodes">>, <<"retract-items">>,
<<"retrieve-affiliations">>, <<"retrieve-items">>,
<<"retrieve-subscriptions">>, <<"subscribe">>,
<<"subscription-notifications">>].
create_node_permission(Host, ServerHost, Node,
ParentNode, Owner, Access) ->
node_hometree:create_node_permission(Host, ServerHost,
Node, ParentNode, Owner, Access).
create_node(NodeId, Owner) ->
node_hometree:create_node(NodeId, Owner).
delete_node(Removed) ->
node_hometree:delete_node(Removed).
subscribe_node(NodeId, Sender, Subscriber, AccessModel,
SendLast, PresenceSubscription, RosterGroup, Options) ->
node_hometree:subscribe_node(NodeId, Sender, Subscriber,
AccessModel, SendLast, PresenceSubscription,
RosterGroup, Options).
unsubscribe_node(NodeId, Sender, Subscriber, SubID) ->
node_hometree:unsubscribe_node(NodeId, Sender,
Subscriber, SubID).
publish_item(NodeId, Publisher, Model, MaxItems, ItemId,
Payload) ->
node_hometree:publish_item(NodeId, Publisher, Model,
MaxItems, ItemId, Payload).
remove_extra_items(NodeId, MaxItems, ItemIds) ->
node_hometree:remove_extra_items(NodeId, MaxItems,
ItemIds).
delete_item(NodeId, Publisher, PublishModel, ItemId) ->
node_hometree:delete_item(NodeId, Publisher,
PublishModel, ItemId).
purge_node(NodeId, Owner) ->
node_hometree:purge_node(NodeId, Owner).
get_entity_affiliations(Host, Owner) ->
node_hometree:get_entity_affiliations(Host, Owner).
get_node_affiliations(NodeId) ->
node_hometree:get_node_affiliations(NodeId).
get_affiliation(NodeId, Owner) ->
node_hometree:get_affiliation(NodeId, Owner).
set_affiliation(NodeId, Owner, Affiliation) ->
node_hometree:set_affiliation(NodeId, Owner,
Affiliation).
get_entity_subscriptions(Host, Owner) ->
node_hometree:get_entity_subscriptions(Host, Owner).
get_node_subscriptions(NodeId) ->
node_hometree:get_node_subscriptions(NodeId).
get_subscriptions(NodeId, Owner) ->
node_hometree:get_subscriptions(NodeId, Owner).
set_subscriptions(NodeId, Owner, Subscription, SubId) ->
node_hometree:set_subscriptions(NodeId, Owner,
Subscription, SubId).
get_pending_nodes(Host, Owner) ->
node_hometree:get_pending_nodes(Host, Owner).
get_states(NodeId) -> node_hometree:get_states(NodeId).
get_state(NodeId, JID) ->
node_hometree:get_state(NodeId, JID).
set_state(State) -> node_hometree:set_state(State).
get_items(NodeId, From) ->
node_hometree:get_items(NodeId, From).
get_items(NodeId, JID, AccessModel,
PresenceSubscription, RosterGroup, SubId) ->
node_hometree:get_items(NodeId, JID, AccessModel,
PresenceSubscription, RosterGroup, SubId).
get_item(NodeId, ItemId) ->
node_hometree:get_item(NodeId, ItemId).
get_item(NodeId, ItemId, JID, AccessModel,
PresenceSubscription, RosterGroup, SubId) ->
node_hometree:get_item(NodeId, ItemId, JID, AccessModel,
PresenceSubscription, RosterGroup, SubId).
set_item(Item) -> node_hometree:set_item(Item).
get_item_name(Host, Node, Id) ->
node_hometree:get_item_name(Host, Node, Id).
node_to_path(Node) -> node_flat:node_to_path(Node).
path_to_node(Path) -> node_flat:path_to_node(Path).
|
a06e97895901c08c55eff0056e2bccfacfcb2431658ec99b3ee91bc022db366b
|
CRogers/obc
|
lr0.mli
|
* lr0.mli
*
* This file is part of the Oxford Oberon-2 compiler
* Copyright ( c ) 2006
* 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 . The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission .
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` 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 AUTHOR 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 ,
* 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 .
*
* $ I d : lr0.mli 1643 2010 - 11 - 12 14:42:37Z mike $
* lr0.mli
*
* This file is part of the Oxford Oberon-2 compiler
* Copyright (c) 2006 J. M. Spivey
* 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. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*
* $Id: lr0.mli 1643 2010-11-12 14:42:37Z mike $
*)
open Grammar
(* This module computes the LR(0) automaton for the grammar *)
(* item -- type of LR(0) items *)
type item =
{ (* The basic item: *)
z_rule: rule; (* Production rule *)
z_index: int; (* Index in RHS *)
Added by LALR
mutable z_lookahead: SymSet.t } (* Lookahead set *)
val fItem : item -> Print.arg
ItemSet -- ADT of sets of items
module ItemSet : Set.S with type elt = item
(* state -- state of LR(0) automaton *)
type state =
{ p_id: int;
p_items: ItemSet.t;
mutable p_trans: transition list }
(* transition -- state transition in LR(0) *)
and transition =
{ t_id: int;
t_source: state;
t_sym: symbol;
t_target: state }
(* action -- potential parser action *)
type action =
Shift of state
| Reduce of rule
| Error
(* fAction -- format a parser action for printing *)
val fAction : action -> Print.arg
(* compute_states -- compute the LR(0) automaton for the grammar *)
val compute_states : unit -> unit
(* get_trans -- find transition for state and symbol *)
val get_trans : state -> symbol -> transition
val do_states : (state -> unit) -> unit
val do_transitions : (transition -> unit) -> unit
val state_vector : 'a -> (state, 'a) Vector.t
val trans_vector : 'a -> (transition, 'a) Vector.t
(* actions_for -- all potential parser actions in a state, using lookahead *)
val actions_for : state -> (symbol * action) list
gotos_for -- compute all from a state
val gotos_for : state -> (symbol * state) list
| null |
https://raw.githubusercontent.com/CRogers/obc/49064db244e0c9d2ec2a83420c8d0ee917b54196/yacc/lr0.mli
|
ocaml
|
This module computes the LR(0) automaton for the grammar
item -- type of LR(0) items
The basic item:
Production rule
Index in RHS
Lookahead set
state -- state of LR(0) automaton
transition -- state transition in LR(0)
action -- potential parser action
fAction -- format a parser action for printing
compute_states -- compute the LR(0) automaton for the grammar
get_trans -- find transition for state and symbol
actions_for -- all potential parser actions in a state, using lookahead
|
* lr0.mli
*
* This file is part of the Oxford Oberon-2 compiler
* Copyright ( c ) 2006
* 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 . The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission .
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` 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 AUTHOR 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 ,
* 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 .
*
* $ I d : lr0.mli 1643 2010 - 11 - 12 14:42:37Z mike $
* lr0.mli
*
* This file is part of the Oxford Oberon-2 compiler
* Copyright (c) 2006 J. M. Spivey
* 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. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*
* $Id: lr0.mli 1643 2010-11-12 14:42:37Z mike $
*)
open Grammar
type item =
Added by LALR
val fItem : item -> Print.arg
ItemSet -- ADT of sets of items
module ItemSet : Set.S with type elt = item
type state =
{ p_id: int;
p_items: ItemSet.t;
mutable p_trans: transition list }
and transition =
{ t_id: int;
t_source: state;
t_sym: symbol;
t_target: state }
type action =
Shift of state
| Reduce of rule
| Error
val fAction : action -> Print.arg
val compute_states : unit -> unit
val get_trans : state -> symbol -> transition
val do_states : (state -> unit) -> unit
val do_transitions : (transition -> unit) -> unit
val state_vector : 'a -> (state, 'a) Vector.t
val trans_vector : 'a -> (transition, 'a) Vector.t
val actions_for : state -> (symbol * action) list
gotos_for -- compute all from a state
val gotos_for : state -> (symbol * state) list
|
89ff9ed4868ce52545babedc2794176d54def7c6db37b42591089f431a39da3c
|
djblue/portal
|
fetch.cljs
|
(ns examples.fetch)
(defn- node-fetch [url]
(let [http (js/require "https")]
(js/Promise.
(fn [resolve reject]
(.end
(.request
http
url
(fn [res]
(let [body (atom "")]
(.on res "data" #(swap! body str %))
(.on res "error" reject)
(.on res "end" #(resolve @body))))))))))
(defn- web-fetch [url]
(.then (js/fetch url) #(.text %)))
(def fetch (if (exists? js/window) web-fetch node-fetch))
| null |
https://raw.githubusercontent.com/djblue/portal/9110dabd9fb0f05c1fbb54f4b5981e82fc9ed644/src/examples/fetch.cljs
|
clojure
|
(ns examples.fetch)
(defn- node-fetch [url]
(let [http (js/require "https")]
(js/Promise.
(fn [resolve reject]
(.end
(.request
http
url
(fn [res]
(let [body (atom "")]
(.on res "data" #(swap! body str %))
(.on res "error" reject)
(.on res "end" #(resolve @body))))))))))
(defn- web-fetch [url]
(.then (js/fetch url) #(.text %)))
(def fetch (if (exists? js/window) web-fetch node-fetch))
|
|
0a99b0d5468701830522181b3ffa93c4766c0293ea31416d7950ef4651c8979b
|
yawaramin/bs-hyperapp
|
hyperapp.ml
|
type 'msg vnode
type ('model, 'msg) view = 'model -> ('msg -> unit) -> 'msg vnode
type 'model state = < model : 'model > Js.t
type ('model, 'msg) _view =
'model state -> < update : 'msg -> unit > Js.t -> 'msg vnode [@bs]
type ('model, 'msg) actions =
< update :
'model state ->
('model, 'msg) actions ->
'msg ->
(('model state -> unit Js.Promise.t) -> unit Js.Promise.t [@bs]) [@bs] > Js.t
external _h :
string ->
?a:'attrs ->
([ `children of 'msg vnode array | `text of string ] [@bs.unwrap]) ->
'msg vnode =
"h" [@@bs.module "hyperapp"]
let h tagName ?a children =
_h tagName ?a (`children (Array.of_list children))
let h_ tagName ?a text = _h tagName ?a (`text text)
external targetOfEvent : 'event -> Bs_webapi.Dom.Element.t =
"target" [@@bs.get]
external valueOfTarget : Bs_webapi.Dom.Element.t -> string =
"value" [@@bs.get]
let valueOfEvent e = e |> targetOfEvent |> valueOfTarget
external app :
< state : 'model state;
view : ('model, 'msg) _view;
actions : ('model, 'msg) actions;
root : Bs_webapi.Dom.Element.t > Js.t -> unit =
"" [@@bs.module "hyperapp"]
let viewOf view = fun [@bs] state actions ->
view state##model actions##update
let rootOf root =
Js.Option.getExn Bs_webapi.Dom.(Document.getElementById root document)
let app ~model ~view ~update root = app [%obj {
state = {model};
view = viewOf view;
actions = {update = fun [@bs] state _ payload -> fun [@bs] update' ->
payload |> update state##model |> Js.Promise.then_ (fun model' ->
update' {model = model'})};
root = rootOf root
}]
| null |
https://raw.githubusercontent.com/yawaramin/bs-hyperapp/83cdba88fcd262dc31ad171c843b53f1be0dc758/src/hyperapp.ml
|
ocaml
|
type 'msg vnode
type ('model, 'msg) view = 'model -> ('msg -> unit) -> 'msg vnode
type 'model state = < model : 'model > Js.t
type ('model, 'msg) _view =
'model state -> < update : 'msg -> unit > Js.t -> 'msg vnode [@bs]
type ('model, 'msg) actions =
< update :
'model state ->
('model, 'msg) actions ->
'msg ->
(('model state -> unit Js.Promise.t) -> unit Js.Promise.t [@bs]) [@bs] > Js.t
external _h :
string ->
?a:'attrs ->
([ `children of 'msg vnode array | `text of string ] [@bs.unwrap]) ->
'msg vnode =
"h" [@@bs.module "hyperapp"]
let h tagName ?a children =
_h tagName ?a (`children (Array.of_list children))
let h_ tagName ?a text = _h tagName ?a (`text text)
external targetOfEvent : 'event -> Bs_webapi.Dom.Element.t =
"target" [@@bs.get]
external valueOfTarget : Bs_webapi.Dom.Element.t -> string =
"value" [@@bs.get]
let valueOfEvent e = e |> targetOfEvent |> valueOfTarget
external app :
< state : 'model state;
view : ('model, 'msg) _view;
actions : ('model, 'msg) actions;
root : Bs_webapi.Dom.Element.t > Js.t -> unit =
"" [@@bs.module "hyperapp"]
let viewOf view = fun [@bs] state actions ->
view state##model actions##update
let rootOf root =
Js.Option.getExn Bs_webapi.Dom.(Document.getElementById root document)
let app ~model ~view ~update root = app [%obj {
state = {model};
view = viewOf view;
actions = {update = fun [@bs] state _ payload -> fun [@bs] update' ->
payload |> update state##model |> Js.Promise.then_ (fun model' ->
update' {model = model'})};
root = rootOf root
}]
|
|
74ad9a994ea4f231c940f1c448c8ca87de300588c77071f680d02499113a9fff
|
facebook/duckling
|
Tests.hs
|
Copyright ( c ) 2016 - present , Facebook , Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
module Duckling.Volume.TR.Tests
( tests
) where
import Prelude
import Data.String
import Test.Tasty
import Duckling.Dimensions.Types
import Duckling.Testing.Asserts
import Duckling.Volume.TR.Corpus
tests :: TestTree
tests = testGroup "TR Tests"
[ makeCorpusTest [Seal Volume] corpus
]
| null |
https://raw.githubusercontent.com/facebook/duckling/72f45e8e2c7385f41f2f8b1f063e7b5daa6dca94/tests/Duckling/Volume/TR/Tests.hs
|
haskell
|
All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
|
Copyright ( c ) 2016 - present , Facebook , Inc.
module Duckling.Volume.TR.Tests
( tests
) where
import Prelude
import Data.String
import Test.Tasty
import Duckling.Dimensions.Types
import Duckling.Testing.Asserts
import Duckling.Volume.TR.Corpus
tests :: TestTree
tests = testGroup "TR Tests"
[ makeCorpusTest [Seal Volume] corpus
]
|
817035f4d049768320c2102a8d049797e765aab72c76a11c439fb4aff855a2e6
|
GaloisInc/pure-zlib
|
HuffmanTree.hs
|
module Codec.Compression.Zlib.HuffmanTree (
HuffmanTree,
AdvanceResult (..),
createHuffmanTree,
advanceTree,
) where
import Data.Bits (testBit)
import Data.Word (Word8)
data HuffmanTree a
= HuffmanNode (HuffmanTree a) (HuffmanTree a)
| HuffmanValue a
| HuffmanEmpty
deriving (Show)
data AdvanceResult a
= AdvanceError String
| NewTree (HuffmanTree a)
| Result a
emptyHuffmanTree :: HuffmanTree a
emptyHuffmanTree = HuffmanEmpty
createHuffmanTree ::
Show a =>
[(a, Int, Int)] ->
Either String (HuffmanTree a)
createHuffmanTree = foldr addHuffmanNode' (Right emptyHuffmanTree)
where
addHuffmanNode' (a, b, c) acc =
case acc of
Left err -> Left err
Right tree -> addHuffmanNode a b c tree
addHuffmanNode ::
Show a =>
a ->
Int ->
Int ->
HuffmanTree a ->
Either String (HuffmanTree a)
addHuffmanNode val len code node =
case node of
HuffmanEmpty
| len == 0 ->
Right (HuffmanValue val)
HuffmanEmpty ->
case addHuffmanNode val (len - 1) code HuffmanEmpty of
Left err -> Left err
Right newNode
| testBit code (len - 1) -> Right (HuffmanNode HuffmanEmpty newNode)
| otherwise -> Right (HuffmanNode newNode HuffmanEmpty)
--
HuffmanValue _
| len == 0 ->
Left "Two values point to the same place!"
HuffmanValue _ ->
Left "HuffmanValue hit while inserting a value!"
--
HuffmanNode _ _
| len == 0 ->
Left ("Tried to add where the leaf is a node: " ++ show val)
HuffmanNode l r | testBit code (len - 1) ->
case addHuffmanNode val (len - 1) code r of
Left err -> Left err
Right r' -> Right (HuffmanNode l r')
HuffmanNode l r ->
case addHuffmanNode val (len - 1) code l of
Left err -> Left err
Right l' -> Right (HuffmanNode l' r)
advanceTree :: Word8 -> HuffmanTree a -> AdvanceResult a
advanceTree x node =
case node of
HuffmanEmpty -> AdvanceError "Tried to advance empty tree!"
HuffmanValue _ -> AdvanceError "Tried to advance value!"
HuffmanNode l r ->
case if (x == 1) then r else l of
HuffmanEmpty -> AdvanceError "Advanced to empty tree!"
HuffmanValue y -> Result y
t -> NewTree t
# INLINE advanceTree #
| null |
https://raw.githubusercontent.com/GaloisInc/pure-zlib/05392ea8ab8f6426b2491e5495bcb00cdcefbc11/src/Codec/Compression/Zlib/HuffmanTree.hs
|
haskell
|
module Codec.Compression.Zlib.HuffmanTree (
HuffmanTree,
AdvanceResult (..),
createHuffmanTree,
advanceTree,
) where
import Data.Bits (testBit)
import Data.Word (Word8)
data HuffmanTree a
= HuffmanNode (HuffmanTree a) (HuffmanTree a)
| HuffmanValue a
| HuffmanEmpty
deriving (Show)
data AdvanceResult a
= AdvanceError String
| NewTree (HuffmanTree a)
| Result a
emptyHuffmanTree :: HuffmanTree a
emptyHuffmanTree = HuffmanEmpty
createHuffmanTree ::
Show a =>
[(a, Int, Int)] ->
Either String (HuffmanTree a)
createHuffmanTree = foldr addHuffmanNode' (Right emptyHuffmanTree)
where
addHuffmanNode' (a, b, c) acc =
case acc of
Left err -> Left err
Right tree -> addHuffmanNode a b c tree
addHuffmanNode ::
Show a =>
a ->
Int ->
Int ->
HuffmanTree a ->
Either String (HuffmanTree a)
addHuffmanNode val len code node =
case node of
HuffmanEmpty
| len == 0 ->
Right (HuffmanValue val)
HuffmanEmpty ->
case addHuffmanNode val (len - 1) code HuffmanEmpty of
Left err -> Left err
Right newNode
| testBit code (len - 1) -> Right (HuffmanNode HuffmanEmpty newNode)
| otherwise -> Right (HuffmanNode newNode HuffmanEmpty)
HuffmanValue _
| len == 0 ->
Left "Two values point to the same place!"
HuffmanValue _ ->
Left "HuffmanValue hit while inserting a value!"
HuffmanNode _ _
| len == 0 ->
Left ("Tried to add where the leaf is a node: " ++ show val)
HuffmanNode l r | testBit code (len - 1) ->
case addHuffmanNode val (len - 1) code r of
Left err -> Left err
Right r' -> Right (HuffmanNode l r')
HuffmanNode l r ->
case addHuffmanNode val (len - 1) code l of
Left err -> Left err
Right l' -> Right (HuffmanNode l' r)
advanceTree :: Word8 -> HuffmanTree a -> AdvanceResult a
advanceTree x node =
case node of
HuffmanEmpty -> AdvanceError "Tried to advance empty tree!"
HuffmanValue _ -> AdvanceError "Tried to advance value!"
HuffmanNode l r ->
case if (x == 1) then r else l of
HuffmanEmpty -> AdvanceError "Advanced to empty tree!"
HuffmanValue y -> Result y
t -> NewTree t
# INLINE advanceTree #
|
|
d4c1dc5f182bba3d4f905200e9f5e908ecb37661ec006346491cc2db56ba9abb
|
RyanGlScott/text-show
|
VersionSpec.hs
|
module Spec.Data.VersionSpec (main, spec) where
import Data.Proxy.Compat (Proxy(..))
import Data.Version (Version, showVersion)
import Spec.Utils (matchesTextShowSpec)
import Test.Hspec (Expectation, Spec, describe, hspec, parallel, shouldBe)
import Test.Hspec.QuickCheck (prop)
import TextShow (fromString)
import TextShow.Data.Version (showbVersion)
main :: IO ()
main = hspec spec
spec :: Spec
spec = parallel $ do
describe "Version" $
matchesTextShowSpec (Proxy :: Proxy Version)
describe "showbVersion" $
prop "has the same output as showVersion" prop_showVersion
-- | Verifies 'showVersion' and 'showbVersion' generate the same output.
prop_showVersion :: Version -> Expectation
prop_showVersion v = fromString (showVersion v) `shouldBe` showbVersion v
| null |
https://raw.githubusercontent.com/RyanGlScott/text-show/5ea297d0c7ae2d043f000c791cc12ac53f469944/tests/Spec/Data/VersionSpec.hs
|
haskell
|
| Verifies 'showVersion' and 'showbVersion' generate the same output.
|
module Spec.Data.VersionSpec (main, spec) where
import Data.Proxy.Compat (Proxy(..))
import Data.Version (Version, showVersion)
import Spec.Utils (matchesTextShowSpec)
import Test.Hspec (Expectation, Spec, describe, hspec, parallel, shouldBe)
import Test.Hspec.QuickCheck (prop)
import TextShow (fromString)
import TextShow.Data.Version (showbVersion)
main :: IO ()
main = hspec spec
spec :: Spec
spec = parallel $ do
describe "Version" $
matchesTextShowSpec (Proxy :: Proxy Version)
describe "showbVersion" $
prop "has the same output as showVersion" prop_showVersion
prop_showVersion :: Version -> Expectation
prop_showVersion v = fromString (showVersion v) `shouldBe` showbVersion v
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.